Make sure cdlatex customization is taken into account properly
[org-mode.git] / lisp / org.el
blob9441cf4f720f9e9a76a62e10ca56ac397a0191b9
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 "Shen" shen)
189 (const :tag "Sql" sql)
190 (const :tag "Sqlite" sqlite))
191 :value-type (boolean :tag "Activate" :value t)))
193 ;;;; Customization variables
194 (defcustom org-clone-delete-id nil
195 "Remove ID property of clones of a subtree.
196 When non-nil, clones of a subtree don't inherit the ID property.
197 Otherwise they inherit the ID property with a new unique
198 identifier."
199 :type 'boolean
200 :group 'org-id)
202 ;;; Version
204 (defconst org-version "7.7"
205 "The version number of the file org.el.")
207 (defun org-version (&optional here)
208 "Show the org-mode version in the echo area.
209 With prefix arg HERE, insert it at point."
210 (interactive "P")
211 (let* ((origin default-directory)
212 (version org-version)
213 (git-version)
214 (dir (concat (file-name-directory (locate-library "org")) "../" )))
215 (when (and (file-exists-p (expand-file-name ".git" dir))
216 (executable-find "git"))
217 (unwind-protect
218 (progn
219 (cd dir)
220 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
221 (with-current-buffer "*Shell Command Output*"
222 (goto-char (point-min))
223 (setq git-version (buffer-substring (point) (point-at-eol))))
224 (subst-char-in-string ?- ?. git-version t)
225 (when (string-match "\\S-"
226 (shell-command-to-string
227 "git diff-index --name-only HEAD --"))
228 (setq git-version (concat git-version ".dirty")))
229 (setq version (concat version " (" git-version ")"))))
230 (cd origin)))
231 (setq version (format "Org-mode version %s" version))
232 (if here (insert version))
233 (message version)))
235 ;;; Compatibility constants
237 ;;; The custom variables
239 (defgroup org nil
240 "Outline-based notes management and organizer."
241 :tag "Org"
242 :group 'outlines
243 :group 'calendar)
245 (defcustom org-mode-hook nil
246 "Mode hook for Org-mode, run after the mode was turned on."
247 :group 'org
248 :type 'hook)
250 (defcustom org-load-hook nil
251 "Hook that is run after org.el has been loaded."
252 :group 'org
253 :type 'hook)
255 (defcustom org-log-buffer-setup-hook nil
256 "Hook that is run after an Org log buffer is created."
257 :group 'org
258 :type 'hook)
260 (defvar org-modules) ; defined below
261 (defvar org-modules-loaded nil
262 "Have the modules been loaded already?")
264 (defun org-load-modules-maybe (&optional force)
265 "Load all extensions listed in `org-modules'."
266 (when (or force (not org-modules-loaded))
267 (mapc (lambda (ext)
268 (condition-case nil (require ext)
269 (error (message "Problems while trying to load feature `%s'" ext))))
270 org-modules)
271 (setq org-modules-loaded t)))
273 (defun org-set-modules (var value)
274 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
275 (set var value)
276 (when (featurep 'org)
277 (org-load-modules-maybe 'force)))
279 (when (org-bound-and-true-p org-modules)
280 (let ((a (member 'org-infojs org-modules)))
281 (and a (setcar a 'org-jsinfo))))
283 (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)
284 "Modules that should always be loaded together with org.el.
285 If a description starts with <C>, the file is not part of Emacs
286 and loading it will require that you have downloaded and properly installed
287 the org-mode distribution.
289 You can also use this system to load external packages (i.e. neither Org
290 core modules, nor modules from the CONTRIB directory). Just add symbols
291 to the end of the list. If the package is called org-xyz.el, then you need
292 to add the symbol `xyz', and the package must have a call to
294 (provide 'org-xyz)"
295 :group 'org
296 :set 'org-set-modules
297 :type
298 '(set :greedy t
299 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
300 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
301 (const :tag " crypt: Encryption of subtrees" org-crypt)
302 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
303 (const :tag " docview: Links to doc-view buffers" org-docview)
304 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
305 (const :tag " id: Global IDs for identifying entries" org-id)
306 (const :tag " info: Links to Info nodes" org-info)
307 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
308 (const :tag " habit: Track your consistency with habits" org-habit)
309 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
310 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
311 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
312 (const :tag " mew Links to Mew folders/messages" org-mew)
313 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
314 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
315 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
316 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
317 (const :tag " vm: Links to VM folders/messages" org-vm)
318 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
319 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
320 (const :tag " mouse: Additional mouse support" org-mouse)
321 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
323 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
324 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
325 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
326 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
327 (const :tag "C collector: Collect properties into tables" org-collector)
328 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
329 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
330 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
331 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
332 (const :tag "C eval: Include command output as text" org-eval)
333 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
334 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
335 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
336 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
337 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
339 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
341 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
342 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
343 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
344 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
345 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
346 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
347 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
348 (const :tag "C mtags: Support for muse-like tags" org-mtags)
349 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
350 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
351 (const :tag "C registry: A registry for Org-mode links" org-registry)
352 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
353 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
354 (const :tag "C secretary: Team management with org-mode" org-secretary)
355 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
356 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
357 (const :tag "C track: Keep up with Org-mode development" org-track)
358 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
359 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
360 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
362 (defcustom org-support-shift-select nil
363 "Non-nil means make shift-cursor commands select text when possible.
365 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
366 start selecting a region, or enlarge regions started in this way.
367 In Org-mode, in special contexts, these same keys are used for
368 other purposes, important enough to compete with shift selection.
369 Org tries to balance these needs by supporting `shift-select-mode'
370 outside these special contexts, under control of this variable.
372 The default of this variable is nil, to avoid confusing behavior. Shifted
373 cursor keys will then execute Org commands in the following contexts:
374 - on a headline, changing TODO state (left/right) and priority (up/down)
375 - on a time stamp, changing the time
376 - in a plain list item, changing the bullet type
377 - in a property definition line, switching between allowed values
378 - in the BEGIN line of a clock table (changing the time block).
379 Outside these contexts, the commands will throw an error.
381 When this variable is t and the cursor is not in a special
382 context, Org-mode will support shift-selection for making and
383 enlarging regions. To make this more effective, the bullet
384 cycling will no longer happen anywhere in an item line, but only
385 if the cursor is exactly on the bullet.
387 If you set this variable to the symbol `always', then the keys
388 will not be special in headlines, property lines, and item lines,
389 to make shift selection work there as well. If this is what you
390 want, you can use the following alternative commands: `C-c C-t'
391 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
392 can be used to switch TODO sets, `C-c -' to cycle item bullet
393 types, and properties can be edited by hand or in column view.
395 However, when the cursor is on a timestamp, shift-cursor commands
396 will still edit the time stamp - this is just too good to give up.
398 XEmacs user should have this variable set to nil, because
399 `shift-select-mode' is in Emacs 23 or later only."
400 :group 'org
401 :type '(choice
402 (const :tag "Never" nil)
403 (const :tag "When outside special context" t)
404 (const :tag "Everywhere except timestamps" always)))
406 (defgroup org-startup nil
407 "Options concerning startup of Org-mode."
408 :tag "Org Startup"
409 :group 'org)
411 (defcustom org-startup-folded t
412 "Non-nil means entering Org-mode will switch to OVERVIEW.
413 This can also be configured on a per-file basis by adding one of
414 the following lines anywhere in the buffer:
416 #+STARTUP: fold (or `overview', this is equivalent)
417 #+STARTUP: nofold (or `showall', this is equivalent)
418 #+STARTUP: content
419 #+STARTUP: showeverything"
420 :group 'org-startup
421 :type '(choice
422 (const :tag "nofold: show all" nil)
423 (const :tag "fold: overview" t)
424 (const :tag "content: all headlines" content)
425 (const :tag "show everything, even drawers" showeverything)))
427 (defcustom org-startup-truncated t
428 "Non-nil means entering Org-mode will set `truncate-lines'.
429 This is useful since some lines containing links can be very long and
430 uninteresting. Also tables look terrible when wrapped."
431 :group 'org-startup
432 :type 'boolean)
434 (defcustom org-startup-indented nil
435 "Non-nil means turn on `org-indent-mode' on startup.
436 This can also be configured on a per-file basis by adding one of
437 the following lines anywhere in the buffer:
439 #+STARTUP: indent
440 #+STARTUP: noindent"
441 :group 'org-structure
442 :type '(choice
443 (const :tag "Not" nil)
444 (const :tag "Globally (slow on startup in large files)" t)))
446 (defcustom org-use-sub-superscripts t
447 "Non-nil means interpret \"_\" and \"^\" for export.
448 When this option is turned on, you can use TeX-like syntax for sub- and
449 superscripts. Several characters after \"_\" or \"^\" will be
450 considered as a single item - so grouping with {} is normally not
451 needed. For example, the following things will be parsed as single
452 sub- or superscripts.
454 10^24 or 10^tau several digits will be considered 1 item.
455 10^-12 or 10^-tau a leading sign with digits or a word
456 x^2-y^3 will be read as x^2 - y^3, because items are
457 terminated by almost any nonword/nondigit char.
458 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
460 Still, ambiguity is possible - so when in doubt use {} to enclose the
461 sub/superscript. If you set this variable to the symbol `{}',
462 the braces are *required* in order to trigger interpretations as
463 sub/superscript. This can be helpful in documents that need \"_\"
464 frequently in plain text.
466 Not all export backends support this, but HTML does.
468 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
469 :group 'org-startup
470 :group 'org-export-translation
471 :type '(choice
472 (const :tag "Always interpret" t)
473 (const :tag "Only with braces" {})
474 (const :tag "Never interpret" nil)))
476 (if (fboundp 'defvaralias)
477 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
480 (defcustom org-startup-with-beamer-mode nil
481 "Non-nil means turn on `org-beamer-mode' on startup.
482 This can also be configured on a per-file basis by adding one of
483 the following lines anywhere in the buffer:
485 #+STARTUP: beamer"
486 :group 'org-startup
487 :type 'boolean)
489 (defcustom org-startup-align-all-tables nil
490 "Non-nil means align all tables when visiting a file.
491 This is useful when the column width in tables is forced with <N> cookies
492 in table fields. Such tables will look correct only after the first re-align.
493 This can also be configured on a per-file basis by adding one of
494 the following lines anywhere in the buffer:
495 #+STARTUP: align
496 #+STARTUP: noalign"
497 :group 'org-startup
498 :type 'boolean)
500 (defcustom org-startup-with-inline-images nil
501 "Non-nil means show inline images when loading a new Org file.
502 This can also be configured on a per-file basis by adding one of
503 the following lines anywhere in the buffer:
504 #+STARTUP: inlineimages
505 #+STARTUP: noinlineimages"
506 :group 'org-startup
507 :type 'boolean)
509 (defcustom org-insert-mode-line-in-empty-file nil
510 "Non-nil means insert the first line setting Org-mode in empty files.
511 When the function `org-mode' is called interactively in an empty file, this
512 normally means that the file name does not automatically trigger Org-mode.
513 To ensure that the file will always be in Org-mode in the future, a
514 line enforcing Org-mode will be inserted into the buffer, if this option
515 has been set."
516 :group 'org-startup
517 :type 'boolean)
519 (defcustom org-replace-disputed-keys nil
520 "Non-nil means use alternative key bindings for some keys.
521 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
522 These keys are also used by other packages like shift-selection-mode'
523 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
524 If you want to use Org-mode together with one of these other modes,
525 or more generally if you would like to move some Org-mode commands to
526 other keys, set this variable and configure the keys with the variable
527 `org-disputed-keys'.
529 This option is only relevant at load-time of Org-mode, and must be set
530 *before* org.el is loaded. Changing it requires a restart of Emacs to
531 become effective."
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-use-extra-keys nil
536 "Non-nil means use extra key sequence definitions for certain commands.
537 This happens automatically if you run XEmacs or if `window-system'
538 is nil. This variable lets you do the same manually. You must
539 set it before loading org.
541 Example: on Carbon Emacs 22 running graphically, with an external
542 keyboard on a Powerbook, the default way of setting M-left might
543 not work for either Alt or ESC. Setting this variable will make
544 it work for ESC."
545 :group 'org-startup
546 :type 'boolean)
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
551 (defcustom org-disputed-keys
552 '(([(shift up)] . [(meta p)])
553 ([(shift down)] . [(meta n)])
554 ([(shift left)] . [(meta -)])
555 ([(shift right)] . [(meta +)])
556 ([(control shift right)] . [(meta shift +)])
557 ([(control shift left)] . [(meta shift -)]))
558 "Keys for which Org-mode and other modes compete.
559 This is an alist, cars are the default keys, second element specifies
560 the alternative to use when `org-replace-disputed-keys' is t.
562 Keys can be specified in any syntax supported by `define-key'.
563 The value of this option takes effect only at Org-mode's startup,
564 therefore you'll have to restart Emacs to apply it after changing."
565 :group 'org-startup
566 :type 'alist)
568 (defun org-key (key)
569 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
570 Or return the original if not disputed.
571 Also apply the translations defined in `org-xemacs-key-equivalents'."
572 (when org-replace-disputed-keys
573 (let* ((nkey (key-description key))
574 (x (org-find-if (lambda (x)
575 (equal (key-description (car x)) nkey))
576 org-disputed-keys)))
577 (setq key (if x (cdr x) key))))
578 (when (featurep 'xemacs)
579 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
580 key)
582 (defun org-find-if (predicate seq)
583 (catch 'exit
584 (while seq
585 (if (funcall predicate (car seq))
586 (throw 'exit (car seq))
587 (pop seq)))))
589 (defun org-defkey (keymap key def)
590 "Define a key, possibly translated, as returned by `org-key'."
591 (define-key keymap (org-key key) def))
593 (defcustom org-ellipsis nil
594 "The ellipsis to use in the Org-mode outline.
595 When nil, just use the standard three dots. When a string, use that instead,
596 When a face, use the standard 3 dots, but with the specified face.
597 The change affects only Org-mode (which will then use its own display table).
598 Changing this requires executing `M-x org-mode' in a buffer to become
599 effective."
600 :group 'org-startup
601 :type '(choice (const :tag "Default" nil)
602 (face :tag "Face" :value org-warning)
603 (string :tag "String" :value "...#")))
605 (defvar org-display-table nil
606 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
608 (defgroup org-keywords nil
609 "Keywords in Org-mode."
610 :tag "Org Keywords"
611 :group 'org)
613 (defcustom org-deadline-string "DEADLINE:"
614 "String to mark deadline entries.
615 A deadline is this string, followed by a time stamp. Should be a word,
616 terminated by a colon. You can insert a schedule keyword and
617 a timestamp with \\[org-deadline].
618 Changes become only effective after restarting Emacs."
619 :group 'org-keywords
620 :type 'string)
622 (defcustom org-scheduled-string "SCHEDULED:"
623 "String to mark scheduled TODO entries.
624 A schedule is this string, followed by a time stamp. Should be a word,
625 terminated by a colon. You can insert a schedule keyword and
626 a timestamp with \\[org-schedule].
627 Changes become only effective after restarting Emacs."
628 :group 'org-keywords
629 :type 'string)
631 (defcustom org-closed-string "CLOSED:"
632 "String used as the prefix for timestamps logging closing a TODO entry."
633 :group 'org-keywords
634 :type 'string)
636 (defcustom org-clock-string "CLOCK:"
637 "String used as prefix for timestamps clocking work hours on an item."
638 :group 'org-keywords
639 :type 'string)
641 (defcustom org-comment-string "COMMENT"
642 "Entries starting with this keyword will never be exported.
643 An entry can be toggled between COMMENT and normal with
644 \\[org-toggle-comment].
645 Changes become only effective after restarting Emacs."
646 :group 'org-keywords
647 :type 'string)
649 (defcustom org-quote-string "QUOTE"
650 "Entries starting with this keyword will be exported in fixed-width font.
651 Quoting applies only to the text in the entry following the headline, and does
652 not extend beyond the next headline, even if that is lower level.
653 An entry can be toggled between QUOTE and normal with
654 \\[org-toggle-fixed-width-section]."
655 :group 'org-keywords
656 :type 'string)
658 (defconst org-repeat-re
659 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
660 "Regular expression for specifying repeated events.
661 After a match, group 1 contains the repeat expression.")
663 (defgroup org-structure nil
664 "Options concerning the general structure of Org-mode files."
665 :tag "Org Structure"
666 :group 'org)
668 (defgroup org-reveal-location nil
669 "Options about how to make context of a location visible."
670 :tag "Org Reveal Location"
671 :group 'org-structure)
673 (defconst org-context-choice
674 '(choice
675 (const :tag "Always" t)
676 (const :tag "Never" nil)
677 (repeat :greedy t :tag "Individual contexts"
678 (cons
679 (choice :tag "Context"
680 (const agenda)
681 (const org-goto)
682 (const occur-tree)
683 (const tags-tree)
684 (const link-search)
685 (const mark-goto)
686 (const bookmark-jump)
687 (const isearch)
688 (const default))
689 (boolean))))
690 "Contexts for the reveal options.")
692 (defcustom org-show-hierarchy-above '((default . t))
693 "Non-nil means show full hierarchy when revealing a location.
694 Org-mode often shows locations in an org-mode file which might have
695 been invisible before. When this is set, the hierarchy of headings
696 above the exposed location is shown.
697 Turning this off for example for sparse trees makes them very compact.
698 Instead of t, this can also be an alist specifying this option for different
699 contexts. Valid contexts are
700 agenda when exposing an entry from the agenda
701 org-goto when using the command `org-goto' on key C-c C-j
702 occur-tree when using the command `org-occur' on key C-c /
703 tags-tree when constructing a sparse tree based on tags matches
704 link-search when exposing search matches associated with a link
705 mark-goto when exposing the jump goal of a mark
706 bookmark-jump when exposing a bookmark location
707 isearch when exiting from an incremental search
708 default default for all contexts not set explicitly"
709 :group 'org-reveal-location
710 :type org-context-choice)
712 (defcustom org-show-following-heading '((default . nil))
713 "Non-nil means show following heading when revealing a location.
714 Org-mode often shows locations in an org-mode file which might have
715 been invisible before. When this is set, the heading following the
716 match is shown.
717 Turning this off for example for sparse trees makes them very compact,
718 but makes it harder to edit the location of the match. In such a case,
719 use the command \\[org-reveal] to show more context.
720 Instead of t, this can also be an alist specifying this option for different
721 contexts. See `org-show-hierarchy-above' for valid contexts."
722 :group 'org-reveal-location
723 :type org-context-choice)
725 (defcustom org-show-siblings '((default . nil) (isearch t))
726 "Non-nil means show all sibling heading when revealing a location.
727 Org-mode often shows locations in an org-mode file which might have
728 been invisible before. When this is set, the sibling of the current entry
729 heading are all made visible. If `org-show-hierarchy-above' is t,
730 the same happens on each level of the hierarchy above the current entry.
732 By default this is on for the isearch context, off for all other contexts.
733 Turning this off for example for sparse trees makes them very compact,
734 but makes it harder to edit the location of the match. In such a case,
735 use the command \\[org-reveal] to show more context.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. See `org-show-hierarchy-above' for valid contexts."
738 :group 'org-reveal-location
739 :type org-context-choice)
741 (defcustom org-show-entry-below '((default . nil))
742 "Non-nil means show the entry below a headline when revealing a location.
743 Org-mode often shows locations in an org-mode file which might have
744 been invisible before. When this is set, the text below the headline that is
745 exposed is also shown.
747 By default this is off for all contexts.
748 Instead of t, this can also be an alist specifying this option for different
749 contexts. See `org-show-hierarchy-above' for valid contexts."
750 :group 'org-reveal-location
751 :type org-context-choice)
753 (defcustom org-indirect-buffer-display 'other-window
754 "How should indirect tree buffers be displayed?
755 This applies to indirect buffers created with the commands
756 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
757 Valid values are:
758 current-window Display in the current window
759 other-window Just display in another window.
760 dedicated-frame Create one new frame, and re-use it each time.
761 new-frame Make a new frame each time. Note that in this case
762 previously-made indirect buffers are kept, and you need to
763 kill these buffers yourself."
764 :group 'org-structure
765 :group 'org-agenda-windows
766 :type '(choice
767 (const :tag "In current window" current-window)
768 (const :tag "In current frame, other window" other-window)
769 (const :tag "Each time a new frame" new-frame)
770 (const :tag "One dedicated frame" dedicated-frame)))
772 (defcustom org-use-speed-commands nil
773 "Non-nil means activate single letter commands at beginning of a headline.
774 This may also be a function to test for appropriate locations where speed
775 commands should be active."
776 :group 'org-structure
777 :type '(choice
778 (const :tag "Never" nil)
779 (const :tag "At beginning of headline stars" t)
780 (function)))
782 (defcustom org-speed-commands-user nil
783 "Alist of additional speed commands.
784 This list will be checked before `org-speed-commands-default'
785 when the variable `org-use-speed-commands' is non-nil
786 and when the cursor is at the beginning of a headline.
787 The car if each entry is a string with a single letter, which must
788 be assigned to `self-insert-command' in the global map.
789 The cdr is either a command to be called interactively, a function
790 to be called, or a form to be evaluated.
791 An entry that is just a list with a single string will be interpreted
792 as a descriptive headline that will be added when listing the speed
793 commands in the Help buffer using the `?' speed command."
794 :group 'org-structure
795 :type '(repeat :value ("k" . ignore)
796 (choice :value ("k" . ignore)
797 (list :tag "Descriptive Headline" (string :tag "Headline"))
798 (cons :tag "Letter and Command"
799 (string :tag "Command letter")
800 (choice
801 (function)
802 (sexp))))))
804 (defgroup org-cycle nil
805 "Options concerning visibility cycling in Org-mode."
806 :tag "Org Cycle"
807 :group 'org-structure)
809 (defcustom org-cycle-skip-children-state-if-no-children t
810 "Non-nil means skip CHILDREN state in entries that don't have any."
811 :group 'org-cycle
812 :type 'boolean)
814 (defcustom org-cycle-max-level nil
815 "Maximum level which should still be subject to visibility cycling.
816 Levels higher than this will, for cycling, be treated as text, not a headline.
817 When `org-odd-levels-only' is set, a value of N in this variable actually
818 means 2N-1 stars as the limiting headline.
819 When nil, cycle all levels.
820 Note that the limiting level of cycling is also influenced by
821 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
822 `org-inlinetask-min-level' is, cycling will be limited to levels one less
823 than its value."
824 :group 'org-cycle
825 :type '(choice
826 (const :tag "No limit" nil)
827 (integer :tag "Maximum level")))
829 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
830 "Names of drawers. Drawers are not opened by cycling on the headline above.
831 Drawers only open with a TAB on the drawer line itself. A drawer looks like
832 this:
833 :DRAWERNAME:
834 .....
835 :END:
836 The drawer \"PROPERTIES\" is special for capturing properties through
837 the property API.
839 Drawers can be defined on the per-file basis with a line like:
841 #+DRAWERS: HIDDEN STATE PROPERTIES"
842 :group 'org-structure
843 :group 'org-cycle
844 :type '(repeat (string :tag "Drawer Name")))
846 (defcustom org-hide-block-startup nil
847 "Non-nil means entering Org-mode will fold all blocks.
848 This can also be set in on a per-file basis with
850 #+STARTUP: hideblocks
851 #+STARTUP: showblocks"
852 :group 'org-startup
853 :group 'org-cycle
854 :type 'boolean)
856 (defcustom org-cycle-global-at-bob nil
857 "Cycle globally if cursor is at beginning of buffer and not at a headline.
858 This makes it possible to do global cycling without having to use S-TAB or
859 \\[universal-argument] TAB. For this special case to work, the first line \
860 of the buffer
861 must not be a headline - it may be empty or some other text. When used in
862 this way, `org-cycle-hook' is disables temporarily, to make sure the
863 cursor stays at the beginning of the buffer.
864 When this option is nil, don't do anything special at the beginning
865 of the buffer."
866 :group 'org-cycle
867 :type 'boolean)
869 (defcustom org-cycle-level-after-item/entry-creation t
870 "Non-nil means cycle entry level or item indentation in new empty entries.
872 When the cursor is at the end of an empty headline, i.e with only stars
873 and maybe a TODO keyword, TAB will then switch the entry to become a child,
874 and then all possible ancestor states, before returning to the original state.
875 This makes data entry extremely fast: M-RET to create a new headline,
876 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
878 When the cursor is at the end of an empty plain list item, one TAB will
879 make it a subitem, two or more tabs will back up to make this an item
880 higher up in the item hierarchy."
881 :group 'org-cycle
882 :type 'boolean)
884 (defcustom org-cycle-emulate-tab t
885 "Where should `org-cycle' emulate TAB.
886 nil Never
887 white Only in completely white lines
888 whitestart Only at the beginning of lines, before the first non-white char
889 t Everywhere except in headlines
890 exc-hl-bol Everywhere except at the start of a headline
891 If TAB is used in a place where it does not emulate TAB, the current subtree
892 visibility is cycled."
893 :group 'org-cycle
894 :type '(choice (const :tag "Never" nil)
895 (const :tag "Only in completely white lines" white)
896 (const :tag "Before first char in a line" whitestart)
897 (const :tag "Everywhere except in headlines" t)
898 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
901 (defcustom org-cycle-separator-lines 2
902 "Number of empty lines needed to keep an empty line between collapsed trees.
903 If you leave an empty line between the end of a subtree and the following
904 headline, this empty line is hidden when the subtree is folded.
905 Org-mode will leave (exactly) one empty line visible if the number of
906 empty lines is equal or larger to the number given in this variable.
907 So the default 2 means at least 2 empty lines after the end of a subtree
908 are needed to produce free space between a collapsed subtree and the
909 following headline.
911 If the number is negative, and the number of empty lines is at least -N,
912 all empty lines are shown.
914 Special case: when 0, never leave empty lines in collapsed view."
915 :group 'org-cycle
916 :type 'integer)
917 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
919 (defcustom org-pre-cycle-hook nil
920 "Hook that is run before visibility cycling is happening.
921 The function(s) in this hook must accept a single argument which indicates
922 the new state that will be set right after running this hook. The
923 argument is a symbol. Before a global state change, it can have the values
924 `overview', `content', or `all'. Before a local state change, it can have
925 the values `folded', `children', or `subtree'."
926 :group 'org-cycle
927 :type 'hook)
929 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
930 org-cycle-hide-drawers
931 org-cycle-show-empty-lines
932 org-optimize-window-after-visibility-change)
933 "Hook that is run after `org-cycle' has changed the buffer visibility.
934 The function(s) in this hook must accept a single argument which indicates
935 the new state that was set by the most recent `org-cycle' command. The
936 argument is a symbol. After a global state change, it can have the values
937 `overview', `content', or `all'. After a local state change, it can have
938 the values `folded', `children', or `subtree'."
939 :group 'org-cycle
940 :type 'hook)
942 (defgroup org-edit-structure nil
943 "Options concerning structure editing in Org-mode."
944 :tag "Org Edit Structure"
945 :group 'org-structure)
947 (defcustom org-odd-levels-only nil
948 "Non-nil means skip even levels and only use odd levels for the outline.
949 This has the effect that two stars are being added/taken away in
950 promotion/demotion commands. It also influences how levels are
951 handled by the exporters.
952 Changing it requires restart of `font-lock-mode' to become effective
953 for fontification also in regions already fontified.
954 You may also set this on a per-file basis by adding one of the following
955 lines to the buffer:
957 #+STARTUP: odd
958 #+STARTUP: oddeven"
959 :group 'org-edit-structure
960 :group 'org-appearance
961 :type 'boolean)
963 (defcustom org-adapt-indentation t
964 "Non-nil means adapt indentation to outline node level.
966 When this variable is set, Org assumes that you write outlines by
967 indenting text in each node to align with the headline (after the stars).
968 The following issues are influenced by this variable:
970 - When this is set and the *entire* text in an entry is indented, the
971 indentation is increased by one space in a demotion command, and
972 decreased by one in a promotion command. If any line in the entry
973 body starts with text at column 0, indentation is not changed at all.
975 - Property drawers and planning information is inserted indented when
976 this variable s set. When nil, they will not be indented.
978 - TAB indents a line relative to context. The lines below a headline
979 will be indented when this variable is set.
981 Note that this is all about true indentation, by adding and removing
982 space characters. See also `org-indent.el' which does level-dependent
983 indentation in a virtual way, i.e. at display time in Emacs."
984 :group 'org-edit-structure
985 :type 'boolean)
987 (defcustom org-special-ctrl-a/e nil
988 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
990 When t, `C-a' will bring back the cursor to the beginning of the
991 headline text, i.e. after the stars and after a possible TODO keyword.
992 In an item, this will be the position after the bullet.
993 When the cursor is already at that position, another `C-a' will bring
994 it to the beginning of the line.
996 `C-e' will jump to the end of the headline, ignoring the presence of tags
997 in the headline. A second `C-e' will then jump to the true end of the
998 line, after any tags. This also means that, when this variable is
999 non-nil, `C-e' also will never jump beyond the end of the heading of a
1000 folded section, i.e. not after the ellipses.
1002 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1003 going to the true line boundary first. Only a directly following, identical
1004 keypress will bring the cursor to the special positions.
1006 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1007 set separately."
1008 :group 'org-edit-structure
1009 :type '(choice
1010 (const :tag "off" nil)
1011 (const :tag "on: after stars/bullet and before tags first" t)
1012 (const :tag "reversed: true line boundary first" reversed)
1013 (cons :tag "Set C-a and C-e separately"
1014 (choice :tag "Special C-a"
1015 (const :tag "off" nil)
1016 (const :tag "on: after stars/bullet first" t)
1017 (const :tag "reversed: before stars/bullet first" reversed))
1018 (choice :tag "Special C-e"
1019 (const :tag "off" nil)
1020 (const :tag "on: before tags first" t)
1021 (const :tag "reversed: after tags first" reversed)))))
1022 (if (fboundp 'defvaralias)
1023 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1025 (defcustom org-special-ctrl-k nil
1026 "Non-nil means `C-k' will behave specially in headlines.
1027 When nil, `C-k' will call the default `kill-line' command.
1028 When t, the following will happen while the cursor is in the headline:
1030 - When the cursor is at the beginning of a headline, kill the entire
1031 line and possible the folded subtree below the line.
1032 - When in the middle of the headline text, kill the headline up to the tags.
1033 - When after the headline text, kill the tags."
1034 :group 'org-edit-structure
1035 :type 'boolean)
1037 (defcustom org-ctrl-k-protect-subtree nil
1038 "Non-nil means, do not delete a hidden subtree with C-k.
1039 When set to the symbol `error', simply throw an error when C-k is
1040 used to kill (part-of) a headline that has hidden text behind it.
1041 Any other non-nil value will result in a query to the user, if it is
1042 OK to kill that hidden subtree. When nil, kill without remorse."
1043 :group 'org-edit-structure
1044 :type '(choice
1045 (const :tag "Do not protect hidden subtrees" nil)
1046 (const :tag "Protect hidden subtrees with a security query" t)
1047 (const :tag "Never kill a hidden subtree with C-k" error)))
1049 (defcustom org-yank-folded-subtrees t
1050 "Non-nil means when yanking subtrees, fold them.
1051 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1052 it starts with a heading and all other headings in it are either children
1053 or siblings, then fold all the subtrees. However, do this only if no
1054 text after the yank would be swallowed into a folded tree by this action."
1055 :group 'org-edit-structure
1056 :type 'boolean)
1058 (defcustom org-yank-adjusted-subtrees nil
1059 "Non-nil means when yanking subtrees, adjust the level.
1060 With this setting, `org-paste-subtree' is used to insert the subtree, see
1061 this function for details."
1062 :group 'org-edit-structure
1063 :type 'boolean)
1065 (defcustom org-M-RET-may-split-line '((default . t))
1066 "Non-nil means M-RET will split the line at the cursor position.
1067 When nil, it will go to the end of the line before making a
1068 new line.
1069 You may also set this option in a different way for different
1070 contexts. Valid contexts are:
1072 headline when creating a new headline
1073 item when creating a new item
1074 table in a table field
1075 default the value to be used for all contexts not explicitly
1076 customized"
1077 :group 'org-structure
1078 :group 'org-table
1079 :type '(choice
1080 (const :tag "Always" t)
1081 (const :tag "Never" nil)
1082 (repeat :greedy t :tag "Individual contexts"
1083 (cons
1084 (choice :tag "Context"
1085 (const headline)
1086 (const item)
1087 (const table)
1088 (const default))
1089 (boolean)))))
1092 (defcustom org-insert-heading-respect-content nil
1093 "Non-nil means insert new headings after the current subtree.
1094 When nil, the new heading is created directly after the current line.
1095 The commands \\[org-insert-heading-respect-content] and
1096 \\[org-insert-todo-heading-respect-content] turn this variable on
1097 for the duration of the command."
1098 :group 'org-structure
1099 :type 'boolean)
1101 (defcustom org-blank-before-new-entry '((heading . auto)
1102 (plain-list-item . auto))
1103 "Should `org-insert-heading' leave a blank line before new heading/item?
1104 The value is an alist, with `heading' and `plain-list-item' as CAR,
1105 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1106 which case Org will look at the surrounding headings/items and try to
1107 make an intelligent decision whether to insert a blank line or not.
1109 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1110 set, the setting here is ignored and no empty line is inserted, to avoid
1111 breaking the list structure."
1112 :group 'org-edit-structure
1113 :type '(list
1114 (cons (const heading)
1115 (choice (const :tag "Never" nil)
1116 (const :tag "Always" t)
1117 (const :tag "Auto" auto)))
1118 (cons (const plain-list-item)
1119 (choice (const :tag "Never" nil)
1120 (const :tag "Always" t)
1121 (const :tag "Auto" auto)))))
1123 (defcustom org-insert-heading-hook nil
1124 "Hook being run after inserting a new heading."
1125 :group 'org-edit-structure
1126 :type 'hook)
1128 (defcustom org-enable-fixed-width-editor t
1129 "Non-nil means lines starting with \":\" are treated as fixed-width.
1130 This currently only means they are never auto-wrapped.
1131 When nil, such lines will be treated like ordinary lines.
1132 See also the QUOTE keyword."
1133 :group 'org-edit-structure
1134 :type 'boolean)
1136 (defcustom org-goto-auto-isearch t
1137 "Non-nil means typing characters in `org-goto' starts incremental search."
1138 :group 'org-edit-structure
1139 :type 'boolean)
1141 (defgroup org-sparse-trees nil
1142 "Options concerning sparse trees in Org-mode."
1143 :tag "Org Sparse Trees"
1144 :group 'org-structure)
1146 (defcustom org-highlight-sparse-tree-matches t
1147 "Non-nil means highlight all matches that define a sparse tree.
1148 The highlights will automatically disappear the next time the buffer is
1149 changed by an edit command."
1150 :group 'org-sparse-trees
1151 :type 'boolean)
1153 (defcustom org-remove-highlights-with-change t
1154 "Non-nil means any change to the buffer will remove temporary highlights.
1155 Such highlights are created by `org-occur' and `org-clock-display'.
1156 When nil, `C-c C-c needs to be used to get rid of the highlights.
1157 The highlights created by `org-preview-latex-fragment' always need
1158 `C-c C-c' to be removed."
1159 :group 'org-sparse-trees
1160 :group 'org-time
1161 :type 'boolean)
1164 (defcustom org-occur-hook '(org-first-headline-recenter)
1165 "Hook that is run after `org-occur' has constructed a sparse tree.
1166 This can be used to recenter the window to show as much of the structure
1167 as possible."
1168 :group 'org-sparse-trees
1169 :type 'hook)
1171 (defgroup org-imenu-and-speedbar nil
1172 "Options concerning imenu and speedbar in Org-mode."
1173 :tag "Org Imenu and Speedbar"
1174 :group 'org-structure)
1176 (defcustom org-imenu-depth 2
1177 "The maximum level for Imenu access to Org-mode headlines.
1178 This also applied for speedbar access."
1179 :group 'org-imenu-and-speedbar
1180 :type 'integer)
1182 (defgroup org-table nil
1183 "Options concerning tables in Org-mode."
1184 :tag "Org Table"
1185 :group 'org)
1187 (defcustom org-enable-table-editor 'optimized
1188 "Non-nil means lines starting with \"|\" are handled by the table editor.
1189 When nil, such lines will be treated like ordinary lines.
1191 When equal to the symbol `optimized', the table editor will be optimized to
1192 do the following:
1193 - Automatic overwrite mode in front of whitespace in table fields.
1194 This makes the structure of the table stay in tact as long as the edited
1195 field does not exceed the column width.
1196 - Minimize the number of realigns. Normally, the table is aligned each time
1197 TAB or RET are pressed to move to another field. With optimization this
1198 happens only if changes to a field might have changed the column width.
1199 Optimization requires replacing the functions `self-insert-command',
1200 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1201 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1202 very good at guessing when a re-align will be necessary, but you can always
1203 force one with \\[org-ctrl-c-ctrl-c].
1205 If you would like to use the optimized version in Org-mode, but the
1206 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1208 This variable can be used to turn on and off the table editor during a session,
1209 but in order to toggle optimization, a restart is required.
1211 See also the variable `org-table-auto-blank-field'."
1212 :group 'org-table
1213 :type '(choice
1214 (const :tag "off" nil)
1215 (const :tag "on" t)
1216 (const :tag "on, optimized" optimized)))
1218 (defcustom org-self-insert-cluster-for-undo t
1219 "Non-nil means cluster self-insert commands for undo when possible.
1220 If this is set, then, like in the Emacs command loop, 20 consecutive
1221 characters will be undone together.
1222 This is configurable, because there is some impact on typing performance."
1223 :group 'org-table
1224 :type 'boolean)
1226 (defcustom org-table-tab-recognizes-table.el t
1227 "Non-nil means TAB will automatically notice a table.el table.
1228 When it sees such a table, it moves point into it and - if necessary -
1229 calls `table-recognize-table'."
1230 :group 'org-table-editing
1231 :type 'boolean)
1233 (defgroup org-link nil
1234 "Options concerning links in Org-mode."
1235 :tag "Org Link"
1236 :group 'org)
1238 (defvar org-link-abbrev-alist-local nil
1239 "Buffer-local version of `org-link-abbrev-alist', which see.
1240 The value of this is taken from the #+LINK lines.")
1241 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1243 (defcustom org-link-abbrev-alist nil
1244 "Alist of link abbreviations.
1245 The car of each element is a string, to be replaced at the start of a link.
1246 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1247 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1249 [[linkkey:tag][description]]
1251 The 'linkkey' must be a word word, starting with a letter, followed
1252 by letters, numbers, '-' or '_'.
1254 If REPLACE is a string, the tag will simply be appended to create the link.
1255 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1256 the placeholder \"%h\" will cause a url-encoded version of the tag to
1257 be inserted at that point (see the function `url-hexify-string').
1259 REPLACE may also be a function that will be called with the tag as the
1260 only argument to create the link, which should be returned as a string.
1262 See the manual for examples."
1263 :group 'org-link
1264 :type '(repeat
1265 (cons
1266 (string :tag "Protocol")
1267 (choice
1268 (string :tag "Format")
1269 (function)))))
1271 (defcustom org-descriptive-links t
1272 "Non-nil means Org will display descriptive links.
1273 E.g. [[http://orgmode.org][Org website]] will be displayed as
1274 \"Org Website\", hiding the link itself and just displaying its
1275 description. When set to `nil', Org will display the full links
1276 literally.
1278 You can interactively set the value of this variable by calling
1279 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1280 :group 'org-link
1281 :type 'boolean)
1283 (defcustom org-link-file-path-type 'adaptive
1284 "How the path name in file links should be stored.
1285 Valid values are:
1287 relative Relative to the current directory, i.e. the directory of the file
1288 into which the link is being inserted.
1289 absolute Absolute path, if possible with ~ for home directory.
1290 noabbrev Absolute path, no abbreviation of home directory.
1291 adaptive Use relative path for files in the current directory and sub-
1292 directories of it. For other files, use an absolute path."
1293 :group 'org-link
1294 :type '(choice
1295 (const relative)
1296 (const absolute)
1297 (const noabbrev)
1298 (const adaptive)))
1300 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1301 "Types of links that should be activated in Org-mode files.
1302 This is a list of symbols, each leading to the activation of a certain link
1303 type. In principle, it does not hurt to turn on most link types - there may
1304 be a small gain when turning off unused link types. The types are:
1306 bracket The recommended [[link][description]] or [[link]] links with hiding.
1307 angle Links in angular brackets that may contain whitespace like
1308 <bbdb:Carsten Dominik>.
1309 plain Plain links in normal text, no whitespace, like http://google.com.
1310 radio Text that is matched by a radio target, see manual for details.
1311 tag Tag settings in a headline (link to tag search).
1312 date Time stamps (link to calendar).
1313 footnote Footnote labels.
1315 Changing this variable requires a restart of Emacs to become effective."
1316 :group 'org-link
1317 :type '(set :greedy t
1318 (const :tag "Double bracket links" bracket)
1319 (const :tag "Angular bracket links" angle)
1320 (const :tag "Plain text links" plain)
1321 (const :tag "Radio target matches" radio)
1322 (const :tag "Tags" tag)
1323 (const :tag "Timestamps" date)
1324 (const :tag "Footnotes" footnote)))
1326 (defcustom org-make-link-description-function nil
1327 "Function to use to generate link descriptions from links.
1328 If nil the link location will be used. This function must take
1329 two parameters; the first is the link and the second the
1330 description `org-insert-link' has generated, and should return the
1331 description to use."
1332 :group 'org-link
1333 :type 'function)
1335 (defgroup org-link-store nil
1336 "Options concerning storing links in Org-mode."
1337 :tag "Org Store Link"
1338 :group 'org-link)
1340 (defcustom org-email-link-description-format "Email %c: %.30s"
1341 "Format of the description part of a link to an email or usenet message.
1342 The following %-escapes will be replaced by corresponding information:
1344 %F full \"From\" field
1345 %f name, taken from \"From\" field, address if no name
1346 %T full \"To\" field
1347 %t first name in \"To\" field, address if no name
1348 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1349 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1350 %s subject
1351 %d date
1352 %m message-id.
1354 You may use normal field width specification between the % and the letter.
1355 This is for example useful to limit the length of the subject.
1357 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1358 :group 'org-link-store
1359 :type 'string)
1361 (defcustom org-from-is-user-regexp
1362 (let (r1 r2)
1363 (when (and user-mail-address (not (string= user-mail-address "")))
1364 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1365 (when (and user-full-name (not (string= user-full-name "")))
1366 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1367 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1368 "Regexp matched against the \"From:\" header of an email or usenet message.
1369 It should match if the message is from the user him/herself."
1370 :group 'org-link-store
1371 :type 'regexp)
1373 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1374 "Non-nil means storing a link to an Org file will use entry IDs.
1376 Note that before this variable is even considered, org-id must be loaded,
1377 so please customize `org-modules' and turn it on.
1379 The variable can have the following values:
1381 t Create an ID if needed to make a link to the current entry.
1383 create-if-interactive
1384 If `org-store-link' is called directly (interactively, as a user
1385 command), do create an ID to support the link. But when doing the
1386 job for remember, only use the ID if it already exists. The
1387 purpose of this setting is to avoid proliferation of unwanted
1388 IDs, just because you happen to be in an Org file when you
1389 call `org-remember' that automatically and preemptively
1390 creates a link. If you do want to get an ID link in a remember
1391 template to an entry not having an ID, create it first by
1392 explicitly creating a link to it, using `C-c C-l' first.
1394 create-if-interactive-and-no-custom-id
1395 Like create-if-interactive, but do not create an ID if there is
1396 a CUSTOM_ID property defined in the entry. This is the default.
1398 use-existing
1399 Use existing ID, do not create one.
1401 nil Never use an ID to make a link, instead link using a text search for
1402 the headline text."
1403 :group 'org-link-store
1404 :type '(choice
1405 (const :tag "Create ID to make link" t)
1406 (const :tag "Create if storing link interactively"
1407 create-if-interactive)
1408 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1409 create-if-interactive-and-no-custom-id)
1410 (const :tag "Only use existing" use-existing)
1411 (const :tag "Do not use ID to create link" nil)))
1413 (defcustom org-context-in-file-links t
1414 "Non-nil means file links from `org-store-link' contain context.
1415 A search string will be added to the file name with :: as separator and
1416 used to find the context when the link is activated by the command
1417 `org-open-at-point'. When this option is t, the entire active region
1418 will be placed in the search string of the file link. If set to a
1419 positive integer, only the first n lines of context will be stored.
1421 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1422 negates this setting for the duration of the command."
1423 :group 'org-link-store
1424 :type '(choice boolean integer))
1426 (defcustom org-keep-stored-link-after-insertion nil
1427 "Non-nil means keep link in list for entire session.
1429 The command `org-store-link' adds a link pointing to the current
1430 location to an internal list. These links accumulate during a session.
1431 The command `org-insert-link' can be used to insert links into any
1432 Org-mode file (offering completion for all stored links). When this
1433 option is nil, every link which has been inserted once using \\[org-insert-link]
1434 will be removed from the list, to make completing the unused links
1435 more efficient."
1436 :group 'org-link-store
1437 :type 'boolean)
1439 (defgroup org-link-follow nil
1440 "Options concerning following links in Org-mode."
1441 :tag "Org Follow Link"
1442 :group 'org-link)
1444 (defcustom org-link-translation-function nil
1445 "Function to translate links with different syntax to Org syntax.
1446 This can be used to translate links created for example by the Planner
1447 or emacs-wiki packages to Org syntax.
1448 The function must accept two parameters, a TYPE containing the link
1449 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1450 which is everything after the link protocol. It should return a cons
1451 with possibly modified values of type and path.
1452 Org contains a function for this, so if you set this variable to
1453 `org-translate-link-from-planner', you should be able follow many
1454 links created by planner."
1455 :group 'org-link-follow
1456 :type 'function)
1458 (defcustom org-follow-link-hook nil
1459 "Hook that is run after a link has been followed."
1460 :group 'org-link-follow
1461 :type 'hook)
1463 (defcustom org-tab-follows-link nil
1464 "Non-nil means on links TAB will follow the link.
1465 Needs to be set before org.el is loaded.
1466 This really should not be used, it does not make sense, and the
1467 implementation is bad."
1468 :group 'org-link-follow
1469 :type 'boolean)
1471 (defcustom org-return-follows-link nil
1472 "Non-nil means on links RET will follow the link."
1473 :group 'org-link-follow
1474 :type 'boolean)
1476 (defcustom org-mouse-1-follows-link
1477 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1478 "Non-nil means mouse-1 on a link will follow the link.
1479 A longer mouse click will still set point. Does not work on XEmacs.
1480 Needs to be set before org.el is loaded."
1481 :group 'org-link-follow
1482 :type 'boolean)
1484 (defcustom org-mark-ring-length 4
1485 "Number of different positions to be recorded in the ring.
1486 Changing this requires a restart of Emacs to work correctly."
1487 :group 'org-link-follow
1488 :type 'integer)
1490 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1491 "Non-nil means internal links in Org files must exactly match a headline.
1492 When nil, the link search tries to match a phrase with all words
1493 in the search text."
1494 :group 'org-link-follow
1495 :type '(choice
1496 (const :tag "Use fuzy text search" nil)
1497 (const :tag "Match only exact headline" t)
1498 (const :tag "Match extact headline or query to create it"
1499 query-to-create)))
1501 (defcustom org-link-frame-setup
1502 '((vm . vm-visit-folder-other-frame)
1503 (gnus . org-gnus-no-new-news)
1504 (file . find-file-other-window)
1505 (wl . wl-other-frame))
1506 "Setup the frame configuration for following links.
1507 When following a link with Emacs, it may often be useful to display
1508 this link in another window or frame. This variable can be used to
1509 set this up for the different types of links.
1510 For VM, use any of
1511 `vm-visit-folder'
1512 `vm-visit-folder-other-window'
1513 `vm-visit-folder-other-frame'
1514 For Gnus, use any of
1515 `gnus'
1516 `gnus-other-frame'
1517 `org-gnus-no-new-news'
1518 For FILE, use any of
1519 `find-file'
1520 `find-file-other-window'
1521 `find-file-other-frame'
1522 For Wanderlust use any of
1523 `wl'
1524 `wl-other-frame'
1525 For the calendar, use the variable `calendar-setup'.
1526 For BBDB, it is currently only possible to display the matches in
1527 another window."
1528 :group 'org-link-follow
1529 :type '(list
1530 (cons (const vm)
1531 (choice
1532 (const vm-visit-folder)
1533 (const vm-visit-folder-other-window)
1534 (const vm-visit-folder-other-frame)))
1535 (cons (const gnus)
1536 (choice
1537 (const gnus)
1538 (const gnus-other-frame)
1539 (const org-gnus-no-new-news)))
1540 (cons (const file)
1541 (choice
1542 (const find-file)
1543 (const find-file-other-window)
1544 (const find-file-other-frame)))
1545 (cons (const wl)
1546 (choice
1547 (const wl)
1548 (const wl-other-frame)))))
1550 (defcustom org-display-internal-link-with-indirect-buffer nil
1551 "Non-nil means use indirect buffer to display infile links.
1552 Activating internal links (from one location in a file to another location
1553 in the same file) normally just jumps to the location. When the link is
1554 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1555 is displayed in
1556 another window. When this option is set, the other window actually displays
1557 an indirect buffer clone of the current buffer, to avoid any visibility
1558 changes to the current buffer."
1559 :group 'org-link-follow
1560 :type 'boolean)
1562 (defcustom org-open-non-existing-files nil
1563 "Non-nil means `org-open-file' will open non-existing files.
1564 When nil, an error will be generated.
1565 This variable applies only to external applications because they
1566 might choke on non-existing files. If the link is to a file that
1567 will be opened in Emacs, the variable is ignored."
1568 :group 'org-link-follow
1569 :type 'boolean)
1571 (defcustom org-open-directory-means-index-dot-org nil
1572 "Non-nil means a link to a directory really means to index.org.
1573 When nil, following a directory link will run dired or open a finder/explorer
1574 window on that directory."
1575 :group 'org-link-follow
1576 :type 'boolean)
1578 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1579 "Function and arguments to call for following mailto links.
1580 This is a list with the first element being a Lisp function, and the
1581 remaining elements being arguments to the function. In string arguments,
1582 %a will be replaced by the address, and %s will be replaced by the subject
1583 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1584 :group 'org-link-follow
1585 :type '(choice
1586 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1587 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1588 (const :tag "message-mail" (message-mail "%a" "%s"))
1589 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1591 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1592 "Non-nil means ask for confirmation before executing shell links.
1593 Shell links can be dangerous: just think about a link
1595 [[shell:rm -rf ~/*][Google Search]]
1597 This link would show up in your Org-mode document as \"Google Search\",
1598 but really it would remove your entire home directory.
1599 Therefore we advise against setting this variable to nil.
1600 Just change it to `y-or-n-p' if you want to confirm with a
1601 single keystroke rather than having to type \"yes\"."
1602 :group 'org-link-follow
1603 :type '(choice
1604 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1605 (const :tag "with y-or-n (faster)" y-or-n-p)
1606 (const :tag "no confirmation (dangerous)" nil)))
1607 (put 'org-confirm-shell-link-function
1608 'safe-local-variable
1609 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1611 (defcustom org-confirm-shell-link-not-regexp ""
1612 "A regexp to skip confirmation for shell links."
1613 :group 'org-link-follow
1614 :type 'regexp)
1616 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1617 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1618 Elisp links can be dangerous: just think about a link
1620 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1622 This link would show up in your Org-mode document as \"Google Search\",
1623 but really it would remove your entire home directory.
1624 Therefore we advise against setting this variable to nil.
1625 Just change it to `y-or-n-p' if you want to confirm with a
1626 single keystroke rather than having to type \"yes\"."
1627 :group 'org-link-follow
1628 :type '(choice
1629 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1630 (const :tag "with y-or-n (faster)" y-or-n-p)
1631 (const :tag "no confirmation (dangerous)" nil)))
1632 (put 'org-confirm-shell-link-function
1633 'safe-local-variable
1634 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1636 (defcustom org-confirm-elisp-link-not-regexp ""
1637 "A regexp to skip confirmation for Elisp links."
1638 :group 'org-link-follow
1639 :type 'regexp)
1641 (defconst org-file-apps-defaults-gnu
1642 '((remote . emacs)
1643 (system . mailcap)
1644 (t . mailcap))
1645 "Default file applications on a UNIX or GNU/Linux system.
1646 See `org-file-apps'.")
1648 (defconst org-file-apps-defaults-macosx
1649 '((remote . emacs)
1650 (t . "open %s")
1651 (system . "open %s")
1652 ("ps.gz" . "gv %s")
1653 ("eps.gz" . "gv %s")
1654 ("dvi" . "xdvi %s")
1655 ("fig" . "xfig %s"))
1656 "Default file applications on a MacOS X system.
1657 The system \"open\" is known as a default, but we use X11 applications
1658 for some files for which the OS does not have a good default.
1659 See `org-file-apps'.")
1661 (defconst org-file-apps-defaults-windowsnt
1662 (list
1663 '(remote . emacs)
1664 (cons t
1665 (list (if (featurep 'xemacs)
1666 'mswindows-shell-execute
1667 'w32-shell-execute)
1668 "open" 'file))
1669 (cons 'system
1670 (list (if (featurep 'xemacs)
1671 'mswindows-shell-execute
1672 'w32-shell-execute)
1673 "open" 'file)))
1674 "Default file applications on a Windows NT system.
1675 The system \"open\" is used for most files.
1676 See `org-file-apps'.")
1678 (defcustom org-file-apps
1680 (auto-mode . emacs)
1681 ("\\.mm\\'" . default)
1682 ("\\.x?html?\\'" . default)
1683 ("\\.pdf\\'" . default)
1685 "External applications for opening `file:path' items in a document.
1686 Org-mode uses system defaults for different file types, but
1687 you can use this variable to set the application for a given file
1688 extension. The entries in this list are cons cells where the car identifies
1689 files and the cdr the corresponding command. Possible values for the
1690 file identifier are
1691 \"string\" A string as a file identifier can be interpreted in different
1692 ways, depending on its contents:
1694 - Alphanumeric characters only:
1695 Match links with this file extension.
1696 Example: (\"pdf\" . \"evince %s\")
1697 to open PDFs with evince.
1699 - Regular expression: Match links where the
1700 filename matches the regexp. If you want to
1701 use groups here, use shy groups.
1703 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1704 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1705 to open *.html and *.xhtml with firefox.
1707 - Regular expression which contains (non-shy) groups:
1708 Match links where the whole link, including \"::\", and
1709 anything after that, matches the regexp.
1710 In a custom command string, %1, %2, etc. are replaced with
1711 the parts of the link that were matched by the groups.
1712 For backwards compatibility, if a command string is given
1713 that does not use any of the group matches, this case is
1714 handled identically to the second one (i.e. match against
1715 file name only).
1716 In a custom lisp form, you can access the group matches with
1717 (match-string n link).
1719 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1720 to open [[file:document.pdf::5]] with evince at page 5.
1722 `directory' Matches a directory
1723 `remote' Matches a remote file, accessible through tramp or efs.
1724 Remote files most likely should be visited through Emacs
1725 because external applications cannot handle such paths.
1726 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1727 so all files Emacs knows how to handle. Using this with
1728 command `emacs' will open most files in Emacs. Beware that this
1729 will also open html files inside Emacs, unless you add
1730 (\"html\" . default) to the list as well.
1731 t Default for files not matched by any of the other options.
1732 `system' The system command to open files, like `open' on Windows
1733 and Mac OS X, and mailcap under GNU/Linux. This is the command
1734 that will be selected if you call `C-c C-o' with a double
1735 \\[universal-argument] \\[universal-argument] prefix.
1737 Possible values for the command are:
1738 `emacs' The file will be visited by the current Emacs process.
1739 `default' Use the default application for this file type, which is the
1740 association for t in the list, most likely in the system-specific
1741 part.
1742 This can be used to overrule an unwanted setting in the
1743 system-specific variable.
1744 `system' Use the system command for opening files, like \"open\".
1745 This command is specified by the entry whose car is `system'.
1746 Most likely, the system-specific version of this variable
1747 does define this command, but you can overrule/replace it
1748 here.
1749 string A command to be executed by a shell; %s will be replaced
1750 by the path to the file.
1751 sexp A Lisp form which will be evaluated. The file path will
1752 be available in the Lisp variable `file'.
1753 For more examples, see the system specific constants
1754 `org-file-apps-defaults-macosx'
1755 `org-file-apps-defaults-windowsnt'
1756 `org-file-apps-defaults-gnu'."
1757 :group 'org-link-follow
1758 :type '(repeat
1759 (cons (choice :value ""
1760 (string :tag "Extension")
1761 (const :tag "System command to open files" system)
1762 (const :tag "Default for unrecognized files" t)
1763 (const :tag "Remote file" remote)
1764 (const :tag "Links to a directory" directory)
1765 (const :tag "Any files that have Emacs modes"
1766 auto-mode))
1767 (choice :value ""
1768 (const :tag "Visit with Emacs" emacs)
1769 (const :tag "Use default" default)
1770 (const :tag "Use the system command" system)
1771 (string :tag "Command")
1772 (sexp :tag "Lisp form")))))
1776 (defgroup org-refile nil
1777 "Options concerning refiling entries in Org-mode."
1778 :tag "Org Refile"
1779 :group 'org)
1781 (defcustom org-directory "~/org"
1782 "Directory with org files.
1783 This is just a default location to look for Org files. There is no need
1784 at all to put your files into this directory. It is only used in the
1785 following situations:
1787 1. When a remember template specifies a target file that is not an
1788 absolute path. The path will then be interpreted relative to
1789 `org-directory'
1790 2. When a remember note is filed away in an interactive way (when exiting the
1791 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1792 with `org-directory' as the default path."
1793 :group 'org-refile
1794 :group 'org-remember
1795 :type 'directory)
1797 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1798 "Default target for storing notes.
1799 Used as a fall back file for org-remember.el and org-capture.el, for
1800 templates that do not specify a target file."
1801 :group 'org-refile
1802 :group 'org-remember
1803 :type '(choice
1804 (const :tag "Default from remember-data-file" nil)
1805 file))
1807 (defcustom org-goto-interface 'outline
1808 "The default interface to be used for `org-goto'.
1809 Allowed values are:
1810 outline The interface shows an outline of the relevant file
1811 and the correct heading is found by moving through
1812 the outline or by searching with incremental search.
1813 outline-path-completion Headlines in the current buffer are offered via
1814 completion. This is the interface also used by
1815 the refile command."
1816 :group 'org-refile
1817 :type '(choice
1818 (const :tag "Outline" outline)
1819 (const :tag "Outline-path-completion" outline-path-completion)))
1821 (defcustom org-goto-max-level 5
1822 "Maximum target level when running `org-goto' with refile interface."
1823 :group 'org-refile
1824 :type 'integer)
1826 (defcustom org-reverse-note-order nil
1827 "Non-nil means store new notes at the beginning of a file or entry.
1828 When nil, new notes will be filed to the end of a file or entry.
1829 This can also be a list with cons cells of regular expressions that
1830 are matched against file names, and values."
1831 :group 'org-remember
1832 :group 'org-refile
1833 :type '(choice
1834 (const :tag "Reverse always" t)
1835 (const :tag "Reverse never" nil)
1836 (repeat :tag "By file name regexp"
1837 (cons regexp boolean))))
1839 (defcustom org-log-refile nil
1840 "Information to record when a task is refiled.
1842 Possible values are:
1844 nil Don't add anything
1845 time Add a time stamp to the task
1846 note Prompt for a note and add it with template `org-log-note-headings'
1848 This option can also be set with on a per-file-basis with
1850 #+STARTUP: nologrefile
1851 #+STARTUP: logrefile
1852 #+STARTUP: lognoterefile
1854 You can have local logging settings for a subtree by setting the LOGGING
1855 property to one or more of these keywords.
1857 When bulk-refiling from the agenda, the value `note' is forbidden and
1858 will temporarily be changed to `time'."
1859 :group 'org-refile
1860 :group 'org-progress
1861 :type '(choice
1862 (const :tag "No logging" nil)
1863 (const :tag "Record timestamp" time)
1864 (const :tag "Record timestamp with note." note)))
1866 (defcustom org-refile-targets nil
1867 "Targets for refiling entries with \\[org-refile].
1868 This is a list of cons cells. Each cell contains:
1869 - a specification of the files to be considered, either a list of files,
1870 or a symbol whose function or variable value will be used to retrieve
1871 a file name or a list of file names. If you use `org-agenda-files' for
1872 that, all agenda files will be scanned for targets. Nil means consider
1873 headings in the current buffer.
1874 - A specification of how to find candidate refile targets. This may be
1875 any of:
1876 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1877 This tag has to be present in all target headlines, inheritance will
1878 not be considered.
1879 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1880 todo keyword.
1881 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1882 headlines that are refiling targets.
1883 - a cons cell (:level . N). Any headline of level N is considered a target.
1884 Note that, when `org-odd-levels-only' is set, level corresponds to
1885 order in hierarchy, not to the number of stars.
1886 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1887 Note that, when `org-odd-levels-only' is set, level corresponds to
1888 order in hierarchy, not to the number of stars.
1890 Each element of this list generates a set of possible targets.
1891 The union of these sets is presented (with completion) to
1892 the user by `org-refile'.
1894 You can set the variable `org-refile-target-verify-function' to a function
1895 to verify each headline found by the simple criteria above.
1897 When this variable is nil, all top-level headlines in the current buffer
1898 are used, equivalent to the value `((nil . (:level . 1))'."
1899 :group 'org-refile
1900 :type '(repeat
1901 (cons
1902 (choice :value org-agenda-files
1903 (const :tag "All agenda files" org-agenda-files)
1904 (const :tag "Current buffer" nil)
1905 (function) (variable) (file))
1906 (choice :tag "Identify target headline by"
1907 (cons :tag "Specific tag" (const :value :tag) (string))
1908 (cons :tag "TODO keyword" (const :value :todo) (string))
1909 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1910 (cons :tag "Level number" (const :value :level) (integer))
1911 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1913 (defcustom org-refile-target-verify-function nil
1914 "Function to verify if the headline at point should be a refile target.
1915 The function will be called without arguments, with point at the
1916 beginning of the headline. It should return t and leave point
1917 where it is if the headline is a valid target for refiling.
1919 If the target should not be selected, the function must return nil.
1920 In addition to this, it may move point to a place from where the search
1921 should be continued. For example, the function may decide that the entire
1922 subtree of the current entry should be excluded and move point to the end
1923 of the subtree."
1924 :group 'org-refile
1925 :type 'function)
1927 (defcustom org-refile-use-cache nil
1928 "Non-nil means cache refile targets to speed up the process.
1929 The cache for a particular file will be updated automatically when
1930 the buffer has been killed, or when any of the marker used for flagging
1931 refile targets no longer points at a live buffer.
1932 If you have added new entries to a buffer that might themselves be targets,
1933 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1934 find that easier, `C-u C-u C-u C-c C-w'."
1935 :group 'org-refile
1936 :type 'boolean)
1938 (defcustom org-refile-use-outline-path nil
1939 "Non-nil means provide refile targets as paths.
1940 So a level 3 headline will be available as level1/level2/level3.
1942 When the value is `file', also include the file name (without directory)
1943 into the path. In this case, you can also stop the completion after
1944 the file name, to get entries inserted as top level in the file.
1946 When `full-file-path', include the full file path."
1947 :group 'org-refile
1948 :type '(choice
1949 (const :tag "Not" nil)
1950 (const :tag "Yes" t)
1951 (const :tag "Start with file name" file)
1952 (const :tag "Start with full file path" full-file-path)))
1954 (defcustom org-outline-path-complete-in-steps t
1955 "Non-nil means complete the outline path in hierarchical steps.
1956 When Org-mode uses the refile interface to select an outline path
1957 \(see variable `org-refile-use-outline-path'), the completion of
1958 the path can be done is a single go, or if can be done in steps down
1959 the headline hierarchy. Going in steps is probably the best if you
1960 do not use a special completion package like `ido' or `icicles'.
1961 However, when using these packages, going in one step can be very
1962 fast, while still showing the whole path to the entry."
1963 :group 'org-refile
1964 :type 'boolean)
1966 (defcustom org-refile-allow-creating-parent-nodes nil
1967 "Non-nil means allow to create new nodes as refile targets.
1968 New nodes are then created by adding \"/new node name\" to the completion
1969 of an existing node. When the value of this variable is `confirm',
1970 new node creation must be confirmed by the user (recommended)
1971 When nil, the completion must match an existing entry.
1973 Note that, if the new heading is not seen by the criteria
1974 listed in `org-refile-targets', multiple instances of the same
1975 heading would be created by trying again to file under the new
1976 heading."
1977 :group 'org-refile
1978 :type '(choice
1979 (const :tag "Never" nil)
1980 (const :tag "Always" t)
1981 (const :tag "Prompt for confirmation" confirm)))
1983 (defcustom org-refile-active-region-within-subtree nil
1984 "Non-nil means also refile active region within a subtree.
1986 By default `org-refile' doesn't allow refiling regions if they
1987 don't contain a set of subtrees, but it might be convenient to
1988 do so sometimes: in that case, the first line of the region is
1989 converted to a headline before refiling."
1990 :group 'org-refile
1991 :type 'boolean)
1993 (defgroup org-todo nil
1994 "Options concerning TODO items in Org-mode."
1995 :tag "Org TODO"
1996 :group 'org)
1998 (defgroup org-progress nil
1999 "Options concerning Progress logging in Org-mode."
2000 :tag "Org Progress"
2001 :group 'org-time)
2003 (defvar org-todo-interpretation-widgets
2004 '((:tag "Sequence (cycling hits every state)" sequence)
2005 (:tag "Type (cycling directly to DONE)" type))
2006 "The available interpretation symbols for customizing `org-todo-keywords'.
2007 Interested libraries should add to this list.")
2009 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2010 "List of TODO entry keyword sequences and their interpretation.
2011 \\<org-mode-map>This is a list of sequences.
2013 Each sequence starts with a symbol, either `sequence' or `type',
2014 indicating if the keywords should be interpreted as a sequence of
2015 action steps, or as different types of TODO items. The first
2016 keywords are states requiring action - these states will select a headline
2017 for inclusion into the global TODO list Org-mode produces. If one of
2018 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2019 signify that no further action is necessary. If \"|\" is not found,
2020 the last keyword is treated as the only DONE state of the sequence.
2022 The command \\[org-todo] cycles an entry through these states, and one
2023 additional state where no keyword is present. For details about this
2024 cycling, see the manual.
2026 TODO keywords and interpretation can also be set on a per-file basis with
2027 the special #+SEQ_TODO and #+TYP_TODO lines.
2029 Each keyword can optionally specify a character for fast state selection
2030 \(in combination with the variable `org-use-fast-todo-selection')
2031 and specifiers for state change logging, using the same syntax
2032 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2033 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2034 indicates to record a time stamp each time this state is selected.
2036 Each keyword may also specify if a timestamp or a note should be
2037 recorded when entering or leaving the state, by adding additional
2038 characters in the parenthesis after the keyword. This looks like this:
2039 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2040 record only the time of the state change. With X and Y being either
2041 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2042 Y when leaving the state if and only if the *target* state does not
2043 define X. You may omit any of the fast-selection key or X or /Y,
2044 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2046 For backward compatibility, this variable may also be just a list
2047 of keywords - in this case the interpretation (sequence or type) will be
2048 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2049 :group 'org-todo
2050 :group 'org-keywords
2051 :type '(choice
2052 (repeat :tag "Old syntax, just keywords"
2053 (string :tag "Keyword"))
2054 (repeat :tag "New syntax"
2055 (cons
2056 (choice
2057 :tag "Interpretation"
2058 ;;Quick and dirty way to see
2059 ;;`org-todo-interpretations'. This takes the
2060 ;;place of item arguments
2061 :convert-widget
2062 (lambda (widget)
2063 (widget-put widget
2064 :args (mapcar
2065 #'(lambda (x)
2066 (widget-convert
2067 (cons 'const x)))
2068 org-todo-interpretation-widgets))
2069 widget))
2070 (repeat
2071 (string :tag "Keyword"))))))
2073 (defvar org-todo-keywords-1 nil
2074 "All TODO and DONE keywords active in a buffer.")
2075 (make-variable-buffer-local 'org-todo-keywords-1)
2076 (defvar org-todo-keywords-for-agenda nil)
2077 (defvar org-done-keywords-for-agenda nil)
2078 (defvar org-drawers-for-agenda nil)
2079 (defvar org-todo-keyword-alist-for-agenda nil)
2080 (defvar org-tag-alist-for-agenda nil)
2081 (defvar org-agenda-contributing-files nil)
2082 (defvar org-not-done-keywords nil)
2083 (make-variable-buffer-local 'org-not-done-keywords)
2084 (defvar org-done-keywords nil)
2085 (make-variable-buffer-local 'org-done-keywords)
2086 (defvar org-todo-heads nil)
2087 (make-variable-buffer-local 'org-todo-heads)
2088 (defvar org-todo-sets nil)
2089 (make-variable-buffer-local 'org-todo-sets)
2090 (defvar org-todo-log-states nil)
2091 (make-variable-buffer-local 'org-todo-log-states)
2092 (defvar org-todo-kwd-alist nil)
2093 (make-variable-buffer-local 'org-todo-kwd-alist)
2094 (defvar org-todo-key-alist nil)
2095 (make-variable-buffer-local 'org-todo-key-alist)
2096 (defvar org-todo-key-trigger nil)
2097 (make-variable-buffer-local 'org-todo-key-trigger)
2099 (defcustom org-todo-interpretation 'sequence
2100 "Controls how TODO keywords are interpreted.
2101 This variable is in principle obsolete and is only used for
2102 backward compatibility, if the interpretation of todo keywords is
2103 not given already in `org-todo-keywords'. See that variable for
2104 more information."
2105 :group 'org-todo
2106 :group 'org-keywords
2107 :type '(choice (const sequence)
2108 (const type)))
2110 (defcustom org-use-fast-todo-selection t
2111 "Non-nil means use the fast todo selection scheme with C-c C-t.
2112 This variable describes if and under what circumstances the cycling
2113 mechanism for TODO keywords will be replaced by a single-key, direct
2114 selection scheme.
2116 When nil, fast selection is never used.
2118 When the symbol `prefix', it will be used when `org-todo' is called with
2119 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2120 in an agenda buffer.
2122 When t, fast selection is used by default. In this case, the prefix
2123 argument forces cycling instead.
2125 In all cases, the special interface is only used if access keys have actually
2126 been assigned by the user, i.e. if keywords in the configuration are followed
2127 by a letter in parenthesis, like TODO(t)."
2128 :group 'org-todo
2129 :type '(choice
2130 (const :tag "Never" nil)
2131 (const :tag "By default" t)
2132 (const :tag "Only with C-u C-c C-t" prefix)))
2134 (defcustom org-provide-todo-statistics t
2135 "Non-nil means update todo statistics after insert and toggle.
2136 ALL-HEADLINES means update todo statistics by including headlines
2137 with no TODO keyword as well, counting them as not done.
2138 A list of TODO keywords means the same, but skip keywords that are
2139 not in this list.
2141 When this is set, todo statistics is updated in the parent of the
2142 current entry each time a todo state is changed."
2143 :group 'org-todo
2144 :type '(choice
2145 (const :tag "Yes, only for TODO entries" t)
2146 (const :tag "Yes, including all entries" 'all-headlines)
2147 (repeat :tag "Yes, for TODOs in this list"
2148 (string :tag "TODO keyword"))
2149 (other :tag "No TODO statistics" nil)))
2151 (defcustom org-hierarchical-todo-statistics t
2152 "Non-nil means TODO statistics covers just direct children.
2153 When nil, all entries in the subtree are considered.
2154 This has only an effect if `org-provide-todo-statistics' is set.
2155 To set this to nil for only a single subtree, use a COOKIE_DATA
2156 property and include the word \"recursive\" into the value."
2157 :group 'org-todo
2158 :type 'boolean)
2160 (defcustom org-after-todo-state-change-hook nil
2161 "Hook which is run after the state of a TODO item was changed.
2162 The new state (a string with a TODO keyword, or nil) is available in the
2163 Lisp variable `state'."
2164 :group 'org-todo
2165 :type 'hook)
2167 (defvar org-blocker-hook nil
2168 "Hook for functions that are allowed to block a state change.
2170 Each function gets as its single argument a property list, see
2171 `org-trigger-hook' for more information about this list.
2173 If any of the functions in this hook returns nil, the state change
2174 is blocked.")
2176 (defvar org-trigger-hook nil
2177 "Hook for functions that are triggered by a state change.
2179 Each function gets as its single argument a property list with at least
2180 the following elements:
2182 (:type type-of-change :position pos-at-entry-start
2183 :from old-state :to new-state)
2185 Depending on the type, more properties may be present.
2187 This mechanism is currently implemented for:
2189 TODO state changes
2190 ------------------
2191 :type todo-state-change
2192 :from previous state (keyword as a string), or nil, or a symbol
2193 'todo' or 'done', to indicate the general type of state.
2194 :to new state, like in :from")
2196 (defcustom org-enforce-todo-dependencies nil
2197 "Non-nil means undone TODO entries will block switching the parent to DONE.
2198 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2199 be blocked if any prior sibling is not yet done.
2200 Finally, if the parent is blocked because of ordered siblings of its own,
2201 the child will also be blocked.
2202 This variable needs to be set before org.el is loaded, and you need to
2203 restart Emacs after a change to make the change effective. The only way
2204 to change is while Emacs is running is through the customize interface."
2205 :set (lambda (var val)
2206 (set var val)
2207 (if val
2208 (add-hook 'org-blocker-hook
2209 'org-block-todo-from-children-or-siblings-or-parent)
2210 (remove-hook 'org-blocker-hook
2211 'org-block-todo-from-children-or-siblings-or-parent)))
2212 :group 'org-todo
2213 :type 'boolean)
2215 (defcustom org-enforce-todo-checkbox-dependencies nil
2216 "Non-nil means unchecked boxes will block switching the parent to DONE.
2217 When this is nil, checkboxes have no influence on switching TODO states.
2218 When non-nil, you first need to check off all check boxes before the TODO
2219 entry can be switched to DONE.
2220 This variable needs to be set before org.el is loaded, and you need to
2221 restart Emacs after a change to make the change effective. The only way
2222 to change is while Emacs is running is through the customize interface."
2223 :set (lambda (var val)
2224 (set var val)
2225 (if val
2226 (add-hook 'org-blocker-hook
2227 'org-block-todo-from-checkboxes)
2228 (remove-hook 'org-blocker-hook
2229 'org-block-todo-from-checkboxes)))
2230 :group 'org-todo
2231 :type 'boolean)
2233 (defcustom org-treat-insert-todo-heading-as-state-change nil
2234 "Non-nil means inserting a TODO heading is treated as state change.
2235 So when the command \\[org-insert-todo-heading] is used, state change
2236 logging will apply if appropriate. When nil, the new TODO item will
2237 be inserted directly, and no logging will take place."
2238 :group 'org-todo
2239 :type 'boolean)
2241 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2242 "Non-nil means switching TODO states with S-cursor counts as state change.
2243 This is the default behavior. However, setting this to nil allows a
2244 convenient way to select a TODO state and bypass any logging associated
2245 with that."
2246 :group 'org-todo
2247 :type 'boolean)
2249 (defcustom org-todo-state-tags-triggers nil
2250 "Tag changes that should be triggered by TODO state changes.
2251 This is a list. Each entry is
2253 (state-change (tag . flag) .......)
2255 State-change can be a string with a state, and empty string to indicate the
2256 state that has no TODO keyword, or it can be one of the symbols `todo'
2257 or `done', meaning any not-done or done state, respectively."
2258 :group 'org-todo
2259 :group 'org-tags
2260 :type '(repeat
2261 (cons (choice :tag "When changing to"
2262 (const :tag "Not-done state" todo)
2263 (const :tag "Done state" done)
2264 (string :tag "State"))
2265 (repeat
2266 (cons :tag "Tag action"
2267 (string :tag "Tag")
2268 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2270 (defcustom org-log-done nil
2271 "Information to record when a task moves to the DONE state.
2273 Possible values are:
2275 nil Don't add anything, just change the keyword
2276 time Add a time stamp to the task
2277 note Prompt for a note and add it with template `org-log-note-headings'
2279 This option can also be set with on a per-file-basis with
2281 #+STARTUP: nologdone
2282 #+STARTUP: logdone
2283 #+STARTUP: lognotedone
2285 You can have local logging settings for a subtree by setting the LOGGING
2286 property to one or more of these keywords."
2287 :group 'org-todo
2288 :group 'org-progress
2289 :type '(choice
2290 (const :tag "No logging" nil)
2291 (const :tag "Record CLOSED timestamp" time)
2292 (const :tag "Record CLOSED timestamp with note." note)))
2294 ;; Normalize old uses of org-log-done.
2295 (cond
2296 ((eq org-log-done t) (setq org-log-done 'time))
2297 ((and (listp org-log-done) (memq 'done org-log-done))
2298 (setq org-log-done 'note)))
2300 (defcustom org-log-reschedule nil
2301 "Information to record when the scheduling date of a tasks is modified.
2303 Possible values are:
2305 nil Don't add anything, just change the date
2306 time Add a time stamp to the task
2307 note Prompt for a note and add it with template `org-log-note-headings'
2309 This option can also be set with on a per-file-basis with
2311 #+STARTUP: nologreschedule
2312 #+STARTUP: logreschedule
2313 #+STARTUP: lognotereschedule"
2314 :group 'org-todo
2315 :group 'org-progress
2316 :type '(choice
2317 (const :tag "No logging" nil)
2318 (const :tag "Record timestamp" time)
2319 (const :tag "Record timestamp with note." note)))
2321 (defcustom org-log-redeadline nil
2322 "Information to record when the deadline date of a tasks is modified.
2324 Possible values are:
2326 nil Don't add anything, just change the date
2327 time Add a time stamp to the task
2328 note Prompt for a note and add it with template `org-log-note-headings'
2330 This option can also be set with on a per-file-basis with
2332 #+STARTUP: nologredeadline
2333 #+STARTUP: logredeadline
2334 #+STARTUP: lognoteredeadline
2336 You can have local logging settings for a subtree by setting the LOGGING
2337 property to one or more of these keywords."
2338 :group 'org-todo
2339 :group 'org-progress
2340 :type '(choice
2341 (const :tag "No logging" nil)
2342 (const :tag "Record timestamp" time)
2343 (const :tag "Record timestamp with note." note)))
2345 (defcustom org-log-note-clock-out nil
2346 "Non-nil means record a note when clocking out of an item.
2347 This can also be configured on a per-file basis by adding one of
2348 the following lines anywhere in the buffer:
2350 #+STARTUP: lognoteclock-out
2351 #+STARTUP: nolognoteclock-out"
2352 :group 'org-todo
2353 :group 'org-progress
2354 :type 'boolean)
2356 (defcustom org-log-done-with-time t
2357 "Non-nil means the CLOSED time stamp will contain date and time.
2358 When nil, only the date will be recorded."
2359 :group 'org-progress
2360 :type 'boolean)
2362 (defcustom org-log-note-headings
2363 '((done . "CLOSING NOTE %t")
2364 (state . "State %-12s from %-12S %t")
2365 (note . "Note taken on %t")
2366 (reschedule . "Rescheduled from %S on %t")
2367 (delschedule . "Not scheduled, was %S on %t")
2368 (redeadline . "New deadline from %S on %t")
2369 (deldeadline . "Removed deadline, was %S on %t")
2370 (refile . "Refiled on %t")
2371 (clock-out . ""))
2372 "Headings for notes added to entries.
2373 The value is an alist, with the car being a symbol indicating the note
2374 context, and the cdr is the heading to be used. The heading may also be the
2375 empty string.
2376 %t in the heading will be replaced by a time stamp.
2377 %T will be an active time stamp instead the default inactive one
2378 %d will be replaced by a short-format time stamp.
2379 %D will be replaced by an active short-format time stamp.
2380 %s will be replaced by the new TODO state, in double quotes.
2381 %S will be replaced by the old TODO state, in double quotes.
2382 %u will be replaced by the user name.
2383 %U will be replaced by the full user name.
2385 In fact, it is not a good idea to change the `state' entry, because
2386 agenda log mode depends on the format of these entries."
2387 :group 'org-todo
2388 :group 'org-progress
2389 :type '(list :greedy t
2390 (cons (const :tag "Heading when closing an item" done) string)
2391 (cons (const :tag
2392 "Heading when changing todo state (todo sequence only)"
2393 state) string)
2394 (cons (const :tag "Heading when just taking a note" note) string)
2395 (cons (const :tag "Heading when clocking out" clock-out) string)
2396 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2397 (cons (const :tag "Heading when rescheduling" reschedule) string)
2398 (cons (const :tag "Heading when changing deadline" redeadline) string)
2399 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2400 (cons (const :tag "Heading when refiling" refile) string)))
2402 (unless (assq 'note org-log-note-headings)
2403 (push '(note . "%t") org-log-note-headings))
2405 (defcustom org-log-into-drawer nil
2406 "Non-nil means insert state change notes and time stamps into a drawer.
2407 When nil, state changes notes will be inserted after the headline and
2408 any scheduling and clock lines, but not inside a drawer.
2410 The value of this variable should be the name of the drawer to use.
2411 LOGBOOK is proposed as the default drawer for this purpose, you can
2412 also set this to a string to define the drawer of your choice.
2414 A value of t is also allowed, representing \"LOGBOOK\".
2416 If this variable is set, `org-log-state-notes-insert-after-drawers'
2417 will be ignored.
2419 You can set the property LOG_INTO_DRAWER to overrule this setting for
2420 a subtree."
2421 :group 'org-todo
2422 :group 'org-progress
2423 :type '(choice
2424 (const :tag "Not into a drawer" nil)
2425 (const :tag "LOGBOOK" t)
2426 (string :tag "Other")))
2428 (if (fboundp 'defvaralias)
2429 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2431 (defun org-log-into-drawer ()
2432 "Return the value of `org-log-into-drawer', but let properties overrule.
2433 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2434 used instead of the default value."
2435 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2436 (cond
2437 ((or (not p) (equal p "nil")) org-log-into-drawer)
2438 ((equal p "t") "LOGBOOK")
2439 (t p))))
2441 (defcustom org-log-state-notes-insert-after-drawers nil
2442 "Non-nil means insert state change notes after any drawers in entry.
2443 Only the drawers that *immediately* follow the headline and the
2444 deadline/scheduled line are skipped.
2445 When nil, insert notes right after the heading and perhaps the line
2446 with deadline/scheduling if present.
2448 This variable will have no effect if `org-log-into-drawer' is
2449 set."
2450 :group 'org-todo
2451 :group 'org-progress
2452 :type 'boolean)
2454 (defcustom org-log-states-order-reversed t
2455 "Non-nil means the latest state note will be directly after heading.
2456 When nil, the state change notes will be ordered according to time."
2457 :group 'org-todo
2458 :group 'org-progress
2459 :type 'boolean)
2461 (defcustom org-todo-repeat-to-state nil
2462 "The TODO state to which a repeater should return the repeating task.
2463 By default this is the first task in a TODO sequence, or the previous state
2464 in a TODO_TYP set. But you can specify another task here.
2465 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2466 :group 'org-todo
2467 :type '(choice (const :tag "Head of sequence" nil)
2468 (string :tag "Specific state")))
2470 (defcustom org-log-repeat 'time
2471 "Non-nil means record moving through the DONE state when triggering repeat.
2472 An auto-repeating task is immediately switched back to TODO when
2473 marked DONE. If you are not logging state changes (by adding \"@\"
2474 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2475 record a closing note, there will be no record of the task moving
2476 through DONE. This variable forces taking a note anyway.
2478 nil Don't force a record
2479 time Record a time stamp
2480 note Record a note
2482 This option can also be set with on a per-file-basis with
2484 #+STARTUP: logrepeat
2485 #+STARTUP: lognoterepeat
2486 #+STARTUP: nologrepeat
2488 You can have local logging settings for a subtree by setting the LOGGING
2489 property to one or more of these keywords."
2490 :group 'org-todo
2491 :group 'org-progress
2492 :type '(choice
2493 (const :tag "Don't force a record" nil)
2494 (const :tag "Force recording the DONE state" time)
2495 (const :tag "Force recording a note with the DONE state" note)))
2498 (defgroup org-priorities nil
2499 "Priorities in Org-mode."
2500 :tag "Org Priorities"
2501 :group 'org-todo)
2503 (defcustom org-enable-priority-commands t
2504 "Non-nil means priority commands are active.
2505 When nil, these commands will be disabled, so that you never accidentally
2506 set a priority."
2507 :group 'org-priorities
2508 :type 'boolean)
2510 (defcustom org-highest-priority ?A
2511 "The highest priority of TODO items. A character like ?A, ?B etc.
2512 Must have a smaller ASCII number than `org-lowest-priority'."
2513 :group 'org-priorities
2514 :type 'character)
2516 (defcustom org-lowest-priority ?C
2517 "The lowest priority of TODO items. A character like ?A, ?B etc.
2518 Must have a larger ASCII number than `org-highest-priority'."
2519 :group 'org-priorities
2520 :type 'character)
2522 (defcustom org-default-priority ?B
2523 "The default priority of TODO items.
2524 This is the priority an item gets if no explicit priority is given.
2525 When starting to cycle on an empty priority the first step in the cycle
2526 depends on `org-priority-start-cycle-with-default'. The resulting first
2527 step priority must not exceed the range from `org-highest-priority' to
2528 `org-lowest-priority' which means that `org-default-priority' has to be
2529 in this range exclusive or inclusive the range boundaries. Else the
2530 first step refuses to set the default and the second will fall back
2531 to (depending on the command used) the highest or lowest priority."
2532 :group 'org-priorities
2533 :type 'character)
2535 (defcustom org-priority-start-cycle-with-default t
2536 "Non-nil means start with default priority when starting to cycle.
2537 When this is nil, the first step in the cycle will be (depending on the
2538 command used) one higher or lower than the default priority.
2539 See also `org-default-priority'."
2540 :group 'org-priorities
2541 :type 'boolean)
2543 (defcustom org-get-priority-function nil
2544 "Function to extract the priority from a string.
2545 The string is normally the headline. If this is nil Org computes the
2546 priority from the priority cookie like [#A] in the headline. It returns
2547 an integer, increasing by 1000 for each priority level.
2548 The user can set a different function here, which should take a string
2549 as an argument and return the numeric priority."
2550 :group 'org-priorities
2551 :type 'function)
2553 (defgroup org-time nil
2554 "Options concerning time stamps and deadlines in Org-mode."
2555 :tag "Org Time"
2556 :group 'org)
2558 (defcustom org-insert-labeled-timestamps-at-point nil
2559 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2560 When nil, these labeled time stamps are forces into the second line of an
2561 entry, just after the headline. When scheduling from the global TODO list,
2562 the time stamp will always be forced into the second line."
2563 :group 'org-time
2564 :type 'boolean)
2566 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2567 "Formats for `format-time-string' which are used for time stamps.
2568 It is not recommended to change this constant.")
2570 (defcustom org-time-stamp-rounding-minutes '(0 5)
2571 "Number of minutes to round time stamps to.
2572 These are two values, the first applies when first creating a time stamp.
2573 The second applies when changing it with the commands `S-up' and `S-down'.
2574 When changing the time stamp, this means that it will change in steps
2575 of N minutes, as given by the second value.
2577 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2578 numbers should be factors of 60, so for example 5, 10, 15.
2580 When this is larger than 1, you can still force an exact time stamp by using
2581 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2582 and by using a prefix arg to `S-up/down' to specify the exact number
2583 of minutes to shift."
2584 :group 'org-time
2585 :get #'(lambda (var) ; Make sure both elements are there
2586 (if (integerp (default-value var))
2587 (list (default-value var) 5)
2588 (default-value var)))
2589 :type '(list
2590 (integer :tag "when inserting times")
2591 (integer :tag "when modifying times")))
2593 ;; Normalize old customizations of this variable.
2594 (when (integerp org-time-stamp-rounding-minutes)
2595 (setq org-time-stamp-rounding-minutes
2596 (list org-time-stamp-rounding-minutes
2597 org-time-stamp-rounding-minutes)))
2599 (defcustom org-display-custom-times nil
2600 "Non-nil means overlay custom formats over all time stamps.
2601 The formats are defined through the variable `org-time-stamp-custom-formats'.
2602 To turn this on on a per-file basis, insert anywhere in the file:
2603 #+STARTUP: customtime"
2604 :group 'org-time
2605 :set 'set-default
2606 :type 'sexp)
2607 (make-variable-buffer-local 'org-display-custom-times)
2609 (defcustom org-time-stamp-custom-formats
2610 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2611 "Custom formats for time stamps. See `format-time-string' for the syntax.
2612 These are overlayed over the default ISO format if the variable
2613 `org-display-custom-times' is set. Time like %H:%M should be at the
2614 end of the second format. The custom formats are also honored by export
2615 commands, if custom time display is turned on at the time of export."
2616 :group 'org-time
2617 :type 'sexp)
2619 (defun org-time-stamp-format (&optional long inactive)
2620 "Get the right format for a time string."
2621 (let ((f (if long (cdr org-time-stamp-formats)
2622 (car org-time-stamp-formats))))
2623 (if inactive
2624 (concat "[" (substring f 1 -1) "]")
2625 f)))
2627 (defcustom org-time-clocksum-format "%d:%02d"
2628 "The format string used when creating CLOCKSUM lines.
2629 This is also used when org-mode generates a time duration."
2630 :group 'org-time
2631 :type 'string)
2633 (defcustom org-time-clocksum-use-fractional nil
2634 "If non-nil, \\[org-clock-display] uses fractional times.
2635 org-mode generates a time duration."
2636 :group 'org-time
2637 :type 'boolean)
2639 (defcustom org-time-clocksum-fractional-format "%.2f"
2640 "The format string used when creating CLOCKSUM lines, or when
2641 org-mode generates a time duration."
2642 :group 'org-time
2643 :type 'string)
2645 (defcustom org-deadline-warning-days 14
2646 "No. of days before expiration during which a deadline becomes active.
2647 This variable governs the display in sparse trees and in the agenda.
2648 When 0 or negative, it means use this number (the absolute value of it)
2649 even if a deadline has a different individual lead time specified.
2651 Custom commands can set this variable in the options section."
2652 :group 'org-time
2653 :group 'org-agenda-daily/weekly
2654 :type 'integer)
2656 (defcustom org-read-date-prefer-future t
2657 "Non-nil means assume future for incomplete date input from user.
2658 This affects the following situations:
2659 1. The user gives a month but not a year.
2660 For example, if it is April and you enter \"feb 2\", this will be read
2661 as Feb 2, *next* year. \"May 5\", however, will be this year.
2662 2. The user gives a day, but no month.
2663 For example, if today is the 15th, and you enter \"3\", Org-mode will
2664 read this as the third of *next* month. However, if you enter \"17\",
2665 it will be considered as *this* month.
2667 If you set this variable to the symbol `time', then also the following
2668 will work:
2670 3. If the user gives a time, but no day. If the time is before now,
2671 to will be interpreted as tomorrow.
2673 Currently none of this works for ISO week specifications.
2675 When this option is nil, the current day, month and year will always be
2676 used as defaults.
2678 See also `org-agenda-jump-prefer-future'."
2679 :group 'org-time
2680 :type '(choice
2681 (const :tag "Never" nil)
2682 (const :tag "Check month and day" t)
2683 (const :tag "Check month, day, and time" time)))
2685 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2686 "Should the agenda jump command prefer the future for incomplete dates?
2687 The default is to do the same as configured in `org-read-date-prefer-future'.
2688 But you can also set a deviating value here.
2689 This may t or nil, or the symbol `org-read-date-prefer-future'."
2690 :group 'org-agenda
2691 :group 'org-time
2692 :type '(choice
2693 (const :tag "Use org-read-date-prefer-future"
2694 org-read-date-prefer-future)
2695 (const :tag "Never" nil)
2696 (const :tag "Always" t)))
2698 (defcustom org-read-date-force-compatible-dates t
2699 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2701 Depending on the system Emacs is running on, certain dates cannot
2702 be represented with the type used internally to represent time.
2703 Dates between 1970-1-1 and 2038-1-1 can always be represented
2704 correctly. Some systems allow for earlier dates, some for later,
2705 some for both. One way to find out it to insert any date into an
2706 Org buffer, putting the cursor on the year and hitting S-up and
2707 S-down to test the range.
2709 When this variable is set to t, the date/time prompt will not let
2710 you specify dates outside the 1970-2037 range, so it is certain that
2711 these dates will work in whatever version of Emacs you are
2712 running, and also that you can move a file from one Emacs implementation
2713 to another. WHenever Org is forcing the year for you, it will display
2714 a message and beep.
2716 When this variable is nil, Org will check if the date is
2717 representable in the specific Emacs implementation you are using.
2718 If not, it will force a year, usually the current year, and beep
2719 to remind you. Currently this setting is not recommended because
2720 the likelihood that you will open your Org files in an Emacs that
2721 has limited date range is not negligible.
2723 A workaround for this problem is to use diary sexp dates for time
2724 stamps outside of this range."
2725 :group 'org-time
2726 :type 'boolean)
2728 (defcustom org-read-date-display-live t
2729 "Non-nil means display current interpretation of date prompt live.
2730 This display will be in an overlay, in the minibuffer."
2731 :group 'org-time
2732 :type 'boolean)
2734 (defcustom org-read-date-popup-calendar t
2735 "Non-nil means pop up a calendar when prompting for a date.
2736 In the calendar, the date can be selected with mouse-1. However, the
2737 minibuffer will also be active, and you can simply enter the date as well.
2738 When nil, only the minibuffer will be available."
2739 :group 'org-time
2740 :type 'boolean)
2741 (if (fboundp 'defvaralias)
2742 (defvaralias 'org-popup-calendar-for-date-prompt
2743 'org-read-date-popup-calendar))
2745 (defcustom org-read-date-minibuffer-setup-hook nil
2746 "Hook to be used to set up keys for the date/time interface.
2747 Add key definitions to `minibuffer-local-map', which will be a temporary
2748 copy."
2749 :group 'org-time
2750 :type 'hook)
2752 (defcustom org-extend-today-until 0
2753 "The hour when your day really ends. Must be an integer.
2754 This has influence for the following applications:
2755 - When switching the agenda to \"today\". It it is still earlier than
2756 the time given here, the day recognized as TODAY is actually yesterday.
2757 - When a date is read from the user and it is still before the time given
2758 here, the current date and time will be assumed to be yesterday, 23:59.
2759 Also, timestamps inserted in remember templates follow this rule.
2761 IMPORTANT: This is a feature whose implementation is and likely will
2762 remain incomplete. Really, it is only here because past midnight seems to
2763 be the favorite working time of John Wiegley :-)"
2764 :group 'org-time
2765 :type 'integer)
2767 (defcustom org-use-effective-time nil
2768 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2769 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2770 \"effective time\" of any timestamps between midnight and 8am will be
2771 23:59 of the previous day."
2772 :group 'boolean
2773 :type 'integer)
2775 (defcustom org-edit-timestamp-down-means-later nil
2776 "Non-nil means S-down will increase the time in a time stamp.
2777 When nil, S-up will increase."
2778 :group 'org-time
2779 :type 'boolean)
2781 (defcustom org-calendar-follow-timestamp-change t
2782 "Non-nil means make the calendar window follow timestamp changes.
2783 When a timestamp is modified and the calendar window is visible, it will be
2784 moved to the new date."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defgroup org-tags nil
2789 "Options concerning tags in Org-mode."
2790 :tag "Org Tags"
2791 :group 'org)
2793 (defcustom org-tag-alist nil
2794 "List of tags allowed in Org-mode files.
2795 When this list is nil, Org-mode will base TAG input on what is already in the
2796 buffer.
2797 The value of this variable is an alist, the car of each entry must be a
2798 keyword as a string, the cdr may be a character that is used to select
2799 that tag through the fast-tag-selection interface.
2800 See the manual for details."
2801 :group 'org-tags
2802 :type '(repeat
2803 (choice
2804 (cons (string :tag "Tag name")
2805 (character :tag "Access char"))
2806 (list :tag "Start radio group"
2807 (const :startgroup)
2808 (option (string :tag "Group description")))
2809 (list :tag "End radio group"
2810 (const :endgroup)
2811 (option (string :tag "Group description")))
2812 (const :tag "New line" (:newline)))))
2814 (defcustom org-tag-persistent-alist nil
2815 "List of tags that will always appear in all Org-mode files.
2816 This is in addition to any in buffer settings or customizations
2817 of `org-tag-alist'.
2818 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2819 The value of this variable is an alist, the car of each entry must be a
2820 keyword as a string, the cdr may be a character that is used to select
2821 that tag through the fast-tag-selection interface.
2822 See the manual for details.
2823 To disable these tags on a per-file basis, insert anywhere in the file:
2824 #+STARTUP: noptag"
2825 :group 'org-tags
2826 :type '(repeat
2827 (choice
2828 (cons (string :tag "Tag name")
2829 (character :tag "Access char"))
2830 (const :tag "Start radio group" (:startgroup))
2831 (const :tag "End radio group" (:endgroup))
2832 (const :tag "New line" (:newline)))))
2834 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2835 "If non-nil, always offer completion for all tags of all agenda files.
2836 Instead of customizing this variable directly, you might want to
2837 set it locally for capture buffers, because there no list of
2838 tags in that file can be created dynamically (there are none).
2840 (add-hook 'org-capture-mode-hook
2841 (lambda ()
2842 (set (make-local-variable
2843 'org-complete-tags-always-offer-all-agenda-tags)
2844 t)))"
2845 :group 'org-tags
2846 :type 'boolean)
2848 (defvar org-file-tags nil
2849 "List of tags that can be inherited by all entries in the file.
2850 The tags will be inherited if the variable `org-use-tag-inheritance'
2851 says they should be.
2852 This variable is populated from #+FILETAGS lines.")
2854 (defcustom org-use-fast-tag-selection 'auto
2855 "Non-nil means use fast tag selection scheme.
2856 This is a special interface to select and deselect tags with single keys.
2857 When nil, fast selection is never used.
2858 When the symbol `auto', fast selection is used if and only if selection
2859 characters for tags have been configured, either through the variable
2860 `org-tag-alist' or through a #+TAGS line in the buffer.
2861 When t, fast selection is always used and selection keys are assigned
2862 automatically if necessary."
2863 :group 'org-tags
2864 :type '(choice
2865 (const :tag "Always" t)
2866 (const :tag "Never" nil)
2867 (const :tag "When selection characters are configured" 'auto)))
2869 (defcustom org-fast-tag-selection-single-key nil
2870 "Non-nil means fast tag selection exits after first change.
2871 When nil, you have to press RET to exit it.
2872 During fast tag selection, you can toggle this flag with `C-c'.
2873 This variable can also have the value `expert'. In this case, the window
2874 displaying the tags menu is not even shown, until you press C-c again."
2875 :group 'org-tags
2876 :type '(choice
2877 (const :tag "No" nil)
2878 (const :tag "Yes" t)
2879 (const :tag "Expert" expert)))
2881 (defvar org-fast-tag-selection-include-todo nil
2882 "Non-nil means fast tags selection interface will also offer TODO states.
2883 This is an undocumented feature, you should not rely on it.")
2885 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2886 "The column to which tags should be indented in a headline.
2887 If this number is positive, it specifies the column. If it is negative,
2888 it means that the tags should be flushright to that column. For example,
2889 -80 works well for a normal 80 character screen.
2890 When 0, place tags directly after headline text, with only one space in
2891 between."
2892 :group 'org-tags
2893 :type 'integer)
2895 (defcustom org-auto-align-tags t
2896 "Non-nil keeps tags aligned when modifying headlines.
2897 Some operations (i.e. demoting) change the length of a headline and
2898 therefore shift the tags around. With this option turned on, after
2899 each such operation the tags are again aligned to `org-tags-column'."
2900 :group 'org-tags
2901 :type 'boolean)
2903 (defcustom org-use-tag-inheritance t
2904 "Non-nil means tags in levels apply also for sublevels.
2905 When nil, only the tags directly given in a specific line apply there.
2906 This may also be a list of tags that should be inherited, or a regexp that
2907 matches tags that should be inherited. Additional control is possible
2908 with the variable `org-tags-exclude-from-inheritance' which gives an
2909 explicit list of tags to be excluded from inheritance., even if the value of
2910 `org-use-tag-inheritance' would select it for inheritance.
2912 If this option is t, a match early-on in a tree can lead to a large
2913 number of matches in the subtree when constructing the agenda or creating
2914 a sparse tree. If you only want to see the first match in a tree during
2915 a search, check out the variable `org-tags-match-list-sublevels'."
2916 :group 'org-tags
2917 :type '(choice
2918 (const :tag "Not" nil)
2919 (const :tag "Always" t)
2920 (repeat :tag "Specific tags" (string :tag "Tag"))
2921 (regexp :tag "Tags matched by regexp")))
2923 (defcustom org-tags-exclude-from-inheritance nil
2924 "List of tags that should never be inherited.
2925 This is a way to exclude a few tags from inheritance. For way to do
2926 the opposite, to actively allow inheritance for selected tags,
2927 see the variable `org-use-tag-inheritance'."
2928 :group 'org-tags
2929 :type '(repeat (string :tag "Tag")))
2931 (defun org-tag-inherit-p (tag)
2932 "Check if TAG is one that should be inherited."
2933 (cond
2934 ((member tag org-tags-exclude-from-inheritance) nil)
2935 ((eq org-use-tag-inheritance t) t)
2936 ((not org-use-tag-inheritance) nil)
2937 ((stringp org-use-tag-inheritance)
2938 (string-match org-use-tag-inheritance tag))
2939 ((listp org-use-tag-inheritance)
2940 (member tag org-use-tag-inheritance))
2941 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2943 (defcustom org-tags-match-list-sublevels t
2944 "Non-nil means list also sublevels of headlines matching a search.
2945 This variable applies to tags/property searches, and also to stuck
2946 projects because this search is based on a tags match as well.
2948 When set to the symbol `indented', sublevels are indented with
2949 leading dots.
2951 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2952 the sublevels of a headline matching a tag search often also match
2953 the same search. Listing all of them can create very long lists.
2954 Setting this variable to nil causes subtrees of a match to be skipped.
2956 This variable is semi-obsolete and probably should always be true. It
2957 is better to limit inheritance to certain tags using the variables
2958 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2959 :group 'org-tags
2960 :type '(choice
2961 (const :tag "No, don't list them" nil)
2962 (const :tag "Yes, do list them" t)
2963 (const :tag "List them, indented with leading dots" indented)))
2965 (defcustom org-tags-sort-function nil
2966 "When set, tags are sorted using this function as a comparator."
2967 :group 'org-tags
2968 :type '(choice
2969 (const :tag "No sorting" nil)
2970 (const :tag "Alphabetical" string<)
2971 (const :tag "Reverse alphabetical" string>)
2972 (function :tag "Custom function" nil)))
2974 (defvar org-tags-history nil
2975 "History of minibuffer reads for tags.")
2976 (defvar org-last-tags-completion-table nil
2977 "The last used completion table for tags.")
2978 (defvar org-after-tags-change-hook nil
2979 "Hook that is run after the tags in a line have changed.")
2981 (defgroup org-properties nil
2982 "Options concerning properties in Org-mode."
2983 :tag "Org Properties"
2984 :group 'org)
2986 (defcustom org-property-format "%-10s %s"
2987 "How property key/value pairs should be formatted by `indent-line'.
2988 When `indent-line' hits a property definition, it will format the line
2989 according to this format, mainly to make sure that the values are
2990 lined-up with respect to each other."
2991 :group 'org-properties
2992 :type 'string)
2994 (defcustom org-properties-postprocess-alist nil
2995 "Alist of properties and functions to adjust inserted values.
2996 Elements of this alist must be of the form
2998 ([string] [function])
3000 where [string] must be a property name and [function] must be a
3001 lambda expression: this lambda expression must take one argument,
3002 the value to adjust, and return the new value as a string.
3004 For example, this element will allow the property \"Remaining\"
3005 to be updated wrt the relation between the \"Effort\" property
3006 and the clock summary:
3008 ((\"Remaining\" (lambda(value)
3009 (let ((clocksum (org-clock-sum-current-item))
3010 (effort (org-duration-string-to-minutes
3011 (org-entry-get (point) \"Effort\"))))
3012 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3013 :group 'org-properties
3014 :type 'alist)
3016 (defcustom org-use-property-inheritance nil
3017 "Non-nil means properties apply also for sublevels.
3019 This setting is chiefly used during property searches. Turning it on can
3020 cause significant overhead when doing a search, which is why it is not
3021 on by default.
3023 When nil, only the properties directly given in the current entry count.
3024 When t, every property is inherited. The value may also be a list of
3025 properties that should have inheritance, or a regular expression matching
3026 properties that should be inherited.
3028 However, note that some special properties use inheritance under special
3029 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3030 and the properties ending in \"_ALL\" when they are used as descriptor
3031 for valid values of a property.
3033 Note for programmers:
3034 When querying an entry with `org-entry-get', you can control if inheritance
3035 should be used. By default, `org-entry-get' looks only at the local
3036 properties. You can request inheritance by setting the inherit argument
3037 to t (to force inheritance) or to `selective' (to respect the setting
3038 in this variable)."
3039 :group 'org-properties
3040 :type '(choice
3041 (const :tag "Not" nil)
3042 (const :tag "Always" t)
3043 (repeat :tag "Specific properties" (string :tag "Property"))
3044 (regexp :tag "Properties matched by regexp")))
3046 (defun org-property-inherit-p (property)
3047 "Check if PROPERTY is one that should be inherited."
3048 (cond
3049 ((eq org-use-property-inheritance t) t)
3050 ((not org-use-property-inheritance) nil)
3051 ((stringp org-use-property-inheritance)
3052 (string-match org-use-property-inheritance property))
3053 ((listp org-use-property-inheritance)
3054 (member property org-use-property-inheritance))
3055 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3057 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3058 "The default column format, if no other format has been defined.
3059 This variable can be set on the per-file basis by inserting a line
3061 #+COLUMNS: %25ITEM ....."
3062 :group 'org-properties
3063 :type 'string)
3065 (defcustom org-columns-ellipses ".."
3066 "The ellipses to be used when a field in column view is truncated.
3067 When this is the empty string, as many characters as possible are shown,
3068 but then there will be no visual indication that the field has been truncated.
3069 When this is a string of length N, the last N characters of a truncated
3070 field are replaced by this string. If the column is narrower than the
3071 ellipses string, only part of the ellipses string will be shown."
3072 :group 'org-properties
3073 :type 'string)
3075 (defcustom org-columns-modify-value-for-display-function nil
3076 "Function that modifies values for display in column view.
3077 For example, it can be used to cut out a certain part from a time stamp.
3078 The function must take 2 arguments:
3080 column-title The title of the column (*not* the property name)
3081 value The value that should be modified.
3083 The function should return the value that should be displayed,
3084 or nil if the normal value should be used."
3085 :group 'org-properties
3086 :type 'function)
3088 (defcustom org-effort-property "Effort"
3089 "The property that is being used to keep track of effort estimates.
3090 Effort estimates given in this property need to have the format H:MM."
3091 :group 'org-properties
3092 :group 'org-progress
3093 :type '(string :tag "Property"))
3095 (defconst org-global-properties-fixed
3096 '(("VISIBILITY_ALL" . "folded children content all")
3097 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3098 "List of property/value pairs that can be inherited by any entry.
3100 These are fixed values, for the preset properties. The user variable
3101 that can be used to add to this list is `org-global-properties'.
3103 The entries in this list are cons cells where the car is a property
3104 name and cdr is a string with the value. If the value represents
3105 multiple items like an \"_ALL\" property, separate the items by
3106 spaces.")
3108 (defcustom org-global-properties nil
3109 "List of property/value pairs that can be inherited by any entry.
3111 This list will be combined with the constant `org-global-properties-fixed'.
3113 The entries in this list are cons cells where the car is a property
3114 name and cdr is a string with the value.
3116 You can set buffer-local values for the same purpose in the variable
3117 `org-file-properties' this by adding lines like
3119 #+PROPERTY: NAME VALUE"
3120 :group 'org-properties
3121 :type '(repeat
3122 (cons (string :tag "Property")
3123 (string :tag "Value"))))
3125 (defvar org-file-properties nil
3126 "List of property/value pairs that can be inherited by any entry.
3127 Valid for the current buffer.
3128 This variable is populated from #+PROPERTY lines.")
3129 (make-variable-buffer-local 'org-file-properties)
3131 (defgroup org-agenda nil
3132 "Options concerning agenda views in Org-mode."
3133 :tag "Org Agenda"
3134 :group 'org)
3136 (defvar org-category nil
3137 "Variable used by org files to set a category for agenda display.
3138 Such files should use a file variable to set it, for example
3140 # -*- mode: org; org-category: \"ELisp\"
3142 or contain a special line
3144 #+CATEGORY: ELisp
3146 If the file does not specify a category, then file's base name
3147 is used instead.")
3148 (make-variable-buffer-local 'org-category)
3149 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3151 (defcustom org-agenda-files nil
3152 "The files to be used for agenda display.
3153 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3154 \\[org-remove-file]. You can also use customize to edit the list.
3156 If an entry is a directory, all files in that directory that are matched by
3157 `org-agenda-file-regexp' will be part of the file list.
3159 If the value of the variable is not a list but a single file name, then
3160 the list of agenda files is actually stored and maintained in that file, one
3161 agenda file per line. In this file paths can be given relative to
3162 `org-directory'. Tilde expansion and environment variable substitution
3163 are also made."
3164 :group 'org-agenda
3165 :type '(choice
3166 (repeat :tag "List of files and directories" file)
3167 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3169 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3170 "Regular expression to match files for `org-agenda-files'.
3171 If any element in the list in that variable contains a directory instead
3172 of a normal file, all files in that directory that are matched by this
3173 regular expression will be included."
3174 :group 'org-agenda
3175 :type 'regexp)
3177 (defcustom org-agenda-text-search-extra-files nil
3178 "List of extra files to be searched by text search commands.
3179 These files will be search in addition to the agenda files by the
3180 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3181 Note that these files will only be searched for text search commands,
3182 not for the other agenda views like todo lists, tag searches or the weekly
3183 agenda. This variable is intended to list notes and possibly archive files
3184 that should also be searched by these two commands.
3185 In fact, if the first element in the list is the symbol `agenda-archives',
3186 than all archive files of all agenda files will be added to the search
3187 scope."
3188 :group 'org-agenda
3189 :type '(set :greedy t
3190 (const :tag "Agenda Archives" agenda-archives)
3191 (repeat :inline t (file))))
3193 (if (fboundp 'defvaralias)
3194 (defvaralias 'org-agenda-multi-occur-extra-files
3195 'org-agenda-text-search-extra-files))
3197 (defcustom org-agenda-skip-unavailable-files nil
3198 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3199 A nil value means to remove them, after a query, from the list."
3200 :group 'org-agenda
3201 :type 'boolean)
3203 (defcustom org-calendar-to-agenda-key [?c]
3204 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3205 The command `org-calendar-goto-agenda' will be bound to this key. The
3206 default is the character `c' because then `c' can be used to switch back and
3207 forth between agenda and calendar."
3208 :group 'org-agenda
3209 :type 'sexp)
3211 (defcustom org-calendar-agenda-action-key [?k]
3212 "The key to be installed in `calendar-mode-map' for agenda-action.
3213 The command `org-agenda-action' will be bound to this key. The
3214 default is the character `k' because we use the same key in the agenda."
3215 :group 'org-agenda
3216 :type 'sexp)
3218 (defcustom org-calendar-insert-diary-entry-key [?i]
3219 "The key to be installed in `calendar-mode-map' for adding diary entries.
3220 This option is irrelevant until `org-agenda-diary-file' has been configured
3221 to point to an Org-mode file. When that is the case, the command
3222 `org-agenda-diary-entry' will be bound to the key given here, by default
3223 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3224 if you want to continue doing this, you need to change this to a different
3225 key."
3226 :group 'org-agenda
3227 :type 'sexp)
3229 (defcustom org-agenda-diary-file 'diary-file
3230 "File to which to add new entries with the `i' key in agenda and calendar.
3231 When this is the symbol `diary-file', the functionality in the Emacs
3232 calendar will be used to add entries to the `diary-file'. But when this
3233 points to a file, `org-agenda-diary-entry' will be used instead."
3234 :group 'org-agenda
3235 :type '(choice
3236 (const :tag "The standard Emacs diary file" diary-file)
3237 (file :tag "Special Org file diary entries")))
3239 (eval-after-load "calendar"
3240 '(progn
3241 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3242 'org-calendar-goto-agenda)
3243 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3244 'org-agenda-action)
3245 (add-hook 'calendar-mode-hook
3246 (lambda ()
3247 (unless (eq org-agenda-diary-file 'diary-file)
3248 (define-key calendar-mode-map
3249 org-calendar-insert-diary-entry-key
3250 'org-agenda-diary-entry))))))
3252 (defgroup org-latex nil
3253 "Options for embedding LaTeX code into Org-mode."
3254 :tag "Org LaTeX"
3255 :group 'org)
3257 (defcustom org-format-latex-options
3258 '(:foreground default :background default :scale 1.0
3259 :html-foreground "Black" :html-background "Transparent"
3260 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3261 "Options for creating images from LaTeX fragments.
3262 This is a property list with the following properties:
3263 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3264 `default' means use the foreground of the default face.
3265 :background the background color, or \"Transparent\".
3266 `default' means use the background of the default face.
3267 :scale a scaling factor for the size of the images, to get more pixels
3268 :html-foreground, :html-background, :html-scale
3269 the same numbers for HTML export.
3270 :matchers a list indicating which matchers should be used to
3271 find LaTeX fragments. Valid members of this list are:
3272 \"begin\" find environments
3273 \"$1\" find single characters surrounded by $.$
3274 \"$\" find math expressions surrounded by $...$
3275 \"$$\" find math expressions surrounded by $$....$$
3276 \"\\(\" find math expressions surrounded by \\(...\\)
3277 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3278 :group 'org-latex
3279 :type 'plist)
3281 (defcustom org-format-latex-signal-error t
3282 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3283 When nil, just push out a message."
3284 :group 'org-latex
3285 :type 'boolean)
3286 (defcustom org-latex-to-mathml-jar-file nil
3287 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3288 Use this to specify additional executable file say a jar file.
3290 When using MathToWeb as the converter, specify the full-path to
3291 your mathtoweb.jar file."
3292 :group 'org-latex
3293 :type '(choice
3294 (const :tag "None" nil)
3295 (file :tag "JAR file" :must-match t)))
3297 (defcustom org-latex-to-mathml-convert-command nil
3298 "Command to convert LaTeX fragments to MathML.
3299 Replace format-specifiers in the command as noted below and use
3300 `shell-command' to convert LaTeX to MathML.
3301 %j: Executable file in fully expanded form as specified by
3302 `org-latex-to-mathml-jar-file'.
3303 %I: Input LaTeX file in fully expanded form
3304 %o: Output MathML file
3305 This command is used by `org-create-math-formula'.
3307 When using MathToWeb as the converter, set this to
3308 \"java -jar %j -unicode -force -df %o %I\"."
3309 :group 'org-latex
3310 :type '(choice
3311 (const :tag "None" nil)
3312 (string :tag "\nShell command")))
3314 (defun org-format-latex-mathml-available-p ()
3315 "Return t if `org-latex-to-mathml-convert-command' is usable."
3316 (save-match-data
3317 (when (and (boundp 'org-latex-to-mathml-convert-command)
3318 org-latex-to-mathml-convert-command)
3319 (let ((executable (car (split-string
3320 org-latex-to-mathml-convert-command))))
3321 (when (executable-find executable)
3322 (if (string-match
3323 "%j" org-latex-to-mathml-convert-command)
3324 (file-readable-p org-latex-to-mathml-jar-file)
3325 t))))))
3327 (defcustom org-format-latex-header "\\documentclass{article}
3328 \\usepackage[usenames]{color}
3329 \\usepackage{amsmath}
3330 \\usepackage[mathscr]{eucal}
3331 \\pagestyle{empty} % do not remove
3332 \[PACKAGES]
3333 \[DEFAULT-PACKAGES]
3334 % The settings below are copied from fullpage.sty
3335 \\setlength{\\textwidth}{\\paperwidth}
3336 \\addtolength{\\textwidth}{-3cm}
3337 \\setlength{\\oddsidemargin}{1.5cm}
3338 \\addtolength{\\oddsidemargin}{-2.54cm}
3339 \\setlength{\\evensidemargin}{\\oddsidemargin}
3340 \\setlength{\\textheight}{\\paperheight}
3341 \\addtolength{\\textheight}{-\\headheight}
3342 \\addtolength{\\textheight}{-\\headsep}
3343 \\addtolength{\\textheight}{-\\footskip}
3344 \\addtolength{\\textheight}{-3cm}
3345 \\setlength{\\topmargin}{1.5cm}
3346 \\addtolength{\\topmargin}{-2.54cm}"
3347 "The document header used for processing LaTeX fragments.
3348 It is imperative that this header make sure that no page number
3349 appears on the page. The package defined in the variables
3350 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3351 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3352 will be appended."
3353 :group 'org-latex
3354 :type 'string)
3356 (defvar org-format-latex-header-extra nil)
3358 (defun org-set-packages-alist (var val)
3359 "Set the packages alist and make sure it has 3 elements per entry."
3360 (set var (mapcar (lambda (x)
3361 (if (and (consp x) (= (length x) 2))
3362 (list (car x) (nth 1 x) t)
3364 val)))
3366 (defun org-get-packages-alist (var)
3368 "Get the packages alist and make sure it has 3 elements per entry."
3369 (mapcar (lambda (x)
3370 (if (and (consp x) (= (length x) 2))
3371 (list (car x) (nth 1 x) t)
3373 (default-value var)))
3375 ;; The following variables are defined here because is it also used
3376 ;; when formatting latex fragments. Originally it was part of the
3377 ;; LaTeX exporter, which is why the name includes "export".
3378 (defcustom org-export-latex-default-packages-alist
3379 '(("AUTO" "inputenc" t)
3380 ("T1" "fontenc" t)
3381 ("" "fixltx2e" nil)
3382 ("" "graphicx" t)
3383 ("" "longtable" nil)
3384 ("" "float" nil)
3385 ("" "wrapfig" nil)
3386 ("" "soul" t)
3387 ("" "textcomp" t)
3388 ("" "marvosym" t)
3389 ("" "wasysym" t)
3390 ("" "latexsym" t)
3391 ("" "amssymb" t)
3392 ("" "hyperref" nil)
3393 "\\tolerance=1000"
3395 "Alist of default packages to be inserted in the header.
3396 Change this only if one of the packages here causes an incompatibility
3397 with another package you are using.
3398 The packages in this list are needed by one part or another of Org-mode
3399 to function properly.
3401 - inputenc, fontenc: for basic font and character selection
3402 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3403 for interpreting the entities in `org-entities'. You can skip some of these
3404 packages if you don't use any of the symbols in it.
3405 - graphicx: for including images
3406 - float, wrapfig: for figure placement
3407 - longtable: for long tables
3408 - hyperref: for cross references
3410 Therefore you should not modify this variable unless you know what you
3411 are doing. The one reason to change it anyway is that you might be loading
3412 some other package that conflicts with one of the default packages.
3413 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3414 If SNIPPET-FLAG is t, the package also needs to be included when
3415 compiling LaTeX snippets into images for inclusion into HTML."
3416 :group 'org-export-latex
3417 :set 'org-set-packages-alist
3418 :get 'org-get-packages-alist
3419 :type '(repeat
3420 (choice
3421 (list :tag "options/package pair"
3422 (string :tag "options")
3423 (string :tag "package")
3424 (boolean :tag "Snippet"))
3425 (string :tag "A line of LaTeX"))))
3427 (defcustom org-export-latex-packages-alist nil
3428 "Alist of packages to be inserted in every LaTeX header.
3429 These will be inserted after `org-export-latex-default-packages-alist'.
3430 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3431 SNIPPET-FLAG, when t, indicates that this package is also needed when
3432 turning LaTeX snippets into images for inclusion into HTML.
3433 Make sure that you only list packages here which:
3434 - you want in every file
3435 - do not conflict with the default packages in
3436 `org-export-latex-default-packages-alist'
3437 - do not conflict with the setup in `org-format-latex-header'."
3438 :group 'org-export-latex
3439 :set 'org-set-packages-alist
3440 :get 'org-get-packages-alist
3441 :type '(repeat
3442 (choice
3443 (list :tag "options/package pair"
3444 (string :tag "options")
3445 (string :tag "package")
3446 (boolean :tag "Snippet"))
3447 (string :tag "A line of LaTeX"))))
3450 (defgroup org-appearance nil
3451 "Settings for Org-mode appearance."
3452 :tag "Org Appearance"
3453 :group 'org)
3455 (defcustom org-level-color-stars-only nil
3456 "Non-nil means fontify only the stars in each headline.
3457 When nil, the entire headline is fontified.
3458 Changing it requires restart of `font-lock-mode' to become effective
3459 also in regions already fontified."
3460 :group 'org-appearance
3461 :type 'boolean)
3463 (defcustom org-hide-leading-stars nil
3464 "Non-nil means hide the first N-1 stars in a headline.
3465 This works by using the face `org-hide' for these stars. This
3466 face is white for a light background, and black for a dark
3467 background. You may have to customize the face `org-hide' to
3468 make this work.
3469 Changing it requires restart of `font-lock-mode' to become effective
3470 also in regions already fontified.
3471 You may also set this on a per-file basis by adding one of the following
3472 lines to the buffer:
3474 #+STARTUP: hidestars
3475 #+STARTUP: showstars"
3476 :group 'org-appearance
3477 :type 'boolean)
3479 (defcustom org-hidden-keywords nil
3480 "List of symbols corresponding to keywords to be hidden the org buffer.
3481 For example, a value '(title) for this list will make the document's title
3482 appear in the buffer without the initial #+TITLE: keyword."
3483 :group 'org-appearance
3484 :type '(set (const :tag "#+AUTHOR" author)
3485 (const :tag "#+DATE" date)
3486 (const :tag "#+EMAIL" email)
3487 (const :tag "#+TITLE" title)))
3489 (defcustom org-fontify-done-headline nil
3490 "Non-nil means change the face of a headline if it is marked DONE.
3491 Normally, only the TODO/DONE keyword indicates the state of a headline.
3492 When this is non-nil, the headline after the keyword is set to the
3493 `org-headline-done' as an additional indication."
3494 :group 'org-appearance
3495 :type 'boolean)
3497 (defcustom org-fontify-emphasized-text t
3498 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3499 Changing this variable requires a restart of Emacs to take effect."
3500 :group 'org-appearance
3501 :type 'boolean)
3503 (defcustom org-fontify-whole-heading-line nil
3504 "Non-nil means fontify the whole line for headings.
3505 This is useful when setting a background color for the
3506 org-level-* faces."
3507 :group 'org-appearance
3508 :type 'boolean)
3510 (defcustom org-highlight-latex-fragments-and-specials nil
3511 "Non-nil means fontify what is treated specially by the exporters."
3512 :group 'org-appearance
3513 :type 'boolean)
3515 (defcustom org-hide-emphasis-markers nil
3516 "Non-nil mean font-lock should hide the emphasis marker characters."
3517 :group 'org-appearance
3518 :type 'boolean)
3520 (defcustom org-pretty-entities nil
3521 "Non-nil means show entities as UTF8 characters.
3522 When nil, the \\name form remains in the buffer."
3523 :group 'org-appearance
3524 :type 'boolean)
3526 (defcustom org-pretty-entities-include-sub-superscripts t
3527 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3528 :group 'org-appearance
3529 :type 'boolean)
3531 (defvar org-emph-re nil
3532 "Regular expression for matching emphasis.
3533 After a match, the match groups contain these elements:
3534 0 The match of the full regular expression, including the characters
3535 before and after the proper match
3536 1 The character before the proper match, or empty at beginning of line
3537 2 The proper match, including the leading and trailing markers
3538 3 The leading marker like * or /, indicating the type of highlighting
3539 4 The text between the emphasis markers, not including the markers
3540 5 The character after the match, empty at the end of a line")
3541 (defvar org-verbatim-re nil
3542 "Regular expression for matching verbatim text.")
3543 (defvar org-emphasis-regexp-components) ; defined just below
3544 (defvar org-emphasis-alist) ; defined just below
3545 (defun org-set-emph-re (var val)
3546 "Set variable and compute the emphasis regular expression."
3547 (set var val)
3548 (when (and (boundp 'org-emphasis-alist)
3549 (boundp 'org-emphasis-regexp-components)
3550 org-emphasis-alist org-emphasis-regexp-components)
3551 (let* ((e org-emphasis-regexp-components)
3552 (pre (car e))
3553 (post (nth 1 e))
3554 (border (nth 2 e))
3555 (body (nth 3 e))
3556 (nl (nth 4 e))
3557 (body1 (concat body "*?"))
3558 (markers (mapconcat 'car org-emphasis-alist ""))
3559 (vmarkers (mapconcat
3560 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3561 org-emphasis-alist "")))
3562 ;; make sure special characters appear at the right position in the class
3563 (if (string-match "\\^" markers)
3564 (setq markers (concat (replace-match "" t t markers) "^")))
3565 (if (string-match "-" markers)
3566 (setq markers (concat (replace-match "" t t markers) "-")))
3567 (if (string-match "\\^" vmarkers)
3568 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3569 (if (string-match "-" vmarkers)
3570 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3571 (if (> nl 0)
3572 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3573 (int-to-string nl) "\\}")))
3574 ;; Make the regexp
3575 (setq org-emph-re
3576 (concat "\\([" pre "]\\|^\\)"
3577 "\\("
3578 "\\([" markers "]\\)"
3579 "\\("
3580 "[^" border "]\\|"
3581 "[^" border "]"
3582 body1
3583 "[^" border "]"
3584 "\\)"
3585 "\\3\\)"
3586 "\\([" post "]\\|$\\)"))
3587 (setq org-verbatim-re
3588 (concat "\\([" pre "]\\|^\\)"
3589 "\\("
3590 "\\([" vmarkers "]\\)"
3591 "\\("
3592 "[^" border "]\\|"
3593 "[^" border "]"
3594 body1
3595 "[^" border "]"
3596 "\\)"
3597 "\\3\\)"
3598 "\\([" post "]\\|$\\)")))))
3600 (defcustom org-emphasis-regexp-components
3601 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3602 "Components used to build the regular expression for emphasis.
3603 This is a list with five entries. Terminology: In an emphasis string
3604 like \" *strong word* \", we call the initial space PREMATCH, the final
3605 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3606 and \"trong wor\" is the body. The different components in this variable
3607 specify what is allowed/forbidden in each part:
3609 pre Chars allowed as prematch. Beginning of line will be allowed too.
3610 post Chars allowed as postmatch. End of line will be allowed too.
3611 border The chars *forbidden* as border characters.
3612 body-regexp A regexp like \".\" to match a body character. Don't use
3613 non-shy groups here, and don't allow newline here.
3614 newline The maximum number of newlines allowed in an emphasis exp.
3616 Use customize to modify this, or restart Emacs after changing it."
3617 :group 'org-appearance
3618 :set 'org-set-emph-re
3619 :type '(list
3620 (sexp :tag "Allowed chars in pre ")
3621 (sexp :tag "Allowed chars in post ")
3622 (sexp :tag "Forbidden chars in border ")
3623 (sexp :tag "Regexp for body ")
3624 (integer :tag "number of newlines allowed")
3625 (option (boolean :tag "Please ignore this button"))))
3627 (defcustom org-emphasis-alist
3628 `(("*" bold "<b>" "</b>")
3629 ("/" italic "<i>" "</i>")
3630 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3631 ("=" org-code "<code>" "</code>" verbatim)
3632 ("~" org-verbatim "<code>" "</code>" verbatim)
3633 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3634 "<del>" "</del>")
3636 "Special syntax for emphasized text.
3637 Text starting and ending with a special character will be emphasized, for
3638 example *bold*, _underlined_ and /italic/. This variable sets the marker
3639 characters, the face to be used by font-lock for highlighting in Org-mode
3640 Emacs buffers, and the HTML tags to be used for this.
3641 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3642 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3643 Use customize to modify this, or restart Emacs after changing it."
3644 :group 'org-appearance
3645 :set 'org-set-emph-re
3646 :type '(repeat
3647 (list
3648 (string :tag "Marker character")
3649 (choice
3650 (face :tag "Font-lock-face")
3651 (plist :tag "Face property list"))
3652 (string :tag "HTML start tag")
3653 (string :tag "HTML end tag")
3654 (option (const verbatim)))))
3656 (defvar org-protecting-blocks
3657 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3658 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3659 This is needed for font-lock setup.")
3661 ;;; Miscellaneous options
3663 (defgroup org-completion nil
3664 "Completion in Org-mode."
3665 :tag "Org Completion"
3666 :group 'org)
3668 (defcustom org-completion-use-ido nil
3669 "Non-nil means use ido completion wherever possible.
3670 Note that `ido-mode' must be active for this variable to be relevant.
3671 If you decide to turn this variable on, you might well want to turn off
3672 `org-outline-path-complete-in-steps'.
3673 See also `org-completion-use-iswitchb'."
3674 :group 'org-completion
3675 :type 'boolean)
3677 (defcustom org-completion-use-iswitchb nil
3678 "Non-nil means use iswitchb completion wherever possible.
3679 Note that `iswitchb-mode' must be active for this variable to be relevant.
3680 If you decide to turn this variable on, you might well want to turn off
3681 `org-outline-path-complete-in-steps'.
3682 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3683 :group 'org-completion
3684 :type 'boolean)
3686 (defcustom org-completion-fallback-command 'hippie-expand
3687 "The expansion command called by \\[pcomplete] in normal context.
3688 Normal means, no org-mode-specific context."
3689 :group 'org-completion
3690 :type 'function)
3692 ;;; Functions and variables from their packages
3693 ;; Declared here to avoid compiler warnings
3695 ;; XEmacs only
3696 (defvar outline-mode-menu-heading)
3697 (defvar outline-mode-menu-show)
3698 (defvar outline-mode-menu-hide)
3699 (defvar zmacs-regions) ; XEmacs regions
3701 ;; Emacs only
3702 (defvar mark-active)
3704 ;; Various packages
3705 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3706 (declare-function calendar-forward-day "cal-move" (arg))
3707 (declare-function calendar-goto-date "cal-move" (date))
3708 (declare-function calendar-goto-today "cal-move" ())
3709 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3710 (defvar calc-embedded-close-formula)
3711 (defvar calc-embedded-open-formula)
3712 (declare-function cdlatex-tab "ext:cdlatex" ())
3713 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3714 (defvar font-lock-unfontify-region-function)
3715 (declare-function iswitchb-read-buffer "iswitchb"
3716 (prompt &optional default require-match start matches-set))
3717 (defvar iswitchb-temp-buflist)
3718 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3719 (defvar org-agenda-tags-todo-honor-ignore-options)
3720 (declare-function org-agenda-skip "org-agenda" ())
3721 (declare-function
3722 org-format-agenda-item "org-agenda"
3723 (extra txt &optional category tags dotime noprefix remove-re habitp))
3724 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3725 (declare-function org-agenda-change-all-lines "org-agenda"
3726 (newhead hdmarker &optional fixface just-this))
3727 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3728 (declare-function org-agenda-maybe-redo "org-agenda" ())
3729 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3730 (beg end))
3731 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3732 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3733 "org-agenda" (&optional end))
3734 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3735 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3736 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3737 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3738 (declare-function org-indent-mode "org-indent" (&optional arg))
3739 (declare-function parse-time-string "parse-time" (string))
3740 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3741 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3742 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3743 (defvar remember-data-file)
3744 (defvar texmathp-why)
3745 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3746 (declare-function table--at-cell-p "table" (position &optional object at-column))
3748 (defvar w3m-current-url)
3749 (defvar w3m-current-title)
3751 (defvar org-latex-regexps)
3753 ;;; Autoload and prepare some org modules
3755 ;; Some table stuff that needs to be defined here, because it is used
3756 ;; by the functions setting up org-mode or checking for table context.
3758 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3759 "Detect an org-type or table-type table.")
3760 (defconst org-table-line-regexp "^[ \t]*|"
3761 "Detect an org-type table line.")
3762 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3763 "Detect an org-type table line.")
3764 (defconst org-table-hline-regexp "^[ \t]*|-"
3765 "Detect an org-type table hline.")
3766 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3767 "Detect a table-type table hline.")
3768 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3769 "Detect the first line outside a table when searching from within it.
3770 This works for both table types.")
3772 ;; Autoload the functions in org-table.el that are needed by functions here.
3774 (eval-and-compile
3775 (org-autoload "org-table"
3776 '(org-table-align org-table-begin org-table-blank-field
3777 org-table-convert org-table-convert-region org-table-copy-down
3778 org-table-copy-region org-table-create
3779 org-table-create-or-convert-from-region
3780 org-table-create-with-table.el org-table-current-dline
3781 org-table-cut-region org-table-delete-column org-table-edit-field
3782 org-table-edit-formulas org-table-end org-table-eval-formula
3783 org-table-export org-table-field-info
3784 org-table-get-stored-formulas org-table-goto-column
3785 org-table-hline-and-move org-table-import org-table-insert-column
3786 org-table-insert-hline org-table-insert-row org-table-iterate
3787 org-table-justify-field-maybe org-table-kill-row
3788 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3789 org-table-move-column org-table-move-column-left
3790 org-table-move-column-right org-table-move-row
3791 org-table-move-row-down org-table-move-row-up
3792 org-table-next-field org-table-next-row org-table-paste-rectangle
3793 org-table-previous-field org-table-recalculate
3794 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3795 org-table-toggle-coordinate-overlays
3796 org-table-toggle-formula-debugger org-table-wrap-region
3797 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3798 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3799 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3801 (defun org-at-table-p (&optional table-type)
3802 "Return t if the cursor is inside an org-type table.
3803 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3804 (if org-enable-table-editor
3805 (save-excursion
3806 (beginning-of-line 1)
3807 (looking-at (if table-type org-table-any-line-regexp
3808 org-table-line-regexp)))
3809 nil))
3810 (defsubst org-table-p () (org-at-table-p))
3812 (defun org-at-table.el-p ()
3813 "Return t if and only if we are at a table.el table."
3814 (and (org-at-table-p 'any)
3815 (save-excursion
3816 (goto-char (org-table-begin 'any))
3817 (looking-at org-table1-hline-regexp))))
3818 (defun org-table-recognize-table.el ()
3819 "If there is a table.el table nearby, recognize it and move into it."
3820 (if org-table-tab-recognizes-table.el
3821 (if (org-at-table.el-p)
3822 (progn
3823 (beginning-of-line 1)
3824 (if (looking-at org-table-dataline-regexp)
3826 (if (looking-at org-table1-hline-regexp)
3827 (progn
3828 (beginning-of-line 2)
3829 (if (looking-at org-table-any-border-regexp)
3830 (beginning-of-line -1)))))
3831 (if (re-search-forward "|" (org-table-end t) t)
3832 (progn
3833 (require 'table)
3834 (if (table--at-cell-p (point))
3836 (message "recognizing table.el table...")
3837 (table-recognize-table)
3838 (message "recognizing table.el table...done")))
3839 (error "This should not happen"))
3841 nil)
3842 nil))
3844 (defun org-at-table-hline-p ()
3845 "Return t if the cursor is inside a hline in a table."
3846 (if org-enable-table-editor
3847 (save-excursion
3848 (beginning-of-line 1)
3849 (looking-at org-table-hline-regexp))
3850 nil))
3852 (defvar org-table-clean-did-remove-column nil)
3854 (defun org-table-map-tables (function &optional quietly)
3855 "Apply FUNCTION to the start of all tables in the buffer."
3856 (save-excursion
3857 (save-restriction
3858 (widen)
3859 (goto-char (point-min))
3860 (while (re-search-forward org-table-any-line-regexp nil t)
3861 (unless quietly
3862 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3863 (beginning-of-line 1)
3864 (when (looking-at org-table-line-regexp)
3865 (save-excursion (funcall function))
3866 (or (looking-at org-table-line-regexp)
3867 (forward-char 1)))
3868 (re-search-forward org-table-any-border-regexp nil 1))))
3869 (unless quietly (message "Mapping tables: done")))
3871 ;; Declare and autoload functions from org-exp.el & Co
3873 (declare-function org-default-export-plist "org-exp")
3874 (declare-function org-infile-export-plist "org-exp")
3875 (declare-function org-get-current-options "org-exp")
3876 (eval-and-compile
3877 (org-autoload "org-exp"
3878 '(org-export org-export-visible
3879 org-insert-export-options-template
3880 org-table-clean-before-export))
3881 (org-autoload "org-ascii"
3882 '(org-export-as-ascii org-export-ascii-preprocess
3883 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3884 org-export-region-as-ascii))
3885 (org-autoload "org-latex"
3886 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3887 org-replace-region-by-latex org-export-region-as-latex
3888 org-export-as-latex org-export-as-pdf
3889 org-export-as-pdf-and-open))
3890 (org-autoload "org-html"
3891 '(org-export-as-html-and-open
3892 org-export-as-html-batch org-export-as-html-to-buffer
3893 org-replace-region-by-html org-export-region-as-html
3894 org-export-as-html))
3895 (org-autoload "org-docbook"
3896 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3897 org-replace-region-by-docbook org-export-region-as-docbook
3898 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3899 org-export-as-docbook))
3900 (org-autoload "org-icalendar"
3901 '(org-export-icalendar-this-file
3902 org-export-icalendar-all-agenda-files
3903 org-export-icalendar-combine-agenda-files))
3904 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3905 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3907 ;; Declare and autoload functions from org-agenda.el
3909 (eval-and-compile
3910 (org-autoload "org-agenda"
3911 '(org-agenda org-agenda-list org-search-view
3912 org-todo-list org-tags-view org-agenda-list-stuck-projects
3913 org-diary org-agenda-to-appt
3914 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3916 ;; Autoload org-remember
3918 (eval-and-compile
3919 (org-autoload "org-remember"
3920 '(org-remember-insinuate org-remember-annotation
3921 org-remember-apply-template org-remember org-remember-handler)))
3923 (eval-and-compile
3924 (org-autoload "org-capture"
3925 '(org-capture org-capture-insert-template-here
3926 org-capture-import-remember-templates)))
3928 ;; Autoload org-clock.el
3930 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3931 (beg end))
3932 (declare-function org-clock-update-mode-line "org-clock" ())
3933 (declare-function org-resolve-clocks "org-clock"
3934 (&optional also-non-dangling-p prompt last-valid))
3935 (defvar org-clock-start-time)
3936 (defvar org-clock-marker (make-marker)
3937 "Marker recording the last clock-in.")
3938 (defvar org-clock-hd-marker (make-marker)
3939 "Marker recording the last clock-in, but the headline position.")
3940 (defvar org-clock-heading ""
3941 "The heading of the current clock entry.")
3942 (defun org-clock-is-active ()
3943 "Return non-nil if clock is currently running.
3944 The return value is actually the clock marker."
3945 (marker-buffer org-clock-marker))
3947 (eval-and-compile
3948 (org-autoload
3949 "org-clock"
3950 '(org-clock-in org-clock-out org-clock-cancel
3951 org-clock-goto org-clock-sum org-clock-display
3952 org-clock-remove-overlays org-clock-report
3953 org-clocktable-shift org-dblock-write:clocktable
3954 org-get-clocktable org-resolve-clocks)))
3956 (defun org-clock-update-time-maybe ()
3957 "If this is a CLOCK line, update it and return t.
3958 Otherwise, return nil."
3959 (interactive)
3960 (save-excursion
3961 (beginning-of-line 1)
3962 (skip-chars-forward " \t")
3963 (when (looking-at org-clock-string)
3964 (let ((re (concat "[ \t]*" org-clock-string
3965 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3966 "\\([ \t]*=>.*\\)?\\)?"))
3967 ts te h m s neg)
3968 (cond
3969 ((not (looking-at re))
3970 nil)
3971 ((not (match-end 2))
3972 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3973 (> org-clock-marker (point))
3974 (<= org-clock-marker (point-at-eol)))
3975 ;; The clock is running here
3976 (setq org-clock-start-time
3977 (apply 'encode-time
3978 (org-parse-time-string (match-string 1))))
3979 (org-clock-update-mode-line)))
3981 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3982 (end-of-line 1)
3983 (setq ts (match-string 1)
3984 te (match-string 3))
3985 (setq s (- (org-float-time
3986 (apply 'encode-time (org-parse-time-string te)))
3987 (org-float-time
3988 (apply 'encode-time (org-parse-time-string ts))))
3989 neg (< s 0)
3990 s (abs s)
3991 h (floor (/ s 3600))
3992 s (- s (* 3600 h))
3993 m (floor (/ s 60))
3994 s (- s (* 60 s)))
3995 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3996 t))))))
3998 (defun org-check-running-clock ()
3999 "Check if the current buffer contains the running clock.
4000 If yes, offer to stop it and to save the buffer with the changes."
4001 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4002 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4003 (buffer-name))))
4004 (org-clock-out)
4005 (when (y-or-n-p "Save changed buffer?")
4006 (save-buffer))))
4008 (defun org-clocktable-try-shift (dir n)
4009 "Check if this line starts a clock table, if yes, shift the time block."
4010 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4011 (org-clocktable-shift dir n)))
4013 ;; Autoload org-timer.el
4015 (eval-and-compile
4016 (org-autoload
4017 "org-timer"
4018 '(org-timer-start org-timer org-timer-item
4019 org-timer-change-times-in-region
4020 org-timer-set-timer
4021 org-timer-reset-timers
4022 org-timer-show-remaining-time)))
4024 ;; Autoload org-feed.el
4026 (eval-and-compile
4027 (org-autoload
4028 "org-feed"
4029 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4032 ;; Autoload org-indent.el
4034 ;; Define the variable already here, to make sure we have it.
4035 (defvar org-indent-mode nil
4036 "Non-nil if Org-Indent mode is enabled.
4037 Use the command `org-indent-mode' to change this variable.")
4039 (eval-and-compile
4040 (org-autoload
4041 "org-indent"
4042 '(org-indent-mode)))
4044 ;; Autoload org-mobile.el
4046 (eval-and-compile
4047 (org-autoload
4048 "org-mobile"
4049 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4051 ;; Autoload archiving code
4052 ;; The stuff that is needed for cycling and tags has to be defined here.
4054 (defgroup org-archive nil
4055 "Options concerning archiving in Org-mode."
4056 :tag "Org Archive"
4057 :group 'org-structure)
4059 (defcustom org-archive-location "%s_archive::"
4060 "The location where subtrees should be archived.
4062 The value of this variable is a string, consisting of two parts,
4063 separated by a double-colon. The first part is a filename and
4064 the second part is a headline.
4066 When the filename is omitted, archiving happens in the same file.
4067 %s in the filename will be replaced by the current file
4068 name (without the directory part). Archiving to a different file
4069 is useful to keep archived entries from contributing to the
4070 Org-mode Agenda.
4072 The archived entries will be filed as subtrees of the specified
4073 headline. When the headline is omitted, the subtrees are simply
4074 filed away at the end of the file, as top-level entries. Also in
4075 the heading you can use %s to represent the file name, this can be
4076 useful when using the same archive for a number of different files.
4078 Here are a few examples:
4079 \"%s_archive::\"
4080 If the current file is Projects.org, archive in file
4081 Projects.org_archive, as top-level trees. This is the default.
4083 \"::* Archived Tasks\"
4084 Archive in the current file, under the top-level headline
4085 \"* Archived Tasks\".
4087 \"~/org/archive.org::\"
4088 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4090 \"~/org/archive.org::* From %s\"
4091 Archive in file ~/org/archive.org (absolute path), under headlines
4092 \"From FILENAME\" where file name is the current file name.
4094 \"basement::** Finished Tasks\"
4095 Archive in file ./basement (relative path), as level 3 trees
4096 below the level 2 heading \"** Finished Tasks\".
4098 You may set this option on a per-file basis by adding to the buffer a
4099 line like
4101 #+ARCHIVE: basement::** Finished Tasks
4103 You may also define it locally for a subtree by setting an ARCHIVE property
4104 in the entry. If such a property is found in an entry, or anywhere up
4105 the hierarchy, it will be used."
4106 :group 'org-archive
4107 :type 'string)
4109 (defcustom org-archive-tag "ARCHIVE"
4110 "The tag that marks a subtree as archived.
4111 An archived subtree does not open during visibility cycling, and does
4112 not contribute to the agenda listings.
4113 After changing this, font-lock must be restarted in the relevant buffers to
4114 get the proper fontification."
4115 :group 'org-archive
4116 :group 'org-keywords
4117 :type 'string)
4119 (defcustom org-agenda-skip-archived-trees t
4120 "Non-nil means the agenda will skip any items located in archived trees.
4121 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4122 variable is no longer recommended, you should leave it at the value t.
4123 Instead, use the key `v' to cycle the archives-mode in the agenda."
4124 :group 'org-archive
4125 :group 'org-agenda-skip
4126 :type 'boolean)
4128 (defcustom org-columns-skip-archived-trees t
4129 "Non-nil means ignore archived trees when creating column view."
4130 :group 'org-archive
4131 :group 'org-properties
4132 :type 'boolean)
4134 (defcustom org-cycle-open-archived-trees nil
4135 "Non-nil means `org-cycle' will open archived trees.
4136 An archived tree is a tree marked with the tag ARCHIVE.
4137 When nil, archived trees will stay folded. You can still open them with
4138 normal outline commands like `show-all', but not with the cycling commands."
4139 :group 'org-archive
4140 :group 'org-cycle
4141 :type 'boolean)
4143 (defcustom org-sparse-tree-open-archived-trees nil
4144 "Non-nil means sparse tree construction shows matches in archived trees.
4145 When nil, matches in these trees are highlighted, but the trees are kept in
4146 collapsed state."
4147 :group 'org-archive
4148 :group 'org-sparse-trees
4149 :type 'boolean)
4151 (defun org-cycle-hide-archived-subtrees (state)
4152 "Re-hide all archived subtrees after a visibility state change."
4153 (when (and (not org-cycle-open-archived-trees)
4154 (not (memq state '(overview folded))))
4155 (save-excursion
4156 (let* ((globalp (memq state '(contents all)))
4157 (beg (if globalp (point-min) (point)))
4158 (end (if globalp (point-max) (org-end-of-subtree t))))
4159 (org-hide-archived-subtrees beg end)
4160 (goto-char beg)
4161 (if (looking-at (concat ".*:" org-archive-tag ":"))
4162 (message "%s" (substitute-command-keys
4163 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4165 (defun org-force-cycle-archived ()
4166 "Cycle subtree even if it is archived."
4167 (interactive)
4168 (setq this-command 'org-cycle)
4169 (let ((org-cycle-open-archived-trees t))
4170 (call-interactively 'org-cycle)))
4172 (defun org-hide-archived-subtrees (beg end)
4173 "Re-hide all archived subtrees after a visibility state change."
4174 (save-excursion
4175 (let* ((re (concat ":" org-archive-tag ":")))
4176 (goto-char beg)
4177 (while (re-search-forward re end t)
4178 (when (org-on-heading-p)
4179 (org-flag-subtree t)
4180 (org-end-of-subtree t))))))
4182 (defun org-flag-subtree (flag)
4183 (save-excursion
4184 (org-back-to-heading t)
4185 (outline-end-of-heading)
4186 (outline-flag-region (point)
4187 (progn (org-end-of-subtree t) (point))
4188 flag)))
4190 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4192 (eval-and-compile
4193 (org-autoload "org-archive"
4194 '(org-add-archive-files org-archive-subtree
4195 org-archive-to-archive-sibling org-toggle-archive-tag
4196 org-archive-subtree-default
4197 org-archive-subtree-default-with-confirmation)))
4199 ;; Autoload Column View Code
4201 (declare-function org-columns-number-to-string "org-colview")
4202 (declare-function org-columns-get-format-and-top-level "org-colview")
4203 (declare-function org-columns-compute "org-colview")
4205 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4206 '(org-columns-number-to-string org-columns-get-format-and-top-level
4207 org-columns-compute org-agenda-columns org-columns-remove-overlays
4208 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4210 ;; Autoload ID code
4212 (declare-function org-id-store-link "org-id")
4213 (declare-function org-id-locations-load "org-id")
4214 (declare-function org-id-locations-save "org-id")
4215 (defvar org-id-track-globally)
4216 (org-autoload "org-id"
4217 '(org-id-get-create org-id-new org-id-copy org-id-get
4218 org-id-get-with-outline-path-completion
4219 org-id-get-with-outline-drilling org-id-store-link
4220 org-id-goto org-id-find org-id-store-link))
4222 ;; Autoload Plotting Code
4224 (org-autoload "org-plot"
4225 '(org-plot/gnuplot))
4227 ;;; Variables for pre-computed regular expressions, all buffer local
4229 (defvar org-drawer-regexp nil
4230 "Matches first line of a hidden block.")
4231 (make-variable-buffer-local 'org-drawer-regexp)
4232 (defvar org-todo-regexp nil
4233 "Matches any of the TODO state keywords.")
4234 (make-variable-buffer-local 'org-todo-regexp)
4235 (defvar org-not-done-regexp nil
4236 "Matches any of the TODO state keywords except the last one.")
4237 (make-variable-buffer-local 'org-not-done-regexp)
4238 (defvar org-not-done-heading-regexp nil
4239 "Matches a TODO headline that is not done.")
4240 (make-variable-buffer-local 'org-not-done-regexp)
4241 (defvar org-todo-line-regexp nil
4242 "Matches a headline and puts TODO state into group 2 if present.")
4243 (make-variable-buffer-local 'org-todo-line-regexp)
4244 (defvar org-complex-heading-regexp nil
4245 "Matches a headline and puts everything into groups:
4246 group 1: the stars
4247 group 2: The todo keyword, maybe
4248 group 3: Priority cookie
4249 group 4: True headline
4250 group 5: Tags")
4251 (make-variable-buffer-local 'org-complex-heading-regexp)
4252 (defvar org-complex-heading-regexp-format nil
4253 "Printf format to make regexp to match an exact headline.
4254 This regexp will match the headline of any node which hase the exact
4255 headline text that is put into the format, but may have any TODO state,
4256 priority and tags.")
4257 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4258 (defvar org-todo-line-tags-regexp nil
4259 "Matches a headline and puts TODO state into group 2 if present.
4260 Also put tags into group 4 if tags are present.")
4261 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4262 (defvar org-nl-done-regexp nil
4263 "Matches newline followed by a headline with the DONE keyword.")
4264 (make-variable-buffer-local 'org-nl-done-regexp)
4265 (defvar org-looking-at-done-regexp nil
4266 "Matches the DONE keyword a point.")
4267 (make-variable-buffer-local 'org-looking-at-done-regexp)
4268 (defvar org-ds-keyword-length 12
4269 "Maximum length of the Deadline and SCHEDULED keywords.")
4270 (make-variable-buffer-local 'org-ds-keyword-length)
4271 (defvar org-deadline-regexp nil
4272 "Matches the DEADLINE keyword.")
4273 (make-variable-buffer-local 'org-deadline-regexp)
4274 (defvar org-deadline-time-regexp nil
4275 "Matches the DEADLINE keyword together with a time stamp.")
4276 (make-variable-buffer-local 'org-deadline-time-regexp)
4277 (defvar org-deadline-line-regexp nil
4278 "Matches the DEADLINE keyword and the rest of the line.")
4279 (make-variable-buffer-local 'org-deadline-line-regexp)
4280 (defvar org-scheduled-regexp nil
4281 "Matches the SCHEDULED keyword.")
4282 (make-variable-buffer-local 'org-scheduled-regexp)
4283 (defvar org-scheduled-time-regexp nil
4284 "Matches the SCHEDULED keyword together with a time stamp.")
4285 (make-variable-buffer-local 'org-scheduled-time-regexp)
4286 (defvar org-closed-time-regexp nil
4287 "Matches the CLOSED keyword together with a time stamp.")
4288 (make-variable-buffer-local 'org-closed-time-regexp)
4290 (defvar org-keyword-time-regexp nil
4291 "Matches any of the 4 keywords, together with the time stamp.")
4292 (make-variable-buffer-local 'org-keyword-time-regexp)
4293 (defvar org-keyword-time-not-clock-regexp nil
4294 "Matches any of the 3 keywords, together with the time stamp.")
4295 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4296 (defvar org-maybe-keyword-time-regexp nil
4297 "Matches a timestamp, possibly preceded by a keyword.")
4298 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4299 (defvar org-planning-or-clock-line-re nil
4300 "Matches a line with planning or clock info.")
4301 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4302 (defvar org-all-time-keywords nil
4303 "List of time keywords.")
4304 (make-variable-buffer-local 'org-all-time-keywords)
4306 (defconst org-plain-time-of-day-regexp
4307 (concat
4308 "\\(\\<[012]?[0-9]"
4309 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4310 "\\(--?"
4311 "\\(\\<[012]?[0-9]"
4312 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4313 "\\)?")
4314 "Regular expression to match a plain time or time range.
4315 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4316 groups carry important information:
4317 0 the full match
4318 1 the first time, range or not
4319 8 the second time, if it is a range.")
4321 (defconst org-plain-time-extension-regexp
4322 (concat
4323 "\\(\\<[012]?[0-9]"
4324 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4325 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4326 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4327 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4328 groups carry important information:
4329 0 the full match
4330 7 hours of duration
4331 9 minutes of duration")
4333 (defconst org-stamp-time-of-day-regexp
4334 (concat
4335 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4336 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4337 "\\(--?"
4338 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4339 "Regular expression to match a timestamp time or time range.
4340 After a match, the following groups carry important information:
4341 0 the full match
4342 1 date plus weekday, for back referencing to make sure both times are on the same day
4343 2 the first time, range or not
4344 4 the second time, if it is a range.")
4346 (defconst org-startup-options
4347 '(("fold" org-startup-folded t)
4348 ("overview" org-startup-folded t)
4349 ("nofold" org-startup-folded nil)
4350 ("showall" org-startup-folded nil)
4351 ("showeverything" org-startup-folded showeverything)
4352 ("content" org-startup-folded content)
4353 ("indent" org-startup-indented t)
4354 ("noindent" org-startup-indented nil)
4355 ("hidestars" org-hide-leading-stars t)
4356 ("showstars" org-hide-leading-stars nil)
4357 ("odd" org-odd-levels-only t)
4358 ("oddeven" org-odd-levels-only nil)
4359 ("align" org-startup-align-all-tables t)
4360 ("noalign" org-startup-align-all-tables nil)
4361 ("inlineimages" org-startup-with-inline-images t)
4362 ("noinlineimages" org-startup-with-inline-images nil)
4363 ("customtime" org-display-custom-times t)
4364 ("logdone" org-log-done time)
4365 ("lognotedone" org-log-done note)
4366 ("nologdone" org-log-done nil)
4367 ("lognoteclock-out" org-log-note-clock-out t)
4368 ("nolognoteclock-out" org-log-note-clock-out nil)
4369 ("logrepeat" org-log-repeat state)
4370 ("lognoterepeat" org-log-repeat note)
4371 ("nologrepeat" org-log-repeat nil)
4372 ("logreschedule" org-log-reschedule time)
4373 ("lognotereschedule" org-log-reschedule note)
4374 ("nologreschedule" org-log-reschedule nil)
4375 ("logredeadline" org-log-redeadline time)
4376 ("lognoteredeadline" org-log-redeadline note)
4377 ("nologredeadline" org-log-redeadline nil)
4378 ("logrefile" org-log-refile time)
4379 ("lognoterefile" org-log-refile note)
4380 ("nologrefile" org-log-refile nil)
4381 ("fninline" org-footnote-define-inline t)
4382 ("nofninline" org-footnote-define-inline nil)
4383 ("fnlocal" org-footnote-section nil)
4384 ("fnauto" org-footnote-auto-label t)
4385 ("fnprompt" org-footnote-auto-label nil)
4386 ("fnconfirm" org-footnote-auto-label confirm)
4387 ("fnplain" org-footnote-auto-label plain)
4388 ("fnadjust" org-footnote-auto-adjust t)
4389 ("nofnadjust" org-footnote-auto-adjust nil)
4390 ("constcgs" constants-unit-system cgs)
4391 ("constSI" constants-unit-system SI)
4392 ("noptag" org-tag-persistent-alist nil)
4393 ("hideblocks" org-hide-block-startup t)
4394 ("nohideblocks" org-hide-block-startup nil)
4395 ("beamer" org-startup-with-beamer-mode t)
4396 ("entitiespretty" org-pretty-entities t)
4397 ("entitiesplain" org-pretty-entities nil))
4398 "Variable associated with STARTUP options for org-mode.
4399 Each element is a list of three items: The startup options as written
4400 in the #+STARTUP line, the corresponding variable, and the value to
4401 set this variable to if the option is found. An optional forth element PUSH
4402 means to push this value onto the list in the variable.")
4404 (defun org-set-regexps-and-options ()
4405 "Precompute regular expressions for current buffer."
4406 (when (org-mode-p)
4407 (org-set-local 'org-todo-kwd-alist nil)
4408 (org-set-local 'org-todo-key-alist nil)
4409 (org-set-local 'org-todo-key-trigger nil)
4410 (org-set-local 'org-todo-keywords-1 nil)
4411 (org-set-local 'org-done-keywords nil)
4412 (org-set-local 'org-todo-heads nil)
4413 (org-set-local 'org-todo-sets nil)
4414 (org-set-local 'org-todo-log-states nil)
4415 (org-set-local 'org-file-properties nil)
4416 (org-set-local 'org-file-tags nil)
4417 (let ((re (org-make-options-regexp
4418 '("CATEGORY" "TODO" "COLUMNS"
4419 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4420 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4421 "OPTIONS")
4422 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4423 (splitre "[ \t]+")
4424 (scripts org-use-sub-superscripts)
4425 kwds kws0 kwsa key log value cat arch tags const links hw dws
4426 tail sep kws1 prio props ftags drawers beamer-p
4427 ext-setup-or-nil setup-contents (start 0))
4428 (save-excursion
4429 (save-restriction
4430 (widen)
4431 (goto-char (point-min))
4432 (while (or (and ext-setup-or-nil
4433 (string-match re ext-setup-or-nil start)
4434 (setq start (match-end 0)))
4435 (and (setq ext-setup-or-nil nil start 0)
4436 (re-search-forward re nil t)))
4437 (setq key (upcase (match-string 1 ext-setup-or-nil))
4438 value (org-match-string-no-properties 2 ext-setup-or-nil))
4439 (if (stringp value) (setq value (org-trim value)))
4440 (cond
4441 ((equal key "CATEGORY")
4442 (setq cat value))
4443 ((member key '("SEQ_TODO" "TODO"))
4444 (push (cons 'sequence (org-split-string value splitre)) kwds))
4445 ((equal key "TYP_TODO")
4446 (push (cons 'type (org-split-string value splitre)) kwds))
4447 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4448 ;; general TODO-like setup
4449 (push (cons (intern (downcase (match-string 1 key)))
4450 (org-split-string value splitre)) kwds))
4451 ((equal key "TAGS")
4452 (setq tags (append tags (if tags '("\\n") nil)
4453 (org-split-string value splitre))))
4454 ((equal key "COLUMNS")
4455 (org-set-local 'org-columns-default-format value))
4456 ((equal key "LINK")
4457 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4458 (push (cons (match-string 1 value)
4459 (org-trim (match-string 2 value)))
4460 links)))
4461 ((equal key "PRIORITIES")
4462 (setq prio (org-split-string value " +")))
4463 ((equal key "PROPERTY")
4464 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4465 (push (cons (match-string 1 value) (match-string 2 value))
4466 props)))
4467 ((equal key "FILETAGS")
4468 (when (string-match "\\S-" value)
4469 (setq ftags
4470 (append
4471 ftags
4472 (apply 'append
4473 (mapcar (lambda (x) (org-split-string x ":"))
4474 (org-split-string value)))))))
4475 ((equal key "DRAWERS")
4476 (setq drawers (org-split-string value splitre)))
4477 ((equal key "CONSTANTS")
4478 (setq const (append const (org-split-string value splitre))))
4479 ((equal key "STARTUP")
4480 (let ((opts (org-split-string value splitre))
4481 l var val)
4482 (while (setq l (pop opts))
4483 (when (setq l (assoc l org-startup-options))
4484 (setq var (nth 1 l) val (nth 2 l))
4485 (if (not (nth 3 l))
4486 (set (make-local-variable var) val)
4487 (if (not (listp (symbol-value var)))
4488 (set (make-local-variable var) nil))
4489 (set (make-local-variable var) (symbol-value var))
4490 (add-to-list var val))))))
4491 ((equal key "ARCHIVE")
4492 (setq arch value)
4493 (remove-text-properties 0 (length arch)
4494 '(face t fontified t) arch))
4495 ((equal key "LATEX_CLASS")
4496 (setq beamer-p (equal value "beamer")))
4497 ((equal key "OPTIONS")
4498 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4499 (setq scripts (read (match-string 2 value)))))
4500 ((equal key "SETUPFILE")
4501 (setq setup-contents (org-file-contents
4502 (expand-file-name
4503 (org-remove-double-quotes value))
4504 'noerror))
4505 (if (not ext-setup-or-nil)
4506 (setq ext-setup-or-nil setup-contents start 0)
4507 (setq ext-setup-or-nil
4508 (concat (substring ext-setup-or-nil 0 start)
4509 "\n" setup-contents "\n"
4510 (substring ext-setup-or-nil start)))))
4511 ))))
4512 (org-set-local 'org-use-sub-superscripts scripts)
4513 (when cat
4514 (org-set-local 'org-category (intern cat))
4515 (push (cons "CATEGORY" cat) props))
4516 (when prio
4517 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4518 (setq prio (mapcar 'string-to-char prio))
4519 (org-set-local 'org-highest-priority (nth 0 prio))
4520 (org-set-local 'org-lowest-priority (nth 1 prio))
4521 (org-set-local 'org-default-priority (nth 2 prio)))
4522 (and props (org-set-local 'org-file-properties (nreverse props)))
4523 (and ftags (org-set-local 'org-file-tags
4524 (mapcar 'org-add-prop-inherited ftags)))
4525 (and drawers (org-set-local 'org-drawers drawers))
4526 (and arch (org-set-local 'org-archive-location arch))
4527 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4528 ;; Process the TODO keywords
4529 (unless kwds
4530 ;; Use the global values as if they had been given locally.
4531 (setq kwds (default-value 'org-todo-keywords))
4532 (if (stringp (car kwds))
4533 (setq kwds (list (cons org-todo-interpretation
4534 (default-value 'org-todo-keywords)))))
4535 (setq kwds (reverse kwds)))
4536 (setq kwds (nreverse kwds))
4537 (let (inter kws kw)
4538 (while (setq kws (pop kwds))
4539 (let ((kws (or
4540 (run-hook-with-args-until-success
4541 'org-todo-setup-filter-hook kws)
4542 kws)))
4543 (setq inter (pop kws) sep (member "|" kws)
4544 kws0 (delete "|" (copy-sequence kws))
4545 kwsa nil
4546 kws1 (mapcar
4547 (lambda (x)
4548 ;; 1 2
4549 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4550 (progn
4551 (setq kw (match-string 1 x)
4552 key (and (match-end 2) (match-string 2 x))
4553 log (org-extract-log-state-settings x))
4554 (push (cons kw (and key (string-to-char key))) kwsa)
4555 (and log (push log org-todo-log-states))
4557 (error "Invalid TODO keyword %s" x)))
4558 kws0)
4559 kwsa (if kwsa (append '((:startgroup))
4560 (nreverse kwsa)
4561 '((:endgroup))))
4562 hw (car kws1)
4563 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4564 tail (list inter hw (car dws) (org-last dws))))
4565 (add-to-list 'org-todo-heads hw 'append)
4566 (push kws1 org-todo-sets)
4567 (setq org-done-keywords (append org-done-keywords dws nil))
4568 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4569 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4570 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4571 (setq org-todo-sets (nreverse org-todo-sets)
4572 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4573 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4574 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4575 ;; Process the constants
4576 (when const
4577 (let (e cst)
4578 (while (setq e (pop const))
4579 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4580 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4581 (setq org-table-formula-constants-local cst)))
4583 ;; Process the tags.
4584 (when tags
4585 (let (e tgs)
4586 (while (setq e (pop tags))
4587 (cond
4588 ((equal e "{") (push '(:startgroup) tgs))
4589 ((equal e "}") (push '(:endgroup) tgs))
4590 ((equal e "\\n") (push '(:newline) tgs))
4591 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4592 (push (cons (match-string 1 e)
4593 (string-to-char (match-string 2 e)))
4594 tgs))
4595 (t (push (list e) tgs))))
4596 (org-set-local 'org-tag-alist nil)
4597 (while (setq e (pop tgs))
4598 (or (and (stringp (car e))
4599 (assoc (car e) org-tag-alist))
4600 (push e org-tag-alist)))))
4602 ;; Compute the regular expressions and other local variables
4603 (if (not org-done-keywords)
4604 (setq org-done-keywords (and org-todo-keywords-1
4605 (list (org-last org-todo-keywords-1)))))
4606 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4607 (length org-scheduled-string)
4608 (length org-clock-string)
4609 (length org-closed-string)))
4610 org-drawer-regexp
4611 (concat "^[ \t]*:\\("
4612 (mapconcat 'regexp-quote org-drawers "\\|")
4613 "\\):[ \t]*$")
4614 org-not-done-keywords
4615 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4616 org-todo-regexp
4617 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4618 "\\|") "\\)\\>")
4619 org-not-done-regexp
4620 (concat "\\<\\("
4621 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4622 "\\)\\>")
4623 org-not-done-heading-regexp
4624 (concat "^\\(\\*+\\)[ \t]+\\("
4625 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4626 "\\)[ \t]+")
4627 org-todo-line-regexp
4628 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4629 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4630 "\\)[ \t]+\\)?\\(.*\\)")
4631 org-complex-heading-regexp
4632 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4633 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4634 "\\)[ \t]+\\)?"
4635 "\\(?:\\(\\[#.\\]\\)[ \t]+\\)?"
4636 "\\(.*?\\)"
4637 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4638 org-complex-heading-regexp-format
4639 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4640 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4641 "\\)[ \t]+\\)?"
4642 "\\(?:\\(\\[#.\\]\\)[ \t]+\\)?"
4643 "\\(?:\\(?:\\[[0-9%%/]+\\]\\)[ \t]+\\)?" ; stats cookie
4644 "\\(%s\\)[ \t]*"
4645 "\\(?:\\[[0-9%%/]+\\]\\)?" ; stats cookie
4646 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$"))
4647 org-nl-done-regexp
4648 (concat "\n\\*+[ \t]+"
4649 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4650 "\\)" "[ \t]+")
4651 org-todo-line-tags-regexp
4652 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4653 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4654 "\\)[ \t]+\\)"
4655 (org-re "\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4656 org-looking-at-done-regexp
4657 (concat "^" "\\(?:"
4658 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4659 "[ \t]+")
4660 org-deadline-regexp (concat "\\<" org-deadline-string)
4661 org-deadline-time-regexp
4662 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4663 org-deadline-line-regexp
4664 (concat "\\<\\(" org-deadline-string "\\).*")
4665 org-scheduled-regexp
4666 (concat "\\<" org-scheduled-string)
4667 org-scheduled-time-regexp
4668 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4669 org-closed-time-regexp
4670 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4671 org-keyword-time-regexp
4672 (concat "\\<\\(" org-scheduled-string
4673 "\\|" org-deadline-string
4674 "\\|" org-closed-string
4675 "\\|" org-clock-string "\\)"
4676 " *[[<]\\([^]>]+\\)[]>]")
4677 org-keyword-time-not-clock-regexp
4678 (concat "\\<\\(" org-scheduled-string
4679 "\\|" org-deadline-string
4680 "\\|" org-closed-string
4681 "\\)"
4682 " *[[<]\\([^]>]+\\)[]>]")
4683 org-maybe-keyword-time-regexp
4684 (concat "\\(\\<\\(" org-scheduled-string
4685 "\\|" org-deadline-string
4686 "\\|" org-closed-string
4687 "\\|" org-clock-string "\\)\\)?"
4688 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4689 org-planning-or-clock-line-re
4690 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4691 "\\|" org-deadline-string
4692 "\\|" org-closed-string "\\|" org-clock-string
4693 "\\)\\>\\)")
4694 org-all-time-keywords
4695 (mapcar (lambda (w) (substring w 0 -1))
4696 (list org-scheduled-string org-deadline-string
4697 org-clock-string org-closed-string))
4699 (org-compute-latex-and-specials-regexp)
4700 (org-set-font-lock-defaults))))
4702 (defun org-file-contents (file &optional noerror)
4703 "Return the contents of FILE, as a string."
4704 (if (or (not file)
4705 (not (file-readable-p file)))
4706 (if noerror
4707 (progn
4708 (message "Cannot read file \"%s\"" file)
4709 (ding) (sit-for 2)
4711 (error "Cannot read file \"%s\"" file))
4712 (with-temp-buffer
4713 (insert-file-contents file)
4714 (buffer-string))))
4716 (defun org-extract-log-state-settings (x)
4717 "Extract the log state setting from a TODO keyword string.
4718 This will extract info from a string like \"WAIT(w@/!)\"."
4719 (let (kw key log1 log2)
4720 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4721 (setq kw (match-string 1 x)
4722 key (and (match-end 2) (match-string 2 x))
4723 log1 (and (match-end 3) (match-string 3 x))
4724 log2 (and (match-end 4) (match-string 4 x)))
4725 (and (or log1 log2)
4726 (list kw
4727 (and log1 (if (equal log1 "!") 'time 'note))
4728 (and log2 (if (equal log2 "!") 'time 'note)))))))
4730 (defun org-remove-keyword-keys (list)
4731 "Remove a pair of parenthesis at the end of each string in LIST."
4732 (mapcar (lambda (x)
4733 (if (string-match "(.*)$" x)
4734 (substring x 0 (match-beginning 0))
4736 list))
4738 (defun org-assign-fast-keys (alist)
4739 "Assign fast keys to a keyword-key alist.
4740 Respect keys that are already there."
4741 (let (new e (alt ?0))
4742 (while (setq e (pop alist))
4743 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4744 (cdr e)) ;; Key already assigned.
4745 (push e new)
4746 (let ((clist (string-to-list (downcase (car e))))
4747 (used (append new alist)))
4748 (when (= (car clist) ?@)
4749 (pop clist))
4750 (while (and clist (rassoc (car clist) used))
4751 (pop clist))
4752 (unless clist
4753 (while (rassoc alt used)
4754 (incf alt)))
4755 (push (cons (car e) (or (car clist) alt)) new))))
4756 (nreverse new)))
4758 ;;; Some variables used in various places
4760 (defvar org-window-configuration nil
4761 "Used in various places to store a window configuration.")
4762 (defvar org-selected-window nil
4763 "Used in various places to store a window configuration.")
4764 (defvar org-finish-function nil
4765 "Function to be called when `C-c C-c' is used.
4766 This is for getting out of special buffers like remember.")
4769 ;; FIXME: Occasionally check by commenting these, to make sure
4770 ;; no other functions uses these, forgetting to let-bind them.
4771 (defvar entry)
4772 (defvar last-state)
4773 (defvar date)
4775 ;; Defined somewhere in this file, but used before definition.
4776 (defvar org-entities) ;; defined in org-entities.el
4777 (defvar org-struct-menu)
4778 (defvar org-org-menu)
4779 (defvar org-tbl-menu)
4781 ;;;; Define the Org-mode
4783 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4784 (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"))
4787 ;; We use a before-change function to check if a table might need
4788 ;; an update.
4789 (defvar org-table-may-need-update t
4790 "Indicates that a table might need an update.
4791 This variable is set by `org-before-change-function'.
4792 `org-table-align' sets it back to nil.")
4793 (defun org-before-change-function (beg end)
4794 "Every change indicates that a table might need an update."
4795 (setq org-table-may-need-update t))
4796 (defvar org-mode-map)
4797 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4798 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4799 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4800 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4801 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4802 (defvar org-table-buffer-is-an nil)
4804 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4805 ;; some places -- e.g. see the macro org-with-limited-levels.
4807 ;; In Org buffers, the value of `outline-regexp' is that of
4808 ;; `org-outline-regexp'. The only function still directly relying on
4809 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4810 ;; job when `orgstruct-mode' is active.
4811 (defvar org-outline-regexp "\\*+ "
4812 "Regexp to match Org headlines.")
4813 (defconst org-outline-regexp-bol "^\\*+ "
4814 "Regexp to match Org headlines.
4815 This is similar to `org-outline-regexp' but additionally makes
4816 sure that we are at the beginning of the line.")
4818 ;;;###autoload
4819 (define-derived-mode org-mode outline-mode "Org"
4820 "Outline-based notes management and organizer, alias
4821 \"Carsten's outline-mode for keeping track of everything.\"
4823 Org-mode develops organizational tasks around a NOTES file which
4824 contains information about projects as plain text. Org-mode is
4825 implemented on top of outline-mode, which is ideal to keep the content
4826 of large files well structured. It supports ToDo items, deadlines and
4827 time stamps, which magically appear in the diary listing of the Emacs
4828 calendar. Tables are easily created with a built-in table editor.
4829 Plain text URL-like links connect to websites, emails (VM), Usenet
4830 messages (Gnus), BBDB entries, and any files related to the project.
4831 For printing and sharing of notes, an Org-mode file (or a part of it)
4832 can be exported as a structured ASCII or HTML file.
4834 The following commands are available:
4836 \\{org-mode-map}"
4838 ;; Get rid of Outline menus, they are not needed
4839 ;; Need to do this here because define-derived-mode sets up
4840 ;; the keymap so late. Still, it is a waste to call this each time
4841 ;; we switch another buffer into org-mode.
4842 (if (featurep 'xemacs)
4843 (when (boundp 'outline-mode-menu-heading)
4844 ;; Assume this is Greg's port, it uses easymenu
4845 (easy-menu-remove outline-mode-menu-heading)
4846 (easy-menu-remove outline-mode-menu-show)
4847 (easy-menu-remove outline-mode-menu-hide))
4848 (define-key org-mode-map [menu-bar headings] 'undefined)
4849 (define-key org-mode-map [menu-bar hide] 'undefined)
4850 (define-key org-mode-map [menu-bar show] 'undefined))
4852 (org-load-modules-maybe)
4853 (easy-menu-add org-org-menu)
4854 (easy-menu-add org-tbl-menu)
4855 (org-install-agenda-files-menu)
4856 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4857 (add-to-invisibility-spec '(org-cwidth))
4858 (add-to-invisibility-spec '(org-hide-block . t))
4859 (when (featurep 'xemacs)
4860 (org-set-local 'line-move-ignore-invisible t))
4861 (org-set-local 'outline-regexp org-outline-regexp)
4862 (org-set-local 'outline-level 'org-outline-level)
4863 (setq bidi-paragraph-direction 'left-to-right)
4864 (when (and org-ellipsis
4865 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4866 (fboundp 'make-glyph-code))
4867 (unless org-display-table
4868 (setq org-display-table (make-display-table)))
4869 (set-display-table-slot
4870 org-display-table 4
4871 (vconcat (mapcar
4872 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4873 org-ellipsis)))
4874 (if (stringp org-ellipsis) org-ellipsis "..."))))
4875 (setq buffer-display-table org-display-table))
4876 (org-set-regexps-and-options)
4877 (when (and org-tag-faces (not org-tags-special-faces-re))
4878 ;; tag faces set outside customize.... force initialization.
4879 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4880 ;; Calc embedded
4881 (org-set-local 'calc-embedded-open-mode "# ")
4882 (modify-syntax-entry ?@ "w")
4883 (if org-startup-truncated (setq truncate-lines t))
4884 (org-set-local 'font-lock-unfontify-region-function
4885 'org-unfontify-region)
4886 ;; Activate before-change-function
4887 (org-set-local 'org-table-may-need-update t)
4888 (org-add-hook 'before-change-functions 'org-before-change-function nil
4889 'local)
4890 ;; Check for running clock before killing a buffer
4891 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4892 ;; Paragraphs and auto-filling
4893 (org-set-autofill-regexps)
4894 (setq indent-line-function 'org-indent-line-function)
4895 (org-update-radio-target-regexp)
4896 ;; Beginning/end of defun
4897 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4898 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4899 ;; Next error for sparse trees
4900 (org-set-local 'next-error-function 'org-occur-next-match)
4901 ;; Make sure dependence stuff works reliably, even for users who set it
4902 ;; too late :-(
4903 (if org-enforce-todo-dependencies
4904 (add-hook 'org-blocker-hook
4905 'org-block-todo-from-children-or-siblings-or-parent)
4906 (remove-hook 'org-blocker-hook
4907 'org-block-todo-from-children-or-siblings-or-parent))
4908 (if org-enforce-todo-checkbox-dependencies
4909 (add-hook 'org-blocker-hook
4910 'org-block-todo-from-checkboxes)
4911 (remove-hook 'org-blocker-hook
4912 'org-block-todo-from-checkboxes))
4914 ;; Comment characters
4915 (org-set-local 'comment-start "#")
4916 (org-set-local 'comment-padding " ")
4918 ;; Align options lines
4919 (org-set-local
4920 'align-mode-rules-list
4921 '((org-in-buffer-settings
4922 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4923 (modes . '(org-mode)))))
4925 ;; Imenu
4926 (org-set-local 'imenu-create-index-function
4927 'org-imenu-get-tree)
4929 ;; Make isearch reveal context
4930 (if (or (featurep 'xemacs)
4931 (not (boundp 'outline-isearch-open-invisible-function)))
4932 ;; Emacs 21 and XEmacs make use of the hook
4933 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4934 ;; Emacs 22 deals with this through a special variable
4935 (org-set-local 'outline-isearch-open-invisible-function
4936 (lambda (&rest ignore) (org-show-context 'isearch))))
4938 ;; Turn on org-beamer-mode?
4939 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4941 ;; Setup the pcomplete hooks
4942 (set (make-local-variable 'pcomplete-command-completion-function)
4943 'org-pcomplete-initial)
4944 (set (make-local-variable 'pcomplete-command-name-function)
4945 'org-command-at-point)
4946 (set (make-local-variable 'pcomplete-default-completion-function)
4947 'ignore)
4948 (set (make-local-variable 'pcomplete-parse-arguments-function)
4949 'org-parse-arguments)
4950 (set (make-local-variable 'pcomplete-termination-string) "")
4951 (set (make-local-variable 'face-remapping-alist)
4952 '((default org-default)))
4954 ;; If empty file that did not turn on org-mode automatically, make it to.
4955 (if (and org-insert-mode-line-in-empty-file
4956 (org-called-interactively-p 'any)
4957 (= (point-min) (point-max)))
4958 (insert "# -*- mode: org -*-\n\n"))
4959 (unless org-inhibit-startup
4960 (when org-startup-align-all-tables
4961 (let ((bmp (buffer-modified-p)))
4962 (org-table-map-tables 'org-table-align 'quietly)
4963 (set-buffer-modified-p bmp)))
4964 (when org-startup-with-inline-images
4965 (org-display-inline-images))
4966 (when org-startup-indented
4967 (require 'org-indent)
4968 (org-indent-mode 1))
4969 (unless org-inhibit-startup-visibility-stuff
4970 (org-set-startup-visibility))))
4972 (when (fboundp 'abbrev-table-put)
4973 (abbrev-table-put org-mode-abbrev-table
4974 :parents (list text-mode-abbrev-table)))
4976 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4978 (defun org-current-time ()
4979 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4980 (if (> (car org-time-stamp-rounding-minutes) 1)
4981 (let ((r (car org-time-stamp-rounding-minutes))
4982 (time (decode-time)))
4983 (apply 'encode-time
4984 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4985 (nthcdr 2 time))))
4986 (current-time)))
4988 (defun org-today ()
4989 "Return today date, considering `org-extend-today-until'."
4990 (time-to-days
4991 (time-subtract (current-time)
4992 (list 0 (* 3600 org-extend-today-until) 0))))
4994 ;;;; Font-Lock stuff, including the activators
4996 (defvar org-mouse-map (make-sparse-keymap))
4997 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4998 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4999 (when org-mouse-1-follows-link
5000 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5001 (when org-tab-follows-link
5002 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5003 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5005 (require 'font-lock)
5007 (defconst org-non-link-chars "]\t\n\r<>")
5008 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5009 "shell" "elisp" "doi" "message"))
5010 (defvar org-link-types-re nil
5011 "Matches a link that has a url-like prefix like \"http:\"")
5012 (defvar org-link-re-with-space nil
5013 "Matches a link with spaces, optional angular brackets around it.")
5014 (defvar org-link-re-with-space2 nil
5015 "Matches a link with spaces, optional angular brackets around it.")
5016 (defvar org-link-re-with-space3 nil
5017 "Matches a link with spaces, only for internal part in bracket links.")
5018 (defvar org-angle-link-re nil
5019 "Matches link with angular brackets, spaces are allowed.")
5020 (defvar org-plain-link-re nil
5021 "Matches plain link, without spaces.")
5022 (defvar org-bracket-link-regexp nil
5023 "Matches a link in double brackets.")
5024 (defvar org-bracket-link-analytic-regexp nil
5025 "Regular expression used to analyze links.
5026 Here is what the match groups contain after a match:
5027 1: http:
5028 2: http
5029 3: path
5030 4: [desc]
5031 5: desc")
5032 (defvar org-bracket-link-analytic-regexp++ nil
5033 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5034 (defvar org-any-link-re nil
5035 "Regular expression matching any link.")
5037 (defcustom org-match-sexp-depth 3
5038 "Number of stacked braces for sub/superscript matching.
5039 This has to be set before loading org.el to be effective."
5040 :group 'org-export-translation ; ??????????????????????????/
5041 :type 'integer)
5043 (defun org-create-multibrace-regexp (left right n)
5044 "Create a regular expression which will match a balanced sexp.
5045 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5046 as single character strings.
5047 The regexp returned will match the entire expression including the
5048 delimiters. It will also define a single group which contains the
5049 match except for the outermost delimiters. The maximum depth of
5050 stacked delimiters is N. Escaping delimiters is not possible."
5051 (let* ((nothing (concat "[^" left right "]*?"))
5052 (or "\\|")
5053 (re nothing)
5054 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5055 (while (> n 1)
5056 (setq n (1- n)
5057 re (concat re or next)
5058 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5059 (concat left "\\(" re "\\)" right)))
5061 (defvar org-match-substring-regexp
5062 (concat
5063 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5064 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5065 "\\|"
5066 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5067 "\\|"
5068 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5069 "The regular expression matching a sub- or superscript.")
5071 (defvar org-match-substring-with-braces-regexp
5072 (concat
5073 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5074 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5075 "\\)")
5076 "The regular expression matching a sub- or superscript, forcing braces.")
5078 (defun org-make-link-regexps ()
5079 "Update the link regular expressions.
5080 This should be called after the variable `org-link-types' has changed."
5081 (setq org-link-types-re
5082 (concat
5083 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5084 org-link-re-with-space
5085 (concat
5086 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5087 "\\([^" org-non-link-chars " ]"
5088 "[^" org-non-link-chars "]*"
5089 "[^" org-non-link-chars " ]\\)>?")
5090 org-link-re-with-space2
5091 (concat
5092 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5093 "\\([^" org-non-link-chars " ]"
5094 "[^\t\n\r]*"
5095 "[^" org-non-link-chars " ]\\)>?")
5096 org-link-re-with-space3
5097 (concat
5098 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5099 "\\([^" org-non-link-chars " ]"
5100 "[^\t\n\r]*\\)")
5101 org-angle-link-re
5102 (concat
5103 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5104 "\\([^" org-non-link-chars " ]"
5105 "[^" org-non-link-chars "]*"
5106 "\\)>")
5107 org-plain-link-re
5108 (concat
5109 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5110 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5111 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5112 org-bracket-link-regexp
5113 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5114 org-bracket-link-analytic-regexp
5115 (concat
5116 "\\[\\["
5117 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5118 "\\([^]]+\\)"
5119 "\\]"
5120 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5121 "\\]")
5122 org-bracket-link-analytic-regexp++
5123 (concat
5124 "\\[\\["
5125 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5126 "\\([^]]+\\)"
5127 "\\]"
5128 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5129 "\\]")
5130 org-any-link-re
5131 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5132 org-angle-link-re "\\)\\|\\("
5133 org-plain-link-re "\\)")))
5135 (org-make-link-regexps)
5137 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5138 "Regular expression for fast time stamp matching.")
5139 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5140 "Regular expression for fast time stamp matching.")
5141 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5142 "Regular expression matching time strings for analysis.
5143 This one does not require the space after the date, so it can be used
5144 on a string that terminates immediately after the date.")
5145 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5146 "Regular expression matching time strings for analysis.")
5147 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5148 "Regular expression matching time stamps, with groups.")
5149 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5150 "Regular expression matching time stamps (also [..]), with groups.")
5151 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5152 "Regular expression matching a time stamp range.")
5153 (defconst org-tr-regexp-both
5154 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5155 "Regular expression matching a time stamp range.")
5156 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5157 org-ts-regexp "\\)?")
5158 "Regular expression matching a time stamp or time stamp range.")
5159 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5160 org-ts-regexp-both "\\)?")
5161 "Regular expression matching a time stamp or time stamp range.
5162 The time stamps may be either active or inactive.")
5164 (defvar org-emph-face nil)
5166 (defun org-do-emphasis-faces (limit)
5167 "Run through the buffer and add overlays to emphasised strings."
5168 (let (rtn a)
5169 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5170 (if (not (= (char-after (match-beginning 3))
5171 (char-after (match-beginning 4))))
5172 (progn
5173 (setq rtn t)
5174 (setq a (assoc (match-string 3) org-emphasis-alist))
5175 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5176 'face
5177 (nth 1 a))
5178 (and (nth 4 a)
5179 (org-remove-flyspell-overlays-in
5180 (match-beginning 0) (match-end 0)))
5181 (add-text-properties (match-beginning 2) (match-end 2)
5182 '(font-lock-multiline t org-emphasis t))
5183 (when org-hide-emphasis-markers
5184 (add-text-properties (match-end 4) (match-beginning 5)
5185 '(invisible org-link))
5186 (add-text-properties (match-beginning 3) (match-end 3)
5187 '(invisible org-link)))))
5188 (backward-char 1))
5189 rtn))
5191 (defun org-emphasize (&optional char)
5192 "Insert or change an emphasis, i.e. a font like bold or italic.
5193 If there is an active region, change that region to a new emphasis.
5194 If there is no region, just insert the marker characters and position
5195 the cursor between them.
5196 CHAR should be either the marker character, or the first character of the
5197 HTML tag associated with that emphasis. If CHAR is a space, the means
5198 to remove the emphasis of the selected region.
5199 If char is not given (for example in an interactive call) it
5200 will be prompted for."
5201 (interactive)
5202 (let ((eal org-emphasis-alist) e det
5203 (erc org-emphasis-regexp-components)
5204 (prompt "")
5205 (string "") beg end move tag c s)
5206 (if (org-region-active-p)
5207 (setq beg (region-beginning) end (region-end)
5208 string (buffer-substring beg end))
5209 (setq move t))
5211 (while (setq e (pop eal))
5212 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5213 c (aref tag 0))
5214 (push (cons c (string-to-char (car e))) det)
5215 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5216 (substring tag 1)))))
5217 (setq det (nreverse det))
5218 (unless char
5219 (message "%s" (concat "Emphasis marker or tag:" prompt))
5220 (setq char (read-char-exclusive)))
5221 (setq char (or (cdr (assoc char det)) char))
5222 (if (equal char ?\ )
5223 (setq s "" move nil)
5224 (unless (assoc (char-to-string char) org-emphasis-alist)
5225 (error "No such emphasis marker: \"%c\"" char))
5226 (setq s (char-to-string char)))
5227 (while (and (> (length string) 1)
5228 (equal (substring string 0 1) (substring string -1))
5229 (assoc (substring string 0 1) org-emphasis-alist))
5230 (setq string (substring string 1 -1)))
5231 (setq string (concat s string s))
5232 (if beg (delete-region beg end))
5233 (unless (or (bolp)
5234 (string-match (concat "[" (nth 0 erc) "\n]")
5235 (char-to-string (char-before (point)))))
5236 (insert " "))
5237 (unless (or (eobp)
5238 (string-match (concat "[" (nth 1 erc) "\n]")
5239 (char-to-string (char-after (point)))))
5240 (insert " ") (backward-char 1))
5241 (insert string)
5242 (and move (backward-char 1))))
5244 (defconst org-nonsticky-props
5245 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5247 (defsubst org-rear-nonsticky-at (pos)
5248 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5250 (defun org-activate-plain-links (limit)
5251 "Run through the buffer and add overlays to links."
5252 (catch 'exit
5253 (let (f)
5254 (if (re-search-forward org-plain-link-re limit t)
5255 (progn
5256 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5257 (setq f (get-text-property (match-beginning 0) 'face))
5258 (if (or (eq f 'org-tag)
5259 (and (listp f) (memq 'org-tag f)))
5261 (add-text-properties (match-beginning 0) (match-end 0)
5262 (list 'mouse-face 'highlight
5263 'face 'org-link
5264 'keymap org-mouse-map))
5265 (org-rear-nonsticky-at (match-end 0)))
5266 t)))))
5268 (defun org-activate-code (limit)
5269 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5270 (progn
5271 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5272 (remove-text-properties (match-beginning 0) (match-end 0)
5273 '(display t invisible t intangible t))
5274 t)))
5276 (defcustom org-src-fontify-natively nil
5277 "When non-nil, fontify code in code blocks."
5278 :type 'boolean
5279 :group 'org-appearance
5280 :group 'org-babel)
5282 (defun org-fontify-meta-lines-and-blocks (limit)
5283 (condition-case nil
5284 (org-fontify-meta-lines-and-blocks-1 limit)
5285 (error (message "org-mode fontification error"))))
5287 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5288 "Fontify #+ lines and blocks, in the correct ways."
5289 (let ((case-fold-search t))
5290 (if (re-search-forward
5291 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5292 limit t)
5293 (let ((beg (match-beginning 0))
5294 (block-start (match-end 0))
5295 (block-end nil)
5296 (lang (match-string 7))
5297 (beg1 (line-beginning-position 2))
5298 (dc1 (downcase (match-string 2)))
5299 (dc3 (downcase (match-string 3)))
5300 end end1 quoting block-type ovl)
5301 (cond
5302 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5303 ;; a single line of backend-specific content
5304 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5305 (remove-text-properties (match-beginning 0) (match-end 0)
5306 '(display t invisible t intangible t))
5307 (add-text-properties (match-beginning 1) (match-end 3)
5308 '(font-lock-fontified t face org-meta-line))
5309 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5310 '(font-lock-fontified t face org-block))
5311 ; for backend-specific code
5313 ((and (match-end 4) (equal dc3 "begin"))
5314 ;; Truly a block
5315 (setq block-type (downcase (match-string 5))
5316 quoting (member block-type org-protecting-blocks))
5317 (when (re-search-forward
5318 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5319 nil t) ;; on purpose, we look further than LIMIT
5320 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5321 (setq block-end (match-beginning 0))
5322 (when quoting
5323 (remove-text-properties beg end
5324 '(display t invisible t intangible t)))
5325 (add-text-properties
5326 beg end
5327 '(font-lock-fontified t font-lock-multiline t))
5328 (add-text-properties beg beg1 '(face org-meta-line))
5329 (add-text-properties end1 (min (point-max) (1+ end))
5330 '(face org-meta-line)) ; for end_src
5331 (cond
5332 ((and lang (not (string= lang "")) org-src-fontify-natively)
5333 (org-src-font-lock-fontify-block lang block-start block-end)
5334 ;; remove old background overlays
5335 (mapc (lambda (ov)
5336 (if (eq (overlay-get ov 'face) 'org-block-background)
5337 (delete-overlay ov)))
5338 (overlays-at (/ (+ beg1 block-end) 2)))
5339 ;; add a background overlay
5340 (setq ovl (make-overlay beg1 block-end))
5341 (overlay-put ovl 'face 'org-block-background)
5342 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5343 (quoting
5344 (add-text-properties beg1 (min (point-max) (1+ end1))
5345 '(face org-block))) ; end of source block
5346 ((not org-fontify-quote-and-verse-blocks))
5347 ((string= block-type "quote")
5348 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5349 ((string= block-type "verse")
5350 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5351 (add-text-properties beg beg1 '(face org-block-begin-line))
5352 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5354 ((member dc1 '("title:" "author:" "email:" "date:"))
5355 (add-text-properties
5356 beg (match-end 3)
5357 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5358 '(font-lock-fontified t invisible t)
5359 '(font-lock-fontified t face org-document-info-keyword)))
5360 (add-text-properties
5361 (match-beginning 6) (match-end 6)
5362 (if (string-equal dc1 "title:")
5363 '(font-lock-fontified t face org-document-title)
5364 '(font-lock-fontified t face org-document-info))))
5365 ((not (member (char-after beg) '(?\ ?\t)))
5366 ;; just any other in-buffer setting, but not indented
5367 (add-text-properties
5368 beg (1+ (match-end 0))
5369 '(font-lock-fontified t face org-meta-line))
5371 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5372 "orgtbl:" "tblfm:" "tblname:" "result:"
5373 "results:" "source:" "srcname:" "call:"
5374 "data:" "header:" "headers:"))
5375 (and (match-end 4) (equal dc3 "attr")))
5376 (add-text-properties
5377 beg (match-end 0)
5378 '(font-lock-fontified t face org-meta-line))
5380 ((member dc3 '(" " ""))
5381 (add-text-properties
5382 beg (match-end 0)
5383 '(font-lock-fontified t face font-lock-comment-face)))
5384 (t nil))))))
5386 (defun org-activate-angle-links (limit)
5387 "Run through the buffer and add overlays to links."
5388 (if (re-search-forward org-angle-link-re limit t)
5389 (progn
5390 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5391 (add-text-properties (match-beginning 0) (match-end 0)
5392 (list 'mouse-face 'highlight
5393 'keymap org-mouse-map))
5394 (org-rear-nonsticky-at (match-end 0))
5395 t)))
5397 (defun org-activate-footnote-links (limit)
5398 "Run through the buffer and add overlays to footnotes."
5399 (let ((fn (org-footnote-next-reference-or-definition limit)))
5400 (when fn
5401 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5402 (org-remove-flyspell-overlays-in beg end)
5403 (add-text-properties beg end
5404 (list 'mouse-face 'highlight
5405 'keymap org-mouse-map
5406 'help-echo
5407 (if (= (point-at-bol) beg)
5408 "Footnote definition"
5409 "Footnote reference")
5410 'font-lock-fontified t
5411 'font-lock-multiline t
5412 'face 'org-footnote))))))
5414 (defun org-activate-bracket-links (limit)
5415 "Run through the buffer and add overlays to bracketed links."
5416 (if (re-search-forward org-bracket-link-regexp limit t)
5417 (let* ((help (concat "LINK: "
5418 (org-match-string-no-properties 1)))
5419 ;; FIXME: above we should remove the escapes.
5420 ;; but that requires another match, protecting match data,
5421 ;; a lot of overhead for font-lock.
5422 (ip (org-maybe-intangible
5423 (list 'invisible 'org-link
5424 'keymap org-mouse-map 'mouse-face 'highlight
5425 'font-lock-multiline t 'help-echo help)))
5426 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5427 'font-lock-multiline t 'help-echo help)))
5428 ;; We need to remove the invisible property here. Table narrowing
5429 ;; may have made some of this invisible.
5430 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5431 (remove-text-properties (match-beginning 0) (match-end 0)
5432 '(invisible nil))
5433 (if (match-end 3)
5434 (progn
5435 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5436 (org-rear-nonsticky-at (match-beginning 3))
5437 (add-text-properties (match-beginning 3) (match-end 3) vp)
5438 (org-rear-nonsticky-at (match-end 3))
5439 (add-text-properties (match-end 3) (match-end 0) ip)
5440 (org-rear-nonsticky-at (match-end 0)))
5441 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5442 (org-rear-nonsticky-at (match-beginning 1))
5443 (add-text-properties (match-beginning 1) (match-end 1) vp)
5444 (org-rear-nonsticky-at (match-end 1))
5445 (add-text-properties (match-end 1) (match-end 0) ip)
5446 (org-rear-nonsticky-at (match-end 0)))
5447 t)))
5449 (defun org-activate-dates (limit)
5450 "Run through the buffer and add overlays to dates."
5451 (if (re-search-forward org-tsr-regexp-both limit t)
5452 (progn
5453 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5454 (add-text-properties (match-beginning 0) (match-end 0)
5455 (list 'mouse-face 'highlight
5456 'keymap org-mouse-map))
5457 (org-rear-nonsticky-at (match-end 0))
5458 (when org-display-custom-times
5459 (if (match-end 3)
5460 (org-display-custom-time (match-beginning 3) (match-end 3)))
5461 (org-display-custom-time (match-beginning 1) (match-end 1)))
5462 t)))
5464 (defvar org-target-link-regexp nil
5465 "Regular expression matching radio targets in plain text.")
5466 (make-variable-buffer-local 'org-target-link-regexp)
5467 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5468 "Regular expression matching a link target.")
5469 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5470 "Regular expression matching a radio target.")
5471 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5472 "Regular expression matching any target.")
5474 (defun org-activate-target-links (limit)
5475 "Run through the buffer and add overlays to target matches."
5476 (when org-target-link-regexp
5477 (let ((case-fold-search t))
5478 (if (re-search-forward org-target-link-regexp limit t)
5479 (progn
5480 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5481 (add-text-properties (match-beginning 0) (match-end 0)
5482 (list 'mouse-face 'highlight
5483 'keymap org-mouse-map
5484 'help-echo "Radio target link"
5485 'org-linked-text t))
5486 (org-rear-nonsticky-at (match-end 0))
5487 t)))))
5489 (defun org-update-radio-target-regexp ()
5490 "Find all radio targets in this file and update the regular expression."
5491 (interactive)
5492 (when (memq 'radio org-activate-links)
5493 (setq org-target-link-regexp
5494 (org-make-target-link-regexp (org-all-targets 'radio)))
5495 (org-restart-font-lock)))
5497 (defun org-hide-wide-columns (limit)
5498 (let (s e)
5499 (setq s (text-property-any (point) (or limit (point-max))
5500 'org-cwidth t))
5501 (when s
5502 (setq e (next-single-property-change s 'org-cwidth))
5503 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5504 (goto-char e)
5505 t)))
5507 (defvar org-latex-and-specials-regexp nil
5508 "Regular expression for highlighting export special stuff.")
5509 (defvar org-match-substring-regexp)
5510 (defvar org-match-substring-with-braces-regexp)
5512 ;; This should be with the exporter code, but we also use if for font-locking
5513 (defconst org-export-html-special-string-regexps
5514 '(("\\\\-" . "&shy;")
5515 ("---\\([^-]\\)" . "&mdash;\\1")
5516 ("--\\([^-]\\)" . "&ndash;\\1")
5517 ("\\.\\.\\." . "&hellip;"))
5518 "Regular expressions for special string conversion.")
5521 (defun org-compute-latex-and-specials-regexp ()
5522 "Compute regular expression for stuff treated specially by exporters."
5523 (if (not org-highlight-latex-fragments-and-specials)
5524 (org-set-local 'org-latex-and-specials-regexp nil)
5525 (require 'org-exp)
5526 (let*
5527 ((matchers (plist-get org-format-latex-options :matchers))
5528 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5529 org-latex-regexps)))
5530 (org-export-allow-BIND nil)
5531 (options (org-combine-plists (org-default-export-plist)
5532 (org-infile-export-plist)))
5533 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5534 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5535 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5536 (org-export-html-expand (plist-get options :expand-quoted-html))
5537 (org-export-with-special-strings (plist-get options :special-strings))
5538 (re-sub
5539 (cond
5540 ((equal org-export-with-sub-superscripts '{})
5541 (list org-match-substring-with-braces-regexp))
5542 (org-export-with-sub-superscripts
5543 (list org-match-substring-regexp))
5544 (t nil)))
5545 (re-latex
5546 (if org-export-with-LaTeX-fragments
5547 (mapcar (lambda (x) (nth 1 x)) latexs)))
5548 (re-macros
5549 (if org-export-with-TeX-macros
5550 (list (concat "\\\\"
5551 (regexp-opt
5552 (append
5554 (delq nil
5555 (mapcar 'car-safe
5556 (append org-entities-user
5557 org-entities)))
5558 (if (boundp 'org-latex-entities)
5559 (mapcar (lambda (x)
5560 (or (car-safe x) x))
5561 org-latex-entities)
5562 nil))
5563 'words))) ; FIXME
5565 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5566 (re-special (if org-export-with-special-strings
5567 (mapcar (lambda (x) (car x))
5568 org-export-html-special-string-regexps)))
5569 (re-rest
5570 (delq nil
5571 (list
5572 (if org-export-html-expand "@<[^>\n]+>")
5573 ))))
5574 (org-set-local
5575 'org-latex-and-specials-regexp
5576 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5577 re-rest) "\\|")))))
5579 (defun org-do-latex-and-special-faces (limit)
5580 "Run through the buffer and add overlays to links."
5581 (when org-latex-and-specials-regexp
5582 (let (rtn d)
5583 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5584 limit t))
5585 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5586 'face))
5587 '(org-code org-verbatim underline)))
5588 (progn
5589 (setq rtn t
5590 d (cond ((member (char-after (1+ (match-beginning 0)))
5591 '(?_ ?^)) 1)
5592 (t 0)))
5593 (font-lock-prepend-text-property
5594 (+ d (match-beginning 0)) (match-end 0)
5595 'face 'org-latex-and-export-specials)
5596 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5597 '(font-lock-multiline t)))))
5598 rtn)))
5600 (defun org-restart-font-lock ()
5601 "Restart `font-lock-mode', to force refontification."
5602 (when (and (boundp 'font-lock-mode) font-lock-mode)
5603 (font-lock-mode -1)
5604 (font-lock-mode 1)))
5606 (defun org-all-targets (&optional radio)
5607 "Return a list of all targets in this file.
5608 With optional argument RADIO, only find radio targets."
5609 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5610 rtn)
5611 (save-excursion
5612 (goto-char (point-min))
5613 (while (re-search-forward re nil t)
5614 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5615 rtn)))
5617 (defun org-make-target-link-regexp (targets)
5618 "Make regular expression matching all strings in TARGETS.
5619 The regular expression finds the targets also if there is a line break
5620 between words."
5621 (and targets
5622 (concat
5623 "\\<\\("
5624 (mapconcat
5625 (lambda (x)
5626 (setq x (regexp-quote x))
5627 (while (string-match " +" x)
5628 (setq x (replace-match "\\s-+" t t x)))
5630 targets
5631 "\\|")
5632 "\\)\\>")))
5634 (defun org-activate-tags (limit)
5635 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5636 (progn
5637 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5638 (add-text-properties (match-beginning 1) (match-end 1)
5639 (list 'mouse-face 'highlight
5640 'keymap org-mouse-map))
5641 (org-rear-nonsticky-at (match-end 1))
5642 t)))
5644 (defun org-outline-level ()
5645 "Compute the outline level of the heading at point.
5646 This function assumes that the cursor is at the beginning of a line matched
5647 by `outline-regexp'. Otherwise it returns garbage.
5648 If this is called at a normal headline, the level is the number of stars.
5649 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5650 (save-excursion
5651 (looking-at org-outline-regexp)
5652 (1- (- (match-end 0) (match-beginning 0)))))
5654 (defvar org-font-lock-keywords nil)
5656 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5657 "Regular expression matching a property line.")
5659 (defvar org-font-lock-hook nil
5660 "Functions to be called for special font lock stuff.")
5662 (defvar org-font-lock-set-keywords-hook nil
5663 "Functions that can manipulate `org-font-lock-extra-keywords'.
5664 This is calles after `org-font-lock-extra-keywords' is defined, but before
5665 it is installed to be used by font lock. This can be useful if something
5666 needs to be inserted at a specific position in the font-lock sequence.")
5668 (defun org-font-lock-hook (limit)
5669 (run-hook-with-args 'org-font-lock-hook limit))
5671 (defun org-set-font-lock-defaults ()
5672 (let* ((em org-fontify-emphasized-text)
5673 (lk org-activate-links)
5674 (org-font-lock-extra-keywords
5675 (list
5676 ;; Call the hook
5677 '(org-font-lock-hook)
5678 ;; Headlines
5679 `(,(if org-fontify-whole-heading-line
5680 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5681 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5682 (1 (org-get-level-face 1))
5683 (2 (org-get-level-face 2))
5684 (3 (org-get-level-face 3)))
5685 ;; Table lines
5686 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5687 (1 'org-table t))
5688 ;; Table internals
5689 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5690 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5691 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5692 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5693 ;; Drawers
5694 (list org-drawer-regexp '(0 'org-special-keyword t))
5695 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5696 ;; Properties
5697 (list org-property-re
5698 '(1 'org-special-keyword t)
5699 '(3 'org-property-value t))
5700 ;; Links
5701 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5702 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5703 (if (memq 'plain lk) '(org-activate-plain-links))
5704 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5705 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5706 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5707 (if (memq 'footnote lk) '(org-activate-footnote-links))
5708 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5709 '(org-hide-wide-columns (0 nil append))
5710 ;; TODO lines
5711 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5712 '(1 (org-get-todo-face 1) t))
5713 ;; DONE
5714 (if org-fontify-done-headline
5715 (list (concat "^[*]+ +\\<\\("
5716 (mapconcat 'regexp-quote org-done-keywords "\\|")
5717 "\\)\\(.*\\)")
5718 '(2 'org-headline-done t))
5719 nil)
5720 ;; Priorities
5721 '(org-font-lock-add-priority-faces)
5722 ;; Tags
5723 '(org-font-lock-add-tag-faces)
5724 ;; Special keywords
5725 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5726 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5727 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5728 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5729 ;; Emphasis
5730 (if em
5731 (if (featurep 'xemacs)
5732 '(org-do-emphasis-faces (0 nil append))
5733 '(org-do-emphasis-faces)))
5734 ;; Checkboxes
5735 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5736 1 'org-checkbox prepend)
5737 (if (cdr (assq 'checkbox org-list-automatic-rules))
5738 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5739 (0 (org-get-checkbox-statistics-face) t)))
5740 ;; Description list items
5741 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5742 1 'bold prepend)
5743 ;; ARCHIVEd headings
5744 (list (concat
5745 org-outline-regexp-bol
5746 "\\(.*:" org-archive-tag ":.*\\)")
5747 '(1 'org-archived prepend))
5748 ;; Specials
5749 '(org-do-latex-and-special-faces)
5750 '(org-fontify-entities)
5751 '(org-raise-scripts)
5752 ;; Code
5753 '(org-activate-code (1 'org-code t))
5754 ;; COMMENT
5755 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5756 "\\|" org-quote-string "\\)\\>")
5757 '(1 'org-special-keyword t))
5758 '("^#.*" (0 'font-lock-comment-face t))
5759 ;; Blocks and meta lines
5760 '(org-fontify-meta-lines-and-blocks)
5762 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5763 (run-hooks 'org-font-lock-set-keywords-hook)
5764 ;; Now set the full font-lock-keywords
5765 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5766 (org-set-local 'font-lock-defaults
5767 '(org-font-lock-keywords t nil nil backward-paragraph))
5768 (kill-local-variable 'font-lock-keywords) nil))
5770 (defun org-toggle-pretty-entities ()
5771 "Toggle the composition display of entities as UTF8 characters."
5772 (interactive)
5773 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5774 (org-restart-font-lock)
5775 (if org-pretty-entities
5776 (message "Entities are displayed as UTF8 characers")
5777 (save-restriction
5778 (widen)
5779 (org-decompose-region (point-min) (point-max))
5780 (message "Entities are displayed plain"))))
5782 (defun org-fontify-entities (limit)
5783 "Find an entity to fontify."
5784 (let (ee)
5785 (when org-pretty-entities
5786 (catch 'match
5787 (while (re-search-forward
5788 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5789 limit t)
5790 (if (and (not (org-in-indented-comment-line))
5791 (setq ee (org-entity-get (match-string 1)))
5792 (= (length (nth 6 ee)) 1))
5793 (progn
5794 (add-text-properties
5795 (match-beginning 0) (match-end 1)
5796 (list 'font-lock-fontified t))
5797 (compose-region (match-beginning 0) (match-end 1)
5798 (nth 6 ee) nil)
5799 (backward-char 1)
5800 (throw 'match t))))
5801 nil))))
5803 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5804 "Fontify string S like in Org-mode."
5805 (with-temp-buffer
5806 (insert s)
5807 (let ((org-odd-levels-only odd-levels))
5808 (org-mode)
5809 (font-lock-fontify-buffer)
5810 (buffer-string))))
5812 (defvar org-m nil)
5813 (defvar org-l nil)
5814 (defvar org-f nil)
5815 (defun org-get-level-face (n)
5816 "Get the right face for match N in font-lock matching of headlines."
5817 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5818 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5819 (if org-cycle-level-faces
5820 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5821 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5822 (cond
5823 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5824 ((eq n 2) org-f)
5825 (t (if org-level-color-stars-only nil org-f))))
5828 (defun org-get-todo-face (kwd)
5829 "Get the right face for a TODO keyword KWD.
5830 If KWD is a number, get the corresponding match group."
5831 (if (numberp kwd) (setq kwd (match-string kwd)))
5832 (or (org-face-from-face-or-color
5833 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5834 (and (member kwd org-done-keywords) 'org-done)
5835 'org-todo))
5837 (defun org-face-from-face-or-color (context inherit face-or-color)
5838 "Create a face list that inherits INHERIT, but sets the foreground color.
5839 When FACE-OR-COLOR is not a string, just return it."
5840 (if (stringp face-or-color)
5841 (list :inherit inherit
5842 (cdr (assoc context org-faces-easy-properties))
5843 face-or-color)
5844 face-or-color))
5846 (defun org-font-lock-add-tag-faces (limit)
5847 "Add the special tag faces."
5848 (when (and org-tag-faces org-tags-special-faces-re)
5849 (while (re-search-forward org-tags-special-faces-re limit t)
5850 (add-text-properties (match-beginning 1) (match-end 1)
5851 (list 'face (org-get-tag-face 1)
5852 'font-lock-fontified t))
5853 (backward-char 1))))
5855 (defun org-font-lock-add-priority-faces (limit)
5856 "Add the special priority faces."
5857 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5858 (add-text-properties
5859 (match-beginning 0) (match-end 0)
5860 (list 'face (or (org-face-from-face-or-color
5861 'priority 'org-special-keyword
5862 (cdr (assoc (char-after (match-beginning 1))
5863 org-priority-faces)))
5864 'org-special-keyword)
5865 'font-lock-fontified t))))
5867 (defun org-get-tag-face (kwd)
5868 "Get the right face for a TODO keyword KWD.
5869 If KWD is a number, get the corresponding match group."
5870 (if (numberp kwd) (setq kwd (match-string kwd)))
5871 (or (org-face-from-face-or-color
5872 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5873 'org-tag))
5875 (defun org-unfontify-region (beg end &optional maybe_loudly)
5876 "Remove fontification and activation overlays from links."
5877 (font-lock-default-unfontify-region beg end)
5878 (let* ((buffer-undo-list t)
5879 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5880 (inhibit-modification-hooks t)
5881 deactivate-mark buffer-file-name buffer-file-truename)
5882 (org-decompose-region beg end)
5883 (remove-text-properties beg end
5884 '(mouse-face t keymap t org-linked-text t
5885 invisible t intangible t
5886 org-no-flyspell t org-emphasis t))
5887 (org-remove-font-lock-display-properties beg end)))
5889 (defconst org-script-display '(((raise -0.3) (height 0.7))
5890 ((raise 0.3) (height 0.7))
5891 ((raise -0.5))
5892 ((raise 0.5)))
5893 "Display properties for showing superscripts and subscripts.")
5895 (defun org-remove-font-lock-display-properties (beg end)
5896 "Remove specific display properties that have been added by font lock.
5897 The will remove the raise properties that are used to show superscripts
5898 and subscripts."
5899 (let (next prop)
5900 (while (< beg end)
5901 (setq next (next-single-property-change beg 'display nil end)
5902 prop (get-text-property beg 'display))
5903 (if (member prop org-script-display)
5904 (put-text-property beg next 'display nil))
5905 (setq beg next))))
5907 (defun org-raise-scripts (limit)
5908 "Add raise properties to sub/superscripts."
5909 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5910 (if (re-search-forward
5911 (if (eq org-use-sub-superscripts t)
5912 org-match-substring-regexp
5913 org-match-substring-with-braces-regexp)
5914 limit t)
5915 (let* ((pos (point)) table-p comment-p
5916 (mpos (match-beginning 3))
5917 (emph-p (get-text-property mpos 'org-emphasis))
5918 (link-p (get-text-property mpos 'mouse-face))
5919 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5920 (goto-char (point-at-bol))
5921 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5922 comment-p (org-looking-at-p "[ \t]*#"))
5923 (goto-char pos)
5924 ;; FIXME: Should we go back one character here, for a_b^c
5925 ;; (goto-char (1- pos)) ;????????????????????
5926 (if (or comment-p emph-p link-p keyw-p)
5928 (put-text-property (match-beginning 3) (match-end 0)
5929 'display
5930 (if (equal (char-after (match-beginning 2)) ?^)
5931 (nth (if table-p 3 1) org-script-display)
5932 (nth (if table-p 2 0) org-script-display)))
5933 (add-text-properties (match-beginning 2) (match-end 2)
5934 (list 'invisible t
5935 'org-dwidth t 'org-dwidth-n 1))
5936 (if (and (eq (char-after (match-beginning 3)) ?{)
5937 (eq (char-before (match-end 3)) ?}))
5938 (progn
5939 (add-text-properties
5940 (match-beginning 3) (1+ (match-beginning 3))
5941 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5942 (add-text-properties
5943 (1- (match-end 3)) (match-end 3)
5944 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5945 t)))))
5947 ;;;; Visibility cycling, including org-goto and indirect buffer
5949 ;;; Cycling
5951 (defvar org-cycle-global-status nil)
5952 (make-variable-buffer-local 'org-cycle-global-status)
5953 (defvar org-cycle-subtree-status nil)
5954 (make-variable-buffer-local 'org-cycle-subtree-status)
5956 ;;;###autoload
5958 (defvar org-inlinetask-min-level)
5960 (defun org-cycle (&optional arg)
5961 "TAB-action and visibility cycling for Org-mode.
5963 This is the command invoked in Org-mode by the TAB key. Its main purpose
5964 is outline visibility cycling, but it also invokes other actions
5965 in special contexts.
5967 - When this function is called with a prefix argument, rotate the entire
5968 buffer through 3 states (global cycling)
5969 1. OVERVIEW: Show only top-level headlines.
5970 2. CONTENTS: Show all headlines of all levels, but no body text.
5971 3. SHOW ALL: Show everything.
5972 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5973 determined by the variable `org-startup-folded', and by any VISIBILITY
5974 properties in the buffer.
5975 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5976 including any drawers.
5978 - When inside a table, re-align the table and move to the next field.
5980 - When point is at the beginning of a headline, rotate the subtree started
5981 by this line through 3 different states (local cycling)
5982 1. FOLDED: Only the main headline is shown.
5983 2. CHILDREN: The main headline and the direct children are shown.
5984 From this state, you can move to one of the children
5985 and zoom in further.
5986 3. SUBTREE: Show the entire subtree, including body text.
5987 If there is no subtree, switch directly from CHILDREN to FOLDED.
5989 - When point is at the beginning of an empty headline and the variable
5990 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5991 of the headline by demoting and promoting it to likely levels. This
5992 speeds up creation document structure by pressing TAB once or several
5993 times right after creating a new headline.
5995 - When there is a numeric prefix, go up to a heading with level ARG, do
5996 a `show-subtree' and return to the previous cursor position. If ARG
5997 is negative, go up that many levels.
5999 - When point is not at the beginning of a headline, execute the global
6000 binding for TAB, which is re-indenting the line. See the option
6001 `org-cycle-emulate-tab' for details.
6003 - Special case: if point is at the beginning of the buffer and there is
6004 no headline in line 1, this function will act as if called with prefix arg
6005 (C-u TAB, same as S-TAB) also when called without prefix arg.
6006 But only if also the variable `org-cycle-global-at-bob' is t."
6007 (interactive "P")
6008 (org-load-modules-maybe)
6009 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6010 (and org-cycle-level-after-item/entry-creation
6011 (or (org-cycle-level)
6012 (org-cycle-item-indentation))))
6013 (let* ((limit-level
6014 (or org-cycle-max-level
6015 (and (boundp 'org-inlinetask-min-level)
6016 org-inlinetask-min-level
6017 (1- org-inlinetask-min-level))))
6018 (nstars (and limit-level
6019 (if org-odd-levels-only
6020 (and limit-level (1- (* limit-level 2)))
6021 limit-level)))
6022 (org-outline-regexp
6023 (if (not (org-mode-p))
6024 outline-regexp
6025 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6026 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6027 (not (looking-at org-outline-regexp))))
6028 (org-cycle-hook
6029 (if bob-special
6030 (delq 'org-optimize-window-after-visibility-change
6031 (copy-sequence org-cycle-hook))
6032 org-cycle-hook))
6033 (pos (point)))
6035 (if (or bob-special (equal arg '(4)))
6036 ;; special case: use global cycling
6037 (setq arg t))
6039 (cond
6041 ((equal arg '(16))
6042 (setq last-command 'dummy)
6043 (org-set-startup-visibility)
6044 (message "Startup visibility, plus VISIBILITY properties"))
6046 ((equal arg '(64))
6047 (show-all)
6048 (message "Entire buffer visible, including drawers"))
6050 ;; Table: enter it or move to the next field.
6051 ((org-at-table-p 'any)
6052 (if (org-at-table.el-p)
6053 (message "Use C-c ' to edit table.el tables")
6054 (if arg (org-table-edit-field t)
6055 (org-table-justify-field-maybe)
6056 (call-interactively 'org-table-next-field))))
6058 ((run-hook-with-args-until-success
6059 'org-tab-after-check-for-table-hook))
6061 ;; Global cycling: delegate to `org-cycle-internal-global'.
6062 ((eq arg t) (org-cycle-internal-global))
6064 ;; Drawers: delegate to `org-flag-drawer'.
6065 ((and org-drawers org-drawer-regexp
6066 (save-excursion
6067 (beginning-of-line 1)
6068 (looking-at org-drawer-regexp)))
6069 (org-flag-drawer ; toggle block visibility
6070 (not (get-char-property (match-end 0) 'invisible))))
6072 ;; Show-subtree, ARG levels up from here.
6073 ((integerp arg)
6074 (save-excursion
6075 (org-back-to-heading)
6076 (outline-up-heading (if (< arg 0) (- arg)
6077 (- (funcall outline-level) arg)))
6078 (org-show-subtree)))
6080 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6081 ((and (featurep 'org-inlinetask)
6082 (org-inlinetask-at-task-p)
6083 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6084 (org-inlinetask-toggle-visibility))
6086 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6087 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6088 (save-excursion (beginning-of-line 1)
6089 (looking-at org-outline-regexp)))
6090 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6091 (org-cycle-internal-local))
6093 ;; From there: TAB emulation and template completion.
6094 (buffer-read-only (org-back-to-heading))
6096 ((run-hook-with-args-until-success
6097 'org-tab-after-check-for-cycling-hook))
6099 ((org-try-structure-completion))
6101 ((org-try-cdlatex-tab))
6103 ((run-hook-with-args-until-success
6104 'org-tab-before-tab-emulation-hook))
6106 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6107 (or (not (bolp))
6108 (not (looking-at org-outline-regexp))))
6109 (call-interactively (global-key-binding "\t")))
6111 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6112 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6113 (or (and (eq org-cycle-emulate-tab 'white)
6114 (= (match-end 0) (point-at-eol)))
6115 (and (eq org-cycle-emulate-tab 'whitestart)
6116 (>= (match-end 0) pos))))
6118 (eq org-cycle-emulate-tab t))
6119 (call-interactively (global-key-binding "\t")))
6121 (t (save-excursion
6122 (org-back-to-heading)
6123 (org-cycle)))))))
6125 (defun org-cycle-internal-global ()
6126 "Do the global cycling action."
6127 (cond
6128 ((and (eq last-command this-command)
6129 (eq org-cycle-global-status 'overview))
6130 ;; We just created the overview - now do table of contents
6131 ;; This can be slow in very large buffers, so indicate action
6132 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6133 (message "CONTENTS...")
6134 (org-content)
6135 (message "CONTENTS...done")
6136 (setq org-cycle-global-status 'contents)
6137 (run-hook-with-args 'org-cycle-hook 'contents))
6139 ((and (eq last-command this-command)
6140 (eq org-cycle-global-status 'contents))
6141 ;; We just showed the table of contents - now show everything
6142 (run-hook-with-args 'org-pre-cycle-hook 'all)
6143 (show-all)
6144 (message "SHOW ALL")
6145 (setq org-cycle-global-status 'all)
6146 (run-hook-with-args 'org-cycle-hook 'all))
6149 ;; Default action: go to overview
6150 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6151 (org-overview)
6152 (message "OVERVIEW")
6153 (setq org-cycle-global-status 'overview)
6154 (run-hook-with-args 'org-cycle-hook 'overview))))
6156 (defun org-cycle-internal-local ()
6157 "Do the local cycling action."
6158 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6159 ;; First, determine end of headline (EOH), end of subtree or item
6160 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6161 (save-excursion
6162 (if (org-at-item-p)
6163 (progn
6164 (beginning-of-line)
6165 (setq struct (org-list-struct))
6166 (setq eoh (point-at-eol))
6167 (setq eos (org-list-get-item-end-before-blank (point) struct))
6168 (setq has-children (org-list-has-child-p (point) struct)))
6169 (org-back-to-heading)
6170 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6171 (setq eos (save-excursion
6172 (org-end-of-subtree t)
6173 (unless (eobp)
6174 (skip-chars-forward " \t\n"))
6175 (if (eobp) (point) (1- (point)))))
6176 (setq has-children
6177 (or (save-excursion
6178 (let ((level (funcall outline-level)))
6179 (outline-next-heading)
6180 (and (org-at-heading-p t)
6181 (> (funcall outline-level) level))))
6182 (save-excursion
6183 (org-list-search-forward (org-item-beginning-re) eos t)))))
6184 ;; Determine end invisible part of buffer (EOL)
6185 (beginning-of-line 2)
6186 ;; XEmacs doesn't have `next-single-char-property-change'
6187 (if (featurep 'xemacs)
6188 (while (and (not (eobp)) ;; this is like `next-line'
6189 (get-char-property (1- (point)) 'invisible))
6190 (beginning-of-line 2))
6191 (while (and (not (eobp)) ;; this is like `next-line'
6192 (get-char-property (1- (point)) 'invisible))
6193 (goto-char (next-single-char-property-change (point) 'invisible))
6194 (and (eolp) (beginning-of-line 2))))
6195 (setq eol (point)))
6196 ;; Find out what to do next and set `this-command'
6197 (cond
6198 ((= eos eoh)
6199 ;; Nothing is hidden behind this heading
6200 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6201 (message "EMPTY ENTRY")
6202 (setq org-cycle-subtree-status nil)
6203 (save-excursion
6204 (goto-char eos)
6205 (outline-next-heading)
6206 (if (outline-invisible-p) (org-flag-heading nil))))
6207 ((and (or (>= eol eos)
6208 (not (string-match "\\S-" (buffer-substring eol eos))))
6209 (or has-children
6210 (not (setq children-skipped
6211 org-cycle-skip-children-state-if-no-children))))
6212 ;; Entire subtree is hidden in one line: children view
6213 (run-hook-with-args 'org-pre-cycle-hook 'children)
6214 (if (org-at-item-p)
6215 (org-list-set-item-visibility (point-at-bol) struct 'children)
6216 (org-show-entry)
6217 (show-children)
6218 ;; Fold every list in subtree to top-level items.
6219 (when (eq org-cycle-include-plain-lists 'integrate)
6220 (save-excursion
6221 (org-back-to-heading)
6222 (while (org-list-search-forward (org-item-beginning-re) eos t)
6223 (beginning-of-line 1)
6224 (let* ((struct (org-list-struct))
6225 (prevs (org-list-prevs-alist struct))
6226 (end (org-list-get-bottom-point struct)))
6227 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6228 (org-list-get-all-items (point) struct prevs))
6229 (goto-char end))))))
6230 (message "CHILDREN")
6231 (save-excursion
6232 (goto-char eos)
6233 (outline-next-heading)
6234 (if (outline-invisible-p) (org-flag-heading nil)))
6235 (setq org-cycle-subtree-status 'children)
6236 (run-hook-with-args 'org-cycle-hook 'children))
6237 ((or children-skipped
6238 (and (eq last-command this-command)
6239 (eq org-cycle-subtree-status 'children)))
6240 ;; We just showed the children, or no children are there,
6241 ;; now show everything.
6242 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6243 (outline-flag-region eoh eos nil)
6244 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6245 (setq org-cycle-subtree-status 'subtree)
6246 (run-hook-with-args 'org-cycle-hook 'subtree))
6248 ;; Default action: hide the subtree.
6249 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6250 (outline-flag-region eoh eos t)
6251 (message "FOLDED")
6252 (setq org-cycle-subtree-status 'folded)
6253 (run-hook-with-args 'org-cycle-hook 'folded)))))
6255 ;;;###autoload
6256 (defun org-global-cycle (&optional arg)
6257 "Cycle the global visibility. For details see `org-cycle'.
6258 With \\[universal-argument] prefix arg, switch to startup visibility.
6259 With a numeric prefix, show all headlines up to that level."
6260 (interactive "P")
6261 (let ((org-cycle-include-plain-lists
6262 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6263 (cond
6264 ((integerp arg)
6265 (show-all)
6266 (hide-sublevels arg)
6267 (setq org-cycle-global-status 'contents))
6268 ((equal arg '(4))
6269 (org-set-startup-visibility)
6270 (message "Startup visibility, plus VISIBILITY properties."))
6272 (org-cycle '(4))))))
6274 (defun org-set-startup-visibility ()
6275 "Set the visibility required by startup options and properties."
6276 (cond
6277 ((eq org-startup-folded t)
6278 (org-cycle '(4)))
6279 ((eq org-startup-folded 'content)
6280 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6281 (org-cycle '(4)) (org-cycle '(4)))))
6282 (unless (eq org-startup-folded 'showeverything)
6283 (if org-hide-block-startup (org-hide-block-all))
6284 (org-set-visibility-according-to-property 'no-cleanup)
6285 (org-cycle-hide-archived-subtrees 'all)
6286 (org-cycle-hide-drawers 'all)
6287 (org-cycle-show-empty-lines t)))
6289 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6290 "Switch subtree visibilities according to :VISIBILITY: property."
6291 (interactive)
6292 (let (org-show-entry-below state)
6293 (save-excursion
6294 (goto-char (point-min))
6295 (while (re-search-forward
6296 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6297 nil t)
6298 (setq state (match-string 1))
6299 (save-excursion
6300 (org-back-to-heading t)
6301 (hide-subtree)
6302 (org-reveal)
6303 (cond
6304 ((equal state '("fold" "folded"))
6305 (hide-subtree))
6306 ((equal state "children")
6307 (org-show-hidden-entry)
6308 (show-children))
6309 ((equal state "content")
6310 (save-excursion
6311 (save-restriction
6312 (org-narrow-to-subtree)
6313 (org-content))))
6314 ((member state '("all" "showall"))
6315 (show-subtree)))))
6316 (unless no-cleanup
6317 (org-cycle-hide-archived-subtrees 'all)
6318 (org-cycle-hide-drawers 'all)
6319 (org-cycle-show-empty-lines 'all)))))
6321 ;; This function uses outline-regexp instead of the more fundamental
6322 ;; org-outline-regexp so that org-cycle-global works outside of Org
6323 ;; buffers, where outline-regexp is needed.
6324 (defun org-overview ()
6325 "Switch to overview mode, showing only top-level headlines.
6326 Really, this shows all headlines with level equal or greater than the level
6327 of the first headline in the buffer. This is important, because if the
6328 first headline is not level one, then (hide-sublevels 1) gives confusing
6329 results."
6330 (interactive)
6331 (let ((level (save-excursion
6332 (goto-char (point-min))
6333 (if (re-search-forward (concat "^" outline-regexp) nil t)
6334 (progn
6335 (goto-char (match-beginning 0))
6336 (funcall outline-level))))))
6337 (and level (hide-sublevels level))))
6339 (defun org-content (&optional arg)
6340 "Show all headlines in the buffer, like a table of contents.
6341 With numerical argument N, show content up to level N."
6342 (interactive "P")
6343 (save-excursion
6344 ;; Visit all headings and show their offspring
6345 (and (integerp arg) (org-overview))
6346 (goto-char (point-max))
6347 (catch 'exit
6348 (while (and (progn (condition-case nil
6349 (outline-previous-visible-heading 1)
6350 (error (goto-char (point-min))))
6352 (looking-at org-outline-regexp))
6353 (if (integerp arg)
6354 (show-children (1- arg))
6355 (show-branches))
6356 (if (bobp) (throw 'exit nil))))))
6359 (defun org-optimize-window-after-visibility-change (state)
6360 "Adjust the window after a change in outline visibility.
6361 This function is the default value of the hook `org-cycle-hook'."
6362 (when (get-buffer-window (current-buffer))
6363 (cond
6364 ((eq state 'content) nil)
6365 ((eq state 'all) nil)
6366 ((eq state 'folded) nil)
6367 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6368 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6370 (defun org-remove-empty-overlays-at (pos)
6371 "Remove outline overlays that do not contain non-white stuff."
6372 (mapc
6373 (lambda (o)
6374 (and (eq 'outline (overlay-get o 'invisible))
6375 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6376 (overlay-end o))))
6377 (delete-overlay o)))
6378 (overlays-at pos)))
6380 (defun org-clean-visibility-after-subtree-move ()
6381 "Fix visibility issues after moving a subtree."
6382 ;; First, find a reasonable region to look at:
6383 ;; Start two siblings above, end three below
6384 (let* ((beg (save-excursion
6385 (and (org-get-last-sibling)
6386 (org-get-last-sibling))
6387 (point)))
6388 (end (save-excursion
6389 (and (org-get-next-sibling)
6390 (org-get-next-sibling)
6391 (org-get-next-sibling))
6392 (if (org-at-heading-p)
6393 (point-at-eol)
6394 (point))))
6395 (level (looking-at "\\*+"))
6396 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6397 (save-excursion
6398 (save-restriction
6399 (narrow-to-region beg end)
6400 (when re
6401 ;; Properly fold already folded siblings
6402 (goto-char (point-min))
6403 (while (re-search-forward re nil t)
6404 (if (and (not (outline-invisible-p))
6405 (save-excursion
6406 (goto-char (point-at-eol)) (outline-invisible-p)))
6407 (hide-entry))))
6408 (org-cycle-show-empty-lines 'overview)
6409 (org-cycle-hide-drawers 'overview)))))
6411 (defun org-cycle-show-empty-lines (state)
6412 "Show empty lines above all visible headlines.
6413 The region to be covered depends on STATE when called through
6414 `org-cycle-hook'. Lisp program can use t for STATE to get the
6415 entire buffer covered. Note that an empty line is only shown if there
6416 are at least `org-cycle-separator-lines' empty lines before the headline."
6417 (when (not (= org-cycle-separator-lines 0))
6418 (save-excursion
6419 (let* ((n (abs org-cycle-separator-lines))
6420 (re (cond
6421 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6422 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6423 (t (let ((ns (number-to-string (- n 2))))
6424 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6425 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6426 beg end b e)
6427 (cond
6428 ((memq state '(overview contents t))
6429 (setq beg (point-min) end (point-max)))
6430 ((memq state '(children folded))
6431 (setq beg (point) end (progn (org-end-of-subtree t t)
6432 (beginning-of-line 2)
6433 (point)))))
6434 (when beg
6435 (goto-char beg)
6436 (while (re-search-forward re end t)
6437 (unless (get-char-property (match-end 1) 'invisible)
6438 (setq e (match-end 1))
6439 (if (< org-cycle-separator-lines 0)
6440 (setq b (save-excursion
6441 (goto-char (match-beginning 0))
6442 (org-back-over-empty-lines)
6443 (if (save-excursion
6444 (goto-char (max (point-min) (1- (point))))
6445 (org-on-heading-p))
6446 (1- (point))
6447 (point))))
6448 (setq b (match-beginning 1)))
6449 (outline-flag-region b e nil)))))))
6450 ;; Never hide empty lines at the end of the file.
6451 (save-excursion
6452 (goto-char (point-max))
6453 (outline-previous-heading)
6454 (outline-end-of-heading)
6455 (if (and (looking-at "[ \t\n]+")
6456 (= (match-end 0) (point-max)))
6457 (outline-flag-region (point) (match-end 0) nil))))
6459 (defun org-show-empty-lines-in-parent ()
6460 "Move to the parent and re-show empty lines before visible headlines."
6461 (save-excursion
6462 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6463 (org-cycle-show-empty-lines context))))
6465 (defun org-files-list ()
6466 "Return `org-agenda-files' list, plus all open org-mode files.
6467 This is useful for operations that need to scan all of a user's
6468 open and agenda-wise Org files."
6469 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6470 (dolist (buf (buffer-list))
6471 (with-current-buffer buf
6472 (if (and (org-mode-p) (buffer-file-name))
6473 (let ((file (expand-file-name (buffer-file-name))))
6474 (unless (member file files)
6475 (push file files))))))
6476 files))
6478 (defsubst org-entry-beginning-position ()
6479 "Return the beginning position of the current entry."
6480 (save-excursion (outline-back-to-heading t) (point)))
6482 (defsubst org-entry-end-position ()
6483 "Return the end position of the current entry."
6484 (save-excursion (outline-next-heading) (point)))
6486 (defun org-cycle-hide-drawers (state)
6487 "Re-hide all drawers after a visibility state change."
6488 (when (and (org-mode-p)
6489 (not (memq state '(overview folded contents))))
6490 (save-excursion
6491 (let* ((globalp (memq state '(contents all)))
6492 (beg (if globalp (point-min) (point)))
6493 (end (if globalp (point-max)
6494 (if (eq state 'children)
6495 (save-excursion (outline-next-heading) (point))
6496 (org-end-of-subtree t)))))
6497 (goto-char beg)
6498 (while (re-search-forward org-drawer-regexp end t)
6499 (org-flag-drawer t))))))
6501 (defun org-flag-drawer (flag)
6502 (save-excursion
6503 (beginning-of-line 1)
6504 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6505 (let ((b (match-end 0)))
6506 (if (re-search-forward
6507 "^[ \t]*:END:"
6508 (save-excursion (outline-next-heading) (point)) t)
6509 (outline-flag-region b (point-at-eol) flag)
6510 (error ":END: line missing at position %s" b))))))
6512 (defun org-subtree-end-visible-p ()
6513 "Is the end of the current subtree visible?"
6514 (pos-visible-in-window-p
6515 (save-excursion (org-end-of-subtree t) (point))))
6517 (defun org-first-headline-recenter (&optional N)
6518 "Move cursor to the first headline and recenter the headline.
6519 Optional argument N means put the headline into the Nth line of the window."
6520 (goto-char (point-min))
6521 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6522 (beginning-of-line)
6523 (recenter (prefix-numeric-value N))))
6525 ;;; Saving and restoring visibility
6527 (defun org-outline-overlay-data (&optional use-markers)
6528 "Return a list of the locations of all outline overlays.
6529 These are overlays with the `invisible' property value `outline'.
6530 The return value is a list of cons cells, with start and stop
6531 positions for each overlay.
6532 If USE-MARKERS is set, return the positions as markers."
6533 (let (beg end)
6534 (save-excursion
6535 (save-restriction
6536 (widen)
6537 (delq nil
6538 (mapcar (lambda (o)
6539 (when (eq (overlay-get o 'invisible) 'outline)
6540 (setq beg (overlay-start o)
6541 end (overlay-end o))
6542 (and beg end (> end beg)
6543 (if use-markers
6544 (cons (move-marker (make-marker) beg)
6545 (move-marker (make-marker) end))
6546 (cons beg end)))))
6547 (overlays-in (point-min) (point-max))))))))
6549 (defun org-set-outline-overlay-data (data)
6550 "Create visibility overlays for all positions in DATA.
6551 DATA should have been made by `org-outline-overlay-data'."
6552 (let (o)
6553 (save-excursion
6554 (save-restriction
6555 (widen)
6556 (show-all)
6557 (mapc (lambda (c)
6558 (setq o (make-overlay (car c) (cdr c)))
6559 (overlay-put o 'invisible 'outline))
6560 data)))))
6562 ;;; Folding of blocks
6564 (defconst org-block-regexp
6565 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6566 "Regular expression for hiding blocks.")
6568 (defvar org-hide-block-overlays nil
6569 "Overlays hiding blocks.")
6570 (make-variable-buffer-local 'org-hide-block-overlays)
6572 (defun org-block-map (function &optional start end)
6573 "Call FUNCTION at the head of all source blocks in the current buffer.
6574 Optional arguments START and END can be used to limit the range."
6575 (let ((start (or start (point-min)))
6576 (end (or end (point-max))))
6577 (save-excursion
6578 (goto-char start)
6579 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6580 (save-excursion
6581 (save-match-data
6582 (goto-char (match-beginning 0))
6583 (funcall function)))))))
6585 (defun org-hide-block-toggle-all ()
6586 "Toggle the visibility of all blocks in the current buffer."
6587 (org-block-map #'org-hide-block-toggle))
6589 (defun org-hide-block-all ()
6590 "Fold all blocks in the current buffer."
6591 (interactive)
6592 (org-show-block-all)
6593 (org-block-map #'org-hide-block-toggle-maybe))
6595 (defun org-show-block-all ()
6596 "Unfold all blocks in the current buffer."
6597 (interactive)
6598 (mapc 'delete-overlay org-hide-block-overlays)
6599 (setq org-hide-block-overlays nil))
6601 (defun org-hide-block-toggle-maybe ()
6602 "Toggle visibility of block at point."
6603 (interactive)
6604 (let ((case-fold-search t))
6605 (if (save-excursion
6606 (beginning-of-line 1)
6607 (looking-at org-block-regexp))
6608 (progn (org-hide-block-toggle)
6609 t) ;; to signal that we took action
6610 nil))) ;; to signal that we did not
6612 (defun org-hide-block-toggle (&optional force)
6613 "Toggle the visibility of the current block."
6614 (interactive)
6615 (save-excursion
6616 (beginning-of-line)
6617 (if (re-search-forward org-block-regexp nil t)
6618 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6619 (end (match-end 0)) ;; end of entire body
6621 (if (memq t (mapcar (lambda (overlay)
6622 (eq (overlay-get overlay 'invisible)
6623 'org-hide-block))
6624 (overlays-at start)))
6625 (if (or (not force) (eq force 'off))
6626 (mapc (lambda (ov)
6627 (when (member ov org-hide-block-overlays)
6628 (setq org-hide-block-overlays
6629 (delq ov org-hide-block-overlays)))
6630 (when (eq (overlay-get ov 'invisible)
6631 'org-hide-block)
6632 (delete-overlay ov)))
6633 (overlays-at start)))
6634 (setq ov (make-overlay start end))
6635 (overlay-put ov 'invisible 'org-hide-block)
6636 ;; make the block accessible to isearch
6637 (overlay-put
6638 ov 'isearch-open-invisible
6639 (lambda (ov)
6640 (when (member ov org-hide-block-overlays)
6641 (setq org-hide-block-overlays
6642 (delq ov org-hide-block-overlays)))
6643 (when (eq (overlay-get ov 'invisible)
6644 'org-hide-block)
6645 (delete-overlay ov))))
6646 (push ov org-hide-block-overlays)))
6647 (error "Not looking at a source block"))))
6649 ;; org-tab-after-check-for-cycling-hook
6650 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6651 ;; Remove overlays when changing major mode
6652 (add-hook 'org-mode-hook
6653 (lambda () (org-add-hook 'change-major-mode-hook
6654 'org-show-block-all 'append 'local)))
6656 ;;; Org-goto
6658 (defvar org-goto-window-configuration nil)
6659 (defvar org-goto-marker nil)
6660 (defvar org-goto-map
6661 (let ((map (make-sparse-keymap)))
6662 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6663 (while (setq cmd (pop cmds))
6664 (substitute-key-definition cmd cmd map global-map)))
6665 (suppress-keymap map)
6666 (org-defkey map "\C-m" 'org-goto-ret)
6667 (org-defkey map [(return)] 'org-goto-ret)
6668 (org-defkey map [(left)] 'org-goto-left)
6669 (org-defkey map [(right)] 'org-goto-right)
6670 (org-defkey map [(control ?g)] 'org-goto-quit)
6671 (org-defkey map "\C-i" 'org-cycle)
6672 (org-defkey map [(tab)] 'org-cycle)
6673 (org-defkey map [(down)] 'outline-next-visible-heading)
6674 (org-defkey map [(up)] 'outline-previous-visible-heading)
6675 (if org-goto-auto-isearch
6676 (if (fboundp 'define-key-after)
6677 (define-key-after map [t] 'org-goto-local-auto-isearch)
6678 nil)
6679 (org-defkey map "q" 'org-goto-quit)
6680 (org-defkey map "n" 'outline-next-visible-heading)
6681 (org-defkey map "p" 'outline-previous-visible-heading)
6682 (org-defkey map "f" 'outline-forward-same-level)
6683 (org-defkey map "b" 'outline-backward-same-level)
6684 (org-defkey map "u" 'outline-up-heading))
6685 (org-defkey map "/" 'org-occur)
6686 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6687 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6688 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6689 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6690 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6691 map))
6693 (defconst org-goto-help
6694 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6695 RET=jump to location [Q]uit and return to previous location
6696 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6698 (defvar org-goto-start-pos) ; dynamically scoped parameter
6700 ;; FIXME: Docstring does not mention both interfaces
6701 (defun org-goto (&optional alternative-interface)
6702 "Look up a different location in the current file, keeping current visibility.
6704 When you want look-up or go to a different location in a document, the
6705 fastest way is often to fold the entire buffer and then dive into the tree.
6706 This method has the disadvantage, that the previous location will be folded,
6707 which may not be what you want.
6709 This command works around this by showing a copy of the current buffer
6710 in an indirect buffer, in overview mode. You can dive into the tree in
6711 that copy, use org-occur and incremental search to find a location.
6712 When pressing RET or `Q', the command returns to the original buffer in
6713 which the visibility is still unchanged. After RET is will also jump to
6714 the location selected in the indirect buffer and expose the headline
6715 hierarchy above."
6716 (interactive "P")
6717 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6718 (org-refile-use-outline-path t)
6719 (org-refile-target-verify-function nil)
6720 (interface
6721 (if (not alternative-interface)
6722 org-goto-interface
6723 (if (eq org-goto-interface 'outline)
6724 'outline-path-completion
6725 'outline)))
6726 (org-goto-start-pos (point))
6727 (selected-point
6728 (if (eq interface 'outline)
6729 (car (org-get-location (current-buffer) org-goto-help))
6730 (let ((pa (org-refile-get-location "Goto")))
6731 (org-refile-check-position pa)
6732 (nth 3 pa)))))
6733 (if selected-point
6734 (progn
6735 (org-mark-ring-push org-goto-start-pos)
6736 (goto-char selected-point)
6737 (if (or (outline-invisible-p) (org-invisible-p2))
6738 (org-show-context 'org-goto)))
6739 (message "Quit"))))
6741 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6742 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6743 (defvar org-goto-local-auto-isearch-map) ; defined below
6745 (defun org-get-location (buf help)
6746 "Let the user select a location in the Org-mode buffer BUF.
6747 This function uses a recursive edit. It returns the selected position
6748 or nil."
6749 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6750 (isearch-hide-immediately nil)
6751 (isearch-search-fun-function
6752 (lambda () 'org-goto-local-search-headings))
6753 (org-goto-selected-point org-goto-exit-command)
6754 (pop-up-frames nil)
6755 (special-display-buffer-names nil)
6756 (special-display-regexps nil)
6757 (special-display-function nil))
6758 (save-excursion
6759 (save-window-excursion
6760 (delete-other-windows)
6761 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6762 (org-pop-to-buffer-same-window
6763 (condition-case nil
6764 (make-indirect-buffer (current-buffer) "*org-goto*")
6765 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6766 (with-output-to-temp-buffer "*Help*"
6767 (princ help))
6768 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6769 (setq buffer-read-only nil)
6770 (let ((org-startup-truncated t)
6771 (org-startup-folded nil)
6772 (org-startup-align-all-tables nil))
6773 (org-mode)
6774 (org-overview))
6775 (setq buffer-read-only t)
6776 (if (and (boundp 'org-goto-start-pos)
6777 (integer-or-marker-p org-goto-start-pos))
6778 (let ((org-show-hierarchy-above t)
6779 (org-show-siblings t)
6780 (org-show-following-heading t))
6781 (goto-char org-goto-start-pos)
6782 (and (outline-invisible-p) (org-show-context)))
6783 (goto-char (point-min)))
6784 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6785 (message "Select location and press RET")
6786 (use-local-map org-goto-map)
6787 (recursive-edit)
6789 (kill-buffer "*org-goto*")
6790 (cons org-goto-selected-point org-goto-exit-command)))
6792 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6793 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6794 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6795 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6797 (defun org-goto-local-search-headings (string bound noerror)
6798 "Search and make sure that any matches are in headlines."
6799 (catch 'return
6800 (while (if isearch-forward
6801 (search-forward string bound noerror)
6802 (search-backward string bound noerror))
6803 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6804 (and (member :headline context)
6805 (not (member :tags context))))
6806 (throw 'return (point))))))
6808 (defun org-goto-local-auto-isearch ()
6809 "Start isearch."
6810 (interactive)
6811 (goto-char (point-min))
6812 (let ((keys (this-command-keys)))
6813 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6814 (isearch-mode t)
6815 (isearch-process-search-char (string-to-char keys)))))
6817 (defun org-goto-ret (&optional arg)
6818 "Finish `org-goto' by going to the new location."
6819 (interactive "P")
6820 (setq org-goto-selected-point (point)
6821 org-goto-exit-command 'return)
6822 (throw 'exit nil))
6824 (defun org-goto-left ()
6825 "Finish `org-goto' by going to the new location."
6826 (interactive)
6827 (if (org-on-heading-p)
6828 (progn
6829 (beginning-of-line 1)
6830 (setq org-goto-selected-point (point)
6831 org-goto-exit-command 'left)
6832 (throw 'exit nil))
6833 (error "Not on a heading")))
6835 (defun org-goto-right ()
6836 "Finish `org-goto' by going to the new location."
6837 (interactive)
6838 (if (org-on-heading-p)
6839 (progn
6840 (setq org-goto-selected-point (point)
6841 org-goto-exit-command 'right)
6842 (throw 'exit nil))
6843 (error "Not on a heading")))
6845 (defun org-goto-quit ()
6846 "Finish `org-goto' without cursor motion."
6847 (interactive)
6848 (setq org-goto-selected-point nil)
6849 (setq org-goto-exit-command 'quit)
6850 (throw 'exit nil))
6852 ;;; Indirect buffer display of subtrees
6854 (defvar org-indirect-dedicated-frame nil
6855 "This is the frame being used for indirect tree display.")
6856 (defvar org-last-indirect-buffer nil)
6858 (defun org-tree-to-indirect-buffer (&optional arg)
6859 "Create indirect buffer and narrow it to current subtree.
6860 With numerical prefix ARG, go up to this level and then take that tree.
6861 If ARG is negative, go up that many levels.
6862 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6863 indirect buffer previously made with this command, to avoid proliferation of
6864 indirect buffers. However, when you call the command with a \
6865 \\[universal-argument] prefix, or
6866 when `org-indirect-buffer-display' is `new-frame', the last buffer
6867 is kept so that you can work with several indirect buffers at the same time.
6868 If `org-indirect-buffer-display' is `dedicated-frame', the \
6869 \\[universal-argument] prefix also
6870 requests that a new frame be made for the new buffer, so that the dedicated
6871 frame is not changed."
6872 (interactive "P")
6873 (let ((cbuf (current-buffer))
6874 (cwin (selected-window))
6875 (pos (point))
6876 beg end level heading ibuf)
6877 (save-excursion
6878 (org-back-to-heading t)
6879 (when (numberp arg)
6880 (setq level (org-outline-level))
6881 (if (< arg 0) (setq arg (+ level arg)))
6882 (while (> (setq level (org-outline-level)) arg)
6883 (outline-up-heading 1 t)))
6884 (setq beg (point)
6885 heading (org-get-heading))
6886 (org-end-of-subtree t t)
6887 (if (org-on-heading-p) (backward-char 1))
6888 (setq end (point)))
6889 (if (and (buffer-live-p org-last-indirect-buffer)
6890 (not (eq org-indirect-buffer-display 'new-frame))
6891 (not arg))
6892 (kill-buffer org-last-indirect-buffer))
6893 (setq ibuf (org-get-indirect-buffer cbuf)
6894 org-last-indirect-buffer ibuf)
6895 (cond
6896 ((or (eq org-indirect-buffer-display 'new-frame)
6897 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6898 (select-frame (make-frame))
6899 (delete-other-windows)
6900 (org-pop-to-buffer-same-window ibuf)
6901 (org-set-frame-title heading))
6902 ((eq org-indirect-buffer-display 'dedicated-frame)
6903 (raise-frame
6904 (select-frame (or (and org-indirect-dedicated-frame
6905 (frame-live-p org-indirect-dedicated-frame)
6906 org-indirect-dedicated-frame)
6907 (setq org-indirect-dedicated-frame (make-frame)))))
6908 (delete-other-windows)
6909 (org-pop-to-buffer-same-window ibuf)
6910 (org-set-frame-title (concat "Indirect: " heading)))
6911 ((eq org-indirect-buffer-display 'current-window)
6912 (org-pop-to-buffer-same-window ibuf))
6913 ((eq org-indirect-buffer-display 'other-window)
6914 (pop-to-buffer ibuf))
6915 (t (error "Invalid value")))
6916 (if (featurep 'xemacs)
6917 (save-excursion (org-mode) (turn-on-font-lock)))
6918 (narrow-to-region beg end)
6919 (show-all)
6920 (goto-char pos)
6921 (run-hook-with-args 'org-cycle-hook 'all)
6922 (and (window-live-p cwin) (select-window cwin))))
6924 (defun org-get-indirect-buffer (&optional buffer)
6925 (setq buffer (or buffer (current-buffer)))
6926 (let ((n 1) (base (buffer-name buffer)) bname)
6927 (while (buffer-live-p
6928 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6929 (setq n (1+ n)))
6930 (condition-case nil
6931 (make-indirect-buffer buffer bname 'clone)
6932 (error (make-indirect-buffer buffer bname)))))
6934 (defun org-set-frame-title (title)
6935 "Set the title of the current frame to the string TITLE."
6936 ;; FIXME: how to name a single frame in XEmacs???
6937 (unless (featurep 'xemacs)
6938 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6940 ;;;; Structure editing
6942 ;;; Inserting headlines
6944 (defun org-previous-line-empty-p ()
6945 (save-excursion
6946 (and (not (bobp))
6947 (or (beginning-of-line 0) t)
6948 (save-match-data
6949 (looking-at "[ \t]*$")))))
6951 (defun org-insert-heading (&optional force-heading invisible-ok)
6952 "Insert a new heading or item with same depth at point.
6953 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6954 If point is at the beginning of a headline, insert a sibling before the
6955 current headline. If point is not at the beginning, split the line,
6956 create the new headline with the text in the current line after point
6957 \(but see also the variable `org-M-RET-may-split-line').
6959 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6960 This is important for non-interactive uses of the command."
6961 (interactive "P")
6962 (if (or (= (buffer-size) 0)
6963 (and (not (save-excursion
6964 (and (ignore-errors (org-back-to-heading invisible-ok))
6965 (org-on-heading-p))))
6966 (or force-heading (not (org-in-item-p)))))
6967 (progn
6968 (insert "\n* ")
6969 (run-hooks 'org-insert-heading-hook))
6970 (when (or force-heading (not (org-insert-item)))
6971 (let* ((empty-line-p nil)
6972 (level nil)
6973 (on-heading (org-on-heading-p))
6974 (head (save-excursion
6975 (condition-case nil
6976 (progn
6977 (org-back-to-heading invisible-ok)
6978 (when (and (not on-heading)
6979 (featurep 'org-inlinetask)
6980 (integerp org-inlinetask-min-level)
6981 (>= (length (match-string 0))
6982 org-inlinetask-min-level))
6983 ;; Find a heading level before the inline task
6984 (while (and (setq level (org-up-heading-safe))
6985 (>= level org-inlinetask-min-level)))
6986 (if (org-on-heading-p)
6987 (org-back-to-heading invisible-ok)
6988 (error "This should not happen")))
6989 (setq empty-line-p (org-previous-line-empty-p))
6990 (match-string 0))
6991 (error "*"))))
6992 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6993 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6994 pos hide-previous previous-pos)
6995 (cond
6996 ((and (org-on-heading-p) (bolp)
6997 (or (bobp)
6998 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6999 ;; insert before the current line
7000 (open-line (if blank 2 1)))
7001 ((and (bolp)
7002 (not org-insert-heading-respect-content)
7003 (or (bobp)
7004 (save-excursion
7005 (backward-char 1) (not (outline-invisible-p)))))
7006 ;; insert right here
7007 nil)
7009 ;; somewhere in the line
7010 (save-excursion
7011 (setq previous-pos (point-at-bol))
7012 (end-of-line)
7013 (setq hide-previous (outline-invisible-p)))
7014 (and org-insert-heading-respect-content (org-show-subtree))
7015 (let ((split
7016 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7017 (save-excursion
7018 (let ((p (point)))
7019 (goto-char (point-at-bol))
7020 (and (looking-at org-complex-heading-regexp)
7021 (> p (match-beginning 4)))))))
7022 tags pos)
7023 (cond
7024 (org-insert-heading-respect-content
7025 (org-end-of-subtree nil t)
7026 (when (featurep 'org-inlinetask)
7027 (while (and (not (eobp))
7028 (looking-at "\\(\\*+\\)[ \t]+")
7029 (>= (length (match-string 1))
7030 org-inlinetask-min-level))
7031 (org-end-of-subtree nil t)))
7032 (or (bolp) (newline))
7033 (or (org-previous-line-empty-p)
7034 (and blank (newline)))
7035 (open-line 1))
7036 ((org-on-heading-p)
7037 (when hide-previous
7038 (show-children)
7039 (org-show-entry))
7040 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7041 (setq tags (and (match-end 2) (match-string 2)))
7042 (and (match-end 1)
7043 (delete-region (match-beginning 1) (match-end 1)))
7044 (setq pos (point-at-bol))
7045 (or split (end-of-line 1))
7046 (delete-horizontal-space)
7047 (if (string-match "\\`\\*+\\'"
7048 (buffer-substring (point-at-bol) (point)))
7049 (insert " "))
7050 (newline (if blank 2 1))
7051 (when tags
7052 (save-excursion
7053 (goto-char pos)
7054 (end-of-line 1)
7055 (insert " " tags)
7056 (org-set-tags nil 'align))))
7058 (or split (end-of-line 1))
7059 (newline (if blank 2 1)))))))
7060 (insert head) (just-one-space)
7061 (setq pos (point))
7062 (end-of-line 1)
7063 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7064 (when (and org-insert-heading-respect-content hide-previous)
7065 (save-excursion
7066 (goto-char previous-pos)
7067 (hide-subtree)))
7068 (run-hooks 'org-insert-heading-hook)))))
7070 (defun org-get-heading (&optional no-tags no-todo)
7071 "Return the heading of the current entry, without the stars.
7072 When NO-TAGS is non-nil, don't include tags.
7073 When NO-TODO is non-nil, don't include TODO keywords."
7074 (save-excursion
7075 (org-back-to-heading t)
7076 (cond
7077 ((and no-tags no-todo)
7078 (looking-at org-complex-heading-regexp)
7079 (match-string 4))
7080 (no-tags
7081 (looking-at "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
7082 (match-string 1))
7083 (no-todo
7084 (looking-at (concat "\\*+[ \t]+" org-todo-regexp " +"
7085 "\\([^\n\r]*?[ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$"))
7086 (match-string 2))
7087 (t (looking-at "\\*+[ \t]+\\([^\r\n]*\\)")
7088 (match-string 1)))))
7090 (defun org-heading-components ()
7091 "Return the components of the current heading.
7092 This is a list with the following elements:
7093 - the level as an integer
7094 - the reduced level, different if `org-odd-levels-only' is set.
7095 - the TODO keyword, or nil
7096 - the priority character, like ?A, or nil if no priority is given
7097 - the headline text itself, or the tags string if no headline text
7098 - the tags string, or nil."
7099 (save-excursion
7100 (org-back-to-heading t)
7101 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7102 (list (length (match-string 1))
7103 (org-reduced-level (length (match-string 1)))
7104 (org-match-string-no-properties 2)
7105 (and (match-end 3) (aref (match-string 3) 2))
7106 (org-match-string-no-properties 4)
7107 (org-match-string-no-properties 5)))))
7109 (defun org-get-entry ()
7110 "Get the entry text, after heading, entire subtree."
7111 (save-excursion
7112 (org-back-to-heading t)
7113 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7115 (defun org-insert-heading-after-current ()
7116 "Insert a new heading with same level as current, after current subtree."
7117 (interactive)
7118 (org-back-to-heading)
7119 (org-insert-heading)
7120 (org-move-subtree-down)
7121 (end-of-line 1))
7123 (defun org-insert-heading-respect-content ()
7124 (interactive)
7125 (let ((org-insert-heading-respect-content t))
7126 (org-insert-heading t)))
7128 (defun org-insert-todo-heading-respect-content (&optional force-state)
7129 (interactive "P")
7130 (let ((org-insert-heading-respect-content t))
7131 (org-insert-todo-heading force-state t)))
7133 (defun org-insert-todo-heading (arg &optional force-heading)
7134 "Insert a new heading with the same level and TODO state as current heading.
7135 If the heading has no TODO state, or if the state is DONE, use the first
7136 state (TODO by default). Also with prefix arg, force first state."
7137 (interactive "P")
7138 (when (or force-heading (not (org-insert-item 'checkbox)))
7139 (org-insert-heading force-heading)
7140 (save-excursion
7141 (org-back-to-heading)
7142 (outline-previous-heading)
7143 (looking-at org-todo-line-regexp))
7144 (let*
7145 ((new-mark-x
7146 (if (or arg
7147 (not (match-beginning 2))
7148 (member (match-string 2) org-done-keywords))
7149 (car org-todo-keywords-1)
7150 (match-string 2)))
7151 (new-mark
7153 (run-hook-with-args-until-success
7154 'org-todo-get-default-hook new-mark-x nil)
7155 new-mark-x)))
7156 (beginning-of-line 1)
7157 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7158 (if org-treat-insert-todo-heading-as-state-change
7159 (org-todo new-mark)
7160 (insert new-mark " "))))
7161 (when org-provide-todo-statistics
7162 (org-update-parent-todo-statistics))))
7164 (defun org-insert-subheading (arg)
7165 "Insert a new subheading and demote it.
7166 Works for outline headings and for plain lists alike."
7167 (interactive "P")
7168 (org-insert-heading arg)
7169 (cond
7170 ((org-on-heading-p) (org-do-demote))
7171 ((org-at-item-p) (org-indent-item))))
7173 (defun org-insert-todo-subheading (arg)
7174 "Insert a new subheading with TODO keyword or checkbox and demote it.
7175 Works for outline headings and for plain lists alike."
7176 (interactive "P")
7177 (org-insert-todo-heading arg)
7178 (cond
7179 ((org-on-heading-p) (org-do-demote))
7180 ((org-at-item-p) (org-indent-item))))
7182 ;;; Promotion and Demotion
7184 (defvar org-after-demote-entry-hook nil
7185 "Hook run after an entry has been demoted.
7186 The cursor will be at the beginning of the entry.
7187 When a subtree is being demoted, the hook will be called for each node.")
7189 (defvar org-after-promote-entry-hook nil
7190 "Hook run after an entry has been promoted.
7191 The cursor will be at the beginning of the entry.
7192 When a subtree is being promoted, the hook will be called for each node.")
7194 (defun org-promote-subtree ()
7195 "Promote the entire subtree.
7196 See also `org-promote'."
7197 (interactive)
7198 (save-excursion
7199 (org-with-limited-levels (org-map-tree 'org-promote)))
7200 (org-fix-position-after-promote))
7202 (defun org-demote-subtree ()
7203 "Demote the entire subtree. See `org-demote'.
7204 See also `org-promote'."
7205 (interactive)
7206 (save-excursion
7207 (org-with-limited-levels (org-map-tree 'org-demote)))
7208 (org-fix-position-after-promote))
7211 (defun org-do-promote ()
7212 "Promote the current heading higher up the tree.
7213 If the region is active in `transient-mark-mode', promote all headings
7214 in the region."
7215 (interactive)
7216 (save-excursion
7217 (if (org-region-active-p)
7218 (org-map-region 'org-promote (region-beginning) (region-end))
7219 (org-promote)))
7220 (org-fix-position-after-promote))
7222 (defun org-do-demote ()
7223 "Demote the current heading lower down the tree.
7224 If the region is active in `transient-mark-mode', demote all headings
7225 in the region."
7226 (interactive)
7227 (save-excursion
7228 (if (org-region-active-p)
7229 (org-map-region 'org-demote (region-beginning) (region-end))
7230 (org-demote)))
7231 (org-fix-position-after-promote))
7233 (defun org-fix-position-after-promote ()
7234 "Make sure that after pro/demotion cursor position is right."
7235 (let ((pos (point)))
7236 (when (save-excursion
7237 (beginning-of-line 1)
7238 (looking-at org-todo-line-regexp)
7239 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7240 (cond ((eobp) (insert " "))
7241 ((eolp) (insert " "))
7242 ((equal (char-after) ?\ ) (forward-char 1))))))
7244 (defun org-current-level ()
7245 "Return the level of the current entry, or nil if before the first headline.
7246 The level is the number of stars at the beginning of the headline."
7247 (save-excursion
7248 (org-with-limited-levels
7249 (ignore-errors
7250 (org-back-to-heading t)
7251 (funcall outline-level)))))
7253 (defun org-get-previous-line-level ()
7254 "Return the outline depth of the last headline before the current line.
7255 Returns 0 for the first headline in the buffer, and nil if before the
7256 first headline."
7257 (let ((current-level (org-current-level))
7258 (prev-level (when (> (line-number-at-pos) 1)
7259 (save-excursion
7260 (beginning-of-line 0)
7261 (org-current-level)))))
7262 (cond ((null current-level) nil) ; Before first headline
7263 ((null prev-level) 0) ; At first headline
7264 (prev-level))))
7266 (defun org-reduced-level (l)
7267 "Compute the effective level of a heading.
7268 This takes into account the setting of `org-odd-levels-only'."
7269 (cond
7270 ((zerop l) 0)
7271 (org-odd-levels-only (1+ (floor (/ l 2))))
7272 (t l)))
7274 (defun org-level-increment ()
7275 "Return the number of stars that will be added or removed at a
7276 time to headlines when structure editing, based on the value of
7277 `org-odd-levels-only'."
7278 (if org-odd-levels-only 2 1))
7280 (defun org-get-valid-level (level &optional change)
7281 "Rectify a level change under the influence of `org-odd-levels-only'
7282 LEVEL is a current level, CHANGE is by how much the level should be
7283 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7284 even level numbers will become the next higher odd number."
7285 (if org-odd-levels-only
7286 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7287 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7288 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7289 (max 1 (+ level (or change 0)))))
7291 (if (boundp 'define-obsolete-function-alias)
7292 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7293 (define-obsolete-function-alias 'org-get-legal-level
7294 'org-get-valid-level)
7295 (define-obsolete-function-alias 'org-get-legal-level
7296 'org-get-valid-level "23.1")))
7298 (defun org-promote ()
7299 "Promote the current heading higher up the tree.
7300 If the region is active in `transient-mark-mode', promote all headings
7301 in the region."
7302 (org-back-to-heading t)
7303 (let* ((level (save-match-data (funcall outline-level)))
7304 (after-change-functions (remove 'flyspell-after-change-function
7305 after-change-functions))
7306 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7307 (diff (abs (- level (length up-head) -1))))
7308 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7309 (replace-match up-head nil t)
7310 ;; Fixup tag positioning
7311 (and org-auto-align-tags (org-set-tags nil t))
7312 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7313 (run-hooks 'org-after-promote-entry-hook)))
7315 (defun org-demote ()
7316 "Demote the current heading lower down the tree.
7317 If the region is active in `transient-mark-mode', demote all headings
7318 in the region."
7319 (org-back-to-heading t)
7320 (let* ((level (save-match-data (funcall outline-level)))
7321 (after-change-functions (remove 'flyspell-after-change-function
7322 after-change-functions))
7323 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7324 (diff (abs (- level (length down-head) -1))))
7325 (replace-match down-head nil t)
7326 ;; Fixup tag positioning
7327 (and org-auto-align-tags (org-set-tags nil t))
7328 (if org-adapt-indentation (org-fixup-indentation diff))
7329 (run-hooks 'org-after-demote-entry-hook)))
7331 (defun org-cycle-level ()
7332 "Cycle the level of an empty headline through possible states.
7333 This goes first to child, then to parent, level, then up the hierarchy.
7334 After top level, it switches back to sibling level."
7335 (interactive)
7336 (let ((org-adapt-indentation nil))
7337 (when (org-point-at-end-of-empty-headline)
7338 (setq this-command 'org-cycle-level) ; Only needed for caching
7339 (let ((cur-level (org-current-level))
7340 (prev-level (org-get-previous-line-level)))
7341 (cond
7342 ;; If first headline in file, promote to top-level.
7343 ((= prev-level 0)
7344 (loop repeat (/ (- cur-level 1) (org-level-increment))
7345 do (org-do-promote)))
7346 ;; If same level as prev, demote one.
7347 ((= prev-level cur-level)
7348 (org-do-demote))
7349 ;; If parent is top-level, promote to top level if not already.
7350 ((= prev-level 1)
7351 (loop repeat (/ (- cur-level 1) (org-level-increment))
7352 do (org-do-promote)))
7353 ;; If top-level, return to prev-level.
7354 ((= cur-level 1)
7355 (loop repeat (/ (- prev-level 1) (org-level-increment))
7356 do (org-do-demote)))
7357 ;; If less than prev-level, promote one.
7358 ((< cur-level prev-level)
7359 (org-do-promote))
7360 ;; If deeper than prev-level, promote until higher than
7361 ;; prev-level.
7362 ((> cur-level prev-level)
7363 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7364 do (org-do-promote))))
7365 t))))
7367 (defun org-map-tree (fun)
7368 "Call FUN for every heading underneath the current one."
7369 (org-back-to-heading)
7370 (let ((level (funcall outline-level)))
7371 (save-excursion
7372 (funcall fun)
7373 (while (and (progn
7374 (outline-next-heading)
7375 (> (funcall outline-level) level))
7376 (not (eobp)))
7377 (funcall fun)))))
7379 (defun org-map-region (fun beg end)
7380 "Call FUN for every heading between BEG and END."
7381 (let ((org-ignore-region t))
7382 (save-excursion
7383 (setq end (copy-marker end))
7384 (goto-char beg)
7385 (if (and (re-search-forward org-outline-regexp-bol nil t)
7386 (< (point) end))
7387 (funcall fun))
7388 (while (and (progn
7389 (outline-next-heading)
7390 (< (point) end))
7391 (not (eobp)))
7392 (funcall fun)))))
7394 (defvar org-property-end-re) ; silence byte-compiler
7395 (defun org-fixup-indentation (diff)
7396 "Change the indentation in the current entry by DIFF.
7397 However, if any line in the current entry has no indentation, or if it
7398 would end up with no indentation after the change, nothing at all is done."
7399 (save-excursion
7400 (let ((end (save-excursion (outline-next-heading)
7401 (point-marker)))
7402 (prohibit (if (> diff 0)
7403 "^\\S-"
7404 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7405 col)
7406 (unless (save-excursion (end-of-line 1)
7407 (re-search-forward prohibit end t))
7408 (while (and (< (point) end)
7409 (re-search-forward "^[ \t]+" end t))
7410 (goto-char (match-end 0))
7411 (setq col (current-column))
7412 (if (< diff 0) (replace-match ""))
7413 (org-indent-to-column (+ diff col))))
7414 (move-marker end nil))))
7416 (defun org-convert-to-odd-levels ()
7417 "Convert an org-mode file with all levels allowed to one with odd levels.
7418 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7419 level 5 etc."
7420 (interactive)
7421 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7422 (let ((outline-level 'org-outline-level)
7423 (org-odd-levels-only nil) n)
7424 (save-excursion
7425 (goto-char (point-min))
7426 (while (re-search-forward "^\\*\\*+ " nil t)
7427 (setq n (- (length (match-string 0)) 2))
7428 (while (>= (setq n (1- n)) 0)
7429 (org-demote))
7430 (end-of-line 1))))))
7432 (defun org-convert-to-oddeven-levels ()
7433 "Convert an org-mode file with only odd levels to one with odd/even levels.
7434 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7435 file contains a section with an even level, conversion would
7436 destroy the structure of the file. An error is signaled in this
7437 case."
7438 (interactive)
7439 (goto-char (point-min))
7440 ;; First check if there are no even levels
7441 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7442 (org-show-context t)
7443 (error "Not all levels are odd in this file. Conversion not possible"))
7444 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7445 (let ((outline-regexp org-outline-regexp)
7446 (outline-level 'org-outline-level)
7447 (org-odd-levels-only nil) n)
7448 (save-excursion
7449 (goto-char (point-min))
7450 (while (re-search-forward "^\\*\\*+ " nil t)
7451 (setq n (/ (1- (length (match-string 0))) 2))
7452 (while (>= (setq n (1- n)) 0)
7453 (org-promote))
7454 (end-of-line 1))))))
7456 (defun org-tr-level (n)
7457 "Make N odd if required."
7458 (if org-odd-levels-only (1+ (/ n 2)) n))
7460 ;;; Vertical tree motion, cutting and pasting of subtrees
7462 (defun org-move-subtree-up (&optional arg)
7463 "Move the current subtree up past ARG headlines of the same level."
7464 (interactive "p")
7465 (org-move-subtree-down (- (prefix-numeric-value arg))))
7467 (defun org-move-subtree-down (&optional arg)
7468 "Move the current subtree down past ARG headlines of the same level."
7469 (interactive "p")
7470 (setq arg (prefix-numeric-value arg))
7471 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7472 'org-get-last-sibling))
7473 (ins-point (make-marker))
7474 (cnt (abs arg))
7475 (col (current-column))
7476 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7477 ;; Select the tree
7478 (org-back-to-heading)
7479 (setq beg0 (point))
7480 (save-excursion
7481 (setq ne-beg (org-back-over-empty-lines))
7482 (setq beg (point)))
7483 (save-match-data
7484 (save-excursion (outline-end-of-heading)
7485 (setq folded (outline-invisible-p)))
7486 (outline-end-of-subtree))
7487 (outline-next-heading)
7488 (setq ne-end (org-back-over-empty-lines))
7489 (setq end (point))
7490 (goto-char beg0)
7491 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7492 ;; include less whitespace
7493 (save-excursion
7494 (goto-char beg)
7495 (forward-line (- ne-beg ne-end))
7496 (setq beg (point))))
7497 ;; Find insertion point, with error handling
7498 (while (> cnt 0)
7499 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7500 (progn (goto-char beg0)
7501 (error "Cannot move past superior level or buffer limit")))
7502 (setq cnt (1- cnt)))
7503 (if (> arg 0)
7504 ;; Moving forward - still need to move over subtree
7505 (progn (org-end-of-subtree t t)
7506 (save-excursion
7507 (org-back-over-empty-lines)
7508 (or (bolp) (newline)))))
7509 (setq ne-ins (org-back-over-empty-lines))
7510 (move-marker ins-point (point))
7511 (setq txt (buffer-substring beg end))
7512 (org-save-markers-in-region beg end)
7513 (delete-region beg end)
7514 (org-remove-empty-overlays-at beg)
7515 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7516 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7517 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7518 (let ((bbb (point)))
7519 (insert-before-markers txt)
7520 (org-reinstall-markers-in-region bbb)
7521 (move-marker ins-point bbb))
7522 (or (bolp) (insert "\n"))
7523 (setq ins-end (point))
7524 (goto-char ins-point)
7525 (org-skip-whitespace)
7526 (when (and (< arg 0)
7527 (org-first-sibling-p)
7528 (> ne-ins ne-beg))
7529 ;; Move whitespace back to beginning
7530 (save-excursion
7531 (goto-char ins-end)
7532 (let ((kill-whole-line t))
7533 (kill-line (- ne-ins ne-beg)) (point)))
7534 (insert (make-string (- ne-ins ne-beg) ?\n)))
7535 (move-marker ins-point nil)
7536 (if folded
7537 (hide-subtree)
7538 (org-show-entry)
7539 (show-children)
7540 (org-cycle-hide-drawers 'children))
7541 (org-clean-visibility-after-subtree-move)
7542 ;; move back to the initial column we were at
7543 (move-to-column col)))
7545 (defvar org-subtree-clip ""
7546 "Clipboard for cut and paste of subtrees.
7547 This is actually only a copy of the kill, because we use the normal kill
7548 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7550 (defvar org-subtree-clip-folded nil
7551 "Was the last copied subtree folded?
7552 This is used to fold the tree back after pasting.")
7554 (defun org-cut-subtree (&optional n)
7555 "Cut the current subtree into the clipboard.
7556 With prefix arg N, cut this many sequential subtrees.
7557 This is a short-hand for marking the subtree and then cutting it."
7558 (interactive "p")
7559 (org-copy-subtree n 'cut))
7561 (defun org-copy-subtree (&optional n cut force-store-markers)
7562 "Cut the current subtree into the clipboard.
7563 With prefix arg N, cut this many sequential subtrees.
7564 This is a short-hand for marking the subtree and then copying it.
7565 If CUT is non-nil, actually cut the subtree.
7566 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7567 of some markers in the region, even if CUT is non-nil. This is
7568 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7569 (interactive "p")
7570 (let (beg end folded (beg0 (point)))
7571 (if (org-called-interactively-p 'any)
7572 (org-back-to-heading nil) ; take what looks like a subtree
7573 (org-back-to-heading t)) ; take what is really there
7574 (org-back-over-empty-lines)
7575 (setq beg (point))
7576 (skip-chars-forward " \t\r\n")
7577 (save-match-data
7578 (save-excursion (outline-end-of-heading)
7579 (setq folded (outline-invisible-p)))
7580 (condition-case nil
7581 (org-forward-same-level (1- n) t)
7582 (error nil))
7583 (org-end-of-subtree t t))
7584 (org-back-over-empty-lines)
7585 (setq end (point))
7586 (goto-char beg0)
7587 (when (> end beg)
7588 (setq org-subtree-clip-folded folded)
7589 (when (or cut force-store-markers)
7590 (org-save-markers-in-region beg end))
7591 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7592 (setq org-subtree-clip (current-kill 0))
7593 (message "%s: Subtree(s) with %d characters"
7594 (if cut "Cut" "Copied")
7595 (length org-subtree-clip)))))
7597 (defun org-paste-subtree (&optional level tree for-yank)
7598 "Paste the clipboard as a subtree, with modification of headline level.
7599 The entire subtree is promoted or demoted in order to match a new headline
7600 level.
7602 If the cursor is at the beginning of a headline, the same level as
7603 that headline is used to paste the tree
7605 If not, the new level is derived from the *visible* headings
7606 before and after the insertion point, and taken to be the inferior headline
7607 level of the two. So if the previous visible heading is level 3 and the
7608 next is level 4 (or vice versa), level 4 will be used for insertion.
7609 This makes sure that the subtree remains an independent subtree and does
7610 not swallow low level entries.
7612 You can also force a different level, either by using a numeric prefix
7613 argument, or by inserting the heading marker by hand. For example, if the
7614 cursor is after \"*****\", then the tree will be shifted to level 5.
7616 If optional TREE is given, use this text instead of the kill ring.
7618 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7619 move back over whitespace before inserting, and move point to the end of
7620 the inserted text when done."
7621 (interactive "P")
7622 (setq tree (or tree (and kill-ring (current-kill 0))))
7623 (unless (org-kill-is-subtree-p tree)
7624 (error "%s"
7625 (substitute-command-keys
7626 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7627 (org-with-limited-levels
7628 (let* ((visp (not (outline-invisible-p)))
7629 (txt tree)
7630 (^re_ "\\(\\*+\\)[ \t]*")
7631 (old-level (if (string-match org-outline-regexp-bol txt)
7632 (- (match-end 0) (match-beginning 0) 1)
7633 -1))
7634 (force-level (cond (level (prefix-numeric-value level))
7635 ((and (looking-at "[ \t]*$")
7636 (string-match
7637 "^\\*+$" (buffer-substring
7638 (point-at-bol) (point))))
7639 (- (match-end 1) (match-beginning 1)))
7640 ((and (bolp)
7641 (looking-at org-outline-regexp))
7642 (- (match-end 0) (point) 1))
7643 (t nil)))
7644 (previous-level (save-excursion
7645 (condition-case nil
7646 (progn
7647 (outline-previous-visible-heading 1)
7648 (if (looking-at ^re_)
7649 (- (match-end 0) (match-beginning 0) 1)
7651 (error 1))))
7652 (next-level (save-excursion
7653 (condition-case nil
7654 (progn
7655 (or (looking-at org-outline-regexp)
7656 (outline-next-visible-heading 1))
7657 (if (looking-at ^re_)
7658 (- (match-end 0) (match-beginning 0) 1)
7660 (error 1))))
7661 (new-level (or force-level (max previous-level next-level)))
7662 (shift (if (or (= old-level -1)
7663 (= new-level -1)
7664 (= old-level new-level))
7666 (- new-level old-level)))
7667 (delta (if (> shift 0) -1 1))
7668 (func (if (> shift 0) 'org-demote 'org-promote))
7669 (org-odd-levels-only nil)
7670 beg end newend)
7671 ;; Remove the forced level indicator
7672 (if force-level
7673 (delete-region (point-at-bol) (point)))
7674 ;; Paste
7675 (beginning-of-line (if (bolp) 1 2))
7676 (unless for-yank (org-back-over-empty-lines))
7677 (setq beg (point))
7678 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7679 (insert-before-markers txt)
7680 (unless (string-match "\n\\'" txt) (insert "\n"))
7681 (setq newend (point))
7682 (org-reinstall-markers-in-region beg)
7683 (setq end (point))
7684 (goto-char beg)
7685 (skip-chars-forward " \t\n\r")
7686 (setq beg (point))
7687 (if (and (outline-invisible-p) visp)
7688 (save-excursion (outline-show-heading)))
7689 ;; Shift if necessary
7690 (unless (= shift 0)
7691 (save-restriction
7692 (narrow-to-region beg end)
7693 (while (not (= shift 0))
7694 (org-map-region func (point-min) (point-max))
7695 (setq shift (+ delta shift)))
7696 (goto-char (point-min))
7697 (setq newend (point-max))))
7698 (when (or (org-called-interactively-p 'interactive) for-yank)
7699 (message "Clipboard pasted as level %d subtree" new-level))
7700 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7701 kill-ring
7702 (eq org-subtree-clip (current-kill 0))
7703 org-subtree-clip-folded)
7704 ;; The tree was folded before it was killed/copied
7705 (hide-subtree))
7706 (and for-yank (goto-char newend)))))
7708 (defun org-kill-is-subtree-p (&optional txt)
7709 "Check if the current kill is an outline subtree, or a set of trees.
7710 Returns nil if kill does not start with a headline, or if the first
7711 headline level is not the largest headline level in the tree.
7712 So this will actually accept several entries of equal levels as well,
7713 which is OK for `org-paste-subtree'.
7714 If optional TXT is given, check this string instead of the current kill."
7715 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7716 (re (org-get-limited-outline-regexp))
7717 (^re (concat "^" re))
7718 (start-level (and kill
7719 (string-match
7720 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7721 kill)
7722 (- (match-end 2) (match-beginning 2) 1)))
7723 (start (1+ (or (match-beginning 2) -1))))
7724 (if (not start-level)
7725 (progn
7726 nil) ;; does not even start with a heading
7727 (catch 'exit
7728 (while (setq start (string-match ^re kill (1+ start)))
7729 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7730 (throw 'exit nil)))
7731 t))))
7733 (defvar org-markers-to-move nil
7734 "Markers that should be moved with a cut-and-paste operation.
7735 Those markers are stored together with their positions relative to
7736 the start of the region.")
7738 (defun org-save-markers-in-region (beg end)
7739 "Check markers in region.
7740 If these markers are between BEG and END, record their position relative
7741 to BEG, so that after moving the block of text, we can put the markers back
7742 into place.
7743 This function gets called just before an entry or tree gets cut from the
7744 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7745 called immediately, to move the markers with the entries."
7746 (setq org-markers-to-move nil)
7747 (when (featurep 'org-clock)
7748 (org-clock-save-markers-for-cut-and-paste beg end))
7749 (when (featurep 'org-agenda)
7750 (org-agenda-save-markers-for-cut-and-paste beg end)))
7752 (defun org-check-and-save-marker (marker beg end)
7753 "Check if MARKER is between BEG and END.
7754 If yes, remember the marker and the distance to BEG."
7755 (when (and (marker-buffer marker)
7756 (equal (marker-buffer marker) (current-buffer)))
7757 (if (and (>= marker beg) (< marker end))
7758 (push (cons marker (- marker beg)) org-markers-to-move))))
7760 (defun org-reinstall-markers-in-region (beg)
7761 "Move all remembered markers to their position relative to BEG."
7762 (mapc (lambda (x)
7763 (move-marker (car x) (+ beg (cdr x))))
7764 org-markers-to-move)
7765 (setq org-markers-to-move nil))
7767 (defun org-narrow-to-subtree ()
7768 "Narrow buffer to the current subtree."
7769 (interactive)
7770 (save-excursion
7771 (save-match-data
7772 (org-with-limited-levels
7773 (narrow-to-region
7774 (progn (org-back-to-heading t) (point))
7775 (progn (org-end-of-subtree t t)
7776 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7777 (point)))))))
7779 (defun org-narrow-to-block ()
7780 "Narrow buffer to the current block."
7781 (interactive)
7782 (let* ((case-fold-search t)
7783 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7784 "^[ \t]*#\\+end_.*")))
7785 (if blockp
7786 (narrow-to-region (car blockp) (cdr blockp))
7787 (error "Not in a block"))))
7789 (eval-when-compile
7790 (defvar org-property-drawer-re))
7792 (defvar org-property-start-re) ;; defined below
7793 (defun org-clone-subtree-with-time-shift (n &optional shift)
7794 "Clone the task (subtree) at point N times.
7795 The clones will be inserted as siblings.
7797 In interactive use, the user will be prompted for the number of
7798 clones to be produced, and for a time SHIFT, which may be a
7799 repeater as used in time stamps, for example `+3d'.
7801 When a valid repeater is given and the entry contains any time
7802 stamps, the clones will become a sequence in time, with time
7803 stamps in the subtree shifted for each clone produced. If SHIFT
7804 is nil or the empty string, time stamps will be left alone. The
7805 ID property of the original subtree is removed.
7807 If the original subtree did contain time stamps with a repeater,
7808 the following will happen:
7809 - the repeater will be removed in each clone
7810 - an additional clone will be produced, with the current, unshifted
7811 date(s) in the entry.
7812 - the original entry will be placed *after* all the clones, with
7813 repeater intact.
7814 - the start days in the repeater in the original entry will be shifted
7815 to past the last clone.
7816 I this way you can spell out a number of instances of a repeating task,
7817 and still retain the repeater to cover future instances of the task."
7818 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7819 (let (beg end template task idprop
7820 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7821 (if (not (and (integerp n) (> n 0)))
7822 (error "Invalid number of replications %s" n))
7823 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7824 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7825 shift)))
7826 (error "Invalid shift specification %s" shift))
7827 (when doshift
7828 (setq shift-n (string-to-number (match-string 1 shift))
7829 shift-what (cdr (assoc (match-string 2 shift)
7830 '(("d" . day) ("w" . week)
7831 ("m" . month) ("y" . year))))))
7832 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7833 (setq nmin 1 nmax n)
7834 (org-back-to-heading t)
7835 (setq beg (point))
7836 (setq idprop (org-entry-get nil "ID"))
7837 (org-end-of-subtree t t)
7838 (or (bolp) (insert "\n"))
7839 (setq end (point))
7840 (setq template (buffer-substring beg end))
7841 ;; Remove clocks and empty drawers
7842 (with-temp-buffer
7843 (insert template)
7844 (goto-char (point-min))
7845 (while (re-search-forward
7846 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7847 (replace-match "")
7848 (kill-whole-line))
7849 (goto-char (point-min))
7850 (while (re-search-forward
7851 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7852 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7853 (setq template (buffer-substring (point-min) (point-max))))
7854 (when (and doshift
7855 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7856 (delete-region beg end)
7857 (setq end beg)
7858 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7859 (goto-char end)
7860 (loop for n from nmin to nmax do
7861 ;; prepare clone
7862 (with-temp-buffer
7863 (insert template)
7864 (org-mode)
7865 (goto-char (point-min))
7866 (and idprop (if org-clone-delete-id
7867 (org-entry-delete nil "ID")
7868 (org-id-get-create t)))
7869 (while (re-search-forward org-property-start-re nil t)
7870 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7871 (goto-char (point-min))
7872 (when doshift
7873 (while (re-search-forward org-ts-regexp-both nil t)
7874 (org-timestamp-change (* n shift-n) shift-what))
7875 (unless (= n n-no-remove)
7876 (goto-char (point-min))
7877 (while (re-search-forward org-ts-regexp nil t)
7878 (save-excursion
7879 (goto-char (match-beginning 0))
7880 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7881 (delete-region (match-beginning 1) (match-end 1)))))))
7882 (setq task (buffer-string)))
7883 (insert task))
7884 (goto-char beg)))
7886 ;;; Outline Sorting
7888 (defun org-sort (with-case)
7889 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7890 Optional argument WITH-CASE means sort case-sensitively.
7891 With a double prefix argument, also remove duplicate entries."
7892 (interactive "P")
7893 (cond
7894 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7895 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7897 (org-call-with-arg 'org-sort-entries with-case))))
7899 (defun org-sort-remove-invisible (s)
7900 (remove-text-properties 0 (length s) org-rm-props s)
7901 (while (string-match org-bracket-link-regexp s)
7902 (setq s (replace-match (if (match-end 2)
7903 (match-string 3 s)
7904 (match-string 1 s)) t t s)))
7907 (defvar org-priority-regexp) ; defined later in the file
7909 (defvar org-after-sorting-entries-or-items-hook nil
7910 "Hook that is run after a bunch of entries or items have been sorted.
7911 When children are sorted, the cursor is in the parent line when this
7912 hook gets called. When a region or a plain list is sorted, the cursor
7913 will be in the first entry of the sorted region/list.")
7915 (defun org-sort-entries
7916 (&optional with-case sorting-type getkey-func compare-func property)
7917 "Sort entries on a certain level of an outline tree.
7918 If there is an active region, the entries in the region are sorted.
7919 Else, if the cursor is before the first entry, sort the top-level items.
7920 Else, the children of the entry at point are sorted.
7922 Sorting can be alphabetically, numerically, by date/time as given by
7923 a time stamp, by a property or by priority.
7925 The command prompts for the sorting type unless it has been given to the
7926 function through the SORTING-TYPE argument, which needs to be a character,
7927 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7928 precise meaning of each character:
7930 n Numerically, by converting the beginning of the entry/item to a number.
7931 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7932 t By date/time, either the first active time stamp in the entry, or, if
7933 none exist, by the first inactive one.
7934 s By the scheduled date/time.
7935 d By deadline date/time.
7936 c By creation time, which is assumed to be the first inactive time stamp
7937 at the beginning of a line.
7938 p By priority according to the cookie.
7939 r By the value of a property.
7941 Capital letters will reverse the sort order.
7943 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7944 called with point at the beginning of the record. It must return either
7945 a string or a number that should serve as the sorting key for that record.
7947 Comparing entries ignores case by default. However, with an optional argument
7948 WITH-CASE, the sorting considers case as well."
7949 (interactive "P")
7950 (let ((case-func (if with-case 'identity 'downcase))
7951 start beg end stars re re2
7952 txt what tmp)
7953 ;; Find beginning and end of region to sort
7954 (cond
7955 ((org-region-active-p)
7956 ;; we will sort the region
7957 (setq end (region-end)
7958 what "region")
7959 (goto-char (region-beginning))
7960 (if (not (org-on-heading-p)) (outline-next-heading))
7961 (setq start (point)))
7962 ((or (org-on-heading-p)
7963 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7964 ;; we will sort the children of the current headline
7965 (org-back-to-heading)
7966 (setq start (point)
7967 end (progn (org-end-of-subtree t t)
7968 (or (bolp) (insert "\n"))
7969 (org-back-over-empty-lines)
7970 (point))
7971 what "children")
7972 (goto-char start)
7973 (show-subtree)
7974 (outline-next-heading))
7976 ;; we will sort the top-level entries in this file
7977 (goto-char (point-min))
7978 (or (org-on-heading-p) (outline-next-heading))
7979 (setq start (point))
7980 (goto-char (point-max))
7981 (beginning-of-line 1)
7982 (when (looking-at ".*?\\S-")
7983 ;; File ends in a non-white line
7984 (end-of-line 1)
7985 (insert "\n"))
7986 (setq end (point-max))
7987 (setq what "top-level")
7988 (goto-char start)
7989 (show-all)))
7991 (setq beg (point))
7992 (if (>= beg end) (error "Nothing to sort"))
7994 (looking-at "\\(\\*+\\)")
7995 (setq stars (match-string 1)
7996 re (concat "^" (regexp-quote stars) " +")
7997 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7998 txt (buffer-substring beg end))
7999 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8000 (if (and (not (equal stars "*")) (string-match re2 txt))
8001 (error "Region to sort contains a level above the first entry"))
8003 (unless sorting-type
8004 (message
8005 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8006 [t]ime [s]cheduled [d]eadline [c]reated
8007 A/N/T/S/D/C/P/O/F means reversed:"
8008 what)
8009 (setq sorting-type (read-char-exclusive))
8011 (and (= (downcase sorting-type) ?f)
8012 (setq getkey-func
8013 (org-icompleting-read "Sort using function: "
8014 obarray 'fboundp t nil nil))
8015 (setq getkey-func (intern getkey-func)))
8017 (and (= (downcase sorting-type) ?r)
8018 (setq property
8019 (org-icompleting-read "Property: "
8020 (mapcar 'list (org-buffer-property-keys t))
8021 nil t))))
8023 (message "Sorting entries...")
8025 (save-restriction
8026 (narrow-to-region start end)
8027 (let ((dcst (downcase sorting-type))
8028 (case-fold-search nil)
8029 (now (current-time)))
8030 (sort-subr
8031 (/= dcst sorting-type)
8032 ;; This function moves to the beginning character of the "record" to
8033 ;; be sorted.
8034 (lambda nil
8035 (if (re-search-forward re nil t)
8036 (goto-char (match-beginning 0))
8037 (goto-char (point-max))))
8038 ;; This function moves to the last character of the "record" being
8039 ;; sorted.
8040 (lambda nil
8041 (save-match-data
8042 (condition-case nil
8043 (outline-forward-same-level 1)
8044 (error
8045 (goto-char (point-max))))))
8046 ;; This function returns the value that gets sorted against.
8047 (lambda nil
8048 (cond
8049 ((= dcst ?n)
8050 (if (looking-at org-complex-heading-regexp)
8051 (string-to-number (match-string 4))
8052 nil))
8053 ((= dcst ?a)
8054 (if (looking-at org-complex-heading-regexp)
8055 (funcall case-func (match-string 4))
8056 nil))
8057 ((= dcst ?t)
8058 (let ((end (save-excursion (outline-next-heading) (point))))
8059 (if (or (re-search-forward org-ts-regexp end t)
8060 (re-search-forward org-ts-regexp-both end t))
8061 (org-time-string-to-seconds (match-string 0))
8062 (org-float-time now))))
8063 ((= dcst ?c)
8064 (let ((end (save-excursion (outline-next-heading) (point))))
8065 (if (re-search-forward
8066 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8067 end t)
8068 (org-time-string-to-seconds (match-string 0))
8069 (org-float-time now))))
8070 ((= dcst ?s)
8071 (let ((end (save-excursion (outline-next-heading) (point))))
8072 (if (re-search-forward org-scheduled-time-regexp end t)
8073 (org-time-string-to-seconds (match-string 1))
8074 (org-float-time now))))
8075 ((= dcst ?d)
8076 (let ((end (save-excursion (outline-next-heading) (point))))
8077 (if (re-search-forward org-deadline-time-regexp end t)
8078 (org-time-string-to-seconds (match-string 1))
8079 (org-float-time now))))
8080 ((= dcst ?p)
8081 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8082 (string-to-char (match-string 2))
8083 org-default-priority))
8084 ((= dcst ?r)
8085 (or (org-entry-get nil property) ""))
8086 ((= dcst ?o)
8087 (if (looking-at org-complex-heading-regexp)
8088 (- 9999 (length (member (match-string 2)
8089 org-todo-keywords-1)))))
8090 ((= dcst ?f)
8091 (if getkey-func
8092 (progn
8093 (setq tmp (funcall getkey-func))
8094 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8095 tmp)
8096 (error "Invalid key function `%s'" getkey-func)))
8097 (t (error "Invalid sorting type `%c'" sorting-type))))
8099 (cond
8100 ((= dcst ?a) 'string<)
8101 ((= dcst ?f) compare-func)
8102 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8103 (t nil)))))
8104 (run-hooks 'org-after-sorting-entries-or-items-hook)
8105 (message "Sorting entries...done")))
8107 (defun org-do-sort (table what &optional with-case sorting-type)
8108 "Sort TABLE of WHAT according to SORTING-TYPE.
8109 The user will be prompted for the SORTING-TYPE if the call to this
8110 function does not specify it. WHAT is only for the prompt, to indicate
8111 what is being sorted. The sorting key will be extracted from
8112 the car of the elements of the table.
8113 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8114 (unless sorting-type
8115 (message
8116 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8117 what)
8118 (setq sorting-type (read-char-exclusive)))
8119 (let ((dcst (downcase sorting-type))
8120 extractfun comparefun)
8121 ;; Define the appropriate functions
8122 (cond
8123 ((= dcst ?n)
8124 (setq extractfun 'string-to-number
8125 comparefun (if (= dcst sorting-type) '< '>)))
8126 ((= dcst ?a)
8127 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8128 (lambda(x) (downcase (org-sort-remove-invisible x))))
8129 comparefun (if (= dcst sorting-type)
8130 'string<
8131 (lambda (a b) (and (not (string< a b))
8132 (not (string= a b)))))))
8133 ((= dcst ?t)
8134 (setq extractfun
8135 (lambda (x)
8136 (if (or (string-match org-ts-regexp x)
8137 (string-match org-ts-regexp-both x))
8138 (org-float-time
8139 (org-time-string-to-time (match-string 0 x)))
8141 comparefun (if (= dcst sorting-type) '< '>)))
8142 (t (error "Invalid sorting type `%c'" sorting-type)))
8144 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8145 table)
8146 (lambda (a b) (funcall comparefun (car a) (car b))))))
8149 ;;; The orgstruct minor mode
8151 ;; Define a minor mode which can be used in other modes in order to
8152 ;; integrate the org-mode structure editing commands.
8154 ;; This is really a hack, because the org-mode structure commands use
8155 ;; keys which normally belong to the major mode. Here is how it
8156 ;; works: The minor mode defines all the keys necessary to operate the
8157 ;; structure commands, but wraps the commands into a function which
8158 ;; tests if the cursor is currently at a headline or a plain list
8159 ;; item. If that is the case, the structure command is used,
8160 ;; temporarily setting many Org-mode variables like regular
8161 ;; expressions for filling etc. However, when any of those keys is
8162 ;; used at a different location, function uses `key-binding' to look
8163 ;; up if the key has an associated command in another currently active
8164 ;; keymap (minor modes, major mode, global), and executes that
8165 ;; command. There might be problems if any of the keys is otherwise
8166 ;; used as a prefix key.
8168 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8169 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8170 ;; addresses this by checking explicitly for both bindings.
8172 (defvar orgstruct-mode-map (make-sparse-keymap)
8173 "Keymap for the minor `orgstruct-mode'.")
8175 (defvar org-local-vars nil
8176 "List of local variables, for use by `orgstruct-mode'.")
8178 ;;;###autoload
8179 (define-minor-mode orgstruct-mode
8180 "Toggle the minor mode `orgstruct-mode'.
8181 This mode is for using Org-mode structure commands in other
8182 modes. The following keys behave as if Org-mode were active, if
8183 the cursor is on a headline, or on a plain list item (both as
8184 defined by Org-mode).
8186 M-up Move entry/item up
8187 M-down Move entry/item down
8188 M-left Promote
8189 M-right Demote
8190 M-S-up Move entry/item up
8191 M-S-down Move entry/item down
8192 M-S-left Promote subtree
8193 M-S-right Demote subtree
8194 M-q Fill paragraph and items like in Org-mode
8195 C-c ^ Sort entries
8196 C-c - Cycle list bullet
8197 TAB Cycle item visibility
8198 M-RET Insert new heading/item
8199 S-M-RET Insert new TODO heading / Checkbox item
8200 C-c C-c Set tags / toggle checkbox"
8201 nil " OrgStruct" nil
8202 (org-load-modules-maybe)
8203 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8205 ;;;###autoload
8206 (defun turn-on-orgstruct ()
8207 "Unconditionally turn on `orgstruct-mode'."
8208 (orgstruct-mode 1))
8210 (defun orgstruct++-mode (&optional arg)
8211 "Toggle `orgstruct-mode', the enhanced version of it.
8212 In addition to setting orgstruct-mode, this also exports all indentation
8213 and autofilling variables from org-mode into the buffer. It will also
8214 recognize item context in multiline items.
8215 Note that turning off orgstruct-mode will *not* remove the
8216 indentation/paragraph settings. This can only be done by refreshing the
8217 major mode, for example with \\[normal-mode]."
8218 (interactive "P")
8219 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8220 (if (< arg 1)
8221 (orgstruct-mode -1)
8222 (orgstruct-mode 1)
8223 (let (var val)
8224 (mapc
8225 (lambda (x)
8226 (when (string-match
8227 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8228 (symbol-name (car x)))
8229 (setq var (car x) val (nth 1 x))
8230 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8231 org-local-vars)
8232 (org-set-local 'orgstruct-is-++ t))))
8234 (defvar orgstruct-is-++ nil
8235 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8236 (make-variable-buffer-local 'orgstruct-is-++)
8238 ;;;###autoload
8239 (defun turn-on-orgstruct++ ()
8240 "Unconditionally turn on `orgstruct++-mode'."
8241 (orgstruct++-mode 1))
8243 (defun orgstruct-error ()
8244 "Error when there is no default binding for a structure key."
8245 (interactive)
8246 (error "This key has no function outside structure elements"))
8248 (defun orgstruct-setup ()
8249 "Setup orgstruct keymaps."
8250 (let ((nfunc 0)
8251 (bindings
8252 (list
8253 '([(meta up)] org-metaup)
8254 '([(meta down)] org-metadown)
8255 '([(meta left)] org-metaleft)
8256 '([(meta right)] org-metaright)
8257 '([(meta shift up)] org-shiftmetaup)
8258 '([(meta shift down)] org-shiftmetadown)
8259 '([(meta shift left)] org-shiftmetaleft)
8260 '([(meta shift right)] org-shiftmetaright)
8261 '([?\e (up)] org-metaup)
8262 '([?\e (down)] org-metadown)
8263 '([?\e (left)] org-metaleft)
8264 '([?\e (right)] org-metaright)
8265 '([?\e (shift up)] org-shiftmetaup)
8266 '([?\e (shift down)] org-shiftmetadown)
8267 '([?\e (shift left)] org-shiftmetaleft)
8268 '([?\e (shift right)] org-shiftmetaright)
8269 '([(shift up)] org-shiftup)
8270 '([(shift down)] org-shiftdown)
8271 '([(shift left)] org-shiftleft)
8272 '([(shift right)] org-shiftright)
8273 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8274 '("\M-q" fill-paragraph)
8275 '("\C-c^" org-sort)
8276 '("\C-c-" org-cycle-list-bullet)))
8277 elt key fun cmd)
8278 (while (setq elt (pop bindings))
8279 (setq nfunc (1+ nfunc))
8280 (setq key (org-key (car elt))
8281 fun (nth 1 elt)
8282 cmd (orgstruct-make-binding fun nfunc key))
8283 (org-defkey orgstruct-mode-map key cmd))
8285 ;; Special treatment needed for TAB and RET
8286 (org-defkey orgstruct-mode-map [(tab)]
8287 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8288 (org-defkey orgstruct-mode-map "\C-i"
8289 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8291 (org-defkey orgstruct-mode-map "\M-\C-m"
8292 (orgstruct-make-binding 'org-insert-heading 105
8293 "\M-\C-m" [(meta return)]))
8294 (org-defkey orgstruct-mode-map [(meta return)]
8295 (orgstruct-make-binding 'org-insert-heading 106
8296 [(meta return)] "\M-\C-m"))
8298 (org-defkey orgstruct-mode-map [(shift meta return)]
8299 (orgstruct-make-binding 'org-insert-todo-heading 107
8300 [(meta return)] "\M-\C-m"))
8302 (org-defkey orgstruct-mode-map "\e\C-m"
8303 (orgstruct-make-binding 'org-insert-heading 108
8304 "\e\C-m" [?\e (return)]))
8305 (org-defkey orgstruct-mode-map [?\e (return)]
8306 (orgstruct-make-binding 'org-insert-heading 109
8307 [?\e (return)] "\e\C-m"))
8308 (org-defkey orgstruct-mode-map [?\e (shift return)]
8309 (orgstruct-make-binding 'org-insert-todo-heading 110
8310 [?\e (return)] "\e\C-m"))
8312 (unless org-local-vars
8313 (setq org-local-vars (org-get-local-variables)))
8317 (defun orgstruct-make-binding (fun n &rest keys)
8318 "Create a function for binding in the structure minor mode.
8319 FUN is the command to call inside a table. N is used to create a unique
8320 command name. KEYS are keys that should be checked in for a command
8321 to execute outside of tables."
8322 (eval
8323 (list 'defun
8324 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8325 '(arg)
8326 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8327 "Outside of structure, run the binding of `"
8328 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8329 "'.")
8330 '(interactive "p")
8331 (list 'if
8332 `(org-context-p 'headline 'item
8333 (and orgstruct-is-++
8334 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8335 'item-body))
8336 (list 'org-run-like-in-org-mode (list 'quote fun))
8337 (list 'let '(orgstruct-mode)
8338 (list 'call-interactively
8339 (append '(or)
8340 (mapcar (lambda (k)
8341 (list 'key-binding k))
8342 keys)
8343 '('orgstruct-error))))))))
8345 (defun org-context-p (&rest contexts)
8346 "Check if local context is any of CONTEXTS.
8347 Possible values in the list of contexts are `table', `headline', and `item'."
8348 (let ((pos (point)))
8349 (goto-char (point-at-bol))
8350 (prog1 (or (and (memq 'table contexts)
8351 (looking-at "[ \t]*|"))
8352 (and (memq 'headline contexts)
8353 (looking-at org-outline-regexp))
8354 (and (memq 'item contexts)
8355 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8356 (and (memq 'item-body contexts)
8357 (org-in-item-p)))
8358 (goto-char pos))))
8360 (defun org-get-local-variables ()
8361 "Return a list of all local variables in an org-mode buffer."
8362 (let (varlist)
8363 (with-current-buffer (get-buffer-create "*Org tmp*")
8364 (erase-buffer)
8365 (org-mode)
8366 (setq varlist (buffer-local-variables)))
8367 (kill-buffer "*Org tmp*")
8368 (delq nil
8369 (mapcar
8370 (lambda (x)
8371 (setq x
8372 (if (symbolp x)
8373 (list x)
8374 (list (car x) (list 'quote (cdr x)))))
8375 (if (string-match
8376 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8377 (symbol-name (car x)))
8378 x nil))
8379 varlist))))
8381 (defun org-clone-local-variables (from-buffer &optional regexp)
8382 "Clone local variables from FROM-BUFFER.
8383 Optional argument REGEXP selects variables to clone."
8384 (mapc
8385 (lambda (pair)
8386 (and (symbolp (car pair))
8387 (or (null regexp)
8388 (string-match regexp (symbol-name (car pair))))
8389 (set (make-local-variable (car pair))
8390 (cdr pair))))
8391 (buffer-local-variables from-buffer)))
8393 ;;;###autoload
8394 (defun org-run-like-in-org-mode (cmd)
8395 "Run a command, pretending that the current buffer is in Org-mode.
8396 This will temporarily bind local variables that are typically bound in
8397 Org-mode to the values they have in Org-mode, and then interactively
8398 call CMD."
8399 (org-load-modules-maybe)
8400 (unless org-local-vars
8401 (setq org-local-vars (org-get-local-variables)))
8402 (eval (list 'let org-local-vars
8403 (list 'call-interactively (list 'quote cmd)))))
8405 ;;;; Archiving
8407 (defun org-get-category (&optional pos force-refresh)
8408 "Get the category applying to position POS."
8409 (if force-refresh (org-refresh-category-properties))
8410 (let ((pos (or pos (point))))
8411 (or (get-text-property pos 'org-category)
8412 (progn (org-refresh-category-properties)
8413 (get-text-property pos 'org-category)))))
8415 (defun org-refresh-category-properties ()
8416 "Refresh category text properties in the buffer."
8417 (let ((def-cat (cond
8418 ((null org-category)
8419 (if buffer-file-name
8420 (file-name-sans-extension
8421 (file-name-nondirectory buffer-file-name))
8422 "???"))
8423 ((symbolp org-category) (symbol-name org-category))
8424 (t org-category)))
8425 beg end cat pos optionp)
8426 (org-unmodified
8427 (save-excursion
8428 (save-restriction
8429 (widen)
8430 (goto-char (point-min))
8431 (put-text-property (point) (point-max) 'org-category def-cat)
8432 (while (re-search-forward
8433 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8434 (setq pos (match-end 0)
8435 optionp (equal (char-after (match-beginning 0)) ?#)
8436 cat (org-trim (match-string 2)))
8437 (if optionp
8438 (setq beg (point-at-bol) end (point-max))
8439 (org-back-to-heading t)
8440 (setq beg (point) end (org-end-of-subtree t t)))
8441 (put-text-property beg end 'org-category cat)
8442 (put-text-property beg end 'org-category-position beg)
8443 (goto-char pos)))))))
8446 ;;;; Link Stuff
8448 ;;; Link abbreviations
8450 (defun org-link-expand-abbrev (link)
8451 "Apply replacements as defined in `org-link-abbrev-alist."
8452 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8453 (let* ((key (match-string 1 link))
8454 (as (or (assoc key org-link-abbrev-alist-local)
8455 (assoc key org-link-abbrev-alist)))
8456 (tag (and (match-end 2) (match-string 3 link)))
8457 rpl)
8458 (if (not as)
8459 link
8460 (setq rpl (cdr as))
8461 (cond
8462 ((symbolp rpl) (funcall rpl tag))
8463 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8464 ((string-match "%h" rpl)
8465 (replace-match (url-hexify-string (or tag "")) t t rpl))
8466 (t (concat rpl tag)))))
8467 link))
8469 ;;; Storing and inserting links
8471 (defvar org-insert-link-history nil
8472 "Minibuffer history for links inserted with `org-insert-link'.")
8474 (defvar org-stored-links nil
8475 "Contains the links stored with `org-store-link'.")
8477 (defvar org-store-link-plist nil
8478 "Plist with info about the most recently link created with `org-store-link'.")
8480 (defvar org-link-protocols nil
8481 "Link protocols added to Org-mode using `org-add-link-type'.")
8483 (defvar org-store-link-functions nil
8484 "List of functions that are called to create and store a link.
8485 Each function will be called in turn until one returns a non-nil
8486 value. Each function should check if it is responsible for creating
8487 this link (for example by looking at the major mode).
8488 If not, it must exit and return nil.
8489 If yes, it should return a non-nil value after a calling
8490 `org-store-link-props' with a list of properties and values.
8491 Special properties are:
8493 :type The link prefix, like \"http\". This must be given.
8494 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8495 This is obligatory as well.
8496 :description Optional default description for the second pair
8497 of brackets in an Org-mode link. The user can still change
8498 this when inserting this link into an Org-mode buffer.
8500 In addition to these, any additional properties can be specified
8501 and then used in remember templates.")
8503 (defun org-add-link-type (type &optional follow export)
8504 "Add TYPE to the list of `org-link-types'.
8505 Re-compute all regular expressions depending on `org-link-types'
8507 FOLLOW and EXPORT are two functions.
8509 FOLLOW should take the link path as the single argument and do whatever
8510 is necessary to follow the link, for example find a file or display
8511 a mail message.
8513 EXPORT should format the link path for export to one of the export formats.
8514 It should be a function accepting three arguments:
8516 path the path of the link, the text after the prefix (like \"http:\")
8517 desc the description of the link, if any, or a description added by
8518 org-export-normalize-links if there is none
8519 format the export format, a symbol like `html' or `latex' or `ascii'..
8521 The function may use the FORMAT information to return different values
8522 depending on the format. The return value will be put literally into
8523 the exported file. If the return value is nil, this means Org should
8524 do what it normally does with links which do not have EXPORT defined.
8526 Org-mode has a built-in default for exporting links. If you are happy with
8527 this default, there is no need to define an export function for the link
8528 type. For a simple example of an export function, see `org-bbdb.el'."
8529 (add-to-list 'org-link-types type t)
8530 (org-make-link-regexps)
8531 (if (assoc type org-link-protocols)
8532 (setcdr (assoc type org-link-protocols) (list follow export))
8533 (push (list type follow export) org-link-protocols)))
8535 (defvar org-agenda-buffer-name)
8537 ;;;###autoload
8538 (defun org-store-link (arg)
8539 "\\<org-mode-map>Store an org-link to the current location.
8540 This link is added to `org-stored-links' and can later be inserted
8541 into an org-buffer with \\[org-insert-link].
8543 For some link types, a prefix arg is interpreted:
8544 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8545 For file links, arg negates `org-context-in-file-links'."
8546 (interactive "P")
8547 (org-load-modules-maybe)
8548 (setq org-store-link-plist nil) ; reset
8549 (org-with-limited-levels
8550 (let (link cpltxt desc description search txt custom-id agenda-link)
8551 (cond
8553 ((run-hook-with-args-until-success 'org-store-link-functions)
8554 (setq link (plist-get org-store-link-plist :link)
8555 desc (or (plist-get org-store-link-plist :description) link)))
8557 ((equal (buffer-name) "*Org Edit Src Example*")
8558 (let (label gc)
8559 (while (or (not label)
8560 (save-excursion
8561 (save-restriction
8562 (widen)
8563 (goto-char (point-min))
8564 (re-search-forward
8565 (regexp-quote (format org-coderef-label-format label))
8566 nil t))))
8567 (when label (message "Label exists already") (sit-for 2))
8568 (setq label (read-string "Code line label: " label)))
8569 (end-of-line 1)
8570 (setq link (format org-coderef-label-format label))
8571 (setq gc (- 79 (length link)))
8572 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8573 (insert link)
8574 (setq link (concat "(" label ")") desc nil)))
8576 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8577 ;; We are in the agenda, link to referenced location
8578 (let ((m (or (get-text-property (point) 'org-hd-marker)
8579 (get-text-property (point) 'org-marker))))
8580 (when m
8581 (org-with-point-at m
8582 (setq agenda-link
8583 (if (org-called-interactively-p 'any)
8584 (call-interactively 'org-store-link)
8585 (org-store-link nil)))))))
8587 ((eq major-mode 'calendar-mode)
8588 (let ((cd (calendar-cursor-to-date)))
8589 (setq link
8590 (format-time-string
8591 (car org-time-stamp-formats)
8592 (apply 'encode-time
8593 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8594 nil nil nil))))
8595 (org-store-link-props :type "calendar" :date cd)))
8597 ((eq major-mode 'w3-mode)
8598 (setq cpltxt (if (and (buffer-name)
8599 (not (string-match "Untitled" (buffer-name))))
8600 (buffer-name)
8601 (url-view-url t))
8602 link (org-make-link (url-view-url t)))
8603 (org-store-link-props :type "w3" :url (url-view-url t)))
8605 ((eq major-mode 'w3m-mode)
8606 (setq cpltxt (or w3m-current-title w3m-current-url)
8607 link (org-make-link w3m-current-url))
8608 (org-store-link-props :type "w3m" :url (url-view-url t)))
8610 ((setq search (run-hook-with-args-until-success
8611 'org-create-file-search-functions))
8612 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8613 "::" search))
8614 (setq cpltxt (or description link)))
8616 ((eq major-mode 'image-mode)
8617 (setq cpltxt (concat "file:"
8618 (abbreviate-file-name buffer-file-name))
8619 link (org-make-link cpltxt))
8620 (org-store-link-props :type "image" :file buffer-file-name))
8622 ((eq major-mode 'dired-mode)
8623 ;; link to the file in the current line
8624 (let ((file (dired-get-filename nil t)))
8625 (setq file (if file
8626 (abbreviate-file-name
8627 (expand-file-name (dired-get-filename nil t)))
8628 ;; otherwise, no file so use current directory.
8629 default-directory))
8630 (setq cpltxt (concat "file:" file)
8631 link (org-make-link cpltxt))))
8633 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8634 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8635 (cond
8636 ((org-in-regexp "<<\\(.*?\\)>>")
8637 (setq cpltxt
8638 (concat "file:"
8639 (abbreviate-file-name
8640 (buffer-file-name (buffer-base-buffer)))
8641 "::" (match-string 1))
8642 link (org-make-link cpltxt)))
8643 ((and (featurep 'org-id)
8644 (or (eq org-link-to-org-use-id t)
8645 (and (eq org-link-to-org-use-id 'create-if-interactive)
8646 (org-called-interactively-p 'any))
8647 (and (eq org-link-to-org-use-id
8648 'create-if-interactive-and-no-custom-id)
8649 (org-called-interactively-p 'any)
8650 (not custom-id))
8651 (and org-link-to-org-use-id
8652 (org-entry-get nil "ID"))))
8653 ;; We can make a link using the ID.
8654 (setq link (condition-case nil
8655 (prog1 (org-id-store-link)
8656 (setq desc (plist-get org-store-link-plist
8657 :description)))
8658 (error
8659 ;; probably before first headline, link to file only
8660 (concat "file:"
8661 (abbreviate-file-name
8662 (buffer-file-name (buffer-base-buffer))))))))
8664 ;; Just link to current headline
8665 (setq cpltxt (concat "file:"
8666 (abbreviate-file-name
8667 (buffer-file-name (buffer-base-buffer)))))
8668 ;; Add a context search string
8669 (when (org-xor org-context-in-file-links arg)
8670 (setq txt (cond
8671 ((org-on-heading-p) nil)
8672 ((org-region-active-p)
8673 (buffer-substring (region-beginning) (region-end)))
8674 (t nil)))
8675 (when (or (null txt) (string-match "\\S-" txt))
8676 (setq cpltxt
8677 (concat cpltxt "::"
8678 (condition-case nil
8679 (org-make-org-heading-search-string txt)
8680 (error "")))
8681 desc (or (nth 4 (ignore-errors
8682 (org-heading-components))) "NONE"))))
8683 (if (string-match "::\\'" cpltxt)
8684 (setq cpltxt (substring cpltxt 0 -2)))
8685 (setq link (org-make-link cpltxt)))))
8687 ((buffer-file-name (buffer-base-buffer))
8688 ;; Just link to this file here.
8689 (setq cpltxt (concat "file:"
8690 (abbreviate-file-name
8691 (buffer-file-name (buffer-base-buffer)))))
8692 ;; Add a context string
8693 (when (org-xor org-context-in-file-links arg)
8694 (setq txt (if (org-region-active-p)
8695 (buffer-substring (region-beginning) (region-end))
8696 (buffer-substring (point-at-bol) (point-at-eol))))
8697 ;; Only use search option if there is some text.
8698 (when (string-match "\\S-" txt)
8699 (setq cpltxt
8700 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8701 desc "NONE")))
8702 (setq link (org-make-link cpltxt)))
8704 ((org-called-interactively-p 'interactive)
8705 (error "Cannot link to a buffer which is not visiting a file"))
8707 (t (setq link nil)))
8709 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8710 (setq link (or link cpltxt)
8711 desc (or desc cpltxt))
8712 (if (equal desc "NONE") (setq desc nil))
8714 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8715 (progn
8716 (setq org-stored-links
8717 (cons (list link desc) org-stored-links))
8718 (message "Stored: %s" (or desc link))
8719 (when custom-id
8720 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8721 "::#" custom-id))
8722 (setq org-stored-links
8723 (cons (list link desc) org-stored-links))))
8724 (or agenda-link (and link (org-make-link-string link desc)))))))
8726 (defun org-store-link-props (&rest plist)
8727 "Store link properties, extract names and addresses."
8728 (let (x adr)
8729 (when (setq x (plist-get plist :from))
8730 (setq adr (mail-extract-address-components x))
8731 (setq plist (plist-put plist :fromname (car adr)))
8732 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8733 (when (setq x (plist-get plist :to))
8734 (setq adr (mail-extract-address-components x))
8735 (setq plist (plist-put plist :toname (car adr)))
8736 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8737 (let ((from (plist-get plist :from))
8738 (to (plist-get plist :to)))
8739 (when (and from to org-from-is-user-regexp)
8740 (setq plist
8741 (plist-put plist :fromto
8742 (if (string-match org-from-is-user-regexp from)
8743 (concat "to %t")
8744 (concat "from %f"))))))
8745 (setq org-store-link-plist plist))
8747 (defun org-add-link-props (&rest plist)
8748 "Add these properties to the link property list."
8749 (let (key value)
8750 (while plist
8751 (setq key (pop plist) value (pop plist))
8752 (setq org-store-link-plist
8753 (plist-put org-store-link-plist key value)))))
8755 (defun org-email-link-description (&optional fmt)
8756 "Return the description part of an email link.
8757 This takes information from `org-store-link-plist' and formats it
8758 according to FMT (default from `org-email-link-description-format')."
8759 (setq fmt (or fmt org-email-link-description-format))
8760 (let* ((p org-store-link-plist)
8761 (to (plist-get p :toaddress))
8762 (from (plist-get p :fromaddress))
8763 (table
8764 (list
8765 (cons "%c" (plist-get p :fromto))
8766 (cons "%F" (plist-get p :from))
8767 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8768 (cons "%T" (plist-get p :to))
8769 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8770 (cons "%s" (plist-get p :subject))
8771 (cons "%d" (plist-get p :date))
8772 (cons "%m" (plist-get p :message-id)))))
8773 (when (string-match "%c" fmt)
8774 ;; Check if the user wrote this message
8775 (if (and org-from-is-user-regexp from to
8776 (save-match-data (string-match org-from-is-user-regexp from)))
8777 (setq fmt (replace-match "to %t" t t fmt))
8778 (setq fmt (replace-match "from %f" t t fmt))))
8779 (org-replace-escapes fmt table)))
8781 (defun org-make-org-heading-search-string (&optional string heading)
8782 "Make search string for STRING or current headline."
8783 (interactive)
8784 (let ((s (or string (org-get-heading)))
8785 (lines org-context-in-file-links))
8786 (unless (and string (not heading))
8787 ;; We are using a headline, clean up garbage in there.
8788 (if (string-match org-todo-regexp s)
8789 (setq s (replace-match "" t t s)))
8790 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8791 (setq s (replace-match "" t t s)))
8792 (setq s (org-trim s))
8793 (if (string-match (concat "^\\(" org-quote-string "\\|"
8794 org-comment-string "\\)") s)
8795 (setq s (replace-match "" t t s)))
8796 (while (string-match org-ts-regexp s)
8797 (setq s (replace-match "" t t s))))
8798 (or string (setq s (concat "*" s))) ; Add * for headlines
8799 (when (and string (integerp lines) (> lines 0))
8800 (let ((slines (org-split-string s "\n")))
8801 (when (< lines (length slines))
8802 (setq s (mapconcat
8803 'identity
8804 (reverse (nthcdr (- (length slines) lines)
8805 (reverse slines))) "\n")))))
8806 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8808 (defun org-make-link (&rest strings)
8809 "Concatenate STRINGS."
8810 (apply 'concat strings))
8812 (defun org-make-link-string (link &optional description)
8813 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8814 (unless (string-match "\\S-" link)
8815 (error "Empty link"))
8816 (when (and description
8817 (stringp description)
8818 (not (string-match "\\S-" description)))
8819 (setq description nil))
8820 (when (stringp description)
8821 ;; Remove brackets from the description, they are fatal.
8822 (while (string-match "\\[" description)
8823 (setq description (replace-match "{" t t description)))
8824 (while (string-match "\\]" description)
8825 (setq description (replace-match "}" t t description))))
8826 (when (equal link description)
8827 ;; No description needed, it is identical
8828 (setq description nil))
8829 (when (and (not description)
8830 (not (string-match (org-image-file-name-regexp) link))
8831 (not (equal link (org-link-escape link))))
8832 (setq description (org-extract-attributes link)))
8833 (setq link
8834 (cond ((string-match (org-image-file-name-regexp) link) link)
8835 ((string-match org-link-types-re link)
8836 (concat (match-string 1 link)
8837 (org-link-escape (substring link (match-end 1)))))
8838 (t (org-link-escape link))))
8839 (concat "[[" link "]"
8840 (if description (concat "[" description "]") "")
8841 "]"))
8843 (defconst org-link-escape-chars
8844 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8845 "List of characters that should be escaped in link.
8846 This is the list that is used for internal purposes.")
8848 (defvar org-url-encoding-use-url-hexify nil)
8850 (defconst org-link-escape-chars-browser
8851 '(?\ )
8852 "List of escapes for characters that are problematic in links.
8853 This is the list that is used before handing over to the browser.")
8855 (defun org-link-escape (text &optional table merge)
8856 "Return percent escaped representation of TEXT.
8857 TEXT is a string with the text to escape.
8858 Optional argument TABLE is a list with characters that should be
8859 escaped. When nil, `org-link-escape-chars' is used.
8860 If optional argument MERGE is set, merge TABLE into
8861 `org-link-escape-chars'."
8862 (if (and org-url-encoding-use-url-hexify (not table))
8863 (url-hexify-string text)
8864 (cond
8865 ((and table merge)
8866 (mapc (lambda (defchr)
8867 (unless (member defchr table)
8868 (setq table (cons defchr table)))) org-link-escape-chars))
8869 ((null table)
8870 (setq table org-link-escape-chars)))
8871 (mapconcat
8872 (lambda (char)
8873 (if (or (member char table)
8874 (< char 32) (= char 37) (> char 126))
8875 (mapconcat (lambda (sequence-element)
8876 (format "%%%.2X" sequence-element))
8877 (or (encode-coding-char char 'utf-8)
8878 (error "Unable to percent escape character: %s"
8879 (char-to-string char))) "")
8880 (char-to-string char))) text "")))
8882 (defun org-link-unescape (str)
8883 "Unhex hexified unicode strings as returned from the JavaScript function
8884 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8885 (unless (and (null str) (string= "" str))
8886 (let ((pos 0) (case-fold-search t) unhexed)
8887 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8888 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8889 (setq str (replace-match unhexed t t str))
8890 (setq pos (+ pos (length unhexed))))))
8891 str)
8893 (defun org-link-unescape-compound (hex)
8894 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8895 Note: this function also decodes single byte encodings like
8896 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8897 (save-match-data
8898 (let* ((bytes (cdr (split-string hex "%")))
8899 (ret "")
8900 (eat 0)
8901 (sum 0))
8902 (while bytes
8903 (let* ((val (string-to-number (pop bytes) 16))
8904 (shift-xor
8905 (if (= 0 eat)
8906 (cond
8907 ((>= val 252) (cons 6 252))
8908 ((>= val 248) (cons 5 248))
8909 ((>= val 240) (cons 4 240))
8910 ((>= val 224) (cons 3 224))
8911 ((>= val 192) (cons 2 192))
8912 (t (cons 0 0)))
8913 (cons 6 128))))
8914 (if (>= val 192) (setq eat (car shift-xor)))
8915 (setq val (logxor val (cdr shift-xor)))
8916 (setq sum (+ (lsh sum (car shift-xor)) val))
8917 (if (> eat 0) (setq eat (- eat 1)))
8918 (cond
8919 ((= 0 eat) ;multi byte
8920 (setq ret (concat ret (org-char-to-string sum)))
8921 (setq sum 0))
8922 ((not bytes) ; single byte(s)
8923 (setq ret (org-link-unescape-single-byte-sequence hex))))
8924 )) ;; end (while bytes
8925 ret )))
8927 (defun org-link-unescape-single-byte-sequence (hex)
8928 "Unhexify hex-encoded single byte character sequences."
8929 (mapconcat (lambda (byte)
8930 (char-to-string (string-to-number byte 16)))
8931 (cdr (split-string hex "%")) ""))
8933 (defun org-xor (a b)
8934 "Exclusive or."
8935 (if a (not b) b))
8937 (defun org-fixup-message-id-for-http (s)
8938 "Replace special characters in a message id, so it can be used in an http query."
8939 (when (string-match "%" s)
8940 (setq s (mapconcat (lambda (c)
8941 (if (eq c ?%)
8942 "%25"
8943 (char-to-string c)))
8944 s "")))
8945 (while (string-match "<" s)
8946 (setq s (replace-match "%3C" t t s)))
8947 (while (string-match ">" s)
8948 (setq s (replace-match "%3E" t t s)))
8949 (while (string-match "@" s)
8950 (setq s (replace-match "%40" t t s)))
8953 ;;;###autoload
8954 (defun org-insert-link-global ()
8955 "Insert a link like Org-mode does.
8956 This command can be called in any mode to insert a link in Org-mode syntax."
8957 (interactive)
8958 (org-load-modules-maybe)
8959 (org-run-like-in-org-mode 'org-insert-link))
8961 (defun org-insert-link (&optional complete-file link-location)
8962 "Insert a link. At the prompt, enter the link.
8964 Completion can be used to insert any of the link protocol prefixes like
8965 http or ftp in use.
8967 The history can be used to select a link previously stored with
8968 `org-store-link'. When the empty string is entered (i.e. if you just
8969 press RET at the prompt), the link defaults to the most recently
8970 stored link. As SPC triggers completion in the minibuffer, you need to
8971 use M-SPC or C-q SPC to force the insertion of a space character.
8973 You will also be prompted for a description, and if one is given, it will
8974 be displayed in the buffer instead of the link.
8976 If there is already a link at point, this command will allow you to edit link
8977 and description parts.
8979 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8980 be selected using completion. The path to the file will be relative to the
8981 current directory if the file is in the current directory or a subdirectory.
8982 Otherwise, the link will be the absolute path as completed in the minibuffer
8983 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8984 option `org-link-file-path-type'.
8986 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8987 the current directory or below.
8989 With three \\[universal-argument] prefixes, negate the meaning of
8990 `org-keep-stored-link-after-insertion'.
8992 If `org-make-link-description-function' is non-nil, this function will be
8993 called with the link target, and the result will be the default
8994 link description.
8996 If the LINK-LOCATION parameter is non-nil, this value will be
8997 used as the link location instead of reading one interactively."
8998 (interactive "P")
8999 (let* ((wcf (current-window-configuration))
9000 (region (if (org-region-active-p)
9001 (buffer-substring (region-beginning) (region-end))))
9002 (remove (and region (list (region-beginning) (region-end))))
9003 (desc region)
9004 tmphist ; byte-compile incorrectly complains about this
9005 (link link-location)
9006 entry file all-prefixes)
9007 (cond
9008 (link-location) ; specified by arg, just use it.
9009 ((org-in-regexp org-bracket-link-regexp 1)
9010 ;; We do have a link at point, and we are going to edit it.
9011 (setq remove (list (match-beginning 0) (match-end 0)))
9012 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9013 (setq link (read-string "Link: "
9014 (org-link-unescape
9015 (org-match-string-no-properties 1)))))
9016 ((or (org-in-regexp org-angle-link-re)
9017 (org-in-regexp org-plain-link-re))
9018 ;; Convert to bracket link
9019 (setq remove (list (match-beginning 0) (match-end 0))
9020 link (read-string "Link: "
9021 (org-remove-angle-brackets (match-string 0)))))
9022 ((member complete-file '((4) (16)))
9023 ;; Completing read for file names.
9024 (setq link (org-file-complete-link complete-file)))
9026 ;; Read link, with completion for stored links.
9027 (with-output-to-temp-buffer "*Org Links*"
9028 (princ "Insert a link.
9029 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9030 (when org-stored-links
9031 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9032 (princ (mapconcat
9033 (lambda (x)
9034 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9035 (reverse org-stored-links) "\n"))))
9036 (let ((cw (selected-window)))
9037 (select-window (get-buffer-window "*Org Links*" 'visible))
9038 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9039 (unless (pos-visible-in-window-p (point-max))
9040 (org-fit-window-to-buffer))
9041 (and (window-live-p cw) (select-window cw)))
9042 ;; Fake a link history, containing the stored links.
9043 (setq tmphist (append (mapcar 'car org-stored-links)
9044 org-insert-link-history))
9045 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9046 (mapcar 'car org-link-abbrev-alist)
9047 org-link-types))
9048 (unwind-protect
9049 (progn
9050 (setq link
9051 (let ((org-completion-use-ido nil)
9052 (org-completion-use-iswitchb nil))
9053 (org-completing-read
9054 "Link: "
9055 (append
9056 (mapcar (lambda (x) (list (concat x ":")))
9057 all-prefixes)
9058 (mapcar 'car org-stored-links))
9059 nil nil nil
9060 'tmphist
9061 (car (car org-stored-links)))))
9062 (if (not (string-match "\\S-" link))
9063 (error "No link selected"))
9064 (if (or (member link all-prefixes)
9065 (and (equal ":" (substring link -1))
9066 (member (substring link 0 -1) all-prefixes)
9067 (setq link (substring link 0 -1))))
9068 (setq link (org-link-try-special-completion link))))
9069 (set-window-configuration wcf)
9070 (kill-buffer "*Org Links*"))
9071 (setq entry (assoc link org-stored-links))
9072 (or entry (push link org-insert-link-history))
9073 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9074 (not org-keep-stored-link-after-insertion))
9075 (setq org-stored-links (delq (assoc link org-stored-links)
9076 org-stored-links)))
9077 (setq desc (or desc (nth 1 entry)))))
9079 (if (string-match org-plain-link-re link)
9080 ;; URL-like link, normalize the use of angular brackets.
9081 (setq link (org-make-link (org-remove-angle-brackets link))))
9083 ;; Check if we are linking to the current file with a search option
9084 ;; If yes, simplify the link by using only the search option.
9085 (when (and buffer-file-name
9086 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9087 (let* ((path (match-string 1 link))
9088 (case-fold-search nil)
9089 (search (match-string 2 link)))
9090 (save-match-data
9091 (if (equal (file-truename buffer-file-name) (file-truename path))
9092 ;; We are linking to this same file, with a search option
9093 (setq link search)))))
9095 ;; Check if we can/should use a relative path. If yes, simplify the link
9096 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9097 (let* ((type (match-string 1 link))
9098 (path (match-string 2 link))
9099 (origpath path)
9100 (case-fold-search nil))
9101 (cond
9102 ((or (eq org-link-file-path-type 'absolute)
9103 (equal complete-file '(16)))
9104 (setq path (abbreviate-file-name (expand-file-name path))))
9105 ((eq org-link-file-path-type 'noabbrev)
9106 (setq path (expand-file-name path)))
9107 ((eq org-link-file-path-type 'relative)
9108 (setq path (file-relative-name path)))
9110 (save-match-data
9111 (if (string-match (concat "^" (regexp-quote
9112 (expand-file-name
9113 (file-name-as-directory
9114 default-directory))))
9115 (expand-file-name path))
9116 ;; We are linking a file with relative path name.
9117 (setq path (substring (expand-file-name path)
9118 (match-end 0)))
9119 (setq path (abbreviate-file-name (expand-file-name path)))))))
9120 (setq link (concat type path))
9121 (if (equal desc origpath)
9122 (setq desc path))))
9124 (if org-make-link-description-function
9125 (setq desc (funcall org-make-link-description-function link desc)))
9127 (setq desc (read-string "Description: " desc))
9128 (unless (string-match "\\S-" desc) (setq desc nil))
9129 (if remove (apply 'delete-region remove))
9130 (insert (org-make-link-string link desc))))
9132 (defun org-link-try-special-completion (type)
9133 "If there is completion support for link type TYPE, offer it."
9134 (let ((fun (intern (concat "org-" type "-complete-link"))))
9135 (if (functionp fun)
9136 (funcall fun)
9137 (read-string "Link (no completion support): " (concat type ":")))))
9139 (defun org-file-complete-link (&optional arg)
9140 "Create a file link using completion."
9141 (let (file link)
9142 (setq file (read-file-name "File: "))
9143 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9144 (pwd1 (file-name-as-directory (abbreviate-file-name
9145 (expand-file-name ".")))))
9146 (cond
9147 ((equal arg '(16))
9148 (setq link (org-make-link
9149 "file:"
9150 (abbreviate-file-name (expand-file-name file)))))
9151 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9152 (setq link (org-make-link "file:" (match-string 1 file))))
9153 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9154 (expand-file-name file))
9155 (setq link (org-make-link
9156 "file:" (match-string 1 (expand-file-name file)))))
9157 (t (setq link (org-make-link "file:" file)))))
9158 link))
9160 (defun org-completing-read (&rest args)
9161 "Completing-read with SPACE being a normal character."
9162 (let ((minibuffer-local-completion-map
9163 (copy-keymap minibuffer-local-completion-map)))
9164 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9165 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9166 (apply 'org-icompleting-read args)))
9168 (defun org-completing-read-no-i (&rest args)
9169 (let (org-completion-use-ido org-completion-use-iswitchb)
9170 (apply 'org-completing-read args)))
9172 (defun org-iswitchb-completing-read (prompt choices &rest args)
9173 "Use iswitch as a completing-read replacement to choose from choices.
9174 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9175 from."
9176 (let* ((iswitchb-use-virtual-buffers nil)
9177 (iswitchb-make-buflist-hook
9178 (lambda ()
9179 (setq iswitchb-temp-buflist choices))))
9180 (iswitchb-read-buffer prompt)))
9182 (defun org-icompleting-read (&rest args)
9183 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9184 (org-without-partial-completion
9185 (if (and org-completion-use-ido
9186 (fboundp 'ido-completing-read)
9187 (boundp 'ido-mode) ido-mode
9188 (listp (second args)))
9189 (let ((ido-enter-matching-directory nil))
9190 (apply 'ido-completing-read (concat (car args))
9191 (if (consp (car (nth 1 args)))
9192 (mapcar 'car (nth 1 args))
9193 (nth 1 args))
9194 (cddr args)))
9195 (if (and org-completion-use-iswitchb
9196 (boundp 'iswitchb-mode) iswitchb-mode
9197 (listp (second args)))
9198 (apply 'org-iswitchb-completing-read (concat (car args))
9199 (if (consp (car (nth 1 args)))
9200 (mapcar 'car (nth 1 args))
9201 (nth 1 args))
9202 (cddr args))
9203 (apply 'completing-read args)))))
9205 (defun org-extract-attributes (s)
9206 "Extract the attributes cookie from a string and set as text property."
9207 (let (a attr (start 0) key value)
9208 (save-match-data
9209 (when (string-match "{{\\([^}]+\\)}}$" s)
9210 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9211 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9212 (setq key (match-string 1 a) value (match-string 2 a)
9213 start (match-end 0)
9214 attr (plist-put attr (intern key) value))))
9215 (org-add-props s nil 'org-attr attr))
9218 (defun org-extract-attributes-from-string (tag)
9219 (let (key value attr)
9220 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9221 (setq key (match-string 1 tag) value (match-string 2 tag)
9222 tag (replace-match "" t t tag)
9223 attr (plist-put attr (intern key) value)))
9224 (cons tag attr)))
9226 (defun org-attributes-to-string (plist)
9227 "Format a property list into an HTML attribute list."
9228 (let ((s "") key value)
9229 (while plist
9230 (setq key (pop plist) value (pop plist))
9231 (and value
9232 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9235 ;;; Opening/following a link
9237 (defvar org-link-search-failed nil)
9239 (defvar org-open-link-functions nil
9240 "Hook for functions finding a plain text link.
9241 These functions must take a single argument, the link content.
9242 They will be called for links that look like [[link text][description]]
9243 when LINK TEXT does not have a protocol like \"http:\" and does not look
9244 like a filename (e.g. \"./blue.png\").
9246 These functions will be called *before* Org attempts to resolve the
9247 link by doing text searches in the current buffer - so if you want a
9248 link \"[[target]]\" to still find \"<<target>>\", your function should
9249 handle this as a special case.
9251 When the function does handle the link, it must return a non-nil value.
9252 If it decides that it is not responsible for this link, it must return
9253 nil to indicate that that Org-mode can continue with other options
9254 like exact and fuzzy text search.")
9256 (defun org-next-link ()
9257 "Move forward to the next link.
9258 If the link is in hidden text, expose it."
9259 (interactive)
9260 (when (and org-link-search-failed (eq this-command last-command))
9261 (goto-char (point-min))
9262 (message "Link search wrapped back to beginning of buffer"))
9263 (setq org-link-search-failed nil)
9264 (let* ((pos (point))
9265 (ct (org-context))
9266 (a (assoc :link ct)))
9267 (if a (goto-char (nth 2 a)))
9268 (if (re-search-forward org-any-link-re nil t)
9269 (progn
9270 (goto-char (match-beginning 0))
9271 (if (outline-invisible-p) (org-show-context)))
9272 (goto-char pos)
9273 (setq org-link-search-failed t)
9274 (error "No further link found"))))
9276 (defun org-previous-link ()
9277 "Move backward to the previous link.
9278 If the link is in hidden text, expose it."
9279 (interactive)
9280 (when (and org-link-search-failed (eq this-command last-command))
9281 (goto-char (point-max))
9282 (message "Link search wrapped back to end of buffer"))
9283 (setq org-link-search-failed nil)
9284 (let* ((pos (point))
9285 (ct (org-context))
9286 (a (assoc :link ct)))
9287 (if a (goto-char (nth 1 a)))
9288 (if (re-search-backward org-any-link-re nil t)
9289 (progn
9290 (goto-char (match-beginning 0))
9291 (if (outline-invisible-p) (org-show-context)))
9292 (goto-char pos)
9293 (setq org-link-search-failed t)
9294 (error "No further link found"))))
9296 (defun org-translate-link (s)
9297 "Translate a link string if a translation function has been defined."
9298 (if (and org-link-translation-function
9299 (fboundp org-link-translation-function)
9300 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9301 (progn
9302 (setq s (funcall org-link-translation-function
9303 (match-string 1) (match-string 2)))
9304 (concat (car s) ":" (cdr s)))
9307 (defun org-translate-link-from-planner (type path)
9308 "Translate a link from Emacs Planner syntax so that Org can follow it.
9309 This is still an experimental function, your mileage may vary."
9310 (cond
9311 ((member type '("http" "https" "news" "ftp"))
9312 ;; standard Internet links are the same.
9313 nil)
9314 ((and (equal type "irc") (string-match "^//" path))
9315 ;; Planner has two / at the beginning of an irc link, we have 1.
9316 ;; We should have zero, actually....
9317 (setq path (substring path 1)))
9318 ((and (equal type "lisp") (string-match "^/" path))
9319 ;; Planner has a slash, we do not.
9320 (setq type "elisp" path (substring path 1)))
9321 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9322 ;; A typical message link. Planner has the id after the final slash,
9323 ;; we separate it with a hash mark
9324 (setq path (concat (match-string 1 path) "#"
9325 (org-remove-angle-brackets (match-string 2 path)))))
9327 (cons type path))
9329 (defun org-find-file-at-mouse (ev)
9330 "Open file link or URL at mouse."
9331 (interactive "e")
9332 (mouse-set-point ev)
9333 (org-open-at-point 'in-emacs))
9335 (defun org-open-at-mouse (ev)
9336 "Open file link or URL at mouse.
9337 See the docstring of `org-open-file' for details."
9338 (interactive "e")
9339 (mouse-set-point ev)
9340 (if (eq major-mode 'org-agenda-mode)
9341 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9342 (org-open-at-point))
9344 (defvar org-window-config-before-follow-link nil
9345 "The window configuration before following a link.
9346 This is saved in case the need arises to restore it.")
9348 (defvar org-open-link-marker (make-marker)
9349 "Marker pointing to the location where `org-open-at-point; was called.")
9351 ;;;###autoload
9352 (defun org-open-at-point-global ()
9353 "Follow a link like Org-mode does.
9354 This command can be called in any mode to follow a link that has
9355 Org-mode syntax."
9356 (interactive)
9357 (org-run-like-in-org-mode 'org-open-at-point))
9359 ;;;###autoload
9360 (defun org-open-link-from-string (s &optional arg reference-buffer)
9361 "Open a link in the string S, as if it was in Org-mode."
9362 (interactive "sLink: \nP")
9363 (let ((reference-buffer (or reference-buffer (current-buffer))))
9364 (with-temp-buffer
9365 (let ((org-inhibit-startup t))
9366 (org-mode)
9367 (insert s)
9368 (goto-char (point-min))
9369 (when reference-buffer
9370 (setq org-link-abbrev-alist-local
9371 (with-current-buffer reference-buffer
9372 org-link-abbrev-alist-local)))
9373 (org-open-at-point arg reference-buffer)))))
9375 (defvar org-open-at-point-functions nil
9376 "Hook that is run when following a link at point.
9378 Functions in this hook must return t if they identify and follow
9379 a link at point. If they don't find anything interesting at point,
9380 they must return nil.")
9382 (defun org-open-at-point (&optional arg reference-buffer)
9383 "Open link at or after point.
9384 If there is no link at point, this function will search forward up to
9385 the end of the current line.
9386 Normally, files will be opened by an appropriate application. If the
9387 optional prefix argument ARG is non-nil, Emacs will visit the file.
9388 With a double prefix argument, try to open outside of Emacs, in the
9389 application the system uses for this file type."
9390 (interactive "P")
9391 ;; if in a code block, then open the block's results
9392 (unless (call-interactively #'org-babel-open-src-block-result)
9393 (org-load-modules-maybe)
9394 (move-marker org-open-link-marker (point))
9395 (setq org-window-config-before-follow-link (current-window-configuration))
9396 (org-remove-occur-highlights nil nil t)
9397 (cond
9398 ((and (org-on-heading-p)
9399 (not (org-in-regexp
9400 (concat org-plain-link-re "\\|"
9401 org-bracket-link-regexp "\\|"
9402 org-angle-link-re "\\|"
9403 "[ \t]:[^ \t\n]+:[ \t]*$")))
9404 (not (get-text-property (point) 'org-linked-text)))
9405 (or (org-offer-links-in-entry arg)
9406 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9407 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9408 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9409 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9410 (not (org-in-regexp org-bracket-link-regexp)))
9411 (org-footnote-action))
9413 (let (type path link line search (pos (point)))
9414 (catch 'match
9415 (save-excursion
9416 (skip-chars-forward "^]\n\r")
9417 (when (org-in-regexp org-bracket-link-regexp 1)
9418 (setq link (org-extract-attributes
9419 (org-link-unescape (org-match-string-no-properties 1))))
9420 (while (string-match " *\n *" link)
9421 (setq link (replace-match " " t t link)))
9422 (setq link (org-link-expand-abbrev link))
9423 (cond
9424 ((or (file-name-absolute-p link)
9425 (string-match "^\\.\\.?/" link))
9426 (setq type "file" path link))
9427 ((string-match org-link-re-with-space3 link)
9428 (setq type (match-string 1 link) path (match-string 2 link)))
9429 (t (setq type "thisfile" path link)))
9430 (throw 'match t)))
9432 (when (get-text-property (point) 'org-linked-text)
9433 (setq type "thisfile"
9434 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9435 (1+ (point)) (point))
9436 path (buffer-substring
9437 (or (previous-single-property-change pos 'org-linked-text)
9438 (point-min))
9439 (or (next-single-property-change pos 'org-linked-text)
9440 (point-max))))
9441 (throw 'match t))
9443 (save-excursion
9444 (when (or (org-in-regexp org-angle-link-re)
9445 (org-in-regexp org-plain-link-re))
9446 (setq type (match-string 1)
9447 path (org-link-unescape (match-string 2)))
9448 (throw 'match t)))
9449 (save-excursion
9450 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9451 (setq type "tags"
9452 path (match-string 1))
9453 (while (string-match ":" path)
9454 (setq path (replace-match "+" t t path)))
9455 (throw 'match t)))
9456 (when (org-in-regexp "<\\([^><\n]+\\)>")
9457 (setq type "tree-match"
9458 path (match-string 1))
9459 (throw 'match t)))
9460 (unless path
9461 (error "No link found"))
9463 ;; switch back to reference buffer
9464 ;; needed when if called in a temporary buffer through
9465 ;; org-open-link-from-string
9466 (with-current-buffer (or reference-buffer (current-buffer))
9468 ;; Remove any trailing spaces in path
9469 (if (string-match " +\\'" path)
9470 (setq path (replace-match "" t t path)))
9471 (if (and org-link-translation-function
9472 (fboundp org-link-translation-function))
9473 ;; Check if we need to translate the link
9474 (let ((tmp (funcall org-link-translation-function type path)))
9475 (setq type (car tmp) path (cdr tmp))))
9477 (cond
9479 ((assoc type org-link-protocols)
9480 (funcall (nth 1 (assoc type org-link-protocols)) path))
9482 ((equal type "mailto")
9483 (let ((cmd (car org-link-mailto-program))
9484 (args (cdr org-link-mailto-program)) args1
9485 (address path) (subject "") a)
9486 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9487 (setq address (match-string 1 path)
9488 subject (org-link-escape (match-string 2 path))))
9489 (while args
9490 (cond
9491 ((not (stringp (car args))) (push (pop args) args1))
9492 (t (setq a (pop args))
9493 (if (string-match "%a" a)
9494 (setq a (replace-match address t t a)))
9495 (if (string-match "%s" a)
9496 (setq a (replace-match subject t t a)))
9497 (push a args1))))
9498 (apply cmd (nreverse args1))))
9500 ((member type '("http" "https" "ftp" "news"))
9501 (browse-url (concat type ":" (org-link-escape
9502 path org-link-escape-chars-browser))))
9504 ((string= type "doi")
9505 (browse-url (concat "http://dx.doi.org/"
9506 (org-link-escape
9507 path org-link-escape-chars-browser))))
9509 ((member type '("message"))
9510 (browse-url (concat type ":" path)))
9512 ((string= type "tags")
9513 (org-tags-view arg path))
9515 ((string= type "tree-match")
9516 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9518 ((string= type "file")
9519 (if (string-match "::\\([0-9]+\\)\\'" path)
9520 (setq line (string-to-number (match-string 1 path))
9521 path (substring path 0 (match-beginning 0)))
9522 (if (string-match "::\\(.+\\)\\'" path)
9523 (setq search (match-string 1 path)
9524 path (substring path 0 (match-beginning 0)))))
9525 (if (string-match "[*?{]" (file-name-nondirectory path))
9526 (dired path)
9527 (org-open-file path arg line search)))
9529 ((string= type "shell")
9530 (let ((cmd path))
9531 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9532 (string-match org-confirm-shell-link-not-regexp cmd))
9533 (not org-confirm-shell-link-function)
9534 (funcall org-confirm-shell-link-function
9535 (format "Execute \"%s\" in shell? "
9536 (org-add-props cmd nil
9537 'face 'org-warning))))
9538 (progn
9539 (message "Executing %s" cmd)
9540 (shell-command cmd))
9541 (error "Abort"))))
9543 ((string= type "elisp")
9544 (let ((cmd path))
9545 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9546 (string-match org-confirm-elisp-link-not-regexp cmd))
9547 (not org-confirm-elisp-link-function)
9548 (funcall org-confirm-elisp-link-function
9549 (format "Execute \"%s\" as elisp? "
9550 (org-add-props cmd nil
9551 'face 'org-warning))))
9552 (message "%s => %s" cmd
9553 (if (equal (string-to-char cmd) ?\()
9554 (eval (read cmd))
9555 (call-interactively (read cmd))))
9556 (error "Abort"))))
9558 ((and (string= type "thisfile")
9559 (run-hook-with-args-until-success
9560 'org-open-link-functions path)))
9562 ((string= type "thisfile")
9563 (if arg
9564 (switch-to-buffer-other-window
9565 (org-get-buffer-for-internal-link (current-buffer)))
9566 (org-mark-ring-push))
9567 (let ((cmd `(org-link-search
9568 ,path
9569 ,(cond ((equal arg '(4)) ''occur)
9570 ((equal arg '(16)) ''org-occur)
9571 (t nil))
9572 ,pos)))
9573 (condition-case nil (let ((org-link-search-inhibit-query t))
9574 (eval cmd))
9575 (error (progn (widen) (eval cmd))))))
9578 (browse-url-at-point)))))))
9579 (move-marker org-open-link-marker nil)
9580 (run-hook-with-args 'org-follow-link-hook)))
9582 (defun org-offer-links-in-entry (&optional nth zero)
9583 "Offer links in the current entry and follow the selected link.
9584 If there is only one link, follow it immediately as well.
9585 If NTH is an integer, immediately pick the NTH link found.
9586 If ZERO is a string, check also this string for a link, and if
9587 there is one, offer it as link number zero."
9588 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9589 "\\(" org-angle-link-re "\\)\\|"
9590 "\\(" org-plain-link-re "\\)"))
9591 (cnt ?0)
9592 (in-emacs (if (integerp nth) nil nth))
9593 have-zero end links link c)
9594 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9595 (push (match-string 0 zero) links)
9596 (setq cnt (1- cnt) have-zero t))
9597 (save-excursion
9598 (org-back-to-heading t)
9599 (setq end (save-excursion (outline-next-heading) (point)))
9600 (while (re-search-forward re end t)
9601 (push (match-string 0) links))
9602 (setq links (org-uniquify (reverse links))))
9604 (cond
9605 ((null links)
9606 (message "No links"))
9607 ((equal (length links) 1)
9608 (setq link (list (car links))))
9609 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9610 (setq link (nth (if have-zero nth (1- nth)) links)))
9611 (t ; we have to select a link
9612 (save-excursion
9613 (save-window-excursion
9614 (delete-other-windows)
9615 (with-output-to-temp-buffer "*Select Link*"
9616 (mapc (lambda (l)
9617 (if (not (string-match org-bracket-link-regexp l))
9618 (princ (format "[%c] %s\n" (incf cnt)
9619 (org-remove-angle-brackets l)))
9620 (if (match-end 3)
9621 (princ (format "[%c] %s (%s)\n" (incf cnt)
9622 (match-string 3 l) (match-string 1 l)))
9623 (princ (format "[%c] %s\n" (incf cnt)
9624 (match-string 1 l))))))
9625 links))
9626 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9627 (message "Select link to open, RET to open all:")
9628 (setq c (read-char-exclusive))
9629 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9630 (when (equal c ?q) (error "Abort"))
9631 (if (equal c ?\C-m)
9632 (setq link links)
9633 (setq nth (- c ?0))
9634 (if have-zero (setq nth (1+ nth)))
9635 (unless (and (integerp nth) (>= (length links) nth))
9636 (error "Invalid link selection"))
9637 (setq link (list (nth (1- nth) links))))))
9638 (if link
9639 (let ((buf (current-buffer)))
9640 (dolist (l link)
9641 (org-open-link-from-string l in-emacs buf))
9643 nil)))
9645 ;; Add special file links that specify the way of opening
9647 (org-add-link-type "file+sys" 'org-open-file-with-system)
9648 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9649 (defun org-open-file-with-system (path)
9650 "Open file at PATH using the system way of opening it."
9651 (org-open-file path 'system))
9652 (defun org-open-file-with-emacs (path)
9653 "Open file at PATH in Emacs."
9654 (org-open-file path 'emacs))
9655 (defun org-remove-file-link-modifiers ()
9656 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9657 (goto-char (point-min))
9658 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9659 (org-if-unprotected
9660 (replace-match "file:" t t))))
9661 (eval-after-load "org-exp"
9662 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9663 'org-remove-file-link-modifiers))
9665 ;;;; Time estimates
9667 (defun org-get-effort (&optional pom)
9668 "Get the effort estimate for the current entry."
9669 (org-entry-get pom org-effort-property))
9671 ;;; File search
9673 (defvar org-create-file-search-functions nil
9674 "List of functions to construct the right search string for a file link.
9675 These functions are called in turn with point at the location to
9676 which the link should point.
9678 A function in the hook should first test if it would like to
9679 handle this file type, for example by checking the `major-mode'
9680 or the file extension. If it decides not to handle this file, it
9681 should just return nil to give other functions a chance. If it
9682 does handle the file, it must return the search string to be used
9683 when following the link. The search string will be part of the
9684 file link, given after a double colon, and `org-open-at-point'
9685 will automatically search for it. If special measures must be
9686 taken to make the search successful, another function should be
9687 added to the companion hook `org-execute-file-search-functions',
9688 which see.
9690 A function in this hook may also use `setq' to set the variable
9691 `description' to provide a suggestion for the descriptive text to
9692 be used for this link when it gets inserted into an Org-mode
9693 buffer with \\[org-insert-link].")
9695 (defvar org-execute-file-search-functions nil
9696 "List of functions to execute a file search triggered by a link.
9698 Functions added to this hook must accept a single argument, the
9699 search string that was part of the file link, the part after the
9700 double colon. The function must first check if it would like to
9701 handle this search, for example by checking the `major-mode' or
9702 the file extension. If it decides not to handle this search, it
9703 should just return nil to give other functions a chance. If it
9704 does handle the search, it must return a non-nil value to keep
9705 other functions from trying.
9707 Each function can access the current prefix argument through the
9708 variable `current-prefix-argument'. Note that a single prefix is
9709 used to force opening a link in Emacs, so it may be good to only
9710 use a numeric or double prefix to guide the search function.
9712 In case this is needed, a function in this hook can also restore
9713 the window configuration before `org-open-at-point' was called using:
9715 (set-window-configuration org-window-config-before-follow-link)")
9717 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9718 (defun org-link-search (s &optional type avoid-pos)
9719 "Search for a link search option.
9720 If S is surrounded by forward slashes, it is interpreted as a
9721 regular expression. In org-mode files, this will create an `org-occur'
9722 sparse tree. In ordinary files, `occur' will be used to list matches.
9723 If the current buffer is in `dired-mode', grep will be used to search
9724 in all files. If AVOID-POS is given, ignore matches near that position."
9725 (let ((case-fold-search t)
9726 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9727 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9728 (append '(("") (" ") ("\t") ("\n"))
9729 org-emphasis-alist)
9730 "\\|") "\\)"))
9731 (pos (point))
9732 (pre nil) (post nil)
9733 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9734 (cond
9735 ;; First check if there are any special search functions
9736 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9737 ;; Now try the builtin stuff
9738 ((and (equal (string-to-char s0) ?#)
9739 (> (length s0) 1)
9740 (save-excursion
9741 (goto-char (point-min))
9742 (and
9743 (re-search-forward
9744 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9745 (setq type 'dedicated
9746 pos (match-beginning 0))))
9747 ;; There is an exact target for this
9748 (goto-char pos)
9749 (org-back-to-heading t)))
9750 ((save-excursion
9751 (goto-char (point-min))
9752 (and
9753 (re-search-forward
9754 (concat "<<" (regexp-quote s0) ">>") nil t)
9755 (setq type 'dedicated
9756 pos (match-beginning 0))))
9757 ;; There is an exact target for this
9758 (goto-char pos))
9759 ((and (string-match "^(\\(.*\\))$" s0)
9760 (save-excursion
9761 (goto-char (point-min))
9762 (and
9763 (re-search-forward
9764 (concat "[^[]" (regexp-quote
9765 (format org-coderef-label-format
9766 (match-string 1 s0))))
9767 nil t)
9768 (setq type 'dedicated
9769 pos (1+ (match-beginning 0))))))
9770 ;; There is a coderef target for this
9771 (goto-char pos))
9772 ((string-match "^/\\(.*\\)/$" s)
9773 ;; A regular expression
9774 (cond
9775 ((org-mode-p)
9776 (org-occur (match-string 1 s)))
9777 ;;((eq major-mode 'dired-mode)
9778 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9779 (t (org-do-occur (match-string 1 s)))))
9780 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9781 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9782 (goto-char (point-min))
9783 (cond
9784 ((let (case-fold-search)
9785 (re-search-forward (format org-complex-heading-regexp-format
9786 (regexp-quote s))
9787 nil t))
9788 ;; OK, found a match
9789 (setq type 'dedicated)
9790 (goto-char (match-beginning 0)))
9791 ((and (not org-link-search-inhibit-query)
9792 (eq org-link-search-must-match-exact-headline 'query-to-create)
9793 (y-or-n-p "No match - create this as a new heading? "))
9794 (goto-char (point-max))
9795 (or (bolp) (newline))
9796 (insert "* " s "\n")
9797 (beginning-of-line 0))
9799 (goto-char pos)
9800 (error "No match"))))
9802 ;; A normal search string
9803 (when (equal (string-to-char s) ?*)
9804 ;; Anchor on headlines, post may include tags.
9805 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9806 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9807 s (substring s 1)))
9808 (remove-text-properties
9809 0 (length s)
9810 '(face nil mouse-face nil keymap nil fontified nil) s)
9811 ;; Make a series of regular expressions to find a match
9812 (setq words (org-split-string s "[ \n\r\t]+")
9814 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9815 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9816 "\\)" markers)
9817 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9818 re2a (concat "[ \t\r\n]" re2a_)
9819 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9820 re4 (concat "[^a-zA-Z_]" re4_)
9822 re1 (concat pre re2 post)
9823 re3 (concat pre (if pre re4_ re4) post)
9824 re5 (concat pre ".*" re4)
9825 re2 (concat pre re2)
9826 re2a (concat pre (if pre re2a_ re2a))
9827 re4 (concat pre (if pre re4_ re4))
9828 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9829 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9830 re5 "\\)"
9832 (cond
9833 ((eq type 'org-occur) (org-occur reall))
9834 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9835 (t (goto-char (point-min))
9836 (setq type 'fuzzy)
9837 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9838 (org-search-not-self 1 re1 nil t)
9839 (org-search-not-self 1 re2 nil t)
9840 (org-search-not-self 1 re2a nil t)
9841 (org-search-not-self 1 re3 nil t)
9842 (org-search-not-self 1 re4 nil t)
9843 (org-search-not-self 1 re5 nil t)
9845 (goto-char (match-beginning 1))
9846 (goto-char pos)
9847 (error "No match"))))))
9848 (and (org-mode-p) (org-show-context 'link-search))
9849 type))
9851 (defun org-search-not-self (group &rest args)
9852 "Execute `re-search-forward', but only accept matches that do not
9853 enclose the position of `org-open-link-marker'."
9854 (let ((m org-open-link-marker))
9855 (catch 'exit
9856 (while (apply 're-search-forward args)
9857 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9858 (goto-char (match-end group))
9859 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9860 (> (match-beginning 0) (marker-position m))
9861 (< (match-end 0) (marker-position m)))
9862 (save-match-data
9863 (or (not (org-in-regexp
9864 org-bracket-link-analytic-regexp 1))
9865 (not (match-end 4)) ; no description
9866 (and (<= (match-beginning 4) (point))
9867 (>= (match-end 4) (point))))))
9868 (throw 'exit (point))))))))
9870 (defun org-get-buffer-for-internal-link (buffer)
9871 "Return a buffer to be used for displaying the link target of internal links."
9872 (cond
9873 ((not org-display-internal-link-with-indirect-buffer)
9874 buffer)
9875 ((string-match "(Clone)$" (buffer-name buffer))
9876 (message "Buffer is already a clone, not making another one")
9877 ;; we also do not modify visibility in this case
9878 buffer)
9879 (t ; make a new indirect buffer for displaying the link
9880 (let* ((bn (buffer-name buffer))
9881 (ibn (concat bn "(Clone)"))
9882 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9883 (with-current-buffer ib (org-overview))
9884 ib))))
9886 (defun org-do-occur (regexp &optional cleanup)
9887 "Call the Emacs command `occur'.
9888 If CLEANUP is non-nil, remove the printout of the regular expression
9889 in the *Occur* buffer. This is useful if the regex is long and not useful
9890 to read."
9891 (occur regexp)
9892 (when cleanup
9893 (let ((cwin (selected-window)) win beg end)
9894 (when (setq win (get-buffer-window "*Occur*"))
9895 (select-window win))
9896 (goto-char (point-min))
9897 (when (re-search-forward "match[a-z]+" nil t)
9898 (setq beg (match-end 0))
9899 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9900 (setq end (1- (match-beginning 0)))))
9901 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9902 (goto-char (point-min))
9903 (select-window cwin))))
9905 ;;; The mark ring for links jumps
9907 (defvar org-mark-ring nil
9908 "Mark ring for positions before jumps in Org-mode.")
9909 (defvar org-mark-ring-last-goto nil
9910 "Last position in the mark ring used to go back.")
9911 ;; Fill and close the ring
9912 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9913 (loop for i from 1 to org-mark-ring-length do
9914 (push (make-marker) org-mark-ring))
9915 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9916 org-mark-ring)
9918 (defun org-mark-ring-push (&optional pos buffer)
9919 "Put the current position or POS into the mark ring and rotate it."
9920 (interactive)
9921 (setq pos (or pos (point)))
9922 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9923 (move-marker (car org-mark-ring)
9924 (or pos (point))
9925 (or buffer (current-buffer)))
9926 (message "%s"
9927 (substitute-command-keys
9928 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9930 (defun org-mark-ring-goto (&optional n)
9931 "Jump to the previous position in the mark ring.
9932 With prefix arg N, jump back that many stored positions. When
9933 called several times in succession, walk through the entire ring.
9934 Org-mode commands jumping to a different position in the current file,
9935 or to another Org-mode file, automatically push the old position
9936 onto the ring."
9937 (interactive "p")
9938 (let (p m)
9939 (if (eq last-command this-command)
9940 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9941 (setq p org-mark-ring))
9942 (setq org-mark-ring-last-goto p)
9943 (setq m (car p))
9944 (org-pop-to-buffer-same-window (marker-buffer m))
9945 (goto-char m)
9946 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9948 (defun org-remove-angle-brackets (s)
9949 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9950 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9952 (defun org-add-angle-brackets (s)
9953 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9954 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9956 (defun org-remove-double-quotes (s)
9957 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9958 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9961 ;;; Following specific links
9963 (defun org-follow-timestamp-link ()
9964 (cond
9965 ((org-at-date-range-p t)
9966 (let ((org-agenda-start-on-weekday)
9967 (t1 (match-string 1))
9968 (t2 (match-string 2)))
9969 (setq t1 (time-to-days (org-time-string-to-time t1))
9970 t2 (time-to-days (org-time-string-to-time t2)))
9971 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9972 ((org-at-timestamp-p t)
9973 (org-agenda-list nil (time-to-days (org-time-string-to-time
9974 (substring (match-string 1) 0 10)))
9976 (t (error "This should not happen"))))
9979 ;;; Following file links
9980 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9981 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9982 (declare-function mailcap-mime-info
9983 "mailcap" (string &optional request no-decode))
9984 (defvar org-wait nil)
9985 (defun org-open-file (path &optional in-emacs line search)
9986 "Open the file at PATH.
9987 First, this expands any special file name abbreviations. Then the
9988 configuration variable `org-file-apps' is checked if it contains an
9989 entry for this file type, and if yes, the corresponding command is launched.
9991 If no application is found, Emacs simply visits the file.
9993 With optional prefix argument IN-EMACS, Emacs will visit the file.
9994 With a double \\[universal-argument] \\[universal-argument] \
9995 prefix arg, Org tries to avoid opening in Emacs
9996 and to use an external application to visit the file.
9998 Optional LINE specifies a line to go to, optional SEARCH a string
9999 to search for. If LINE or SEARCH is given, the file will be
10000 opened in Emacs, unless an entry from org-file-apps that makes
10001 use of groups in a regexp matches.
10003 If you want to change the way frames are used when following a
10004 link, please customize `org-link-frame-setup'.
10006 If the file does not exist, an error is thrown."
10007 (let* ((file (if (equal path "")
10008 buffer-file-name
10009 (substitute-in-file-name (expand-file-name path))))
10010 (file-apps (append org-file-apps (org-default-apps)))
10011 (apps (org-remove-if
10012 'org-file-apps-entry-match-against-dlink-p file-apps))
10013 (apps-dlink (org-remove-if-not
10014 'org-file-apps-entry-match-against-dlink-p file-apps))
10015 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10016 (dirp (if remp nil (file-directory-p file)))
10017 (file (if (and dirp org-open-directory-means-index-dot-org)
10018 (concat (file-name-as-directory file) "index.org")
10019 file))
10020 (a-m-a-p (assq 'auto-mode apps))
10021 (dfile (downcase file))
10022 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10023 (link (cond ((and (eq line nil)
10024 (eq search nil))
10025 file)
10026 (line
10027 (concat file "::" (number-to-string line)))
10028 (search
10029 (concat file "::" search))))
10030 (dlink (downcase link))
10031 (old-buffer (current-buffer))
10032 (old-pos (point))
10033 (old-mode major-mode)
10034 ext cmd link-match-data)
10035 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10036 (setq ext (match-string 1 dfile))
10037 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10038 (setq ext (match-string 1 dfile))))
10039 (cond
10040 ((member in-emacs '((16) system))
10041 (setq cmd (cdr (assoc 'system apps))))
10042 (in-emacs (setq cmd 'emacs))
10044 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10045 (and dirp (cdr (assoc 'directory apps)))
10046 ; first, try matching against apps-dlink
10047 ; if we get a match here, store the match data for later
10048 (let ((match (assoc-default dlink apps-dlink
10049 'string-match)))
10050 (if match
10051 (progn (setq link-match-data (match-data))
10052 match)
10053 (progn (setq in-emacs (or in-emacs line search))
10054 nil))) ; if we have no match in apps-dlink,
10055 ; always open the file in emacs if line or search
10056 ; is given (for backwards compatibility)
10057 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10058 'string-match)
10059 (cdr (assoc ext apps))
10060 (cdr (assoc t apps))))))
10061 (when (eq cmd 'system)
10062 (setq cmd (cdr (assoc 'system apps))))
10063 (when (eq cmd 'default)
10064 (setq cmd (cdr (assoc t apps))))
10065 (when (eq cmd 'mailcap)
10066 (require 'mailcap)
10067 (mailcap-parse-mailcaps)
10068 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10069 (command (mailcap-mime-info mime-type)))
10070 (if (stringp command)
10071 (setq cmd command)
10072 (setq cmd 'emacs))))
10073 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10074 (not (file-exists-p file))
10075 (not org-open-non-existing-files))
10076 (error "No such file: %s" file))
10077 (cond
10078 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10079 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10080 (while (string-match "['\"]%s['\"]" cmd)
10081 (setq cmd (replace-match "%s" t t cmd)))
10082 (while (string-match "%s" cmd)
10083 (setq cmd (replace-match
10084 (save-match-data
10085 (shell-quote-argument
10086 (convert-standard-filename file)))
10087 t t cmd)))
10089 ;; Replace "%1", "%2" etc. in command with group matches from regex
10090 (save-match-data
10091 (let ((match-index 1)
10092 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10093 (set-match-data link-match-data)
10094 (while (<= match-index number-of-groups)
10095 (let ((regex (concat "%" (number-to-string match-index)))
10096 (replace-with (match-string match-index dlink)))
10097 (while (string-match regex cmd)
10098 (setq cmd (replace-match replace-with t t cmd))))
10099 (setq match-index (+ match-index 1)))))
10101 (save-window-excursion
10102 (start-process-shell-command cmd nil cmd)
10103 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10105 ((or (stringp cmd)
10106 (eq cmd 'emacs))
10107 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10108 (widen)
10109 (if line (org-goto-line line)
10110 (if search (org-link-search search))))
10111 ((consp cmd)
10112 (let ((file (convert-standard-filename file)))
10113 (save-match-data
10114 (set-match-data link-match-data)
10115 (eval cmd))))
10116 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10117 (and (org-mode-p) (eq old-mode 'org-mode)
10118 (or (not (equal old-buffer (current-buffer)))
10119 (not (equal old-pos (point))))
10120 (org-mark-ring-push old-pos old-buffer))))
10122 (defun org-file-apps-entry-match-against-dlink-p (entry)
10123 "This function returns non-nil if `entry' uses a regular
10124 expression which should be matched against the whole link by
10125 org-open-file.
10127 It assumes that is the case when the entry uses a regular
10128 expression which has at least one grouping construct and the
10129 action is either a lisp form or a command string containing
10130 '%1', i.e. using at least one subexpression match as a
10131 parameter."
10132 (let ((selector (car entry))
10133 (action (cdr entry)))
10134 (if (stringp selector)
10135 (and (> (regexp-opt-depth selector) 0)
10136 (or (and (stringp action)
10137 (string-match "%[0-9]" action))
10138 (consp action)))
10139 nil)))
10141 (defun org-default-apps ()
10142 "Return the default applications for this operating system."
10143 (cond
10144 ((eq system-type 'darwin)
10145 org-file-apps-defaults-macosx)
10146 ((eq system-type 'windows-nt)
10147 org-file-apps-defaults-windowsnt)
10148 (t org-file-apps-defaults-gnu)))
10150 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10151 "Convert extensions to regular expressions in the cars of LIST.
10152 Also, weed out any non-string entries, because the return value is used
10153 only for regexp matching.
10154 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10155 point to the symbol `emacs', indicating that the file should
10156 be opened in Emacs."
10157 (append
10158 (delq nil
10159 (mapcar (lambda (x)
10160 (if (not (stringp (car x)))
10162 (if (string-match "\\W" (car x))
10164 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10165 list))
10166 (if add-auto-mode
10167 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10169 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10170 (defun org-file-remote-p (file)
10171 "Test whether FILE specifies a location on a remote system.
10172 Return non-nil if the location is indeed remote.
10174 For example, the filename \"/user@host:/foo\" specifies a location
10175 on the system \"/user@host:\"."
10176 (cond ((fboundp 'file-remote-p)
10177 (file-remote-p file))
10178 ((fboundp 'tramp-handle-file-remote-p)
10179 (tramp-handle-file-remote-p file))
10180 ((and (boundp 'ange-ftp-name-format)
10181 (string-match (car ange-ftp-name-format) file))
10183 (t nil)))
10186 ;;;; Refiling
10188 (defun org-get-org-file ()
10189 "Read a filename, with default directory `org-directory'."
10190 (let ((default (or org-default-notes-file remember-data-file)))
10191 (read-file-name (format "File name [%s]: " default)
10192 (file-name-as-directory org-directory)
10193 default)))
10195 (defun org-notes-order-reversed-p ()
10196 "Check if the current file should receive notes in reversed order."
10197 (cond
10198 ((not org-reverse-note-order) nil)
10199 ((eq t org-reverse-note-order) t)
10200 ((not (listp org-reverse-note-order)) nil)
10201 (t (catch 'exit
10202 (let ((all org-reverse-note-order)
10203 entry)
10204 (while (setq entry (pop all))
10205 (if (string-match (car entry) buffer-file-name)
10206 (throw 'exit (cdr entry))))
10207 nil)))))
10209 (defvar org-refile-target-table nil
10210 "The list of refile targets, created by `org-refile'.")
10212 (defvar org-agenda-new-buffers nil
10213 "Buffers created to visit agenda files.")
10215 (defvar org-refile-cache nil
10216 "Cache for refile targets.")
10218 (defvar org-refile-markers nil
10219 "All the markers used for caching refile locations.")
10221 (defun org-refile-marker (pos)
10222 "Get a new refile marker, but only if caching is in use."
10223 (if (not org-refile-use-cache)
10225 (let ((m (make-marker)))
10226 (move-marker m pos)
10227 (push m org-refile-markers)
10228 m)))
10230 (defun org-refile-cache-clear ()
10231 "Clear the refile cache and disable all the markers."
10232 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10233 (setq org-refile-markers nil)
10234 (setq org-refile-cache nil)
10235 (message "Refile cache has been cleared"))
10237 (defun org-refile-cache-check-set (set)
10238 "Check if all the markers in the cache still have live buffers."
10239 (let (marker)
10240 (catch 'exit
10241 (while (and set (setq marker (nth 3 (pop set))))
10242 ;; if org-refile-use-outline-path is 'file, marker may be nil
10243 (when (and marker (null (marker-buffer marker)))
10244 (message "not found") (sit-for 3)
10245 (throw 'exit nil)))
10246 t)))
10248 (defun org-refile-cache-put (set &rest identifiers)
10249 "Push the refile targets SET into the cache, under IDENTIFIERS."
10250 (let* ((key (sha1 (prin1-to-string identifiers)))
10251 (entry (assoc key org-refile-cache)))
10252 (if entry
10253 (setcdr entry set)
10254 (push (cons key set) org-refile-cache))))
10256 (defun org-refile-cache-get (&rest identifiers)
10257 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10258 (cond
10259 ((not org-refile-cache) nil)
10260 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10262 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10263 org-refile-cache))))
10264 (and set (org-refile-cache-check-set set) set)))))
10266 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10267 "Produce a table with refile targets."
10268 (let ((case-fold-search nil)
10269 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10270 (entries (or org-refile-targets '((nil . (:level . 1)))))
10271 targets tgs txt re files f desc descre fast-path-p level pos0)
10272 (message "Getting targets...")
10273 (with-current-buffer (or default-buffer (current-buffer))
10274 (while (setq entry (pop entries))
10275 (setq files (car entry) desc (cdr entry))
10276 (setq fast-path-p nil)
10277 (cond
10278 ((null files) (setq files (list (current-buffer))))
10279 ((eq files 'org-agenda-files)
10280 (setq files (org-agenda-files 'unrestricted)))
10281 ((and (symbolp files) (fboundp files))
10282 (setq files (funcall files)))
10283 ((and (symbolp files) (boundp files))
10284 (setq files (symbol-value files))))
10285 (if (stringp files) (setq files (list files)))
10286 (cond
10287 ((eq (car desc) :tag)
10288 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10289 ((eq (car desc) :todo)
10290 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10291 ((eq (car desc) :regexp)
10292 (setq descre (cdr desc)))
10293 ((eq (car desc) :level)
10294 (setq descre (concat "^\\*\\{" (number-to-string
10295 (if org-odd-levels-only
10296 (1- (* 2 (cdr desc)))
10297 (cdr desc)))
10298 "\\}[ \t]")))
10299 ((eq (car desc) :maxlevel)
10300 (setq fast-path-p t)
10301 (setq descre (concat "^\\*\\{1," (number-to-string
10302 (if org-odd-levels-only
10303 (1- (* 2 (cdr desc)))
10304 (cdr desc)))
10305 "\\}[ \t]")))
10306 (t (error "Bad refiling target description %s" desc)))
10307 (while (setq f (pop files))
10308 (with-current-buffer
10309 (if (bufferp f) f (org-get-agenda-file-buffer f))
10311 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10312 (progn
10313 (if (bufferp f) (setq f (buffer-file-name
10314 (buffer-base-buffer f))))
10315 (setq f (and f (expand-file-name f)))
10316 (if (eq org-refile-use-outline-path 'file)
10317 (push (list (file-name-nondirectory f) f nil nil) tgs))
10318 (save-excursion
10319 (save-restriction
10320 (widen)
10321 (goto-char (point-min))
10322 (while (re-search-forward descre nil t)
10323 (goto-char (setq pos0 (point-at-bol)))
10324 (catch 'next
10325 (when org-refile-target-verify-function
10326 (save-match-data
10327 (or (funcall org-refile-target-verify-function)
10328 (throw 'next t))))
10329 (when (and (looking-at org-complex-heading-regexp)
10330 (not (member (match-string 4) excluded-entries)))
10331 (setq level (org-reduced-level
10332 (- (match-end 1) (match-beginning 1)))
10333 txt (org-link-display-format (match-string 4))
10334 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10335 re (format org-complex-heading-regexp-format
10336 (regexp-quote (match-string 4))))
10337 (when org-refile-use-outline-path
10338 (setq txt (mapconcat
10339 'org-protect-slash
10340 (append
10341 (if (eq org-refile-use-outline-path
10342 'file)
10343 (list (file-name-nondirectory
10344 (buffer-file-name
10345 (buffer-base-buffer))))
10346 (if (eq org-refile-use-outline-path
10347 'full-file-path)
10348 (list (buffer-file-name
10349 (buffer-base-buffer)))))
10350 (org-get-outline-path fast-path-p
10351 level txt)
10352 (list txt))
10353 "/")))
10354 (push (list txt f re (org-refile-marker (point)))
10355 tgs)))
10356 (when (= (point) pos0)
10357 ;; verification function has not moved point
10358 (goto-char (point-at-eol))))))))
10359 (when org-refile-use-cache
10360 (org-refile-cache-put tgs (buffer-file-name) descre))
10361 (setq targets (append tgs targets))
10362 ))))
10363 (message "Getting targets...done")
10364 (nreverse targets)))
10366 (defun org-protect-slash (s)
10367 (while (string-match "/" s)
10368 (setq s (replace-match "\\" t t s)))
10371 (defvar org-olpa (make-vector 20 nil))
10373 (defun org-get-outline-path (&optional fastp level heading)
10374 "Return the outline path to the current entry, as a list.
10376 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10377 routine which makes outline path derivations for an entire file,
10378 avoiding backtracing. Refile target collection makes use of that."
10379 (if fastp
10380 (progn
10381 (if (> level 19)
10382 (error "Outline path failure, more than 19 levels"))
10383 (loop for i from level upto 19 do
10384 (aset org-olpa i nil))
10385 (prog1
10386 (delq nil (append org-olpa nil))
10387 (aset org-olpa level heading)))
10388 (let (rtn case-fold-search)
10389 (save-excursion
10390 (save-restriction
10391 (widen)
10392 (while (org-up-heading-safe)
10393 (when (looking-at org-complex-heading-regexp)
10394 (push (org-match-string-no-properties 4) rtn)))
10395 rtn)))))
10397 (defun org-format-outline-path (path &optional width prefix)
10398 "Format the outline path PATH for display.
10399 Width is the maximum number of characters that is available.
10400 Prefix is a prefix to be included in the returned string,
10401 such as the file name."
10402 (setq width (or width 79))
10403 (if prefix (setq width (- width (length prefix))))
10404 (if (not path)
10405 (or prefix "")
10406 (let* ((nsteps (length path))
10407 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10408 (maxwidth (if (<= total-width width)
10409 10000 ;; everything fits
10410 ;; we need to shorten the level headings
10411 (/ (- width nsteps) nsteps)))
10412 (org-odd-levels-only nil)
10413 (n 0)
10414 (total (1+ (length prefix))))
10415 (setq maxwidth (max maxwidth 10))
10416 (concat prefix
10417 (mapconcat
10418 (lambda (h)
10419 (setq n (1+ n))
10420 (if (and (= n nsteps) (< maxwidth 10000))
10421 (setq maxwidth (- total-width total)))
10422 (if (< (length h) maxwidth)
10423 (progn (setq total (+ total (length h) 1)) h)
10424 (setq h (substring h 0 (- maxwidth 2))
10425 total (+ total maxwidth 1))
10426 (if (string-match "[ \t]+\\'" h)
10427 (setq h (substring h 0 (match-beginning 0))))
10428 (setq h (concat h "..")))
10429 (org-add-props h nil 'face
10430 (nth (% (1- n) org-n-level-faces)
10431 org-level-faces))
10433 path "/")))))
10435 (defun org-display-outline-path (&optional file current)
10436 "Display the current outline path in the echo area."
10437 (interactive "P")
10438 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10439 (case-fold-search nil)
10440 (path (and (org-mode-p) (org-get-outline-path))))
10441 (if current (setq path (append path
10442 (save-excursion
10443 (org-back-to-heading t)
10444 (if (looking-at org-complex-heading-regexp)
10445 (list (match-string 4)))))))
10446 (message "%s"
10447 (org-format-outline-path
10448 path
10449 (1- (frame-width))
10450 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10452 (defvar org-refile-history nil
10453 "History for refiling operations.")
10455 (defvar org-after-refile-insert-hook nil
10456 "Hook run after `org-refile' has inserted its stuff at the new location.
10457 Note that this is still *before* the stuff will be removed from
10458 the *old* location.")
10460 (defvar org-capture-last-stored-marker)
10461 (defun org-refile (&optional goto default-buffer rfloc)
10462 "Move the entry or entries at point to another heading.
10463 The list of target headings is compiled using the information in
10464 `org-refile-targets', which see.
10466 At the target location, the entry is filed as a subitem of the target
10467 heading. Depending on `org-reverse-note-order', the new subitem will
10468 either be the first or the last subitem.
10470 If there is an active region, all entries in that region will be moved.
10471 However, the region must fulfill the requirement that the first heading
10472 is the first one sets the top-level of the moved text - at most siblings
10473 below it are allowed.
10475 With prefix arg GOTO, the command will only visit the target location
10476 and not actually move anything.
10478 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10479 go to the location where the last refiling operation has put the subtree.
10480 With a prefix argument of `2', refile to the running clock.
10482 RFLOC can be a refile location obtained in a different way.
10484 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10486 If you are using target caching (see `org-refile-use-cache'),
10487 You have to clear the target cache in order to find new targets.
10488 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10489 prefix argument (`C-u C-u C-u C-c C-w')."
10491 (interactive "P")
10492 (if (member goto '(0 (64)))
10493 (org-refile-cache-clear)
10494 (let* ((cbuf (current-buffer))
10495 (regionp (org-region-active-p))
10496 (region-start (and regionp (region-beginning)))
10497 (region-end (and regionp (region-end)))
10498 (region-length (and regionp (- region-end region-start)))
10499 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10500 pos it nbuf file re level reversed)
10501 (setq last-command nil)
10502 (when regionp
10503 (goto-char region-start)
10504 (or (bolp) (goto-char (point-at-bol)))
10505 (setq region-start (point))
10506 (unless (or (org-kill-is-subtree-p
10507 (buffer-substring region-start region-end))
10508 (prog1 org-refile-active-region-within-subtree
10509 (org-toggle-heading)))
10510 (error "The region is not a (sequence of) subtree(s)")))
10511 (if (equal goto '(16))
10512 (org-refile-goto-last-stored)
10513 (when (or
10514 (and (equal goto 2)
10515 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10516 (prog1
10517 (setq it (list (or org-clock-heading "running clock")
10518 (buffer-file-name
10519 (marker-buffer org-clock-hd-marker))
10521 (marker-position org-clock-hd-marker)))
10522 (setq goto nil)))
10523 (setq it (or rfloc
10524 (let (heading-text)
10525 (save-excursion
10526 (unless goto
10527 (org-back-to-heading t)
10528 (setq heading-text
10529 (nth 4 (org-heading-components))))
10530 (org-refile-get-location
10531 (cond (goto "Goto")
10532 (regionp "Refile region to")
10533 (t (concat "Refile subtree \""
10534 heading-text "\" to")))
10535 default-buffer
10536 org-refile-allow-creating-parent-nodes
10537 goto))))))
10538 (setq file (nth 1 it)
10539 re (nth 2 it)
10540 pos (nth 3 it))
10541 (if (and (not goto)
10543 (equal (buffer-file-name) file)
10544 (if regionp
10545 (and (>= pos region-start)
10546 (<= pos region-end))
10547 (and (>= pos (point))
10548 (< pos (save-excursion
10549 (org-end-of-subtree t t))))))
10550 (error "Cannot refile to position inside the tree or region"))
10552 (setq nbuf (or (find-buffer-visiting file)
10553 (find-file-noselect file)))
10554 (if goto
10555 (progn
10556 (org-pop-to-buffer-same-window nbuf)
10557 (goto-char pos)
10558 (org-show-context 'org-goto))
10559 (if regionp
10560 (progn
10561 (org-kill-new (buffer-substring region-start region-end))
10562 (org-save-markers-in-region region-start region-end))
10563 (org-copy-subtree 1 nil t))
10564 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10565 (find-file-noselect file)))
10566 (setq reversed (org-notes-order-reversed-p))
10567 (save-excursion
10568 (save-restriction
10569 (widen)
10570 (if pos
10571 (progn
10572 (goto-char pos)
10573 (looking-at org-outline-regexp)
10574 (setq level (org-get-valid-level (funcall outline-level) 1))
10575 (goto-char
10576 (if reversed
10577 (or (outline-next-heading) (point-max))
10578 (or (save-excursion (org-get-next-sibling))
10579 (org-end-of-subtree t t)
10580 (point-max)))))
10581 (setq level 1)
10582 (if (not reversed)
10583 (goto-char (point-max))
10584 (goto-char (point-min))
10585 (or (outline-next-heading) (goto-char (point-max)))))
10586 (if (not (bolp)) (newline))
10587 (org-paste-subtree level)
10588 (when org-log-refile
10589 (org-add-log-setup 'refile nil nil 'findpos
10590 org-log-refile)
10591 (unless (eq org-log-refile 'note)
10592 (save-excursion (org-add-log-note))))
10593 (and org-auto-align-tags (org-set-tags nil t))
10594 (bookmark-set "org-refile-last-stored")
10595 ;; If we are refiling for capture, make sure that the
10596 ;; last-capture pointers point here
10597 (when (org-bound-and-true-p org-refile-for-capture)
10598 (bookmark-set "org-capture-last-stored-marker")
10599 (move-marker org-capture-last-stored-marker (point)))
10600 (if (fboundp 'deactivate-mark) (deactivate-mark))
10601 (run-hooks 'org-after-refile-insert-hook))))
10602 (if regionp
10603 (delete-region (point) (+ (point) region-length))
10604 (org-cut-subtree))
10605 (when (featurep 'org-inlinetask)
10606 (org-inlinetask-remove-END-maybe))
10607 (setq org-markers-to-move nil)
10608 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10610 (defun org-refile-goto-last-stored ()
10611 "Go to the location where the last refile was stored."
10612 (interactive)
10613 (bookmark-jump "org-refile-last-stored")
10614 (message "This is the location of the last refile"))
10616 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10617 no-exclude)
10618 "Prompt the user for a refile location, using PROMPT.
10619 PROMPT should not be suffixed with a colon and a space, because
10620 this function appends the default value from
10621 `org-refile-history' automatically, if that is not empty.
10622 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10623 this is used for the GOTO interface."
10624 (let ((org-refile-targets org-refile-targets)
10625 (org-refile-use-outline-path org-refile-use-outline-path)
10626 excluded-entries)
10627 (when (and (eq major-mode 'org-mode)
10628 (not org-refile-use-cache)
10629 (not no-exclude))
10630 (org-map-tree
10631 (lambda()
10632 (setq excluded-entries
10633 (append excluded-entries (list (org-get-heading t t)))))))
10634 (setq org-refile-target-table
10635 (org-refile-get-targets default-buffer excluded-entries)))
10636 (unless org-refile-target-table
10637 (error "No refile targets"))
10638 (let* ((prompt (concat prompt
10639 (and (car org-refile-history)
10640 (concat " (default " (car org-refile-history) ")"))
10641 ": "))
10642 (cbuf (current-buffer))
10643 (partial-completion-mode nil)
10644 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10645 (cfunc (if (and org-refile-use-outline-path
10646 org-outline-path-complete-in-steps)
10647 'org-olpath-completing-read
10648 'org-icompleting-read))
10649 (extra (if org-refile-use-outline-path "/" ""))
10650 (filename (and cfn (expand-file-name cfn)))
10651 (tbl (mapcar
10652 (lambda (x)
10653 (if (and (not (member org-refile-use-outline-path
10654 '(file full-file-path)))
10655 (not (equal filename (nth 1 x))))
10656 (cons (concat (car x) extra " ("
10657 (file-name-nondirectory (nth 1 x)) ")")
10658 (cdr x))
10659 (cons (concat (car x) extra) (cdr x))))
10660 org-refile-target-table))
10661 (completion-ignore-case t)
10662 pa answ parent-target child parent old-hist)
10663 (setq old-hist org-refile-history)
10664 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10665 nil 'org-refile-history (car org-refile-history)))
10666 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10667 (org-refile-check-position pa)
10668 (if pa
10669 (progn
10670 (when (or (not org-refile-history)
10671 (not (eq old-hist org-refile-history))
10672 (not (equal (car pa) (car org-refile-history))))
10673 (setq org-refile-history
10674 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10675 org-refile-history
10676 (cdr org-refile-history))))
10677 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10678 (pop org-refile-history)))
10680 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10681 (progn
10682 (setq parent (match-string 1 answ)
10683 child (match-string 2 answ))
10684 (setq parent-target (or (assoc parent tbl)
10685 (assoc (concat parent "/") tbl)))
10686 (when (and parent-target
10687 (or (eq new-nodes t)
10688 (and (eq new-nodes 'confirm)
10689 (y-or-n-p (format "Create new node \"%s\"? "
10690 child)))))
10691 (org-refile-new-child parent-target child)))
10692 (error "Invalid target location")))))
10694 (defun org-refile-check-position (refile-pointer)
10695 "Check if the refile pointer matches the readline to which it points."
10696 (let* ((file (nth 1 refile-pointer))
10697 (re (nth 2 refile-pointer))
10698 (pos (nth 3 refile-pointer))
10699 buffer)
10700 (when (org-string-nw-p re)
10701 (setq buffer (if (markerp pos)
10702 (marker-buffer pos)
10703 (or (find-buffer-visiting file)
10704 (find-file-noselect file))))
10705 (with-current-buffer buffer
10706 (save-excursion
10707 (save-restriction
10708 (widen)
10709 (goto-char pos)
10710 (beginning-of-line 1)
10711 (unless (org-looking-at-p re)
10712 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10714 (defun org-refile-new-child (parent-target child)
10715 "Use refile target PARENT-TARGET to add new CHILD below it."
10716 (unless parent-target
10717 (error "Cannot find parent for new node"))
10718 (let ((file (nth 1 parent-target))
10719 (pos (nth 3 parent-target))
10720 level)
10721 (with-current-buffer (or (find-buffer-visiting file)
10722 (find-file-noselect file))
10723 (save-excursion
10724 (save-restriction
10725 (widen)
10726 (if pos
10727 (goto-char pos)
10728 (goto-char (point-max))
10729 (if (not (bolp)) (newline)))
10730 (when (looking-at org-outline-regexp)
10731 (setq level (funcall outline-level))
10732 (org-end-of-subtree t t))
10733 (org-back-over-empty-lines)
10734 (insert "\n" (make-string
10735 (if pos (org-get-valid-level level 1) 1) ?*)
10736 " " child "\n")
10737 (beginning-of-line 0)
10738 (list (concat (car parent-target) "/" child) file "" (point)))))))
10740 (defun org-olpath-completing-read (prompt collection &rest args)
10741 "Read an outline path like a file name."
10742 (let ((thetable collection)
10743 (org-completion-use-ido nil) ; does not work with ido.
10744 (org-completion-use-iswitchb nil)) ; or iswitchb
10745 (apply
10746 'org-icompleting-read prompt
10747 (lambda (string predicate &optional flag)
10748 (let (rtn r f (l (length string)))
10749 (cond
10750 ((eq flag nil)
10751 ;; try completion
10752 (try-completion string thetable))
10753 ((eq flag t)
10754 ;; all-completions
10755 (setq rtn (all-completions string thetable predicate))
10756 (mapcar
10757 (lambda (x)
10758 (setq r (substring x l))
10759 (if (string-match " ([^)]*)$" x)
10760 (setq f (match-string 0 x))
10761 (setq f ""))
10762 (if (string-match "/" r)
10763 (concat string (substring r 0 (match-end 0)) f)
10765 rtn))
10766 ((eq flag 'lambda)
10767 ;; exact match?
10768 (assoc string thetable)))
10770 args)))
10772 ;;;; Dynamic blocks
10774 (defun org-find-dblock (name)
10775 "Find the first dynamic block with name NAME in the buffer.
10776 If not found, stay at current position and return nil."
10777 (let (pos)
10778 (save-excursion
10779 (goto-char (point-min))
10780 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10781 nil t)
10782 (match-beginning 0))))
10783 (if pos (goto-char pos))
10784 pos))
10786 (defconst org-dblock-start-re
10787 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10788 "Matches the start line of a dynamic block, with parameters.")
10790 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10791 "Matches the end of a dynamic block.")
10793 (defun org-create-dblock (plist)
10794 "Create a dynamic block section, with parameters taken from PLIST.
10795 PLIST must contain a :name entry which is used as name of the block."
10796 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10797 (end-of-line 1)
10798 (newline))
10799 (let ((col (current-column))
10800 (name (plist-get plist :name)))
10801 (insert "#+BEGIN: " name)
10802 (while plist
10803 (if (eq (car plist) :name)
10804 (setq plist (cddr plist))
10805 (insert " " (prin1-to-string (pop plist)))))
10806 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10807 (beginning-of-line -2)))
10809 (defun org-prepare-dblock ()
10810 "Prepare dynamic block for refresh.
10811 This empties the block, puts the cursor at the insert position and returns
10812 the property list including an extra property :name with the block name."
10813 (unless (looking-at org-dblock-start-re)
10814 (error "Not at a dynamic block"))
10815 (let* ((begdel (1+ (match-end 0)))
10816 (name (org-no-properties (match-string 1)))
10817 (params (append (list :name name)
10818 (read (concat "(" (match-string 3) ")")))))
10819 (save-excursion
10820 (beginning-of-line 1)
10821 (skip-chars-forward " \t")
10822 (setq params (plist-put params :indentation-column (current-column))))
10823 (unless (re-search-forward org-dblock-end-re nil t)
10824 (error "Dynamic block not terminated"))
10825 (setq params
10826 (append params
10827 (list :content (buffer-substring
10828 begdel (match-beginning 0)))))
10829 (delete-region begdel (match-beginning 0))
10830 (goto-char begdel)
10831 (open-line 1)
10832 params))
10834 (defun org-map-dblocks (&optional command)
10835 "Apply COMMAND to all dynamic blocks in the current buffer.
10836 If COMMAND is not given, use `org-update-dblock'."
10837 (let ((cmd (or command 'org-update-dblock)))
10838 (save-excursion
10839 (goto-char (point-min))
10840 (while (re-search-forward org-dblock-start-re nil t)
10841 (goto-char (match-beginning 0))
10842 (save-excursion
10843 (condition-case nil
10844 (funcall cmd)
10845 (error (message "Error during update of dynamic block"))))
10846 (unless (re-search-forward org-dblock-end-re nil t)
10847 (error "Dynamic block not terminated"))))))
10849 (defun org-dblock-update (&optional arg)
10850 "User command for updating dynamic blocks.
10851 Update the dynamic block at point. With prefix ARG, update all dynamic
10852 blocks in the buffer."
10853 (interactive "P")
10854 (if arg
10855 (org-update-all-dblocks)
10856 (or (looking-at org-dblock-start-re)
10857 (org-beginning-of-dblock))
10858 (org-update-dblock)))
10860 (defun org-update-dblock ()
10861 "Update the dynamic block at point.
10862 This means to empty the block, parse for parameters and then call
10863 the correct writing function."
10864 (interactive)
10865 (save-window-excursion
10866 (let* ((pos (point))
10867 (line (org-current-line))
10868 (params (org-prepare-dblock))
10869 (name (plist-get params :name))
10870 (indent (plist-get params :indentation-column))
10871 (cmd (intern (concat "org-dblock-write:" name))))
10872 (message "Updating dynamic block `%s' at line %d..." name line)
10873 (funcall cmd params)
10874 (message "Updating dynamic block `%s' at line %d...done" name line)
10875 (goto-char pos)
10876 (when (and indent (> indent 0))
10877 (setq indent (make-string indent ?\ ))
10878 (save-excursion
10879 (org-beginning-of-dblock)
10880 (forward-line 1)
10881 (while (not (looking-at org-dblock-end-re))
10882 (insert indent)
10883 (beginning-of-line 2))
10884 (when (looking-at org-dblock-end-re)
10885 (and (looking-at "[ \t]+")
10886 (replace-match ""))
10887 (insert indent)))))))
10889 (defun org-beginning-of-dblock ()
10890 "Find the beginning of the dynamic block at point.
10891 Error if there is no such block at point."
10892 (let ((pos (point))
10893 beg)
10894 (end-of-line 1)
10895 (if (and (re-search-backward org-dblock-start-re nil t)
10896 (setq beg (match-beginning 0))
10897 (re-search-forward org-dblock-end-re nil t)
10898 (> (match-end 0) pos))
10899 (goto-char beg)
10900 (goto-char pos)
10901 (error "Not in a dynamic block"))))
10903 (defun org-update-all-dblocks ()
10904 "Update all dynamic blocks in the buffer.
10905 This function can be used in a hook."
10906 (interactive)
10907 (when (org-mode-p)
10908 (org-map-dblocks 'org-update-dblock)))
10911 ;;;; Completion
10913 (defconst org-additional-option-like-keywords
10914 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10915 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10916 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10917 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10918 "BEGIN:" "END:"
10919 "ORGTBL" "TBLFM:" "TBLNAME:"
10920 "BEGIN_EXAMPLE" "END_EXAMPLE"
10921 "BEGIN_QUOTE" "END_QUOTE"
10922 "BEGIN_VERSE" "END_VERSE"
10923 "BEGIN_CENTER" "END_CENTER"
10924 "BEGIN_SRC" "END_SRC"
10925 "BEGIN_RESULT" "END_RESULT"
10926 "SOURCE:" "SRCNAME:" "FUNCTION:"
10927 "RESULTS:" "DATA:"
10928 "HEADER:" "HEADERS:"
10929 "BABEL:"
10930 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10931 "CAPTION:" "LABEL:"
10932 "SETUPFILE:"
10933 "INCLUDE:"
10934 "BIND:"
10935 "MACRO:"))
10937 (defcustom org-structure-template-alist
10939 ("s" "#+begin_src ?\n\n#+end_src"
10940 "<src lang=\"?\">\n\n</src>")
10941 ("e" "#+begin_example\n?\n#+end_example"
10942 "<example>\n?\n</example>")
10943 ("q" "#+begin_quote\n?\n#+end_quote"
10944 "<quote>\n?\n</quote>")
10945 ("v" "#+begin_verse\n?\n#+end_verse"
10946 "<verse>\n?\n/verse>")
10947 ("c" "#+begin_center\n?\n#+end_center"
10948 "<center>\n?\n/center>")
10949 ("l" "#+begin_latex\n?\n#+end_latex"
10950 "<literal style=\"latex\">\n?\n</literal>")
10951 ("L" "#+latex: "
10952 "<literal style=\"latex\">?</literal>")
10953 ("h" "#+begin_html\n?\n#+end_html"
10954 "<literal style=\"html\">\n?\n</literal>")
10955 ("H" "#+html: "
10956 "<literal style=\"html\">?</literal>")
10957 ("a" "#+begin_ascii\n?\n#+end_ascii")
10958 ("A" "#+ascii: ")
10959 ("i" "#+index: ?"
10960 "#+index: ?")
10961 ("I" "#+include %file ?"
10962 "<include file=%file markup=\"?\">")
10964 "Structure completion elements.
10965 This is a list of abbreviation keys and values. The value gets inserted
10966 if you type `<' followed by the key and then press the completion key,
10967 usually `M-TAB'. %file will be replaced by a file name after prompting
10968 for the file using completion. The cursor will be placed at the position
10969 of the `?` in the template.
10970 There are two templates for each key, the first uses the original Org syntax,
10971 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10972 the default when the /org-mtags.el/ module has been loaded. See also the
10973 variable `org-mtags-prefer-muse-templates'.
10974 This is an experimental feature, it is undecided if it is going to stay in."
10975 :group 'org-completion
10976 :type '(repeat
10977 (string :tag "Key")
10978 (string :tag "Template")
10979 (string :tag "Muse Template")))
10981 (defun org-try-structure-completion ()
10982 "Try to complete a structure template before point.
10983 This looks for strings like \"<e\" on an otherwise empty line and
10984 expands them."
10985 (let ((l (buffer-substring (point-at-bol) (point)))
10987 (when (and (looking-at "[ \t]*$")
10988 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10989 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10990 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10991 (match-beginning 1)) a)
10992 t)))
10994 (defun org-complete-expand-structure-template (start cell)
10995 "Expand a structure template."
10996 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10997 (rpl (nth (if musep 2 1) cell))
10998 (ind ""))
10999 (delete-region start (point))
11000 (when (string-match "\\`#\\+" rpl)
11001 (cond
11002 ((bolp))
11003 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11004 (setq ind (buffer-substring (point-at-bol) (point))))
11005 (t (newline))))
11006 (setq start (point))
11007 (if (string-match "%file" rpl)
11008 (setq rpl (replace-match
11009 (concat
11010 "\""
11011 (save-match-data
11012 (abbreviate-file-name (read-file-name "Include file: ")))
11013 "\"")
11014 t t rpl)))
11015 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11016 (concat "\n" ind)))
11017 (insert rpl)
11018 (if (re-search-backward "\\?" start t) (delete-char 1))))
11020 ;;;; TODO, DEADLINE, Comments
11022 (defun org-toggle-comment ()
11023 "Change the COMMENT state of an entry."
11024 (interactive)
11025 (save-excursion
11026 (org-back-to-heading)
11027 (let (case-fold-search)
11028 (if (looking-at (concat org-outline-regexp
11029 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
11030 (replace-match "" t t nil 1)
11031 (if (looking-at org-outline-regexp)
11032 (progn
11033 (goto-char (match-end 0))
11034 (insert org-comment-string " ")))))))
11036 (defvar org-last-todo-state-is-todo nil
11037 "This is non-nil when the last TODO state change led to a TODO state.
11038 If the last change removed the TODO tag or switched to DONE, then
11039 this is nil.")
11041 (defvar org-setting-tags nil) ; dynamically skipped
11043 (defvar org-todo-setup-filter-hook nil
11044 "Hook for functions that pre-filter todo specs.
11045 Each function takes a todo spec and returns either nil or the spec
11046 transformed into canonical form." )
11048 (defvar org-todo-get-default-hook nil
11049 "Hook for functions that get a default item for todo.
11050 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11051 nil or a string to be used for the todo mark." )
11053 (defvar org-agenda-headline-snapshot-before-repeat)
11055 (defun org-current-effective-time ()
11056 "Return current time adjusted for `org-extend-today-until' variable"
11057 (let* ((ct (org-current-time))
11058 (dct (decode-time ct))
11059 (ct1
11060 (if (and org-use-effective-time
11061 (< (nth 2 dct) org-extend-today-until))
11062 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11063 ct)))
11064 ct1))
11066 (defun org-todo-yesterday (&optional arg)
11067 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11068 (interactive "P")
11069 (let* ((hour (third (decode-time
11070 (org-current-time))))
11071 (org-extend-today-until (1+ hour)))
11072 (org-todo arg)))
11074 (defun org-todo (&optional arg)
11075 "Change the TODO state of an item.
11076 The state of an item is given by a keyword at the start of the heading,
11077 like
11078 *** TODO Write paper
11079 *** DONE Call mom
11081 The different keywords are specified in the variable `org-todo-keywords'.
11082 By default the available states are \"TODO\" and \"DONE\".
11083 So for this example: when the item starts with TODO, it is changed to DONE.
11084 When it starts with DONE, the DONE is removed. And when neither TODO nor
11085 DONE are present, add TODO at the beginning of the heading.
11087 With \\[universal-argument] prefix arg, use completion to determine the new \
11088 state.
11089 With numeric prefix arg, switch to that state.
11090 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11091 keywords (nextset).
11092 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11094 For calling through lisp, arg is also interpreted in the following way:
11095 'none -> empty state
11096 \"\"(empty string) -> switch to empty state
11097 'done -> switch to DONE
11098 'nextset -> switch to the next set of keywords
11099 'previousset -> switch to the previous set of keywords
11100 \"WAITING\" -> switch to the specified keyword, but only if it
11101 really is a member of `org-todo-keywords'."
11102 (interactive "P")
11103 (if (equal arg '(16)) (setq arg 'nextset))
11104 (let ((org-blocker-hook org-blocker-hook)
11105 (case-fold-search nil))
11106 (when (equal arg '(64))
11107 (setq arg nil org-blocker-hook nil))
11108 (when (and org-blocker-hook
11109 (or org-inhibit-blocking
11110 (org-entry-get nil "NOBLOCKING")))
11111 (setq org-blocker-hook nil))
11112 (save-excursion
11113 (catch 'exit
11114 (org-back-to-heading t)
11115 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11116 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
11117 (looking-at " *"))
11118 (let* ((match-data (match-data))
11119 (startpos (point-at-bol))
11120 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11121 (org-log-done org-log-done)
11122 (org-log-repeat org-log-repeat)
11123 (org-todo-log-states org-todo-log-states)
11124 (this (match-string 1))
11125 (hl-pos (match-beginning 0))
11126 (head (org-get-todo-sequence-head this))
11127 (ass (assoc head org-todo-kwd-alist))
11128 (interpret (nth 1 ass))
11129 (done-word (nth 3 ass))
11130 (final-done-word (nth 4 ass))
11131 (last-state (or this ""))
11132 (completion-ignore-case t)
11133 (member (member this org-todo-keywords-1))
11134 (tail (cdr member))
11135 (state (cond
11136 ((and org-todo-key-trigger
11137 (or (and (equal arg '(4))
11138 (eq org-use-fast-todo-selection 'prefix))
11139 (and (not arg) org-use-fast-todo-selection
11140 (not (eq org-use-fast-todo-selection
11141 'prefix)))))
11142 ;; Use fast selection
11143 (org-fast-todo-selection))
11144 ((and (equal arg '(4))
11145 (or (not org-use-fast-todo-selection)
11146 (not org-todo-key-trigger)))
11147 ;; Read a state with completion
11148 (org-icompleting-read
11149 "State: " (mapcar (lambda(x) (list x))
11150 org-todo-keywords-1)
11151 nil t))
11152 ((eq arg 'right)
11153 (if this
11154 (if tail (car tail) nil)
11155 (car org-todo-keywords-1)))
11156 ((eq arg 'left)
11157 (if (equal member org-todo-keywords-1)
11159 (if this
11160 (nth (- (length org-todo-keywords-1)
11161 (length tail) 2)
11162 org-todo-keywords-1)
11163 (org-last org-todo-keywords-1))))
11164 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11165 (setq arg nil))) ; hack to fall back to cycling
11166 (arg
11167 ;; user or caller requests a specific state
11168 (cond
11169 ((equal arg "") nil)
11170 ((eq arg 'none) nil)
11171 ((eq arg 'done) (or done-word (car org-done-keywords)))
11172 ((eq arg 'nextset)
11173 (or (car (cdr (member head org-todo-heads)))
11174 (car org-todo-heads)))
11175 ((eq arg 'previousset)
11176 (let ((org-todo-heads (reverse org-todo-heads)))
11177 (or (car (cdr (member head org-todo-heads)))
11178 (car org-todo-heads))))
11179 ((car (member arg org-todo-keywords-1)))
11180 ((stringp arg)
11181 (error "State `%s' not valid in this file" arg))
11182 ((nth (1- (prefix-numeric-value arg))
11183 org-todo-keywords-1))))
11184 ((null member) (or head (car org-todo-keywords-1)))
11185 ((equal this final-done-word) nil) ;; -> make empty
11186 ((null tail) nil) ;; -> first entry
11187 ((memq interpret '(type priority))
11188 (if (eq this-command last-command)
11189 (car tail)
11190 (if (> (length tail) 0)
11191 (or done-word (car org-done-keywords))
11192 nil)))
11194 (car tail))))
11195 (state (or
11196 (run-hook-with-args-until-success
11197 'org-todo-get-default-hook state last-state)
11198 state))
11199 (next (if state (concat " " state " ") " "))
11200 (change-plist (list :type 'todo-state-change :from this :to state
11201 :position startpos))
11202 dolog now-done-p)
11203 (when org-blocker-hook
11204 (setq org-last-todo-state-is-todo
11205 (not (member this org-done-keywords)))
11206 (unless (save-excursion
11207 (save-match-data
11208 (org-with-wide-buffer
11209 (run-hook-with-args-until-failure
11210 'org-blocker-hook change-plist))))
11211 (if (org-called-interactively-p 'interactive)
11212 (error "TODO state change from %s to %s blocked" this state)
11213 ;; fail silently
11214 (message "TODO state change from %s to %s blocked" this state)
11215 (throw 'exit nil))))
11216 (store-match-data match-data)
11217 (replace-match next t t)
11218 (unless (pos-visible-in-window-p hl-pos)
11219 (message "TODO state changed to %s" (org-trim next)))
11220 (unless head
11221 (setq head (org-get-todo-sequence-head state)
11222 ass (assoc head org-todo-kwd-alist)
11223 interpret (nth 1 ass)
11224 done-word (nth 3 ass)
11225 final-done-word (nth 4 ass)))
11226 (when (memq arg '(nextset previousset))
11227 (message "Keyword-Set %d/%d: %s"
11228 (- (length org-todo-sets) -1
11229 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11230 (length org-todo-sets)
11231 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11232 (setq org-last-todo-state-is-todo
11233 (not (member state org-done-keywords)))
11234 (setq now-done-p (and (member state org-done-keywords)
11235 (not (member this org-done-keywords))))
11236 (and logging (org-local-logging logging))
11237 (when (and (or org-todo-log-states org-log-done)
11238 (not (eq org-inhibit-logging t))
11239 (not (memq arg '(nextset previousset))))
11240 ;; we need to look at recording a time and note
11241 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11242 (nth 2 (assoc this org-todo-log-states))))
11243 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11244 (setq dolog 'time))
11245 (when (and state
11246 (member state org-not-done-keywords)
11247 (not (member this org-not-done-keywords)))
11248 ;; This is now a todo state and was not one before
11249 ;; If there was a CLOSED time stamp, get rid of it.
11250 (org-add-planning-info nil nil 'closed))
11251 (when (and now-done-p org-log-done)
11252 ;; It is now done, and it was not done before
11253 (org-add-planning-info 'closed (org-current-effective-time))
11254 (if (and (not dolog) (eq 'note org-log-done))
11255 (org-add-log-setup 'done state this 'findpos 'note)))
11256 (when (and state dolog)
11257 ;; This is a non-nil state, and we need to log it
11258 (org-add-log-setup 'state state this 'findpos dolog)))
11259 ;; Fixup tag positioning
11260 (org-todo-trigger-tag-changes state)
11261 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11262 (when org-provide-todo-statistics
11263 (org-update-parent-todo-statistics))
11264 (run-hooks 'org-after-todo-state-change-hook)
11265 (if (and arg (not (member state org-done-keywords)))
11266 (setq head (org-get-todo-sequence-head state)))
11267 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11268 ;; Do we need to trigger a repeat?
11269 (when now-done-p
11270 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11271 ;; This is for the agenda, take a snapshot of the headline.
11272 (save-match-data
11273 (setq org-agenda-headline-snapshot-before-repeat
11274 (org-get-heading))))
11275 (org-auto-repeat-maybe state))
11276 ;; Fixup cursor location if close to the keyword
11277 (if (and (outline-on-heading-p)
11278 (not (bolp))
11279 (save-excursion (beginning-of-line 1)
11280 (looking-at org-todo-line-regexp))
11281 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11282 (progn
11283 (goto-char (or (match-end 2) (match-end 1)))
11284 (and (looking-at " ") (just-one-space))))
11285 (when org-trigger-hook
11286 (save-excursion
11287 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11289 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11290 "Block turning an entry into a TODO, using the hierarchy.
11291 This checks whether the current task should be blocked from state
11292 changes. Such blocking occurs when:
11294 1. The task has children which are not all in a completed state.
11296 2. A task has a parent with the property :ORDERED:, and there
11297 are siblings prior to the current task with incomplete
11298 status.
11300 3. The parent of the task is blocked because it has siblings that should
11301 be done first, or is child of a block grandparent TODO entry."
11303 (if (not org-enforce-todo-dependencies)
11304 t ; if locally turned off don't block
11305 (catch 'dont-block
11306 ;; If this is not a todo state change, or if this entry is already DONE,
11307 ;; do not block
11308 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11309 (member (plist-get change-plist :from)
11310 (cons 'done org-done-keywords))
11311 (member (plist-get change-plist :to)
11312 (cons 'todo org-not-done-keywords))
11313 (not (plist-get change-plist :to)))
11314 (throw 'dont-block t))
11315 ;; If this task has children, and any are undone, it's blocked
11316 (save-excursion
11317 (org-back-to-heading t)
11318 (let ((this-level (funcall outline-level)))
11319 (outline-next-heading)
11320 (let ((child-level (funcall outline-level)))
11321 (while (and (not (eobp))
11322 (> child-level this-level))
11323 ;; this todo has children, check whether they are all
11324 ;; completed
11325 (if (and (not (org-entry-is-done-p))
11326 (org-entry-is-todo-p))
11327 (throw 'dont-block nil))
11328 (outline-next-heading)
11329 (setq child-level (funcall outline-level))))))
11330 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11331 ;; any previous siblings are undone, it's blocked
11332 (save-excursion
11333 (org-back-to-heading t)
11334 (let* ((pos (point))
11335 (parent-pos (and (org-up-heading-safe) (point))))
11336 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11337 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11338 (forward-line 1)
11339 (re-search-forward org-not-done-heading-regexp pos t))
11340 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11341 ;; Search further up the hierarchy, to see if an anchestor is blocked
11342 (while t
11343 (goto-char parent-pos)
11344 (if (not (looking-at org-not-done-heading-regexp))
11345 (throw 'dont-block t)) ; do not block, parent is not a TODO
11346 (setq pos (point))
11347 (setq parent-pos (and (org-up-heading-safe) (point)))
11348 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11349 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11350 (forward-line 1)
11351 (re-search-forward org-not-done-heading-regexp pos t))
11352 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11354 (defcustom org-track-ordered-property-with-tag nil
11355 "Should the ORDERED property also be shown as a tag?
11356 The ORDERED property decides if an entry should require subtasks to be
11357 completed in sequence. Since a property is not very visible, setting
11358 this option means that toggling the ORDERED property with the command
11359 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11360 not relevant for the behavior, but it makes things more visible.
11362 Note that toggling the tag with tags commands will not change the property
11363 and therefore not influence behavior!
11365 This can be t, meaning the tag ORDERED should be used, It can also be a
11366 string to select a different tag for this task."
11367 :group 'org-todo
11368 :type '(choice
11369 (const :tag "No tracking" nil)
11370 (const :tag "Track with ORDERED tag" t)
11371 (string :tag "Use other tag")))
11373 (defun org-toggle-ordered-property ()
11374 "Toggle the ORDERED property of the current entry.
11375 For better visibility, you can track the value of this property with a tag.
11376 See variable `org-track-ordered-property-with-tag'."
11377 (interactive)
11378 (let* ((t1 org-track-ordered-property-with-tag)
11379 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11380 (save-excursion
11381 (org-back-to-heading)
11382 (if (org-entry-get nil "ORDERED")
11383 (progn
11384 (org-delete-property "ORDERED")
11385 (and tag (org-toggle-tag tag 'off))
11386 (message "Subtasks can be completed in arbitrary order"))
11387 (org-entry-put nil "ORDERED" "t")
11388 (and tag (org-toggle-tag tag 'on))
11389 (message "Subtasks must be completed in sequence")))))
11391 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11392 (defun org-block-todo-from-checkboxes (change-plist)
11393 "Block turning an entry into a TODO, using checkboxes.
11394 This checks whether the current task should be blocked from state
11395 changes because there are unchecked boxes in this entry."
11396 (if (not org-enforce-todo-checkbox-dependencies)
11397 t ; if locally turned off don't block
11398 (catch 'dont-block
11399 ;; If this is not a todo state change, or if this entry is already DONE,
11400 ;; do not block
11401 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11402 (member (plist-get change-plist :from)
11403 (cons 'done org-done-keywords))
11404 (member (plist-get change-plist :to)
11405 (cons 'todo org-not-done-keywords))
11406 (not (plist-get change-plist :to)))
11407 (throw 'dont-block t))
11408 ;; If this task has checkboxes that are not checked, it's blocked
11409 (save-excursion
11410 (org-back-to-heading t)
11411 (let ((beg (point)) end)
11412 (outline-next-heading)
11413 (setq end (point))
11414 (goto-char beg)
11415 (if (org-list-search-forward
11416 (concat (org-item-beginning-re)
11417 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11418 "\\[[- ]\\]")
11419 end t)
11420 (progn
11421 (if (boundp 'org-blocked-by-checkboxes)
11422 (setq org-blocked-by-checkboxes t))
11423 (throw 'dont-block nil)))))
11424 t))) ; do not block
11426 (defun org-entry-blocked-p ()
11427 "Is the current entry blocked?"
11428 (if (org-entry-get nil "NOBLOCKING")
11429 nil ;; Never block this entry
11430 (not
11431 (run-hook-with-args-until-failure
11432 'org-blocker-hook
11433 (list :type 'todo-state-change
11434 :position (point)
11435 :from 'todo
11436 :to 'done)))))
11438 (defun org-update-statistics-cookies (all)
11439 "Update the statistics cookie, either from TODO or from checkboxes.
11440 This should be called with the cursor in a line with a statistics cookie."
11441 (interactive "P")
11442 (if all
11443 (progn
11444 (org-update-checkbox-count 'all)
11445 (org-map-entries 'org-update-parent-todo-statistics))
11446 (if (not (org-on-heading-p))
11447 (org-update-checkbox-count)
11448 (let ((pos (move-marker (make-marker) (point)))
11449 end l1 l2)
11450 (ignore-errors (org-back-to-heading t))
11451 (if (not (org-on-heading-p))
11452 (org-update-checkbox-count)
11453 (setq l1 (org-outline-level))
11454 (setq end (save-excursion
11455 (outline-next-heading)
11456 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11457 (point)))
11458 (if (and (save-excursion
11459 (re-search-forward
11460 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11461 (not (save-excursion (re-search-forward
11462 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11463 (org-update-checkbox-count)
11464 (if (and l2 (> l2 l1))
11465 (progn
11466 (goto-char end)
11467 (org-update-parent-todo-statistics))
11468 (goto-char pos)
11469 (beginning-of-line 1)
11470 (while (re-search-forward
11471 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11472 (point-at-eol) t)
11473 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11474 (goto-char pos)
11475 (move-marker pos nil)))))
11477 (defvar org-entry-property-inherited-from) ;; defined below
11478 (defun org-update-parent-todo-statistics ()
11479 "Update any statistics cookie in the parent of the current headline.
11480 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11481 the entire subtree and this will travel up the hierarchy and update
11482 statistics everywhere."
11483 (let* ((prop (save-excursion (org-up-heading-safe)
11484 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11485 (recursive (or (not org-hierarchical-todo-statistics)
11486 (and prop (string-match "\\<recursive\\>" prop))))
11487 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11489 (first t)
11490 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11491 level ltoggle l1 new ndel
11492 (cnt-all 0) (cnt-done 0) is-percent kwd
11493 checkbox-beg ov ovs ove cookie-present)
11494 (catch 'exit
11495 (save-excursion
11496 (beginning-of-line 1)
11497 (setq ltoggle (funcall outline-level))
11498 ;; Three situations are to consider:
11500 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11501 ;; to the top-level ancestor on the headline;
11503 ;; 2. If parent has "recursive" property, repeat up to the
11504 ;; headline setting that property, taking inheritance into
11505 ;; account;
11507 ;; 3. Else, move up to direct parent and proceed only once.
11508 (while (and (setq level (org-up-heading-safe))
11509 (or recursive first)
11510 (>= (point) lim))
11511 (setq first nil cookie-present nil)
11512 (unless (and level
11513 (not (string-match
11514 "\\<checkbox\\>"
11515 (downcase (or (org-entry-get nil "COOKIE_DATA")
11516 "")))))
11517 (throw 'exit nil))
11518 (while (re-search-forward box-re (point-at-eol) t)
11519 (setq cnt-all 0 cnt-done 0 cookie-present t)
11520 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11521 (save-match-data
11522 (unless (outline-next-heading) (throw 'exit nil))
11523 (while (and (looking-at org-complex-heading-regexp)
11524 (> (setq l1 (length (match-string 1))) level))
11525 (setq kwd (and (or recursive (= l1 ltoggle))
11526 (match-string 2)))
11527 (if (or (eq org-provide-todo-statistics 'all-headlines)
11528 (and (listp org-provide-todo-statistics)
11529 (or (member kwd org-provide-todo-statistics)
11530 (member kwd org-done-keywords))))
11531 (setq cnt-all (1+ cnt-all))
11532 (if (eq org-provide-todo-statistics t)
11533 (and kwd (setq cnt-all (1+ cnt-all)))))
11534 (and (member kwd org-done-keywords)
11535 (setq cnt-done (1+ cnt-done)))
11536 (outline-next-heading)))
11537 (setq new
11538 (if is-percent
11539 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11540 (format "[%d/%d]" cnt-done cnt-all))
11541 ndel (- (match-end 0) checkbox-beg))
11542 ;; handle overlays when updating cookie from column view
11543 (when (setq ov (car (overlays-at checkbox-beg)))
11544 (setq ovs (overlay-start ov) ove (overlay-end ov))
11545 (delete-overlay ov))
11546 (goto-char checkbox-beg)
11547 (insert new)
11548 (delete-region (point) (+ (point) ndel))
11549 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11550 (when ov (move-overlay ov ovs ove)))
11551 (when cookie-present
11552 (run-hook-with-args 'org-after-todo-statistics-hook
11553 cnt-done (- cnt-all cnt-done))))))
11554 (run-hooks 'org-todo-statistics-hook)))
11556 (defvar org-after-todo-statistics-hook nil
11557 "Hook that is called after a TODO statistics cookie has been updated.
11558 Each function is called with two arguments: the number of not-done entries
11559 and the number of done entries.
11561 For example, the following function, when added to this hook, will switch
11562 an entry to DONE when all children are done, and back to TODO when new
11563 entries are set to a TODO status. Note that this hook is only called
11564 when there is a statistics cookie in the headline!
11566 (defun org-summary-todo (n-done n-not-done)
11567 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11568 (let (org-log-done org-log-states) ; turn off logging
11569 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11572 (defvar org-todo-statistics-hook nil
11573 "Hook that is run whenever Org thinks TODO statistics should be updated.
11574 This hook runs even if there is no statistics cookie present, in which case
11575 `org-after-todo-statistics-hook' would not run.")
11577 (defun org-todo-trigger-tag-changes (state)
11578 "Apply the changes defined in `org-todo-state-tags-triggers'."
11579 (let ((l org-todo-state-tags-triggers)
11580 changes)
11581 (when (or (not state) (equal state ""))
11582 (setq changes (append changes (cdr (assoc "" l)))))
11583 (when (and (stringp state) (> (length state) 0))
11584 (setq changes (append changes (cdr (assoc state l)))))
11585 (when (member state org-not-done-keywords)
11586 (setq changes (append changes (cdr (assoc 'todo l)))))
11587 (when (member state org-done-keywords)
11588 (setq changes (append changes (cdr (assoc 'done l)))))
11589 (dolist (c changes)
11590 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11592 (defun org-local-logging (value)
11593 "Get logging settings from a property VALUE."
11594 (let* (words w a)
11595 ;; directly set the variables, they are already local.
11596 (setq org-log-done nil
11597 org-log-repeat nil
11598 org-todo-log-states nil)
11599 (setq words (org-split-string value))
11600 (while (setq w (pop words))
11601 (cond
11602 ((setq a (assoc w org-startup-options))
11603 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11604 (set (nth 1 a) (nth 2 a))))
11605 ((setq a (org-extract-log-state-settings w))
11606 (and (member (car a) org-todo-keywords-1)
11607 (push a org-todo-log-states)))))))
11609 (defun org-get-todo-sequence-head (kwd)
11610 "Return the head of the TODO sequence to which KWD belongs.
11611 If KWD is not set, check if there is a text property remembering the
11612 right sequence."
11613 (let (p)
11614 (cond
11615 ((not kwd)
11616 (or (get-text-property (point-at-bol) 'org-todo-head)
11617 (progn
11618 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11619 nil (point-at-eol)))
11620 (get-text-property p 'org-todo-head))))
11621 ((not (member kwd org-todo-keywords-1))
11622 (car org-todo-keywords-1))
11623 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11625 (defun org-fast-todo-selection ()
11626 "Fast TODO keyword selection with single keys.
11627 Returns the new TODO keyword, or nil if no state change should occur."
11628 (let* ((fulltable org-todo-key-alist)
11629 (done-keywords org-done-keywords) ;; needed for the faces.
11630 (maxlen (apply 'max (mapcar
11631 (lambda (x)
11632 (if (stringp (car x)) (string-width (car x)) 0))
11633 fulltable)))
11634 (expert nil)
11635 (fwidth (+ maxlen 3 1 3))
11636 (ncol (/ (- (window-width) 4) fwidth))
11637 tg cnt e c tbl
11638 groups ingroup)
11639 (save-excursion
11640 (save-window-excursion
11641 (if expert
11642 (set-buffer (get-buffer-create " *Org todo*"))
11643 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11644 (erase-buffer)
11645 (org-set-local 'org-done-keywords done-keywords)
11646 (setq tbl fulltable cnt 0)
11647 (while (setq e (pop tbl))
11648 (cond
11649 ((equal e '(:startgroup))
11650 (push '() groups) (setq ingroup t)
11651 (when (not (= cnt 0))
11652 (setq cnt 0)
11653 (insert "\n"))
11654 (insert "{ "))
11655 ((equal e '(:endgroup))
11656 (setq ingroup nil cnt 0)
11657 (insert "}\n"))
11658 ((equal e '(:newline))
11659 (when (not (= cnt 0))
11660 (setq cnt 0)
11661 (insert "\n")
11662 (setq e (car tbl))
11663 (while (equal (car tbl) '(:newline))
11664 (insert "\n")
11665 (setq tbl (cdr tbl)))))
11667 (setq tg (car e) c (cdr e))
11668 (if ingroup (push tg (car groups)))
11669 (setq tg (org-add-props tg nil 'face
11670 (org-get-todo-face tg)))
11671 (if (and (= cnt 0) (not ingroup)) (insert " "))
11672 (insert "[" c "] " tg (make-string
11673 (- fwidth 4 (length tg)) ?\ ))
11674 (when (= (setq cnt (1+ cnt)) ncol)
11675 (insert "\n")
11676 (if ingroup (insert " "))
11677 (setq cnt 0)))))
11678 (insert "\n")
11679 (goto-char (point-min))
11680 (if (not expert) (org-fit-window-to-buffer))
11681 (message "[a-z..]:Set [SPC]:clear")
11682 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11683 (cond
11684 ((or (= c ?\C-g)
11685 (and (= c ?q) (not (rassoc c fulltable))))
11686 (setq quit-flag t))
11687 ((= c ?\ ) nil)
11688 ((setq e (rassoc c fulltable) tg (car e))
11690 (t (setq quit-flag t)))))))
11692 (defun org-entry-is-todo-p ()
11693 (member (org-get-todo-state) org-not-done-keywords))
11695 (defun org-entry-is-done-p ()
11696 (member (org-get-todo-state) org-done-keywords))
11698 (defun org-get-todo-state ()
11699 (save-excursion
11700 (org-back-to-heading t)
11701 (and (looking-at org-todo-line-regexp)
11702 (match-end 2)
11703 (match-string 2))))
11705 (defun org-at-date-range-p (&optional inactive-ok)
11706 "Is the cursor inside a date range?"
11707 (interactive)
11708 (save-excursion
11709 (catch 'exit
11710 (let ((pos (point)))
11711 (skip-chars-backward "^[<\r\n")
11712 (skip-chars-backward "<[")
11713 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11714 (>= (match-end 0) pos)
11715 (throw 'exit t))
11716 (skip-chars-backward "^<[\r\n")
11717 (skip-chars-backward "<[")
11718 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11719 (>= (match-end 0) pos)
11720 (throw 'exit t)))
11721 nil)))
11723 (defun org-get-repeat (&optional tagline)
11724 "Check if there is a deadline/schedule with repeater in this entry."
11725 (save-match-data
11726 (save-excursion
11727 (org-back-to-heading t)
11728 (and (re-search-forward (if tagline
11729 (concat tagline "\\s-*" org-repeat-re)
11730 org-repeat-re)
11731 (org-entry-end-position) t)
11732 (match-string-no-properties 1)))))
11734 (defvar org-last-changed-timestamp)
11735 (defvar org-last-inserted-timestamp)
11736 (defvar org-log-post-message)
11737 (defvar org-log-note-purpose)
11738 (defvar org-log-note-how)
11739 (defvar org-log-note-extra)
11740 (defun org-auto-repeat-maybe (done-word)
11741 "Check if the current headline contains a repeated deadline/schedule.
11742 If yes, set TODO state back to what it was and change the base date
11743 of repeating deadline/scheduled time stamps to new date.
11744 This function is run automatically after each state change to a DONE state."
11745 ;; last-state is dynamically scoped into this function
11746 (let* ((repeat (org-get-repeat))
11747 (aa (assoc last-state org-todo-kwd-alist))
11748 (interpret (nth 1 aa))
11749 (head (nth 2 aa))
11750 (whata '(("d" . day) ("m" . month) ("y" . year)))
11751 (msg "Entry repeats: ")
11752 (org-log-done nil)
11753 (org-todo-log-states nil)
11754 re type n what ts time to-state)
11755 (when repeat
11756 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11757 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11758 org-todo-repeat-to-state))
11759 (unless (and to-state (member to-state org-todo-keywords-1))
11760 (setq to-state (if (eq interpret 'type) last-state head)))
11761 (org-todo to-state)
11762 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11763 (org-entry-put nil "LAST_REPEAT" (format-time-string
11764 (org-time-stamp-format t t))))
11765 (when org-log-repeat
11766 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11767 (memq 'org-add-log-note post-command-hook))
11768 ;; OK, we are already setup for some record
11769 (if (eq org-log-repeat 'note)
11770 ;; make sure we take a note, not only a time stamp
11771 (setq org-log-note-how 'note))
11772 ;; Set up for taking a record
11773 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11774 last-state
11775 'findpos org-log-repeat)))
11776 (org-back-to-heading t)
11777 (org-add-planning-info nil nil 'closed)
11778 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11779 org-deadline-time-regexp "\\)\\|\\("
11780 org-ts-regexp "\\)"))
11781 (while (re-search-forward
11782 re (save-excursion (outline-next-heading) (point)) t)
11783 (setq type (if (match-end 1) org-scheduled-string
11784 (if (match-end 3) org-deadline-string "Plain:"))
11785 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11786 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11787 (setq n (string-to-number (match-string 2 ts))
11788 what (match-string 3 ts))
11789 (if (equal what "w") (setq n (* n 7) what "d"))
11790 ;; Preparation, see if we need to modify the start date for the change
11791 (when (match-end 1)
11792 (setq time (save-match-data (org-time-string-to-time ts)))
11793 (cond
11794 ((equal (match-string 1 ts) ".")
11795 ;; Shift starting date to today
11796 (org-timestamp-change
11797 (- (org-today) (time-to-days time))
11798 'day))
11799 ((equal (match-string 1 ts) "+")
11800 (let ((nshiftmax 10) (nshift 0))
11801 (while (or (= nshift 0)
11802 (<= (time-to-days time)
11803 (time-to-days (current-time))))
11804 (when (= (incf nshift) nshiftmax)
11805 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11806 (error "Abort")))
11807 (org-timestamp-change n (cdr (assoc what whata)))
11808 (org-at-timestamp-p t)
11809 (setq ts (match-string 1))
11810 (setq time (save-match-data (org-time-string-to-time ts)))))
11811 (org-timestamp-change (- n) (cdr (assoc what whata)))
11812 ;; rematch, so that we have everything in place for the real shift
11813 (org-at-timestamp-p t)
11814 (setq ts (match-string 1))
11815 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11816 (org-timestamp-change n (cdr (assoc what whata)))
11817 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11818 (setq org-log-post-message msg)
11819 (message "%s" msg))))
11821 (defun org-show-todo-tree (arg)
11822 "Make a compact tree which shows all headlines marked with TODO.
11823 The tree will show the lines where the regexp matches, and all higher
11824 headlines above the match.
11825 With a \\[universal-argument] prefix, prompt for a regexp to match.
11826 With a numeric prefix N, construct a sparse tree for the Nth element
11827 of `org-todo-keywords-1'."
11828 (interactive "P")
11829 (let ((case-fold-search nil)
11830 (kwd-re
11831 (cond ((null arg) org-not-done-regexp)
11832 ((equal arg '(4))
11833 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11834 (mapcar 'list org-todo-keywords-1))))
11835 (concat "\\("
11836 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11837 "\\)\\>")))
11838 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11839 (regexp-quote (nth (1- (prefix-numeric-value arg))
11840 org-todo-keywords-1)))
11841 (t (error "Invalid prefix argument: %s" arg)))))
11842 (message "%d TODO entries found"
11843 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11845 (defun org-deadline (&optional remove time)
11846 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11847 With argument REMOVE, remove any deadline from the item.
11848 With argument TIME, set the deadline at the corresponding date. TIME
11849 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11850 (interactive "P")
11851 (let* ((old-date (org-entry-get nil "DEADLINE"))
11852 (repeater (and old-date
11853 (string-match
11854 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11855 old-date)
11856 (match-string 1 old-date))))
11857 (if remove
11858 (progn
11859 (when (and old-date org-log-redeadline)
11860 (org-add-log-setup 'deldeadline nil old-date 'findpos
11861 org-log-redeadline))
11862 (org-remove-timestamp-with-keyword org-deadline-string)
11863 (message "Item no longer has a deadline."))
11864 (org-add-planning-info 'deadline time 'closed)
11865 (when (and old-date org-log-redeadline
11866 (not (equal old-date
11867 (substring org-last-inserted-timestamp 1 -1))))
11868 (org-add-log-setup 'redeadline nil old-date 'findpos
11869 org-log-redeadline))
11870 (when repeater
11871 (save-excursion
11872 (org-back-to-heading t)
11873 (when (re-search-forward (concat org-deadline-string " "
11874 org-last-inserted-timestamp)
11875 (save-excursion
11876 (outline-next-heading) (point)) t)
11877 (goto-char (1- (match-end 0)))
11878 (insert " " repeater)
11879 (setq org-last-inserted-timestamp
11880 (concat (substring org-last-inserted-timestamp 0 -1)
11881 " " repeater
11882 (substring org-last-inserted-timestamp -1))))))
11883 (message "Deadline on %s" org-last-inserted-timestamp))))
11885 (defun org-schedule (&optional remove time)
11886 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11887 With argument REMOVE, remove any scheduling date from the item.
11888 With argument TIME, scheduled at the corresponding date. TIME can
11889 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11890 (interactive "P")
11891 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11892 (repeater (and old-date
11893 (string-match
11894 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11895 old-date)
11896 (match-string 1 old-date))))
11897 (if remove
11898 (progn
11899 (when (and old-date org-log-reschedule)
11900 (org-add-log-setup 'delschedule nil old-date 'findpos
11901 org-log-reschedule))
11902 (org-remove-timestamp-with-keyword org-scheduled-string)
11903 (message "Item is no longer scheduled."))
11904 (org-add-planning-info 'scheduled time 'closed)
11905 (when (and old-date org-log-reschedule
11906 (not (equal old-date
11907 (substring org-last-inserted-timestamp 1 -1))))
11908 (org-add-log-setup 'reschedule nil old-date 'findpos
11909 org-log-reschedule))
11910 (when repeater
11911 (save-excursion
11912 (org-back-to-heading t)
11913 (when (re-search-forward (concat org-scheduled-string " "
11914 org-last-inserted-timestamp)
11915 (save-excursion
11916 (outline-next-heading) (point)) t)
11917 (goto-char (1- (match-end 0)))
11918 (insert " " repeater)
11919 (setq org-last-inserted-timestamp
11920 (concat (substring org-last-inserted-timestamp 0 -1)
11921 " " repeater
11922 (substring org-last-inserted-timestamp -1))))))
11923 (message "Scheduled to %s" org-last-inserted-timestamp))))
11925 (defun org-get-scheduled-time (pom &optional inherit)
11926 "Get the scheduled time as a time tuple, of a format suitable
11927 for calling org-schedule with, or if there is no scheduling,
11928 returns nil."
11929 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11930 (when time
11931 (apply 'encode-time (org-parse-time-string time)))))
11933 (defun org-get-deadline-time (pom &optional inherit)
11934 "Get the deadline as a time tuple, of a format suitable for
11935 calling org-deadline with, or if there is no scheduling, returns
11936 nil."
11937 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11938 (when time
11939 (apply 'encode-time (org-parse-time-string time)))))
11941 (defun org-remove-timestamp-with-keyword (keyword)
11942 "Remove all time stamps with KEYWORD in the current entry."
11943 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11944 beg)
11945 (save-excursion
11946 (org-back-to-heading t)
11947 (setq beg (point))
11948 (outline-next-heading)
11949 (while (re-search-backward re beg t)
11950 (replace-match "")
11951 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11952 (equal (char-before) ?\ ))
11953 (backward-delete-char 1)
11954 (if (string-match "^[ \t]*$" (buffer-substring
11955 (point-at-bol) (point-at-eol)))
11956 (delete-region (point-at-bol)
11957 (min (point-max) (1+ (point-at-eol))))))))))
11959 (defun org-add-planning-info (what &optional time &rest remove)
11960 "Insert new timestamp with keyword in the line directly after the headline.
11961 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
11962 If non is given, the user is prompted for a date.
11963 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11964 be removed."
11965 (interactive)
11966 (let (org-time-was-given org-end-time-was-given ts
11967 end default-time default-input)
11969 (catch 'exit
11970 (when (and (memq what '(scheduled deadline))
11971 (or (not time)
11972 (and (stringp time)
11973 (string-match "^[-+]+[0-9]" time))))
11974 ;; Try to get a default date/time from existing timestamp
11975 (save-excursion
11976 (org-back-to-heading t)
11977 (setq end (save-excursion (outline-next-heading) (point)))
11978 (when (re-search-forward (if (eq what 'scheduled)
11979 org-scheduled-time-regexp
11980 org-deadline-time-regexp)
11981 end t)
11982 (setq ts (match-string 1)
11983 default-time
11984 (apply 'encode-time (org-parse-time-string ts))
11985 default-input (and ts (org-get-compact-tod ts))))))
11986 (when what
11987 (setq time
11988 (if (and (stringp time)
11989 (string-match "^[-+]+[0-9]" time))
11990 ;; This is a relative time, set the proper date
11991 (apply 'encode-time
11992 (org-read-date-analyze
11993 time default-time (decode-time default-time)))
11994 ;; If necessary, get the time from the user
11995 (or time (org-read-date nil 'to-time nil nil
11996 default-time default-input)))))
11998 (when (and org-insert-labeled-timestamps-at-point
11999 (member what '(scheduled deadline)))
12000 (insert
12001 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12002 (org-insert-time-stamp time org-time-was-given
12003 nil nil nil (list org-end-time-was-given))
12004 (setq what nil))
12005 (save-excursion
12006 (save-restriction
12007 (let (col list elt ts buffer-invisibility-spec)
12008 (org-back-to-heading t)
12009 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12010 (goto-char (match-end 1))
12011 (setq col (current-column))
12012 (goto-char (match-end 0))
12013 (if (eobp) (insert "\n") (forward-char 1))
12014 (when (and (not what)
12015 (not (looking-at
12016 (concat "[ \t]*"
12017 org-keyword-time-not-clock-regexp))))
12018 ;; Nothing to add, nothing to remove...... :-)
12019 (throw 'exit nil))
12020 (if (and (not (looking-at org-outline-regexp))
12021 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12022 "[^\r\n]*"))
12023 (not (equal (match-string 1) org-clock-string)))
12024 (narrow-to-region (match-beginning 0) (match-end 0))
12025 (insert-before-markers "\n")
12026 (backward-char 1)
12027 (narrow-to-region (point) (point))
12028 (and org-adapt-indentation (org-indent-to-column col)))
12029 ;; Check if we have to remove something.
12030 (setq list (cons what remove))
12031 (while list
12032 (setq elt (pop list))
12033 (when (or (and (eq elt 'scheduled)
12034 (re-search-forward org-scheduled-time-regexp nil t))
12035 (and (eq elt 'deadline)
12036 (re-search-forward org-deadline-time-regexp nil t))
12037 (and (eq elt 'closed)
12038 (re-search-forward org-closed-time-regexp nil t)))
12039 (replace-match "")
12040 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12041 (and (looking-at "[ \t]+") (replace-match ""))
12042 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12043 (when what
12044 (insert
12045 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12046 (cond ((eq what 'scheduled) org-scheduled-string)
12047 ((eq what 'deadline) org-deadline-string)
12048 ((eq what 'closed) org-closed-string))
12049 " ")
12050 (setq ts (org-insert-time-stamp
12051 time
12052 (or org-time-was-given
12053 (and (eq what 'closed) org-log-done-with-time))
12054 (eq what 'closed)
12055 nil nil (list org-end-time-was-given)))
12056 (insert
12057 (if (not (or (bolp) (eq (char-before) ?\ )
12058 (memq (char-after) '(32 10))
12059 (eobp))) " " ""))
12060 (end-of-line 1))
12061 (goto-char (point-min))
12062 (widen)
12063 (if (and (looking-at "[ \t]*\n")
12064 (equal (char-before) ?\n))
12065 (delete-region (1- (point)) (point-at-eol)))
12066 ts))))))
12068 (defvar org-log-note-marker (make-marker))
12069 (defvar org-log-note-purpose nil)
12070 (defvar org-log-note-state nil)
12071 (defvar org-log-note-previous-state nil)
12072 (defvar org-log-note-how nil)
12073 (defvar org-log-note-extra nil)
12074 (defvar org-log-note-window-configuration nil)
12075 (defvar org-log-note-return-to (make-marker))
12076 (defvar org-log-note-effective-time nil
12077 "Remembered current time so that dynamically scoped
12078 `org-extend-today-until' affects tha timestamps in state change
12079 log")
12081 (defvar org-log-post-message nil
12082 "Message to be displayed after a log note has been stored.
12083 The auto-repeater uses this.")
12085 (defun org-add-note ()
12086 "Add a note to the current entry.
12087 This is done in the same way as adding a state change note."
12088 (interactive)
12089 (org-add-log-setup 'note nil nil 'findpos nil))
12091 (defvar org-property-end-re)
12092 (defun org-add-log-setup (&optional purpose state prev-state
12093 findpos how extra)
12094 "Set up the post command hook to take a note.
12095 If this is about to TODO state change, the new state is expected in STATE.
12096 When FINDPOS is non-nil, find the correct position for the note in
12097 the current entry. If not, assume that it can be inserted at point.
12098 HOW is an indicator what kind of note should be created.
12099 EXTRA is additional text that will be inserted into the notes buffer."
12100 (let* ((org-log-into-drawer (org-log-into-drawer))
12101 (drawer (cond ((stringp org-log-into-drawer)
12102 org-log-into-drawer)
12103 (org-log-into-drawer "LOGBOOK")
12104 (t nil))))
12105 (save-restriction
12106 (save-excursion
12107 (when findpos
12108 (org-back-to-heading t)
12109 (narrow-to-region (point) (save-excursion
12110 (outline-next-heading) (point)))
12111 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12112 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12113 "[^\r\n]*\\)?"))
12114 (goto-char (match-end 0))
12115 (cond
12116 (drawer
12117 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12118 nil t)
12119 (progn
12120 (goto-char (match-end 0))
12121 (or org-log-states-order-reversed
12122 (and (re-search-forward org-property-end-re nil t)
12123 (goto-char (1- (match-beginning 0))))))
12124 (insert "\n:" drawer ":\n:END:")
12125 (beginning-of-line 0)
12126 (org-indent-line-function)
12127 (beginning-of-line 2)
12128 (org-indent-line-function)
12129 (end-of-line 0)))
12130 ((and org-log-state-notes-insert-after-drawers
12131 (save-excursion
12132 (forward-line) (looking-at org-drawer-regexp)))
12133 (forward-line)
12134 (while (looking-at org-drawer-regexp)
12135 (goto-char (match-end 0))
12136 (re-search-forward org-property-end-re (point-max) t)
12137 (forward-line))
12138 (forward-line -1)))
12139 (unless org-log-states-order-reversed
12140 (and (= (char-after) ?\n) (forward-char 1))
12141 (org-skip-over-state-notes)
12142 (skip-chars-backward " \t\n\r")))
12143 (move-marker org-log-note-marker (point))
12144 (setq org-log-note-purpose purpose
12145 org-log-note-state state
12146 org-log-note-previous-state prev-state
12147 org-log-note-how how
12148 org-log-note-extra extra
12149 org-log-note-effective-time (org-current-effective-time))
12150 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12152 (defun org-skip-over-state-notes ()
12153 "Skip past the list of State notes in an entry."
12154 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12155 (when (ignore-errors (goto-char (org-in-item-p)))
12156 (let* ((struct (org-list-struct))
12157 (prevs (org-list-prevs-alist struct)))
12158 (while (looking-at "[ \t]*- State")
12159 (goto-char (or (org-list-get-next-item (point) struct prevs)
12160 (org-list-get-item-end (point) struct)))))))
12162 (defun org-add-log-note (&optional purpose)
12163 "Pop up a window for taking a note, and add this note later at point."
12164 (remove-hook 'post-command-hook 'org-add-log-note)
12165 (setq org-log-note-window-configuration (current-window-configuration))
12166 (delete-other-windows)
12167 (move-marker org-log-note-return-to (point))
12168 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12169 (goto-char org-log-note-marker)
12170 (org-switch-to-buffer-other-window "*Org Note*")
12171 (erase-buffer)
12172 (if (memq org-log-note-how '(time state))
12173 (let (current-prefix-arg) (org-store-log-note))
12174 (let ((org-inhibit-startup t)) (org-mode))
12175 (insert (format "# Insert note for %s.
12176 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12177 (cond
12178 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12179 ((eq org-log-note-purpose 'done) "closed todo item")
12180 ((eq org-log-note-purpose 'state)
12181 (format "state change from \"%s\" to \"%s\""
12182 (or org-log-note-previous-state "")
12183 (or org-log-note-state "")))
12184 ((eq org-log-note-purpose 'reschedule)
12185 "rescheduling")
12186 ((eq org-log-note-purpose 'delschedule)
12187 "no longer scheduled")
12188 ((eq org-log-note-purpose 'redeadline)
12189 "changing deadline")
12190 ((eq org-log-note-purpose 'deldeadline)
12191 "removing deadline")
12192 ((eq org-log-note-purpose 'refile)
12193 "refiling")
12194 ((eq org-log-note-purpose 'note)
12195 "this entry")
12196 (t (error "This should not happen")))))
12197 (if org-log-note-extra (insert org-log-note-extra))
12198 (org-set-local 'org-finish-function 'org-store-log-note)
12199 (run-hooks 'org-log-buffer-setup-hook)))
12201 (defvar org-note-abort nil) ; dynamically scoped
12202 (defun org-store-log-note ()
12203 "Finish taking a log note, and insert it to where it belongs."
12204 (let ((txt (buffer-string))
12205 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12206 lines ind bul)
12207 (kill-buffer (current-buffer))
12208 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12209 (setq txt (replace-match "" t t txt)))
12210 (if (string-match "\\s-+\\'" txt)
12211 (setq txt (replace-match "" t t txt)))
12212 (setq lines (org-split-string txt "\n"))
12213 (when (and note (string-match "\\S-" note))
12214 (setq note
12215 (org-replace-escapes
12216 note
12217 (list (cons "%u" (user-login-name))
12218 (cons "%U" user-full-name)
12219 (cons "%t" (format-time-string
12220 (org-time-stamp-format 'long 'inactive)
12221 org-log-note-effective-time))
12222 (cons "%T" (format-time-string
12223 (org-time-stamp-format 'long nil)
12224 org-log-note-effective-time))
12225 (cons "%d" (format-time-string
12226 (org-time-stamp-format nil 'inactive)
12227 org-log-note-effective-time))
12228 (cons "%D" (format-time-string
12229 (org-time-stamp-format nil nil)
12230 org-log-note-effective-time))
12231 (cons "%s" (if org-log-note-state
12232 (concat "\"" org-log-note-state "\"")
12233 ""))
12234 (cons "%S" (if org-log-note-previous-state
12235 (concat "\"" org-log-note-previous-state "\"")
12236 "\"\"")))))
12237 (if lines (setq note (concat note " \\\\")))
12238 (push note lines))
12239 (when (or current-prefix-arg org-note-abort)
12240 (when org-log-into-drawer
12241 (org-remove-empty-drawer-at
12242 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12243 org-log-note-marker))
12244 (setq lines nil))
12245 (when lines
12246 (with-current-buffer (marker-buffer org-log-note-marker)
12247 (save-excursion
12248 (goto-char org-log-note-marker)
12249 (move-marker org-log-note-marker nil)
12250 (end-of-line 1)
12251 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12252 (setq ind (save-excursion
12253 (if (ignore-errors (goto-char (org-in-item-p)))
12254 (let ((struct (org-list-struct)))
12255 (org-list-get-ind
12256 (org-list-get-top-point struct) struct))
12257 (skip-chars-backward " \r\t\n")
12258 (cond
12259 ((and (org-at-heading-p)
12260 org-adapt-indentation)
12261 (1+ (org-current-level)))
12262 ((org-at-heading-p) 0)
12263 (t (org-get-indentation))))))
12264 (setq bul (org-list-bullet-string "-"))
12265 (org-indent-line-to ind)
12266 (insert bul (pop lines))
12267 (let ((ind-body (+ (length bul) ind)))
12268 (while lines
12269 (insert "\n")
12270 (org-indent-line-to ind-body)
12271 (insert (pop lines))))
12272 (message "Note stored")
12273 (org-back-to-heading t)
12274 (org-cycle-hide-drawers 'children)))))
12275 (set-window-configuration org-log-note-window-configuration)
12276 (with-current-buffer (marker-buffer org-log-note-return-to)
12277 (goto-char org-log-note-return-to))
12278 (move-marker org-log-note-return-to nil)
12279 (and org-log-post-message (message "%s" org-log-post-message)))
12281 (defun org-remove-empty-drawer-at (drawer pos)
12282 "Remove an empty drawer DRAWER at position POS.
12283 POS may also be a marker."
12284 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12285 (save-excursion
12286 (save-restriction
12287 (widen)
12288 (goto-char pos)
12289 (if (org-in-regexp
12290 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12291 (replace-match ""))))))
12293 (defun org-sparse-tree (&optional arg)
12294 "Create a sparse tree, prompt for the details.
12295 This command can create sparse trees. You first need to select the type
12296 of match used to create the tree:
12298 t Show all TODO entries.
12299 T Show entries with a specific TODO keyword.
12300 m Show entries selected by a tags/property match.
12301 p Enter a property name and its value (both with completion on existing
12302 names/values) and show entries with that property.
12303 r Show entries matching a regular expression (`/' can be used as well)
12304 d Show deadlines due within `org-deadline-warning-days'.
12305 b Show deadlines and scheduled items before a date.
12306 a Show deadlines and scheduled items after a date."
12307 (interactive "P")
12308 (let (ans kwd value)
12309 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12310 (setq ans (read-char-exclusive))
12311 (cond
12312 ((equal ans ?d)
12313 (call-interactively 'org-check-deadlines))
12314 ((equal ans ?b)
12315 (call-interactively 'org-check-before-date))
12316 ((equal ans ?a)
12317 (call-interactively 'org-check-after-date))
12318 ((equal ans ?t)
12319 (org-show-todo-tree nil))
12320 ((equal ans ?T)
12321 (org-show-todo-tree '(4)))
12322 ((member ans '(?T ?m))
12323 (call-interactively 'org-match-sparse-tree))
12324 ((member ans '(?p ?P))
12325 (setq kwd (org-icompleting-read "Property: "
12326 (mapcar 'list (org-buffer-property-keys))))
12327 (setq value (org-icompleting-read "Value: "
12328 (mapcar 'list (org-property-values kwd))))
12329 (unless (string-match "\\`{.*}\\'" value)
12330 (setq value (concat "\"" value "\"")))
12331 (org-match-sparse-tree arg (concat kwd "=" value)))
12332 ((member ans '(?r ?R ?/))
12333 (call-interactively 'org-occur))
12334 (t (error "No such sparse tree command \"%c\"" ans)))))
12336 (defvar org-occur-highlights nil
12337 "List of overlays used for occur matches.")
12338 (make-variable-buffer-local 'org-occur-highlights)
12339 (defvar org-occur-parameters nil
12340 "Parameters of the active org-occur calls.
12341 This is a list, each call to org-occur pushes as cons cell,
12342 containing the regular expression and the callback, onto the list.
12343 The list can contain several entries if `org-occur' has been called
12344 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12345 will only contain one set of parameters. When the highlights are
12346 removed (for example with `C-c C-c', or with the next edit (depending
12347 on `org-remove-highlights-with-change'), this variable is emptied
12348 as well.")
12349 (make-variable-buffer-local 'org-occur-parameters)
12351 (defun org-occur (regexp &optional keep-previous callback)
12352 "Make a compact tree which shows all matches of REGEXP.
12353 The tree will show the lines where the regexp matches, and all higher
12354 headlines above the match. It will also show the heading after the match,
12355 to make sure editing the matching entry is easy.
12356 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12357 call to `org-occur' will be kept, to allow stacking of calls to this
12358 command.
12359 If CALLBACK is non-nil, it is a function which is called to confirm
12360 that the match should indeed be shown."
12361 (interactive "sRegexp: \nP")
12362 (when (equal regexp "")
12363 (error "Regexp cannot be empty"))
12364 (unless keep-previous
12365 (org-remove-occur-highlights nil nil t))
12366 (push (cons regexp callback) org-occur-parameters)
12367 (let ((cnt 0))
12368 (save-excursion
12369 (goto-char (point-min))
12370 (if (or (not keep-previous) ; do not want to keep
12371 (not org-occur-highlights)) ; no previous matches
12372 ;; hide everything
12373 (org-overview))
12374 (while (re-search-forward regexp nil t)
12375 (when (or (not callback)
12376 (save-match-data (funcall callback)))
12377 (setq cnt (1+ cnt))
12378 (when org-highlight-sparse-tree-matches
12379 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12380 (org-show-context 'occur-tree))))
12381 (when org-remove-highlights-with-change
12382 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12383 nil 'local))
12384 (unless org-sparse-tree-open-archived-trees
12385 (org-hide-archived-subtrees (point-min) (point-max)))
12386 (run-hooks 'org-occur-hook)
12387 (if (org-called-interactively-p 'interactive)
12388 (message "%d match(es) for regexp %s" cnt regexp))
12389 cnt))
12391 (defun org-occur-next-match (&optional n reset)
12392 "Function for `next-error-function' to find sparse tree matches.
12393 N is the number of matches to move, when negative move backwards.
12394 RESET is entirely ignored - this function always goes back to the
12395 starting point when no match is found."
12396 (let* ((limit (if (< n 0) (point-min) (point-max)))
12397 (search-func (if (< n 0)
12398 'previous-single-char-property-change
12399 'next-single-char-property-change))
12400 (n (abs n))
12401 (pos (point))
12403 (catch 'exit
12404 (while (setq p1 (funcall search-func (point) 'org-type))
12405 (when (equal p1 limit)
12406 (goto-char pos)
12407 (error "No more matches"))
12408 (when (equal (get-char-property p1 'org-type) 'org-occur)
12409 (setq n (1- n))
12410 (when (= n 0)
12411 (goto-char p1)
12412 (throw 'exit (point))))
12413 (goto-char p1))
12414 (goto-char p1)
12415 (error "No more matches"))))
12417 (defun org-show-context (&optional key)
12418 "Make sure point and context are visible.
12419 How much context is shown depends upon the variables
12420 `org-show-hierarchy-above', `org-show-following-heading'. and
12421 `org-show-siblings'."
12422 (let ((heading-p (org-on-heading-p t))
12423 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12424 (following-p (org-get-alist-option org-show-following-heading key))
12425 (entry-p (org-get-alist-option org-show-entry-below key))
12426 (siblings-p (org-get-alist-option org-show-siblings key)))
12427 (catch 'exit
12428 ;; Show heading or entry text
12429 (if (and heading-p (not entry-p))
12430 (org-flag-heading nil) ; only show the heading
12431 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12432 (org-show-hidden-entry))) ; show entire entry
12433 (when following-p
12434 ;; Show next sibling, or heading below text
12435 (save-excursion
12436 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12437 (org-flag-heading nil))))
12438 (when siblings-p (org-show-siblings))
12439 (when hierarchy-p
12440 ;; show all higher headings, possibly with siblings
12441 (save-excursion
12442 (while (and (condition-case nil
12443 (progn (org-up-heading-all 1) t)
12444 (error nil))
12445 (not (bobp)))
12446 (org-flag-heading nil)
12447 (when siblings-p (org-show-siblings))))))))
12449 (defvar org-reveal-start-hook nil
12450 "Hook run before revealing a location.")
12452 (defun org-reveal (&optional siblings)
12453 "Show current entry, hierarchy above it, and the following headline.
12454 This can be used to show a consistent set of context around locations
12455 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12456 not t for the search context.
12458 With optional argument SIBLINGS, on each level of the hierarchy all
12459 siblings are shown. This repairs the tree structure to what it would
12460 look like when opened with hierarchical calls to `org-cycle'.
12461 With double optional argument \\[universal-argument] \\[universal-argument], \
12462 go to the parent and show the
12463 entire tree."
12464 (interactive "P")
12465 (run-hooks 'org-reveal-start-hook)
12466 (let ((org-show-hierarchy-above t)
12467 (org-show-following-heading t)
12468 (org-show-siblings (if siblings t org-show-siblings)))
12469 (org-show-context nil))
12470 (when (equal siblings '(16))
12471 (save-excursion
12472 (when (org-up-heading-safe)
12473 (org-show-subtree)
12474 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12476 (defun org-highlight-new-match (beg end)
12477 "Highlight from BEG to END and mark the highlight is an occur headline."
12478 (let ((ov (make-overlay beg end)))
12479 (overlay-put ov 'face 'secondary-selection)
12480 (overlay-put ov 'org-type 'org-occur)
12481 (push ov org-occur-highlights)))
12483 (defun org-remove-occur-highlights (&optional beg end noremove)
12484 "Remove the occur highlights from the buffer.
12485 BEG and END are ignored. If NOREMOVE is nil, remove this function
12486 from the `before-change-functions' in the current buffer."
12487 (interactive)
12488 (unless org-inhibit-highlight-removal
12489 (mapc 'delete-overlay org-occur-highlights)
12490 (setq org-occur-highlights nil)
12491 (setq org-occur-parameters nil)
12492 (unless noremove
12493 (remove-hook 'before-change-functions
12494 'org-remove-occur-highlights 'local))))
12496 ;;;; Priorities
12498 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12499 "Regular expression matching the priority indicator.")
12501 (defvar org-remove-priority-next-time nil)
12503 (defun org-priority-up ()
12504 "Increase the priority of the current item."
12505 (interactive)
12506 (org-priority 'up))
12508 (defun org-priority-down ()
12509 "Decrease the priority of the current item."
12510 (interactive)
12511 (org-priority 'down))
12513 (defun org-priority (&optional action)
12514 "Change the priority of an item by ARG.
12515 ACTION can be `set', `up', `down', or a character."
12516 (interactive)
12517 (unless org-enable-priority-commands
12518 (error "Priority commands are disabled"))
12519 (setq action (or action 'set))
12520 (let (current new news have remove)
12521 (save-excursion
12522 (org-back-to-heading t)
12523 (if (looking-at org-priority-regexp)
12524 (setq current (string-to-char (match-string 2))
12525 have t))
12526 (cond
12527 ((eq action 'remove)
12528 (setq remove t new ?\ ))
12529 ((or (eq action 'set)
12530 (if (featurep 'xemacs) (characterp action) (integerp action)))
12531 (if (not (eq action 'set))
12532 (setq new action)
12533 (message "Priority %c-%c, SPC to remove: "
12534 org-highest-priority org-lowest-priority)
12535 (save-match-data
12536 (setq new (read-char-exclusive))))
12537 (if (and (= (upcase org-highest-priority) org-highest-priority)
12538 (= (upcase org-lowest-priority) org-lowest-priority))
12539 (setq new (upcase new)))
12540 (cond ((equal new ?\ ) (setq remove t))
12541 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12542 (error "Priority must be between `%c' and `%c'"
12543 org-highest-priority org-lowest-priority))))
12544 ((eq action 'up)
12545 (setq new (if have
12546 (1- current) ; normal cycling
12547 ;; last priority was empty
12548 (if (eq last-command this-command)
12549 org-lowest-priority ; wrap around empty to lowest
12550 ;; default
12551 (if org-priority-start-cycle-with-default
12552 org-default-priority
12553 (1- org-default-priority))))))
12554 ((eq action 'down)
12555 (setq new (if have
12556 (1+ current) ; normal cycling
12557 ;; last priority was empty
12558 (if (eq last-command this-command)
12559 org-highest-priority ; wrap around empty to highest
12560 ;; default
12561 (if org-priority-start-cycle-with-default
12562 org-default-priority
12563 (1+ org-default-priority))))))
12564 (t (error "Invalid action")))
12565 (if (or (< (upcase new) org-highest-priority)
12566 (> (upcase new) org-lowest-priority))
12567 (if (and (memq action '(up down))
12568 (not have) (not (eq last-command this-command)))
12569 ;; `new' is from default priority
12570 (error
12571 "The default can not be set, see `org-default-priority' why")
12572 ;; normal cycling: `new' is beyond highest/lowest priority
12573 ;; and is wrapped around to the empty priority
12574 (setq remove t)))
12575 (setq news (format "%c" new))
12576 (if have
12577 (if remove
12578 (replace-match "" t t nil 1)
12579 (replace-match news t t nil 2))
12580 (if remove
12581 (error "No priority cookie found in line")
12582 (let ((case-fold-search nil))
12583 (looking-at org-todo-line-regexp))
12584 (if (match-end 2)
12585 (progn
12586 (goto-char (match-end 2))
12587 (insert " [#" news "]"))
12588 (goto-char (match-beginning 3))
12589 (insert "[#" news "] "))))
12590 (org-preserve-lc (org-set-tags nil 'align)))
12591 (if remove
12592 (message "Priority removed")
12593 (message "Priority of current item set to %s" news))))
12595 (defun org-get-priority (s)
12596 "Find priority cookie and return priority."
12597 (if (functionp org-get-priority-function)
12598 (funcall org-get-priority-function)
12599 (save-match-data
12600 (if (not (string-match org-priority-regexp s))
12601 (* 1000 (- org-lowest-priority org-default-priority))
12602 (* 1000 (- org-lowest-priority
12603 (string-to-char (match-string 2 s))))))))
12605 ;;;; Tags
12607 (defvar org-agenda-archives-mode)
12608 (defvar org-map-continue-from nil
12609 "Position from where mapping should continue.
12610 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12612 (defvar org-scanner-tags nil
12613 "The current tag list while the tags scanner is running.")
12614 (defvar org-trust-scanner-tags nil
12615 "Should `org-get-tags-at' use the tags for the scanner.
12616 This is for internal dynamical scoping only.
12617 When this is non-nil, the function `org-get-tags-at' will return the value
12618 of `org-scanner-tags' instead of building the list by itself. This
12619 can lead to large speed-ups when the tags scanner is used in a file with
12620 many entries, and when the list of tags is retrieved, for example to
12621 obtain a list of properties. Building the tags list for each entry in such
12622 a file becomes an N^2 operation - but with this variable set, it scales
12623 as N.")
12625 (defun org-scan-tags (action matcher &optional todo-only)
12626 "Scan headline tags with inheritance and produce output ACTION.
12628 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12629 or `agenda' to produce an entry list for an agenda view. It can also be
12630 a Lisp form or a function that should be called at each matched headline, in
12631 this case the return value is a list of all return values from these calls.
12633 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12634 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12635 only lines with a TODO keyword are included in the output."
12636 (require 'org-agenda)
12637 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12638 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12639 (org-re
12640 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12641 (props (list 'face 'default
12642 'done-face 'org-agenda-done
12643 'undone-face 'default
12644 'mouse-face 'highlight
12645 'org-not-done-regexp org-not-done-regexp
12646 'org-todo-regexp org-todo-regexp
12647 'help-echo
12648 (format "mouse-2 or RET jump to org file %s"
12649 (abbreviate-file-name
12650 (or (buffer-file-name (buffer-base-buffer))
12651 (buffer-name (buffer-base-buffer)))))))
12652 (case-fold-search nil)
12653 (org-map-continue-from nil)
12654 lspos tags tags-list
12655 (tags-alist (list (cons 0 org-file-tags)))
12656 (llast 0) rtn rtn1 level category i txt
12657 todo marker entry priority)
12658 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12659 (setq action (list 'lambda nil action)))
12660 (save-excursion
12661 (goto-char (point-min))
12662 (when (eq action 'sparse-tree)
12663 (org-overview)
12664 (org-remove-occur-highlights))
12665 (while (re-search-forward re nil t)
12666 (catch :skip
12667 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12668 tags (if (match-end 4) (org-match-string-no-properties 4)))
12669 (goto-char (setq lspos (match-beginning 0)))
12670 (setq level (org-reduced-level (funcall outline-level))
12671 category (org-get-category))
12672 (setq i llast llast level)
12673 ;; remove tag lists from same and sublevels
12674 (while (>= i level)
12675 (when (setq entry (assoc i tags-alist))
12676 (setq tags-alist (delete entry tags-alist)))
12677 (setq i (1- i)))
12678 ;; add the next tags
12679 (when tags
12680 (setq tags (org-split-string tags ":")
12681 tags-alist
12682 (cons (cons level tags) tags-alist)))
12683 ;; compile tags for current headline
12684 (setq tags-list
12685 (if org-use-tag-inheritance
12686 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12687 tags)
12688 org-scanner-tags tags-list)
12689 (when org-use-tag-inheritance
12690 (setcdr (car tags-alist)
12691 (mapcar (lambda (x)
12692 (setq x (copy-sequence x))
12693 (org-add-prop-inherited x))
12694 (cdar tags-alist))))
12695 (when (and tags org-use-tag-inheritance
12696 (or (not (eq t org-use-tag-inheritance))
12697 org-tags-exclude-from-inheritance))
12698 ;; selective inheritance, remove uninherited ones
12699 (setcdr (car tags-alist)
12700 (org-remove-uninherited-tags (cdar tags-alist))))
12701 (when (and
12703 ;; eval matcher only when the todo condition is OK
12704 (and (or (not todo-only) (member todo org-not-done-keywords))
12705 (let ((case-fold-search t)) (eval matcher)))
12707 ;; Call the skipper, but return t if it does not skip,
12708 ;; so that the `and' form continues evaluating
12709 (progn
12710 (unless (eq action 'sparse-tree) (org-agenda-skip))
12713 ;; Check if timestamps are deselecting this entry
12714 (or (not todo-only)
12715 (and (member todo org-not-done-keywords)
12716 (or (not org-agenda-tags-todo-honor-ignore-options)
12717 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12719 ;; Extra check for the archive tag
12720 ;; FIXME: Does the skipper already do this????
12722 (not (member org-archive-tag tags-list))
12723 ;; we have an archive tag, should we use this anyway?
12724 (or (not org-agenda-skip-archived-trees)
12725 (and (eq action 'agenda) org-agenda-archives-mode))))
12727 ;; select this headline
12729 (cond
12730 ((eq action 'sparse-tree)
12731 (and org-highlight-sparse-tree-matches
12732 (org-get-heading) (match-end 0)
12733 (org-highlight-new-match
12734 (match-beginning 0) (match-beginning 1)))
12735 (org-show-context 'tags-tree))
12736 ((eq action 'agenda)
12737 (setq txt (org-format-agenda-item
12739 (concat
12740 (if (eq org-tags-match-list-sublevels 'indented)
12741 (make-string (1- level) ?.) "")
12742 (org-get-heading))
12743 category
12744 tags-list
12746 priority (org-get-priority txt))
12747 (goto-char lspos)
12748 (setq marker (org-agenda-new-marker))
12749 (org-add-props txt props
12750 'org-marker marker 'org-hd-marker marker 'org-category category
12751 'todo-state todo
12752 'priority priority 'type "tagsmatch")
12753 (push txt rtn))
12754 ((functionp action)
12755 (setq org-map-continue-from nil)
12756 (save-excursion
12757 (setq rtn1 (funcall action))
12758 (push rtn1 rtn)))
12759 (t (error "Invalid action")))
12761 ;; if we are to skip sublevels, jump to end of subtree
12762 (unless org-tags-match-list-sublevels
12763 (org-end-of-subtree t)
12764 (backward-char 1))))
12765 ;; Get the correct position from where to continue
12766 (if org-map-continue-from
12767 (goto-char org-map-continue-from)
12768 (and (= (point) lspos) (end-of-line 1)))))
12769 (when (and (eq action 'sparse-tree)
12770 (not org-sparse-tree-open-archived-trees))
12771 (org-hide-archived-subtrees (point-min) (point-max)))
12772 (nreverse rtn)))
12774 (defun org-remove-uninherited-tags (tags)
12775 "Remove all tags that are not inherited from the list TAGS."
12776 (cond
12777 ((eq org-use-tag-inheritance t)
12778 (if org-tags-exclude-from-inheritance
12779 (org-delete-all org-tags-exclude-from-inheritance tags)
12780 tags))
12781 ((not org-use-tag-inheritance) nil)
12782 ((stringp org-use-tag-inheritance)
12783 (delq nil (mapcar
12784 (lambda (x)
12785 (if (and (string-match org-use-tag-inheritance x)
12786 (not (member x org-tags-exclude-from-inheritance)))
12787 x nil))
12788 tags)))
12789 ((listp org-use-tag-inheritance)
12790 (delq nil (mapcar
12791 (lambda (x)
12792 (if (member x org-use-tag-inheritance) x nil))
12793 tags)))))
12795 (defvar todo-only) ;; dynamically scoped
12797 (defun org-match-sparse-tree (&optional todo-only match)
12798 "Create a sparse tree according to tags string MATCH.
12799 MATCH can contain positive and negative selection of tags, like
12800 \"+WORK+URGENT-WITHBOSS\".
12801 If optional argument TODO-ONLY is non-nil, only select lines that are
12802 also TODO lines."
12803 (interactive "P")
12804 (org-prepare-agenda-buffers (list (current-buffer)))
12805 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12807 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12809 (defvar org-cached-props nil)
12810 (defun org-cached-entry-get (pom property)
12811 (if (or (eq t org-use-property-inheritance)
12812 (and (stringp org-use-property-inheritance)
12813 (string-match org-use-property-inheritance property))
12814 (and (listp org-use-property-inheritance)
12815 (member property org-use-property-inheritance)))
12816 ;; Caching is not possible, check it directly
12817 (org-entry-get pom property 'inherit)
12818 ;; Get all properties, so that we can do complicated checks easily
12819 (cdr (assoc property (or org-cached-props
12820 (setq org-cached-props
12821 (org-entry-properties pom)))))))
12823 (defun org-global-tags-completion-table (&optional files)
12824 "Return the list of all tags in all agenda buffer/files.
12825 Optional FILES argument is a list of files to which can be used
12826 instead of the agenda files."
12827 (save-excursion
12828 (org-uniquify
12829 (delq nil
12830 (apply 'append
12831 (mapcar
12832 (lambda (file)
12833 (set-buffer (find-file-noselect file))
12834 (append (org-get-buffer-tags)
12835 (mapcar (lambda (x) (if (stringp (car-safe x))
12836 (list (car-safe x)) nil))
12837 org-tag-alist)))
12838 (if (and files (car files))
12839 files
12840 (org-agenda-files))))))))
12842 (defun org-make-tags-matcher (match)
12843 "Create the TAGS/TODO matcher form for the selection string MATCH."
12844 ;; todo-only is scoped dynamically into this function, and the function
12845 ;; may change it if the matcher asks for it.
12846 (unless match
12847 ;; Get a new match request, with completion
12848 (let ((org-last-tags-completion-table
12849 (org-global-tags-completion-table)))
12850 (setq match (org-completing-read-no-i
12851 "Match: " 'org-tags-completion-function nil nil nil
12852 'org-tags-history))))
12854 ;; Parse the string and create a lisp form
12855 (let ((match0 match)
12856 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12857 minus tag mm
12858 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12859 orterms term orlist re-p str-p level-p level-op time-p
12860 prop-p pn pv po gv rest)
12861 (if (string-match "/+" match)
12862 ;; match contains also a todo-matching request
12863 (progn
12864 (setq tagsmatch (substring match 0 (match-beginning 0))
12865 todomatch (substring match (match-end 0)))
12866 (if (string-match "^!" todomatch)
12867 (setq todo-only t todomatch (substring todomatch 1)))
12868 (if (string-match "^\\s-*$" todomatch)
12869 (setq todomatch nil)))
12870 ;; only matching tags
12871 (setq tagsmatch match todomatch nil))
12873 ;; Make the tags matcher
12874 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12875 (setq tagsmatcher t)
12876 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12877 (while (setq term (pop orterms))
12878 (while (and (equal (substring term -1) "\\") orterms)
12879 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12880 (while (string-match re term)
12881 (setq rest (substring term (match-end 0))
12882 minus (and (match-end 1)
12883 (equal (match-string 1 term) "-"))
12884 tag (save-match-data (replace-regexp-in-string
12885 "\\\\-" "-"
12886 (match-string 2 term)))
12887 re-p (equal (string-to-char tag) ?{)
12888 level-p (match-end 4)
12889 prop-p (match-end 5)
12890 mm (cond
12891 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12892 (level-p
12893 (setq level-op (org-op-to-function (match-string 3 term)))
12894 `(,level-op level ,(string-to-number
12895 (match-string 4 term))))
12896 (prop-p
12897 (setq pn (match-string 5 term)
12898 po (match-string 6 term)
12899 pv (match-string 7 term)
12900 re-p (equal (string-to-char pv) ?{)
12901 str-p (equal (string-to-char pv) ?\")
12902 time-p (save-match-data
12903 (string-match "^\"[[<].*[]>]\"$" pv))
12904 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12905 (if time-p (setq pv (org-matcher-time pv)))
12906 (setq po (org-op-to-function po (if time-p 'time str-p)))
12907 (cond
12908 ((equal pn "CATEGORY")
12909 (setq gv '(get-text-property (point) 'org-category)))
12910 ((equal pn "TODO")
12911 (setq gv 'todo))
12913 (setq gv `(org-cached-entry-get nil ,pn))))
12914 (if re-p
12915 (if (eq po 'org<>)
12916 `(not (string-match ,pv (or ,gv "")))
12917 `(string-match ,pv (or ,gv "")))
12918 (if str-p
12919 `(,po (or ,gv "") ,pv)
12920 `(,po (string-to-number (or ,gv ""))
12921 ,(string-to-number pv) ))))
12922 (t `(member ,tag tags-list)))
12923 mm (if minus (list 'not mm) mm)
12924 term rest)
12925 (push mm tagsmatcher))
12926 (push (if (> (length tagsmatcher) 1)
12927 (cons 'and tagsmatcher)
12928 (car tagsmatcher))
12929 orlist)
12930 (setq tagsmatcher nil))
12931 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12932 (setq tagsmatcher
12933 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12934 ;; Make the todo matcher
12935 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12936 (setq todomatcher t)
12937 (setq orterms (org-split-string todomatch "|") orlist nil)
12938 (while (setq term (pop orterms))
12939 (while (string-match re term)
12940 (setq minus (and (match-end 1)
12941 (equal (match-string 1 term) "-"))
12942 kwd (match-string 2 term)
12943 re-p (equal (string-to-char kwd) ?{)
12944 term (substring term (match-end 0))
12945 mm (if re-p
12946 `(string-match ,(substring kwd 1 -1) todo)
12947 (list 'equal 'todo kwd))
12948 mm (if minus (list 'not mm) mm))
12949 (push mm todomatcher))
12950 (push (if (> (length todomatcher) 1)
12951 (cons 'and todomatcher)
12952 (car todomatcher))
12953 orlist)
12954 (setq todomatcher nil))
12955 (setq todomatcher (if (> (length orlist) 1)
12956 (cons 'or orlist) (car orlist))))
12958 ;; Return the string and lisp forms of the matcher
12959 (setq matcher (if todomatcher
12960 (list 'and tagsmatcher todomatcher)
12961 tagsmatcher))
12962 (cons match0 matcher)))
12964 (defun org-op-to-function (op &optional stringp)
12965 "Turn an operator into the appropriate function."
12966 (setq op
12967 (cond
12968 ((equal op "<" ) '(< string< org-time<))
12969 ((equal op ">" ) '(> org-string> org-time>))
12970 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12971 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12972 ((member op '("=" "==")) '(= string= org-time=))
12973 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12974 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12976 (defun org<> (a b) (not (= a b)))
12977 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12978 (defun org-string>= (a b) (not (string< a b)))
12979 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12980 (defun org-string<> (a b) (not (string= a b)))
12981 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12982 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12983 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12984 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12985 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12986 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12987 (defun org-2ft (s)
12988 "Convert S to a floating point time.
12989 If S is already a number, just return it. If it is a string, parse
12990 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12991 (cond
12992 ((numberp s) s)
12993 ((stringp s)
12994 (condition-case nil
12995 (float-time (apply 'encode-time (org-parse-time-string s)))
12996 (error 0.)))
12997 (t 0.)))
12999 (defun org-time-today ()
13000 "Time in seconds today at 0:00.
13001 Returns the float number of seconds since the beginning of the
13002 epoch to the beginning of today (00:00)."
13003 (float-time (apply 'encode-time
13004 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13006 (defun org-matcher-time (s)
13007 "Interpret a time comparison value."
13008 (save-match-data
13009 (cond
13010 ((string= s "<now>") (float-time))
13011 ((string= s "<today>") (org-time-today))
13012 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13013 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13014 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13015 (+ (org-time-today)
13016 (* (string-to-number (match-string 1 s))
13017 (cdr (assoc (match-string 2 s)
13018 '(("d" . 86400.0) ("w" . 604800.0)
13019 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13020 (t (org-2ft s)))))
13022 (defun org-match-any-p (re list)
13023 "Does re match any element of list?"
13024 (setq list (mapcar (lambda (x) (string-match re x)) list))
13025 (delq nil list))
13027 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13028 (defvar org-tags-overlay (make-overlay 1 1))
13029 (org-detach-overlay org-tags-overlay)
13031 (defun org-get-local-tags-at (&optional pos)
13032 "Get a list of tags defined in the current headline."
13033 (org-get-tags-at pos 'local))
13035 (defun org-get-local-tags ()
13036 "Get a list of tags defined in the current headline."
13037 (org-get-tags-at nil 'local))
13039 (defun org-get-tags-at (&optional pos local)
13040 "Get a list of all headline tags applicable at POS.
13041 POS defaults to point. If tags are inherited, the list contains
13042 the targets in the same sequence as the headlines appear, i.e.
13043 the tags of the current headline come last.
13044 When LOCAL is non-nil, only return tags from the current headline,
13045 ignore inherited ones."
13046 (interactive)
13047 (if (and org-trust-scanner-tags
13048 (or (not pos) (equal pos (point)))
13049 (not local))
13050 org-scanner-tags
13051 (let (tags ltags lastpos parent)
13052 (save-excursion
13053 (save-restriction
13054 (widen)
13055 (goto-char (or pos (point)))
13056 (save-match-data
13057 (catch 'done
13058 (condition-case nil
13059 (progn
13060 (org-back-to-heading t)
13061 (while (not (equal lastpos (point)))
13062 (setq lastpos (point))
13063 (when (looking-at
13064 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13065 (setq ltags (org-split-string
13066 (org-match-string-no-properties 1) ":"))
13067 (when parent
13068 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13069 (setq tags (append
13070 (if parent
13071 (org-remove-uninherited-tags ltags)
13072 ltags)
13073 tags)))
13074 (or org-use-tag-inheritance (throw 'done t))
13075 (if local (throw 'done t))
13076 (or (org-up-heading-safe) (error nil))
13077 (setq parent t)))
13078 (error nil)))))
13079 (if local
13080 tags
13081 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13083 (defun org-add-prop-inherited (s)
13084 (add-text-properties 0 (length s) '(inherited t) s)
13087 (defun org-toggle-tag (tag &optional onoff)
13088 "Toggle the tag TAG for the current line.
13089 If ONOFF is `on' or `off', don't toggle but set to this state."
13090 (let (res current)
13091 (save-excursion
13092 (org-back-to-heading t)
13093 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13094 (point-at-eol) t)
13095 (progn
13096 (setq current (match-string 1))
13097 (replace-match ""))
13098 (setq current ""))
13099 (setq current (nreverse (org-split-string current ":")))
13100 (cond
13101 ((eq onoff 'on)
13102 (setq res t)
13103 (or (member tag current) (push tag current)))
13104 ((eq onoff 'off)
13105 (or (not (member tag current)) (setq current (delete tag current))))
13106 (t (if (member tag current)
13107 (setq current (delete tag current))
13108 (setq res t)
13109 (push tag current))))
13110 (end-of-line 1)
13111 (if current
13112 (progn
13113 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13114 (org-set-tags nil t))
13115 (delete-horizontal-space))
13116 (run-hooks 'org-after-tags-change-hook))
13117 res))
13119 (defun org-align-tags-here (to-col)
13120 ;; Assumes that this is a headline
13121 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13122 (beginning-of-line 1)
13123 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13124 (< pos (match-beginning 2)))
13125 (progn
13126 (setq tags-l (- (match-end 2) (match-beginning 2)))
13127 (goto-char (match-beginning 1))
13128 (insert " ")
13129 (delete-region (point) (1+ (match-beginning 2)))
13130 (setq ncol (max (current-column)
13131 (1+ col)
13132 (if (> to-col 0)
13133 to-col
13134 (- (abs to-col) tags-l))))
13135 (setq p (point))
13136 (insert (make-string (- ncol (current-column)) ?\ ))
13137 (setq ncol (current-column))
13138 (when indent-tabs-mode (tabify p (point-at-eol)))
13139 (org-move-to-column (min ncol col) t))
13140 (goto-char pos))))
13142 (defun org-set-tags-command (&optional arg just-align)
13143 "Call the set-tags command for the current entry."
13144 (interactive "P")
13145 (if (org-on-heading-p)
13146 (org-set-tags arg just-align)
13147 (save-excursion
13148 (org-back-to-heading t)
13149 (org-set-tags arg just-align))))
13151 (defun org-set-tags-to (data)
13152 "Set the tags of the current entry to DATA, replacing the current tags.
13153 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13154 If DATA is nil or the empty string, any tags will be removed."
13155 (interactive "sTags: ")
13156 (setq data
13157 (cond
13158 ((eq data nil) "")
13159 ((equal data "") "")
13160 ((stringp data)
13161 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13162 ":"))
13163 ((listp data)
13164 (concat ":" (mapconcat 'identity data ":") ":"))
13165 (t nil)))
13166 (when data
13167 (save-excursion
13168 (org-back-to-heading t)
13169 (when (looking-at org-complex-heading-regexp)
13170 (if (match-end 5)
13171 (progn
13172 (goto-char (match-beginning 5))
13173 (insert data)
13174 (delete-region (point) (point-at-eol))
13175 (org-set-tags nil 'align))
13176 (goto-char (point-at-eol))
13177 (insert " " data)
13178 (org-set-tags nil 'align)))
13179 (beginning-of-line 1)
13180 (if (looking-at ".*?\\([ \t]+\\)$")
13181 (delete-region (match-beginning 1) (match-end 1))))))
13183 (defun org-align-all-tags ()
13184 "Align the tags i all headings."
13185 (interactive)
13186 (save-excursion
13187 (or (ignore-errors (org-back-to-heading t))
13188 (outline-next-heading))
13189 (if (org-on-heading-p)
13190 (org-set-tags t)
13191 (message "No headings"))))
13193 (defvar org-indent-indentation-per-level)
13194 (defun org-set-tags (&optional arg just-align)
13195 "Set the tags for the current headline.
13196 With prefix ARG, realign all tags in headings in the current buffer."
13197 (interactive "P")
13198 (let* ((re org-outline-regexp-bol)
13199 (current (org-get-tags-string))
13200 (col (current-column))
13201 (org-setting-tags t)
13202 table current-tags inherited-tags ; computed below when needed
13203 tags p0 c0 c1 rpl di tc level)
13204 (if arg
13205 (save-excursion
13206 (goto-char (point-min))
13207 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13208 (while (re-search-forward re nil t)
13209 (org-set-tags nil t)
13210 (end-of-line 1)))
13211 (message "All tags realigned to column %d" org-tags-column))
13212 (if just-align
13213 (setq tags current)
13214 ;; Get a new set of tags from the user
13215 (save-excursion
13216 (setq table (append org-tag-persistent-alist
13217 (or org-tag-alist (org-get-buffer-tags))
13218 (and
13219 org-complete-tags-always-offer-all-agenda-tags
13220 (org-global-tags-completion-table
13221 (org-agenda-files))))
13222 org-last-tags-completion-table table
13223 current-tags (org-split-string current ":")
13224 inherited-tags (nreverse
13225 (nthcdr (length current-tags)
13226 (nreverse (org-get-tags-at))))
13227 tags
13228 (if (or (eq t org-use-fast-tag-selection)
13229 (and org-use-fast-tag-selection
13230 (delq nil (mapcar 'cdr table))))
13231 (org-fast-tag-selection
13232 current-tags inherited-tags table
13233 (if org-fast-tag-selection-include-todo
13234 org-todo-key-alist))
13235 (let ((org-add-colon-after-tag-completion t))
13236 (org-trim
13237 (org-icompleting-read "Tags: "
13238 'org-tags-completion-function
13239 nil nil current 'org-tags-history))))))
13240 (while (string-match "[-+&]+" tags)
13241 ;; No boolean logic, just a list
13242 (setq tags (replace-match ":" t t tags))))
13244 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13246 (if org-tags-sort-function
13247 (setq tags (mapconcat 'identity
13248 (sort (org-split-string
13249 tags (org-re "[^[:alnum:]_@#%]+"))
13250 org-tags-sort-function) ":")))
13252 (if (string-match "\\`[\t ]*\\'" tags)
13253 (setq tags "")
13254 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13255 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13257 ;; Insert new tags at the correct column
13258 (beginning-of-line 1)
13259 (setq level (or (and (looking-at org-outline-regexp)
13260 (- (match-end 0) (point) 1))
13262 (cond
13263 ((and (equal current "") (equal tags "")))
13264 ((re-search-forward
13265 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13266 (point-at-eol) t)
13267 (if (equal tags "")
13268 (setq rpl "")
13269 (goto-char (match-beginning 0))
13270 (setq c0 (current-column)
13271 ;; compute offset for the case of org-indent-mode active
13272 di (if org-indent-mode
13273 (* (1- org-indent-indentation-per-level) (1- level))
13275 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13276 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13277 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13278 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13279 (replace-match rpl t t)
13280 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13281 tags)
13282 (t (error "Tags alignment failed")))
13283 (org-move-to-column col)
13284 (unless just-align
13285 (run-hooks 'org-after-tags-change-hook)))))
13287 (defun org-change-tag-in-region (beg end tag off)
13288 "Add or remove TAG for each entry in the region.
13289 This works in the agenda, and also in an org-mode buffer."
13290 (interactive
13291 (list (region-beginning) (region-end)
13292 (let ((org-last-tags-completion-table
13293 (if (org-mode-p)
13294 (org-get-buffer-tags)
13295 (org-global-tags-completion-table))))
13296 (org-icompleting-read
13297 "Tag: " 'org-tags-completion-function nil nil nil
13298 'org-tags-history))
13299 (progn
13300 (message "[s]et or [r]emove? ")
13301 (equal (read-char-exclusive) ?r))))
13302 (if (fboundp 'deactivate-mark) (deactivate-mark))
13303 (let ((agendap (equal major-mode 'org-agenda-mode))
13304 l1 l2 m buf pos newhead (cnt 0))
13305 (goto-char end)
13306 (setq l2 (1- (org-current-line)))
13307 (goto-char beg)
13308 (setq l1 (org-current-line))
13309 (loop for l from l1 to l2 do
13310 (org-goto-line l)
13311 (setq m (get-text-property (point) 'org-hd-marker))
13312 (when (or (and (org-mode-p) (org-on-heading-p))
13313 (and agendap m))
13314 (setq buf (if agendap (marker-buffer m) (current-buffer))
13315 pos (if agendap m (point)))
13316 (with-current-buffer buf
13317 (save-excursion
13318 (save-restriction
13319 (goto-char pos)
13320 (setq cnt (1+ cnt))
13321 (org-toggle-tag tag (if off 'off 'on))
13322 (setq newhead (org-get-heading)))))
13323 (and agendap (org-agenda-change-all-lines newhead m))))
13324 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13326 (defun org-tags-completion-function (string predicate &optional flag)
13327 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13328 (confirm (lambda (x) (stringp (car x)))))
13329 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13330 (setq s1 (match-string 1 string)
13331 s2 (match-string 2 string))
13332 (setq s1 "" s2 string))
13333 (cond
13334 ((eq flag nil)
13335 ;; try completion
13336 (setq rtn (try-completion s2 ctable confirm))
13337 (if (stringp rtn)
13338 (setq rtn
13339 (concat s1 s2 (substring rtn (length s2))
13340 (if (and org-add-colon-after-tag-completion
13341 (assoc rtn ctable))
13342 ":" ""))))
13343 rtn)
13344 ((eq flag t)
13345 ;; all-completions
13346 (all-completions s2 ctable confirm)
13348 ((eq flag 'lambda)
13349 ;; exact match?
13350 (assoc s2 ctable)))
13353 (defun org-fast-tag-insert (kwd tags face &optional end)
13354 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13355 (insert (format "%-12s" (concat kwd ":"))
13356 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13357 (or end "")))
13359 (defun org-fast-tag-show-exit (flag)
13360 (save-excursion
13361 (org-goto-line 3)
13362 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13363 (replace-match ""))
13364 (when flag
13365 (end-of-line 1)
13366 (org-move-to-column (- (window-width) 19) t)
13367 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13369 (defun org-set-current-tags-overlay (current prefix)
13370 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13371 (if (featurep 'xemacs)
13372 (org-overlay-display org-tags-overlay (concat prefix s)
13373 'secondary-selection)
13374 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13375 (org-overlay-display org-tags-overlay (concat prefix s)))))
13377 (defvar org-last-tag-selection-key nil)
13378 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13379 "Fast tag selection with single keys.
13380 CURRENT is the current list of tags in the headline, INHERITED is the
13381 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13382 possibly with grouping information. TODO-TABLE is a similar table with
13383 TODO keywords, should these have keys assigned to them.
13384 If the keys are nil, a-z are automatically assigned.
13385 Returns the new tags string, or nil to not change the current settings."
13386 (let* ((fulltable (append table todo-table))
13387 (maxlen (apply 'max (mapcar
13388 (lambda (x)
13389 (if (stringp (car x)) (string-width (car x)) 0))
13390 fulltable)))
13391 (buf (current-buffer))
13392 (expert (eq org-fast-tag-selection-single-key 'expert))
13393 (buffer-tags nil)
13394 (fwidth (+ maxlen 3 1 3))
13395 (ncol (/ (- (window-width) 4) fwidth))
13396 (i-face 'org-done)
13397 (c-face 'org-todo)
13398 tg cnt e c char c1 c2 ntable tbl rtn
13399 ov-start ov-end ov-prefix
13400 (exit-after-next org-fast-tag-selection-single-key)
13401 (done-keywords org-done-keywords)
13402 groups ingroup)
13403 (save-excursion
13404 (beginning-of-line 1)
13405 (if (looking-at
13406 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13407 (setq ov-start (match-beginning 1)
13408 ov-end (match-end 1)
13409 ov-prefix "")
13410 (setq ov-start (1- (point-at-eol))
13411 ov-end (1+ ov-start))
13412 (skip-chars-forward "^\n\r")
13413 (setq ov-prefix
13414 (concat
13415 (buffer-substring (1- (point)) (point))
13416 (if (> (current-column) org-tags-column)
13418 (make-string (- org-tags-column (current-column)) ?\ ))))))
13419 (move-overlay org-tags-overlay ov-start ov-end)
13420 (save-window-excursion
13421 (if expert
13422 (set-buffer (get-buffer-create " *Org tags*"))
13423 (delete-other-windows)
13424 (split-window-vertically)
13425 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13426 (erase-buffer)
13427 (org-set-local 'org-done-keywords done-keywords)
13428 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13429 (org-fast-tag-insert "Current" current c-face "\n\n")
13430 (org-fast-tag-show-exit exit-after-next)
13431 (org-set-current-tags-overlay current ov-prefix)
13432 (setq tbl fulltable char ?a cnt 0)
13433 (while (setq e (pop tbl))
13434 (cond
13435 ((equal (car e) :startgroup)
13436 (push '() groups) (setq ingroup t)
13437 (when (not (= cnt 0))
13438 (setq cnt 0)
13439 (insert "\n"))
13440 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13441 ((equal (car e) :endgroup)
13442 (setq ingroup nil cnt 0)
13443 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13444 ((equal e '(:newline))
13445 (when (not (= cnt 0))
13446 (setq cnt 0)
13447 (insert "\n")
13448 (setq e (car tbl))
13449 (while (equal (car tbl) '(:newline))
13450 (insert "\n")
13451 (setq tbl (cdr tbl)))))
13453 (setq tg (copy-sequence (car e)) c2 nil)
13454 (if (cdr e)
13455 (setq c (cdr e))
13456 ;; automatically assign a character.
13457 (setq c1 (string-to-char
13458 (downcase (substring
13459 tg (if (= (string-to-char tg) ?@) 1 0)))))
13460 (if (or (rassoc c1 ntable) (rassoc c1 table))
13461 (while (or (rassoc char ntable) (rassoc char table))
13462 (setq char (1+ char)))
13463 (setq c2 c1))
13464 (setq c (or c2 char)))
13465 (if ingroup (push tg (car groups)))
13466 (setq tg (org-add-props tg nil 'face
13467 (cond
13468 ((not (assoc tg table))
13469 (org-get-todo-face tg))
13470 ((member tg current) c-face)
13471 ((member tg inherited) i-face)
13472 (t nil))))
13473 (if (and (= cnt 0) (not ingroup)) (insert " "))
13474 (insert "[" c "] " tg (make-string
13475 (- fwidth 4 (length tg)) ?\ ))
13476 (push (cons tg c) ntable)
13477 (when (= (setq cnt (1+ cnt)) ncol)
13478 (insert "\n")
13479 (if ingroup (insert " "))
13480 (setq cnt 0)))))
13481 (setq ntable (nreverse ntable))
13482 (insert "\n")
13483 (goto-char (point-min))
13484 (if (not expert) (org-fit-window-to-buffer))
13485 (setq rtn
13486 (catch 'exit
13487 (while t
13488 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13489 (if (not groups) "no " "")
13490 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13491 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13492 (setq org-last-tag-selection-key c)
13493 (cond
13494 ((= c ?\r) (throw 'exit t))
13495 ((= c ?!)
13496 (setq groups (not groups))
13497 (goto-char (point-min))
13498 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13499 ((= c ?\C-c)
13500 (if (not expert)
13501 (org-fast-tag-show-exit
13502 (setq exit-after-next (not exit-after-next)))
13503 (setq expert nil)
13504 (delete-other-windows)
13505 (set-window-buffer (split-window-vertically) " *Org tags*")
13506 (org-switch-to-buffer-other-window " *Org tags*")
13507 (org-fit-window-to-buffer)))
13508 ((or (= c ?\C-g)
13509 (and (= c ?q) (not (rassoc c ntable))))
13510 (org-detach-overlay org-tags-overlay)
13511 (setq quit-flag t))
13512 ((= c ?\ )
13513 (setq current nil)
13514 (if exit-after-next (setq exit-after-next 'now)))
13515 ((= c ?\t)
13516 (condition-case nil
13517 (setq tg (org-icompleting-read
13518 "Tag: "
13519 (or buffer-tags
13520 (with-current-buffer buf
13521 (org-get-buffer-tags)))))
13522 (quit (setq tg "")))
13523 (when (string-match "\\S-" tg)
13524 (add-to-list 'buffer-tags (list tg))
13525 (if (member tg current)
13526 (setq current (delete tg current))
13527 (push tg current)))
13528 (if exit-after-next (setq exit-after-next 'now)))
13529 ((setq e (rassoc c todo-table) tg (car e))
13530 (with-current-buffer buf
13531 (save-excursion (org-todo tg)))
13532 (if exit-after-next (setq exit-after-next 'now)))
13533 ((setq e (rassoc c ntable) tg (car e))
13534 (if (member tg current)
13535 (setq current (delete tg current))
13536 (loop for g in groups do
13537 (if (member tg g)
13538 (mapc (lambda (x)
13539 (setq current (delete x current)))
13540 g)))
13541 (push tg current))
13542 (if exit-after-next (setq exit-after-next 'now))))
13544 ;; Create a sorted list
13545 (setq current
13546 (sort current
13547 (lambda (a b)
13548 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13549 (if (eq exit-after-next 'now) (throw 'exit t))
13550 (goto-char (point-min))
13551 (beginning-of-line 2)
13552 (delete-region (point) (point-at-eol))
13553 (org-fast-tag-insert "Current" current c-face)
13554 (org-set-current-tags-overlay current ov-prefix)
13555 (while (re-search-forward
13556 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13557 (setq tg (match-string 1))
13558 (add-text-properties
13559 (match-beginning 1) (match-end 1)
13560 (list 'face
13561 (cond
13562 ((member tg current) c-face)
13563 ((member tg inherited) i-face)
13564 (t (get-text-property (match-beginning 1) 'face))))))
13565 (goto-char (point-min)))))
13566 (org-detach-overlay org-tags-overlay)
13567 (if rtn
13568 (mapconcat 'identity current ":")
13569 nil))))
13571 (defun org-get-tags-string ()
13572 "Get the TAGS string in the current headline."
13573 (unless (org-on-heading-p t)
13574 (error "Not on a heading"))
13575 (save-excursion
13576 (beginning-of-line 1)
13577 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13578 (org-match-string-no-properties 1)
13579 "")))
13581 (defun org-get-tags ()
13582 "Get the list of tags specified in the current headline."
13583 (org-split-string (org-get-tags-string) ":"))
13585 (defun org-get-buffer-tags ()
13586 "Get a table of all tags used in the buffer, for completion."
13587 (let (tags)
13588 (save-excursion
13589 (goto-char (point-min))
13590 (while (re-search-forward
13591 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13592 (when (equal (char-after (point-at-bol 0)) ?*)
13593 (mapc (lambda (x) (add-to-list 'tags x))
13594 (org-split-string (org-match-string-no-properties 1) ":")))))
13595 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13596 (mapcar 'list tags)))
13598 ;;;; The mapping API
13600 ;;;###autoload
13601 (defun org-map-entries (func &optional match scope &rest skip)
13602 "Call FUNC at each headline selected by MATCH in SCOPE.
13604 FUNC is a function or a lisp form. The function will be called without
13605 arguments, with the cursor positioned at the beginning of the headline.
13606 The return values of all calls to the function will be collected and
13607 returned as a list.
13609 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13610 does not need to preserve point. After evaluation, the cursor will be
13611 moved to the end of the line (presumably of the headline of the
13612 processed entry) and search continues from there. Under some
13613 circumstances, this may not produce the wanted results. For example,
13614 if you have removed (e.g. archived) the current (sub)tree it could
13615 mean that the next entry will be skipped entirely. In such cases, you
13616 can specify the position from where search should continue by making
13617 FUNC set the variable `org-map-continue-from' to the desired buffer
13618 position.
13620 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13621 Only headlines that are matched by this query will be considered during
13622 the iteration. When MATCH is nil or t, all headlines will be
13623 visited by the iteration.
13625 SCOPE determines the scope of this command. It can be any of:
13627 nil The current buffer, respecting the restriction if any
13628 tree The subtree started with the entry at point
13629 region The entries within the active region, if any
13630 file The current buffer, without restriction
13631 file-with-archives
13632 The current buffer, and any archives associated with it
13633 agenda All agenda files
13634 agenda-with-archives
13635 All agenda files with any archive files associated with them
13636 \(file1 file2 ...)
13637 If this is a list, all files in the list will be scanned
13639 The remaining args are treated as settings for the skipping facilities of
13640 the scanner. The following items can be given here:
13642 archive skip trees with the archive tag.
13643 comment skip trees with the COMMENT keyword
13644 function or Emacs Lisp form:
13645 will be used as value for `org-agenda-skip-function', so whenever
13646 the function returns t, FUNC will not be called for that
13647 entry and search will continue from the point where the
13648 function leaves it.
13650 If your function needs to retrieve the tags including inherited tags
13651 at the *current* entry, you can use the value of the variable
13652 `org-scanner-tags' which will be much faster than getting the value
13653 with `org-get-tags-at'. If your function gets properties with
13654 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13655 to t around the call to `org-entry-properties' to get the same speedup.
13656 Note that if your function moves around to retrieve tags and properties at
13657 a *different* entry, you cannot use these techniques."
13658 (let* ((org-agenda-archives-mode nil) ; just to make sure
13659 (org-agenda-skip-archived-trees (memq 'archive skip))
13660 (org-agenda-skip-comment-trees (memq 'comment skip))
13661 (org-agenda-skip-function
13662 (car (org-delete-all '(comment archive) skip)))
13663 (org-tags-match-list-sublevels t)
13664 matcher file res
13665 org-todo-keywords-for-agenda
13666 org-done-keywords-for-agenda
13667 org-todo-keyword-alist-for-agenda
13668 org-drawers-for-agenda
13669 org-tag-alist-for-agenda)
13671 (cond
13672 ((eq match t) (setq matcher t))
13673 ((eq match nil) (setq matcher t))
13674 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13676 (save-excursion
13677 (save-restriction
13678 (cond ((eq scope 'tree)
13679 (org-back-to-heading t)
13680 (org-narrow-to-subtree)
13681 (setq scope nil))
13682 ((and (eq scope 'region) (org-region-active-p))
13683 (narrow-to-region (region-beginning) (region-end))
13684 (setq scope nil)))
13686 (if (not scope)
13687 (progn
13688 (org-prepare-agenda-buffers
13689 (list (buffer-file-name (current-buffer))))
13690 (setq res (org-scan-tags func matcher)))
13691 ;; Get the right scope
13692 (cond
13693 ((and scope (listp scope) (symbolp (car scope)))
13694 (setq scope (eval scope)))
13695 ((eq scope 'agenda)
13696 (setq scope (org-agenda-files t)))
13697 ((eq scope 'agenda-with-archives)
13698 (setq scope (org-agenda-files t))
13699 (setq scope (org-add-archive-files scope)))
13700 ((eq scope 'file)
13701 (setq scope (list (buffer-file-name))))
13702 ((eq scope 'file-with-archives)
13703 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13704 (org-prepare-agenda-buffers scope)
13705 (while (setq file (pop scope))
13706 (with-current-buffer (org-find-base-buffer-visiting file)
13707 (save-excursion
13708 (save-restriction
13709 (widen)
13710 (goto-char (point-min))
13711 (setq res (append res (org-scan-tags func matcher))))))))))
13712 res))
13714 ;;;; Properties
13716 ;;; Setting and retrieving properties
13718 (defconst org-special-properties
13719 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13720 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13721 "The special properties valid in Org-mode.
13723 These are properties that are not defined in the property drawer,
13724 but in some other way.")
13726 (defconst org-default-properties
13727 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13728 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13729 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13730 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13731 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13732 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13733 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13734 "Some properties that are used by Org-mode for various purposes.
13735 Being in this list makes sure that they are offered for completion.")
13737 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13738 "Regular expression matching the first line of a property drawer.")
13740 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13741 "Regular expression matching the last line of a property drawer.")
13743 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13744 "Regular expression matching the first line of a property drawer.")
13746 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13747 "Regular expression matching the first line of a property drawer.")
13749 (defconst org-property-drawer-re
13750 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13751 org-property-end-re "\\)\n?")
13752 "Matches an entire property drawer.")
13754 (defconst org-clock-drawer-re
13755 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13756 org-property-end-re "\\)\n?")
13757 "Matches an entire clock drawer.")
13759 (defsubst org-re-property (property)
13760 "Return a regexp matching PROPERTY.
13761 Match group 1 will be set to the value "
13762 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13764 (defun org-property-action ()
13765 "Do an action on properties."
13766 (interactive)
13767 (let (c)
13768 (org-at-property-p)
13769 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13770 (setq c (read-char-exclusive))
13771 (cond
13772 ((equal c ?s)
13773 (call-interactively 'org-set-property))
13774 ((equal c ?d)
13775 (call-interactively 'org-delete-property))
13776 ((equal c ?D)
13777 (call-interactively 'org-delete-property-globally))
13778 ((equal c ?c)
13779 (call-interactively 'org-compute-property-at-point))
13780 (t (error "No such property action %c" c)))))
13782 (defun org-set-effort (&optional value)
13783 "Set the effort property of the current entry.
13784 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13785 allowed value."
13786 (interactive "P")
13787 (if (equal value 0) (setq value 10))
13788 (let* ((completion-ignore-case t)
13789 (prop org-effort-property)
13790 (cur (org-entry-get nil prop))
13791 (allowed (org-property-get-allowed-values nil prop 'table))
13792 (existing (mapcar 'list (org-property-values prop)))
13794 (val (cond
13795 ((stringp value) value)
13796 ((and allowed (integerp value))
13797 (or (car (nth (1- value) allowed))
13798 (car (org-last allowed))))
13799 (allowed
13800 (message "Select 1-9,0, [RET%s]: %s"
13801 (if cur (concat "=" cur) "")
13802 (mapconcat 'car allowed " "))
13803 (setq rpl (read-char-exclusive))
13804 (if (equal rpl ?\r)
13806 (setq rpl (- rpl ?0))
13807 (if (equal rpl 0) (setq rpl 10))
13808 (if (and (> rpl 0) (<= rpl (length allowed)))
13809 (car (nth (1- rpl) allowed))
13810 (org-completing-read "Effort: " allowed nil))))
13812 (let (org-completion-use-ido org-completion-use-iswitchb)
13813 (org-completing-read
13814 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13815 (concat "[" cur "]") "")
13816 ": ")
13817 existing nil nil "" nil cur))))))
13818 (unless (equal (org-entry-get nil prop) val)
13819 (org-entry-put nil prop val))
13820 (message "%s is now %s" prop val)))
13822 (defun org-at-property-p ()
13823 "Is cursor inside a property drawer?"
13824 (save-excursion
13825 (beginning-of-line 1)
13826 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13827 (save-match-data ;; Used by calling procedures
13828 (let ((p (point))
13829 (range (unless (org-before-first-heading-p)
13830 (org-get-property-block))))
13831 (and range (<= (car range) p) (< p (cdr range))))))))
13833 (defun org-get-property-block (&optional beg end force)
13834 "Return the (beg . end) range of the body of the property drawer.
13835 BEG and END can be beginning and end of subtree, if not given
13836 they will be found.
13837 If the drawer does not exist and FORCE is non-nil, create the drawer."
13838 (catch 'exit
13839 (save-excursion
13840 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13841 (end (or end (progn (outline-next-heading) (point)))))
13842 (goto-char beg)
13843 (if (re-search-forward org-property-start-re end t)
13844 (setq beg (1+ (match-end 0)))
13845 (if force
13846 (save-excursion
13847 (org-insert-property-drawer)
13848 (setq end (progn (outline-next-heading) (point))))
13849 (throw 'exit nil))
13850 (goto-char beg)
13851 (if (re-search-forward org-property-start-re end t)
13852 (setq beg (1+ (match-end 0)))))
13853 (if (re-search-forward org-property-end-re end t)
13854 (setq end (match-beginning 0))
13855 (or force (throw 'exit nil))
13856 (goto-char beg)
13857 (setq end beg)
13858 (org-indent-line-function)
13859 (insert ":END:\n"))
13860 (cons beg end)))))
13862 (defun org-entry-properties (&optional pom which specific)
13863 "Get all properties of the entry at point-or-marker POM.
13864 This includes the TODO keyword, the tags, time strings for deadline,
13865 scheduled, and clocking, and any additional properties defined in the
13866 entry. The return value is an alist, keys may occur multiple times
13867 if the property key was used several times.
13868 POM may also be nil, in which case the current entry is used.
13869 If WHICH is nil or `all', get all properties. If WHICH is
13870 `special' or `standard', only get that subclass. If WHICH
13871 is a string only get exactly this property. SPECIFIC can be a string, the
13872 specific property we are interested in. Specifying it can speed
13873 things up because then unnecessary parsing is avoided."
13874 (setq which (or which 'all))
13875 (org-with-point-at pom
13876 (let ((clockstr (substring org-clock-string 0 -1))
13877 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13878 (case-fold-search nil)
13879 beg end range props sum-props key key1 value string clocksum)
13880 (save-excursion
13881 (when (condition-case nil
13882 (and (org-mode-p) (org-back-to-heading t))
13883 (error nil))
13884 (setq beg (point))
13885 (setq sum-props (get-text-property (point) 'org-summaries))
13886 (setq clocksum (get-text-property (point) :org-clock-minutes))
13887 (outline-next-heading)
13888 (setq end (point))
13889 (when (memq which '(all special))
13890 ;; Get the special properties, like TODO and tags
13891 (goto-char beg)
13892 (when (and (or (not specific) (string= specific "TODO"))
13893 (looking-at org-todo-line-regexp) (match-end 2))
13894 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13895 (when (and (or (not specific) (string= specific "PRIORITY"))
13896 (looking-at org-priority-regexp))
13897 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13898 (when (or (not specific) (string= specific "FILE"))
13899 (push (cons "FILE" buffer-file-name) props))
13900 (when (and (or (not specific) (string= specific "TAGS"))
13901 (setq value (org-get-tags-string))
13902 (string-match "\\S-" value))
13903 (push (cons "TAGS" value) props))
13904 (when (and (or (not specific) (string= specific "ALLTAGS"))
13905 (setq value (org-get-tags-at)))
13906 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13907 ":"))
13908 props))
13909 (when (or (not specific) (string= specific "BLOCKED"))
13910 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13911 (when (or (not specific)
13912 (member specific
13913 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13914 "TIMESTAMP" "TIMESTAMP_IA")))
13915 (catch 'match
13916 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13917 (setq key (if (match-end 1)
13918 (substring (org-match-string-no-properties 1)
13919 0 -1))
13920 string (if (equal key clockstr)
13921 (org-no-properties
13922 (org-trim
13923 (buffer-substring
13924 (match-beginning 3) (goto-char
13925 (point-at-eol)))))
13926 (substring (org-match-string-no-properties 3)
13927 1 -1)))
13928 ;; Get the correct property name from the key. This is
13929 ;; necessary if the user has configured time keywords.
13930 (setq key1 (concat key ":"))
13931 (cond
13932 ((not key)
13933 (setq key
13934 (if (= (char-after (match-beginning 3)) ?\[)
13935 "TIMESTAMP_IA" "TIMESTAMP")))
13936 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13937 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13938 ((equal key1 org-closed-string) (setq key "CLOSED"))
13939 ((equal key1 org-clock-string) (setq key "CLOCK")))
13940 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13941 (progn
13942 (push (cons key string) props)
13943 ;; no need to search further if match is found
13944 (throw 'match t))
13945 (when (or (equal key "CLOCK") (not (assoc key props)))
13946 (push (cons key string) props))))))
13949 (when (memq which '(all standard))
13950 ;; Get the standard properties, like :PROP: ...
13951 (setq range (org-get-property-block beg end))
13952 (when range
13953 (goto-char (car range))
13954 (while (re-search-forward
13955 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13956 (cdr range) t)
13957 (setq key (org-match-string-no-properties 1)
13958 value (org-trim (or (org-match-string-no-properties 2) "")))
13959 (unless (member key excluded)
13960 (push (cons key (or value "")) props)))))
13961 (if clocksum
13962 (push (cons "CLOCKSUM"
13963 (org-columns-number-to-string (/ (float clocksum) 60.)
13964 'add_times))
13965 props))
13966 (unless (assoc "CATEGORY" props)
13967 (push (cons "CATEGORY" (org-get-category)) props))
13968 (append sum-props (nreverse props)))))))
13970 (defun org-entry-get (pom property &optional inherit literal-nil)
13971 "Get value of PROPERTY for entry at point-or-marker POM.
13972 If INHERIT is non-nil and the entry does not have the property,
13973 then also check higher levels of the hierarchy.
13974 If INHERIT is the symbol `selective', use inheritance only if the setting
13975 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13976 If the property is present but empty, the return value is the empty string.
13977 If the property is not present at all, nil is returned.
13979 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13980 do not interpret it as the list atom nil. This is used for inheritance
13981 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13982 (org-with-point-at pom
13983 (if (and inherit (if (eq inherit 'selective)
13984 (org-property-inherit-p property)
13986 (org-entry-get-with-inheritance property literal-nil)
13987 (if (member property org-special-properties)
13988 ;; We need a special property. Use `org-entry-properties' to
13989 ;; retrieve it, but specify the wanted property
13990 (cdr (assoc property (org-entry-properties nil 'special property)))
13991 (let ((range (unless (org-before-first-heading-p)
13992 (org-get-property-block))))
13993 (if (and range
13994 (goto-char (car range))
13995 (re-search-forward
13996 (org-re-property property)
13997 (cdr range) t))
13998 ;; Found the property, return it.
13999 (if (match-end 1)
14000 (if literal-nil
14001 (org-match-string-no-properties 1)
14002 (org-not-nil (org-match-string-no-properties 1)))
14003 "")))))))
14005 (defun org-property-or-variable-value (var &optional inherit)
14006 "Check if there is a property fixing the value of VAR.
14007 If yes, return this value. If not, return the current value of the variable."
14008 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14009 (if (and prop (stringp prop) (string-match "\\S-" prop))
14010 (read prop)
14011 (symbol-value var))))
14013 (defun org-entry-delete (pom property)
14014 "Delete the property PROPERTY from entry at point-or-marker POM."
14015 (org-with-point-at pom
14016 (if (member property org-special-properties)
14017 nil ; cannot delete these properties.
14018 (let ((range (org-get-property-block)))
14019 (if (and range
14020 (goto-char (car range))
14021 (re-search-forward
14022 (org-re-property property)
14023 (cdr range) t))
14024 (progn
14025 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14027 nil)))))
14029 ;; Multi-values properties are properties that contain multiple values
14030 ;; These values are assumed to be single words, separated by whitespace.
14031 (defun org-entry-add-to-multivalued-property (pom property value)
14032 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14033 (let* ((old (org-entry-get pom property))
14034 (values (and old (org-split-string old "[ \t]"))))
14035 (setq value (org-entry-protect-space value))
14036 (unless (member value values)
14037 (setq values (cons value values))
14038 (org-entry-put pom property
14039 (mapconcat 'identity values " ")))))
14041 (defun org-entry-remove-from-multivalued-property (pom property value)
14042 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14043 (let* ((old (org-entry-get pom property))
14044 (values (and old (org-split-string old "[ \t]"))))
14045 (setq value (org-entry-protect-space value))
14046 (when (member value values)
14047 (setq values (delete value values))
14048 (org-entry-put pom property
14049 (mapconcat 'identity values " ")))))
14051 (defun org-entry-member-in-multivalued-property (pom property value)
14052 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14053 (let* ((old (org-entry-get pom property))
14054 (values (and old (org-split-string old "[ \t]"))))
14055 (setq value (org-entry-protect-space value))
14056 (member value values)))
14058 (defun org-entry-get-multivalued-property (pom property)
14059 "Return a list of values in a multivalued property."
14060 (let* ((value (org-entry-get pom property))
14061 (values (and value (org-split-string value "[ \t]"))))
14062 (mapcar 'org-entry-restore-space values)))
14064 (defun org-entry-put-multivalued-property (pom property &rest values)
14065 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14066 VALUES should be a list of strings. Spaces will be protected."
14067 (org-entry-put pom property
14068 (mapconcat 'org-entry-protect-space values " "))
14069 (let* ((value (org-entry-get pom property))
14070 (values (and value (org-split-string value "[ \t]"))))
14071 (mapcar 'org-entry-restore-space values)))
14073 (defun org-entry-protect-space (s)
14074 "Protect spaces and newline in string S."
14075 (while (string-match " " s)
14076 (setq s (replace-match "%20" t t s)))
14077 (while (string-match "\n" s)
14078 (setq s (replace-match "%0A" t t s)))
14081 (defun org-entry-restore-space (s)
14082 "Restore spaces and newline in string S."
14083 (while (string-match "%20" s)
14084 (setq s (replace-match " " t t s)))
14085 (while (string-match "%0A" s)
14086 (setq s (replace-match "\n" t t s)))
14089 (defvar org-entry-property-inherited-from (make-marker)
14090 "Marker pointing to the entry from where a property was inherited.
14091 Each call to `org-entry-get-with-inheritance' will set this marker to the
14092 location of the entry where the inheritance search matched. If there was
14093 no match, the marker will point nowhere.
14094 Note that also `org-entry-get' calls this function, if the INHERIT flag
14095 is set.")
14097 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14098 "Get entry property, and search higher levels if not present.
14099 The search will stop at the first ancestor which has the property defined.
14100 If the value found is \"nil\", return nil to show that the property
14101 should be considered as undefined (this is the meaning of nil here).
14102 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14103 (move-marker org-entry-property-inherited-from nil)
14104 (let (tmp)
14105 (unless (org-before-first-heading-p)
14106 (save-excursion
14107 (save-restriction
14108 (widen)
14109 (catch 'ex
14110 (while t
14111 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14112 (org-back-to-heading t)
14113 (move-marker org-entry-property-inherited-from (point))
14114 (throw 'ex tmp))
14115 (or (org-up-heading-safe) (throw 'ex nil)))))))
14116 (setq tmp (or tmp
14117 (cdr (assoc property org-file-properties))
14118 (cdr (assoc property org-global-properties))
14119 (cdr (assoc property org-global-properties-fixed))))
14120 (if literal-nil tmp (org-not-nil tmp))))
14122 (defvar org-property-changed-functions nil
14123 "Hook called when the value of a property has changed.
14124 Each hook function should accept two arguments, the name of the property
14125 and the new value.")
14127 (defun org-entry-put (pom property value)
14128 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14129 (org-with-point-at pom
14130 (org-back-to-heading t)
14131 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14132 range)
14133 (cond
14134 ((equal property "TODO")
14135 (when (and (stringp value) (string-match "\\S-" value)
14136 (not (member value org-todo-keywords-1)))
14137 (error "\"%s\" is not a valid TODO state" value))
14138 (if (or (not value)
14139 (not (string-match "\\S-" value)))
14140 (setq value 'none))
14141 (org-todo value)
14142 (org-set-tags nil 'align))
14143 ((equal property "PRIORITY")
14144 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14145 (string-to-char value) ?\ ))
14146 (org-set-tags nil 'align))
14147 ((equal property "SCHEDULED")
14148 (if (re-search-forward org-scheduled-time-regexp end t)
14149 (cond
14150 ((eq value 'earlier) (org-timestamp-change -1 'day))
14151 ((eq value 'later) (org-timestamp-change 1 'day))
14152 (t (call-interactively 'org-schedule)))
14153 (call-interactively 'org-schedule)))
14154 ((equal property "DEADLINE")
14155 (if (re-search-forward org-deadline-time-regexp end t)
14156 (cond
14157 ((eq value 'earlier) (org-timestamp-change -1 'day))
14158 ((eq value 'later) (org-timestamp-change 1 'day))
14159 (t (call-interactively 'org-deadline)))
14160 (call-interactively 'org-deadline)))
14161 ((member property org-special-properties)
14162 (error "The %s property can not yet be set with `org-entry-put'"
14163 property))
14164 (t ; a non-special property
14165 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14166 (setq range (org-get-property-block beg end 'force))
14167 (goto-char (car range))
14168 (if (re-search-forward
14169 (org-re-property property) (cdr range) t)
14170 (progn
14171 (delete-region (match-beginning 0) (match-end 0))
14172 (goto-char (match-beginning 0)))
14173 (goto-char (cdr range))
14174 (insert "\n")
14175 (backward-char 1)
14176 (org-indent-line-function))
14177 (insert ":" property ":")
14178 (and value (insert " " value))
14179 (org-indent-line-function)))))
14180 (run-hook-with-args 'org-property-changed-functions property value)))
14182 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14183 "Get all property keys in the current buffer.
14184 With INCLUDE-SPECIALS, also list the special properties that reflect things
14185 like tags and TODO state.
14186 With INCLUDE-DEFAULTS, also include properties that has special meaning
14187 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14188 and others.
14189 With INCLUDE-COLUMNS, also include property names given in COLUMN
14190 formats in the current buffer."
14191 (let (rtn range cfmt s p)
14192 (save-excursion
14193 (save-restriction
14194 (widen)
14195 (goto-char (point-min))
14196 (while (re-search-forward org-property-start-re nil t)
14197 (setq range (org-get-property-block))
14198 (goto-char (car range))
14199 (while (re-search-forward
14200 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14201 (cdr range) t)
14202 (add-to-list 'rtn (org-match-string-no-properties 1)))
14203 (outline-next-heading))))
14205 (when include-specials
14206 (setq rtn (append org-special-properties rtn)))
14208 (when include-defaults
14209 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14210 (add-to-list 'rtn org-effort-property))
14212 (when include-columns
14213 (save-excursion
14214 (save-restriction
14215 (widen)
14216 (goto-char (point-min))
14217 (while (re-search-forward
14218 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14219 nil t)
14220 (setq cfmt (match-string 2) s 0)
14221 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14222 cfmt s)
14223 (setq s (match-end 0)
14224 p (match-string 1 cfmt))
14225 (unless (or (equal p "ITEM")
14226 (member p org-special-properties))
14227 (add-to-list 'rtn (match-string 1 cfmt))))))))
14229 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14231 (defun org-property-values (key)
14232 "Return a list of all values of property KEY in the current buffer."
14233 (save-excursion
14234 (save-restriction
14235 (widen)
14236 (goto-char (point-min))
14237 (let ((re (org-re-property key))
14238 values)
14239 (while (re-search-forward re nil t)
14240 (add-to-list 'values (org-trim (match-string 1))))
14241 (delete "" values)))))
14243 (defun org-insert-property-drawer ()
14244 "Insert a property drawer into the current entry."
14245 (interactive)
14246 (org-back-to-heading t)
14247 (looking-at org-outline-regexp)
14248 (let ((indent (if org-adapt-indentation
14249 (- (match-end 0)(match-beginning 0))
14251 (beg (point))
14252 (re (concat "^[ \t]*" org-keyword-time-regexp))
14253 end hiddenp)
14254 (outline-next-heading)
14255 (setq end (point))
14256 (goto-char beg)
14257 (while (re-search-forward re end t))
14258 (setq hiddenp (outline-invisible-p))
14259 (end-of-line 1)
14260 (and (equal (char-after) ?\n) (forward-char 1))
14261 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14262 (if (member (match-string 1) '("CLOCK:" ":END:"))
14263 ;; just skip this line
14264 (beginning-of-line 2)
14265 ;; Drawer start, find the end
14266 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14267 (beginning-of-line 1)))
14268 (org-skip-over-state-notes)
14269 (skip-chars-backward " \t\n\r")
14270 (if (eq (char-before) ?*) (forward-char 1))
14271 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14272 (beginning-of-line 0)
14273 (org-indent-to-column indent)
14274 (beginning-of-line 2)
14275 (org-indent-to-column indent)
14276 (beginning-of-line 0)
14277 (if hiddenp
14278 (save-excursion
14279 (org-back-to-heading t)
14280 (hide-entry))
14281 (org-flag-drawer t))))
14283 (defvar org-property-set-functions-alist nil
14284 "Property set function alist.
14285 Each entry should have the following format:
14287 (PROPERTY . READ-FUNCTION)
14289 The read function will be called with the same argument as
14290 `org-completing-read'.")
14292 (defun org-set-property-function (property)
14293 "Get the function that should be used to set PROPERTY.
14294 This is computed according to `org-property-set-functions-alist'."
14295 (or (cdr (assoc property org-property-set-functions-alist))
14296 'org-completing-read))
14298 (defun org-read-property-value (property)
14299 "Read PROPERTY value from user."
14300 (let* ((completion-ignore-case t)
14301 (allowed (org-property-get-allowed-values nil property 'table))
14302 (cur (org-entry-get nil property))
14303 (prompt (concat property " value"
14304 (if (and cur (string-match "\\S-" cur))
14305 (concat " [" cur "]") "") ": "))
14306 (set-function (org-set-property-function property))
14307 (val (if allowed
14308 (funcall set-function prompt allowed nil
14309 (not (get-text-property 0 'org-unrestricted
14310 (caar allowed))))
14311 (let (org-completion-use-ido org-completion-use-iswitchb)
14312 (funcall set-function prompt
14313 (mapcar 'list (org-property-values property))
14314 nil nil "" nil cur)))))
14315 (if (equal val "")
14317 val)))
14319 (defvar org-last-set-property nil)
14320 (defun org-read-property-name ()
14321 "Read a property name."
14322 (let* ((completion-ignore-case t)
14323 (keys (org-buffer-property-keys nil t t))
14324 (default-prop (or (save-excursion
14325 (save-match-data
14326 (beginning-of-line)
14327 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14328 (null (string= (match-string 1) "END"))
14329 (match-string 1))))
14330 org-last-set-property))
14331 (property (org-icompleting-read
14332 (concat "Property"
14333 (if default-prop (concat " [" default-prop "]") "")
14334 ": ")
14335 (mapcar 'list keys)
14336 nil nil nil nil
14337 default-prop
14339 (if (member property keys)
14340 property
14341 (or (cdr (assoc (downcase property)
14342 (mapcar (lambda (x) (cons (downcase x) x))
14343 keys)))
14344 property))))
14346 (defun org-set-property (property value)
14347 "In the current entry, set PROPERTY to VALUE.
14348 When called interactively, this will prompt for a property name, offering
14349 completion on existing and default properties. And then it will prompt
14350 for a value, offering completion either on allowed values (via an inherited
14351 xxx_ALL property) or on existing values in other instances of this property
14352 in the current file."
14353 (interactive (list nil nil))
14354 (let* ((property (or property (org-read-property-name)))
14355 (value (or value (org-read-property-value property)))
14356 (fn (assoc property org-properties-postprocess-alist)))
14357 (setq org-last-set-property property)
14358 ;; Possibly postprocess the inserted value:
14359 (when fn (setq value (funcall (cadr fn) value)))
14360 (unless (equal (org-entry-get nil property) value)
14361 (org-entry-put nil property value))))
14363 (defun org-delete-property (property)
14364 "In the current entry, delete PROPERTY."
14365 (interactive
14366 (let* ((completion-ignore-case t)
14367 (prop (org-icompleting-read "Property: "
14368 (org-entry-properties nil 'standard))))
14369 (list prop)))
14370 (message "Property %s %s" property
14371 (if (org-entry-delete nil property)
14372 "deleted"
14373 "was not present in the entry")))
14375 (defun org-delete-property-globally (property)
14376 "Remove PROPERTY globally, from all entries."
14377 (interactive
14378 (let* ((completion-ignore-case t)
14379 (prop (org-icompleting-read
14380 "Globally remove property: "
14381 (mapcar 'list (org-buffer-property-keys)))))
14382 (list prop)))
14383 (save-excursion
14384 (save-restriction
14385 (widen)
14386 (goto-char (point-min))
14387 (let ((cnt 0))
14388 (while (re-search-forward
14389 (org-re-property property)
14390 nil t)
14391 (setq cnt (1+ cnt))
14392 (replace-match ""))
14393 (message "Property \"%s\" removed from %d entries" property cnt)))))
14395 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14397 (defun org-compute-property-at-point ()
14398 "Compute the property at point.
14399 This looks for an enclosing column format, extracts the operator and
14400 then applies it to the property in the column format's scope."
14401 (interactive)
14402 (unless (org-at-property-p)
14403 (error "Not at a property"))
14404 (let ((prop (org-match-string-no-properties 2)))
14405 (org-columns-get-format-and-top-level)
14406 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14407 (error "No operator defined for property %s" prop))
14408 (org-columns-compute prop)))
14410 (defvar org-property-allowed-value-functions nil
14411 "Hook for functions supplying allowed values for a specific property.
14412 The functions must take a single argument, the name of the property, and
14413 return a flat list of allowed values. If \":ETC\" is one of
14414 the values, this means that these values are intended as defaults for
14415 completion, but that other values should be allowed too.
14416 The functions must return nil if they are not responsible for this
14417 property.")
14419 (defun org-property-get-allowed-values (pom property &optional table)
14420 "Get allowed values for the property PROPERTY.
14421 When TABLE is non-nil, return an alist that can directly be used for
14422 completion."
14423 (let (vals)
14424 (cond
14425 ((equal property "TODO")
14426 (setq vals (org-with-point-at pom
14427 (append org-todo-keywords-1 '("")))))
14428 ((equal property "PRIORITY")
14429 (let ((n org-lowest-priority))
14430 (while (>= n org-highest-priority)
14431 (push (char-to-string n) vals)
14432 (setq n (1- n)))))
14433 ((member property org-special-properties))
14434 ((setq vals (run-hook-with-args-until-success
14435 'org-property-allowed-value-functions property)))
14437 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14438 (when (and vals (string-match "\\S-" vals))
14439 (setq vals (car (read-from-string (concat "(" vals ")"))))
14440 (setq vals (mapcar (lambda (x)
14441 (cond ((stringp x) x)
14442 ((numberp x) (number-to-string x))
14443 ((symbolp x) (symbol-name x))
14444 (t "???")))
14445 vals)))))
14446 (when (member ":ETC" vals)
14447 (setq vals (remove ":ETC" vals))
14448 (org-add-props (car vals) '(org-unrestricted t)))
14449 (if table (mapcar 'list vals) vals)))
14451 (defun org-property-previous-allowed-value (&optional previous)
14452 "Switch to the next allowed value for this property."
14453 (interactive)
14454 (org-property-next-allowed-value t))
14456 (defun org-property-next-allowed-value (&optional previous)
14457 "Switch to the next allowed value for this property."
14458 (interactive)
14459 (unless (org-at-property-p)
14460 (error "Not at a property"))
14461 (let* ((key (match-string 2))
14462 (value (match-string 3))
14463 (allowed (or (org-property-get-allowed-values (point) key)
14464 (and (member value '("[ ]" "[-]" "[X]"))
14465 '("[ ]" "[X]"))))
14466 nval)
14467 (unless allowed
14468 (error "Allowed values for this property have not been defined"))
14469 (if previous (setq allowed (reverse allowed)))
14470 (if (member value allowed)
14471 (setq nval (car (cdr (member value allowed)))))
14472 (setq nval (or nval (car allowed)))
14473 (if (equal nval value)
14474 (error "Only one allowed value for this property"))
14475 (org-at-property-p)
14476 (replace-match (concat " :" key ": " nval) t t)
14477 (org-indent-line-function)
14478 (beginning-of-line 1)
14479 (skip-chars-forward " \t")
14480 (run-hook-with-args 'org-property-changed-functions key nval)))
14482 (defun org-find-olp (path &optional this-buffer)
14483 "Return a marker pointing to the entry at outline path OLP.
14484 If anything goes wrong, throw an error.
14485 You can wrap this call to catch the error like this:
14487 (condition-case msg
14488 (org-mobile-locate-entry (match-string 4))
14489 (error (nth 1 msg)))
14491 The return value will then be either a string with the error message,
14492 or a marker if everything is OK.
14494 If THIS-BUFFER is set, the outline path does not contain a file,
14495 only headings."
14496 (let* ((file (if this-buffer buffer-file-name (pop path)))
14497 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14498 (level 1)
14499 (lmin 1)
14500 (lmax 1)
14501 limit re end found pos heading cnt flevel)
14502 (unless buffer (error "File not found :%s" file))
14503 (with-current-buffer buffer
14504 (save-excursion
14505 (save-restriction
14506 (widen)
14507 (setq limit (point-max))
14508 (goto-char (point-min))
14509 (while (setq heading (pop path))
14510 (setq re (format org-complex-heading-regexp-format
14511 (regexp-quote heading)))
14512 (setq cnt 0 pos (point))
14513 (while (re-search-forward re end t)
14514 (setq level (- (match-end 1) (match-beginning 1)))
14515 (if (and (>= level lmin) (<= level lmax))
14516 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14517 (when (= cnt 0) (error "Heading not found on level %d: %s"
14518 lmax heading))
14519 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14520 lmax heading))
14521 (goto-char found)
14522 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14523 (setq end (save-excursion (org-end-of-subtree t t))))
14524 (when (org-on-heading-p)
14525 (move-marker (make-marker) (point))))))))
14527 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14528 "Find node HEADING in BUFFER.
14529 Return a marker to the heading if it was found, or nil if not.
14530 If POS-ONLY is set, return just the position instead of a marker.
14532 The heading text must match exact, but it may have a TODO keyword,
14533 a priority cookie and tags in the standard locations."
14534 (with-current-buffer (or buffer (current-buffer))
14535 (save-excursion
14536 (save-restriction
14537 (widen)
14538 (goto-char (point-min))
14539 (let (case-fold-search)
14540 (if (re-search-forward
14541 (format org-complex-heading-regexp-format
14542 (regexp-quote heading)) nil t)
14543 (if pos-only
14544 (match-beginning 0)
14545 (move-marker (make-marker) (match-beginning 0)))))))))
14547 (defun org-find-exact-heading-in-directory (heading &optional dir)
14548 "Find Org node headline HEADING in all .org files in directory DIR.
14549 When the target headline is found, return a marker to this location."
14550 (let ((files (directory-files (or dir default-directory)
14551 nil "\\`[^.#].*\\.org\\'"))
14552 file visiting m buffer)
14553 (catch 'found
14554 (while (setq file (pop files))
14555 (message "trying %s" file)
14556 (setq visiting (org-find-base-buffer-visiting file))
14557 (setq buffer (or visiting (find-file-noselect file)))
14558 (setq m (org-find-exact-headline-in-buffer
14559 heading buffer))
14560 (when (and (not m) (not visiting)) (kill-buffer buffer))
14561 (and m (throw 'found m))))))
14563 (defun org-find-entry-with-id (ident)
14564 "Locate the entry that contains the ID property with exact value IDENT.
14565 IDENT can be a string, a symbol or a number, this function will search for
14566 the string representation of it.
14567 Return the position where this entry starts, or nil if there is no such entry."
14568 (interactive "sID: ")
14569 (let ((id (cond
14570 ((stringp ident) ident)
14571 ((symbol-name ident) (symbol-name ident))
14572 ((numberp ident) (number-to-string ident))
14573 (t (error "IDENT %s must be a string, symbol or number" ident))))
14574 (case-fold-search nil))
14575 (save-excursion
14576 (save-restriction
14577 (widen)
14578 (goto-char (point-min))
14579 (when (re-search-forward
14580 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14581 nil t)
14582 (org-back-to-heading t)
14583 (point))))))
14585 ;;;; Timestamps
14587 (defvar org-last-changed-timestamp nil)
14588 (defvar org-last-inserted-timestamp nil
14589 "The last time stamp inserted with `org-insert-time-stamp'.")
14590 (defvar org-time-was-given) ; dynamically scoped parameter
14591 (defvar org-end-time-was-given) ; dynamically scoped parameter
14592 (defvar org-ts-what) ; dynamically scoped parameter
14594 (defun org-time-stamp (arg &optional inactive)
14595 "Prompt for a date/time and insert a time stamp.
14596 If the user specifies a time like HH:MM, or if this command is called
14597 with a prefix argument, the time stamp will contain date and time.
14598 Otherwise, only the date will be included. All parts of a date not
14599 specified by the user will be filled in from the current date/time.
14600 So if you press just return without typing anything, the time stamp
14601 will represent the current date/time. If there is already a timestamp
14602 at the cursor, it will be modified."
14603 (interactive "P")
14604 (let* ((ts nil)
14605 (default-time
14606 ;; Default time is either today, or, when entering a range,
14607 ;; the range start.
14608 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14609 (save-excursion
14610 (re-search-backward
14611 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14612 (- (point) 20) t)))
14613 (apply 'encode-time (org-parse-time-string (match-string 1)))
14614 (current-time)))
14615 (default-input (and ts (org-get-compact-tod ts)))
14616 (repeater (save-excursion
14617 (save-match-data
14618 (beginning-of-line)
14619 (when (re-search-forward
14620 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14621 (save-excursion (progn (end-of-line) (point))) t)
14622 (match-string 0)))))
14623 org-time-was-given org-end-time-was-given time)
14624 (cond
14625 ((and (org-at-timestamp-p t)
14626 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14627 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14628 (insert "--")
14629 (setq time (let ((this-command this-command))
14630 (org-read-date arg 'totime nil nil
14631 default-time default-input)))
14632 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14633 ((org-at-timestamp-p t)
14634 (setq time (let ((this-command this-command))
14635 (org-read-date arg 'totime nil nil default-time default-input)))
14636 (when (org-at-timestamp-p t) ; just to get the match data
14637 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14638 (replace-match "")
14639 (setq org-last-changed-timestamp
14640 (org-insert-time-stamp
14641 time (or org-time-was-given arg)
14642 inactive nil nil (list org-end-time-was-given)))
14643 (when repeater (goto-char (1- (point))) (insert " " repeater)
14644 (setq org-last-changed-timestamp
14645 (concat (substring org-last-inserted-timestamp 0 -1)
14646 " " repeater ">"))))
14647 (message "Timestamp updated"))
14649 (setq time (let ((this-command this-command))
14650 (org-read-date arg 'totime nil nil default-time default-input)))
14651 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14652 nil nil (list org-end-time-was-given))))))
14654 ;; FIXME: can we use this for something else, like computing time differences?
14655 (defun org-get-compact-tod (s)
14656 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14657 (let* ((t1 (match-string 1 s))
14658 (h1 (string-to-number (match-string 2 s)))
14659 (m1 (string-to-number (match-string 3 s)))
14660 (t2 (and (match-end 4) (match-string 5 s)))
14661 (h2 (and t2 (string-to-number (match-string 6 s))))
14662 (m2 (and t2 (string-to-number (match-string 7 s))))
14663 dh dm)
14664 (if (not t2)
14666 (setq dh (- h2 h1) dm (- m2 m1))
14667 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14668 (concat t1 "+" (number-to-string dh)
14669 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14671 (defun org-time-stamp-inactive (&optional arg)
14672 "Insert an inactive time stamp.
14673 An inactive time stamp is enclosed in square brackets instead of angle
14674 brackets. It is inactive in the sense that it does not trigger agenda entries,
14675 does not link to the calendar and cannot be changed with the S-cursor keys.
14676 So these are more for recording a certain time/date."
14677 (interactive "P")
14678 (org-time-stamp arg 'inactive))
14680 (defvar org-date-ovl (make-overlay 1 1))
14681 (overlay-put org-date-ovl 'face 'org-warning)
14682 (org-detach-overlay org-date-ovl)
14684 (defvar org-ans1) ; dynamically scoped parameter
14685 (defvar org-ans2) ; dynamically scoped parameter
14687 (defvar org-plain-time-of-day-regexp) ; defined below
14689 (defvar org-overriding-default-time nil) ; dynamically scoped
14690 (defvar org-read-date-overlay nil)
14691 (defvar org-dcst nil) ; dynamically scoped
14692 (defvar org-read-date-history nil)
14693 (defvar org-read-date-final-answer nil)
14694 (defvar org-read-date-analyze-futurep nil)
14695 (defvar org-read-date-analyze-forced-year nil)
14697 (defun org-read-date (&optional with-time to-time from-string prompt
14698 default-time default-input)
14699 "Read a date, possibly a time, and make things smooth for the user.
14700 The prompt will suggest to enter an ISO date, but you can also enter anything
14701 which will at least partially be understood by `parse-time-string'.
14702 Unrecognized parts of the date will default to the current day, month, year,
14703 hour and minute. If this command is called to replace a timestamp at point,
14704 of to enter the second timestamp of a range, the default time is taken
14705 from the existing stamp. Furthermore, the command prefers the future,
14706 so if you are giving a date where the year is not given, and the day-month
14707 combination is already past in the current year, it will assume you
14708 mean next year. For details, see the manual. A few examples:
14710 3-2-5 --> 2003-02-05
14711 feb 15 --> currentyear-02-15
14712 2/15 --> currentyear-02-15
14713 sep 12 9 --> 2009-09-12
14714 12:45 --> today 12:45
14715 22 sept 0:34 --> currentyear-09-22 0:34
14716 12 --> currentyear-currentmonth-12
14717 Fri --> nearest Friday (today or later)
14718 etc.
14720 Furthermore you can specify a relative date by giving, as the *first* thing
14721 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14722 change in days weeks, months, years.
14723 With a single plus or minus, the date is relative to today. With a double
14724 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14725 +4d --> four days from today
14726 +4 --> same as above
14727 +2w --> two weeks from today
14728 ++5 --> five days from default date
14730 The function understands only English month and weekday abbreviations,
14731 but this can be configured with the variables `parse-time-months' and
14732 `parse-time-weekdays'.
14734 While prompting, a calendar is popped up - you can also select the
14735 date with the mouse (button 1). The calendar shows a period of three
14736 months. To scroll it to other months, use the keys `>' and `<'.
14737 If you don't like the calendar, turn it off with
14738 \(setq org-read-date-popup-calendar nil)
14740 With optional argument TO-TIME, the date will immediately be converted
14741 to an internal time.
14742 With an optional argument WITH-TIME, the prompt will suggest to also
14743 insert a time. Note that when WITH-TIME is not set, you can still
14744 enter a time, and this function will inform the calling routine about
14745 this change. The calling routine may then choose to change the format
14746 used to insert the time stamp into the buffer to include the time.
14747 With optional argument FROM-STRING, read from this string instead from
14748 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14749 the time/date that is used for everything that is not specified by the
14750 user."
14751 (require 'parse-time)
14752 (let* ((org-time-stamp-rounding-minutes
14753 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14754 (org-dcst org-display-custom-times)
14755 (ct (org-current-time))
14756 (def (or org-overriding-default-time default-time ct))
14757 (defdecode (decode-time def))
14758 (dummy (progn
14759 (when (< (nth 2 defdecode) org-extend-today-until)
14760 (setcar (nthcdr 2 defdecode) -1)
14761 (setcar (nthcdr 1 defdecode) 59)
14762 (setq def (apply 'encode-time defdecode)
14763 defdecode (decode-time def)))))
14764 (calendar-frame-setup nil)
14765 (calendar-setup nil)
14766 (calendar-move-hook nil)
14767 (calendar-view-diary-initially-flag nil)
14768 (calendar-view-holidays-initially-flag nil)
14769 (timestr (format-time-string
14770 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14771 (prompt (concat (if prompt (concat prompt " ") "")
14772 (format "Date+time [%s]: " timestr)))
14773 ans (org-ans0 "") org-ans1 org-ans2 final)
14775 (cond
14776 (from-string (setq ans from-string))
14777 (org-read-date-popup-calendar
14778 (save-excursion
14779 (save-window-excursion
14780 (calendar)
14781 (unwind-protect
14782 (progn
14783 (calendar-forward-day (- (time-to-days def)
14784 (calendar-absolute-from-gregorian
14785 (calendar-current-date))))
14786 (org-eval-in-calendar nil t)
14787 (let* ((old-map (current-local-map))
14788 (map (copy-keymap calendar-mode-map))
14789 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14790 (org-defkey map (kbd "RET") 'org-calendar-select)
14791 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14792 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14793 (org-defkey minibuffer-local-map [(meta shift left)]
14794 (lambda () (interactive)
14795 (org-eval-in-calendar '(calendar-backward-month 1))))
14796 (org-defkey minibuffer-local-map [(meta shift right)]
14797 (lambda () (interactive)
14798 (org-eval-in-calendar '(calendar-forward-month 1))))
14799 (org-defkey minibuffer-local-map [(meta shift up)]
14800 (lambda () (interactive)
14801 (org-eval-in-calendar '(calendar-backward-year 1))))
14802 (org-defkey minibuffer-local-map [(meta shift down)]
14803 (lambda () (interactive)
14804 (org-eval-in-calendar '(calendar-forward-year 1))))
14805 (org-defkey minibuffer-local-map [?\e (shift left)]
14806 (lambda () (interactive)
14807 (org-eval-in-calendar '(calendar-backward-month 1))))
14808 (org-defkey minibuffer-local-map [?\e (shift right)]
14809 (lambda () (interactive)
14810 (org-eval-in-calendar '(calendar-forward-month 1))))
14811 (org-defkey minibuffer-local-map [?\e (shift up)]
14812 (lambda () (interactive)
14813 (org-eval-in-calendar '(calendar-backward-year 1))))
14814 (org-defkey minibuffer-local-map [?\e (shift down)]
14815 (lambda () (interactive)
14816 (org-eval-in-calendar '(calendar-forward-year 1))))
14817 (org-defkey minibuffer-local-map [(shift up)]
14818 (lambda () (interactive)
14819 (org-eval-in-calendar '(calendar-backward-week 1))))
14820 (org-defkey minibuffer-local-map [(shift down)]
14821 (lambda () (interactive)
14822 (org-eval-in-calendar '(calendar-forward-week 1))))
14823 (org-defkey minibuffer-local-map [(shift left)]
14824 (lambda () (interactive)
14825 (org-eval-in-calendar '(calendar-backward-day 1))))
14826 (org-defkey minibuffer-local-map [(shift right)]
14827 (lambda () (interactive)
14828 (org-eval-in-calendar '(calendar-forward-day 1))))
14829 (org-defkey minibuffer-local-map ">"
14830 (lambda () (interactive)
14831 (org-eval-in-calendar '(scroll-calendar-left 1))))
14832 (org-defkey minibuffer-local-map "<"
14833 (lambda () (interactive)
14834 (org-eval-in-calendar '(scroll-calendar-right 1))))
14835 (org-defkey minibuffer-local-map "\C-v"
14836 (lambda () (interactive)
14837 (org-eval-in-calendar
14838 '(calendar-scroll-left-three-months 1))))
14839 (org-defkey minibuffer-local-map "\M-v"
14840 (lambda () (interactive)
14841 (org-eval-in-calendar
14842 '(calendar-scroll-right-three-months 1))))
14843 (run-hooks 'org-read-date-minibuffer-setup-hook)
14844 (unwind-protect
14845 (progn
14846 (use-local-map map)
14847 (add-hook 'post-command-hook 'org-read-date-display)
14848 (setq org-ans0 (read-string prompt default-input
14849 'org-read-date-history nil))
14850 ;; org-ans0: from prompt
14851 ;; org-ans1: from mouse click
14852 ;; org-ans2: from calendar motion
14853 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14854 (remove-hook 'post-command-hook 'org-read-date-display)
14855 (use-local-map old-map)
14856 (when org-read-date-overlay
14857 (delete-overlay org-read-date-overlay)
14858 (setq org-read-date-overlay nil)))))
14859 (bury-buffer "*Calendar*")))))
14861 (t ; Naked prompt only
14862 (unwind-protect
14863 (setq ans (read-string prompt default-input
14864 'org-read-date-history timestr))
14865 (when org-read-date-overlay
14866 (delete-overlay org-read-date-overlay)
14867 (setq org-read-date-overlay nil)))))
14869 (setq final (org-read-date-analyze ans def defdecode))
14871 (when org-read-date-analyze-forced-year
14872 (message "Year was forced into %s"
14873 (if org-read-date-force-compatible-dates
14874 "compatible range (1970-2037)"
14875 "range representable on this machine"))
14876 (ding))
14878 ;; One round trip to get rid of 34th of August and stuff like that....
14879 (setq final (decode-time (apply 'encode-time final)))
14881 (setq org-read-date-final-answer ans)
14883 (if to-time
14884 (apply 'encode-time final)
14885 (if (and (boundp 'org-time-was-given) org-time-was-given)
14886 (format "%04d-%02d-%02d %02d:%02d"
14887 (nth 5 final) (nth 4 final) (nth 3 final)
14888 (nth 2 final) (nth 1 final))
14889 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14891 (defvar def)
14892 (defvar defdecode)
14893 (defvar with-time)
14894 (defun org-read-date-display ()
14895 "Display the current date prompt interpretation in the minibuffer."
14896 (when org-read-date-display-live
14897 (when org-read-date-overlay
14898 (delete-overlay org-read-date-overlay))
14899 (let ((p (point)))
14900 (end-of-line 1)
14901 (while (not (equal (buffer-substring
14902 (max (point-min) (- (point) 4)) (point))
14903 " "))
14904 (insert " "))
14905 (goto-char p))
14906 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14907 " " (or org-ans1 org-ans2)))
14908 (org-end-time-was-given nil)
14909 (f (org-read-date-analyze ans def defdecode))
14910 (fmts (if org-dcst
14911 org-time-stamp-custom-formats
14912 org-time-stamp-formats))
14913 (fmt (if (or with-time
14914 (and (boundp 'org-time-was-given) org-time-was-given))
14915 (cdr fmts)
14916 (car fmts)))
14917 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14918 (when (and org-end-time-was-given
14919 (string-match org-plain-time-of-day-regexp txt))
14920 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14921 org-end-time-was-given
14922 (substring txt (match-end 0)))))
14923 (when org-read-date-analyze-futurep
14924 (setq txt (concat txt " (=>F)")))
14925 (setq org-read-date-overlay
14926 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14927 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14929 (defun org-read-date-analyze (ans def defdecode)
14930 "Analyze the combined answer of the date prompt."
14931 ;; FIXME: cleanup and comment
14932 (let ((nowdecode (decode-time (current-time)))
14933 delta deltan deltaw deltadef year month day
14934 hour minute second wday pm h2 m2 tl wday1
14935 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14936 (setq org-read-date-analyze-futurep nil
14937 org-read-date-analyze-forced-year nil)
14938 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14939 (setq ans "+0"))
14941 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14942 (setq ans (replace-match "" t t ans)
14943 deltan (car delta)
14944 deltaw (nth 1 delta)
14945 deltadef (nth 2 delta)))
14947 ;; Check if there is an iso week date in there
14948 ;; If yes, store the info and postpone interpreting it until the rest
14949 ;; of the parsing is done
14950 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14951 (setq iso-year (if (match-end 1)
14952 (org-small-year-to-year
14953 (string-to-number (match-string 1 ans))))
14954 iso-weekday (if (match-end 3)
14955 (string-to-number (match-string 3 ans)))
14956 iso-week (string-to-number (match-string 2 ans)))
14957 (setq ans (replace-match "" t t ans)))
14959 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14960 (when (string-match
14961 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14962 (setq year (if (match-end 2)
14963 (string-to-number (match-string 2 ans))
14964 (progn (setq kill-year t)
14965 (string-to-number (format-time-string "%Y"))))
14966 month (string-to-number (match-string 3 ans))
14967 day (string-to-number (match-string 4 ans)))
14968 (if (< year 100) (setq year (+ 2000 year)))
14969 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14970 t nil ans)))
14972 ;; Help matching dottet european dates
14973 (when (string-match
14974 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14975 (setq year (if (match-end 3)
14976 (string-to-number (match-string 3 ans))
14977 (progn (setq kill-year t)
14978 (string-to-number (format-time-string "%Y"))))
14979 day (string-to-number (match-string 1 ans))
14980 month (string-to-number (match-string 2 ans))
14981 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14982 t nil ans)))
14984 ;; Help matching american dates, like 5/30 or 5/30/7
14985 (when (string-match
14986 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14987 (setq year (if (match-end 4)
14988 (string-to-number (match-string 4 ans))
14989 (progn (setq kill-year t)
14990 (string-to-number (format-time-string "%Y"))))
14991 month (string-to-number (match-string 1 ans))
14992 day (string-to-number (match-string 2 ans)))
14993 (if (< year 100) (setq year (+ 2000 year)))
14994 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14995 t nil ans)))
14996 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14997 ;; If there is a time with am/pm, and *no* time without it, we convert
14998 ;; so that matching will be successful.
14999 (loop for i from 1 to 2 do ; twice, for end time as well
15000 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15001 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15002 (setq hour (string-to-number (match-string 1 ans))
15003 minute (if (match-end 3)
15004 (string-to-number (match-string 3 ans))
15006 pm (equal ?p
15007 (string-to-char (downcase (match-string 4 ans)))))
15008 (if (and (= hour 12) (not pm))
15009 (setq hour 0)
15010 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15011 (setq ans (replace-match (format "%02d:%02d" hour minute)
15012 t t ans))))
15014 ;; Check if a time range is given as a duration
15015 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15016 (setq hour (string-to-number (match-string 1 ans))
15017 h2 (+ hour (string-to-number (match-string 3 ans)))
15018 minute (string-to-number (match-string 2 ans))
15019 m2 (+ minute (if (match-end 5) (string-to-number
15020 (match-string 5 ans))0)))
15021 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15022 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15023 t t ans)))
15025 ;; Check if there is a time range
15026 (when (boundp 'org-end-time-was-given)
15027 (setq org-time-was-given nil)
15028 (when (and (string-match org-plain-time-of-day-regexp ans)
15029 (match-end 8))
15030 (setq org-end-time-was-given (match-string 8 ans))
15031 (setq ans (concat (substring ans 0 (match-beginning 7))
15032 (substring ans (match-end 7))))))
15034 (setq tl (parse-time-string ans)
15035 day (or (nth 3 tl) (nth 3 defdecode))
15036 month (or (nth 4 tl)
15037 (if (and org-read-date-prefer-future
15038 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15039 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15040 (nth 4 defdecode)))
15041 year (or (and (not kill-year) (nth 5 tl))
15042 (if (and org-read-date-prefer-future
15043 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15044 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15045 (nth 5 defdecode)))
15046 hour (or (nth 2 tl) (nth 2 defdecode))
15047 minute (or (nth 1 tl) (nth 1 defdecode))
15048 second (or (nth 0 tl) 0)
15049 wday (nth 6 tl))
15051 (when (and (eq org-read-date-prefer-future 'time)
15052 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15053 (equal day (nth 3 nowdecode))
15054 (equal month (nth 4 nowdecode))
15055 (equal year (nth 5 nowdecode))
15056 (nth 2 tl)
15057 (or (< (nth 2 tl) (nth 2 nowdecode))
15058 (and (= (nth 2 tl) (nth 2 nowdecode))
15059 (nth 1 tl)
15060 (< (nth 1 tl) (nth 1 nowdecode)))))
15061 (setq day (1+ day)
15062 futurep t))
15064 ;; Special date definitions below
15065 (cond
15066 (iso-week
15067 ;; There was an iso week
15068 (require 'cal-iso)
15069 (setq futurep nil)
15070 (setq year (or iso-year year)
15071 day (or iso-weekday wday 1)
15072 wday nil ; to make sure that the trigger below does not match
15073 iso-date (calendar-gregorian-from-absolute
15074 (calendar-absolute-from-iso
15075 (list iso-week day year))))
15076 ; FIXME: Should we also push ISO weeks into the future?
15077 ; (when (and org-read-date-prefer-future
15078 ; (not iso-year)
15079 ; (< (calendar-absolute-from-gregorian iso-date)
15080 ; (time-to-days (current-time))))
15081 ; (setq year (1+ year)
15082 ; iso-date (calendar-gregorian-from-absolute
15083 ; (calendar-absolute-from-iso
15084 ; (list iso-week day year)))))
15085 (setq month (car iso-date)
15086 year (nth 2 iso-date)
15087 day (nth 1 iso-date)))
15088 (deltan
15089 (setq futurep nil)
15090 (unless deltadef
15091 (let ((now (decode-time (current-time))))
15092 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15093 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15094 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15095 ((equal deltaw "m") (setq month (+ month deltan)))
15096 ((equal deltaw "y") (setq year (+ year deltan)))))
15097 ((and wday (not (nth 3 tl)))
15098 (setq futurep nil)
15099 ;; Weekday was given, but no day, so pick that day in the week
15100 ;; on or after the derived date.
15101 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15102 (unless (equal wday wday1)
15103 (setq day (+ day (% (- wday wday1 -7) 7))))))
15104 (if (and (boundp 'org-time-was-given)
15105 (nth 2 tl))
15106 (setq org-time-was-given t))
15107 (if (< year 100) (setq year (+ 2000 year)))
15108 ;; Check of the date is representable
15109 (if org-read-date-force-compatible-dates
15110 (progn
15111 (if (< year 1970)
15112 (setq year 1970 org-read-date-analyze-forced-year t))
15113 (if (> year 2037)
15114 (setq year 2037 org-read-date-analyze-forced-year t)))
15115 (condition-case nil
15116 (ignore (encode-time second minute hour day month year))
15117 (error
15118 (setq year (nth 5 defdecode))
15119 (setq org-read-date-analyze-forced-year t))))
15120 (setq org-read-date-analyze-futurep futurep)
15121 (list second minute hour day month year)))
15123 (defvar parse-time-weekdays)
15125 (defun org-read-date-get-relative (s today default)
15126 "Check string S for special relative date string.
15127 TODAY and DEFAULT are internal times, for today and for a default.
15128 Return shift list (N what def-flag)
15129 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15130 N is the number of WHATs to shift.
15131 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15132 the DEFAULT date rather than TODAY."
15133 (when (and
15134 (string-match
15135 (concat
15136 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15137 "\\([0-9]+\\)?"
15138 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15139 "\\([ \t]\\|$\\)") s)
15140 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15141 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15142 (string-to-char (substring (match-string 1 s) -1))
15143 ?+))
15144 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15145 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15146 (what (if (match-end 3) (match-string 3 s) "d"))
15147 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15148 (date (if rel default today))
15149 (wday (nth 6 (decode-time date)))
15150 delta)
15151 (if wday1
15152 (progn
15153 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15154 (if (= dir ?-) (setq delta (- delta 7)))
15155 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15156 (list delta "d" rel))
15157 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15159 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15160 "Turn a user-specified date into the internal representation.
15161 The internal representation needed by the calendar is (month day year).
15162 This is a wrapper to handle the brain-dead convention in calendar that
15163 user function argument order change dependent on argument order."
15164 (if (boundp 'calendar-date-style)
15165 (cond
15166 ((eq calendar-date-style 'american)
15167 (list arg1 arg2 arg3))
15168 ((eq calendar-date-style 'european)
15169 (list arg2 arg1 arg3))
15170 ((eq calendar-date-style 'iso)
15171 (list arg2 arg3 arg1)))
15172 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15173 (if (org-bound-and-true-p european-calendar-style)
15174 (list arg2 arg1 arg3)
15175 (list arg1 arg2 arg3)))))
15177 (defun org-eval-in-calendar (form &optional keepdate)
15178 "Eval FORM in the calendar window and return to current window.
15179 Also, store the cursor date in variable org-ans2."
15180 (let ((sf (selected-frame))
15181 (sw (selected-window)))
15182 (select-window (get-buffer-window "*Calendar*" t))
15183 (eval form)
15184 (when (and (not keepdate) (calendar-cursor-to-date))
15185 (let* ((date (calendar-cursor-to-date))
15186 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15187 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15188 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15189 (select-window sw)
15190 (org-select-frame-set-input-focus sf)))
15192 (defun org-calendar-select ()
15193 "Return to `org-read-date' with the date currently selected.
15194 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15195 (interactive)
15196 (when (calendar-cursor-to-date)
15197 (let* ((date (calendar-cursor-to-date))
15198 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15199 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15200 (if (active-minibuffer-window) (exit-minibuffer))))
15202 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15203 "Insert a date stamp for the date given by the internal TIME.
15204 WITH-HM means use the stamp format that includes the time of the day.
15205 INACTIVE means use square brackets instead of angular ones, so that the
15206 stamp will not contribute to the agenda.
15207 PRE and POST are optional strings to be inserted before and after the
15208 stamp.
15209 The command returns the inserted time stamp."
15210 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15211 stamp)
15212 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15213 (insert-before-markers (or pre ""))
15214 (when (listp extra)
15215 (setq extra (car extra))
15216 (if (and (stringp extra)
15217 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15218 (setq extra (format "-%02d:%02d"
15219 (string-to-number (match-string 1 extra))
15220 (string-to-number (match-string 2 extra))))
15221 (setq extra nil)))
15222 (when extra
15223 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15224 (insert-before-markers (setq stamp (format-time-string fmt time)))
15225 (insert-before-markers (or post ""))
15226 (setq org-last-inserted-timestamp stamp)))
15228 (defun org-toggle-time-stamp-overlays ()
15229 "Toggle the use of custom time stamp formats."
15230 (interactive)
15231 (setq org-display-custom-times (not org-display-custom-times))
15232 (unless org-display-custom-times
15233 (let ((p (point-min)) (bmp (buffer-modified-p)))
15234 (while (setq p (next-single-property-change p 'display))
15235 (if (and (get-text-property p 'display)
15236 (eq (get-text-property p 'face) 'org-date))
15237 (remove-text-properties
15238 p (setq p (next-single-property-change p 'display))
15239 '(display t))))
15240 (set-buffer-modified-p bmp)))
15241 (if (featurep 'xemacs)
15242 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15243 (org-restart-font-lock)
15244 (setq org-table-may-need-update t)
15245 (if org-display-custom-times
15246 (message "Time stamps are overlayed with custom format")
15247 (message "Time stamp overlays removed")))
15249 (defun org-display-custom-time (beg end)
15250 "Overlay modified time stamp format over timestamp between BEG and END."
15251 (let* ((ts (buffer-substring beg end))
15252 t1 w1 with-hm tf time str w2 (off 0))
15253 (save-match-data
15254 (setq t1 (org-parse-time-string ts t))
15255 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15256 (setq off (- (match-end 0) (match-beginning 0)))))
15257 (setq end (- end off))
15258 (setq w1 (- end beg)
15259 with-hm (and (nth 1 t1) (nth 2 t1))
15260 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15261 time (org-fix-decoded-time t1)
15262 str (org-add-props
15263 (format-time-string
15264 (substring tf 1 -1) (apply 'encode-time time))
15265 nil 'mouse-face 'highlight)
15266 w2 (length str))
15267 (if (not (= w2 w1))
15268 (add-text-properties (1+ beg) (+ 2 beg)
15269 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15270 (if (featurep 'xemacs)
15271 (progn
15272 (put-text-property beg end 'invisible t)
15273 (put-text-property beg end 'end-glyph (make-glyph str)))
15274 (put-text-property beg end 'display str))))
15276 (defun org-translate-time (string)
15277 "Translate all timestamps in STRING to custom format.
15278 But do this only if the variable `org-display-custom-times' is set."
15279 (when org-display-custom-times
15280 (save-match-data
15281 (let* ((start 0)
15282 (re org-ts-regexp-both)
15283 t1 with-hm inactive tf time str beg end)
15284 (while (setq start (string-match re string start))
15285 (setq beg (match-beginning 0)
15286 end (match-end 0)
15287 t1 (save-match-data
15288 (org-parse-time-string (substring string beg end) t))
15289 with-hm (and (nth 1 t1) (nth 2 t1))
15290 inactive (equal (substring string beg (1+ beg)) "[")
15291 tf (funcall (if with-hm 'cdr 'car)
15292 org-time-stamp-custom-formats)
15293 time (org-fix-decoded-time t1)
15294 str (format-time-string
15295 (concat
15296 (if inactive "[" "<") (substring tf 1 -1)
15297 (if inactive "]" ">"))
15298 (apply 'encode-time time))
15299 string (replace-match str t t string)
15300 start (+ start (length str)))))))
15301 string)
15303 (defun org-fix-decoded-time (time)
15304 "Set 0 instead of nil for the first 6 elements of time.
15305 Don't touch the rest."
15306 (let ((n 0))
15307 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15309 (defun org-days-to-time (timestamp-string)
15310 "Difference between TIMESTAMP-STRING and now in days."
15311 (- (time-to-days (org-time-string-to-time timestamp-string))
15312 (time-to-days (current-time))))
15314 (defun org-deadline-close (timestamp-string &optional ndays)
15315 "Is the time in TIMESTAMP-STRING close to the current date?"
15316 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15317 (and (< (org-days-to-time timestamp-string) ndays)
15318 (not (org-entry-is-done-p))))
15320 (defun org-get-wdays (ts)
15321 "Get the deadline lead time appropriate for timestring TS."
15322 (cond
15323 ((<= org-deadline-warning-days 0)
15324 ;; 0 or negative, enforce this value no matter what
15325 (- org-deadline-warning-days))
15326 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15327 ;; lead time is specified.
15328 (floor (* (string-to-number (match-string 1 ts))
15329 (cdr (assoc (match-string 2 ts)
15330 '(("d" . 1) ("w" . 7)
15331 ("m" . 30.4) ("y" . 365.25)))))))
15332 ;; go for the default.
15333 (t org-deadline-warning-days)))
15335 (defun org-calendar-select-mouse (ev)
15336 "Return to `org-read-date' with the date currently selected.
15337 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15338 (interactive "e")
15339 (mouse-set-point ev)
15340 (when (calendar-cursor-to-date)
15341 (let* ((date (calendar-cursor-to-date))
15342 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15343 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15344 (if (active-minibuffer-window) (exit-minibuffer))))
15346 (defun org-check-deadlines (ndays)
15347 "Check if there are any deadlines due or past due.
15348 A deadline is considered due if it happens within `org-deadline-warning-days'
15349 days from today's date. If the deadline appears in an entry marked DONE,
15350 it is not shown. The prefix arg NDAYS can be used to test that many
15351 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15352 (interactive "P")
15353 (let* ((org-warn-days
15354 (cond
15355 ((equal ndays '(4)) 100000)
15356 (ndays (prefix-numeric-value ndays))
15357 (t (abs org-deadline-warning-days))))
15358 (case-fold-search nil)
15359 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15360 (callback
15361 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15363 (message "%d deadlines past-due or due within %d days"
15364 (org-occur regexp nil callback)
15365 org-warn-days)))
15367 (defun org-check-before-date (date)
15368 "Check if there are deadlines or scheduled entries before DATE."
15369 (interactive (list (org-read-date)))
15370 (let ((case-fold-search nil)
15371 (regexp (concat "\\<\\(" org-deadline-string
15372 "\\|" org-scheduled-string
15373 "\\) *<\\([^>]+\\)>"))
15374 (callback
15375 (lambda () (time-less-p
15376 (org-time-string-to-time (match-string 2))
15377 (org-time-string-to-time date)))))
15378 (message "%d entries before %s"
15379 (org-occur regexp nil callback) date)))
15381 (defun org-check-after-date (date)
15382 "Check if there are deadlines or scheduled entries after DATE."
15383 (interactive (list (org-read-date)))
15384 (let ((case-fold-search nil)
15385 (regexp (concat "\\<\\(" org-deadline-string
15386 "\\|" org-scheduled-string
15387 "\\) *<\\([^>]+\\)>"))
15388 (callback
15389 (lambda () (not
15390 (time-less-p
15391 (org-time-string-to-time (match-string 2))
15392 (org-time-string-to-time date))))))
15393 (message "%d entries after %s"
15394 (org-occur regexp nil callback) date)))
15396 (defun org-evaluate-time-range (&optional to-buffer)
15397 "Evaluate a time range by computing the difference between start and end.
15398 Normally the result is just printed in the echo area, but with prefix arg
15399 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15400 If the time range is actually in a table, the result is inserted into the
15401 next column.
15402 For time difference computation, a year is assumed to be exactly 365
15403 days in order to avoid rounding problems."
15404 (interactive "P")
15406 (org-clock-update-time-maybe)
15407 (save-excursion
15408 (unless (org-at-date-range-p t)
15409 (goto-char (point-at-bol))
15410 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15411 (if (not (org-at-date-range-p t))
15412 (error "Not at a time-stamp range, and none found in current line")))
15413 (let* ((ts1 (match-string 1))
15414 (ts2 (match-string 2))
15415 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15416 (match-end (match-end 0))
15417 (time1 (org-time-string-to-time ts1))
15418 (time2 (org-time-string-to-time ts2))
15419 (t1 (org-float-time time1))
15420 (t2 (org-float-time time2))
15421 (diff (abs (- t2 t1)))
15422 (negative (< (- t2 t1) 0))
15423 ;; (ys (floor (* 365 24 60 60)))
15424 (ds (* 24 60 60))
15425 (hs (* 60 60))
15426 (fy "%dy %dd %02d:%02d")
15427 (fy1 "%dy %dd")
15428 (fd "%dd %02d:%02d")
15429 (fd1 "%dd")
15430 (fh "%02d:%02d")
15431 y d h m align)
15432 (if havetime
15433 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15435 d (floor (/ diff ds)) diff (mod diff ds)
15436 h (floor (/ diff hs)) diff (mod diff hs)
15437 m (floor (/ diff 60)))
15438 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15440 d (floor (+ (/ diff ds) 0.5))
15441 h 0 m 0))
15442 (if (not to-buffer)
15443 (message "%s" (org-make-tdiff-string y d h m))
15444 (if (org-at-table-p)
15445 (progn
15446 (goto-char match-end)
15447 (setq align t)
15448 (and (looking-at " *|") (goto-char (match-end 0))))
15449 (goto-char match-end))
15450 (if (looking-at
15451 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15452 (replace-match ""))
15453 (if negative (insert " -"))
15454 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15455 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15456 (insert " " (format fh h m))))
15457 (if align (org-table-align))
15458 (message "Time difference inserted")))))
15460 (defun org-make-tdiff-string (y d h m)
15461 (let ((fmt "")
15462 (l nil))
15463 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15464 l (push y l)))
15465 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15466 l (push d l)))
15467 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15468 l (push h l)))
15469 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15470 l (push m l)))
15471 (apply 'format fmt (nreverse l))))
15473 (defun org-time-string-to-time (s &optional buffer pos)
15474 (condition-case errdata
15475 (apply 'encode-time (org-parse-time-string s))
15476 (error (error "Bad timestamp `%s'%s\nError was: %s"
15477 s (if (not (and buffer pos))
15479 (format " at %d in buffer `%s'" pos buffer))
15480 (cdr errdata)))))
15482 (defun org-time-string-to-seconds (s)
15483 (org-float-time (org-time-string-to-time s)))
15485 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15486 "Convert a time stamp to an absolute day number.
15487 If there is a specifier for a cyclic time stamp, get the closest date to
15488 DAYNR.
15489 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15490 The variable date is bound by the calendar when this is called."
15491 (cond
15492 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15493 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15494 daynr
15495 (+ daynr 1000)))
15496 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15497 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15498 (time-to-days (current-time))) (match-string 0 s)
15499 prefer show-all))
15500 (t (time-to-days
15501 (condition-case errdata
15502 (apply 'encode-time (org-parse-time-string s))
15503 (error (error "Bad timestamp `%s'%s\nError was: %s"
15504 s (if (not (and buffer pos))
15506 (format " at %d in buffer `%s'" pos buffer))
15507 (cdr errdata))))))))
15509 (defun org-days-to-iso-week (days)
15510 "Return the iso week number."
15511 (require 'cal-iso)
15512 (car (calendar-iso-from-absolute days)))
15514 (defun org-small-year-to-year (year)
15515 "Convert 2-digit years into 4-digit years.
15516 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15517 The year 2000 cannot be abbreviated. Any year larger than 99
15518 is returned unchanged."
15519 (if (< year 38)
15520 (setq year (+ 2000 year))
15521 (if (< year 100)
15522 (setq year (+ 1900 year))))
15523 year)
15525 (defun org-time-from-absolute (d)
15526 "Return the time corresponding to date D.
15527 D may be an absolute day number, or a calendar-type list (month day year)."
15528 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15529 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15531 (defun org-calendar-holiday ()
15532 "List of holidays, for Diary display in Org-mode."
15533 (require 'holidays)
15534 (let ((hl (funcall
15535 (if (fboundp 'calendar-check-holidays)
15536 'calendar-check-holidays 'check-calendar-holidays) date)))
15537 (if hl (mapconcat 'identity hl "; "))))
15539 (defun org-diary-sexp-entry (sexp entry date)
15540 "Process a SEXP diary ENTRY for DATE."
15541 (require 'diary-lib)
15542 (let ((result (if calendar-debug-sexp
15543 (let ((stack-trace-on-error t))
15544 (eval (car (read-from-string sexp))))
15545 (condition-case nil
15546 (eval (car (read-from-string sexp)))
15547 (error
15548 (beep)
15549 (message "Bad sexp at line %d in %s: %s"
15550 (org-current-line)
15551 (buffer-file-name) sexp)
15552 (sleep-for 2))))))
15553 (cond ((stringp result) (split-string result "; "))
15554 ((and (consp result)
15555 (not (consp (cdr result)))
15556 (stringp (cdr result))) (cdr result))
15557 ((and (consp result)
15558 (stringp (car result))) result)
15559 (result entry)
15560 (t nil))))
15562 (defun org-diary-to-ical-string (frombuf)
15563 "Get iCalendar entries from diary entries in buffer FROMBUF.
15564 This uses the icalendar.el library."
15565 (let* ((tmpdir (if (featurep 'xemacs)
15566 (temp-directory)
15567 temporary-file-directory))
15568 (tmpfile (make-temp-name
15569 (expand-file-name "orgics" tmpdir)))
15570 buf rtn b e)
15571 (with-current-buffer frombuf
15572 (icalendar-export-region (point-min) (point-max) tmpfile)
15573 (setq buf (find-buffer-visiting tmpfile))
15574 (set-buffer buf)
15575 (goto-char (point-min))
15576 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15577 (setq b (match-beginning 0)))
15578 (goto-char (point-max))
15579 (if (re-search-backward "^END:VEVENT" nil t)
15580 (setq e (match-end 0)))
15581 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15582 (kill-buffer buf)
15583 (delete-file tmpfile)
15584 rtn))
15586 (defun org-closest-date (start current change prefer show-all)
15587 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15588 When PREFER is `past', return a date that is either CURRENT or past.
15589 When PREFER is `future', return a date that is either CURRENT or future.
15590 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15591 ;; Make the proper lists from the dates
15592 (catch 'exit
15593 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15594 dn dw sday cday n1 n2 n0
15595 d m y y1 y2 date1 date2 nmonths nm ny m2)
15597 (setq start (org-date-to-gregorian start)
15598 current (org-date-to-gregorian
15599 (if show-all
15600 current
15601 (time-to-days (current-time))))
15602 sday (calendar-absolute-from-gregorian start)
15603 cday (calendar-absolute-from-gregorian current))
15605 (if (<= cday sday) (throw 'exit sday))
15607 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15608 (setq dn (string-to-number (match-string 1 change))
15609 dw (cdr (assoc (match-string 2 change) a1)))
15610 (error "Invalid change specifier: %s" change))
15611 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15612 (cond
15613 ((eq dw 'day)
15614 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15615 n2 (+ n1 dn)))
15616 ((eq dw 'year)
15617 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15618 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15619 (setq date1 (list m d y1)
15620 n1 (calendar-absolute-from-gregorian date1)
15621 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15622 n2 (calendar-absolute-from-gregorian date2)))
15623 ((eq dw 'month)
15624 ;; approx number of month between the two dates
15625 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15626 ;; How often does dn fit in there?
15627 (setq d (nth 1 start) m (car start) y (nth 2 start)
15628 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15629 m (+ m nm)
15630 ny (floor (/ m 12))
15631 y (+ y ny)
15632 m (- m (* ny 12)))
15633 (while (> m 12) (setq m (- m 12) y (1+ y)))
15634 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15635 (setq m2 (+ m dn) y2 y)
15636 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15637 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15638 (while (<= n2 cday)
15639 (setq n1 n2 m m2 y y2)
15640 (setq m2 (+ m dn) y2 y)
15641 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15642 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15643 ;; Make sure n1 is the earlier date
15644 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15645 (if show-all
15646 (cond
15647 ((eq prefer 'past) (if (= cday n2) n2 n1))
15648 ((eq prefer 'future) (if (= cday n1) n1 n2))
15649 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15650 (cond
15651 ((eq prefer 'past) (if (= cday n2) n2 n1))
15652 ((eq prefer 'future) (if (= cday n1) n1 n2))
15653 (t (if (= cday n1) n1 n2)))))))
15655 (defun org-date-to-gregorian (date)
15656 "Turn any specification of DATE into a Gregorian date for the calendar."
15657 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15658 ((and (listp date) (= (length date) 3)) date)
15659 ((stringp date)
15660 (setq date (org-parse-time-string date))
15661 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15662 ((listp date)
15663 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15665 (defun org-parse-time-string (s &optional nodefault)
15666 "Parse the standard Org-mode time string.
15667 This should be a lot faster than the normal `parse-time-string'.
15668 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15669 hour and minute fields will be nil if not given."
15670 (if (string-match org-ts-regexp0 s)
15671 (list 0
15672 (if (or (match-beginning 8) (not nodefault))
15673 (string-to-number (or (match-string 8 s) "0")))
15674 (if (or (match-beginning 7) (not nodefault))
15675 (string-to-number (or (match-string 7 s) "0")))
15676 (string-to-number (match-string 4 s))
15677 (string-to-number (match-string 3 s))
15678 (string-to-number (match-string 2 s))
15679 nil nil nil)
15680 (error "Not a standard Org-mode time string: %s" s)))
15682 (defun org-timestamp-up (&optional arg)
15683 "Increase the date item at the cursor by one.
15684 If the cursor is on the year, change the year. If it is on the month,
15685 the day or the time, change that.
15686 With prefix ARG, change by that many units."
15687 (interactive "p")
15688 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15690 (defun org-timestamp-down (&optional arg)
15691 "Decrease the date item at the cursor by one.
15692 If the cursor is on the year, change the year. If it is on the month,
15693 the day or the time, change that.
15694 With prefix ARG, change by that many units."
15695 (interactive "p")
15696 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15698 (defun org-timestamp-up-day (&optional arg)
15699 "Increase the date in the time stamp by one day.
15700 With prefix ARG, change that many days."
15701 (interactive "p")
15702 (if (and (not (org-at-timestamp-p t))
15703 (org-on-heading-p))
15704 (org-todo 'up)
15705 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15707 (defun org-timestamp-down-day (&optional arg)
15708 "Decrease the date in the time stamp by one day.
15709 With prefix ARG, change that many days."
15710 (interactive "p")
15711 (if (and (not (org-at-timestamp-p t))
15712 (org-on-heading-p))
15713 (org-todo 'down)
15714 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15716 (defun org-at-timestamp-p (&optional inactive-ok)
15717 "Determine if the cursor is in or at a timestamp."
15718 (interactive)
15719 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15720 (pos (point))
15721 (ans (or (looking-at tsr)
15722 (save-excursion
15723 (skip-chars-backward "^[<\n\r\t")
15724 (if (> (point) (point-min)) (backward-char 1))
15725 (and (looking-at tsr)
15726 (> (- (match-end 0) pos) -1))))))
15727 (and ans
15728 (boundp 'org-ts-what)
15729 (setq org-ts-what
15730 (cond
15731 ((= pos (match-beginning 0)) 'bracket)
15732 ;; Point is considered to be "on the bracket" whether
15733 ;; it's really on it or right after it.
15734 ((or (= pos (1- (match-end 0)))
15735 (= pos (match-end 0))) 'bracket)
15736 ((org-pos-in-match-range pos 2) 'year)
15737 ((org-pos-in-match-range pos 3) 'month)
15738 ((org-pos-in-match-range pos 7) 'hour)
15739 ((org-pos-in-match-range pos 8) 'minute)
15740 ((or (org-pos-in-match-range pos 4)
15741 (org-pos-in-match-range pos 5)) 'day)
15742 ((and (> pos (or (match-end 8) (match-end 5)))
15743 (< pos (match-end 0)))
15744 (- pos (or (match-end 8) (match-end 5))))
15745 (t 'day))))
15746 ans))
15748 (defun org-toggle-timestamp-type ()
15749 "Toggle the type (<active> or [inactive]) of a time stamp."
15750 (interactive)
15751 (when (org-at-timestamp-p t)
15752 (let ((beg (match-beginning 0)) (end (match-end 0))
15753 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15754 (save-excursion
15755 (goto-char beg)
15756 (while (re-search-forward "[][<>]" end t)
15757 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15758 t t)))
15759 (message "Timestamp is now %sactive"
15760 (if (equal (char-after beg) ?<) "" "in")))))
15762 (defun org-timestamp-change (n &optional what updown)
15763 "Change the date in the time stamp at point.
15764 The date will be changed by N times WHAT. WHAT can be `day', `month',
15765 `year', `minute', `second'. If WHAT is not given, the cursor position
15766 in the timestamp determines what will be changed."
15767 (let ((origin (point)) origin-cat
15768 with-hm inactive
15769 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15770 org-ts-what
15771 extra rem
15772 ts time time0)
15773 (if (not (org-at-timestamp-p t))
15774 (error "Not at a timestamp"))
15775 (if (and (not what) (eq org-ts-what 'bracket))
15776 (org-toggle-timestamp-type)
15777 ;; Point isn't on brackets. Remember the part of the time-stamp
15778 ;; the point was in. Indeed, size of time-stamps may change,
15779 ;; but point must be kept in the same category nonetheless.
15780 (setq origin-cat org-ts-what)
15781 (if (and (not what) (not (eq org-ts-what 'day))
15782 org-display-custom-times
15783 (get-text-property (point) 'display)
15784 (not (get-text-property (1- (point)) 'display)))
15785 (setq org-ts-what 'day))
15786 (setq org-ts-what (or what org-ts-what)
15787 inactive (= (char-after (match-beginning 0)) ?\[)
15788 ts (match-string 0))
15789 (replace-match "")
15790 (if (string-match
15791 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15793 (setq extra (match-string 1 ts)))
15794 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15795 (setq with-hm t))
15796 (setq time0 (org-parse-time-string ts))
15797 (when (and updown
15798 (eq org-ts-what 'minute)
15799 (not current-prefix-arg))
15800 ;; This looks like s-up and s-down. Change by one rounding step.
15801 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15802 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15803 (setcar (cdr time0) (+ (nth 1 time0)
15804 (if (> n 0) (- rem) (- dm rem))))))
15805 (setq time
15806 (encode-time (or (car time0) 0)
15807 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15808 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15809 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15810 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15811 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15812 (nthcdr 6 time0)))
15813 (when (and (member org-ts-what '(hour minute))
15814 extra
15815 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15816 (setq extra (org-modify-ts-extra
15817 extra
15818 (if (eq org-ts-what 'hour) 2 5)
15819 n dm)))
15820 (when (integerp org-ts-what)
15821 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15822 (if (eq what 'calendar)
15823 (let ((cal-date (org-get-date-from-calendar)))
15824 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15825 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15826 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15827 (setcar time0 (or (car time0) 0))
15828 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15829 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15830 (setq time (apply 'encode-time time0))))
15831 ;; Insert the new time-stamp, and ensure point stays in the same
15832 ;; category as before (i.e. not after the last position in that
15833 ;; category).
15834 (let ((pos (point)))
15835 ;; Stay before inserted string. `save-excursion' is of no use.
15836 (setq org-last-changed-timestamp
15837 (org-insert-time-stamp time with-hm inactive nil nil extra))
15838 (goto-char pos))
15839 (save-match-data
15840 (looking-at org-ts-regexp3)
15841 (goto-char (cond
15842 ;; `day' category ends before `hour' if any, or at
15843 ;; the end of the day name.
15844 ((eq origin-cat 'day)
15845 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15846 ((eq origin-cat 'hour) (min (match-end 7) origin))
15847 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15848 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15849 ;; `year' and `month' have both fixed size: point
15850 ;; couldn't have moved into another part.
15851 (t origin))))
15852 ;; Update clock if on a CLOCK line.
15853 (org-clock-update-time-maybe)
15854 ;; Try to recenter the calendar window, if any.
15855 (if (and org-calendar-follow-timestamp-change
15856 (get-buffer-window "*Calendar*" t)
15857 (memq org-ts-what '(day month year)))
15858 (org-recenter-calendar (time-to-days time))))))
15860 (defun org-modify-ts-extra (s pos n dm)
15861 "Change the different parts of the lead-time and repeat fields in timestamp."
15862 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15863 ng h m new rem)
15864 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15865 (cond
15866 ((or (org-pos-in-match-range pos 2)
15867 (org-pos-in-match-range pos 3))
15868 (setq m (string-to-number (match-string 3 s))
15869 h (string-to-number (match-string 2 s)))
15870 (if (org-pos-in-match-range pos 2)
15871 (setq h (+ h n))
15872 (setq n (* dm (org-no-warnings (signum n))))
15873 (when (not (= 0 (setq rem (% m dm))))
15874 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15875 (setq m (+ m n)))
15876 (if (< m 0) (setq m (+ m 60) h (1- h)))
15877 (if (> m 59) (setq m (- m 60) h (1+ h)))
15878 (setq h (min 24 (max 0 h)))
15879 (setq ng 1 new (format "-%02d:%02d" h m)))
15880 ((org-pos-in-match-range pos 6)
15881 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15882 ((org-pos-in-match-range pos 5)
15883 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15885 ((org-pos-in-match-range pos 9)
15886 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15887 ((org-pos-in-match-range pos 8)
15888 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15890 (when ng
15891 (setq s (concat
15892 (substring s 0 (match-beginning ng))
15894 (substring s (match-end ng))))))
15897 (defun org-recenter-calendar (date)
15898 "If the calendar is visible, recenter it to DATE."
15899 (let* ((win (selected-window))
15900 (cwin (get-buffer-window "*Calendar*" t))
15901 (calendar-move-hook nil))
15902 (when cwin
15903 (select-window cwin)
15904 (calendar-goto-date (if (listp date) date
15905 (calendar-gregorian-from-absolute date)))
15906 (select-window win))))
15908 (defun org-goto-calendar (&optional arg)
15909 "Go to the Emacs calendar at the current date.
15910 If there is a time stamp in the current line, go to that date.
15911 A prefix ARG can be used to force the current date."
15912 (interactive "P")
15913 (let ((tsr org-ts-regexp) diff
15914 (calendar-move-hook nil)
15915 (calendar-view-holidays-initially-flag nil)
15916 (calendar-view-diary-initially-flag nil))
15917 (if (or (org-at-timestamp-p)
15918 (save-excursion
15919 (beginning-of-line 1)
15920 (looking-at (concat ".*" tsr))))
15921 (let ((d1 (time-to-days (current-time)))
15922 (d2 (time-to-days
15923 (org-time-string-to-time (match-string 1)))))
15924 (setq diff (- d2 d1))))
15925 (calendar)
15926 (calendar-goto-today)
15927 (if (and diff (not arg)) (calendar-forward-day diff))))
15929 (defun org-get-date-from-calendar ()
15930 "Return a list (month day year) of date at point in calendar."
15931 (with-current-buffer "*Calendar*"
15932 (save-match-data
15933 (calendar-cursor-to-date))))
15935 (defun org-date-from-calendar ()
15936 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15937 If there is already a time stamp at the cursor position, update it."
15938 (interactive)
15939 (if (org-at-timestamp-p t)
15940 (org-timestamp-change 0 'calendar)
15941 (let ((cal-date (org-get-date-from-calendar)))
15942 (org-insert-time-stamp
15943 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15945 (defun org-minutes-to-hh:mm-string (m)
15946 "Compute H:MM from a number of minutes."
15947 (let ((h (/ m 60)))
15948 (setq m (- m (* 60 h)))
15949 (format org-time-clocksum-format h m)))
15951 (defun org-hh:mm-string-to-minutes (s)
15952 "Convert a string H:MM to a number of minutes.
15953 If the string is just a number, interpret it as minutes.
15954 In fact, the first hh:mm or number in the string will be taken,
15955 there can be extra stuff in the string.
15956 If no number is found, the return value is 0."
15957 (cond
15958 ((integerp s) s)
15959 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15960 (+ (* (string-to-number (match-string 1 s)) 60)
15961 (string-to-number (match-string 2 s))))
15962 ((string-match "\\([0-9]+\\)" s)
15963 (string-to-number (match-string 1 s)))
15964 (t 0)))
15966 (defcustom org-effort-durations
15967 `(("h" . 60)
15968 ("d" . ,(* 60 8))
15969 ("w" . ,(* 60 8 5))
15970 ("m" . ,(* 60 8 5 4))
15971 ("y" . ,(* 60 8 5 40)))
15972 "Conversion factor to minutes for an effort modifier.
15974 Each entry has the form (MODIFIER . MINUTES).
15976 In an effort string, a number followed by MODIFIER is multiplied
15977 by the specified number of MINUTES to obtain an effort in
15978 minutes.
15980 For example, if the value of this variable is ((\"hours\" . 60)), then an
15981 effort string \"2hours\" is equivalent to 120 minutes."
15982 :group 'org-agenda
15983 :type '(alist :key-type (string :tag "Modifier")
15984 :value-type (number :tag "Minutes")))
15986 (defun org-duration-string-to-minutes (s)
15987 "Convert a duration string S to minutes.
15989 A bare number is interpreted as minutes, modifiers can be set by
15990 customizing `org-effort-durations' (which see).
15992 Entries containing a colon are interpreted as H:MM by
15993 `org-hh:mm-string-to-minutes'."
15994 (let ((result 0)
15995 (re (concat "\\([0-9]+\\) *\\("
15996 (regexp-opt (mapcar 'car org-effort-durations))
15997 "\\)")))
15998 (while (string-match re s)
15999 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16000 (string-to-number (match-string 1 s))))
16001 (setq s (replace-match "" nil t s)))
16002 (incf result (org-hh:mm-string-to-minutes s))
16003 result))
16005 ;;;; Files
16007 (defun org-save-all-org-buffers ()
16008 "Save all Org-mode buffers without user confirmation."
16009 (interactive)
16010 (message "Saving all Org-mode buffers...")
16011 (save-some-buffers t 'org-mode-p)
16012 (when (featurep 'org-id) (org-id-locations-save))
16013 (message "Saving all Org-mode buffers... done"))
16015 (defun org-revert-all-org-buffers ()
16016 "Revert all Org-mode buffers.
16017 Prompt for confirmation when there are unsaved changes.
16018 Be sure you know what you are doing before letting this function
16019 overwrite your changes.
16021 This function is useful in a setup where one tracks org files
16022 with a version control system, to revert on one machine after pulling
16023 changes from another. I believe the procedure must be like this:
16025 1. M-x org-save-all-org-buffers
16026 2. Pull changes from the other machine, resolve conflicts
16027 3. M-x org-revert-all-org-buffers"
16028 (interactive)
16029 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16030 (error "Abort"))
16031 (save-excursion
16032 (save-window-excursion
16033 (mapc
16034 (lambda (b)
16035 (when (and (with-current-buffer b (org-mode-p))
16036 (with-current-buffer b buffer-file-name))
16037 (org-pop-to-buffer-same-window b)
16038 (revert-buffer t 'no-confirm)))
16039 (buffer-list))
16040 (when (and (featurep 'org-id) org-id-track-globally)
16041 (org-id-locations-load)))))
16043 ;;;; Agenda files
16045 ;;;###autoload
16046 (defun org-switchb (&optional arg)
16047 "Switch between Org buffers.
16048 With a prefix argument, restrict available to files.
16049 With two prefix arguments, restrict available buffers to agenda files.
16051 Defaults to `iswitchb' for buffer name completion.
16052 Set `org-completion-use-ido' to make it use ido instead."
16053 (interactive "P")
16054 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16055 ((equal arg '(16)) (org-buffer-list 'agenda))
16056 (t (org-buffer-list))))
16057 (org-completion-use-iswitchb org-completion-use-iswitchb)
16058 (org-completion-use-ido org-completion-use-ido))
16059 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16060 (setq org-completion-use-iswitchb t))
16061 (org-pop-to-buffer-same-window
16062 (org-icompleting-read "Org buffer: "
16063 (mapcar 'list (mapcar 'buffer-name blist))
16064 nil t))))
16066 ;;; Define some older names previously used for this functionality
16067 ;;;###autoload
16068 (defalias 'org-ido-switchb 'org-switchb)
16069 ;;;###autoload
16070 (defalias 'org-iswitchb 'org-switchb)
16072 (defun org-buffer-list (&optional predicate exclude-tmp)
16073 "Return a list of Org buffers.
16074 PREDICATE can be `export', `files' or `agenda'.
16076 export restrict the list to Export buffers.
16077 files restrict the list to buffers visiting Org files.
16078 agenda restrict the list to buffers visiting agenda files.
16080 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16081 (let* ((bfn nil)
16082 (agenda-files (and (eq predicate 'agenda)
16083 (mapcar 'file-truename (org-agenda-files t))))
16084 (filter
16085 (cond
16086 ((eq predicate 'files)
16087 (lambda (b) (with-current-buffer b (org-mode-p))))
16088 ((eq predicate 'export)
16089 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16090 ((eq predicate 'agenda)
16091 (lambda (b)
16092 (with-current-buffer b
16093 (and (org-mode-p)
16094 (setq bfn (buffer-file-name b))
16095 (member (file-truename bfn) agenda-files)))))
16096 (t (lambda (b) (with-current-buffer b
16097 (or (org-mode-p)
16098 (string-match "\*Org .*Export"
16099 (buffer-name b)))))))))
16100 (delq nil
16101 (mapcar
16102 (lambda(b)
16103 (if (and (funcall filter b)
16104 (or (not exclude-tmp)
16105 (not (string-match "tmp" (buffer-name b)))))
16107 nil))
16108 (buffer-list)))))
16110 (defun org-agenda-files (&optional unrestricted archives)
16111 "Get the list of agenda files.
16112 Optional UNRESTRICTED means return the full list even if a restriction
16113 is currently in place.
16114 When ARCHIVES is t, include all archive files that are really being
16115 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16116 `org-agenda-archives-mode' is t."
16117 (let ((files
16118 (cond
16119 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16120 ((stringp org-agenda-files) (org-read-agenda-file-list))
16121 ((listp org-agenda-files) org-agenda-files)
16122 (t (error "Invalid value of `org-agenda-files'")))))
16123 (setq files (apply 'append
16124 (mapcar (lambda (f)
16125 (if (file-directory-p f)
16126 (directory-files
16127 f t org-agenda-file-regexp)
16128 (list f)))
16129 files)))
16130 (when org-agenda-skip-unavailable-files
16131 (setq files (delq nil
16132 (mapcar (function
16133 (lambda (file)
16134 (and (file-readable-p file) file)))
16135 files))))
16136 (when (or (eq archives t)
16137 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16138 (setq files (org-add-archive-files files)))
16139 files))
16141 (defun org-agenda-file-p (&optional file)
16142 "Return non-nil, if FILE is an agenda file.
16143 If FILE is omitted, use the file associated with the current
16144 buffer."
16145 (member (or file (buffer-file-name))
16146 (org-agenda-files t)))
16148 (defun org-edit-agenda-file-list ()
16149 "Edit the list of agenda files.
16150 Depending on setup, this either uses customize to edit the variable
16151 `org-agenda-files', or it visits the file that is holding the list. In the
16152 latter case, the buffer is set up in a way that saving it automatically kills
16153 the buffer and restores the previous window configuration."
16154 (interactive)
16155 (if (stringp org-agenda-files)
16156 (let ((cw (current-window-configuration)))
16157 (find-file org-agenda-files)
16158 (org-set-local 'org-window-configuration cw)
16159 (org-add-hook 'after-save-hook
16160 (lambda ()
16161 (set-window-configuration
16162 (prog1 org-window-configuration
16163 (kill-buffer (current-buffer))))
16164 (org-install-agenda-files-menu)
16165 (message "New agenda file list installed"))
16166 nil 'local)
16167 (message "%s" (substitute-command-keys
16168 "Edit list and finish with \\[save-buffer]")))
16169 (customize-variable 'org-agenda-files)))
16171 (defun org-store-new-agenda-file-list (list)
16172 "Set new value for the agenda file list and save it correctly."
16173 (if (stringp org-agenda-files)
16174 (let ((fe (org-read-agenda-file-list t)) b u)
16175 (while (setq b (find-buffer-visiting org-agenda-files))
16176 (kill-buffer b))
16177 (with-temp-file org-agenda-files
16178 (insert
16179 (mapconcat
16180 (lambda (f) ;; Keep un-expanded entries.
16181 (if (setq u (assoc f fe))
16182 (cdr u)
16184 list "\n")
16185 "\n")))
16186 (let ((org-mode-hook nil) (org-inhibit-startup t)
16187 (org-insert-mode-line-in-empty-file nil))
16188 (setq org-agenda-files list)
16189 (customize-save-variable 'org-agenda-files org-agenda-files))))
16191 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16192 "Read the list of agenda files from a file.
16193 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16194 filenames, used by `org-store-new-agenda-file-list' to write back
16195 un-expanded file names."
16196 (when (file-directory-p org-agenda-files)
16197 (error "`org-agenda-files' cannot be a single directory"))
16198 (when (stringp org-agenda-files)
16199 (with-temp-buffer
16200 (insert-file-contents org-agenda-files)
16201 (mapcar
16202 (lambda (f)
16203 (let ((e (expand-file-name (substitute-in-file-name f)
16204 org-directory)))
16205 (if pair-with-expansion
16206 (cons e f)
16207 e)))
16208 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16210 ;;;###autoload
16211 (defun org-cycle-agenda-files ()
16212 "Cycle through the files in `org-agenda-files'.
16213 If the current buffer visits an agenda file, find the next one in the list.
16214 If the current buffer does not, find the first agenda file."
16215 (interactive)
16216 (let* ((fs (org-agenda-files t))
16217 (files (append fs (list (car fs))))
16218 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16219 file)
16220 (unless files (error "No agenda files"))
16221 (catch 'exit
16222 (while (setq file (pop files))
16223 (if (equal (file-truename file) tcf)
16224 (when (car files)
16225 (find-file (car files))
16226 (throw 'exit t))))
16227 (find-file (car fs)))
16228 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16230 (defun org-agenda-file-to-front (&optional to-end)
16231 "Move/add the current file to the top of the agenda file list.
16232 If the file is not present in the list, it is added to the front. If it is
16233 present, it is moved there. With optional argument TO-END, add/move to the
16234 end of the list."
16235 (interactive "P")
16236 (let ((org-agenda-skip-unavailable-files nil)
16237 (file-alist (mapcar (lambda (x)
16238 (cons (file-truename x) x))
16239 (org-agenda-files t)))
16240 (ctf (file-truename buffer-file-name))
16241 x had)
16242 (setq x (assoc ctf file-alist) had x)
16244 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16245 (if to-end
16246 (setq file-alist (append (delq x file-alist) (list x)))
16247 (setq file-alist (cons x (delq x file-alist))))
16248 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16249 (org-install-agenda-files-menu)
16250 (message "File %s to %s of agenda file list"
16251 (if had "moved" "added") (if to-end "end" "front"))))
16253 (defun org-remove-file (&optional file)
16254 "Remove current file from the list of files in variable `org-agenda-files'.
16255 These are the files which are being checked for agenda entries.
16256 Optional argument FILE means use this file instead of the current."
16257 (interactive)
16258 (let* ((org-agenda-skip-unavailable-files nil)
16259 (file (or file buffer-file-name))
16260 (true-file (file-truename file))
16261 (afile (abbreviate-file-name file))
16262 (files (delq nil (mapcar
16263 (lambda (x)
16264 (if (equal true-file
16265 (file-truename x))
16266 nil x))
16267 (org-agenda-files t)))))
16268 (if (not (= (length files) (length (org-agenda-files t))))
16269 (progn
16270 (org-store-new-agenda-file-list files)
16271 (org-install-agenda-files-menu)
16272 (message "Removed file: %s" afile))
16273 (message "File was not in list: %s (not removed)" afile))))
16275 (defun org-file-menu-entry (file)
16276 (vector file (list 'find-file file) t))
16278 (defun org-check-agenda-file (file)
16279 "Make sure FILE exists. If not, ask user what to do."
16280 (when (not (file-exists-p file))
16281 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16282 (abbreviate-file-name file))
16283 (let ((r (downcase (read-char-exclusive))))
16284 (cond
16285 ((equal r ?r)
16286 (org-remove-file file)
16287 (throw 'nextfile t))
16288 (t (error "Abort"))))))
16290 (defun org-get-agenda-file-buffer (file)
16291 "Get a buffer visiting FILE. If the buffer needs to be created, add
16292 it to the list of buffers which might be released later."
16293 (let ((buf (org-find-base-buffer-visiting file)))
16294 (if buf
16295 buf ; just return it
16296 ;; Make a new buffer and remember it
16297 (setq buf (find-file-noselect file))
16298 (if buf (push buf org-agenda-new-buffers))
16299 buf)))
16301 (defun org-release-buffers (blist)
16302 "Release all buffers in list, asking the user for confirmation when needed.
16303 When a buffer is unmodified, it is just killed. When modified, it is saved
16304 \(if the user agrees) and then killed."
16305 (let (buf file)
16306 (while (setq buf (pop blist))
16307 (setq file (buffer-file-name buf))
16308 (when (and (buffer-modified-p buf)
16309 file
16310 (y-or-n-p (format "Save file %s? " file)))
16311 (with-current-buffer buf (save-buffer)))
16312 (kill-buffer buf))))
16314 (defun org-prepare-agenda-buffers (files)
16315 "Create buffers for all agenda files, protect archived trees and comments."
16316 (interactive)
16317 (let ((pa '(:org-archived t))
16318 (pc '(:org-comment t))
16319 (pall '(:org-archived t :org-comment t))
16320 (inhibit-read-only t)
16321 (rea (concat ":" org-archive-tag ":"))
16322 bmp file re)
16323 (save-excursion
16324 (save-restriction
16325 (while (setq file (pop files))
16326 (catch 'nextfile
16327 (if (bufferp file)
16328 (set-buffer file)
16329 (org-check-agenda-file file)
16330 (set-buffer (org-get-agenda-file-buffer file)))
16331 (widen)
16332 (setq bmp (buffer-modified-p))
16333 (org-refresh-category-properties)
16334 (setq org-todo-keywords-for-agenda
16335 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16336 (setq org-done-keywords-for-agenda
16337 (append org-done-keywords-for-agenda org-done-keywords))
16338 (setq org-todo-keyword-alist-for-agenda
16339 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16340 (setq org-drawers-for-agenda
16341 (append org-drawers-for-agenda org-drawers))
16342 (setq org-tag-alist-for-agenda
16343 (append org-tag-alist-for-agenda org-tag-alist))
16345 (save-excursion
16346 (remove-text-properties (point-min) (point-max) pall)
16347 (when org-agenda-skip-archived-trees
16348 (goto-char (point-min))
16349 (while (re-search-forward rea nil t)
16350 (if (org-on-heading-p t)
16351 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16352 (goto-char (point-min))
16353 (setq re (concat org-outline-regexp-bol "+" org-comment-string "\\>"))
16354 (while (re-search-forward re nil t)
16355 (add-text-properties
16356 (match-beginning 0) (org-end-of-subtree t) pc)))
16357 (set-buffer-modified-p bmp)))))
16358 (setq org-todo-keywords-for-agenda
16359 (org-uniquify org-todo-keywords-for-agenda))
16360 (setq org-todo-keyword-alist-for-agenda
16361 (org-uniquify org-todo-keyword-alist-for-agenda)
16362 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16364 ;;;; Embedded LaTeX
16366 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16367 "Keymap for the minor `org-cdlatex-mode'.")
16369 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16370 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16371 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16372 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16373 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16375 (defvar org-cdlatex-texmathp-advice-is-done nil
16376 "Flag remembering if we have applied the advice to texmathp already.")
16378 (define-minor-mode org-cdlatex-mode
16379 "Toggle the minor `org-cdlatex-mode'.
16380 This mode supports entering LaTeX environment and math in LaTeX fragments
16381 in Org-mode.
16382 \\{org-cdlatex-mode-map}"
16383 nil " OCDL" nil
16384 (when org-cdlatex-mode
16385 (require 'cdlatex)
16386 (run-hooks 'cdlatex-mode-hook)
16387 (cdlatex-compute-tables))
16388 (unless org-cdlatex-texmathp-advice-is-done
16389 (setq org-cdlatex-texmathp-advice-is-done t)
16390 (defadvice texmathp (around org-math-always-on activate)
16391 "Always return t in org-mode buffers.
16392 This is because we want to insert math symbols without dollars even outside
16393 the LaTeX math segments. If Orgmode thinks that point is actually inside
16394 an embedded LaTeX fragment, let texmathp do its job.
16395 \\[org-cdlatex-mode-map]"
16396 (interactive)
16397 (let (p)
16398 (cond
16399 ((not (org-mode-p)) ad-do-it)
16400 ((eq this-command 'cdlatex-math-symbol)
16401 (setq ad-return-value t
16402 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16404 (let ((p (org-inside-LaTeX-fragment-p)))
16405 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16406 (setq ad-return-value t
16407 texmathp-why '("Org-mode embedded math" . 0))
16408 (if p ad-do-it)))))))))
16410 (defun turn-on-org-cdlatex ()
16411 "Unconditionally turn on `org-cdlatex-mode'."
16412 (org-cdlatex-mode 1))
16414 (defun org-inside-LaTeX-fragment-p ()
16415 "Test if point is inside a LaTeX fragment.
16416 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16417 sequence appearing also before point.
16418 Even though the matchers for math are configurable, this function assumes
16419 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16420 delimiters are skipped when they have been removed by customization.
16421 The return value is nil, or a cons cell with the delimiter and the
16422 position of this delimiter.
16424 This function does a reasonably good job, but can locally be fooled by
16425 for example currency specifications. For example it will assume being in
16426 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16427 fragments that are properly closed, but during editing, we have to live
16428 with the uncertainty caused by missing closing delimiters. This function
16429 looks only before point, not after."
16430 (catch 'exit
16431 (let ((pos (point))
16432 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16433 (lim (progn
16434 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16435 (point)))
16436 dd-on str (start 0) m re)
16437 (goto-char pos)
16438 (when dodollar
16439 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16440 re (nth 1 (assoc "$" org-latex-regexps)))
16441 (while (string-match re str start)
16442 (cond
16443 ((= (match-end 0) (length str))
16444 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16445 ((= (match-end 0) (- (length str) 5))
16446 (throw 'exit nil))
16447 (t (setq start (match-end 0))))))
16448 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16449 (goto-char pos)
16450 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16451 (and (match-beginning 2) (throw 'exit nil))
16452 ;; count $$
16453 (while (re-search-backward "\\$\\$" lim t)
16454 (setq dd-on (not dd-on)))
16455 (goto-char pos)
16456 (if dd-on (cons "$$" m))))))
16458 (defun org-inside-latex-macro-p ()
16459 "Is point inside a LaTeX macro or its arguments?"
16460 (save-match-data
16461 (org-in-regexp
16462 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16464 (defun org-try-cdlatex-tab ()
16465 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16466 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16467 - inside a LaTeX fragment, or
16468 - after the first word in a line, where an abbreviation expansion could
16469 insert a LaTeX environment."
16470 (when org-cdlatex-mode
16471 (cond
16472 ((save-excursion
16473 (skip-chars-backward "a-zA-Z0-9*")
16474 (skip-chars-backward " \t")
16475 (bolp))
16476 (cdlatex-tab) t)
16477 ((org-inside-LaTeX-fragment-p)
16478 (cdlatex-tab) t)
16479 (t nil))))
16481 (defun org-cdlatex-underscore-caret (&optional arg)
16482 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16483 Revert to the normal definition outside of these fragments."
16484 (interactive "P")
16485 (if (org-inside-LaTeX-fragment-p)
16486 (call-interactively 'cdlatex-sub-superscript)
16487 (let (org-cdlatex-mode)
16488 (call-interactively (key-binding (vector last-input-event))))))
16490 (defun org-cdlatex-math-modify (&optional arg)
16491 "Execute `cdlatex-math-modify' in LaTeX fragments.
16492 Revert to the normal definition outside of these fragments."
16493 (interactive "P")
16494 (if (org-inside-LaTeX-fragment-p)
16495 (call-interactively 'cdlatex-math-modify)
16496 (let (org-cdlatex-mode)
16497 (call-interactively (key-binding (vector last-input-event))))))
16499 (defvar org-latex-fragment-image-overlays nil
16500 "List of overlays carrying the images of latex fragments.")
16501 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16503 (defun org-remove-latex-fragment-image-overlays ()
16504 "Remove all overlays with LaTeX fragment images in current buffer."
16505 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16506 (setq org-latex-fragment-image-overlays nil))
16508 (defun org-preview-latex-fragment (&optional subtree)
16509 "Preview the LaTeX fragment at point, or all locally or globally.
16510 If the cursor is in a LaTeX fragment, create the image and overlay
16511 it over the source code. If there is no fragment at point, display
16512 all fragments in the current text, from one headline to the next. With
16513 prefix SUBTREE, display all fragments in the current subtree. With a
16514 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16515 the cursor is before the first headline,
16516 display all fragments in the buffer.
16517 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16518 (interactive "P")
16519 (org-remove-latex-fragment-image-overlays)
16520 (save-excursion
16521 (save-restriction
16522 (let (beg end at msg)
16523 (cond
16524 ((or (equal subtree '(16))
16525 (not (save-excursion
16526 (re-search-backward org-outline-regexp-bol nil t))))
16527 (setq beg (point-min) end (point-max)
16528 msg "Creating images for buffer...%s"))
16529 ((equal subtree '(4))
16530 (org-back-to-heading)
16531 (setq beg (point) end (org-end-of-subtree t)
16532 msg "Creating images for subtree...%s"))
16534 (if (setq at (org-inside-LaTeX-fragment-p))
16535 (goto-char (max (point-min) (- (cdr at) 2)))
16536 (org-back-to-heading))
16537 (setq beg (point) end (progn (outline-next-heading) (point))
16538 msg (if at "Creating image...%s"
16539 "Creating images for entry...%s"))))
16540 (message msg "")
16541 (narrow-to-region beg end)
16542 (goto-char beg)
16543 (org-format-latex
16544 (concat "ltxpng/" (file-name-sans-extension
16545 (file-name-nondirectory
16546 buffer-file-name)))
16547 default-directory 'overlays msg at 'forbuffer 'dvipng)
16548 (message msg "done. Use `C-c C-c' to remove images.")))))
16550 (defvar org-latex-regexps
16551 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16552 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16553 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16554 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16555 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16556 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16557 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16558 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16559 "Regular expressions for matching embedded LaTeX.")
16561 (defvar org-export-have-math nil) ;; dynamic scoping
16562 (defun org-format-latex (prefix &optional dir overlays msg at
16563 forbuffer processing-type)
16564 "Replace LaTeX fragments with links to an image, and produce images.
16565 Some of the options can be changed using the variable
16566 `org-format-latex-options'."
16567 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16568 (let* ((prefixnodir (file-name-nondirectory prefix))
16569 (absprefix (expand-file-name prefix dir))
16570 (todir (file-name-directory absprefix))
16571 (opt org-format-latex-options)
16572 (matchers (plist-get opt :matchers))
16573 (re-list org-latex-regexps)
16574 (org-format-latex-header-extra
16575 (plist-get (org-infile-export-plist) :latex-header-extra))
16576 (cnt 0) txt hash link beg end re e checkdir
16577 executables-checked string
16578 m n block-type block linkfile movefile ov)
16579 ;; Check the different regular expressions
16580 (while (setq e (pop re-list))
16581 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16582 block (if block-type "\n\n" ""))
16583 (when (member m matchers)
16584 (goto-char (point-min))
16585 (while (re-search-forward re nil t)
16586 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16587 (not (get-text-property (match-beginning n)
16588 'org-protected))
16589 (or (not overlays)
16590 (not (eq (get-char-property (match-beginning n)
16591 'org-overlay-type)
16592 'org-latex-overlay))))
16593 (setq org-export-have-math t)
16594 (cond
16595 ((eq processing-type 'verbatim)
16596 ;; Leave the text verbatim, just protect it
16597 (add-text-properties (match-beginning n) (match-end n)
16598 '(org-protected t)))
16599 ((eq processing-type 'mathjax)
16600 ;; Prepare for MathJax processing
16601 (setq string (match-string n))
16602 (if (member m '("$" "$1"))
16603 (save-excursion
16604 (delete-region (match-beginning n) (match-end n))
16605 (goto-char (match-beginning n))
16606 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16607 "\\)")
16608 '(org-protected t))))
16609 (add-text-properties (match-beginning n) (match-end n)
16610 '(org-protected t))))
16611 ((eq processing-type 'dvipng)
16612 ;; Process to an image
16613 (setq txt (match-string n)
16614 beg (match-beginning n) end (match-end n)
16615 cnt (1+ cnt))
16616 (let (print-length print-level) ; make sure full list is printed
16617 (setq hash (sha1 (prin1-to-string
16618 (list org-format-latex-header
16619 org-format-latex-header-extra
16620 org-export-latex-default-packages-alist
16621 org-export-latex-packages-alist
16622 org-format-latex-options
16623 forbuffer txt)))
16624 linkfile (format "%s_%s.png" prefix hash)
16625 movefile (format "%s_%s.png" absprefix hash)))
16626 (setq link (concat block "[[file:" linkfile "]]" block))
16627 (if msg (message msg cnt))
16628 (goto-char beg)
16629 (unless checkdir ; make sure the directory exists
16630 (setq checkdir t)
16631 (or (file-directory-p todir) (make-directory todir t)))
16633 (unless executables-checked
16634 (org-check-external-command
16635 "latex" "needed to convert LaTeX fragments to images")
16636 (org-check-external-command
16637 "dvipng" "needed to convert LaTeX fragments to images")
16638 (setq executables-checked t))
16640 (unless (file-exists-p movefile)
16641 (org-create-formula-image
16642 txt movefile opt forbuffer))
16643 (if overlays
16644 (progn
16645 (mapc (lambda (o)
16646 (if (eq (overlay-get o 'org-overlay-type)
16647 'org-latex-overlay)
16648 (delete-overlay o)))
16649 (overlays-in beg end))
16650 (setq ov (make-overlay beg end))
16651 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16652 (if (featurep 'xemacs)
16653 (progn
16654 (overlay-put ov 'invisible t)
16655 (overlay-put
16656 ov 'end-glyph
16657 (make-glyph (vector 'png :file movefile))))
16658 (overlay-put
16659 ov 'display
16660 (list 'image :type 'png :file movefile :ascent 'center)))
16661 (push ov org-latex-fragment-image-overlays)
16662 (goto-char end))
16663 (delete-region beg end)
16664 (insert (org-add-props link
16665 (list 'org-latex-src
16666 (replace-regexp-in-string
16667 "\"" "" txt)
16668 'org-latex-src-embed-type
16669 (if block-type 'paragraph 'character))))))
16670 ((eq processing-type 'mathml)
16671 ;; Process to MathML
16672 (unless executables-checked
16673 (unless (save-match-data (org-format-latex-mathml-available-p))
16674 (error "LaTeX to MathML converter not configured"))
16675 (setq executables-checked t))
16676 (setq txt (match-string n)
16677 beg (match-beginning n) end (match-end n)
16678 cnt (1+ cnt))
16679 (if msg (message msg cnt))
16680 (goto-char beg)
16681 (delete-region beg end)
16682 (insert (org-format-latex-as-mathml
16683 txt block-type prefix dir)))
16685 (error "Unknown conversion type %s for latex fragments"
16686 processing-type)))))))))
16688 (defun org-create-math-formula (latex-frag &optional mathml-file)
16689 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16690 Use `org-latex-to-mathml-convert-command'. If the conversion is
16691 sucessful, return the portion between \"<math...> </math>\"
16692 elements otherwise return nil. When MATHML-FILE is specified,
16693 write the results in to that file. When invoked as an
16694 interactive command, prompt for LATEX-FRAG, with initial value
16695 set to the current active region and echo the results for user
16696 inspection."
16697 (interactive (list (let ((frag (when (region-active-p)
16698 (buffer-substring-no-properties
16699 (region-beginning) (region-end)))))
16700 (read-string "LaTeX Fragment: " frag nil frag))))
16701 (unless latex-frag (error "Invalid latex-frag"))
16702 (let* ((tmp-in-file (file-relative-name
16703 (make-temp-name (expand-file-name "ltxmathml-in"))))
16704 (ignore (write-region latex-frag nil tmp-in-file))
16705 (tmp-out-file (file-relative-name
16706 (make-temp-name (expand-file-name "ltxmathml-out"))))
16707 (cmd (format-spec
16708 org-latex-to-mathml-convert-command
16709 `((?j . ,(shell-quote-argument
16710 (expand-file-name org-latex-to-mathml-jar-file)))
16711 (?I . ,(shell-quote-argument tmp-in-file))
16712 (?o . ,(shell-quote-argument tmp-out-file)))))
16713 mathml shell-command-output)
16714 (when (org-called-interactively-p 'any)
16715 (unless (org-format-latex-mathml-available-p)
16716 (error "LaTeX to MathML converter not configured")))
16717 (message "Running %s" cmd)
16718 (setq shell-command-output (shell-command-to-string cmd))
16719 (setq mathml
16720 (when (file-readable-p tmp-out-file)
16721 (with-current-buffer (find-file-noselect tmp-out-file t)
16722 (goto-char (point-min))
16723 (when (re-search-forward
16724 (concat
16725 (regexp-quote
16726 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16727 "\\(.\\|\n\\)*"
16728 (regexp-quote "</math>")) nil t)
16729 (prog1 (match-string 0) (kill-buffer))))))
16730 (cond
16731 (mathml
16732 (setq mathml
16733 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16734 (when mathml-file
16735 (write-region mathml nil mathml-file))
16736 (when (org-called-interactively-p 'any)
16737 (message mathml)))
16738 ((message "LaTeX to MathML conversion failed")
16739 (message shell-command-output)))
16740 (delete-file tmp-in-file)
16741 (when (file-exists-p tmp-out-file)
16742 (delete-file tmp-out-file))
16743 mathml))
16745 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16746 prefix &optional dir)
16747 "Use `org-create-math-formula' but check local cache first."
16748 (let* ((absprefix (expand-file-name prefix dir))
16749 (print-length nil) (print-level nil)
16750 (formula-id (concat
16751 "formula-"
16752 (sha1
16753 (prin1-to-string
16754 (list latex-frag
16755 org-latex-to-mathml-convert-command)))))
16756 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16757 (formula-cache-dir (file-name-directory formula-cache)))
16759 (unless (file-directory-p formula-cache-dir)
16760 (make-directory formula-cache-dir t))
16762 (unless (file-exists-p formula-cache)
16763 (org-create-math-formula latex-frag formula-cache))
16765 (if (file-exists-p formula-cache)
16766 ;; Successful conversion. Return the link to MathML file.
16767 (org-add-props
16768 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16769 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16770 'org-latex-src-embed-type (if latex-frag-type
16771 'paragraph 'character)))
16772 ;; Failed conversion. Return the LaTeX fragment verbatim
16773 (add-text-properties
16774 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16775 latex-frag)))
16777 ;; This function borrows from Ganesh Swami's latex2png.el
16778 (defun org-create-formula-image (string tofile options buffer)
16779 "This calls dvipng."
16780 (require 'org-latex)
16781 (let* ((tmpdir (if (featurep 'xemacs)
16782 (temp-directory)
16783 temporary-file-directory))
16784 (texfilebase (make-temp-name
16785 (expand-file-name "orgtex" tmpdir)))
16786 (texfile (concat texfilebase ".tex"))
16787 (dvifile (concat texfilebase ".dvi"))
16788 (pngfile (concat texfilebase ".png"))
16789 (fnh (if (featurep 'xemacs)
16790 (font-height (get-face-font 'default))
16791 (face-attribute 'default :height nil)))
16792 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16793 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16794 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16795 "Black"))
16796 (bg (or (plist-get options (if buffer :background :html-background))
16797 "Transparent")))
16798 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16799 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16800 (with-temp-file texfile
16801 (insert (org-splice-latex-header
16802 org-format-latex-header
16803 org-export-latex-default-packages-alist
16804 org-export-latex-packages-alist t
16805 org-format-latex-header-extra))
16806 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16807 (require 'org-latex)
16808 (org-export-latex-fix-inputenc))
16809 (let ((dir default-directory))
16810 (condition-case nil
16811 (progn
16812 (cd tmpdir)
16813 (call-process "latex" nil nil nil texfile))
16814 (error nil))
16815 (cd dir))
16816 (if (not (file-exists-p dvifile))
16817 (progn (message "Failed to create dvi file from %s" texfile) nil)
16818 (condition-case nil
16819 (call-process "dvipng" nil nil nil
16820 "-fg" fg "-bg" bg
16821 "-D" dpi
16822 ;;"-x" scale "-y" scale
16823 "-T" "tight"
16824 "-o" pngfile
16825 dvifile)
16826 (error nil))
16827 (if (not (file-exists-p pngfile))
16828 (if org-format-latex-signal-error
16829 (error "Failed to create png file from %s" texfile)
16830 (message "Failed to create png file from %s" texfile)
16831 nil)
16832 ;; Use the requested file name and clean up
16833 (copy-file pngfile tofile 'replace)
16834 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16835 (delete-file (concat texfilebase e)))
16836 pngfile))))
16838 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16839 "Fill a LaTeX header template TPL.
16840 In the template, the following place holders will be recognized:
16842 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16843 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16844 [PACKAGES] \\usepackage statements for PKG
16845 [NO-PACKAGES] do not include PKG
16846 [EXTRA] the string EXTRA
16847 [NO-EXTRA] do not include EXTRA
16849 For backward compatibility, if both the positive and the negative place
16850 holder is missing, the positive one (without the \"NO-\") will be
16851 assumed to be present at the end of the template.
16852 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16853 EXTRA is a string.
16854 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16855 (let (rpl (end ""))
16856 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16857 (setq rpl (if (or (match-end 1) (not def-pkg))
16858 "" (org-latex-packages-to-string def-pkg snippets-p t))
16859 tpl (replace-match rpl t t tpl))
16860 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16862 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16863 (setq rpl (if (or (match-end 1) (not pkg))
16864 "" (org-latex-packages-to-string pkg snippets-p t))
16865 tpl (replace-match rpl t t tpl))
16866 (if pkg (setq end
16867 (concat end "\n"
16868 (org-latex-packages-to-string pkg snippets-p)))))
16870 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16871 (setq rpl (if (or (match-end 1) (not extra))
16872 "" (concat extra "\n"))
16873 tpl (replace-match rpl t t tpl))
16874 (if (and extra (string-match "\\S-" extra))
16875 (setq end (concat end "\n" extra))))
16877 (if (string-match "\\S-" end)
16878 (concat tpl "\n" end)
16879 tpl)))
16881 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16882 "Turn an alist of packages into a string with the \\usepackage macros."
16883 (setq pkg (mapconcat (lambda(p)
16884 (cond
16885 ((stringp p) p)
16886 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16887 (format "%% Package %s omitted" (cadr p)))
16888 ((equal "" (car p))
16889 (format "\\usepackage{%s}" (cadr p)))
16891 (format "\\usepackage[%s]{%s}"
16892 (car p) (cadr p)))))
16894 "\n"))
16895 (if newline (concat pkg "\n") pkg))
16897 (defun org-dvipng-color (attr)
16898 "Return an rgb color specification for dvipng."
16899 (apply 'format "rgb %s %s %s"
16900 (mapcar 'org-normalize-color
16901 (color-values (face-attribute 'default attr nil)))))
16903 (defun org-normalize-color (value)
16904 "Return string to be used as color value for an RGB component."
16905 (format "%g" (/ value 65535.0)))
16907 ;; Image display
16910 (defvar org-inline-image-overlays nil)
16911 (make-variable-buffer-local 'org-inline-image-overlays)
16913 (defun org-toggle-inline-images (&optional include-linked)
16914 "Toggle the display of inline images.
16915 INCLUDE-LINKED is passed to `org-display-inline-images'."
16916 (interactive "P")
16917 (if org-inline-image-overlays
16918 (progn
16919 (org-remove-inline-images)
16920 (message "Inline image display turned off"))
16921 (org-display-inline-images include-linked)
16922 (if org-inline-image-overlays
16923 (message "%d images displayed inline"
16924 (length org-inline-image-overlays))
16925 (message "No images to display inline"))))
16927 (defun org-display-inline-images (&optional include-linked refresh beg end)
16928 "Display inline images.
16929 Normally only links without a description part are inlined, because this
16930 is how it will work for export. When INCLUDE-LINKED is set, also links
16931 with a description part will be inlined. This can be nice for a quick
16932 look at those images, but it does not reflect what exported files will look
16933 like.
16934 When REFRESH is set, refresh existing images between BEG and END.
16935 This will create new image displays only if necessary.
16936 BEG and END default to the buffer boundaries."
16937 (interactive "P")
16938 (unless refresh
16939 (org-remove-inline-images)
16940 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16941 (save-excursion
16942 (save-restriction
16943 (widen)
16944 (setq beg (or beg (point-min)) end (or end (point-max)))
16945 (goto-char (point-min))
16946 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16947 (substring (org-image-file-name-regexp) 0 -2)
16948 "\\)\\]" (if include-linked "" "\\]")))
16949 old file ov img)
16950 (while (re-search-forward re end t)
16951 (setq old (get-char-property-and-overlay (match-beginning 1)
16952 'org-image-overlay))
16953 (setq file (expand-file-name
16954 (concat (or (match-string 3) "") (match-string 4))))
16955 (when (file-exists-p file)
16956 (if (and (car-safe old) refresh)
16957 (image-refresh (overlay-get (cdr old) 'display))
16958 (setq img (save-match-data (create-image file)))
16959 (when img
16960 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16961 (overlay-put ov 'display img)
16962 (overlay-put ov 'face 'default)
16963 (overlay-put ov 'org-image-overlay t)
16964 (overlay-put ov 'modification-hooks
16965 (list 'org-display-inline-modification-hook))
16966 (push ov org-inline-image-overlays)))))))))
16968 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16969 "Remove inline-display overlay if a corresponding region is modified."
16970 (let ((inhibit-modification-hooks t))
16971 (when (and ov after)
16972 (delete ov org-inline-image-overlays)
16973 (delete-overlay ov))))
16975 (defun org-remove-inline-images ()
16976 "Remove inline display of images."
16977 (interactive)
16978 (mapc 'delete-overlay org-inline-image-overlays)
16979 (setq org-inline-image-overlays nil))
16981 ;;;; Key bindings
16983 ;; Make `C-c C-x' a prefix key
16984 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16986 ;; TAB key with modifiers
16987 (org-defkey org-mode-map "\C-i" 'org-cycle)
16988 (org-defkey org-mode-map [(tab)] 'org-cycle)
16989 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16990 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16991 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16992 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16993 ;; The following line is necessary under Suse GNU/Linux
16994 (unless (featurep 'xemacs)
16995 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16996 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16997 (define-key org-mode-map [backtab] 'org-shifttab)
16999 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17000 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17001 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17003 ;; Cursor keys with modifiers
17004 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17005 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17006 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17007 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17009 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17010 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17011 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17012 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17014 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17015 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17016 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17017 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17019 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17020 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17021 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17022 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17024 ;; Babel keys
17025 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17026 (mapc (lambda (pair)
17027 (define-key org-babel-map (car pair) (cdr pair)))
17028 org-babel-key-bindings)
17030 ;;; Extra keys for tty access.
17031 ;; We only set them when really needed because otherwise the
17032 ;; menus don't show the simple keys
17034 (when (or org-use-extra-keys
17035 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17036 (not window-system))
17037 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17038 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17039 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17040 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17041 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17042 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17043 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17044 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17045 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17046 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17047 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17048 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17049 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17050 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17051 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17052 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17053 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17054 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17055 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17056 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17057 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17058 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17059 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17060 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17061 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17062 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17063 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17064 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17066 ;; All the other keys
17068 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17069 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17070 (if (boundp 'narrow-map)
17071 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17072 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17073 (if (boundp 'narrow-map)
17074 (org-defkey narrow-map "b" 'org-narrow-to-block)
17075 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17076 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17077 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17078 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17079 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17080 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17081 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17082 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17083 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17084 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17085 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17086 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17087 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17088 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17089 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17090 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17091 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17092 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17093 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17094 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17095 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17096 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17097 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17098 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17099 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17100 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17101 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17102 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17103 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17104 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17105 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17106 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17107 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17108 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17109 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17110 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17111 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17112 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17113 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17114 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17115 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17116 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17117 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17118 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17119 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17120 (org-defkey org-mode-map "\C-c^" 'org-sort)
17121 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17122 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17123 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17124 (org-defkey org-mode-map "\C-m" 'org-return)
17125 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17126 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17127 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17128 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17129 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17130 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17131 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17132 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17133 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17134 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17135 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17136 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17137 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17138 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17139 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17140 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17141 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17142 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17143 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17144 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17145 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17146 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17148 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17149 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17150 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17151 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17153 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17154 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17155 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17156 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17157 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17158 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17159 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17160 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17161 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17162 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17163 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17164 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17165 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17166 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17167 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17168 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17169 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17170 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17172 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17173 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17174 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17175 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17176 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17178 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17180 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17182 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17183 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17185 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17188 (when (featurep 'xemacs)
17189 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17192 (defconst org-speed-commands-default
17194 ("Outline Navigation")
17195 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17196 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17197 ("f" . (org-speed-move-safe 'org-forward-same-level))
17198 ("b" . (org-speed-move-safe 'org-backward-same-level))
17199 ("u" . (org-speed-move-safe 'outline-up-heading))
17200 ("j" . org-goto)
17201 ("g" . (org-refile t))
17202 ("Outline Visibility")
17203 ("c" . org-cycle)
17204 ("C" . org-shifttab)
17205 (" " . org-display-outline-path)
17206 ("Outline Structure Editing")
17207 ("U" . org-shiftmetaup)
17208 ("D" . org-shiftmetadown)
17209 ("r" . org-metaright)
17210 ("l" . org-metaleft)
17211 ("R" . org-shiftmetaright)
17212 ("L" . org-shiftmetaleft)
17213 ("i" . (progn (forward-char 1) (call-interactively
17214 'org-insert-heading-respect-content)))
17215 ("^" . org-sort)
17216 ("w" . org-refile)
17217 ("a" . org-archive-subtree-default-with-confirmation)
17218 ("." . org-mark-subtree)
17219 ("Clock Commands")
17220 ("I" . org-clock-in)
17221 ("O" . org-clock-out)
17222 ("Meta Data Editing")
17223 ("t" . org-todo)
17224 ("0" . (org-priority ?\ ))
17225 ("1" . (org-priority ?A))
17226 ("2" . (org-priority ?B))
17227 ("3" . (org-priority ?C))
17228 (";" . org-set-tags-command)
17229 ("e" . org-set-effort)
17230 ("Agenda Views etc")
17231 ("v" . org-agenda)
17232 ("/" . org-sparse-tree)
17233 ("Misc")
17234 ("o" . org-open-at-point)
17235 ("?" . org-speed-command-help)
17236 ("<" . (org-agenda-set-restriction-lock 'subtree))
17237 (">" . (org-agenda-remove-restriction-lock))
17239 "The default speed commands.")
17241 (defun org-print-speed-command (e)
17242 (if (> (length (car e)) 1)
17243 (progn
17244 (princ "\n")
17245 (princ (car e))
17246 (princ "\n")
17247 (princ (make-string (length (car e)) ?-))
17248 (princ "\n"))
17249 (princ (car e))
17250 (princ " ")
17251 (if (symbolp (cdr e))
17252 (princ (symbol-name (cdr e)))
17253 (prin1 (cdr e)))
17254 (princ "\n")))
17256 (defun org-speed-command-help ()
17257 "Show the available speed commands."
17258 (interactive)
17259 (if (not org-use-speed-commands)
17260 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17261 (with-output-to-temp-buffer "*Help*"
17262 (princ "User-defined Speed commands\n===========================\n")
17263 (mapc 'org-print-speed-command org-speed-commands-user)
17264 (princ "\n")
17265 (princ "Built-in Speed commands\n=======================\n")
17266 (mapc 'org-print-speed-command org-speed-commands-default))
17267 (with-current-buffer "*Help*"
17268 (setq truncate-lines t))))
17270 (defun org-speed-move-safe (cmd)
17271 "Execute CMD, but make sure that the cursor always ends up in a headline.
17272 If not, return to the original position and throw an error."
17273 (interactive)
17274 (let ((pos (point)))
17275 (call-interactively cmd)
17276 (unless (and (bolp) (org-on-heading-p))
17277 (goto-char pos)
17278 (error "Boundary reached while executing %s" cmd))))
17280 (defvar org-self-insert-command-undo-counter 0)
17282 (defvar org-table-auto-blank-field) ; defined in org-table.el
17283 (defvar org-speed-command nil)
17285 (defun org-speed-command-default-hook (keys)
17286 "Hook for activating single-letter speed commands.
17287 `org-speed-commands-default' specifies a minimal command set.
17288 Use `org-speed-commands-user' for further customization."
17289 (when (or (and (bolp) (looking-at org-outline-regexp))
17290 (and (functionp org-use-speed-commands)
17291 (funcall org-use-speed-commands)))
17292 (cdr (assoc keys (append org-speed-commands-user
17293 org-speed-commands-default)))))
17295 (defun org-babel-speed-command-hook (keys)
17296 "Hook for activating single-letter code block commands."
17297 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17298 (cdr (assoc keys org-babel-key-bindings))))
17300 (defcustom org-speed-command-hook
17301 '(org-speed-command-default-hook org-babel-speed-command-hook)
17302 "Hook for activating speed commands at strategic locations.
17303 Hook functions are called in sequence until a valid handler is
17304 found.
17306 Each hook takes a single argument, a user-pressed command key
17307 which is also a `self-insert-command' from the global map.
17309 Within the hook, examine the cursor position and the command key
17310 and return nil or a valid handler as appropriate. Handler could
17311 be one of an interactive command, a function, or a form.
17313 Set `org-use-speed-commands' to non-nil value to enable this
17314 hook. The default setting is `org-speed-command-default-hook'."
17315 :group 'org-structure
17316 :type 'hook)
17318 (defun org-self-insert-command (N)
17319 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17320 If the cursor is in a table looking at whitespace, the whitespace is
17321 overwritten, and the table is not marked as requiring realignment."
17322 (interactive "p")
17323 (cond
17324 ((and org-use-speed-commands
17325 (setq org-speed-command
17326 (run-hook-with-args-until-success
17327 'org-speed-command-hook (this-command-keys))))
17328 (cond
17329 ((commandp org-speed-command)
17330 (setq this-command org-speed-command)
17331 (call-interactively org-speed-command))
17332 ((functionp org-speed-command)
17333 (funcall org-speed-command))
17334 ((and org-speed-command (listp org-speed-command))
17335 (eval org-speed-command))
17336 (t (let (org-use-speed-commands)
17337 (call-interactively 'org-self-insert-command)))))
17338 ((and
17339 (org-table-p)
17340 (progn
17341 ;; check if we blank the field, and if that triggers align
17342 (and (featurep 'org-table) org-table-auto-blank-field
17343 (member last-command
17344 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17345 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17346 ;; got extra space, this field does not determine column width
17347 (let (org-table-may-need-update) (org-table-blank-field))
17348 ;; no extra space, this field may determine column width
17349 (org-table-blank-field)))
17351 (eq N 1)
17352 (looking-at "[^|\n]* |"))
17353 (let (org-table-may-need-update)
17354 (goto-char (1- (match-end 0)))
17355 (delete-char -1)
17356 (goto-char (match-beginning 0))
17357 (self-insert-command N)))
17359 (setq org-table-may-need-update t)
17360 (self-insert-command N)
17361 (org-fix-tags-on-the-fly)
17362 (if org-self-insert-cluster-for-undo
17363 (if (not (eq last-command 'org-self-insert-command))
17364 (setq org-self-insert-command-undo-counter 1)
17365 (if (>= org-self-insert-command-undo-counter 20)
17366 (setq org-self-insert-command-undo-counter 1)
17367 (and (> org-self-insert-command-undo-counter 0)
17368 buffer-undo-list (listp buffer-undo-list)
17369 (not (cadr buffer-undo-list)) ; remove nil entry
17370 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17371 (setq org-self-insert-command-undo-counter
17372 (1+ org-self-insert-command-undo-counter))))))))
17374 (defun org-fix-tags-on-the-fly ()
17375 (when (and (equal (char-after (point-at-bol)) ?*)
17376 (org-on-heading-p))
17377 (org-align-tags-here org-tags-column)))
17379 (defun org-delete-backward-char (N)
17380 "Like `delete-backward-char', insert whitespace at field end in tables.
17381 When deleting backwards, in tables this function will insert whitespace in
17382 front of the next \"|\" separator, to keep the table aligned. The table will
17383 still be marked for re-alignment if the field did fill the entire column,
17384 because, in this case the deletion might narrow the column."
17385 (interactive "p")
17386 (if (and (org-table-p)
17387 (eq N 1)
17388 (string-match "|" (buffer-substring (point-at-bol) (point)))
17389 (looking-at ".*?|"))
17390 (let ((pos (point))
17391 (noalign (looking-at "[^|\n\r]* |"))
17392 (c org-table-may-need-update))
17393 (backward-delete-char N)
17394 (if (not overwrite-mode)
17395 (progn
17396 (skip-chars-forward "^|")
17397 (insert " ")
17398 (goto-char (1- pos))))
17399 ;; noalign: if there were two spaces at the end, this field
17400 ;; does not determine the width of the column.
17401 (if noalign (setq org-table-may-need-update c)))
17402 (backward-delete-char N)
17403 (org-fix-tags-on-the-fly)))
17405 (defun org-delete-char (N)
17406 "Like `delete-char', but insert whitespace at field end in tables.
17407 When deleting characters, in tables this function will insert whitespace in
17408 front of the next \"|\" separator, to keep the table aligned. The table will
17409 still be marked for re-alignment if the field did fill the entire column,
17410 because, in this case the deletion might narrow the column."
17411 (interactive "p")
17412 (if (and (org-table-p)
17413 (not (bolp))
17414 (not (= (char-after) ?|))
17415 (eq N 1))
17416 (if (looking-at ".*?|")
17417 (let ((pos (point))
17418 (noalign (looking-at "[^|\n\r]* |"))
17419 (c org-table-may-need-update))
17420 (replace-match (concat
17421 (substring (match-string 0) 1 -1)
17422 " |"))
17423 (goto-char pos)
17424 ;; noalign: if there were two spaces at the end, this field
17425 ;; does not determine the width of the column.
17426 (if noalign (setq org-table-may-need-update c)))
17427 (delete-char N))
17428 (delete-char N)
17429 (org-fix-tags-on-the-fly)))
17431 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17432 (put 'org-self-insert-command 'delete-selection t)
17433 (put 'orgtbl-self-insert-command 'delete-selection t)
17434 (put 'org-delete-char 'delete-selection 'supersede)
17435 (put 'org-delete-backward-char 'delete-selection 'supersede)
17436 (put 'org-yank 'delete-selection 'yank)
17438 ;; Make `flyspell-mode' delay after some commands
17439 (put 'org-self-insert-command 'flyspell-delayed t)
17440 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17441 (put 'org-delete-char 'flyspell-delayed t)
17442 (put 'org-delete-backward-char 'flyspell-delayed t)
17444 ;; Make pabbrev-mode expand after org-mode commands
17445 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17446 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17448 ;; How to do this: Measure non-white length of current string
17449 ;; If equal to column width, we should realign.
17451 (defun org-remap (map &rest commands)
17452 "In MAP, remap the functions given in COMMANDS.
17453 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17454 (let (new old)
17455 (while commands
17456 (setq old (pop commands) new (pop commands))
17457 (if (fboundp 'command-remapping)
17458 (org-defkey map (vector 'remap old) new)
17459 (substitute-key-definition old new map global-map)))))
17461 (when (eq org-enable-table-editor 'optimized)
17462 ;; If the user wants maximum table support, we need to hijack
17463 ;; some standard editing functions
17464 (org-remap org-mode-map
17465 'self-insert-command 'org-self-insert-command
17466 'delete-char 'org-delete-char
17467 'delete-backward-char 'org-delete-backward-char)
17468 (org-defkey org-mode-map "|" 'org-force-self-insert))
17470 (defvar org-ctrl-c-ctrl-c-hook nil
17471 "Hook for functions attaching themselves to `C-c C-c'.
17473 This can be used to add additional functionality to the C-c C-c
17474 key which executes context-dependent commands. This hook is run
17475 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17476 run after the last test.
17478 Each function will be called with no arguments. The function
17479 must check if the context is appropriate for it to act. If yes,
17480 it should do its thing and then return a non-nil value. If the
17481 context is wrong, just do nothing and return nil.")
17483 (defvar org-ctrl-c-ctrl-c-final-hook nil
17484 "Hook for functions attaching themselves to `C-c C-c'.
17486 This can be used to add additional functionality to the C-c C-c
17487 key which executes context-dependent commands. This hook is run
17488 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17489 before the first test.
17491 Each function will be called with no arguments. The function
17492 must check if the context is appropriate for it to act. If yes,
17493 it should do its thing and then return a non-nil value. If the
17494 context is wrong, just do nothing and return nil.")
17496 (defvar org-tab-first-hook nil
17497 "Hook for functions to attach themselves to TAB.
17498 See `org-ctrl-c-ctrl-c-hook' for more information.
17499 This hook runs as the first action when TAB is pressed, even before
17500 `org-cycle' messes around with the `outline-regexp' to cater for
17501 inline tasks and plain list item folding.
17502 If any function in this hook returns t, any other actions that
17503 would have been caused by TAB (such as table field motion or visibility
17504 cycling) will not occur.")
17506 (defvar org-tab-after-check-for-table-hook nil
17507 "Hook for functions to attach themselves to TAB.
17508 See `org-ctrl-c-ctrl-c-hook' for more information.
17509 This hook runs after it has been established that the cursor is not in a
17510 table, but before checking if the cursor is in a headline or if global cycling
17511 should be done.
17512 If any function in this hook returns t, not other actions like visibility
17513 cycling will be done.")
17515 (defvar org-tab-after-check-for-cycling-hook nil
17516 "Hook for functions to attach themselves to TAB.
17517 See `org-ctrl-c-ctrl-c-hook' for more information.
17518 This hook runs after it has been established that not table field motion and
17519 not visibility should be done because of current context. This is probably
17520 the place where a package like yasnippets can hook in.")
17522 (defvar org-tab-before-tab-emulation-hook nil
17523 "Hook for functions to attach themselves to TAB.
17524 See `org-ctrl-c-ctrl-c-hook' for more information.
17525 This hook runs after every other options for TAB have been exhausted, but
17526 before indentation and \t insertion takes place.")
17528 (defvar org-metaleft-hook nil
17529 "Hook for functions attaching themselves to `M-left'.
17530 See `org-ctrl-c-ctrl-c-hook' for more information.")
17531 (defvar org-metaright-hook nil
17532 "Hook for functions attaching themselves to `M-right'.
17533 See `org-ctrl-c-ctrl-c-hook' for more information.")
17534 (defvar org-metaup-hook nil
17535 "Hook for functions attaching themselves to `M-up'.
17536 See `org-ctrl-c-ctrl-c-hook' for more information.")
17537 (defvar org-metadown-hook nil
17538 "Hook for functions attaching themselves to `M-down'.
17539 See `org-ctrl-c-ctrl-c-hook' for more information.")
17540 (defvar org-shiftmetaleft-hook nil
17541 "Hook for functions attaching themselves to `M-S-left'.
17542 See `org-ctrl-c-ctrl-c-hook' for more information.")
17543 (defvar org-shiftmetaright-hook nil
17544 "Hook for functions attaching themselves to `M-S-right'.
17545 See `org-ctrl-c-ctrl-c-hook' for more information.")
17546 (defvar org-shiftmetaup-hook nil
17547 "Hook for functions attaching themselves to `M-S-up'.
17548 See `org-ctrl-c-ctrl-c-hook' for more information.")
17549 (defvar org-shiftmetadown-hook nil
17550 "Hook for functions attaching themselves to `M-S-down'.
17551 See `org-ctrl-c-ctrl-c-hook' for more information.")
17552 (defvar org-metareturn-hook nil
17553 "Hook for functions attaching themselves to `M-RET'.
17554 See `org-ctrl-c-ctrl-c-hook' for more information.")
17555 (defvar org-shiftup-hook nil
17556 "Hook for functions attaching themselves to `S-up'.
17557 See `org-ctrl-c-ctrl-c-hook' for more information.")
17558 (defvar org-shiftup-final-hook nil
17559 "Hook for functions attaching themselves to `S-up'.
17560 This one runs after all other options except shift-select have been excluded.
17561 See `org-ctrl-c-ctrl-c-hook' for more information.")
17562 (defvar org-shiftdown-hook nil
17563 "Hook for functions attaching themselves to `S-down'.
17564 See `org-ctrl-c-ctrl-c-hook' for more information.")
17565 (defvar org-shiftdown-final-hook nil
17566 "Hook for functions attaching themselves to `S-down'.
17567 This one runs after all other options except shift-select have been excluded.
17568 See `org-ctrl-c-ctrl-c-hook' for more information.")
17569 (defvar org-shiftleft-hook nil
17570 "Hook for functions attaching themselves to `S-left'.
17571 See `org-ctrl-c-ctrl-c-hook' for more information.")
17572 (defvar org-shiftleft-final-hook nil
17573 "Hook for functions attaching themselves to `S-left'.
17574 This one runs after all other options except shift-select have been excluded.
17575 See `org-ctrl-c-ctrl-c-hook' for more information.")
17576 (defvar org-shiftright-hook nil
17577 "Hook for functions attaching themselves to `S-right'.
17578 See `org-ctrl-c-ctrl-c-hook' for more information.")
17579 (defvar org-shiftright-final-hook nil
17580 "Hook for functions attaching themselves to `S-right'.
17581 This one runs after all other options except shift-select have been excluded.
17582 See `org-ctrl-c-ctrl-c-hook' for more information.")
17584 (defun org-modifier-cursor-error ()
17585 "Throw an error, a modified cursor command was applied in wrong context."
17586 (error "This command is active in special context like tables, headlines or items"))
17588 (defun org-shiftselect-error ()
17589 "Throw an error because Shift-Cursor command was applied in wrong context."
17590 (if (and (boundp 'shift-select-mode) shift-select-mode)
17591 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17592 (error "This command works only in special context like headlines or timestamps")))
17594 (defun org-call-for-shift-select (cmd)
17595 (let ((this-command-keys-shift-translated t))
17596 (call-interactively cmd)))
17598 (defun org-shifttab (&optional arg)
17599 "Global visibility cycling or move to previous table field.
17600 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17601 on context.
17602 See the individual commands for more information."
17603 (interactive "P")
17604 (cond
17605 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17606 ((integerp arg)
17607 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17608 (message "Content view to level: %d" arg)
17609 (org-content (prefix-numeric-value arg2))
17610 (setq org-cycle-global-status 'overview)))
17611 (t (call-interactively 'org-global-cycle))))
17613 (defun org-shiftmetaleft ()
17614 "Promote subtree or delete table column.
17615 Calls `org-promote-subtree', `org-outdent-item',
17616 or `org-table-delete-column', depending on context.
17617 See the individual commands for more information."
17618 (interactive)
17619 (cond
17620 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17621 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17622 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17623 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17624 (t (org-modifier-cursor-error))))
17626 (defun org-shiftmetaright ()
17627 "Demote subtree or insert table column.
17628 Calls `org-demote-subtree', `org-indent-item',
17629 or `org-table-insert-column', depending on context.
17630 See the individual commands for more information."
17631 (interactive)
17632 (cond
17633 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17634 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17635 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17636 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17637 (t (org-modifier-cursor-error))))
17639 (defun org-shiftmetaup (&optional arg)
17640 "Move subtree up or kill table row.
17641 Calls `org-move-subtree-up' or `org-table-kill-row' or
17642 `org-move-item-up' depending on context. See the individual commands
17643 for more information."
17644 (interactive "P")
17645 (cond
17646 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17647 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17648 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17649 ((org-at-item-p) (call-interactively 'org-move-item-up))
17650 (t (org-modifier-cursor-error))))
17652 (defun org-shiftmetadown (&optional arg)
17653 "Move subtree down or insert table row.
17654 Calls `org-move-subtree-down' or `org-table-insert-row' or
17655 `org-move-item-down', depending on context. See the individual
17656 commands for more information."
17657 (interactive "P")
17658 (cond
17659 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17660 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17661 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17662 ((org-at-item-p) (call-interactively 'org-move-item-down))
17663 (t (org-modifier-cursor-error))))
17665 (defsubst org-hidden-tree-error ()
17666 (error
17667 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17669 (defun org-metaleft (&optional arg)
17670 "Promote heading or move table column to left.
17671 Calls `org-do-promote' or `org-table-move-column', depending on context.
17672 With no specific context, calls the Emacs default `backward-word'.
17673 See the individual commands for more information."
17674 (interactive "P")
17675 (cond
17676 ((run-hook-with-args-until-success 'org-metaleft-hook))
17677 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17678 ((org-with-limited-levels
17679 (or (org-on-heading-p)
17680 (and (org-region-active-p)
17681 (save-excursion
17682 (goto-char (region-beginning))
17683 (org-on-heading-p)))))
17684 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17685 (call-interactively 'org-do-promote))
17686 ;; At an inline task.
17687 ((org-on-heading-p)
17688 (call-interactively 'org-inlinetask-promote))
17689 ((or (org-at-item-p)
17690 (and (org-region-active-p)
17691 (save-excursion
17692 (goto-char (region-beginning))
17693 (org-at-item-p))))
17694 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17695 (call-interactively 'org-outdent-item))
17696 (t (call-interactively 'backward-word))))
17698 (defun org-metaright (&optional arg)
17699 "Demote subtree or move table column to right.
17700 Calls `org-do-demote' or `org-table-move-column', depending on context.
17701 With no specific context, calls the Emacs default `forward-word'.
17702 See the individual commands for more information."
17703 (interactive "P")
17704 (cond
17705 ((run-hook-with-args-until-success 'org-metaright-hook))
17706 ((org-at-table-p) (call-interactively 'org-table-move-column))
17707 ((org-with-limited-levels
17708 (or (org-on-heading-p)
17709 (and (org-region-active-p)
17710 (save-excursion
17711 (goto-char (region-beginning))
17712 (org-on-heading-p)))))
17713 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17714 (call-interactively 'org-do-demote))
17715 ;; At an inline task.
17716 ((org-on-heading-p)
17717 (call-interactively 'org-inlinetask-demote))
17718 ((or (org-at-item-p)
17719 (and (org-region-active-p)
17720 (save-excursion
17721 (goto-char (region-beginning))
17722 (org-at-item-p))))
17723 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17724 (call-interactively 'org-indent-item))
17725 (t (call-interactively 'forward-word))))
17727 (defun org-check-for-hidden (what)
17728 "Check if there are hidden headlines/items in the current visual line.
17729 WHAT can be either `headlines' or `items'. If the current line is
17730 an outline or item heading and it has a folded subtree below it,
17731 this function returns t, nil otherwise."
17732 (let ((re (cond
17733 ((eq what 'headlines) org-outline-regexp-bol)
17734 ((eq what 'items) (org-item-beginning-re))
17735 (t (error "This should not happen"))))
17736 beg end)
17737 (save-excursion
17738 (catch 'exit
17739 (unless (org-region-active-p)
17740 (setq beg (point-at-bol))
17741 (beginning-of-line 2)
17742 (while (and (not (eobp)) ;; this is like `next-line'
17743 (get-char-property (1- (point)) 'invisible))
17744 (beginning-of-line 2))
17745 (setq end (point))
17746 (goto-char beg)
17747 (goto-char (point-at-eol))
17748 (setq end (max end (point)))
17749 (while (re-search-forward re end t)
17750 (if (get-char-property (match-beginning 0) 'invisible)
17751 (throw 'exit t))))
17752 nil))))
17754 (defun org-metaup (&optional arg)
17755 "Move subtree up or move table row up.
17756 Calls `org-move-subtree-up' or `org-table-move-row' or
17757 `org-move-item-up', depending on context. See the individual commands
17758 for more information."
17759 (interactive "P")
17760 (cond
17761 ((run-hook-with-args-until-success 'org-metaup-hook))
17762 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17763 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17764 ((org-at-item-p) (call-interactively 'org-move-item-up))
17765 (t (transpose-lines 1) (beginning-of-line -1))))
17767 (defun org-metadown (&optional arg)
17768 "Move subtree down or move table row down.
17769 Calls `org-move-subtree-down' or `org-table-move-row' or
17770 `org-move-item-down', depending on context. See the individual
17771 commands for more information."
17772 (interactive "P")
17773 (cond
17774 ((run-hook-with-args-until-success 'org-metadown-hook))
17775 ((org-at-table-p) (call-interactively 'org-table-move-row))
17776 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17777 ((org-at-item-p) (call-interactively 'org-move-item-down))
17778 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17780 (defun org-shiftup (&optional arg)
17781 "Increase item in timestamp or increase priority of current headline.
17782 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17783 depending on context. See the individual commands for more information."
17784 (interactive "P")
17785 (cond
17786 ((run-hook-with-args-until-success 'org-shiftup-hook))
17787 ((and org-support-shift-select (org-region-active-p))
17788 (org-call-for-shift-select 'previous-line))
17789 ((org-at-timestamp-p t)
17790 (call-interactively (if org-edit-timestamp-down-means-later
17791 'org-timestamp-down 'org-timestamp-up)))
17792 ((and (not (eq org-support-shift-select 'always))
17793 org-enable-priority-commands
17794 (org-on-heading-p))
17795 (call-interactively 'org-priority-up))
17796 ((and (not org-support-shift-select) (org-at-item-p))
17797 (call-interactively 'org-previous-item))
17798 ((org-clocktable-try-shift 'up arg))
17799 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17800 (org-support-shift-select
17801 (org-call-for-shift-select 'previous-line))
17802 (t (org-shiftselect-error))))
17804 (defun org-shiftdown (&optional arg)
17805 "Decrease item in timestamp or decrease priority of current headline.
17806 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17807 depending on context. See the individual commands for more information."
17808 (interactive "P")
17809 (cond
17810 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17811 ((and org-support-shift-select (org-region-active-p))
17812 (org-call-for-shift-select 'next-line))
17813 ((org-at-timestamp-p t)
17814 (call-interactively (if org-edit-timestamp-down-means-later
17815 'org-timestamp-up 'org-timestamp-down)))
17816 ((and (not (eq org-support-shift-select 'always))
17817 org-enable-priority-commands
17818 (org-on-heading-p))
17819 (call-interactively 'org-priority-down))
17820 ((and (not org-support-shift-select) (org-at-item-p))
17821 (call-interactively 'org-next-item))
17822 ((org-clocktable-try-shift 'down arg))
17823 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17824 (org-support-shift-select
17825 (org-call-for-shift-select 'next-line))
17826 (t (org-shiftselect-error))))
17828 (defun org-shiftright (&optional arg)
17829 "Cycle the thing at point or in the current line, depending on context.
17830 Depending on context, this does one of the following:
17832 - switch a timestamp at point one day into the future
17833 - on a headline, switch to the next TODO keyword.
17834 - on an item, switch entire list to the next bullet type
17835 - on a property line, switch to the next allowed value
17836 - on a clocktable definition line, move time block into the future"
17837 (interactive "P")
17838 (cond
17839 ((run-hook-with-args-until-success 'org-shiftright-hook))
17840 ((and org-support-shift-select (org-region-active-p))
17841 (org-call-for-shift-select 'forward-char))
17842 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17843 ((and (not (eq org-support-shift-select 'always))
17844 (org-on-heading-p))
17845 (let ((org-inhibit-logging
17846 (not org-treat-S-cursor-todo-selection-as-state-change))
17847 (org-inhibit-blocking
17848 (not org-treat-S-cursor-todo-selection-as-state-change)))
17849 (org-call-with-arg 'org-todo 'right)))
17850 ((or (and org-support-shift-select
17851 (not (eq org-support-shift-select 'always))
17852 (org-at-item-bullet-p))
17853 (and (not org-support-shift-select) (org-at-item-p)))
17854 (org-call-with-arg 'org-cycle-list-bullet nil))
17855 ((and (not (eq org-support-shift-select 'always))
17856 (org-at-property-p))
17857 (call-interactively 'org-property-next-allowed-value))
17858 ((org-clocktable-try-shift 'right arg))
17859 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17860 (org-support-shift-select
17861 (org-call-for-shift-select 'forward-char))
17862 (t (org-shiftselect-error))))
17864 (defun org-shiftleft (&optional arg)
17865 "Cycle the thing at point or in the current line, depending on context.
17866 Depending on context, this does one of the following:
17868 - switch a timestamp at point one day into the past
17869 - on a headline, switch to the previous TODO keyword.
17870 - on an item, switch entire list to the previous bullet type
17871 - on a property line, switch to the previous allowed value
17872 - on a clocktable definition line, move time block into the past"
17873 (interactive "P")
17874 (cond
17875 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17876 ((and org-support-shift-select (org-region-active-p))
17877 (org-call-for-shift-select 'backward-char))
17878 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17879 ((and (not (eq org-support-shift-select 'always))
17880 (org-on-heading-p))
17881 (let ((org-inhibit-logging
17882 (not org-treat-S-cursor-todo-selection-as-state-change))
17883 (org-inhibit-blocking
17884 (not org-treat-S-cursor-todo-selection-as-state-change)))
17885 (org-call-with-arg 'org-todo 'left)))
17886 ((or (and org-support-shift-select
17887 (not (eq org-support-shift-select 'always))
17888 (org-at-item-bullet-p))
17889 (and (not org-support-shift-select) (org-at-item-p)))
17890 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17891 ((and (not (eq org-support-shift-select 'always))
17892 (org-at-property-p))
17893 (call-interactively 'org-property-previous-allowed-value))
17894 ((org-clocktable-try-shift 'left arg))
17895 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17896 (org-support-shift-select
17897 (org-call-for-shift-select 'backward-char))
17898 (t (org-shiftselect-error))))
17900 (defun org-shiftcontrolright ()
17901 "Switch to next TODO set."
17902 (interactive)
17903 (cond
17904 ((and org-support-shift-select (org-region-active-p))
17905 (org-call-for-shift-select 'forward-word))
17906 ((and (not (eq org-support-shift-select 'always))
17907 (org-on-heading-p))
17908 (org-call-with-arg 'org-todo 'nextset))
17909 (org-support-shift-select
17910 (org-call-for-shift-select 'forward-word))
17911 (t (org-shiftselect-error))))
17913 (defun org-shiftcontrolleft ()
17914 "Switch to previous TODO set."
17915 (interactive)
17916 (cond
17917 ((and org-support-shift-select (org-region-active-p))
17918 (org-call-for-shift-select 'backward-word))
17919 ((and (not (eq org-support-shift-select 'always))
17920 (org-on-heading-p))
17921 (org-call-with-arg 'org-todo 'previousset))
17922 (org-support-shift-select
17923 (org-call-for-shift-select 'backward-word))
17924 (t (org-shiftselect-error))))
17926 (defun org-shiftcontrolup ()
17927 "Change timestamps synchronously up in CLOCK log lines."
17928 (interactive)
17929 (cond ((and (not org-support-shift-select)
17930 (org-at-clock-log-p)
17931 (org-at-timestamp-p t))
17932 (org-clock-timestamps-up))
17933 (t (org-shiftselect-error))))
17935 (defun org-shiftcontroldown ()
17936 "Change timestamps synchronously down in CLOCK log lines."
17937 (interactive)
17938 (cond ((and (not org-support-shift-select)
17939 (org-at-clock-log-p)
17940 (org-at-timestamp-p t))
17941 (org-clock-timestamps-down))
17942 (t (org-shiftselect-error))))
17944 (defun org-ctrl-c-ret ()
17945 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17946 (interactive)
17947 (cond
17948 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17949 (t (call-interactively 'org-insert-heading))))
17951 (defun org-find-visible ()
17952 (let ((s (point)))
17953 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17954 (get-char-property s 'invisible)))
17956 (defun org-find-invisible ()
17957 (let ((s (point)))
17958 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17959 (not (get-char-property s 'invisible))))
17962 (defun org-copy-visible (beg end)
17963 "Copy the visible parts of the region."
17964 (interactive "r")
17965 (let (snippets s)
17966 (save-excursion
17967 (save-restriction
17968 (narrow-to-region beg end)
17969 (setq s (goto-char (point-min)))
17970 (while (not (= (point) (point-max)))
17971 (goto-char (org-find-invisible))
17972 (push (buffer-substring s (point)) snippets)
17973 (setq s (goto-char (org-find-visible))))))
17974 (kill-new (apply 'concat (nreverse snippets)))))
17976 (defun org-copy-special ()
17977 "Copy region in table or copy current subtree.
17978 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17979 See the individual commands for more information."
17980 (interactive)
17981 (call-interactively
17982 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17984 (defun org-cut-special ()
17985 "Cut region in table or cut current subtree.
17986 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17987 See the individual commands for more information."
17988 (interactive)
17989 (call-interactively
17990 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17992 (defun org-paste-special (arg)
17993 "Paste rectangular region into table, or past subtree relative to level.
17994 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17995 See the individual commands for more information."
17996 (interactive "P")
17997 (if (org-at-table-p)
17998 (org-table-paste-rectangle)
17999 (org-paste-subtree arg)))
18001 (defun org-edit-special (&optional arg)
18002 "Call a special editor for the stuff at point.
18003 When at a table, call the formula editor with `org-table-edit-formulas'.
18004 When at the first line of an src example, call `org-edit-src-code'.
18005 When in an #+include line, visit the include file. Otherwise call
18006 `ffap' to visit the file at point."
18007 (interactive)
18008 ;; possibly prep session before editing source
18009 (when arg
18010 (let* ((info (org-babel-get-src-block-info))
18011 (lang (nth 0 info))
18012 (params (nth 2 info))
18013 (session (cdr (assoc :session params))))
18014 (when (and info session) ;; we are in a source-code block with a session
18015 (funcall
18016 (intern (concat "org-babel-prep-session:" lang)) session params))))
18017 (cond ;; proceed with `org-edit-special'
18018 ((save-excursion
18019 (beginning-of-line 1)
18020 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18021 (find-file (org-trim (match-string 1))))
18022 ((org-edit-src-code))
18023 ((org-edit-fixed-width-region))
18024 ((org-at-table.el-p)
18025 (org-edit-src-code))
18026 ((or (org-at-table-p)
18027 (save-excursion
18028 (beginning-of-line 1)
18029 (looking-at "[ \t]*#\\+TBLFM:")))
18030 (call-interactively 'org-table-edit-formulas))
18031 (t (call-interactively 'ffap))))
18033 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18034 (defun org-ctrl-c-ctrl-c (&optional arg)
18035 "Set tags in headline, or update according to changed information at point.
18037 This command does many different things, depending on context:
18039 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18040 this is what we do.
18042 - If the cursor is on a statistics cookie, update it.
18044 - If the cursor is in a headline, prompt for tags and insert them
18045 into the current line, aligned to `org-tags-column'. When called
18046 with prefix arg, realign all tags in the current buffer.
18048 - If the cursor is in one of the special #+KEYWORD lines, this
18049 triggers scanning the buffer for these lines and updating the
18050 information.
18052 - If the cursor is inside a table, realign the table. This command
18053 works even if the automatic table editor has been turned off.
18055 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18056 the entire table.
18058 - If the cursor is at a footnote reference or definition, jump to
18059 the corresponding definition or references, respectively.
18061 - If the cursor is a the beginning of a dynamic block, update it.
18063 - If the current buffer is a capture buffer, close note and file it.
18065 - If the cursor is on a <<<target>>>, update radio targets and
18066 corresponding links in this buffer.
18068 - If the cursor is on a numbered item in a plain list, renumber the
18069 ordered list.
18071 - If the cursor is on a checkbox, toggle it.
18073 - If the cursor is on a code block, evaluate it. The variable
18074 `org-confirm-babel-evaluate' can be used to control prompting
18075 before code block evaluation, by default every code block
18076 evaluation requires confirmation. Code block evaluation can be
18077 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18078 (interactive "P")
18079 (let ((org-enable-table-editor t))
18080 (cond
18081 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18082 org-occur-highlights
18083 org-latex-fragment-image-overlays)
18084 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18085 (org-remove-occur-highlights)
18086 (org-remove-latex-fragment-image-overlays)
18087 (message "Temporary highlights/overlays removed from current buffer"))
18088 ((and (local-variable-p 'org-finish-function (current-buffer))
18089 (fboundp org-finish-function))
18090 (funcall org-finish-function))
18091 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18092 ((or (looking-at org-property-start-re)
18093 (org-at-property-p))
18094 (call-interactively 'org-property-action))
18095 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18096 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18097 (or (org-on-heading-p) (org-at-item-p)))
18098 (call-interactively 'org-update-statistics-cookies))
18099 ((org-on-heading-p) (call-interactively 'org-set-tags))
18100 ((org-at-table.el-p)
18101 (message "Use C-c ' to edit table.el tables"))
18102 ((org-at-table-p)
18103 (org-table-maybe-eval-formula)
18104 (if arg
18105 (call-interactively 'org-table-recalculate)
18106 (org-table-maybe-recalculate-line))
18107 (call-interactively 'org-table-align)
18108 (orgtbl-send-table 'maybe))
18109 ((or (org-footnote-at-reference-p)
18110 (org-footnote-at-definition-p))
18111 (call-interactively 'org-footnote-action))
18112 ((org-at-item-checkbox-p)
18113 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18114 ;; list only if at top item.
18115 (let* ((cbox (match-string 1))
18116 (struct (org-list-struct))
18117 (old-struct (copy-tree struct))
18118 (parents (org-list-parents-alist struct))
18119 (orderedp (org-entry-get nil "ORDERED"))
18120 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18121 block-item)
18122 ;; Use a light version of `org-toggle-checkbox' to avoid
18123 ;; computing list structure twice.
18124 (org-list-set-checkbox (point-at-bol) struct
18125 (cond
18126 ((equal arg '(16)) "[-]")
18127 ((equal arg '(4)) nil)
18128 ((equal "[X]" cbox) "[ ]")
18129 (t "[X]")))
18130 ;; Replicate `org-list-write-struct', while grabbing a return
18131 ;; value from `org-list-struct-fix-box'.
18132 (org-list-struct-fix-ind struct parents 2)
18133 (org-list-struct-fix-item-end struct)
18134 (let ((prevs (org-list-prevs-alist struct)))
18135 (org-list-struct-fix-bul struct prevs)
18136 (org-list-struct-fix-ind struct parents)
18137 (setq block-item
18138 (org-list-struct-fix-box struct parents prevs orderedp)))
18139 (org-list-struct-apply-struct struct old-struct)
18140 (org-update-checkbox-count-maybe)
18141 (when block-item
18142 (message
18143 "Checkboxes were removed due to unchecked box at line %d"
18144 (org-current-line block-item)))
18145 (when firstp (org-list-send-list 'maybe))))
18146 ((org-at-item-p)
18147 ;; Cursor at an item: repair list. Do checkbox related actions
18148 ;; only if function was called with an argument. Send list only
18149 ;; if at top item.
18150 (let* ((struct (org-list-struct))
18151 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18152 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18153 (org-list-write-struct struct (org-list-parents-alist struct))
18154 (when arg (org-update-checkbox-count-maybe))
18155 (when firstp (org-list-send-list 'maybe))))
18156 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18157 ;; Dynamic block
18158 (beginning-of-line 1)
18159 (save-excursion (org-update-dblock)))
18160 ((save-excursion
18161 (beginning-of-line 1)
18162 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18163 (cond
18164 ((equal (match-string 1) "TBLFM")
18165 ;; Recalculate the table before this line
18166 (save-excursion
18167 (beginning-of-line 1)
18168 (skip-chars-backward " \r\n\t")
18169 (if (org-at-table-p)
18170 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18172 (let ((org-inhibit-startup-visibility-stuff t)
18173 (org-startup-align-all-tables nil))
18174 (when (boundp 'org-table-coordinate-overlays)
18175 (mapc 'delete-overlay org-table-coordinate-overlays)
18176 (setq org-table-coordinate-overlays nil))
18177 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18178 (message "Local setup has been refreshed"))))
18179 ((org-clock-update-time-maybe))
18181 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18182 (error "C-c C-c can do nothing useful at this location"))))))
18184 (defun org-mode-restart ()
18185 "Restart Org-mode, to scan again for special lines.
18186 Also updates the keyword regular expressions."
18187 (interactive)
18188 (org-mode)
18189 (message "Org-mode restarted"))
18191 (defun org-kill-note-or-show-branches ()
18192 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18193 (interactive)
18194 (if (not org-finish-function)
18195 (progn
18196 (hide-subtree)
18197 (call-interactively 'show-branches))
18198 (let ((org-note-abort t))
18199 (funcall org-finish-function))))
18201 (defun org-return (&optional indent)
18202 "Goto next table row or insert a newline.
18203 Calls `org-table-next-row' or `newline', depending on context.
18204 See the individual commands for more information."
18205 (interactive)
18206 (cond
18207 ((bobp) (if indent (newline-and-indent) (newline)))
18208 ((org-at-table-p)
18209 (org-table-justify-field-maybe)
18210 (call-interactively 'org-table-next-row))
18211 ;; when `newline-and-indent' is called within a list, make sure
18212 ;; text moved stays inside the item.
18213 ((and (org-in-item-p) indent)
18214 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18215 (progn
18216 (save-match-data (newline))
18217 (org-indent-line-to (length (match-string 0))))
18218 (let ((ind (org-get-indentation)))
18219 (newline)
18220 (if (org-looking-back org-list-end-re)
18221 (org-indent-line-function)
18222 (org-indent-line-to ind)))))
18223 ((and org-return-follows-link
18224 (eq (get-text-property (point) 'face) 'org-link))
18225 (call-interactively 'org-open-at-point))
18226 ((and (org-at-heading-p)
18227 (looking-at
18228 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18229 (org-show-entry)
18230 (end-of-line 1)
18231 (newline))
18232 (t (if indent (newline-and-indent) (newline)))))
18234 (defun org-return-indent ()
18235 "Goto next table row or insert a newline and indent.
18236 Calls `org-table-next-row' or `newline-and-indent', depending on
18237 context. See the individual commands for more information."
18238 (interactive)
18239 (org-return t))
18241 (defun org-ctrl-c-star ()
18242 "Compute table, or change heading status of lines.
18243 Calls `org-table-recalculate' or `org-toggle-heading',
18244 depending on context."
18245 (interactive)
18246 (cond
18247 ((org-at-table-p)
18248 (call-interactively 'org-table-recalculate))
18250 ;; Convert all lines in region to list items
18251 (call-interactively 'org-toggle-heading))))
18253 (defun org-ctrl-c-minus ()
18254 "Insert separator line in table or modify bullet status of line.
18255 Also turns a plain line or a region of lines into list items.
18256 Calls `org-table-insert-hline', `org-toggle-item', or
18257 `org-cycle-list-bullet', depending on context."
18258 (interactive)
18259 (cond
18260 ((org-at-table-p)
18261 (call-interactively 'org-table-insert-hline))
18262 ((org-region-active-p)
18263 (call-interactively 'org-toggle-item))
18264 ((org-in-item-p)
18265 (call-interactively 'org-cycle-list-bullet))
18267 (call-interactively 'org-toggle-item))))
18269 (defun org-toggle-item (arg)
18270 "Convert headings or normal lines to items, items to normal lines.
18271 If there is no active region, only the current line is considered.
18273 If the first non blank line in the region is an headline, convert
18274 all headlines to items, shifting text accordingly.
18276 If it is an item, convert all items to normal lines.
18278 If it is normal text, change region into an item. With a prefix
18279 argument ARG, change each line in region into an item."
18280 (interactive "P")
18281 (let ((shift-text
18282 (function
18283 ;; Shift text in current section to IND, from point to END.
18284 ;; The function leaves point to END line.
18285 (lambda (ind end)
18286 (let ((min-i 1000) (end (copy-marker end)))
18287 ;; First determine the minimum indentation (MIN-I) of
18288 ;; the text.
18289 (save-excursion
18290 (catch 'exit
18291 (while (< (point) end)
18292 (let ((i (org-get-indentation)))
18293 (cond
18294 ;; Skip blank lines and inline tasks.
18295 ((looking-at "^[ \t]*$"))
18296 ((looking-at org-outline-regexp-bol))
18297 ;; We can't find less than 0 indentation.
18298 ((zerop i) (throw 'exit (setq min-i 0)))
18299 ((< i min-i) (setq min-i i))))
18300 (forward-line))))
18301 ;; Then indent each line so that a line indented to
18302 ;; MIN-I becomes indented to IND. Ignore blank lines
18303 ;; and inline tasks in the process.
18304 (let ((delta (- ind min-i)))
18305 (while (< (point) end)
18306 (unless (or (looking-at "^[ \t]*$")
18307 (looking-at org-outline-regexp-bol))
18308 (org-indent-line-to (+ (org-get-indentation) delta)))
18309 (forward-line)))))))
18310 (skip-blanks
18311 (function
18312 ;; Return beginning of first non-blank line, starting from
18313 ;; line at POS.
18314 (lambda (pos)
18315 (save-excursion
18316 (goto-char pos)
18317 (skip-chars-forward " \r\t\n")
18318 (point-at-bol)))))
18319 beg end)
18320 ;; Determine boundaries of changes.
18321 (if (org-region-active-p)
18322 (setq beg (funcall skip-blanks (region-beginning))
18323 end (copy-marker (region-end)))
18324 (setq beg (funcall skip-blanks (point-at-bol))
18325 end (copy-marker (point-at-eol))))
18326 ;; Depending on the starting line, choose an action on the text
18327 ;; between BEG and END.
18328 (org-with-limited-levels
18329 (save-excursion
18330 (goto-char beg)
18331 (cond
18332 ;; Case 1. Start at an item: de-itemize. Note that it only
18333 ;; happens when a region is active: `org-ctrl-c-minus'
18334 ;; would call `org-cycle-list-bullet' otherwise.
18335 ((org-at-item-p)
18336 (while (< (point) end)
18337 (when (org-at-item-p)
18338 (skip-chars-forward " \t")
18339 (delete-region (point) (match-end 0)))
18340 (forward-line)))
18341 ;; Case 2. Start at an heading: convert to items.
18342 ((org-on-heading-p)
18343 (let* ((bul (org-list-bullet-string "-"))
18344 (bul-len (length bul))
18345 ;; Indentation of the first heading. It should be
18346 ;; relative to the indentation of its parent, if any.
18347 (start-ind (save-excursion
18348 (cond
18349 ((not org-adapt-indentation) 0)
18350 ((not (outline-previous-heading)) 0)
18351 (t (length (match-string 0))))))
18352 ;; Level of first heading. Further headings will be
18353 ;; compared to it to determine hierarchy in the list.
18354 (ref-level (org-reduced-level (org-outline-level))))
18355 (while (< (point) end)
18356 (let* ((level (org-reduced-level (org-outline-level)))
18357 (delta (max 0 (- level ref-level))))
18358 ;; If current headline is less indented than the first
18359 ;; one, set it as reference, in order to preserve
18360 ;; subtrees.
18361 (when (< level ref-level) (setq ref-level level))
18362 (replace-match bul t t)
18363 (org-indent-line-to (+ start-ind (* delta bul-len)))
18364 ;; Ensure all text down to END (or SECTION-END) belongs
18365 ;; to the newly created item.
18366 (let ((section-end (save-excursion
18367 (or (outline-next-heading) (point)))))
18368 (forward-line)
18369 (funcall shift-text
18370 (+ start-ind (* (1+ delta) bul-len))
18371 (min end section-end)))))))
18372 ;; Case 3. Normal line with ARG: turn each non-item line into
18373 ;; an item.
18374 (arg
18375 (while (< (point) end)
18376 (unless (or (org-on-heading-p) (org-at-item-p))
18377 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18378 (replace-match
18379 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18380 (forward-line)))
18381 ;; Case 4. Normal line without ARG: make the first line of
18382 ;; region an item, and shift indentation of others
18383 ;; lines to set them as item's body.
18384 (t (let* ((bul (org-list-bullet-string "-"))
18385 (bul-len (length bul))
18386 (ref-ind (org-get-indentation)))
18387 (skip-chars-forward " \t")
18388 (insert bul)
18389 (forward-line)
18390 (while (< (point) end)
18391 ;; Ensure that lines less indented than first one
18392 ;; still get included in item body.
18393 (funcall shift-text
18394 (+ ref-ind bul-len)
18395 (min end (save-excursion (or (outline-next-heading)
18396 (point)))))
18397 (forward-line)))))))))
18399 (defun org-toggle-heading (&optional nstars)
18400 "Convert headings to normal text, or items or text to headings.
18401 If there is no active region, only the current line is considered.
18403 If the first non blank line is an headline, remove the stars from
18404 all headlines in the region.
18406 If it is a plain list item, turn all plain list items into headings.
18408 If it is a normal line, turn each and every normal line (i.e. not
18409 an heading or an item) in the region into a heading.
18411 When converting a line into a heading, the number of stars is chosen
18412 such that the lines become children of the current entry. However,
18413 when a prefix argument is given, its value determines the number of
18414 stars to add."
18415 (interactive "P")
18416 (let ((skip-blanks
18417 (function
18418 ;; Return beginning of first non-blank line, starting from
18419 ;; line at POS.
18420 (lambda (pos)
18421 (save-excursion
18422 (goto-char pos)
18423 (skip-chars-forward " \r\t\n")
18424 (point-at-bol)))))
18425 beg end)
18426 ;; Determine boundaries of changes. If region ends at a bol, do
18427 ;; not consider the last line to be in the region.
18428 (if (org-region-active-p)
18429 (setq beg (funcall skip-blanks (region-beginning))
18430 end (copy-marker (save-excursion
18431 (goto-char (region-end))
18432 (if (bolp) (point) (point-at-eol)))))
18433 (setq beg (funcall skip-blanks (point-at-bol))
18434 end (copy-marker (point-at-eol))))
18435 ;; Ensure inline tasks don't count as headings.
18436 (org-with-limited-levels
18437 (save-excursion
18438 (goto-char beg)
18439 (cond
18440 ;; Case 1. Started at an heading: de-star headings.
18441 ((org-on-heading-p)
18442 (while (< (point) end)
18443 (when (org-on-heading-p t)
18444 (looking-at org-outline-regexp) (replace-match ""))
18445 (forward-line)))
18446 ;; Case 2. Started at an item: change items into headlines.
18447 ;; One star will be added by `org-list-to-subtree'.
18448 ((org-at-item-p)
18449 (let* ((stars (make-string
18450 (if nstars
18451 ;; subtract the star that will be added again by
18452 ;; `org-list-to-subtree'
18453 (1- (prefix-numeric-value current-prefix-arg))
18454 (or (org-current-level) 0))
18455 ?*))
18456 (add-stars
18457 (cond (nstars "") ; stars from prefix only
18458 ((equal stars "") "") ; before first heading
18459 (org-odd-levels-only "*") ; inside heading, odd
18460 (t "")))) ; inside heading, oddeven
18461 (while (< (point) end)
18462 (when (org-at-item-p)
18463 ;; Pay attention to cases when region ends before list.
18464 (let* ((struct (org-list-struct))
18465 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18466 (save-restriction
18467 (narrow-to-region (point) list-end)
18468 (insert
18469 (org-list-to-subtree
18470 (org-list-parse-list t)
18471 '(:istart (concat stars add-stars (funcall get-stars depth))
18472 :icount (concat stars add-stars (funcall get-stars depth))))))))
18473 (forward-line))))
18474 ;; Case 3. Started at normal text: make every line an heading,
18475 ;; skipping headlines and items.
18476 (t (let* ((stars (make-string
18477 (if nstars
18478 (prefix-numeric-value current-prefix-arg)
18479 (or (org-current-level) 0))
18480 ?*))
18481 (add-stars
18482 (cond (nstars "") ; stars from prefix only
18483 ((equal stars "") "*") ; before first heading
18484 (org-odd-levels-only "**") ; inside heading, odd
18485 (t "*"))) ; inside heading, oddeven
18486 (rpl (concat stars add-stars " ")))
18487 (while (< (point) end)
18488 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18489 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18490 (replace-match (concat rpl (match-string 2))))
18491 (forward-line)))))))))
18493 (defun org-meta-return (&optional arg)
18494 "Insert a new heading or wrap a region in a table.
18495 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18496 See the individual commands for more information."
18497 (interactive "P")
18498 (cond
18499 ((run-hook-with-args-until-success 'org-metareturn-hook))
18500 ((org-at-table-p)
18501 (call-interactively 'org-table-wrap-region))
18502 (t (call-interactively 'org-insert-heading))))
18504 ;;; Menu entries
18506 ;; Define the Org-mode menus
18507 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18508 '("Tbl"
18509 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18510 ["Next Field" org-cycle (org-at-table-p)]
18511 ["Previous Field" org-shifttab (org-at-table-p)]
18512 ["Next Row" org-return (org-at-table-p)]
18513 "--"
18514 ["Blank Field" org-table-blank-field (org-at-table-p)]
18515 ["Edit Field" org-table-edit-field (org-at-table-p)]
18516 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18517 "--"
18518 ("Column"
18519 ["Move Column Left" org-metaleft (org-at-table-p)]
18520 ["Move Column Right" org-metaright (org-at-table-p)]
18521 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18522 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18523 ("Row"
18524 ["Move Row Up" org-metaup (org-at-table-p)]
18525 ["Move Row Down" org-metadown (org-at-table-p)]
18526 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18527 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18528 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18529 "--"
18530 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18531 ("Rectangle"
18532 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18533 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18534 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18535 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18536 "--"
18537 ("Calculate"
18538 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18539 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18540 ["Edit Formulas" org-edit-special (org-at-table-p)]
18541 "--"
18542 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18543 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18544 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18545 "--"
18546 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18547 "--"
18548 ["Sum Column/Rectangle" org-table-sum
18549 (or (org-at-table-p) (org-region-active-p))]
18550 ["Which Column?" org-table-current-column (org-at-table-p)])
18551 ["Debug Formulas"
18552 org-table-toggle-formula-debugger
18553 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18554 ["Show Col/Row Numbers"
18555 org-table-toggle-coordinate-overlays
18556 :style toggle
18557 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18558 "--"
18559 ["Create" org-table-create (and (not (org-at-table-p))
18560 org-enable-table-editor)]
18561 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18562 ["Import from File" org-table-import (not (org-at-table-p))]
18563 ["Export to File" org-table-export (org-at-table-p)]
18564 "--"
18565 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18567 (easy-menu-define org-org-menu org-mode-map "Org menu"
18568 '("Org"
18569 ("Show/Hide"
18570 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18571 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18572 ["Sparse Tree..." org-sparse-tree t]
18573 ["Reveal Context" org-reveal t]
18574 ["Show All" show-all t]
18575 "--"
18576 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18577 "--"
18578 ["New Heading" org-insert-heading t]
18579 ("Navigate Headings"
18580 ["Up" outline-up-heading t]
18581 ["Next" outline-next-visible-heading t]
18582 ["Previous" outline-previous-visible-heading t]
18583 ["Next Same Level" outline-forward-same-level t]
18584 ["Previous Same Level" outline-backward-same-level t]
18585 "--"
18586 ["Jump" org-goto t])
18587 ("Edit Structure"
18588 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18589 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18590 "--"
18591 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18592 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18593 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18594 "--"
18595 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18596 "--"
18597 ["Copy visible text" org-copy-visible t]
18598 "--"
18599 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18600 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18601 ["Demote Heading" org-metaright (not (org-at-table-p))]
18602 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18603 "--"
18604 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18605 "--"
18606 ["Convert to odd levels" org-convert-to-odd-levels t]
18607 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18608 ("Editing"
18609 ["Emphasis..." org-emphasize t]
18610 ["Edit Source Example" org-edit-special t]
18611 "--"
18612 ["Footnote new/jump" org-footnote-action t]
18613 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18614 ("Archive"
18615 ["Archive (default method)" org-archive-subtree-default t]
18616 "--"
18617 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18618 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18619 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18621 "--"
18622 ("Hyperlinks"
18623 ["Store Link (Global)" org-store-link t]
18624 ["Find existing link to here" org-occur-link-in-agenda-files t]
18625 ["Insert Link" org-insert-link t]
18626 ["Follow Link" org-open-at-point t]
18627 "--"
18628 ["Next link" org-next-link t]
18629 ["Previous link" org-previous-link t]
18630 "--"
18631 ["Descriptive Links"
18632 org-toggle-link-display
18633 :style radio
18634 :selected org-descriptive-links
18636 ["Literal Links"
18637 org-toggle-link-display
18638 :style radio
18639 :selected (not org-descriptive-links)])
18640 "--"
18641 ("TODO Lists"
18642 ["TODO/DONE/-" org-todo t]
18643 ("Select keyword"
18644 ["Next keyword" org-shiftright (org-on-heading-p)]
18645 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18646 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18647 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18648 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18649 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18650 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18651 "--"
18652 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18653 :selected org-enforce-todo-dependencies :style toggle :active t]
18654 "Settings for tree at point"
18655 ["Do Children sequentially" org-toggle-ordered-property :style radio
18656 :selected (org-entry-get nil "ORDERED")
18657 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18658 ["Do Children parallel" org-toggle-ordered-property :style radio
18659 :selected (not (org-entry-get nil "ORDERED"))
18660 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18661 "--"
18662 ["Set Priority" org-priority t]
18663 ["Priority Up" org-shiftup t]
18664 ["Priority Down" org-shiftdown t]
18665 "--"
18666 ["Get news from all feeds" org-feed-update-all t]
18667 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18668 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18669 ("TAGS and Properties"
18670 ["Set Tags" org-set-tags-command t]
18671 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18672 "--"
18673 ["Set property" org-set-property t]
18674 ["Column view of properties" org-columns t]
18675 ["Insert Column View DBlock" org-insert-columns-dblock t])
18676 ("Dates and Scheduling"
18677 ["Timestamp" org-time-stamp t]
18678 ["Timestamp (inactive)" org-time-stamp-inactive t]
18679 ("Change Date"
18680 ["1 Day Later" org-shiftright t]
18681 ["1 Day Earlier" org-shiftleft t]
18682 ["1 ... Later" org-shiftup t]
18683 ["1 ... Earlier" org-shiftdown t])
18684 ["Compute Time Range" org-evaluate-time-range t]
18685 ["Schedule Item" org-schedule t]
18686 ["Deadline" org-deadline t]
18687 "--"
18688 ["Custom time format" org-toggle-time-stamp-overlays
18689 :style radio :selected org-display-custom-times]
18690 "--"
18691 ["Goto Calendar" org-goto-calendar t]
18692 ["Date from Calendar" org-date-from-calendar t]
18693 "--"
18694 ["Start/Restart Timer" org-timer-start t]
18695 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18696 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18697 ["Insert Timer String" org-timer t]
18698 ["Insert Timer Item" org-timer-item t])
18699 ("Logging work"
18700 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18701 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18702 ["Clock out" org-clock-out t]
18703 ["Clock cancel" org-clock-cancel t]
18704 "--"
18705 ["Mark as default task" org-clock-mark-default-task t]
18706 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18707 ["Goto running clock" org-clock-goto t]
18708 "--"
18709 ["Display times" org-clock-display t]
18710 ["Create clock table" org-clock-report t]
18711 "--"
18712 ["Record DONE time"
18713 (progn (setq org-log-done (not org-log-done))
18714 (message "Switching to %s will %s record a timestamp"
18715 (car org-done-keywords)
18716 (if org-log-done "automatically" "not")))
18717 :style toggle :selected org-log-done])
18718 "--"
18719 ["Agenda Command..." org-agenda t]
18720 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18721 ("File List for Agenda")
18722 ("Special views current file"
18723 ["TODO Tree" org-show-todo-tree t]
18724 ["Check Deadlines" org-check-deadlines t]
18725 ["Timeline" org-timeline t]
18726 ["Tags/Property tree" org-match-sparse-tree t])
18727 "--"
18728 ["Export/Publish..." org-export t]
18729 ("LaTeX"
18730 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18731 :selected org-cdlatex-mode]
18732 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18733 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18734 ["Modify math symbol" org-cdlatex-math-modify
18735 (org-inside-LaTeX-fragment-p)]
18736 ["Insert citation" org-reftex-citation t]
18737 "--"
18738 ["Template for BEAMER" org-insert-beamer-options-template t])
18739 "--"
18740 ("MobileOrg"
18741 ["Push Files and Views" org-mobile-push t]
18742 ["Get Captured and Flagged" org-mobile-pull t]
18743 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18744 "--"
18745 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18746 "--"
18747 ("Documentation"
18748 ["Show Version" org-version t]
18749 ["Info Documentation" org-info t])
18750 ("Customize"
18751 ["Browse Org Group" org-customize t]
18752 "--"
18753 ["Expand This Menu" org-create-customize-menu
18754 (fboundp 'customize-menu-create)])
18755 ["Send bug report" org-submit-bug-report t]
18756 "--"
18757 ("Refresh/Reload"
18758 ["Refresh setup current buffer" org-mode-restart t]
18759 ["Reload Org (after update)" org-reload t]
18760 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18763 (defun org-info (&optional node)
18764 "Read documentation for Org-mode in the info system.
18765 With optional NODE, go directly to that node."
18766 (interactive)
18767 (info (format "(org)%s" (or node ""))))
18769 ;;;###autoload
18770 (defun org-submit-bug-report ()
18771 "Submit a bug report on Org-mode via mail.
18773 Don't hesitate to report any problems or inaccurate documentation.
18775 If you don't have setup sending mail from (X)Emacs, please copy the
18776 output buffer into your mail program, as it gives us important
18777 information about your Org-mode version and configuration."
18778 (interactive)
18779 (require 'reporter)
18780 (org-load-modules-maybe)
18781 (org-require-autoloaded-modules)
18782 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18783 (reporter-submit-bug-report
18784 "emacs-orgmode@gnu.org"
18785 (org-version)
18786 (let (list)
18787 (save-window-excursion
18788 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18789 (delete-other-windows)
18790 (erase-buffer)
18791 (insert "You are about to submit a bug report to the Org-mode mailing list.
18793 We would like to add your full Org-mode and Outline configuration to the
18794 bug report. This greatly simplifies the work of the maintainer and
18795 other experts on the mailing list.
18797 HOWEVER, some variables you have customized may contain private
18798 information. The names of customers, colleagues, or friends, might
18799 appear in the form of file names, tags, todo states, or search strings.
18800 If you answer yes to the prompt, you might want to check and remove
18801 such private information before sending the email.")
18802 (add-text-properties (point-min) (point-max) '(face org-warning))
18803 (when (yes-or-no-p "Include your Org-mode configuration ")
18804 (mapatoms
18805 (lambda (v)
18806 (and (boundp v)
18807 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18808 (or (and (symbol-value v)
18809 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18810 (and
18811 (get v 'custom-type) (get v 'standard-value)
18812 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18813 (push v list)))))
18814 (kill-buffer (get-buffer "*Warn about privacy*"))
18815 list))
18816 nil nil
18817 "Remember to cover the basics, that is, what you expected to happen and
18818 what in fact did happen. You don't know how to make a good report? See
18820 http://orgmode.org/manual/Feedback.html#Feedback
18822 Your bug report will be posted to the Org-mode mailing list.
18823 ------------------------------------------------------------------------")
18824 (save-excursion
18825 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18826 (replace-match "\\1Bug: \\3 [\\2]")))))
18829 (defun org-install-agenda-files-menu ()
18830 (let ((bl (buffer-list)))
18831 (save-excursion
18832 (while bl
18833 (set-buffer (pop bl))
18834 (if (org-mode-p) (setq bl nil)))
18835 (when (org-mode-p)
18836 (easy-menu-change
18837 '("Org") "File List for Agenda"
18838 (append
18839 (list
18840 ["Edit File List" (org-edit-agenda-file-list) t]
18841 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18842 ["Remove Current File from List" org-remove-file t]
18843 ["Cycle through agenda files" org-cycle-agenda-files t]
18844 ["Occur in all agenda files" org-occur-in-agenda-files t]
18845 "--")
18846 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18848 ;;;; Documentation
18850 ;;;###autoload
18851 (defun org-require-autoloaded-modules ()
18852 (interactive)
18853 (mapc 'require
18854 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18855 org-docbook org-exp org-html org-icalendar
18856 org-id org-latex
18857 org-publish org-remember org-table
18858 org-timer org-xoxo)))
18860 ;;;###autoload
18861 (defun org-reload (&optional uncompiled)
18862 "Reload all org lisp files.
18863 With prefix arg UNCOMPILED, load the uncompiled versions."
18864 (interactive "P")
18865 (require 'find-func)
18866 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18867 (dir-org (file-name-directory (org-find-library-name "org")))
18868 (dir-org-contrib (ignore-errors
18869 (file-name-directory
18870 (org-find-library-name "org-contribdir"))))
18871 (babel-files
18872 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18873 (append (list nil "comint" "eval" "exp" "keys"
18874 "lob" "ref" "table" "tangle")
18875 (delq nil
18876 (mapcar
18877 (lambda (lang)
18878 (when (cdr lang) (symbol-name (car lang))))
18879 org-babel-load-languages)))))
18880 (files
18881 (append (directory-files dir-org t file-re)
18882 babel-files
18883 (and dir-org-contrib
18884 (directory-files dir-org-contrib t file-re))))
18885 (remove-re (concat (if (featurep 'xemacs)
18886 "org-colview" "org-colview-xemacs")
18887 "\\'")))
18888 (setq files (mapcar 'file-name-sans-extension files))
18889 (setq files (mapcar
18890 (lambda (x) (if (string-match remove-re x) nil x))
18891 files))
18892 (setq files (delq nil files))
18893 (mapc
18894 (lambda (f)
18895 (when (featurep (intern (file-name-nondirectory f)))
18896 (if (and (not uncompiled)
18897 (file-exists-p (concat f ".elc")))
18898 (load (concat f ".elc") nil nil t)
18899 (load (concat f ".el") nil nil t))))
18900 files))
18901 (org-version))
18903 ;;;###autoload
18904 (defun org-customize ()
18905 "Call the customize function with org as argument."
18906 (interactive)
18907 (org-load-modules-maybe)
18908 (org-require-autoloaded-modules)
18909 (customize-browse 'org))
18911 (defun org-create-customize-menu ()
18912 "Create a full customization menu for Org-mode, insert it into the menu."
18913 (interactive)
18914 (org-load-modules-maybe)
18915 (org-require-autoloaded-modules)
18916 (if (fboundp 'customize-menu-create)
18917 (progn
18918 (easy-menu-change
18919 '("Org") "Customize"
18920 `(["Browse Org group" org-customize t]
18921 "--"
18922 ,(customize-menu-create 'org)
18923 ["Set" Custom-set t]
18924 ["Save" Custom-save t]
18925 ["Reset to Current" Custom-reset-current t]
18926 ["Reset to Saved" Custom-reset-saved t]
18927 ["Reset to Standard Settings" Custom-reset-standard t]))
18928 (message "\"Org\"-menu now contains full customization menu"))
18929 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18931 ;;;; Miscellaneous stuff
18933 ;;; Generally useful functions
18935 (defun org-get-at-bol (property)
18936 "Get text property PROPERTY at beginning of line."
18937 (get-text-property (point-at-bol) property))
18939 (defun org-find-text-property-in-string (prop s)
18940 "Return the first non-nil value of property PROP in string S."
18941 (or (get-text-property 0 prop s)
18942 (get-text-property (or (next-single-property-change 0 prop s) 0)
18943 prop s)))
18945 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18946 "Display the given MESSAGE as a warning."
18947 (if (fboundp 'display-warning)
18948 (display-warning 'org message
18949 (if (featurep 'xemacs) 'warning :warning))
18950 (let ((buf (get-buffer-create "*Org warnings*")))
18951 (with-current-buffer buf
18952 (goto-char (point-max))
18953 (insert "Warning (Org): " message)
18954 (unless (bolp)
18955 (newline)))
18956 (display-buffer buf)
18957 (sit-for 0))))
18959 (defun org-eval (form)
18960 "Eval FORM and return result."
18961 (condition-case error
18962 (eval form)
18963 (error (format "%%![Error: %s]" error))))
18965 (defun org-in-commented-line ()
18966 "Is point in a line starting with `#'?"
18967 (equal (char-after (point-at-bol)) ?#))
18969 (defun org-in-indented-comment-line ()
18970 "Is point in a line starting with `#' after some white space?"
18971 (save-excursion
18972 (save-match-data
18973 (goto-char (point-at-bol))
18974 (looking-at "[ \t]*#"))))
18976 (defun org-in-verbatim-emphasis ()
18977 (save-match-data
18978 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18980 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18981 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18982 (if (and marker (marker-buffer marker)
18983 (buffer-live-p (marker-buffer marker)))
18984 (progn
18985 (org-pop-to-buffer-same-window (marker-buffer marker))
18986 (if (or (> marker (point-max)) (< marker (point-min)))
18987 (widen))
18988 (goto-char marker)
18989 (org-show-context 'org-goto))
18990 (if bookmark
18991 (bookmark-jump bookmark)
18992 (error "Cannot find location"))))
18994 (defun org-quote-csv-field (s)
18995 "Quote field for inclusion in CSV material."
18996 (if (string-match "[\",]" s)
18997 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19000 (defun org-force-self-insert (N)
19001 "Needed to enforce self-insert under remapping."
19002 (interactive "p")
19003 (self-insert-command N))
19005 (defun org-string-width (s)
19006 "Compute width of string, ignoring invisible characters.
19007 This ignores character with invisibility property `org-link', and also
19008 characters with property `org-cwidth', because these will become invisible
19009 upon the next fontification round."
19010 (let (b l)
19011 (when (or (eq t buffer-invisibility-spec)
19012 (assq 'org-link buffer-invisibility-spec))
19013 (while (setq b (text-property-any 0 (length s)
19014 'invisible 'org-link s))
19015 (setq s (concat (substring s 0 b)
19016 (substring s (or (next-single-property-change
19017 b 'invisible s) (length s)))))))
19018 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19019 (setq s (concat (substring s 0 b)
19020 (substring s (or (next-single-property-change
19021 b 'org-cwidth s) (length s))))))
19022 (setq l (string-width s) b -1)
19023 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19024 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19027 (defun org-shorten-string (s maxlength)
19028 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19029 If the string is shorter or has length MAXLENGTH, just return the
19030 original string. If it is longer, the functions finds a space in the
19031 string, breaks this string off at that locations and adds three dots
19032 as ellipsis. Including the ellipsis, the string will not be longer
19033 than MAXLENGTH. If finding a good breaking point in the string does
19034 not work, the string is just chopped off in the middle of a word
19035 if necessary."
19036 (if (<= (length s) maxlength)
19038 (let* ((n (max (- maxlength 4) 1))
19039 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19040 (if (string-match re s)
19041 (concat (match-string 1 s) "...")
19042 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19044 (defun org-get-indentation (&optional line)
19045 "Get the indentation of the current line, interpreting tabs.
19046 When LINE is given, assume it represents a line and compute its indentation."
19047 (if line
19048 (if (string-match "^ *" (org-remove-tabs line))
19049 (match-end 0))
19050 (save-excursion
19051 (beginning-of-line 1)
19052 (skip-chars-forward " \t")
19053 (current-column))))
19055 (defun org-get-string-indentation (s)
19056 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19057 (let ((n -1) (i 0) (w tab-width) c)
19058 (catch 'exit
19059 (while (< (setq n (1+ n)) (length s))
19060 (setq c (aref s n))
19061 (cond ((= c ?\ ) (setq i (1+ i)))
19062 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19063 (t (throw 'exit t)))))
19066 (defun org-remove-tabs (s &optional width)
19067 "Replace tabulators in S with spaces.
19068 Assumes that s is a single line, starting in column 0."
19069 (setq width (or width tab-width))
19070 (while (string-match "\t" s)
19071 (setq s (replace-match
19072 (make-string
19073 (- (* width (/ (+ (match-beginning 0) width) width))
19074 (match-beginning 0)) ?\ )
19075 t t s)))
19078 (defun org-fix-indentation (line ind)
19079 "Fix indentation in LINE.
19080 IND is a cons cell with target and minimum indentation.
19081 If the current indentation in LINE is smaller than the minimum,
19082 leave it alone. If it is larger than ind, set it to the target."
19083 (let* ((l (org-remove-tabs line))
19084 (i (org-get-indentation l))
19085 (i1 (car ind)) (i2 (cdr ind)))
19086 (if (>= i i2) (setq l (substring line i2)))
19087 (if (> i1 0)
19088 (concat (make-string i1 ?\ ) l)
19089 l)))
19091 (defun org-remove-indentation (code &optional n)
19092 "Remove the maximum common indentation from the lines in CODE.
19093 N may optionally be the number of spaces to remove."
19094 (with-temp-buffer
19095 (insert code)
19096 (org-do-remove-indentation n)
19097 (buffer-string)))
19099 (defun org-do-remove-indentation (&optional n)
19100 "Remove the maximum common indentation from the buffer."
19101 (untabify (point-min) (point-max))
19102 (let ((min 10000) re)
19103 (if n
19104 (setq min n)
19105 (goto-char (point-min))
19106 (while (re-search-forward "^ *[^ \n]" nil t)
19107 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19108 (unless (or (= min 0) (= min 10000))
19109 (setq re (format "^ \\{%d\\}" min))
19110 (goto-char (point-min))
19111 (while (re-search-forward re nil t)
19112 (replace-match "")
19113 (end-of-line 1))
19114 min)))
19116 (defun org-fill-template (template alist)
19117 "Find each %key of ALIST in TEMPLATE and replace it."
19118 (let ((case-fold-search nil)
19119 entry key value)
19120 (setq alist (sort (copy-sequence alist)
19121 (lambda (a b) (< (length (car a)) (length (car b))))))
19122 (while (setq entry (pop alist))
19123 (setq template
19124 (replace-regexp-in-string
19125 (concat "%" (regexp-quote (car entry)))
19126 (cdr entry) template t t)))
19127 template))
19129 (defun org-base-buffer (buffer)
19130 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19131 (if (not buffer)
19132 buffer
19133 (or (buffer-base-buffer buffer)
19134 buffer)))
19136 (defun org-trim (s)
19137 "Remove whitespace at beginning and end of string."
19138 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19139 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19142 (defun org-wrap (string &optional width lines)
19143 "Wrap string to either a number of lines, or a width in characters.
19144 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19145 that costs. If there is a word longer than WIDTH, the text is actually
19146 wrapped to the length of that word.
19147 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19148 many lines, whatever width that takes.
19149 The return value is a list of lines, without newlines at the end."
19150 (let* ((words (org-split-string string "[ \t\n]+"))
19151 (maxword (apply 'max (mapcar 'org-string-width words)))
19152 w ll)
19153 (cond (width
19154 (org-do-wrap words (max maxword width)))
19155 (lines
19156 (setq w maxword)
19157 (setq ll (org-do-wrap words maxword))
19158 (if (<= (length ll) lines)
19160 (setq ll words)
19161 (while (> (length ll) lines)
19162 (setq w (1+ w))
19163 (setq ll (org-do-wrap words w)))
19164 ll))
19165 (t (error "Cannot wrap this")))))
19167 (defun org-do-wrap (words width)
19168 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19169 (let (lines line)
19170 (while words
19171 (setq line (pop words))
19172 (while (and words (< (+ (length line) (length (car words))) width))
19173 (setq line (concat line " " (pop words))))
19174 (setq lines (push line lines)))
19175 (nreverse lines)))
19177 (defun org-split-string (string &optional separators)
19178 "Splits STRING into substrings at SEPARATORS.
19179 No empty strings are returned if there are matches at the beginning
19180 and end of string."
19181 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19182 (start 0)
19183 notfirst
19184 (list nil))
19185 (while (and (string-match rexp string
19186 (if (and notfirst
19187 (= start (match-beginning 0))
19188 (< start (length string)))
19189 (1+ start) start))
19190 (< (match-beginning 0) (length string)))
19191 (setq notfirst t)
19192 (or (eq (match-beginning 0) 0)
19193 (and (eq (match-beginning 0) (match-end 0))
19194 (eq (match-beginning 0) start))
19195 (setq list
19196 (cons (substring string start (match-beginning 0))
19197 list)))
19198 (setq start (match-end 0)))
19199 (or (eq start (length string))
19200 (setq list
19201 (cons (substring string start)
19202 list)))
19203 (nreverse list)))
19205 (defun org-quote-vert (s)
19206 "Replace \"|\" with \"\\vert\"."
19207 (while (string-match "|" s)
19208 (setq s (replace-match "\\vert" t t s)))
19211 (defun org-uuidgen-p (s)
19212 "Is S an ID created by UUIDGEN?"
19213 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19215 (defun org-context ()
19216 "Return a list of contexts of the current cursor position.
19217 If several contexts apply, all are returned.
19218 Each context entry is a list with a symbol naming the context, and
19219 two positions indicating start and end of the context. Possible
19220 contexts are:
19222 :headline anywhere in a headline
19223 :headline-stars on the leading stars in a headline
19224 :todo-keyword on a TODO keyword (including DONE) in a headline
19225 :tags on the TAGS in a headline
19226 :priority on the priority cookie in a headline
19227 :item on the first line of a plain list item
19228 :item-bullet on the bullet/number of a plain list item
19229 :checkbox on the checkbox in a plain list item
19230 :table in an org-mode table
19231 :table-special on a special filed in a table
19232 :table-table in a table.el table
19233 :link on a hyperlink
19234 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19235 :target on a <<target>>
19236 :radio-target on a <<<radio-target>>>
19237 :latex-fragment on a LaTeX fragment
19238 :latex-preview on a LaTeX fragment with overlayed preview image
19240 This function expects the position to be visible because it uses font-lock
19241 faces as a help to recognize the following contexts: :table-special, :link,
19242 and :keyword."
19243 (let* ((f (get-text-property (point) 'face))
19244 (faces (if (listp f) f (list f)))
19245 (p (point)) clist o)
19246 ;; First the large context
19247 (cond
19248 ((org-on-heading-p t)
19249 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19250 (when (progn
19251 (beginning-of-line 1)
19252 (looking-at org-todo-line-tags-regexp))
19253 (push (org-point-in-group p 1 :headline-stars) clist)
19254 (push (org-point-in-group p 2 :todo-keyword) clist)
19255 (push (org-point-in-group p 4 :tags) clist))
19256 (goto-char p)
19257 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19258 (if (looking-at "\\[#[A-Z0-9]\\]")
19259 (push (org-point-in-group p 0 :priority) clist)))
19261 ((org-at-item-p)
19262 (push (org-point-in-group p 2 :item-bullet) clist)
19263 (push (list :item (point-at-bol)
19264 (save-excursion (org-end-of-item) (point)))
19265 clist)
19266 (and (org-at-item-checkbox-p)
19267 (push (org-point-in-group p 0 :checkbox) clist)))
19269 ((org-at-table-p)
19270 (push (list :table (org-table-begin) (org-table-end)) clist)
19271 (if (memq 'org-formula faces)
19272 (push (list :table-special
19273 (previous-single-property-change p 'face)
19274 (next-single-property-change p 'face)) clist)))
19275 ((org-at-table-p 'any)
19276 (push (list :table-table) clist)))
19277 (goto-char p)
19279 ;; Now the small context
19280 (cond
19281 ((org-at-timestamp-p)
19282 (push (org-point-in-group p 0 :timestamp) clist))
19283 ((memq 'org-link faces)
19284 (push (list :link
19285 (previous-single-property-change p 'face)
19286 (next-single-property-change p 'face)) clist))
19287 ((memq 'org-special-keyword faces)
19288 (push (list :keyword
19289 (previous-single-property-change p 'face)
19290 (next-single-property-change p 'face)) clist))
19291 ((org-on-target-p)
19292 (push (org-point-in-group p 0 :target) clist)
19293 (goto-char (1- (match-beginning 0)))
19294 (if (looking-at org-radio-target-regexp)
19295 (push (org-point-in-group p 0 :radio-target) clist))
19296 (goto-char p))
19297 ((setq o (car (delq nil
19298 (mapcar
19299 (lambda (x)
19300 (if (memq x org-latex-fragment-image-overlays) x))
19301 (overlays-at (point))))))
19302 (push (list :latex-fragment
19303 (overlay-start o) (overlay-end o)) clist)
19304 (push (list :latex-preview
19305 (overlay-start o) (overlay-end o)) clist))
19306 ((org-inside-LaTeX-fragment-p)
19307 ;; FIXME: positions wrong.
19308 (push (list :latex-fragment (point) (point)) clist)))
19310 (setq clist (nreverse (delq nil clist)))
19311 clist))
19313 ;; FIXME: Compare with at-regexp-p Do we need both?
19314 (defun org-in-regexp (re &optional nlines visually)
19315 "Check if point is inside a match of regexp.
19316 Normally only the current line is checked, but you can include NLINES extra
19317 lines both before and after point into the search.
19318 If VISUALLY is set, require that the cursor is not after the match but
19319 really on, so that the block visually is on the match."
19320 (catch 'exit
19321 (let ((pos (point))
19322 (eol (point-at-eol (+ 1 (or nlines 0))))
19323 (inc (if visually 1 0)))
19324 (save-excursion
19325 (beginning-of-line (- 1 (or nlines 0)))
19326 (while (re-search-forward re eol t)
19327 (if (and (<= (match-beginning 0) pos)
19328 (>= (+ inc (match-end 0)) pos))
19329 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19331 (defun org-at-regexp-p (regexp)
19332 "Is point inside a match of REGEXP in the current line?"
19333 (catch 'exit
19334 (save-excursion
19335 (let ((pos (point)) (end (point-at-eol)))
19336 (beginning-of-line 1)
19337 (while (re-search-forward regexp end t)
19338 (if (and (<= (match-beginning 0) pos)
19339 (>= (match-end 0) pos))
19340 (throw 'exit t)))
19341 nil))))
19343 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19344 "Non-nil when point is between matches of START-RE and END-RE.
19346 Also return a non-nil value when point is on one of the matches.
19348 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19349 buffer positions. Default values are the positions of headlines
19350 surrounding the point.
19352 The functions returns a cons cell whose car (resp. cdr) is the
19353 position before START-RE (resp. after END-RE)."
19354 (save-match-data
19355 (let ((pos (point))
19356 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19357 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19358 beg end)
19359 (save-excursion
19360 ;; Point is on a block when on START-RE or if START-RE can be
19361 ;; found before it...
19362 (and (or (org-at-regexp-p start-re)
19363 (re-search-backward start-re limit-up t))
19364 (setq beg (match-beginning 0))
19365 ;; ... and END-RE after it...
19366 (goto-char (match-end 0))
19367 (re-search-forward end-re limit-down t)
19368 (> (setq end (match-end 0)) pos)
19369 ;; ... without another START-RE in-between.
19370 (goto-char (match-beginning 0))
19371 (not (re-search-backward start-re (1+ beg) t))
19372 ;; Return value.
19373 (cons beg end))))))
19375 (defun org-in-block-p (names)
19376 "Is point inside any block whose name belongs to NAMES?
19378 NAMES is a list of strings containing names of blocks."
19379 (save-match-data
19380 (catch 'exit
19381 (let ((case-fold-search t)
19382 (lim-up (save-excursion (outline-previous-heading)))
19383 (lim-down (save-excursion (outline-next-heading))))
19384 (mapc (lambda (name)
19385 (let ((n (regexp-quote name)))
19386 (when (org-between-regexps-p
19387 (concat "^[ \t]*#\\+begin_" n)
19388 (concat "^[ \t]*#\\+end_" n)
19389 lim-up lim-down)
19390 (throw 'exit t))))
19391 names))
19392 nil)))
19394 (defun org-occur-in-agenda-files (regexp &optional nlines)
19395 "Call `multi-occur' with buffers for all agenda files."
19396 (interactive "sOrg-files matching: \np")
19397 (let* ((files (org-agenda-files))
19398 (tnames (mapcar 'file-truename files))
19399 (extra org-agenda-text-search-extra-files)
19401 (when (eq (car extra) 'agenda-archives)
19402 (setq extra (cdr extra))
19403 (setq files (org-add-archive-files files)))
19404 (while (setq f (pop extra))
19405 (unless (member (file-truename f) tnames)
19406 (add-to-list 'files f 'append)
19407 (add-to-list 'tnames (file-truename f) 'append)))
19408 (multi-occur
19409 (mapcar (lambda (x)
19410 (with-current-buffer
19411 (or (get-file-buffer x) (find-file-noselect x))
19412 (widen)
19413 (current-buffer)))
19414 files)
19415 regexp)))
19417 (if (boundp 'occur-mode-find-occurrence-hook)
19418 ;; Emacs 23
19419 (add-hook 'occur-mode-find-occurrence-hook
19420 (lambda ()
19421 (when (org-mode-p)
19422 (org-reveal))))
19423 ;; Emacs 22
19424 (defadvice occur-mode-goto-occurrence
19425 (after org-occur-reveal activate)
19426 (and (org-mode-p) (org-reveal)))
19427 (defadvice occur-mode-goto-occurrence-other-window
19428 (after org-occur-reveal activate)
19429 (and (org-mode-p) (org-reveal)))
19430 (defadvice occur-mode-display-occurrence
19431 (after org-occur-reveal activate)
19432 (when (org-mode-p)
19433 (let ((pos (occur-mode-find-occurrence)))
19434 (with-current-buffer (marker-buffer pos)
19435 (save-excursion
19436 (goto-char pos)
19437 (org-reveal)))))))
19439 (defun org-occur-link-in-agenda-files ()
19440 "Create a link and search for it in the agendas.
19441 The link is not stored in `org-stored-links', it is just created
19442 for the search purpose."
19443 (interactive)
19444 (let ((link (condition-case nil
19445 (org-store-link nil)
19446 (error "Unable to create a link to here"))))
19447 (org-occur-in-agenda-files (regexp-quote link))))
19449 (defun org-uniquify (list)
19450 "Remove duplicate elements from LIST."
19451 (let (res)
19452 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19453 res))
19455 (defun org-delete-all (elts list)
19456 "Remove all elements in ELTS from LIST."
19457 (while elts
19458 (setq list (delete (pop elts) list)))
19459 list)
19461 (defun org-count (cl-item cl-seq)
19462 "Count the number of occurrences of ITEM in SEQ.
19463 Taken from `count' in cl-seq.el with all keyword arguments removed."
19464 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19465 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19466 (while (< cl-start cl-end)
19467 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19468 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19469 (setq cl-start (1+ cl-start)))
19470 cl-count))
19472 (defun org-remove-if (predicate seq)
19473 "Remove everything from SEQ that fulfills PREDICATE."
19474 (let (res e)
19475 (while seq
19476 (setq e (pop seq))
19477 (if (not (funcall predicate e)) (push e res)))
19478 (nreverse res)))
19480 (defun org-remove-if-not (predicate seq)
19481 "Remove everything from SEQ that does not fulfill PREDICATE."
19482 (let (res e)
19483 (while seq
19484 (setq e (pop seq))
19485 (if (funcall predicate e) (push e res)))
19486 (nreverse res)))
19488 (defun org-back-over-empty-lines ()
19489 "Move backwards over whitespace, to the beginning of the first empty line.
19490 Returns the number of empty lines passed."
19491 (let ((pos (point)))
19492 (if (cdr (assoc 'heading org-blank-before-new-entry))
19493 (skip-chars-backward " \t\n\r")
19494 (unless (eobp)
19495 (forward-line -1)))
19496 (beginning-of-line 2)
19497 (goto-char (min (point) pos))
19498 (count-lines (point) pos)))
19500 (defun org-skip-whitespace ()
19501 (skip-chars-forward " \t\n\r"))
19503 (defun org-point-in-group (point group &optional context)
19504 "Check if POINT is in match-group GROUP.
19505 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19506 match. If the match group does not exist or point is not inside it,
19507 return nil."
19508 (and (match-beginning group)
19509 (>= point (match-beginning group))
19510 (<= point (match-end group))
19511 (if context
19512 (list context (match-beginning group) (match-end group))
19513 t)))
19515 (defun org-switch-to-buffer-other-window (&rest args)
19516 "Switch to buffer in a second window on the current frame.
19517 In particular, do not allow pop-up frames.
19518 Returns the newly created buffer."
19519 (let (pop-up-frames special-display-buffer-names special-display-regexps
19520 special-display-function)
19521 (apply 'switch-to-buffer-other-window args)))
19523 (defun org-combine-plists (&rest plists)
19524 "Create a single property list from all plists in PLISTS.
19525 The process starts by copying the first list, and then setting properties
19526 from the other lists. Settings in the last list are the most significant
19527 ones and overrule settings in the other lists."
19528 (let ((rtn (copy-sequence (pop plists)))
19529 p v ls)
19530 (while plists
19531 (setq ls (pop plists))
19532 (while ls
19533 (setq p (pop ls) v (pop ls))
19534 (setq rtn (plist-put rtn p v))))
19535 rtn))
19537 (defun org-move-line-down (arg)
19538 "Move the current line down. With prefix argument, move it past ARG lines."
19539 (interactive "p")
19540 (let ((col (current-column))
19541 beg end pos)
19542 (beginning-of-line 1) (setq beg (point))
19543 (beginning-of-line 2) (setq end (point))
19544 (beginning-of-line (+ 1 arg))
19545 (setq pos (move-marker (make-marker) (point)))
19546 (insert (delete-and-extract-region beg end))
19547 (goto-char pos)
19548 (org-move-to-column col)))
19550 (defun org-move-line-up (arg)
19551 "Move the current line up. With prefix argument, move it past ARG lines."
19552 (interactive "p")
19553 (let ((col (current-column))
19554 beg end pos)
19555 (beginning-of-line 1) (setq beg (point))
19556 (beginning-of-line 2) (setq end (point))
19557 (beginning-of-line (- arg))
19558 (setq pos (move-marker (make-marker) (point)))
19559 (insert (delete-and-extract-region beg end))
19560 (goto-char pos)
19561 (org-move-to-column col)))
19563 (defun org-replace-escapes (string table)
19564 "Replace %-escapes in STRING with values in TABLE.
19565 TABLE is an association list with keys like \"%a\" and string values.
19566 The sequences in STRING may contain normal field width and padding information,
19567 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19568 so values can contain further %-escapes if they are define later in TABLE."
19569 (let ((tbl (copy-alist table))
19570 (case-fold-search nil)
19571 (pchg 0)
19572 e re rpl)
19573 (while (setq e (pop tbl))
19574 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19575 (when (and (cdr e) (string-match re (cdr e)))
19576 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19577 (safe "SREF"))
19578 (add-text-properties 0 3 (list 'sref sref) safe)
19579 (setcdr e (replace-match safe t t (cdr e)))))
19580 (while (string-match re string)
19581 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19582 (cdr e)))
19583 (setq string (replace-match rpl t t string))))
19584 (while (setq pchg (next-property-change pchg string))
19585 (let ((sref (get-text-property pchg 'sref string)))
19586 (when (and sref (string-match "SREF" string pchg))
19587 (setq string (replace-match sref t t string)))))
19588 string))
19590 (defun org-sublist (list start end)
19591 "Return a section of LIST, from START to END.
19592 Counting starts at 1."
19593 (let (rtn (c start))
19594 (setq list (nthcdr (1- start) list))
19595 (while (and list (<= c end))
19596 (push (pop list) rtn)
19597 (setq c (1+ c)))
19598 (nreverse rtn)))
19600 (defun org-find-base-buffer-visiting (file)
19601 "Like `find-buffer-visiting' but always return the base buffer and
19602 not an indirect buffer."
19603 (let ((buf (or (get-file-buffer file)
19604 (find-buffer-visiting file))))
19605 (if buf
19606 (or (buffer-base-buffer buf) buf)
19607 nil)))
19609 (defun org-image-file-name-regexp (&optional extensions)
19610 "Return regexp matching the file names of images.
19611 If EXTENSIONS is given, only match these."
19612 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19613 (image-file-name-regexp)
19614 (let ((image-file-name-extensions
19615 (or extensions
19616 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19617 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19618 (concat "\\."
19619 (regexp-opt (nconc (mapcar 'upcase
19620 image-file-name-extensions)
19621 image-file-name-extensions)
19623 "\\'"))))
19625 (defun org-file-image-p (file &optional extensions)
19626 "Return non-nil if FILE is an image."
19627 (save-match-data
19628 (string-match (org-image-file-name-regexp extensions) file)))
19630 (defun org-get-cursor-date ()
19631 "Return the date at cursor in as a time.
19632 This works in the calendar and in the agenda, anywhere else it just
19633 returns the current time."
19634 (let (date day defd)
19635 (cond
19636 ((eq major-mode 'calendar-mode)
19637 (setq date (calendar-cursor-to-date)
19638 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19639 ((eq major-mode 'org-agenda-mode)
19640 (setq day (get-text-property (point) 'day))
19641 (if day
19642 (setq date (calendar-gregorian-from-absolute day)
19643 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19644 (nth 2 date))))))
19645 (or defd (current-time))))
19647 (defvar org-agenda-action-marker (make-marker)
19648 "Marker pointing to the entry for the next agenda action.")
19650 (defun org-mark-entry-for-agenda-action ()
19651 "Mark the current entry as target of an agenda action.
19652 Agenda actions are actions executed from the agenda with the key `k',
19653 which make use of the date at the cursor."
19654 (interactive)
19655 (move-marker org-agenda-action-marker
19656 (save-excursion (org-back-to-heading t) (point))
19657 (current-buffer))
19658 (message
19659 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19661 (defun org-mark-subtree ()
19662 "Mark the current subtree.
19663 This puts point at the start of the current subtree, and mark at the end.
19665 If point is in an inline task, mark that task instead."
19666 (interactive)
19667 (let ((inline-task-p
19668 (and (featurep 'org-inlinetask)
19669 (org-inlinetask-in-task-p)))
19670 (beg))
19671 ;; Get beginning of subtree
19672 (cond
19673 (inline-task-p (org-inlinetask-goto-beginning))
19674 ((org-at-heading-p) (beginning-of-line))
19675 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19676 (setq beg (point))
19677 ;; Get end of it
19678 (if inline-task-p
19679 (org-inlinetask-goto-end)
19680 (org-end-of-subtree))
19681 ;; Mark zone
19682 (push-mark (point) nil t)
19683 (goto-char beg)))
19685 ;;; Paragraph filling stuff.
19686 ;; We want this to be just right, so use the full arsenal.
19688 (defun org-indent-line-function ()
19689 "Indent line depending on context."
19690 (interactive)
19691 (let* ((pos (point))
19692 (itemp (org-at-item-p))
19693 (case-fold-search t)
19694 (org-drawer-regexp (or org-drawer-regexp "\000"))
19695 (inline-task-p (and (featurep 'org-inlinetask)
19696 (org-inlinetask-in-task-p)))
19697 (inline-re (and inline-task-p
19698 (org-inlinetask-outline-regexp)))
19699 column)
19700 (beginning-of-line 1)
19701 (cond
19702 ;; Comments
19703 ((looking-at "# ") (setq column 0))
19704 ;; Headings
19705 ((looking-at org-outline-regexp) (setq column 0))
19706 ;; Included files
19707 ((looking-at "#\\+include:") (setq column 0))
19708 ;; Footnote definition
19709 ((looking-at org-footnote-definition-re) (setq column 0))
19710 ;; Literal examples
19711 ((looking-at "[ \t]*:\\( \\|$\\)")
19712 (setq column (org-get-indentation))) ; do nothing
19713 ;; Lists
19714 ((ignore-errors (goto-char (org-in-item-p)))
19715 (setq column (if itemp
19716 (org-get-indentation)
19717 (org-list-item-body-column (point))))
19718 (goto-char pos))
19719 ;; Drawers
19720 ((and (looking-at "[ \t]*:END:")
19721 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19722 (save-excursion
19723 (goto-char (1- (match-beginning 1)))
19724 (setq column (current-column))))
19725 ;; Special blocks
19726 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19727 (save-excursion
19728 (re-search-backward
19729 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19730 (setq column (org-get-indentation (match-string 0))))
19731 ((and (not (looking-at "[ \t]*#\\+begin_"))
19732 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19733 (save-excursion
19734 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19735 (setq column
19736 (cond ((equal (downcase (match-string 1)) "src")
19737 ;; src blocks: let `org-edit-src-exit' handle them
19738 (org-get-indentation))
19739 ((equal (downcase (match-string 1)) "example")
19740 (max (org-get-indentation)
19741 (org-get-indentation (match-string 0))))
19743 (org-get-indentation (match-string 0))))))
19744 ;; This line has nothing special, look at the previous relevant
19745 ;; line to compute indentation
19747 (beginning-of-line 0)
19748 (while (and (not (bobp))
19749 (not (looking-at org-drawer-regexp))
19750 ;; When point started in an inline task, do not move
19751 ;; above task starting line.
19752 (not (and inline-task-p (looking-at inline-re)))
19753 ;; Skip drawers, blocks, empty lines, verbatim,
19754 ;; comments, tables, footnotes definitions, lists,
19755 ;; inline tasks.
19756 (or (and (looking-at "[ \t]*:END:")
19757 (re-search-backward org-drawer-regexp nil t))
19758 (and (looking-at "[ \t]*#\\+end_")
19759 (re-search-backward "[ \t]*#\\+begin_"nil t))
19760 (looking-at "[ \t]*[\n:#|]")
19761 (looking-at org-footnote-definition-re)
19762 (and (ignore-errors (goto-char (org-in-item-p)))
19763 (goto-char
19764 (org-list-get-top-point (org-list-struct))))
19765 (and (not inline-task-p)
19766 (featurep 'org-inlinetask)
19767 (org-inlinetask-in-task-p)
19768 (or (org-inlinetask-goto-beginning) t))))
19769 (beginning-of-line 0))
19770 (cond
19771 ;; There was an heading above.
19772 ((looking-at "\\*+[ \t]+")
19773 (if (not org-adapt-indentation)
19774 (setq column 0)
19775 (goto-char (match-end 0))
19776 (setq column (current-column))))
19777 ;; A drawer had started and is unfinished
19778 ((looking-at org-drawer-regexp)
19779 (goto-char (1- (match-beginning 1)))
19780 (setq column (current-column)))
19781 ;; Else, nothing noticeable found: get indentation and go on.
19782 (t (setq column (org-get-indentation))))))
19783 ;; Now apply indentation and move cursor accordingly
19784 (goto-char pos)
19785 (if (<= (current-column) (current-indentation))
19786 (org-indent-line-to column)
19787 (save-excursion (org-indent-line-to column)))
19788 ;; Special polishing for properties, see `org-property-format'
19789 (setq column (current-column))
19790 (beginning-of-line 1)
19791 (if (looking-at
19792 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19793 (replace-match (concat (match-string 1)
19794 (format org-property-format
19795 (match-string 2) (match-string 3)))
19796 t t))
19797 (org-move-to-column column)))
19799 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19800 "Variable to store copy of `adaptive-fill-regexp'.
19801 Since `adaptive-fill-regexp' is set to never match, we need to
19802 store a backup of its value before entering `org-mode' so that
19803 the functionality can be provided as a fall-back.")
19805 (defun org-set-autofill-regexps ()
19806 (interactive)
19807 ;; In the paragraph separator we include headlines, because filling
19808 ;; text in a line directly attached to a headline would otherwise
19809 ;; fill the headline as well.
19810 (org-set-local 'comment-start-skip "^#+[ \t]*")
19811 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19812 ;; The paragraph starter includes hand-formatted lists.
19813 (org-set-local
19814 'paragraph-start
19815 (concat
19816 "\f" "\\|"
19817 "[ ]*$" "\\|"
19818 org-outline-regexp "\\|"
19819 "[ \t]*#" "\\|"
19820 (org-item-re) "\\|"
19821 "[ \t]*[:|]" "\\|"
19822 "\\$\\$" "\\|"
19823 "\\\\\\(begin\\|end\\|[][]\\)"))
19824 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19825 ;; But only if the user has not turned off tables or fixed-width regions
19826 (org-set-local
19827 'auto-fill-inhibit-regexp
19828 (concat org-outline-regexp
19829 "\\|#\\+"
19830 "\\|[ \t]*" org-keyword-time-regexp
19831 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19832 (concat
19833 "\\|[ \t]*["
19834 (if org-enable-table-editor "|" "")
19835 (if org-enable-fixed-width-editor ":" "")
19836 "]"))))
19837 ;; We use our own fill-paragraph function, to make sure that tables
19838 ;; and fixed-width regions are not wrapped. That function will pass
19839 ;; through to `fill-paragraph' when appropriate.
19840 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19841 ;; Prevent auto-fill from inserting unwanted new items.
19842 (org-set-local 'fill-nobreak-predicate
19843 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19844 fill-nobreak-predicate
19845 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19846 ;; Adaptive filling: To get full control, first make sure that
19847 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19848 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19849 (org-set-local 'org-adaptive-fill-regexp-backup
19850 adaptive-fill-regexp))
19851 (org-set-local 'adaptive-fill-regexp "\000")
19852 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19853 (org-set-local 'adaptive-fill-function
19854 'org-adaptive-fill-function)
19855 (org-set-local
19856 'align-mode-rules-list
19857 '((org-in-buffer-settings
19858 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19859 (modes . '(org-mode))))))
19861 (defun org-fill-item-nobreak-p ()
19862 "Non-nil when a line break at point would insert a new item."
19863 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19865 (defun org-fill-paragraph (&optional justify)
19866 "Re-align a table, pass through to fill-paragraph if no table."
19867 (let ((table-p (org-at-table-p))
19868 (table.el-p (org-at-table.el-p))
19869 (itemp (org-in-item-p)))
19870 (cond ((and (equal (char-after (point-at-bol)) ?*)
19871 (save-excursion (goto-char (point-at-bol))
19872 (looking-at org-outline-regexp)))
19873 t) ; skip headlines
19874 (table.el-p t) ; skip table.el tables
19875 (table-p (org-table-align) t) ; align Org tables
19876 (itemp ; align text in items
19877 (let* ((struct (save-excursion (goto-char itemp)
19878 (org-list-struct)))
19879 (parents (org-list-parents-alist struct))
19880 (children (org-list-get-children itemp struct parents))
19881 beg end prev next prefix)
19882 ;; Determine in which part of item point is: before
19883 ;; first child, after last child, between two
19884 ;; sub-lists, or simply in item if there's no child.
19885 (cond
19886 ((not children)
19887 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19888 beg itemp
19889 end (org-list-get-item-end itemp struct)))
19890 ((< (point) (setq next (car children)))
19891 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19892 beg itemp
19893 end next))
19894 ((> (point) (setq prev (car (last children))))
19895 (setq beg (org-list-get-item-end prev struct)
19896 end (org-list-get-item-end itemp struct)
19897 prefix (save-excursion
19898 (goto-char beg)
19899 (skip-chars-forward " \t")
19900 (make-string (current-column) ?\ ))))
19901 (t (catch 'exit
19902 (while (setq next (pop children))
19903 (if (> (point) next)
19904 (setq prev next)
19905 (setq beg (org-list-get-item-end prev struct)
19906 end next
19907 prefix (save-excursion
19908 (goto-char beg)
19909 (skip-chars-forward " \t")
19910 (make-string (current-column) ?\ )))
19911 (throw 'exit nil))))))
19912 ;; Use `fill-paragraph' with buffer narrowed to item
19913 ;; without any child, and with our computed PREFIX.
19914 (flet ((fill-context-prefix (from to &optional flr) prefix))
19915 (save-restriction
19916 (narrow-to-region beg end)
19917 (save-excursion (fill-paragraph justify)))) t))
19918 ;; Special case where point is not in a list but is on
19919 ;; a paragraph adjacent to a list: make sure this paragraph
19920 ;; doesn't get merged with the end of the list by narrowing
19921 ;; buffer first.
19922 ((save-excursion (forward-paragraph -1)
19923 (setq itemp (org-in-item-p)))
19924 (let ((struct (save-excursion (goto-char itemp)
19925 (org-list-struct))))
19926 (save-restriction
19927 (narrow-to-region (org-list-get-bottom-point struct)
19928 (save-excursion (forward-paragraph 1)
19929 (point)))
19930 (fill-paragraph justify) t)))
19931 ;; Else simply call `fill-paragraph'.
19932 (t nil))))
19934 ;; For reference, this is the default value of adaptive-fill-regexp
19935 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19937 (defun org-adaptive-fill-function ()
19938 "Return a fill prefix for org-mode files."
19939 (let (itemp)
19940 (save-excursion
19941 (cond
19942 ;; Comment line
19943 ((looking-at "#[ \t]+")
19944 (match-string-no-properties 0))
19945 ;; Plain list item
19946 ((org-at-item-p)
19947 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19948 ;; Point is in a list after `backward-paragraph': original
19949 ;; point wasn't in the list, or filling would have been taken
19950 ;; care of by `org-auto-fill-function', but the list and the
19951 ;; real paragraph are not separated by a blank line. Thus, move
19952 ;; point after the list to go back to real paragraph and
19953 ;; determine fill-prefix.
19954 ((setq itemp (org-in-item-p))
19955 (goto-char itemp)
19956 (let* ((struct (org-list-struct))
19957 (bottom (org-list-get-bottom-point struct)))
19958 (goto-char bottom)
19959 (make-string (org-get-indentation) ?\ )))
19960 ;; Other text
19961 ((looking-at org-adaptive-fill-regexp-backup)
19962 (match-string-no-properties 0))))))
19964 (defun org-auto-fill-function ()
19965 "Auto-fill function."
19966 (let (itemp prefix)
19967 ;; When in a list, compute an appropriate fill-prefix and make
19968 ;; sure it will be used by `do-auto-fill'.
19969 (if (setq itemp (org-in-item-p))
19970 (progn
19971 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19972 (flet ((fill-context-prefix (from to &optional flr) prefix))
19973 (do-auto-fill)))
19974 ;; Else just use `do-auto-fill'.
19975 (do-auto-fill))))
19977 ;;; Other stuff.
19979 (defun org-toggle-fixed-width-section (arg)
19980 "Toggle the fixed-width export.
19981 If there is no active region, the QUOTE keyword at the current headline is
19982 inserted or removed. When present, it causes the text between this headline
19983 and the next to be exported as fixed-width text, and unmodified.
19984 If there is an active region, this command adds or removes a colon as the
19985 first character of this line. If the first character of a line is a colon,
19986 this line is also exported in fixed-width font."
19987 (interactive "P")
19988 (let* ((cc 0)
19989 (regionp (org-region-active-p))
19990 (beg (if regionp (region-beginning) (point)))
19991 (end (if regionp (region-end)))
19992 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19993 (case-fold-search nil)
19994 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
19995 off)
19996 (if regionp
19997 (save-excursion
19998 (goto-char beg)
19999 (setq cc (current-column))
20000 (beginning-of-line 1)
20001 (setq off (looking-at re))
20002 (while (> nlines 0)
20003 (setq nlines (1- nlines))
20004 (beginning-of-line 1)
20005 (cond
20006 (arg
20007 (org-move-to-column cc t)
20008 (insert ": \n")
20009 (forward-line -1))
20010 ((and off (looking-at re))
20011 (replace-match "" t t nil 1))
20012 ((not off) (org-move-to-column cc t) (insert ": ")))
20013 (forward-line 1)))
20014 (save-excursion
20015 (org-back-to-heading)
20016 (if (looking-at (concat org-outline-regexp
20017 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
20018 (replace-match "" t t nil 1)
20019 (if (looking-at org-outline-regexp)
20020 (progn
20021 (goto-char (match-end 0))
20022 (insert org-quote-string " "))))))))
20024 (defun org-reftex-citation ()
20025 "Use reftex-citation to insert a citation into the buffer.
20026 This looks for a line like
20028 #+BIBLIOGRAPHY: foo plain option:-d
20030 and derives from it that foo.bib is the bibliography file relevant
20031 for this document. It then installs the necessary environment for RefTeX
20032 to work in this buffer and calls `reftex-citation' to insert a citation
20033 into the buffer.
20035 Export of such citations to both LaTeX and HTML is handled by the contributed
20036 package org-exp-bibtex by Taru Karttunen."
20037 (interactive)
20038 (let ((reftex-docstruct-symbol 'rds)
20039 (reftex-cite-format "\\cite{%l}")
20040 rds bib)
20041 (save-excursion
20042 (save-restriction
20043 (widen)
20044 (let ((case-fold-search t)
20045 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20046 (if (not (save-excursion
20047 (or (re-search-forward re nil t)
20048 (re-search-backward re nil t))))
20049 (error "No bibliography defined in file")
20050 (setq bib (concat (match-string 1) ".bib")
20051 rds (list (list 'bib bib)))))))
20052 (call-interactively 'reftex-citation)))
20054 ;;;; Functions extending outline functionality
20056 (defun org-beginning-of-line (&optional arg)
20057 "Go to the beginning of the current line. If that is invisible, continue
20058 to a visible line beginning. This makes the function of C-a more intuitive.
20059 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20060 first attempt, and only move to after the tags when the cursor is already
20061 beyond the end of the headline."
20062 (interactive "P")
20063 (let ((pos (point))
20064 (special (if (consp org-special-ctrl-a/e)
20065 (car org-special-ctrl-a/e)
20066 org-special-ctrl-a/e))
20067 refpos)
20068 (if (org-bound-and-true-p line-move-visual)
20069 (beginning-of-visual-line 1)
20070 (beginning-of-line 1))
20071 (if (and arg (fboundp 'move-beginning-of-line))
20072 (call-interactively 'move-beginning-of-line)
20073 (if (bobp)
20075 (backward-char 1)
20076 (if (org-truely-invisible-p)
20077 (while (and (not (bobp)) (org-truely-invisible-p))
20078 (backward-char 1)
20079 (beginning-of-line 1))
20080 (forward-char 1))))
20081 (when special
20082 (cond
20083 ((and (looking-at org-complex-heading-regexp)
20084 (= (char-after (match-end 1)) ?\ ))
20085 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20086 (point-at-eol)))
20087 (goto-char
20088 (if (eq special t)
20089 (cond ((> pos refpos) refpos)
20090 ((= pos (point)) refpos)
20091 (t (point)))
20092 (cond ((> pos (point)) (point))
20093 ((not (eq last-command this-command)) (point))
20094 (t refpos)))))
20095 ((org-at-item-p)
20096 (goto-char
20097 (if (eq special t)
20098 (cond ((> pos (match-end 0)) (match-end 0))
20099 ((= pos (point)) (match-end 0))
20100 (t (point)))
20101 (cond ((> pos (point)) (point))
20102 ((not (eq last-command this-command)) (point))
20103 (t (match-end 0))))))))
20104 (org-no-warnings
20105 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20107 (defun org-end-of-line (&optional arg)
20108 "Go to the end of the line.
20109 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20110 first attempt, and only move to after the tags when the cursor is already
20111 beyond the end of the headline."
20112 (interactive "P")
20113 (let ((special (if (consp org-special-ctrl-a/e)
20114 (cdr org-special-ctrl-a/e)
20115 org-special-ctrl-a/e)))
20116 (cond
20117 ((or (not special) arg
20118 (not (or (org-on-heading-p) (org-at-item-p))))
20119 (call-interactively
20120 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20121 ((fboundp 'move-end-of-line) 'move-end-of-line)
20122 (t 'end-of-line))))
20123 ((org-on-heading-p)
20124 (let ((pos (point)))
20125 (beginning-of-line 1)
20126 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20127 (if (eq special t)
20128 (if (or (< pos (match-beginning 1))
20129 (= pos (match-end 0)))
20130 (goto-char (match-beginning 1))
20131 (goto-char (match-end 0)))
20132 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20133 (goto-char (match-end 0))
20134 (goto-char (match-beginning 1))))
20135 (call-interactively (if (fboundp 'move-end-of-line)
20136 'move-end-of-line
20137 'end-of-line)))))
20138 ;; At an item: Move before any hidden text.
20139 (t (call-interactively 'end-of-line)))
20140 (org-no-warnings
20141 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20143 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20144 (define-key org-mode-map "\C-e" 'org-end-of-line)
20146 (defun org-backward-sentence (&optional arg)
20147 "Go to beginning of sentence, or beginning of table field.
20148 This will call `backward-sentence' or `org-table-beginning-of-field',
20149 depending on context."
20150 (interactive "P")
20151 (cond
20152 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20153 (t (call-interactively 'backward-sentence))))
20155 (defun org-forward-sentence (&optional arg)
20156 "Go to end of sentence, or end of table field.
20157 This will call `forward-sentence' or `org-table-end-of-field',
20158 depending on context."
20159 (interactive "P")
20160 (cond
20161 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20162 (t (call-interactively 'forward-sentence))))
20164 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20165 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20167 (defun org-kill-line (&optional arg)
20168 "Kill line, to tags or end of line."
20169 (interactive "P")
20170 (cond
20171 ((or (not org-special-ctrl-k)
20172 (bolp)
20173 (not (org-on-heading-p)))
20174 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20175 org-ctrl-k-protect-subtree)
20176 (if (or (eq org-ctrl-k-protect-subtree 'error)
20177 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20178 (error "C-k aborted - would kill hidden subtree")))
20179 (call-interactively 'kill-line))
20180 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20181 (kill-region (point) (match-beginning 1))
20182 (org-set-tags nil t))
20183 (t (kill-region (point) (point-at-eol)))))
20185 (define-key org-mode-map "\C-k" 'org-kill-line)
20187 (defun org-yank (&optional arg)
20188 "Yank. If the kill is a subtree, treat it specially.
20189 This command will look at the current kill and check if is a single
20190 subtree, or a series of subtrees[1]. If it passes the test, and if the
20191 cursor is at the beginning of a line or after the stars of a currently
20192 empty headline, then the yank is handled specially. How exactly depends
20193 on the value of the following variables, both set by default.
20195 org-yank-folded-subtrees
20196 When set, the subtree(s) will be folded after insertion, but only
20197 if doing so would now swallow text after the yanked text.
20199 org-yank-adjusted-subtrees
20200 When set, the subtree will be promoted or demoted in order to
20201 fit into the local outline tree structure, which means that the level
20202 will be adjusted so that it becomes the smaller one of the two
20203 *visible* surrounding headings.
20205 Any prefix to this command will cause `yank' to be called directly with
20206 no special treatment. In particular, a simple \\[universal-argument] prefix \
20207 will just
20208 plainly yank the text as it is.
20210 \[1] The test checks if the first non-white line is a heading
20211 and if there are no other headings with fewer stars."
20212 (interactive "P")
20213 (org-yank-generic 'yank arg))
20215 (defun org-yank-generic (command arg)
20216 "Perform some yank-like command.
20218 This function implements the behavior described in the `org-yank'
20219 documentation. However, it has been generalized to work for any
20220 interactive command with similar behavior."
20222 ;; pretend to be command COMMAND
20223 (setq this-command command)
20225 (if arg
20226 (call-interactively command)
20228 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20229 (and (org-kill-is-subtree-p)
20230 (or (bolp)
20231 (and (looking-at "[ \t]*$")
20232 (string-match
20233 "\\`\\*+\\'"
20234 (buffer-substring (point-at-bol) (point)))))))
20235 swallowp)
20236 (cond
20237 ((and subtreep org-yank-folded-subtrees)
20238 (let ((beg (point))
20239 end)
20240 (if (and subtreep org-yank-adjusted-subtrees)
20241 (org-paste-subtree nil nil 'for-yank)
20242 (call-interactively command))
20244 (setq end (point))
20245 (goto-char beg)
20246 (when (and (bolp) subtreep
20247 (not (setq swallowp
20248 (org-yank-folding-would-swallow-text beg end))))
20249 (org-with-limited-levels
20250 (or (looking-at org-outline-regexp)
20251 (re-search-forward org-outline-regexp-bol end t))
20252 (while (and (< (point) end) (looking-at org-outline-regexp))
20253 (hide-subtree)
20254 (org-cycle-show-empty-lines 'folded)
20255 (condition-case nil
20256 (outline-forward-same-level 1)
20257 (error (goto-char end))))))
20258 (when swallowp
20259 (message
20260 "Inserted text not folded because that would swallow text"))
20262 (goto-char end)
20263 (skip-chars-forward " \t\n\r")
20264 (beginning-of-line 1)
20265 (push-mark beg 'nomsg)))
20266 ((and subtreep org-yank-adjusted-subtrees)
20267 (let ((beg (point-at-bol)))
20268 (org-paste-subtree nil nil 'for-yank)
20269 (push-mark beg 'nomsg)))
20271 (call-interactively command))))))
20273 (defun org-yank-folding-would-swallow-text (beg end)
20274 "Would hide-subtree at BEG swallow any text after END?"
20275 (let (level)
20276 (org-with-limited-levels
20277 (save-excursion
20278 (goto-char beg)
20279 (when (or (looking-at org-outline-regexp)
20280 (re-search-forward org-outline-regexp-bol end t))
20281 (setq level (org-outline-level)))
20282 (goto-char end)
20283 (skip-chars-forward " \t\r\n\v\f")
20284 (if (or (eobp)
20285 (and (bolp) (looking-at org-outline-regexp)
20286 (<= (org-outline-level) level)))
20287 nil ; Nothing would be swallowed
20288 t))))) ; something would swallow
20290 (define-key org-mode-map "\C-y" 'org-yank)
20292 (defun org-truely-invisible-p ()
20293 "Check if point is at a character currently not visible.
20294 This version does not only check the character property, but also
20295 `visible-mode'."
20296 ;; Early versions of noutline don't have `outline-invisible-p'.
20297 (if (org-bound-and-true-p visible-mode)
20299 (outline-invisible-p)))
20301 (defun org-invisible-p2 ()
20302 "Check if point is at a character currently not visible."
20303 (save-excursion
20304 (if (and (eolp) (not (bobp))) (backward-char 1))
20305 ;; Early versions of noutline don't have `outline-invisible-p'.
20306 (outline-invisible-p)))
20308 (defun org-back-to-heading (&optional invisible-ok)
20309 "Call `outline-back-to-heading', but provide a better error message."
20310 (condition-case nil
20311 (outline-back-to-heading invisible-ok)
20312 (error (error "Before first headline at position %d in buffer %s"
20313 (point) (current-buffer)))))
20315 (defun org-beginning-of-defun ()
20316 "Go to the beginning of the subtree, i.e. back to the heading."
20317 (org-back-to-heading))
20318 (defun org-end-of-defun ()
20319 "Go to the end of the subtree."
20320 (org-end-of-subtree nil t))
20322 (defun org-before-first-heading-p ()
20323 "Before first heading?"
20324 (save-excursion
20325 (end-of-line)
20326 (null (re-search-backward org-outline-regexp-bol nil t))))
20328 (defun org-on-heading-p (&optional ignored)
20329 (outline-on-heading-p t))
20330 (defun org-at-heading-p (&optional ignored)
20331 (outline-on-heading-p t))
20333 (defun org-point-at-end-of-empty-headline ()
20334 "If point is at the end of an empty headline, return t, else nil.
20335 If the heading only contains a TODO keyword, it is still still considered
20336 empty."
20337 (and (looking-at "[ \t]*$")
20338 (save-excursion
20339 (beginning-of-line 1)
20340 (let ((case-fold-search nil))
20341 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
20342 "\\)?[ \t]*$"))))))
20343 (defun org-at-heading-or-item-p ()
20344 (or (org-on-heading-p) (org-at-item-p)))
20346 (defun org-on-target-p ()
20347 (or (org-in-regexp org-radio-target-regexp)
20348 (org-in-regexp org-target-regexp)))
20350 (defun org-up-heading-all (arg)
20351 "Move to the heading line of which the present line is a subheading.
20352 This function considers both visible and invisible heading lines.
20353 With argument, move up ARG levels."
20354 (if (fboundp 'outline-up-heading-all)
20355 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20356 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20358 (defun org-up-heading-safe ()
20359 "Move to the heading line of which the present line is a subheading.
20360 This version will not throw an error. It will return the level of the
20361 headline found, or nil if no higher level is found.
20363 Also, this function will be a lot faster than `outline-up-heading',
20364 because it relies on stars being the outline starters. This can really
20365 make a significant difference in outlines with very many siblings."
20366 (let (start-level re)
20367 (org-back-to-heading t)
20368 (setq start-level (funcall outline-level))
20369 (if (equal start-level 1)
20371 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20372 (if (re-search-backward re nil t)
20373 (funcall outline-level)))))
20375 (defun org-first-sibling-p ()
20376 "Is this heading the first child of its parents?"
20377 (interactive)
20378 (let ((re org-outline-regexp-bol)
20379 level l)
20380 (unless (org-at-heading-p t)
20381 (error "Not at a heading"))
20382 (setq level (funcall outline-level))
20383 (save-excursion
20384 (if (not (re-search-backward re nil t))
20386 (setq l (funcall outline-level))
20387 (< l level)))))
20389 (defun org-goto-sibling (&optional previous)
20390 "Goto the next sibling, even if it is invisible.
20391 When PREVIOUS is set, go to the previous sibling instead. Returns t
20392 when a sibling was found. When none is found, return nil and don't
20393 move point."
20394 (let ((fun (if previous 're-search-backward 're-search-forward))
20395 (pos (point))
20396 (re org-outline-regexp-bol)
20397 level l)
20398 (when (condition-case nil (org-back-to-heading t) (error nil))
20399 (setq level (funcall outline-level))
20400 (catch 'exit
20401 (or previous (forward-char 1))
20402 (while (funcall fun re nil t)
20403 (setq l (funcall outline-level))
20404 (when (< l level) (goto-char pos) (throw 'exit nil))
20405 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20406 (goto-char pos)
20407 nil))))
20409 (defun org-show-siblings ()
20410 "Show all siblings of the current headline."
20411 (save-excursion
20412 (while (org-goto-sibling) (org-flag-heading nil)))
20413 (save-excursion
20414 (while (org-goto-sibling 'previous)
20415 (org-flag-heading nil))))
20417 (defun org-goto-first-child ()
20418 "Goto the first child, even if it is invisible.
20419 Return t when a child was found. Otherwise don't move point and
20420 return nil."
20421 (let (level (pos (point)) (re org-outline-regexp-bol))
20422 (when (condition-case nil (org-back-to-heading t) (error nil))
20423 (setq level (outline-level))
20424 (forward-char 1)
20425 (if (and (re-search-forward re nil t) (> (outline-level) level))
20426 (progn (goto-char (match-beginning 0)) t)
20427 (goto-char pos) nil))))
20429 (defun org-show-hidden-entry ()
20430 "Show an entry where even the heading is hidden."
20431 (save-excursion
20432 (org-show-entry)))
20434 (defun org-flag-heading (flag &optional entry)
20435 "Flag the current heading. FLAG non-nil means make invisible.
20436 When ENTRY is non-nil, show the entire entry."
20437 (save-excursion
20438 (org-back-to-heading t)
20439 ;; Check if we should show the entire entry
20440 (if entry
20441 (progn
20442 (org-show-entry)
20443 (save-excursion
20444 (and (outline-next-heading)
20445 (org-flag-heading nil))))
20446 (outline-flag-region (max (point-min) (1- (point)))
20447 (save-excursion (outline-end-of-heading) (point))
20448 flag))))
20450 (defun org-get-next-sibling ()
20451 "Move to next heading of the same level, and return point.
20452 If there is no such heading, return nil.
20453 This is like outline-next-sibling, but invisible headings are ok."
20454 (let ((level (funcall outline-level)))
20455 (outline-next-heading)
20456 (while (and (not (eobp)) (> (funcall outline-level) level))
20457 (outline-next-heading))
20458 (if (or (eobp) (< (funcall outline-level) level))
20460 (point))))
20462 (defun org-get-last-sibling ()
20463 "Move to previous heading of the same level, and return point.
20464 If there is no such heading, return nil."
20465 (let ((opoint (point))
20466 (level (funcall outline-level)))
20467 (outline-previous-heading)
20468 (when (and (/= (point) opoint) (outline-on-heading-p t))
20469 (while (and (> (funcall outline-level) level)
20470 (not (bobp)))
20471 (outline-previous-heading))
20472 (if (< (funcall outline-level) level)
20474 (point)))))
20476 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20477 ;; This contains an exact copy of the original function, but it uses
20478 ;; `org-back-to-heading', to make it work also in invisible
20479 ;; trees. And is uses an invisible-OK argument.
20480 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20481 ;; Furthermore, when used inside Org, finding the end of a large subtree
20482 ;; with many children and grandchildren etc, this can be much faster
20483 ;; than the outline version.
20484 (org-back-to-heading invisible-OK)
20485 (let ((first t)
20486 (level (funcall outline-level)))
20487 (if (and (org-mode-p) (< level 1000))
20488 ;; A true heading (not a plain list item), in Org-mode
20489 ;; This means we can easily find the end by looking
20490 ;; only for the right number of stars. Using a regexp to do
20491 ;; this is so much faster than using a Lisp loop.
20492 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20493 (forward-char 1)
20494 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20495 ;; something else, do it the slow way
20496 (while (and (not (eobp))
20497 (or first (> (funcall outline-level) level)))
20498 (setq first nil)
20499 (outline-next-heading)))
20500 (unless to-heading
20501 (if (memq (preceding-char) '(?\n ?\^M))
20502 (progn
20503 ;; Go to end of line before heading
20504 (forward-char -1)
20505 (if (memq (preceding-char) '(?\n ?\^M))
20506 ;; leave blank line before heading
20507 (forward-char -1))))))
20508 (point))
20510 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20511 "Use Org version in org-mode, for dramatic speed-up."
20512 (if (org-mode-p)
20513 (progn
20514 (org-end-of-subtree nil t)
20515 (unless (eobp) (backward-char 1)))
20516 ad-do-it))
20518 (defun org-end-of-meta-data-and-drawers ()
20519 "Jump to the first text after meta data and drawers in the current entry.
20520 This will move over empty lines, lines with planning time stamps,
20521 clocking lines, and drawers."
20522 (org-back-to-heading t)
20523 (let ((end (save-excursion (outline-next-heading) (point)))
20524 (re (concat "\\(" org-drawer-regexp "\\)"
20525 "\\|" "[ \t]*" org-keyword-time-regexp)))
20526 (forward-line 1)
20527 (while (re-search-forward re end t)
20528 (if (not (match-end 1))
20529 ;; empty or planning line
20530 (forward-line 1)
20531 ;; a drawer, find the end
20532 (re-search-forward "^[ \t]*:END:" end 'move)
20533 (forward-line 1)))
20534 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20535 (point)))
20537 (defun org-forward-same-level (arg &optional invisible-ok)
20538 "Move forward to the arg'th subheading at same level as this one.
20539 Stop at the first and last subheadings of a superior heading.
20540 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20541 it wil also look at invisible ones."
20542 (interactive "p")
20543 (org-back-to-heading invisible-ok)
20544 (org-on-heading-p)
20545 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20546 (re (format "^\\*\\{1,%d\\} " level))
20548 (forward-char 1)
20549 (while (> arg 0)
20550 (while (and (re-search-forward re nil 'move)
20551 (setq l (- (match-end 0) (match-beginning 0) 1))
20552 (= l level)
20553 (not invisible-ok)
20554 (progn (backward-char 1) (outline-invisible-p)))
20555 (if (< l level) (setq arg 1)))
20556 (setq arg (1- arg)))
20557 (beginning-of-line 1)))
20559 (defun org-backward-same-level (arg &optional invisible-ok)
20560 "Move backward to the arg'th subheading at same level as this one.
20561 Stop at the first and last subheadings of a superior heading."
20562 (interactive "p")
20563 (org-back-to-heading)
20564 (org-on-heading-p)
20565 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20566 (re (format "^\\*\\{1,%d\\} " level))
20568 (while (> arg 0)
20569 (while (and (re-search-backward re nil 'move)
20570 (setq l (- (match-end 0) (match-beginning 0) 1))
20571 (= l level)
20572 (not invisible-ok)
20573 (outline-invisible-p))
20574 (if (< l level) (setq arg 1)))
20575 (setq arg (1- arg)))))
20577 (defun org-show-subtree ()
20578 "Show everything after this heading at deeper levels."
20579 (outline-flag-region
20580 (point)
20581 (save-excursion
20582 (org-end-of-subtree t t))
20583 nil))
20585 (defun org-show-entry ()
20586 "Show the body directly following this heading.
20587 Show the heading too, if it is currently invisible."
20588 (interactive)
20589 (save-excursion
20590 (condition-case nil
20591 (progn
20592 (org-back-to-heading t)
20593 (outline-flag-region
20594 (max (point-min) (1- (point)))
20595 (save-excursion
20596 (if (re-search-forward
20597 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20598 (match-beginning 1)
20599 (point-max)))
20600 nil)
20601 (org-cycle-hide-drawers 'children))
20602 (error nil))))
20604 (defun org-make-options-regexp (kwds &optional extra)
20605 "Make a regular expression for keyword lines."
20606 (concat
20608 "#?[ \t]*\\+\\("
20609 (mapconcat 'regexp-quote kwds "\\|")
20610 (if extra (concat "\\|" extra))
20611 "\\):[ \t]*"
20612 "\\(.*\\)"))
20614 ;; Make isearch reveal the necessary context
20615 (defun org-isearch-end ()
20616 "Reveal context after isearch exits."
20617 (when isearch-success ; only if search was successful
20618 (if (featurep 'xemacs)
20619 ;; Under XEmacs, the hook is run in the correct place,
20620 ;; we directly show the context.
20621 (org-show-context 'isearch)
20622 ;; In Emacs the hook runs *before* restoring the overlays.
20623 ;; So we have to use a one-time post-command-hook to do this.
20624 ;; (Emacs 22 has a special variable, see function `org-mode')
20625 (unless (and (boundp 'isearch-mode-end-hook-quit)
20626 isearch-mode-end-hook-quit)
20627 ;; Only when the isearch was not quitted.
20628 (org-add-hook 'post-command-hook 'org-isearch-post-command
20629 'append 'local)))))
20631 (defun org-isearch-post-command ()
20632 "Remove self from hook, and show context."
20633 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20634 (org-show-context 'isearch))
20637 ;;;; Integration with and fixes for other packages
20639 ;;; Imenu support
20641 (defvar org-imenu-markers nil
20642 "All markers currently used by Imenu.")
20643 (make-variable-buffer-local 'org-imenu-markers)
20645 (defun org-imenu-new-marker (&optional pos)
20646 "Return a new marker for use by Imenu, and remember the marker."
20647 (let ((m (make-marker)))
20648 (move-marker m (or pos (point)))
20649 (push m org-imenu-markers)
20652 (defun org-imenu-get-tree ()
20653 "Produce the index for Imenu."
20654 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20655 (setq org-imenu-markers nil)
20656 (let* ((n org-imenu-depth)
20657 (re (concat "^" (org-get-limited-outline-regexp)))
20658 (subs (make-vector (1+ n) nil))
20659 (last-level 0)
20660 m level head)
20661 (save-excursion
20662 (save-restriction
20663 (widen)
20664 (goto-char (point-max))
20665 (while (re-search-backward re nil t)
20666 (setq level (org-reduced-level (funcall outline-level)))
20667 (when (<= level n)
20668 (looking-at org-complex-heading-regexp)
20669 (setq head (org-link-display-format
20670 (org-match-string-no-properties 4))
20671 m (org-imenu-new-marker))
20672 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20673 (if (>= level last-level)
20674 (push (cons head m) (aref subs level))
20675 (push (cons head (aref subs (1+ level))) (aref subs level))
20676 (loop for i from (1+ level) to n do (aset subs i nil)))
20677 (setq last-level level)))))
20678 (aref subs 1)))
20680 (eval-after-load "imenu"
20681 '(progn
20682 (add-hook 'imenu-after-jump-hook
20683 (lambda ()
20684 (if (org-mode-p)
20685 (org-show-context 'org-goto))))))
20687 (defun org-link-display-format (link)
20688 "Replace a link with either the description, or the link target
20689 if no description is present"
20690 (save-match-data
20691 (if (string-match org-bracket-link-analytic-regexp link)
20692 (replace-match (if (match-end 5)
20693 (match-string 5 link)
20694 (concat (match-string 1 link)
20695 (match-string 3 link)))
20696 nil t link)
20697 link)))
20699 (defun org-toggle-link-display ()
20700 "Toggle the literal or descriptive display of links."
20701 (interactive)
20702 (if org-descriptive-links
20703 (progn (org-remove-from-invisibility-spec '(org-link))
20704 (org-restart-font-lock)
20705 (setq org-descriptive-links nil))
20706 (progn (add-to-invisibility-spec '(org-link))
20707 (org-restart-font-lock)
20708 (setq org-descriptive-links t))))
20710 ;; Speedbar support
20712 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20713 "Overlay marking the agenda restriction line in speedbar.")
20714 (overlay-put org-speedbar-restriction-lock-overlay
20715 'face 'org-agenda-restriction-lock)
20716 (overlay-put org-speedbar-restriction-lock-overlay
20717 'help-echo "Agendas are currently limited to this item.")
20718 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20720 (defun org-speedbar-set-agenda-restriction ()
20721 "Restrict future agenda commands to the location at point in speedbar.
20722 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20723 (interactive)
20724 (require 'org-agenda)
20725 (let (p m tp np dir txt)
20726 (cond
20727 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20728 'org-imenu t))
20729 (setq m (get-text-property p 'org-imenu-marker))
20730 (with-current-buffer (marker-buffer m)
20731 (goto-char m)
20732 (org-agenda-set-restriction-lock 'subtree)))
20733 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20734 'speedbar-function 'speedbar-find-file))
20735 (setq tp (previous-single-property-change
20736 (1+ p) 'speedbar-function)
20737 np (next-single-property-change
20738 tp 'speedbar-function)
20739 dir (speedbar-line-directory)
20740 txt (buffer-substring-no-properties (or tp (point-min))
20741 (or np (point-max))))
20742 (with-current-buffer (find-file-noselect
20743 (let ((default-directory dir))
20744 (expand-file-name txt)))
20745 (unless (org-mode-p)
20746 (error "Cannot restrict to non-Org-mode file"))
20747 (org-agenda-set-restriction-lock 'file)))
20748 (t (error "Don't know how to restrict Org-mode's agenda")))
20749 (move-overlay org-speedbar-restriction-lock-overlay
20750 (point-at-bol) (point-at-eol))
20751 (setq current-prefix-arg nil)
20752 (org-agenda-maybe-redo)))
20754 (eval-after-load "speedbar"
20755 '(progn
20756 (speedbar-add-supported-extension ".org")
20757 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20758 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20759 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20760 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20761 (add-hook 'speedbar-visiting-tag-hook
20762 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20764 ;;; Fixes and Hacks for problems with other packages
20766 ;; Make flyspell not check words in links, to not mess up our keymap
20767 (defun org-mode-flyspell-verify ()
20768 "Don't let flyspell put overlays at active buttons, or on
20769 {todo,all-time,additional-option-like}-keywords."
20770 (let ((pos (max (1- (point)) (point-min)))
20771 (word (thing-at-point 'word)))
20772 (and (not (get-text-property pos 'keymap))
20773 (not (get-text-property pos 'org-no-flyspell))
20774 (not (member word org-todo-keywords-1))
20775 (not (member word org-all-time-keywords))
20776 (not (member word org-additional-option-like-keywords)))))
20778 (defun org-remove-flyspell-overlays-in (beg end)
20779 "Remove flyspell overlays in region."
20780 (and (org-bound-and-true-p flyspell-mode)
20781 (fboundp 'flyspell-delete-region-overlays)
20782 (flyspell-delete-region-overlays beg end))
20783 (add-text-properties beg end '(org-no-flyspell t)))
20785 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20786 (eval-after-load "bookmark"
20787 '(if (boundp 'bookmark-after-jump-hook)
20788 ;; We can use the hook
20789 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20790 ;; Hook not available, use advice
20791 (defadvice bookmark-jump (after org-make-visible activate)
20792 "Make the position visible."
20793 (org-bookmark-jump-unhide))))
20795 ;; Make sure saveplace shows the location if it was hidden
20796 (eval-after-load "saveplace"
20797 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20798 "Make the position visible."
20799 (org-bookmark-jump-unhide)))
20801 ;; Make sure ecb shows the location if it was hidden
20802 (eval-after-load "ecb"
20803 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20804 "Make hierarchy visible when jumping into location from ECB tree buffer."
20805 (if (org-mode-p)
20806 (org-show-context))))
20808 (defun org-bookmark-jump-unhide ()
20809 "Unhide the current position, to show the bookmark location."
20810 (and (org-mode-p)
20811 (or (outline-invisible-p)
20812 (save-excursion (goto-char (max (point-min) (1- (point))))
20813 (outline-invisible-p)))
20814 (org-show-context 'bookmark-jump)))
20816 ;; Make session.el ignore our circular variable
20817 (eval-after-load "session"
20818 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20820 ;;;; Experimental code
20822 (defun org-closed-in-range ()
20823 "Sparse tree of items closed in a certain time range.
20824 Still experimental, may disappear in the future."
20825 (interactive)
20826 ;; Get the time interval from the user.
20827 (let* ((time1 (org-float-time
20828 (org-read-date nil 'to-time nil "Starting date: ")))
20829 (time2 (org-float-time
20830 (org-read-date nil 'to-time nil "End date:")))
20831 ;; callback function
20832 (callback (lambda ()
20833 (let ((time
20834 (org-float-time
20835 (apply 'encode-time
20836 (org-parse-time-string
20837 (match-string 1))))))
20838 ;; check if time in interval
20839 (and (>= time time1) (<= time time2))))))
20840 ;; make tree, check each match with the callback
20841 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20843 ;;;; Finish up
20845 (provide 'org)
20847 (run-hooks 'org-load-hook)
20849 ;;; org.el ends here