* Allow for a different markup for inactive time stamps on latex export
[org-mode/org-tableheadings.git] / lisp / org.el
blob9fddf3fdd6da3681ed77dece22f9a4dac4cc6acc
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.5
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" ())
110 ;; babel
111 (require 'ob)
112 (require 'ob-table)
113 (require 'ob-lob)
114 (require 'ob-ref)
115 (require 'ob-tangle)
116 (require 'ob-comint)
117 (require 'ob-keys)
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "Awk" awk)
154 (const :tag "C" C)
155 (const :tag "R" R)
156 (const :tag "Asymptote" asymptote)
157 (const :tag "Calc" calc)
158 (const :tag "Clojure" clojure)
159 (const :tag "CSS" css)
160 (const :tag "Ditaa" ditaa)
161 (const :tag "Dot" dot)
162 (const :tag "Emacs Lisp" emacs-lisp)
163 (const :tag "Gnuplot" gnuplot)
164 (const :tag "Haskell" haskell)
165 (const :tag "Javascript" js)
166 (const :tag "Latex" latex)
167 (const :tag "Ledger" ledger)
168 (const :tag "Lilypond" lilypond)
169 (const :tag "Maxima" maxima)
170 (const :tag "Matlab" matlab)
171 (const :tag "Mscgen" mscgen)
172 (const :tag "Ocaml" ocaml)
173 (const :tag "Octave" octave)
174 (const :tag "Org" org)
175 (const :tag "Perl" perl)
176 (const :tag "PlantUML" plantuml)
177 (const :tag "Python" python)
178 (const :tag "Ruby" ruby)
179 (const :tag "Sass" sass)
180 (const :tag "Scheme" scheme)
181 (const :tag "Screen" screen)
182 (const :tag "Shell Script" sh)
183 (const :tag "Sql" sql)
184 (const :tag "Sqlite" sqlite))
185 :value-type (boolean :tag "Activate" :value t)))
187 ;;;; Customization variables
188 (defcustom org-clone-delete-id nil
189 "Remove ID property of clones of a subtree.
190 When non-nil, clones of a subtree don't inherit the ID property.
191 Otherwise they inherit the ID property with a new unique
192 identifier."
193 :type 'boolean
194 :group 'org-id)
196 ;;; Version
198 (defconst org-version "7.5"
199 "The version number of the file org.el.")
201 (defun org-version (&optional here)
202 "Show the org-mode version in the echo area.
203 With prefix arg HERE, insert it at point."
204 (interactive "P")
205 (let* ((origin default-directory)
206 (version org-version)
207 (git-version)
208 (dir (concat (file-name-directory (locate-library "org")) "../" )))
209 (when (and (file-exists-p (expand-file-name ".git" dir))
210 (executable-find "git"))
211 (unwind-protect
212 (progn
213 (cd dir)
214 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
215 (with-current-buffer "*Shell Command Output*"
216 (goto-char (point-min))
217 (setq git-version (buffer-substring (point) (point-at-eol))))
218 (subst-char-in-string ?- ?. git-version t)
219 (when (string-match "\\S-"
220 (shell-command-to-string
221 "git diff-index --name-only HEAD --"))
222 (setq git-version (concat git-version ".dirty")))
223 (setq version (concat version " (" git-version ")"))))
224 (cd origin)))
225 (setq version (format "Org-mode version %s" version))
226 (if here (insert version))
227 (message version)))
229 ;;; Compatibility constants
231 ;;; The custom variables
233 (defgroup org nil
234 "Outline-based notes management and organizer."
235 :tag "Org"
236 :group 'outlines
237 :group 'calendar)
239 (defcustom org-mode-hook nil
240 "Mode hook for Org-mode, run after the mode was turned on."
241 :group 'org
242 :type 'hook)
244 (defcustom org-load-hook nil
245 "Hook that is run after org.el has been loaded."
246 :group 'org
247 :type 'hook)
249 (defvar org-modules) ; defined below
250 (defvar org-modules-loaded nil
251 "Have the modules been loaded already?")
253 (defun org-load-modules-maybe (&optional force)
254 "Load all extensions listed in `org-modules'."
255 (when (or force (not org-modules-loaded))
256 (mapc (lambda (ext)
257 (condition-case nil (require ext)
258 (error (message "Problems while trying to load feature `%s'" ext))))
259 org-modules)
260 (setq org-modules-loaded t)))
262 (defun org-set-modules (var value)
263 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
264 (set var value)
265 (when (featurep 'org)
266 (org-load-modules-maybe 'force)))
268 (when (org-bound-and-true-p org-modules)
269 (let ((a (member 'org-infojs org-modules)))
270 (and a (setcar a 'org-jsinfo))))
272 (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)
273 "Modules that should always be loaded together with org.el.
274 If a description starts with <C>, the file is not part of Emacs
275 and loading it will require that you have downloaded and properly installed
276 the org-mode distribution.
278 You can also use this system to load external packages (i.e. neither Org
279 core modules, nor modules from the CONTRIB directory). Just add symbols
280 to the end of the list. If the package is called org-xyz.el, then you need
281 to add the symbol `xyz', and the package must have a call to
283 (provide 'org-xyz)"
284 :group 'org
285 :set 'org-set-modules
286 :type
287 '(set :greedy t
288 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
289 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
290 (const :tag " crypt: Encryption of subtrees" org-crypt)
291 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
292 (const :tag " docview: Links to doc-view buffers" org-docview)
293 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
294 (const :tag " id: Global IDs for identifying entries" org-id)
295 (const :tag " info: Links to Info nodes" org-info)
296 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
297 (const :tag " habit: Track your consistency with habits" org-habit)
298 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
299 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
300 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
301 (const :tag " mew Links to Mew folders/messages" org-mew)
302 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
303 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
304 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
305 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
306 (const :tag " vm: Links to VM folders/messages" org-vm)
307 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
308 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
309 (const :tag " mouse: Additional mouse support" org-mouse)
310 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
312 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
313 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
314 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
315 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
316 (const :tag "C collector: Collect properties into tables" org-collector)
317 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
318 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
319 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
320 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
321 (const :tag "C eval: Include command output as text" org-eval)
322 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
323 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
324 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
325 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
326 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
328 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
330 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
331 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
332 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
333 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
334 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
335 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
336 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
337 (const :tag "C mtags: Support for muse-like tags" org-mtags)
338 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
339 (const :tag "C registry: A registry for Org-mode links" org-registry)
340 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
341 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
342 (const :tag "C secretary: Team management with org-mode" org-secretary)
343 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
344 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
345 (const :tag "C track: Keep up with Org-mode development" org-track)
346 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
347 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
348 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
350 (defcustom org-support-shift-select nil
351 "Non-nil means make shift-cursor commands select text when possible.
353 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
354 selecting a region, or enlarge regions started in this way.
355 In Org-mode, in special contexts, these same keys are used for other
356 purposes, important enough to compete with shift selection. Org tries
357 to balance these needs by supporting `shift-select-mode' outside these
358 special contexts, under control of this variable.
360 The default of this variable is nil, to avoid confusing behavior. Shifted
361 cursor keys will then execute Org commands in the following contexts:
362 - on a headline, changing TODO state (left/right) and priority (up/down)
363 - on a time stamp, changing the time
364 - in a plain list item, changing the bullet type
365 - in a property definition line, switching between allowed values
366 - in the BEGIN line of a clock table (changing the time block).
367 Outside these contexts, the commands will throw an error.
369 When this variable is t and the cursor is not in a special context,
370 Org-mode will support shift-selection for making and enlarging regions.
371 To make this more effective, the bullet cycling will no longer happen
372 anywhere in an item line, but only if the cursor is exactly on the bullet.
374 If you set this variable to the symbol `always', then the keys
375 will not be special in headlines, property lines, and item lines, to make
376 shift selection work there as well. If this is what you want, you can
377 use the following alternative commands: `C-c C-t' and `C-c ,' to
378 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
379 TODO sets, `C-c -' to cycle item bullet types, and properties can be
380 edited by hand or in column view.
382 However, when the cursor is on a timestamp, shift-cursor commands
383 will still edit the time stamp - this is just too good to give up.
385 XEmacs user should have this variable set to nil, because shift-select-mode
386 is Emacs 23 only."
387 :group 'org
388 :type '(choice
389 (const :tag "Never" nil)
390 (const :tag "When outside special context" t)
391 (const :tag "Everywhere except timestamps" always)))
393 (defgroup org-startup nil
394 "Options concerning startup of Org-mode."
395 :tag "Org Startup"
396 :group 'org)
398 (defcustom org-startup-folded t
399 "Non-nil means entering Org-mode will switch to OVERVIEW.
400 This can also be configured on a per-file basis by adding one of
401 the following lines anywhere in the buffer:
403 #+STARTUP: fold (or `overview', this is equivalent)
404 #+STARTUP: nofold (or `showall', this is equivalent)
405 #+STARTUP: content
406 #+STARTUP: showeverything"
407 :group 'org-startup
408 :type '(choice
409 (const :tag "nofold: show all" nil)
410 (const :tag "fold: overview" t)
411 (const :tag "content: all headlines" content)
412 (const :tag "show everything, even drawers" showeverything)))
414 (defcustom org-startup-truncated t
415 "Non-nil means entering Org-mode will set `truncate-lines'.
416 This is useful since some lines containing links can be very long and
417 uninteresting. Also tables look terrible when wrapped."
418 :group 'org-startup
419 :type 'boolean)
421 (defcustom org-startup-indented nil
422 "Non-nil means turn on `org-indent-mode' on startup.
423 This can also be configured on a per-file basis by adding one of
424 the following lines anywhere in the buffer:
426 #+STARTUP: indent
427 #+STARTUP: noindent"
428 :group 'org-structure
429 :type '(choice
430 (const :tag "Not" nil)
431 (const :tag "Globally (slow on startup in large files)" t)))
433 (defcustom org-use-sub-superscripts t
434 "Non-nil means interpret \"_\" and \"^\" for export.
435 When this option is turned on, you can use TeX-like syntax for sub- and
436 superscripts. Several characters after \"_\" or \"^\" will be
437 considered as a single item - so grouping with {} is normally not
438 needed. For example, the following things will be parsed as single
439 sub- or superscripts.
441 10^24 or 10^tau several digits will be considered 1 item.
442 10^-12 or 10^-tau a leading sign with digits or a word
443 x^2-y^3 will be read as x^2 - y^3, because items are
444 terminated by almost any nonword/nondigit char.
445 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
447 Still, ambiguity is possible - so when in doubt use {} to enclose the
448 sub/superscript. If you set this variable to the symbol `{}',
449 the braces are *required* in order to trigger interpretations as
450 sub/superscript. This can be helpful in documents that need \"_\"
451 frequently in plain text.
453 Not all export backends support this, but HTML does.
455 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
456 :group 'org-startup
457 :group 'org-export-translation
458 :type '(choice
459 (const :tag "Always interpret" t)
460 (const :tag "Only with braces" {})
461 (const :tag "Never interpret" nil)))
463 (if (fboundp 'defvaralias)
464 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
467 (defcustom org-startup-with-beamer-mode nil
468 "Non-nil means turn on `org-beamer-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
472 #+STARTUP: beamer"
473 :group 'org-startup
474 :type 'boolean)
476 (defcustom org-startup-align-all-tables nil
477 "Non-nil means align all tables when visiting a file.
478 This is useful when the column width in tables is forced with <N> cookies
479 in table fields. Such tables will look correct only after the first re-align.
480 This can also be configured on a per-file basis by adding one of
481 the following lines anywhere in the buffer:
482 #+STARTUP: align
483 #+STARTUP: noalign"
484 :group 'org-startup
485 :type 'boolean)
487 (defcustom org-startup-with-inline-images nil
488 "Non-nil means show inline images when loading a new Org file.
489 This can also be configured on a per-file basis by adding one of
490 the following lines anywhere in the buffer:
491 #+STARTUP: inlineimages
492 #+STARTUP: noinlineimages"
493 :group 'org-startup
494 :type 'boolean)
496 (defcustom org-insert-mode-line-in-empty-file nil
497 "Non-nil means insert the first line setting Org-mode in empty files.
498 When the function `org-mode' is called interactively in an empty file, this
499 normally means that the file name does not automatically trigger Org-mode.
500 To ensure that the file will always be in Org-mode in the future, a
501 line enforcing Org-mode will be inserted into the buffer, if this option
502 has been set."
503 :group 'org-startup
504 :type 'boolean)
506 (defcustom org-replace-disputed-keys nil
507 "Non-nil means use alternative key bindings for some keys.
508 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
509 These keys are also used by other packages like shift-selection-mode'
510 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
511 If you want to use Org-mode together with one of these other modes,
512 or more generally if you would like to move some Org-mode commands to
513 other keys, set this variable and configure the keys with the variable
514 `org-disputed-keys'.
516 This option is only relevant at load-time of Org-mode, and must be set
517 *before* org.el is loaded. Changing it requires a restart of Emacs to
518 become effective."
519 :group 'org-startup
520 :type 'boolean)
522 (defcustom org-use-extra-keys nil
523 "Non-nil means use extra key sequence definitions for certain commands.
524 This happens automatically if you run XEmacs or if `window-system'
525 is nil. This variable lets you do the same manually. You must
526 set it before loading org.
528 Example: on Carbon Emacs 22 running graphically, with an external
529 keyboard on a Powerbook, the default way of setting M-left might
530 not work for either Alt or ESC. Setting this variable will make
531 it work for ESC."
532 :group 'org-startup
533 :type 'boolean)
535 (if (fboundp 'defvaralias)
536 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
538 (defcustom org-disputed-keys
539 '(([(shift up)] . [(meta p)])
540 ([(shift down)] . [(meta n)])
541 ([(shift left)] . [(meta -)])
542 ([(shift right)] . [(meta +)])
543 ([(control shift right)] . [(meta shift +)])
544 ([(control shift left)] . [(meta shift -)]))
545 "Keys for which Org-mode and other modes compete.
546 This is an alist, cars are the default keys, second element specifies
547 the alternative to use when `org-replace-disputed-keys' is t.
549 Keys can be specified in any syntax supported by `define-key'.
550 The value of this option takes effect only at Org-mode's startup,
551 therefore you'll have to restart Emacs to apply it after changing."
552 :group 'org-startup
553 :type 'alist)
555 (defun org-key (key)
556 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
557 Or return the original if not disputed.
558 Also apply the translations defined in `org-xemacs-key-equivalents'."
559 (when org-replace-disputed-keys
560 (let* ((nkey (key-description key))
561 (x (org-find-if (lambda (x)
562 (equal (key-description (car x)) nkey))
563 org-disputed-keys)))
564 (setq key (if x (cdr x) key))))
565 (when (featurep 'xemacs)
566 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
567 key)
569 (defun org-find-if (predicate seq)
570 (catch 'exit
571 (while seq
572 (if (funcall predicate (car seq))
573 (throw 'exit (car seq))
574 (pop seq)))))
576 (defun org-defkey (keymap key def)
577 "Define a key, possibly translated, as returned by `org-key'."
578 (define-key keymap (org-key key) def))
580 (defcustom org-ellipsis nil
581 "The ellipsis to use in the Org-mode outline.
582 When nil, just use the standard three dots. When a string, use that instead,
583 When a face, use the standard 3 dots, but with the specified face.
584 The change affects only Org-mode (which will then use its own display table).
585 Changing this requires executing `M-x org-mode' in a buffer to become
586 effective."
587 :group 'org-startup
588 :type '(choice (const :tag "Default" nil)
589 (face :tag "Face" :value org-warning)
590 (string :tag "String" :value "...#")))
592 (defvar org-display-table nil
593 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
595 (defgroup org-keywords nil
596 "Keywords in Org-mode."
597 :tag "Org Keywords"
598 :group 'org)
600 (defcustom org-deadline-string "DEADLINE:"
601 "String to mark deadline entries.
602 A deadline is this string, followed by a time stamp. Should be a word,
603 terminated by a colon. You can insert a schedule keyword and
604 a timestamp with \\[org-deadline].
605 Changes become only effective after restarting Emacs."
606 :group 'org-keywords
607 :type 'string)
609 (defcustom org-scheduled-string "SCHEDULED:"
610 "String to mark scheduled TODO entries.
611 A schedule is this string, followed by a time stamp. Should be a word,
612 terminated by a colon. You can insert a schedule keyword and
613 a timestamp with \\[org-schedule].
614 Changes become only effective after restarting Emacs."
615 :group 'org-keywords
616 :type 'string)
618 (defcustom org-closed-string "CLOSED:"
619 "String used as the prefix for timestamps logging closing a TODO entry."
620 :group 'org-keywords
621 :type 'string)
623 (defcustom org-clock-string "CLOCK:"
624 "String used as prefix for timestamps clocking work hours on an item."
625 :group 'org-keywords
626 :type 'string)
628 (defcustom org-comment-string "COMMENT"
629 "Entries starting with this keyword will never be exported.
630 An entry can be toggled between COMMENT and normal with
631 \\[org-toggle-comment].
632 Changes become only effective after restarting Emacs."
633 :group 'org-keywords
634 :type 'string)
636 (defcustom org-quote-string "QUOTE"
637 "Entries starting with this keyword will be exported in fixed-width font.
638 Quoting applies only to the text in the entry following the headline, and does
639 not extend beyond the next headline, even if that is lower level.
640 An entry can be toggled between QUOTE and normal with
641 \\[org-toggle-fixed-width-section]."
642 :group 'org-keywords
643 :type 'string)
645 (defconst org-repeat-re
646 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
647 "Regular expression for specifying repeated events.
648 After a match, group 1 contains the repeat expression.")
650 (defgroup org-structure nil
651 "Options concerning the general structure of Org-mode files."
652 :tag "Org Structure"
653 :group 'org)
655 (defgroup org-reveal-location nil
656 "Options about how to make context of a location visible."
657 :tag "Org Reveal Location"
658 :group 'org-structure)
660 (defconst org-context-choice
661 '(choice
662 (const :tag "Always" t)
663 (const :tag "Never" nil)
664 (repeat :greedy t :tag "Individual contexts"
665 (cons
666 (choice :tag "Context"
667 (const agenda)
668 (const org-goto)
669 (const occur-tree)
670 (const tags-tree)
671 (const link-search)
672 (const mark-goto)
673 (const bookmark-jump)
674 (const isearch)
675 (const default))
676 (boolean))))
677 "Contexts for the reveal options.")
679 (defcustom org-show-hierarchy-above '((default . t))
680 "Non-nil means show full hierarchy when revealing a location.
681 Org-mode often shows locations in an org-mode file which might have
682 been invisible before. When this is set, the hierarchy of headings
683 above the exposed location is shown.
684 Turning this off for example for sparse trees makes them very compact.
685 Instead of t, this can also be an alist specifying this option for different
686 contexts. Valid contexts are
687 agenda when exposing an entry from the agenda
688 org-goto when using the command `org-goto' on key C-c C-j
689 occur-tree when using the command `org-occur' on key C-c /
690 tags-tree when constructing a sparse tree based on tags matches
691 link-search when exposing search matches associated with a link
692 mark-goto when exposing the jump goal of a mark
693 bookmark-jump when exposing a bookmark location
694 isearch when exiting from an incremental search
695 default default for all contexts not set explicitly"
696 :group 'org-reveal-location
697 :type org-context-choice)
699 (defcustom org-show-following-heading '((default . nil))
700 "Non-nil means show following heading when revealing a location.
701 Org-mode often shows locations in an org-mode file which might have
702 been invisible before. When this is set, the heading following the
703 match is shown.
704 Turning this off for example for sparse trees makes them very compact,
705 but makes it harder to edit the location of the match. In such a case,
706 use the command \\[org-reveal] to show more context.
707 Instead of t, this can also be an alist specifying this option for different
708 contexts. See `org-show-hierarchy-above' for valid contexts."
709 :group 'org-reveal-location
710 :type org-context-choice)
712 (defcustom org-show-siblings '((default . nil) (isearch t))
713 "Non-nil means show all sibling 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 sibling of the current entry
716 heading are all made visible. If `org-show-hierarchy-above' is t,
717 the same happens on each level of the hierarchy above the current entry.
719 By default this is on for the isearch context, off for all other contexts.
720 Turning this off for example for sparse trees makes them very compact,
721 but makes it harder to edit the location of the match. In such a case,
722 use the command \\[org-reveal] to show more context.
723 Instead of t, this can also be an alist specifying this option for different
724 contexts. See `org-show-hierarchy-above' for valid contexts."
725 :group 'org-reveal-location
726 :type org-context-choice)
728 (defcustom org-show-entry-below '((default . nil))
729 "Non-nil means show the entry below a headline when revealing a location.
730 Org-mode often shows locations in an org-mode file which might have
731 been invisible before. When this is set, the text below the headline that is
732 exposed is also shown.
734 By default this is off for all contexts.
735 Instead of t, this can also be an alist specifying this option for different
736 contexts. See `org-show-hierarchy-above' for valid contexts."
737 :group 'org-reveal-location
738 :type org-context-choice)
740 (defcustom org-indirect-buffer-display 'other-window
741 "How should indirect tree buffers be displayed?
742 This applies to indirect buffers created with the commands
743 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
744 Valid values are:
745 current-window Display in the current window
746 other-window Just display in another window.
747 dedicated-frame Create one new frame, and re-use it each time.
748 new-frame Make a new frame each time. Note that in this case
749 previously-made indirect buffers are kept, and you need to
750 kill these buffers yourself."
751 :group 'org-structure
752 :group 'org-agenda-windows
753 :type '(choice
754 (const :tag "In current window" current-window)
755 (const :tag "In current frame, other window" other-window)
756 (const :tag "Each time a new frame" new-frame)
757 (const :tag "One dedicated frame" dedicated-frame)))
759 (defcustom org-use-speed-commands nil
760 "Non-nil means activate single letter commands at beginning of a headline.
761 This may also be a function to test for appropriate locations where speed
762 commands should be active."
763 :group 'org-structure
764 :type '(choice
765 (const :tag "Never" nil)
766 (const :tag "At beginning of headline stars" t)
767 (function)))
769 (defcustom org-speed-commands-user nil
770 "Alist of additional speed commands.
771 This list will be checked before `org-speed-commands-default'
772 when the variable `org-use-speed-commands' is non-nil
773 and when the cursor is at the beginning of a headline.
774 The car if each entry is a string with a single letter, which must
775 be assigned to `self-insert-command' in the global map.
776 The cdr is either a command to be called interactively, a function
777 to be called, or a form to be evaluated.
778 An entry that is just a list with a single string will be interpreted
779 as a descriptive headline that will be added when listing the speed
780 commands in the Help buffer using the `?' speed command."
781 :group 'org-structure
782 :type '(repeat :value ("k" . ignore)
783 (choice :value ("k" . ignore)
784 (list :tag "Descriptive Headline" (string :tag "Headline"))
785 (cons :tag "Letter and Command"
786 (string :tag "Command letter")
787 (choice
788 (function)
789 (sexp))))))
791 (defgroup org-cycle nil
792 "Options concerning visibility cycling in Org-mode."
793 :tag "Org Cycle"
794 :group 'org-structure)
796 (defcustom org-cycle-skip-children-state-if-no-children t
797 "Non-nil means skip CHILDREN state in entries that don't have any."
798 :group 'org-cycle
799 :type 'boolean)
801 (defcustom org-cycle-max-level nil
802 "Maximum level which should still be subject to visibility cycling.
803 Levels higher than this will, for cycling, be treated as text, not a headline.
804 When `org-odd-levels-only' is set, a value of N in this variable actually
805 means 2N-1 stars as the limiting headline.
806 When nil, cycle all levels.
807 Note that the limiting level of cycling is also influenced by
808 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
809 `org-inlinetask-min-level' is, cycling will be limited to levels one less
810 than its value."
811 :group 'org-cycle
812 :type '(choice
813 (const :tag "No limit" nil)
814 (integer :tag "Maximum level")))
816 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
817 "Names of drawers. Drawers are not opened by cycling on the headline above.
818 Drawers only open with a TAB on the drawer line itself. A drawer looks like
819 this:
820 :DRAWERNAME:
821 .....
822 :END:
823 The drawer \"PROPERTIES\" is special for capturing properties through
824 the property API.
826 Drawers can be defined on the per-file basis with a line like:
828 #+DRAWERS: HIDDEN STATE PROPERTIES"
829 :group 'org-structure
830 :group 'org-cycle
831 :type '(repeat (string :tag "Drawer Name")))
833 (defcustom org-hide-block-startup nil
834 "Non-nil means entering Org-mode will fold all blocks.
835 This can also be set in on a per-file basis with
837 #+STARTUP: hideblocks
838 #+STARTUP: showblocks"
839 :group 'org-startup
840 :group 'org-cycle
841 :type 'boolean)
843 (defcustom org-cycle-global-at-bob nil
844 "Cycle globally if cursor is at beginning of buffer and not at a headline.
845 This makes it possible to do global cycling without having to use S-TAB or
846 \\[universal-argument] TAB. For this special case to work, the first line \
847 of the buffer
848 must not be a headline - it may be empty or some other text. When used in
849 this way, `org-cycle-hook' is disables temporarily, to make sure the
850 cursor stays at the beginning of the buffer.
851 When this option is nil, don't do anything special at the beginning
852 of the buffer."
853 :group 'org-cycle
854 :type 'boolean)
856 (defcustom org-cycle-level-after-item/entry-creation t
857 "Non-nil means cycle entry level or item indentation in new empty entries.
859 When the cursor is at the end of an empty headline, i.e with only stars
860 and maybe a TODO keyword, TAB will then switch the entry to become a child,
861 and then all possible ancestor states, before returning to the original state.
862 This makes data entry extremely fast: M-RET to create a new headline,
863 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
865 When the cursor is at the end of an empty plain list item, one TAB will
866 make it a subitem, two or more tabs will back up to make this an item
867 higher up in the item hierarchy."
868 :group 'org-cycle
869 :type 'boolean)
871 (defcustom org-cycle-emulate-tab t
872 "Where should `org-cycle' emulate TAB.
873 nil Never
874 white Only in completely white lines
875 whitestart Only at the beginning of lines, before the first non-white char
876 t Everywhere except in headlines
877 exc-hl-bol Everywhere except at the start of a headline
878 If TAB is used in a place where it does not emulate TAB, the current subtree
879 visibility is cycled."
880 :group 'org-cycle
881 :type '(choice (const :tag "Never" nil)
882 (const :tag "Only in completely white lines" white)
883 (const :tag "Before first char in a line" whitestart)
884 (const :tag "Everywhere except in headlines" t)
885 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
888 (defcustom org-cycle-separator-lines 2
889 "Number of empty lines needed to keep an empty line between collapsed trees.
890 If you leave an empty line between the end of a subtree and the following
891 headline, this empty line is hidden when the subtree is folded.
892 Org-mode will leave (exactly) one empty line visible if the number of
893 empty lines is equal or larger to the number given in this variable.
894 So the default 2 means at least 2 empty lines after the end of a subtree
895 are needed to produce free space between a collapsed subtree and the
896 following headline.
898 If the number is negative, and the number of empty lines is at least -N,
899 all empty lines are shown.
901 Special case: when 0, never leave empty lines in collapsed view."
902 :group 'org-cycle
903 :type 'integer)
904 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
906 (defcustom org-pre-cycle-hook nil
907 "Hook that is run before visibility cycling is happening.
908 The function(s) in this hook must accept a single argument which indicates
909 the new state that will be set right after running this hook. The
910 argument is a symbol. Before a global state change, it can have the values
911 `overview', `content', or `all'. Before a local state change, it can have
912 the values `folded', `children', or `subtree'."
913 :group 'org-cycle
914 :type 'hook)
916 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
917 org-cycle-hide-drawers
918 org-cycle-show-empty-lines
919 org-optimize-window-after-visibility-change)
920 "Hook that is run after `org-cycle' has changed the buffer visibility.
921 The function(s) in this hook must accept a single argument which indicates
922 the new state that was set by the most recent `org-cycle' command. The
923 argument is a symbol. After a global state change, it can have the values
924 `overview', `content', or `all'. After a local state change, it can have
925 the values `folded', `children', or `subtree'."
926 :group 'org-cycle
927 :type 'hook)
929 (defgroup org-edit-structure nil
930 "Options concerning structure editing in Org-mode."
931 :tag "Org Edit Structure"
932 :group 'org-structure)
934 (defcustom org-odd-levels-only nil
935 "Non-nil means skip even levels and only use odd levels for the outline.
936 This has the effect that two stars are being added/taken away in
937 promotion/demotion commands. It also influences how levels are
938 handled by the exporters.
939 Changing it requires restart of `font-lock-mode' to become effective
940 for fontification also in regions already fontified.
941 You may also set this on a per-file basis by adding one of the following
942 lines to the buffer:
944 #+STARTUP: odd
945 #+STARTUP: oddeven"
946 :group 'org-edit-structure
947 :group 'org-appearance
948 :type 'boolean)
950 (defcustom org-adapt-indentation t
951 "Non-nil means adapt indentation to outline node level.
953 When this variable is set, Org assumes that you write outlines by
954 indenting text in each node to align with the headline (after the stars).
955 The following issues are influenced by this variable:
957 - When this is set and the *entire* text in an entry is indented, the
958 indentation is increased by one space in a demotion command, and
959 decreased by one in a promotion command. If any line in the entry
960 body starts with text at column 0, indentation is not changed at all.
962 - Property drawers and planning information is inserted indented when
963 this variable s set. When nil, they will not be indented.
965 - TAB indents a line relative to context. The lines below a headline
966 will be indented when this variable is set.
968 Note that this is all about true indentation, by adding and removing
969 space characters. See also `org-indent.el' which does level-dependent
970 indentation in a virtual way, i.e. at display time in Emacs."
971 :group 'org-edit-structure
972 :type 'boolean)
974 (defcustom org-special-ctrl-a/e nil
975 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
977 When t, `C-a' will bring back the cursor to the beginning of the
978 headline text, i.e. after the stars and after a possible TODO keyword.
979 In an item, this will be the position after the bullet.
980 When the cursor is already at that position, another `C-a' will bring
981 it to the beginning of the line.
983 `C-e' will jump to the end of the headline, ignoring the presence of tags
984 in the headline. A second `C-e' will then jump to the true end of the
985 line, after any tags. This also means that, when this variable is
986 non-nil, `C-e' also will never jump beyond the end of the heading of a
987 folded section, i.e. not after the ellipses.
989 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
990 going to the true line boundary first. Only a directly following, identical
991 keypress will bring the cursor to the special positions.
993 This may also be a cons cell where the behavior for `C-a' and `C-e' is
994 set separately."
995 :group 'org-edit-structure
996 :type '(choice
997 (const :tag "off" nil)
998 (const :tag "on: after stars/bullet and before tags first" t)
999 (const :tag "reversed: true line boundary first" reversed)
1000 (cons :tag "Set C-a and C-e separately"
1001 (choice :tag "Special C-a"
1002 (const :tag "off" nil)
1003 (const :tag "on: after stars/bullet first" t)
1004 (const :tag "reversed: before stars/bullet first" reversed))
1005 (choice :tag "Special C-e"
1006 (const :tag "off" nil)
1007 (const :tag "on: before tags first" t)
1008 (const :tag "reversed: after tags first" reversed)))))
1009 (if (fboundp 'defvaralias)
1010 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1012 (defcustom org-special-ctrl-k nil
1013 "Non-nil means `C-k' will behave specially in headlines.
1014 When nil, `C-k' will call the default `kill-line' command.
1015 When t, the following will happen while the cursor is in the headline:
1017 - When the cursor is at the beginning of a headline, kill the entire
1018 line and possible the folded subtree below the line.
1019 - When in the middle of the headline text, kill the headline up to the tags.
1020 - When after the headline text, kill the tags."
1021 :group 'org-edit-structure
1022 :type 'boolean)
1024 (defcustom org-ctrl-k-protect-subtree nil
1025 "Non-nil means, do not delete a hidden subtree with C-k.
1026 When set to the symbol `error', simply throw an error when C-k is
1027 used to kill (part-of) a headline that has hidden text behind it.
1028 Any other non-nil value will result in a query to the user, if it is
1029 OK to kill that hidden subtree. When nil, kill without remorse."
1030 :group 'org-edit-structure
1031 :type '(choice
1032 (const :tag "Do not protect hidden subtrees" nil)
1033 (const :tag "Protect hidden subtrees with a security query" t)
1034 (const :tag "Never kill a hidden subtree with C-k" error)))
1036 (defcustom org-yank-folded-subtrees t
1037 "Non-nil means when yanking subtrees, fold them.
1038 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1039 it starts with a heading and all other headings in it are either children
1040 or siblings, then fold all the subtrees. However, do this only if no
1041 text after the yank would be swallowed into a folded tree by this action."
1042 :group 'org-edit-structure
1043 :type 'boolean)
1045 (defcustom org-yank-adjusted-subtrees nil
1046 "Non-nil means when yanking subtrees, adjust the level.
1047 With this setting, `org-paste-subtree' is used to insert the subtree, see
1048 this function for details."
1049 :group 'org-edit-structure
1050 :type 'boolean)
1052 (defcustom org-M-RET-may-split-line '((default . t))
1053 "Non-nil means M-RET will split the line at the cursor position.
1054 When nil, it will go to the end of the line before making a
1055 new line.
1056 You may also set this option in a different way for different
1057 contexts. Valid contexts are:
1059 headline when creating a new headline
1060 item when creating a new item
1061 table in a table field
1062 default the value to be used for all contexts not explicitly
1063 customized"
1064 :group 'org-structure
1065 :group 'org-table
1066 :type '(choice
1067 (const :tag "Always" t)
1068 (const :tag "Never" nil)
1069 (repeat :greedy t :tag "Individual contexts"
1070 (cons
1071 (choice :tag "Context"
1072 (const headline)
1073 (const item)
1074 (const table)
1075 (const default))
1076 (boolean)))))
1079 (defcustom org-insert-heading-respect-content nil
1080 "Non-nil means insert new headings after the current subtree.
1081 When nil, the new heading is created directly after the current line.
1082 The commands \\[org-insert-heading-respect-content] and
1083 \\[org-insert-todo-heading-respect-content] turn this variable on
1084 for the duration of the command."
1085 :group 'org-structure
1086 :type 'boolean)
1088 (defcustom org-blank-before-new-entry '((heading . auto)
1089 (plain-list-item . auto))
1090 "Should `org-insert-heading' leave a blank line before new heading/item?
1091 The value is an alist, with `heading' and `plain-list-item' as car,
1092 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1093 Org will look at the surrounding headings/items and try to make an
1094 intelligent decision whether to insert a blank line or not.
1096 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1097 set, the setting here is ignored and no empty line is inserted, to avoid
1098 breaking the list structure."
1099 :group 'org-edit-structure
1100 :type '(list
1101 (cons (const heading)
1102 (choice (const :tag "Never" nil)
1103 (const :tag "Always" t)
1104 (const :tag "Auto" auto)))
1105 (cons (const plain-list-item)
1106 (choice (const :tag "Never" nil)
1107 (const :tag "Always" t)
1108 (const :tag "Auto" auto)))))
1110 (defcustom org-insert-heading-hook nil
1111 "Hook being run after inserting a new heading."
1112 :group 'org-edit-structure
1113 :type 'hook)
1115 (defcustom org-enable-fixed-width-editor t
1116 "Non-nil means lines starting with \":\" are treated as fixed-width.
1117 This currently only means they are never auto-wrapped.
1118 When nil, such lines will be treated like ordinary lines.
1119 See also the QUOTE keyword."
1120 :group 'org-edit-structure
1121 :type 'boolean)
1123 (defcustom org-goto-auto-isearch t
1124 "Non-nil means typing characters in `org-goto' starts incremental search."
1125 :group 'org-edit-structure
1126 :type 'boolean)
1128 (defgroup org-sparse-trees nil
1129 "Options concerning sparse trees in Org-mode."
1130 :tag "Org Sparse Trees"
1131 :group 'org-structure)
1133 (defcustom org-highlight-sparse-tree-matches t
1134 "Non-nil means highlight all matches that define a sparse tree.
1135 The highlights will automatically disappear the next time the buffer is
1136 changed by an edit command."
1137 :group 'org-sparse-trees
1138 :type 'boolean)
1140 (defcustom org-remove-highlights-with-change t
1141 "Non-nil means any change to the buffer will remove temporary highlights.
1142 Such highlights are created by `org-occur' and `org-clock-display'.
1143 When nil, `C-c C-c needs to be used to get rid of the highlights.
1144 The highlights created by `org-preview-latex-fragment' always need
1145 `C-c C-c' to be removed."
1146 :group 'org-sparse-trees
1147 :group 'org-time
1148 :type 'boolean)
1151 (defcustom org-occur-hook '(org-first-headline-recenter)
1152 "Hook that is run after `org-occur' has constructed a sparse tree.
1153 This can be used to recenter the window to show as much of the structure
1154 as possible."
1155 :group 'org-sparse-trees
1156 :type 'hook)
1158 (defgroup org-imenu-and-speedbar nil
1159 "Options concerning imenu and speedbar in Org-mode."
1160 :tag "Org Imenu and Speedbar"
1161 :group 'org-structure)
1163 (defcustom org-imenu-depth 2
1164 "The maximum level for Imenu access to Org-mode headlines.
1165 This also applied for speedbar access."
1166 :group 'org-imenu-and-speedbar
1167 :type 'integer)
1169 (defgroup org-table nil
1170 "Options concerning tables in Org-mode."
1171 :tag "Org Table"
1172 :group 'org)
1174 (defcustom org-enable-table-editor 'optimized
1175 "Non-nil means lines starting with \"|\" are handled by the table editor.
1176 When nil, such lines will be treated like ordinary lines.
1178 When equal to the symbol `optimized', the table editor will be optimized to
1179 do the following:
1180 - Automatic overwrite mode in front of whitespace in table fields.
1181 This makes the structure of the table stay in tact as long as the edited
1182 field does not exceed the column width.
1183 - Minimize the number of realigns. Normally, the table is aligned each time
1184 TAB or RET are pressed to move to another field. With optimization this
1185 happens only if changes to a field might have changed the column width.
1186 Optimization requires replacing the functions `self-insert-command',
1187 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1188 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1189 very good at guessing when a re-align will be necessary, but you can always
1190 force one with \\[org-ctrl-c-ctrl-c].
1192 If you would like to use the optimized version in Org-mode, but the
1193 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1195 This variable can be used to turn on and off the table editor during a session,
1196 but in order to toggle optimization, a restart is required.
1198 See also the variable `org-table-auto-blank-field'."
1199 :group 'org-table
1200 :type '(choice
1201 (const :tag "off" nil)
1202 (const :tag "on" t)
1203 (const :tag "on, optimized" optimized)))
1205 (defcustom org-self-insert-cluster-for-undo t
1206 "Non-nil means cluster self-insert commands for undo when possible.
1207 If this is set, then, like in the Emacs command loop, 20 consecutive
1208 characters will be undone together.
1209 This is configurable, because there is some impact on typing performance."
1210 :group 'org-table
1211 :type 'boolean)
1213 (defcustom org-table-tab-recognizes-table.el t
1214 "Non-nil means TAB will automatically notice a table.el table.
1215 When it sees such a table, it moves point into it and - if necessary -
1216 calls `table-recognize-table'."
1217 :group 'org-table-editing
1218 :type 'boolean)
1220 (defgroup org-link nil
1221 "Options concerning links in Org-mode."
1222 :tag "Org Link"
1223 :group 'org)
1225 (defvar org-link-abbrev-alist-local nil
1226 "Buffer-local version of `org-link-abbrev-alist', which see.
1227 The value of this is taken from the #+LINK lines.")
1228 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1230 (defcustom org-link-abbrev-alist nil
1231 "Alist of link abbreviations.
1232 The car of each element is a string, to be replaced at the start of a link.
1233 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1234 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1236 [[linkkey:tag][description]]
1238 The 'linkkey' must be a word word, starting with a letter, followed
1239 by letters, numbers, '-' or '_'.
1241 If REPLACE is a string, the tag will simply be appended to create the link.
1242 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1243 the placeholder \"%h\" will cause a url-encoded version of the tag to
1244 be inserted at that point (see the function `url-hexify-string').
1246 REPLACE may also be a function that will be called with the tag as the
1247 only argument to create the link, which should be returned as a string.
1249 See the manual for examples."
1250 :group 'org-link
1251 :type '(repeat
1252 (cons
1253 (string :tag "Protocol")
1254 (choice
1255 (string :tag "Format")
1256 (function)))))
1258 (defcustom org-descriptive-links t
1259 "Non-nil means hide link part and only show description of bracket links.
1260 Bracket links are like [[link][description]]. This variable sets the initial
1261 state in new org-mode buffers. The setting can then be toggled on a
1262 per-buffer basis from the Org->Hyperlinks menu."
1263 :group 'org-link
1264 :type 'boolean)
1266 (defcustom org-link-file-path-type 'adaptive
1267 "How the path name in file links should be stored.
1268 Valid values are:
1270 relative Relative to the current directory, i.e. the directory of the file
1271 into which the link is being inserted.
1272 absolute Absolute path, if possible with ~ for home directory.
1273 noabbrev Absolute path, no abbreviation of home directory.
1274 adaptive Use relative path for files in the current directory and sub-
1275 directories of it. For other files, use an absolute path."
1276 :group 'org-link
1277 :type '(choice
1278 (const relative)
1279 (const absolute)
1280 (const noabbrev)
1281 (const adaptive)))
1283 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1284 "Types of links that should be activated in Org-mode files.
1285 This is a list of symbols, each leading to the activation of a certain link
1286 type. In principle, it does not hurt to turn on most link types - there may
1287 be a small gain when turning off unused link types. The types are:
1289 bracket The recommended [[link][description]] or [[link]] links with hiding.
1290 angle Links in angular brackets that may contain whitespace like
1291 <bbdb:Carsten Dominik>.
1292 plain Plain links in normal text, no whitespace, like http://google.com.
1293 radio Text that is matched by a radio target, see manual for details.
1294 tag Tag settings in a headline (link to tag search).
1295 date Time stamps (link to calendar).
1296 footnote Footnote labels.
1298 Changing this variable requires a restart of Emacs to become effective."
1299 :group 'org-link
1300 :type '(set :greedy t
1301 (const :tag "Double bracket links" bracket)
1302 (const :tag "Angular bracket links" angle)
1303 (const :tag "Plain text links" plain)
1304 (const :tag "Radio target matches" radio)
1305 (const :tag "Tags" tag)
1306 (const :tag "Timestamps" date)
1307 (const :tag "Footnotes" footnote)))
1309 (defcustom org-make-link-description-function nil
1310 "Function to use to generate link descriptions from links.
1311 If nil the link location will be used. This function must take
1312 two parameters; the first is the link and the second the
1313 description `org-insert-link' has generated, and should return the
1314 description to use."
1315 :group 'org-link
1316 :type 'function)
1318 (defgroup org-link-store nil
1319 "Options concerning storing links in Org-mode."
1320 :tag "Org Store Link"
1321 :group 'org-link)
1323 (defcustom org-email-link-description-format "Email %c: %.30s"
1324 "Format of the description part of a link to an email or usenet message.
1325 The following %-escapes will be replaced by corresponding information:
1327 %F full \"From\" field
1328 %f name, taken from \"From\" field, address if no name
1329 %T full \"To\" field
1330 %t first name in \"To\" field, address if no name
1331 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1332 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1333 %s subject
1334 %d date
1335 %m message-id.
1337 You may use normal field width specification between the % and the letter.
1338 This is for example useful to limit the length of the subject.
1340 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1341 :group 'org-link-store
1342 :type 'string)
1344 (defcustom org-from-is-user-regexp
1345 (let (r1 r2)
1346 (when (and user-mail-address (not (string= user-mail-address "")))
1347 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1348 (when (and user-full-name (not (string= user-full-name "")))
1349 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1350 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1351 "Regexp matched against the \"From:\" header of an email or usenet message.
1352 It should match if the message is from the user him/herself."
1353 :group 'org-link-store
1354 :type 'regexp)
1356 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1357 "Non-nil means storing a link to an Org file will use entry IDs.
1359 Note that before this variable is even considered, org-id must be loaded,
1360 so please customize `org-modules' and turn it on.
1362 The variable can have the following values:
1364 t Create an ID if needed to make a link to the current entry.
1366 create-if-interactive
1367 If `org-store-link' is called directly (interactively, as a user
1368 command), do create an ID to support the link. But when doing the
1369 job for remember, only use the ID if it already exists. The
1370 purpose of this setting is to avoid proliferation of unwanted
1371 IDs, just because you happen to be in an Org file when you
1372 call `org-remember' that automatically and preemptively
1373 creates a link. If you do want to get an ID link in a remember
1374 template to an entry not having an ID, create it first by
1375 explicitly creating a link to it, using `C-c C-l' first.
1377 create-if-interactive-and-no-custom-id
1378 Like create-if-interactive, but do not create an ID if there is
1379 a CUSTOM_ID property defined in the entry. This is the default.
1381 use-existing
1382 Use existing ID, do not create one.
1384 nil Never use an ID to make a link, instead link using a text search for
1385 the headline text."
1386 :group 'org-link-store
1387 :type '(choice
1388 (const :tag "Create ID to make link" t)
1389 (const :tag "Create if storing link interactively"
1390 create-if-interactive)
1391 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1392 create-if-interactive-and-no-custom-id)
1393 (const :tag "Only use existing" use-existing)
1394 (const :tag "Do not use ID to create link" nil)))
1396 (defcustom org-context-in-file-links t
1397 "Non-nil means file links from `org-store-link' contain context.
1398 A search string will be added to the file name with :: as separator and
1399 used to find the context when the link is activated by the command
1400 `org-open-at-point'. When this option is t, the entire active region
1401 will be placed in the search string of the file link. If set to a
1402 positive integer, only the first n lines of context will be stored.
1404 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1405 negates this setting for the duration of the command."
1406 :group 'org-link-store
1407 :type '(choice boolean integer))
1409 (defcustom org-keep-stored-link-after-insertion nil
1410 "Non-nil means keep link in list for entire session.
1412 The command `org-store-link' adds a link pointing to the current
1413 location to an internal list. These links accumulate during a session.
1414 The command `org-insert-link' can be used to insert links into any
1415 Org-mode file (offering completion for all stored links). When this
1416 option is nil, every link which has been inserted once using \\[org-insert-link]
1417 will be removed from the list, to make completing the unused links
1418 more efficient."
1419 :group 'org-link-store
1420 :type 'boolean)
1422 (defgroup org-link-follow nil
1423 "Options concerning following links in Org-mode."
1424 :tag "Org Follow Link"
1425 :group 'org-link)
1427 (defcustom org-link-translation-function nil
1428 "Function to translate links with different syntax to Org syntax.
1429 This can be used to translate links created for example by the Planner
1430 or emacs-wiki packages to Org syntax.
1431 The function must accept two parameters, a TYPE containing the link
1432 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1433 which is everything after the link protocol. It should return a cons
1434 with possibly modified values of type and path.
1435 Org contains a function for this, so if you set this variable to
1436 `org-translate-link-from-planner', you should be able follow many
1437 links created by planner."
1438 :group 'org-link-follow
1439 :type 'function)
1441 (defcustom org-follow-link-hook nil
1442 "Hook that is run after a link has been followed."
1443 :group 'org-link-follow
1444 :type 'hook)
1446 (defcustom org-tab-follows-link nil
1447 "Non-nil means on links TAB will follow the link.
1448 Needs to be set before org.el is loaded.
1449 This really should not be used, it does not make sense, and the
1450 implementation is bad."
1451 :group 'org-link-follow
1452 :type 'boolean)
1454 (defcustom org-return-follows-link nil
1455 "Non-nil means on links RET will follow the link."
1456 :group 'org-link-follow
1457 :type 'boolean)
1459 (defcustom org-mouse-1-follows-link
1460 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1461 "Non-nil means mouse-1 on a link will follow the link.
1462 A longer mouse click will still set point. Does not work on XEmacs.
1463 Needs to be set before org.el is loaded."
1464 :group 'org-link-follow
1465 :type 'boolean)
1467 (defcustom org-mark-ring-length 4
1468 "Number of different positions to be recorded in the ring.
1469 Changing this requires a restart of Emacs to work correctly."
1470 :group 'org-link-follow
1471 :type 'integer)
1473 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1474 "Non-nil means internal links in Org files must exactly match a headline.
1475 When nil, the link search tries to match a phrase with all words
1476 in the search text."
1477 :group 'org-link-follow
1478 :type '(choice
1479 (const :tag "Use fuzy text search" nil)
1480 (const :tag "Match only exact headline" t)
1481 (const :tag "Match extact headline or query to create it"
1482 query-to-create)))
1484 (defcustom org-link-frame-setup
1485 '((vm . vm-visit-folder-other-frame)
1486 (gnus . org-gnus-no-new-news)
1487 (file . find-file-other-window)
1488 (wl . wl-other-frame))
1489 "Setup the frame configuration for following links.
1490 When following a link with Emacs, it may often be useful to display
1491 this link in another window or frame. This variable can be used to
1492 set this up for the different types of links.
1493 For VM, use any of
1494 `vm-visit-folder'
1495 `vm-visit-folder-other-window'
1496 `vm-visit-folder-other-frame'
1497 For Gnus, use any of
1498 `gnus'
1499 `gnus-other-frame'
1500 `org-gnus-no-new-news'
1501 For FILE, use any of
1502 `find-file'
1503 `find-file-other-window'
1504 `find-file-other-frame'
1505 For Wanderlust use any of
1506 `wl'
1507 `wl-other-frame'
1508 For the calendar, use the variable `calendar-setup'.
1509 For BBDB, it is currently only possible to display the matches in
1510 another window."
1511 :group 'org-link-follow
1512 :type '(list
1513 (cons (const vm)
1514 (choice
1515 (const vm-visit-folder)
1516 (const vm-visit-folder-other-window)
1517 (const vm-visit-folder-other-frame)))
1518 (cons (const gnus)
1519 (choice
1520 (const gnus)
1521 (const gnus-other-frame)
1522 (const org-gnus-no-new-news)))
1523 (cons (const file)
1524 (choice
1525 (const find-file)
1526 (const find-file-other-window)
1527 (const find-file-other-frame)))
1528 (cons (const wl)
1529 (choice
1530 (const wl)
1531 (const wl-other-frame)))))
1533 (defcustom org-display-internal-link-with-indirect-buffer nil
1534 "Non-nil means use indirect buffer to display infile links.
1535 Activating internal links (from one location in a file to another location
1536 in the same file) normally just jumps to the location. When the link is
1537 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1538 is displayed in
1539 another window. When this option is set, the other window actually displays
1540 an indirect buffer clone of the current buffer, to avoid any visibility
1541 changes to the current buffer."
1542 :group 'org-link-follow
1543 :type 'boolean)
1545 (defcustom org-open-non-existing-files nil
1546 "Non-nil means `org-open-file' will open non-existing files.
1547 When nil, an error will be generated.
1548 This variable applies only to external applications because they
1549 might choke on non-existing files. If the link is to a file that
1550 will be opened in Emacs, the variable is ignored."
1551 :group 'org-link-follow
1552 :type 'boolean)
1554 (defcustom org-open-directory-means-index-dot-org nil
1555 "Non-nil means a link to a directory really means to index.org.
1556 When nil, following a directory link will run dired or open a finder/explorer
1557 window on that directory."
1558 :group 'org-link-follow
1559 :type 'boolean)
1561 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1562 "Function and arguments to call for following mailto links.
1563 This is a list with the first element being a Lisp function, and the
1564 remaining elements being arguments to the function. In string arguments,
1565 %a will be replaced by the address, and %s will be replaced by the subject
1566 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1567 :group 'org-link-follow
1568 :type '(choice
1569 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1570 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1571 (const :tag "message-mail" (message-mail "%a" "%s"))
1572 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1574 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1575 "Non-nil means ask for confirmation before executing shell links.
1576 Shell links can be dangerous: just think about a link
1578 [[shell:rm -rf ~/*][Google Search]]
1580 This link would show up in your Org-mode document as \"Google Search\",
1581 but really it would remove your entire home directory.
1582 Therefore we advise against setting this variable to nil.
1583 Just change it to `y-or-n-p' if you want to confirm with a
1584 single keystroke rather than having to type \"yes\"."
1585 :group 'org-link-follow
1586 :type '(choice
1587 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1588 (const :tag "with y-or-n (faster)" y-or-n-p)
1589 (const :tag "no confirmation (dangerous)" nil)))
1590 (put 'org-confirm-shell-link-function
1591 'safe-local-variable
1592 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1594 (defcustom org-confirm-shell-link-not-regexp ""
1595 "A regexp to skip confirmation for shell links."
1596 :group 'org-link-follow
1597 :type 'regexp)
1599 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1600 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1601 Elisp links can be dangerous: just think about a link
1603 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1605 This link would show up in your Org-mode document as \"Google Search\",
1606 but really it would remove your entire home directory.
1607 Therefore we advise against setting this variable to nil.
1608 Just change it to `y-or-n-p' if you want to confirm with a
1609 single keystroke rather than having to type \"yes\"."
1610 :group 'org-link-follow
1611 :type '(choice
1612 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1613 (const :tag "with y-or-n (faster)" y-or-n-p)
1614 (const :tag "no confirmation (dangerous)" nil)))
1615 (put 'org-confirm-shell-link-function
1616 'safe-local-variable
1617 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1619 (defcustom org-confirm-elisp-link-not-regexp ""
1620 "A regexp to skip confirmation for Elisp links."
1621 :group 'org-link-follow
1622 :type 'regexp)
1624 (defconst org-file-apps-defaults-gnu
1625 '((remote . emacs)
1626 (system . mailcap)
1627 (t . mailcap))
1628 "Default file applications on a UNIX or GNU/Linux system.
1629 See `org-file-apps'.")
1631 (defconst org-file-apps-defaults-macosx
1632 '((remote . emacs)
1633 (t . "open %s")
1634 (system . "open %s")
1635 ("ps.gz" . "gv %s")
1636 ("eps.gz" . "gv %s")
1637 ("dvi" . "xdvi %s")
1638 ("fig" . "xfig %s"))
1639 "Default file applications on a MacOS X system.
1640 The system \"open\" is known as a default, but we use X11 applications
1641 for some files for which the OS does not have a good default.
1642 See `org-file-apps'.")
1644 (defconst org-file-apps-defaults-windowsnt
1645 (list
1646 '(remote . emacs)
1647 (cons t
1648 (list (if (featurep 'xemacs)
1649 'mswindows-shell-execute
1650 'w32-shell-execute)
1651 "open" 'file))
1652 (cons 'system
1653 (list (if (featurep 'xemacs)
1654 'mswindows-shell-execute
1655 'w32-shell-execute)
1656 "open" 'file)))
1657 "Default file applications on a Windows NT system.
1658 The system \"open\" is used for most files.
1659 See `org-file-apps'.")
1661 (defcustom org-file-apps
1663 (auto-mode . emacs)
1664 ("\\.mm\\'" . default)
1665 ("\\.x?html?\\'" . default)
1666 ("\\.pdf\\'" . default)
1668 "External applications for opening `file:path' items in a document.
1669 Org-mode uses system defaults for different file types, but
1670 you can use this variable to set the application for a given file
1671 extension. The entries in this list are cons cells where the car identifies
1672 files and the cdr the corresponding command. Possible values for the
1673 file identifier are
1674 \"string\" A string as a file identifier can be interpreted in different
1675 ways, depending on its contents:
1677 - Alphanumeric characters only:
1678 Match links with this file extension.
1679 Example: (\"pdf\" . \"evince %s\")
1680 to open PDFs with evince.
1682 - Regular expression: Match links where the
1683 filename matches the regexp. If you want to
1684 use groups here, use shy groups.
1686 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1687 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1688 to open *.html and *.xhtml with firefox.
1690 - Regular expression which contains (non-shy) groups:
1691 Match links where the whole link, including \"::\", and
1692 anything after that, matches the regexp.
1693 In a custom command string, %1, %2, etc. are replaced with
1694 the parts of the link that were matched by the groups.
1695 For backwards compatibility, if a command string is given
1696 that does not use any of the group matches, this case is
1697 handled identically to the second one (i.e. match against
1698 file name only).
1699 In a custom lisp form, you can access the group matches with
1700 (match-string n link).
1702 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1703 to open [[file:document.pdf::5]] with evince at page 5.
1705 `directory' Matches a directory
1706 `remote' Matches a remote file, accessible through tramp or efs.
1707 Remote files most likely should be visited through Emacs
1708 because external applications cannot handle such paths.
1709 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1710 so all files Emacs knows how to handle. Using this with
1711 command `emacs' will open most files in Emacs. Beware that this
1712 will also open html files inside Emacs, unless you add
1713 (\"html\" . default) to the list as well.
1714 t Default for files not matched by any of the other options.
1715 `system' The system command to open files, like `open' on Windows
1716 and Mac OS X, and mailcap under GNU/Linux. This is the command
1717 that will be selected if you call `C-c C-o' with a double
1718 \\[universal-argument] \\[universal-argument] prefix.
1720 Possible values for the command are:
1721 `emacs' The file will be visited by the current Emacs process.
1722 `default' Use the default application for this file type, which is the
1723 association for t in the list, most likely in the system-specific
1724 part.
1725 This can be used to overrule an unwanted setting in the
1726 system-specific variable.
1727 `system' Use the system command for opening files, like \"open\".
1728 This command is specified by the entry whose car is `system'.
1729 Most likely, the system-specific version of this variable
1730 does define this command, but you can overrule/replace it
1731 here.
1732 string A command to be executed by a shell; %s will be replaced
1733 by the path to the file.
1734 sexp A Lisp form which will be evaluated. The file path will
1735 be available in the Lisp variable `file'.
1736 For more examples, see the system specific constants
1737 `org-file-apps-defaults-macosx'
1738 `org-file-apps-defaults-windowsnt'
1739 `org-file-apps-defaults-gnu'."
1740 :group 'org-link-follow
1741 :type '(repeat
1742 (cons (choice :value ""
1743 (string :tag "Extension")
1744 (const :tag "System command to open files" system)
1745 (const :tag "Default for unrecognized files" t)
1746 (const :tag "Remote file" remote)
1747 (const :tag "Links to a directory" directory)
1748 (const :tag "Any files that have Emacs modes"
1749 auto-mode))
1750 (choice :value ""
1751 (const :tag "Visit with Emacs" emacs)
1752 (const :tag "Use default" default)
1753 (const :tag "Use the system command" system)
1754 (string :tag "Command")
1755 (sexp :tag "Lisp form")))))
1759 (defgroup org-refile nil
1760 "Options concerning refiling entries in Org-mode."
1761 :tag "Org Refile"
1762 :group 'org)
1764 (defcustom org-directory "~/org"
1765 "Directory with org files.
1766 This is just a default location to look for Org files. There is no need
1767 at all to put your files into this directory. It is only used in the
1768 following situations:
1770 1. When a remember template specifies a target file that is not an
1771 absolute path. The path will then be interpreted relative to
1772 `org-directory'
1773 2. When a remember note is filed away in an interactive way (when exiting the
1774 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1775 with `org-directory' as the default path."
1776 :group 'org-refile
1777 :group 'org-remember
1778 :type 'directory)
1780 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1781 "Default target for storing notes.
1782 Used as a fall back file for org-remember.el and org-capture.el, for
1783 templates that do not specify a target file."
1784 :group 'org-refile
1785 :group 'org-remember
1786 :type '(choice
1787 (const :tag "Default from remember-data-file" nil)
1788 file))
1790 (defcustom org-goto-interface 'outline
1791 "The default interface to be used for `org-goto'.
1792 Allowed values are:
1793 outline The interface shows an outline of the relevant file
1794 and the correct heading is found by moving through
1795 the outline or by searching with incremental search.
1796 outline-path-completion Headlines in the current buffer are offered via
1797 completion. This is the interface also used by
1798 the refile command."
1799 :group 'org-refile
1800 :type '(choice
1801 (const :tag "Outline" outline)
1802 (const :tag "Outline-path-completion" outline-path-completion)))
1804 (defcustom org-goto-max-level 5
1805 "Maximum target level when running `org-goto' with refile interface."
1806 :group 'org-refile
1807 :type 'integer)
1809 (defcustom org-reverse-note-order nil
1810 "Non-nil means store new notes at the beginning of a file or entry.
1811 When nil, new notes will be filed to the end of a file or entry.
1812 This can also be a list with cons cells of regular expressions that
1813 are matched against file names, and values."
1814 :group 'org-remember
1815 :group 'org-refile
1816 :type '(choice
1817 (const :tag "Reverse always" t)
1818 (const :tag "Reverse never" nil)
1819 (repeat :tag "By file name regexp"
1820 (cons regexp boolean))))
1822 (defcustom org-log-refile nil
1823 "Information to record when a task is refiled.
1825 Possible values are:
1827 nil Don't add anything
1828 time Add a time stamp to the task
1829 note Prompt for a note and add it with template `org-log-note-headings'
1831 This option can also be set with on a per-file-basis with
1833 #+STARTUP: nologrefile
1834 #+STARTUP: logrefile
1835 #+STARTUP: lognoterefile
1837 You can have local logging settings for a subtree by setting the LOGGING
1838 property to one or more of these keywords.
1840 When bulk-refiling from the agenda, the value `note' is forbidden and
1841 will temporarily be changed to `time'."
1842 :group 'org-refile
1843 :group 'org-progress
1844 :type '(choice
1845 (const :tag "No logging" nil)
1846 (const :tag "Record timestamp" time)
1847 (const :tag "Record timestamp with note." note)))
1849 (defcustom org-refile-targets nil
1850 "Targets for refiling entries with \\[org-refile].
1851 This is list of cons cells. Each cell contains:
1852 - a specification of the files to be considered, either a list of files,
1853 or a symbol whose function or variable value will be used to retrieve
1854 a file name or a list of file names. If you use `org-agenda-files' for
1855 that, all agenda files will be scanned for targets. Nil means consider
1856 headings in the current buffer.
1857 - A specification of how to find candidate refile targets. This may be
1858 any of:
1859 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1860 This tag has to be present in all target headlines, inheritance will
1861 not be considered.
1862 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1863 todo keyword.
1864 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1865 headlines that are refiling targets.
1866 - a cons cell (:level . N). Any headline of level N is considered a target.
1867 Note that, when `org-odd-levels-only' is set, level corresponds to
1868 order in hierarchy, not to the number of stars.
1869 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1870 Note that, when `org-odd-levels-only' is set, level corresponds to
1871 order in hierarchy, not to the number of stars.
1873 You can set the variable `org-refile-target-verify-function' to a function
1874 to verify each headline found by the simple criteria above.
1876 When this variable is nil, all top-level headlines in the current buffer
1877 are used, equivalent to the value `((nil . (:level . 1))'."
1878 :group 'org-refile
1879 :type '(repeat
1880 (cons
1881 (choice :value org-agenda-files
1882 (const :tag "All agenda files" org-agenda-files)
1883 (const :tag "Current buffer" nil)
1884 (function) (variable) (file))
1885 (choice :tag "Identify target headline by"
1886 (cons :tag "Specific tag" (const :value :tag) (string))
1887 (cons :tag "TODO keyword" (const :value :todo) (string))
1888 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1889 (cons :tag "Level number" (const :value :level) (integer))
1890 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1892 (defcustom org-refile-target-verify-function nil
1893 "Function to verify if the headline at point should be a refile target.
1894 The function will be called without arguments, with point at the
1895 beginning of the headline. It should return t and leave point
1896 where it is if the headline is a valid target for refiling.
1898 If the target should not be selected, the function must return nil.
1899 In addition to this, it may move point to a place from where the search
1900 should be continued. For example, the function may decide that the entire
1901 subtree of the current entry should be excluded and move point to the end
1902 of the subtree."
1903 :group 'org-refile
1904 :type 'function)
1906 (defcustom org-refile-use-cache nil
1907 "Non-nil means cache refile targets to speed up the process.
1908 The cache for a particular file will be updated automatically when
1909 the buffer has been killed, or when any of the marker used for flagging
1910 refile targets no longer points at a live buffer.
1911 If you have added new entries to a buffer that might themselves be targets,
1912 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1913 find that easier, `C-u C-u C-u C-c C-w'."
1914 :group 'org-refile
1915 :type 'boolean)
1917 (defcustom org-refile-use-outline-path nil
1918 "Non-nil means provide refile targets as paths.
1919 So a level 3 headline will be available as level1/level2/level3.
1921 When the value is `file', also include the file name (without directory)
1922 into the path. In this case, you can also stop the completion after
1923 the file name, to get entries inserted as top level in the file.
1925 When `full-file-path', include the full file path."
1926 :group 'org-refile
1927 :type '(choice
1928 (const :tag "Not" nil)
1929 (const :tag "Yes" t)
1930 (const :tag "Start with file name" file)
1931 (const :tag "Start with full file path" full-file-path)))
1933 (defcustom org-outline-path-complete-in-steps t
1934 "Non-nil means complete the outline path in hierarchical steps.
1935 When Org-mode uses the refile interface to select an outline path
1936 \(see variable `org-refile-use-outline-path'), the completion of
1937 the path can be done is a single go, or if can be done in steps down
1938 the headline hierarchy. Going in steps is probably the best if you
1939 do not use a special completion package like `ido' or `icicles'.
1940 However, when using these packages, going in one step can be very
1941 fast, while still showing the whole path to the entry."
1942 :group 'org-refile
1943 :type 'boolean)
1945 (defcustom org-refile-allow-creating-parent-nodes nil
1946 "Non-nil means allow to create new nodes as refile targets.
1947 New nodes are then created by adding \"/new node name\" to the completion
1948 of an existing node. When the value of this variable is `confirm',
1949 new node creation must be confirmed by the user (recommended)
1950 When nil, the completion must match an existing entry.
1952 Note that, if the new heading is not seen by the criteria
1953 listed in `org-refile-targets', multiple instances of the same
1954 heading would be created by trying again to file under the new
1955 heading."
1956 :group 'org-refile
1957 :type '(choice
1958 (const :tag "Never" nil)
1959 (const :tag "Always" t)
1960 (const :tag "Prompt for confirmation" confirm)))
1962 (defgroup org-todo nil
1963 "Options concerning TODO items in Org-mode."
1964 :tag "Org TODO"
1965 :group 'org)
1967 (defgroup org-progress nil
1968 "Options concerning Progress logging in Org-mode."
1969 :tag "Org Progress"
1970 :group 'org-time)
1972 (defvar org-todo-interpretation-widgets
1974 (:tag "Sequence (cycling hits every state)" sequence)
1975 (:tag "Type (cycling directly to DONE)" type))
1976 "The available interpretation symbols for customizing `org-todo-keywords'.
1977 Interested libraries should add to this list.")
1979 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1980 "List of TODO entry keyword sequences and their interpretation.
1981 \\<org-mode-map>This is a list of sequences.
1983 Each sequence starts with a symbol, either `sequence' or `type',
1984 indicating if the keywords should be interpreted as a sequence of
1985 action steps, or as different types of TODO items. The first
1986 keywords are states requiring action - these states will select a headline
1987 for inclusion into the global TODO list Org-mode produces. If one of
1988 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1989 signify that no further action is necessary. If \"|\" is not found,
1990 the last keyword is treated as the only DONE state of the sequence.
1992 The command \\[org-todo] cycles an entry through these states, and one
1993 additional state where no keyword is present. For details about this
1994 cycling, see the manual.
1996 TODO keywords and interpretation can also be set on a per-file basis with
1997 the special #+SEQ_TODO and #+TYP_TODO lines.
1999 Each keyword can optionally specify a character for fast state selection
2000 \(in combination with the variable `org-use-fast-todo-selection')
2001 and specifiers for state change logging, using the same syntax
2002 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2003 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2004 indicates to record a time stamp each time this state is selected.
2006 Each keyword may also specify if a timestamp or a note should be
2007 recorded when entering or leaving the state, by adding additional
2008 characters in the parenthesis after the keyword. This looks like this:
2009 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2010 record only the time of the state change. With X and Y being either
2011 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2012 Y when leaving the state if and only if the *target* state does not
2013 define X. You may omit any of the fast-selection key or X or /Y,
2014 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2016 For backward compatibility, this variable may also be just a list
2017 of keywords - in this case the interpretation (sequence or type) will be
2018 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2019 :group 'org-todo
2020 :group 'org-keywords
2021 :type '(choice
2022 (repeat :tag "Old syntax, just keywords"
2023 (string :tag "Keyword"))
2024 (repeat :tag "New syntax"
2025 (cons
2026 (choice
2027 :tag "Interpretation"
2028 ;;Quick and dirty way to see
2029 ;;`org-todo-interpretations'. This takes the
2030 ;;place of item arguments
2031 :convert-widget
2032 (lambda (widget)
2033 (widget-put widget
2034 :args (mapcar
2035 #'(lambda (x)
2036 (widget-convert
2037 (cons 'const x)))
2038 org-todo-interpretation-widgets))
2039 widget))
2040 (repeat
2041 (string :tag "Keyword"))))))
2043 (defvar org-todo-keywords-1 nil
2044 "All TODO and DONE keywords active in a buffer.")
2045 (make-variable-buffer-local 'org-todo-keywords-1)
2046 (defvar org-todo-keywords-for-agenda nil)
2047 (defvar org-done-keywords-for-agenda nil)
2048 (defvar org-drawers-for-agenda nil)
2049 (defvar org-todo-keyword-alist-for-agenda nil)
2050 (defvar org-tag-alist-for-agenda nil)
2051 (defvar org-agenda-contributing-files nil)
2052 (defvar org-not-done-keywords nil)
2053 (make-variable-buffer-local 'org-not-done-keywords)
2054 (defvar org-done-keywords nil)
2055 (make-variable-buffer-local 'org-done-keywords)
2056 (defvar org-todo-heads nil)
2057 (make-variable-buffer-local 'org-todo-heads)
2058 (defvar org-todo-sets nil)
2059 (make-variable-buffer-local 'org-todo-sets)
2060 (defvar org-todo-log-states nil)
2061 (make-variable-buffer-local 'org-todo-log-states)
2062 (defvar org-todo-kwd-alist nil)
2063 (make-variable-buffer-local 'org-todo-kwd-alist)
2064 (defvar org-todo-key-alist nil)
2065 (make-variable-buffer-local 'org-todo-key-alist)
2066 (defvar org-todo-key-trigger nil)
2067 (make-variable-buffer-local 'org-todo-key-trigger)
2069 (defcustom org-todo-interpretation 'sequence
2070 "Controls how TODO keywords are interpreted.
2071 This variable is in principle obsolete and is only used for
2072 backward compatibility, if the interpretation of todo keywords is
2073 not given already in `org-todo-keywords'. See that variable for
2074 more information."
2075 :group 'org-todo
2076 :group 'org-keywords
2077 :type '(choice (const sequence)
2078 (const type)))
2080 (defcustom org-use-fast-todo-selection t
2081 "Non-nil means use the fast todo selection scheme with C-c C-t.
2082 This variable describes if and under what circumstances the cycling
2083 mechanism for TODO keywords will be replaced by a single-key, direct
2084 selection scheme.
2086 When nil, fast selection is never used.
2088 When the symbol `prefix', it will be used when `org-todo' is called with
2089 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2090 in an agenda buffer.
2092 When t, fast selection is used by default. In this case, the prefix
2093 argument forces cycling instead.
2095 In all cases, the special interface is only used if access keys have actually
2096 been assigned by the user, i.e. if keywords in the configuration are followed
2097 by a letter in parenthesis, like TODO(t)."
2098 :group 'org-todo
2099 :type '(choice
2100 (const :tag "Never" nil)
2101 (const :tag "By default" t)
2102 (const :tag "Only with C-u C-c C-t" prefix)))
2104 (defcustom org-provide-todo-statistics t
2105 "Non-nil means update todo statistics after insert and toggle.
2106 ALL-HEADLINES means update todo statistics by including headlines
2107 with no TODO keyword as well, counting them as not done.
2108 A list of TODO keywords means the same, but skip keywords that are
2109 not in this list.
2111 When this is set, todo statistics is updated in the parent of the
2112 current entry each time a todo state is changed."
2113 :group 'org-todo
2114 :type '(choice
2115 (const :tag "Yes, only for TODO entries" t)
2116 (const :tag "Yes, including all entries" 'all-headlines)
2117 (repeat :tag "Yes, for TODOs in this list"
2118 (string :tag "TODO keyword"))
2119 (other :tag "No TODO statistics" nil)))
2121 (defcustom org-hierarchical-todo-statistics t
2122 "Non-nil means TODO statistics covers just direct children.
2123 When nil, all entries in the subtree are considered.
2124 This has only an effect if `org-provide-todo-statistics' is set.
2125 To set this to nil for only a single subtree, use a COOKIE_DATA
2126 property and include the word \"recursive\" into the value."
2127 :group 'org-todo
2128 :type 'boolean)
2130 (defcustom org-after-todo-state-change-hook nil
2131 "Hook which is run after the state of a TODO item was changed.
2132 The new state (a string with a TODO keyword, or nil) is available in the
2133 Lisp variable `state'."
2134 :group 'org-todo
2135 :type 'hook)
2137 (defvar org-blocker-hook nil
2138 "Hook for functions that are allowed to block a state change.
2140 Each function gets as its single argument a property list, see
2141 `org-trigger-hook' for more information about this list.
2143 If any of the functions in this hook returns nil, the state change
2144 is blocked.")
2146 (defvar org-trigger-hook nil
2147 "Hook for functions that are triggered by a state change.
2149 Each function gets as its single argument a property list with at least
2150 the following elements:
2152 (:type type-of-change :position pos-at-entry-start
2153 :from old-state :to new-state)
2155 Depending on the type, more properties may be present.
2157 This mechanism is currently implemented for:
2159 TODO state changes
2160 ------------------
2161 :type todo-state-change
2162 :from previous state (keyword as a string), or nil, or a symbol
2163 'todo' or 'done', to indicate the general type of state.
2164 :to new state, like in :from")
2166 (defcustom org-enforce-todo-dependencies nil
2167 "Non-nil means undone TODO entries will block switching the parent to DONE.
2168 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2169 be blocked if any prior sibling is not yet done.
2170 Finally, if the parent is blocked because of ordered siblings of its own,
2171 the child will also be blocked.
2172 This variable needs to be set before org.el is loaded, and you need to
2173 restart Emacs after a change to make the change effective. The only way
2174 to change is while Emacs is running is through the customize interface."
2175 :set (lambda (var val)
2176 (set var val)
2177 (if val
2178 (add-hook 'org-blocker-hook
2179 'org-block-todo-from-children-or-siblings-or-parent)
2180 (remove-hook 'org-blocker-hook
2181 'org-block-todo-from-children-or-siblings-or-parent)))
2182 :group 'org-todo
2183 :type 'boolean)
2185 (defcustom org-enforce-todo-checkbox-dependencies nil
2186 "Non-nil means unchecked boxes will block switching the parent to DONE.
2187 When this is nil, checkboxes have no influence on switching TODO states.
2188 When non-nil, you first need to check off all check boxes before the TODO
2189 entry can be switched to DONE.
2190 This variable needs to be set before org.el is loaded, and you need to
2191 restart Emacs after a change to make the change effective. The only way
2192 to change is while Emacs is running is through the customize interface."
2193 :set (lambda (var val)
2194 (set var val)
2195 (if val
2196 (add-hook 'org-blocker-hook
2197 'org-block-todo-from-checkboxes)
2198 (remove-hook 'org-blocker-hook
2199 'org-block-todo-from-checkboxes)))
2200 :group 'org-todo
2201 :type 'boolean)
2203 (defcustom org-treat-insert-todo-heading-as-state-change nil
2204 "Non-nil means inserting a TODO heading is treated as state change.
2205 So when the command \\[org-insert-todo-heading] is used, state change
2206 logging will apply if appropriate. When nil, the new TODO item will
2207 be inserted directly, and no logging will take place."
2208 :group 'org-todo
2209 :type 'boolean)
2211 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2212 "Non-nil means switching TODO states with S-cursor counts as state change.
2213 This is the default behavior. However, setting this to nil allows a
2214 convenient way to select a TODO state and bypass any logging associated
2215 with that."
2216 :group 'org-todo
2217 :type 'boolean)
2219 (defcustom org-todo-state-tags-triggers nil
2220 "Tag changes that should be triggered by TODO state changes.
2221 This is a list. Each entry is
2223 (state-change (tag . flag) .......)
2225 State-change can be a string with a state, and empty string to indicate the
2226 state that has no TODO keyword, or it can be one of the symbols `todo'
2227 or `done', meaning any not-done or done state, respectively."
2228 :group 'org-todo
2229 :group 'org-tags
2230 :type '(repeat
2231 (cons (choice :tag "When changing to"
2232 (const :tag "Not-done state" todo)
2233 (const :tag "Done state" done)
2234 (string :tag "State"))
2235 (repeat
2236 (cons :tag "Tag action"
2237 (string :tag "Tag")
2238 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2240 (defcustom org-log-done nil
2241 "Information to record when a task moves to the DONE state.
2243 Possible values are:
2245 nil Don't add anything, just change the keyword
2246 time Add a time stamp to the task
2247 note Prompt for a note and add it with template `org-log-note-headings'
2249 This option can also be set with on a per-file-basis with
2251 #+STARTUP: nologdone
2252 #+STARTUP: logdone
2253 #+STARTUP: lognotedone
2255 You can have local logging settings for a subtree by setting the LOGGING
2256 property to one or more of these keywords."
2257 :group 'org-todo
2258 :group 'org-progress
2259 :type '(choice
2260 (const :tag "No logging" nil)
2261 (const :tag "Record CLOSED timestamp" time)
2262 (const :tag "Record CLOSED timestamp with note." note)))
2264 ;; Normalize old uses of org-log-done.
2265 (cond
2266 ((eq org-log-done t) (setq org-log-done 'time))
2267 ((and (listp org-log-done) (memq 'done org-log-done))
2268 (setq org-log-done 'note)))
2270 (defcustom org-log-reschedule nil
2271 "Information to record when the scheduling date of a tasks is modified.
2273 Possible values are:
2275 nil Don't add anything, just change the date
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: nologreschedule
2282 #+STARTUP: logreschedule
2283 #+STARTUP: lognotereschedule"
2284 :group 'org-todo
2285 :group 'org-progress
2286 :type '(choice
2287 (const :tag "No logging" nil)
2288 (const :tag "Record timestamp" time)
2289 (const :tag "Record timestamp with note." note)))
2291 (defcustom org-log-redeadline nil
2292 "Information to record when the deadline date of a tasks is modified.
2294 Possible values are:
2296 nil Don't add anything, just change the date
2297 time Add a time stamp to the task
2298 note Prompt for a note and add it with template `org-log-note-headings'
2300 This option can also be set with on a per-file-basis with
2302 #+STARTUP: nologredeadline
2303 #+STARTUP: logredeadline
2304 #+STARTUP: lognoteredeadline
2306 You can have local logging settings for a subtree by setting the LOGGING
2307 property to one or more of these keywords."
2308 :group 'org-todo
2309 :group 'org-progress
2310 :type '(choice
2311 (const :tag "No logging" nil)
2312 (const :tag "Record timestamp" time)
2313 (const :tag "Record timestamp with note." note)))
2315 (defcustom org-log-note-clock-out nil
2316 "Non-nil means record a note when clocking out of an item.
2317 This can also be configured on a per-file basis by adding one of
2318 the following lines anywhere in the buffer:
2320 #+STARTUP: lognoteclock-out
2321 #+STARTUP: nolognoteclock-out"
2322 :group 'org-todo
2323 :group 'org-progress
2324 :type 'boolean)
2326 (defcustom org-log-done-with-time t
2327 "Non-nil means the CLOSED time stamp will contain date and time.
2328 When nil, only the date will be recorded."
2329 :group 'org-progress
2330 :type 'boolean)
2332 (defcustom org-log-note-headings
2333 '((done . "CLOSING NOTE %t")
2334 (state . "State %-12s from %-12S %t")
2335 (note . "Note taken on %t")
2336 (reschedule . "Rescheduled from %S on %t")
2337 (delschedule . "Not scheduled, was %S on %t")
2338 (redeadline . "New deadline from %S on %t")
2339 (deldeadline . "Removed deadline, was %S on %t")
2340 (refile . "Refiled on %t")
2341 (clock-out . ""))
2342 "Headings for notes added to entries.
2343 The value is an alist, with the car being a symbol indicating the note
2344 context, and the cdr is the heading to be used. The heading may also be the
2345 empty string.
2346 %t in the heading will be replaced by a time stamp.
2347 %T will be an active time stamp instead the default inactive one
2348 %s will be replaced by the new TODO state, in double quotes.
2349 %S will be replaced by the old TODO state, in double quotes.
2350 %u will be replaced by the user name.
2351 %U will be replaced by the full user name.
2353 In fact, it is not a good idea to change the `state' entry, because
2354 agenda log mode depends on the format of these entries."
2355 :group 'org-todo
2356 :group 'org-progress
2357 :type '(list :greedy t
2358 (cons (const :tag "Heading when closing an item" done) string)
2359 (cons (const :tag
2360 "Heading when changing todo state (todo sequence only)"
2361 state) string)
2362 (cons (const :tag "Heading when just taking a note" note) string)
2363 (cons (const :tag "Heading when clocking out" clock-out) string)
2364 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2365 (cons (const :tag "Heading when rescheduling" reschedule) string)
2366 (cons (const :tag "Heading when changing deadline" redeadline) string)
2367 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2368 (cons (const :tag "Heading when refiling" refile) string)))
2370 (unless (assq 'note org-log-note-headings)
2371 (push '(note . "%t") org-log-note-headings))
2373 (defcustom org-log-into-drawer nil
2374 "Non-nil means insert state change notes and time stamps into a drawer.
2375 When nil, state changes notes will be inserted after the headline and
2376 any scheduling and clock lines, but not inside a drawer.
2378 The value of this variable should be the name of the drawer to use.
2379 LOGBOOK is proposed as the default drawer for this purpose, you can
2380 also set this to a string to define the drawer of your choice.
2382 A value of t is also allowed, representing \"LOGBOOK\".
2384 If this variable is set, `org-log-state-notes-insert-after-drawers'
2385 will be ignored.
2387 You can set the property LOG_INTO_DRAWER to overrule this setting for
2388 a subtree."
2389 :group 'org-todo
2390 :group 'org-progress
2391 :type '(choice
2392 (const :tag "Not into a drawer" nil)
2393 (const :tag "LOGBOOK" t)
2394 (string :tag "Other")))
2396 (if (fboundp 'defvaralias)
2397 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2399 (defun org-log-into-drawer ()
2400 "Return the value of `org-log-into-drawer', but let properties overrule.
2401 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2402 used instead of the default value."
2403 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2404 (cond
2405 ((or (not p) (equal p "nil")) org-log-into-drawer)
2406 ((equal p "t") "LOGBOOK")
2407 (t p))))
2409 (defcustom org-log-state-notes-insert-after-drawers nil
2410 "Non-nil means insert state change notes after any drawers in entry.
2411 Only the drawers that *immediately* follow the headline and the
2412 deadline/scheduled line are skipped.
2413 When nil, insert notes right after the heading and perhaps the line
2414 with deadline/scheduling if present.
2416 This variable will have no effect if `org-log-into-drawer' is
2417 set."
2418 :group 'org-todo
2419 :group 'org-progress
2420 :type 'boolean)
2422 (defcustom org-log-states-order-reversed t
2423 "Non-nil means the latest state note will be directly after heading.
2424 When nil, the state change notes will be ordered according to time."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type 'boolean)
2429 (defcustom org-todo-repeat-to-state nil
2430 "The TODO state to which a repeater should return the repeating task.
2431 By default this is the first task in a TODO sequence, or the previous state
2432 in a TODO_TYP set. But you can specify another task here.
2433 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2434 :group 'org-todo
2435 :type '(choice (const :tag "Head of sequence" nil)
2436 (string :tag "Specific state")))
2438 (defcustom org-log-repeat 'time
2439 "Non-nil means record moving through the DONE state when triggering repeat.
2440 An auto-repeating task is immediately switched back to TODO when
2441 marked DONE. If you are not logging state changes (by adding \"@\"
2442 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2443 record a closing note, there will be no record of the task moving
2444 through DONE. This variable forces taking a note anyway.
2446 nil Don't force a record
2447 time Record a time stamp
2448 note Record a note
2450 This option can also be set with on a per-file-basis with
2452 #+STARTUP: logrepeat
2453 #+STARTUP: lognoterepeat
2454 #+STARTUP: nologrepeat
2456 You can have local logging settings for a subtree by setting the LOGGING
2457 property to one or more of these keywords."
2458 :group 'org-todo
2459 :group 'org-progress
2460 :type '(choice
2461 (const :tag "Don't force a record" nil)
2462 (const :tag "Force recording the DONE state" time)
2463 (const :tag "Force recording a note with the DONE state" note)))
2466 (defgroup org-priorities nil
2467 "Priorities in Org-mode."
2468 :tag "Org Priorities"
2469 :group 'org-todo)
2471 (defcustom org-enable-priority-commands t
2472 "Non-nil means priority commands are active.
2473 When nil, these commands will be disabled, so that you never accidentally
2474 set a priority."
2475 :group 'org-priorities
2476 :type 'boolean)
2478 (defcustom org-highest-priority ?A
2479 "The highest priority of TODO items. A character like ?A, ?B etc.
2480 Must have a smaller ASCII number than `org-lowest-priority'."
2481 :group 'org-priorities
2482 :type 'character)
2484 (defcustom org-lowest-priority ?C
2485 "The lowest priority of TODO items. A character like ?A, ?B etc.
2486 Must have a larger ASCII number than `org-highest-priority'."
2487 :group 'org-priorities
2488 :type 'character)
2490 (defcustom org-default-priority ?B
2491 "The default priority of TODO items.
2492 This is the priority an item gets if no explicit priority is given.
2493 When starting to cycle on an empty priority the first step in the cycle
2494 depends on `org-priority-start-cycle-with-default'. The resulting first
2495 step priority must not exceed the range from `org-highest-priority' to
2496 `org-lowest-priority' which means that `org-default-priority' has to be
2497 in this range exclusive or inclusive the range boundaries. Else the
2498 first step refuses to set the default and the second will fall back
2499 to (depending on the command used) the highest or lowest priority."
2500 :group 'org-priorities
2501 :type 'character)
2503 (defcustom org-priority-start-cycle-with-default t
2504 "Non-nil means start with default priority when starting to cycle.
2505 When this is nil, the first step in the cycle will be (depending on the
2506 command used) one higher or lower than the default priority.
2507 See also `org-default-priority'."
2508 :group 'org-priorities
2509 :type 'boolean)
2511 (defcustom org-get-priority-function nil
2512 "Function to extract the priority from a string.
2513 The string is normally the headline. If this is nil Org computes the
2514 priority from the priority cookie like [#A] in the headline. It returns
2515 an integer, increasing by 1000 for each priority level.
2516 The user can set a different function here, which should take a string
2517 as an argument and return the numeric priority."
2518 :group 'org-priorities
2519 :type 'function)
2521 (defgroup org-time nil
2522 "Options concerning time stamps and deadlines in Org-mode."
2523 :tag "Org Time"
2524 :group 'org)
2526 (defcustom org-insert-labeled-timestamps-at-point nil
2527 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2528 When nil, these labeled time stamps are forces into the second line of an
2529 entry, just after the headline. When scheduling from the global TODO list,
2530 the time stamp will always be forced into the second line."
2531 :group 'org-time
2532 :type 'boolean)
2534 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2535 "Formats for `format-time-string' which are used for time stamps.
2536 It is not recommended to change this constant.")
2538 (defcustom org-time-stamp-rounding-minutes '(0 5)
2539 "Number of minutes to round time stamps to.
2540 These are two values, the first applies when first creating a time stamp.
2541 The second applies when changing it with the commands `S-up' and `S-down'.
2542 When changing the time stamp, this means that it will change in steps
2543 of N minutes, as given by the second value.
2545 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2546 numbers should be factors of 60, so for example 5, 10, 15.
2548 When this is larger than 1, you can still force an exact time stamp by using
2549 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2550 and by using a prefix arg to `S-up/down' to specify the exact number
2551 of minutes to shift."
2552 :group 'org-time
2553 :get #'(lambda (var) ; Make sure both elements are there
2554 (if (integerp (default-value var))
2555 (list (default-value var) 5)
2556 (default-value var)))
2557 :type '(list
2558 (integer :tag "when inserting times")
2559 (integer :tag "when modifying times")))
2561 ;; Normalize old customizations of this variable.
2562 (when (integerp org-time-stamp-rounding-minutes)
2563 (setq org-time-stamp-rounding-minutes
2564 (list org-time-stamp-rounding-minutes
2565 org-time-stamp-rounding-minutes)))
2567 (defcustom org-display-custom-times nil
2568 "Non-nil means overlay custom formats over all time stamps.
2569 The formats are defined through the variable `org-time-stamp-custom-formats'.
2570 To turn this on on a per-file basis, insert anywhere in the file:
2571 #+STARTUP: customtime"
2572 :group 'org-time
2573 :set 'set-default
2574 :type 'sexp)
2575 (make-variable-buffer-local 'org-display-custom-times)
2577 (defcustom org-time-stamp-custom-formats
2578 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2579 "Custom formats for time stamps. See `format-time-string' for the syntax.
2580 These are overlayed over the default ISO format if the variable
2581 `org-display-custom-times' is set. Time like %H:%M should be at the
2582 end of the second format. The custom formats are also honored by export
2583 commands, if custom time display is turned on at the time of export."
2584 :group 'org-time
2585 :type 'sexp)
2587 (defun org-time-stamp-format (&optional long inactive)
2588 "Get the right format for a time string."
2589 (let ((f (if long (cdr org-time-stamp-formats)
2590 (car org-time-stamp-formats))))
2591 (if inactive
2592 (concat "[" (substring f 1 -1) "]")
2593 f)))
2595 (defcustom org-time-clocksum-format "%d:%02d"
2596 "The format string used when creating CLOCKSUM lines.
2597 This is also used when org-mode generates a time duration."
2598 :group 'org-time
2599 :type 'string)
2601 (defcustom org-time-clocksum-use-fractional nil
2602 "If non-nil, \\[org-clock-display] uses fractional times.
2603 org-mode generates a time duration."
2604 :group 'org-time
2605 :type 'boolean)
2607 (defcustom org-time-clocksum-fractional-format "%.2f"
2608 "The format string used when creating CLOCKSUM lines, or when
2609 org-mode generates a time duration."
2610 :group 'org-time
2611 :type 'string)
2613 (defcustom org-deadline-warning-days 14
2614 "No. of days before expiration during which a deadline becomes active.
2615 This variable governs the display in sparse trees and in the agenda.
2616 When 0 or negative, it means use this number (the absolute value of it)
2617 even if a deadline has a different individual lead time specified.
2619 Custom commands can set this variable in the options section."
2620 :group 'org-time
2621 :group 'org-agenda-daily/weekly
2622 :type 'integer)
2624 (defcustom org-read-date-prefer-future t
2625 "Non-nil means assume future for incomplete date input from user.
2626 This affects the following situations:
2627 1. The user gives a month but not a year.
2628 For example, if it is April and you enter \"feb 2\", this will be read
2629 as Feb 2, *next* year. \"May 5\", however, will be this year.
2630 2. The user gives a day, but no month.
2631 For example, if today is the 15th, and you enter \"3\", Org-mode will
2632 read this as the third of *next* month. However, if you enter \"17\",
2633 it will be considered as *this* month.
2635 If you set this variable to the symbol `time', then also the following
2636 will work:
2638 3. If the user gives a time, but no day. If the time is before now,
2639 to will be interpreted as tomorrow.
2641 Currently none of this works for ISO week specifications.
2643 When this option is nil, the current day, month and year will always be
2644 used as defaults.
2646 See also `org-agenda-jump-prefer-future'."
2647 :group 'org-time
2648 :type '(choice
2649 (const :tag "Never" nil)
2650 (const :tag "Check month and day" t)
2651 (const :tag "Check month, day, and time" time)))
2653 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2654 "Should the agenda jump command prefer the future for incomplete dates?
2655 The default is to do the same as configured in `org-read-date-prefer-future'.
2656 But you can also set a deviating value here.
2657 This may t or nil, or the symbol `org-read-date-prefer-future'."
2658 :group 'org-agenda
2659 :group 'org-time
2660 :type '(choice
2661 (const :tag "Use org-read-date-prefer-future"
2662 org-read-date-prefer-future)
2663 (const :tag "Never" nil)
2664 (const :tag "Always" t)))
2666 (defcustom org-read-date-force-compatible-dates t
2667 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2669 Depending on the system Emacs is running on, certain dates cannot
2670 be represented with the type used internally to represent time.
2671 Dates between 1970-1-1 and 2038-1-1 can always be represented
2672 correctly. Some systems allow for earlier dates, some for later,
2673 some for both. One way to find out it to insert any date into an
2674 Org buffer, putting the cursor on the year and hitting S-up and
2675 S-down to test the range.
2677 When this variable is set to t, the date/time prompt will not let
2678 you specify dates outside the 1970-2037 range, so it is certain that
2679 these dates will work in whatever version of Emacs you are
2680 running, and also that you can move a file from one Emacs implementation
2681 to another. WHenever Org is forcing the year for you, it will display
2682 a message and beep.
2684 When this variable is nil, Org will check if the date is
2685 representable in the specific Emacs implementation you are using.
2686 If not, it will force a year, usually the current year, and beep
2687 to remind you. Currently this setting is not recommended because
2688 the likelihood that you will open your Org files in an Emacs that
2689 has limited date range is not negligible.
2691 A workaround for this problem is to use diary sexp dates for time
2692 stamps outside of this range."
2693 :group 'org-time
2694 :type 'boolean)
2696 (defcustom org-read-date-display-live t
2697 "Non-nil means display current interpretation of date prompt live.
2698 This display will be in an overlay, in the minibuffer."
2699 :group 'org-time
2700 :type 'boolean)
2702 (defcustom org-read-date-popup-calendar t
2703 "Non-nil means pop up a calendar when prompting for a date.
2704 In the calendar, the date can be selected with mouse-1. However, the
2705 minibuffer will also be active, and you can simply enter the date as well.
2706 When nil, only the minibuffer will be available."
2707 :group 'org-time
2708 :type 'boolean)
2709 (if (fboundp 'defvaralias)
2710 (defvaralias 'org-popup-calendar-for-date-prompt
2711 'org-read-date-popup-calendar))
2713 (defcustom org-read-date-minibuffer-setup-hook nil
2714 "Hook to be used to set up keys for the date/time interface.
2715 Add key definitions to `minibuffer-local-map', which will be a temporary
2716 copy."
2717 :group 'org-time
2718 :type 'hook)
2720 (defcustom org-extend-today-until 0
2721 "The hour when your day really ends. Must be an integer.
2722 This has influence for the following applications:
2723 - When switching the agenda to \"today\". It it is still earlier than
2724 the time given here, the day recognized as TODAY is actually yesterday.
2725 - When a date is read from the user and it is still before the time given
2726 here, the current date and time will be assumed to be yesterday, 23:59.
2727 Also, timestamps inserted in remember templates follow this rule.
2729 IMPORTANT: This is a feature whose implementation is and likely will
2730 remain incomplete. Really, it is only here because past midnight seems to
2731 be the favorite working time of John Wiegley :-)"
2732 :group 'org-time
2733 :type 'integer)
2735 (defcustom org-edit-timestamp-down-means-later nil
2736 "Non-nil means S-down will increase the time in a time stamp.
2737 When nil, S-up will increase."
2738 :group 'org-time
2739 :type 'boolean)
2741 (defcustom org-calendar-follow-timestamp-change t
2742 "Non-nil means make the calendar window follow timestamp changes.
2743 When a timestamp is modified and the calendar window is visible, it will be
2744 moved to the new date."
2745 :group 'org-time
2746 :type 'boolean)
2748 (defgroup org-tags nil
2749 "Options concerning tags in Org-mode."
2750 :tag "Org Tags"
2751 :group 'org)
2753 (defcustom org-tag-alist nil
2754 "List of tags allowed in Org-mode files.
2755 When this list is nil, Org-mode will base TAG input on what is already in the
2756 buffer.
2757 The value of this variable is an alist, the car of each entry must be a
2758 keyword as a string, the cdr may be a character that is used to select
2759 that tag through the fast-tag-selection interface.
2760 See the manual for details."
2761 :group 'org-tags
2762 :type '(repeat
2763 (choice
2764 (cons (string :tag "Tag name")
2765 (character :tag "Access char"))
2766 (list :tag "Start radio group"
2767 (const :startgroup)
2768 (option (string :tag "Group description")))
2769 (list :tag "End radio group"
2770 (const :endgroup)
2771 (option (string :tag "Group description")))
2772 (const :tag "New line" (:newline)))))
2774 (defcustom org-tag-persistent-alist nil
2775 "List of tags that will always appear in all Org-mode files.
2776 This is in addition to any in buffer settings or customizations
2777 of `org-tag-alist'.
2778 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2779 The value of this variable is an alist, the car of each entry must be a
2780 keyword as a string, the cdr may be a character that is used to select
2781 that tag through the fast-tag-selection interface.
2782 See the manual for details.
2783 To disable these tags on a per-file basis, insert anywhere in the file:
2784 #+STARTUP: noptag"
2785 :group 'org-tags
2786 :type '(repeat
2787 (choice
2788 (cons (string :tag "Tag name")
2789 (character :tag "Access char"))
2790 (const :tag "Start radio group" (:startgroup))
2791 (const :tag "End radio group" (:endgroup))
2792 (const :tag "New line" (:newline)))))
2794 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2795 "If non-nil, always offer completion for all tags of all agenda files.
2796 Instead of customizing this variable directly, you might want to
2797 set it locally for capture buffers, because there no list of
2798 tags in that file can be created dynamically (there are none).
2800 (add-hook 'org-capture-mode-hook
2801 (lambda ()
2802 (set (make-local-variable
2803 'org-complete-tags-always-offer-all-agenda-tags)
2804 t)))"
2805 :group 'org-tags
2806 :type 'boolean)
2808 (defvar org-file-tags nil
2809 "List of tags that can be inherited by all entries in the file.
2810 The tags will be inherited if the variable `org-use-tag-inheritance'
2811 says they should be.
2812 This variable is populated from #+FILETAGS lines.")
2814 (defcustom org-use-fast-tag-selection 'auto
2815 "Non-nil means use fast tag selection scheme.
2816 This is a special interface to select and deselect tags with single keys.
2817 When nil, fast selection is never used.
2818 When the symbol `auto', fast selection is used if and only if selection
2819 characters for tags have been configured, either through the variable
2820 `org-tag-alist' or through a #+TAGS line in the buffer.
2821 When t, fast selection is always used and selection keys are assigned
2822 automatically if necessary."
2823 :group 'org-tags
2824 :type '(choice
2825 (const :tag "Always" t)
2826 (const :tag "Never" nil)
2827 (const :tag "When selection characters are configured" 'auto)))
2829 (defcustom org-fast-tag-selection-single-key nil
2830 "Non-nil means fast tag selection exits after first change.
2831 When nil, you have to press RET to exit it.
2832 During fast tag selection, you can toggle this flag with `C-c'.
2833 This variable can also have the value `expert'. In this case, the window
2834 displaying the tags menu is not even shown, until you press C-c again."
2835 :group 'org-tags
2836 :type '(choice
2837 (const :tag "No" nil)
2838 (const :tag "Yes" t)
2839 (const :tag "Expert" expert)))
2841 (defvar org-fast-tag-selection-include-todo nil
2842 "Non-nil means fast tags selection interface will also offer TODO states.
2843 This is an undocumented feature, you should not rely on it.")
2845 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2846 "The column to which tags should be indented in a headline.
2847 If this number is positive, it specifies the column. If it is negative,
2848 it means that the tags should be flushright to that column. For example,
2849 -80 works well for a normal 80 character screen."
2850 :group 'org-tags
2851 :type 'integer)
2853 (defcustom org-auto-align-tags t
2854 "Non-nil keeps tags aligned when modifying headlines.
2855 Some operations (i.e. demoting) change the length of a headline and
2856 therefore shift the tags around. With this option turned on, after
2857 each such operation the tags are again aligned to `org-tags-column'."
2858 :group 'org-tags
2859 :type 'boolean)
2861 (defcustom org-use-tag-inheritance t
2862 "Non-nil means tags in levels apply also for sublevels.
2863 When nil, only the tags directly given in a specific line apply there.
2864 This may also be a list of tags that should be inherited, or a regexp that
2865 matches tags that should be inherited. Additional control is possible
2866 with the variable `org-tags-exclude-from-inheritance' which gives an
2867 explicit list of tags to be excluded from inheritance., even if the value of
2868 `org-use-tag-inheritance' would select it for inheritance.
2870 If this option is t, a match early-on in a tree can lead to a large
2871 number of matches in the subtree when constructing the agenda or creating
2872 a sparse tree. If you only want to see the first match in a tree during
2873 a search, check out the variable `org-tags-match-list-sublevels'."
2874 :group 'org-tags
2875 :type '(choice
2876 (const :tag "Not" nil)
2877 (const :tag "Always" t)
2878 (repeat :tag "Specific tags" (string :tag "Tag"))
2879 (regexp :tag "Tags matched by regexp")))
2881 (defcustom org-tags-exclude-from-inheritance nil
2882 "List of tags that should never be inherited.
2883 This is a way to exclude a few tags from inheritance. For way to do
2884 the opposite, to actively allow inheritance for selected tags,
2885 see the variable `org-use-tag-inheritance'."
2886 :group 'org-tags
2887 :type '(repeat (string :tag "Tag")))
2889 (defun org-tag-inherit-p (tag)
2890 "Check if TAG is one that should be inherited."
2891 (cond
2892 ((member tag org-tags-exclude-from-inheritance) nil)
2893 ((eq org-use-tag-inheritance t) t)
2894 ((not org-use-tag-inheritance) nil)
2895 ((stringp org-use-tag-inheritance)
2896 (string-match org-use-tag-inheritance tag))
2897 ((listp org-use-tag-inheritance)
2898 (member tag org-use-tag-inheritance))
2899 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2901 (defcustom org-tags-match-list-sublevels t
2902 "Non-nil means list also sublevels of headlines matching a search.
2903 This variable applies to tags/property searches, and also to stuck
2904 projects because this search is based on a tags match as well.
2906 When set to the symbol `indented', sublevels are indented with
2907 leading dots.
2909 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2910 the sublevels of a headline matching a tag search often also match
2911 the same search. Listing all of them can create very long lists.
2912 Setting this variable to nil causes subtrees of a match to be skipped.
2914 This variable is semi-obsolete and probably should always be true. It
2915 is better to limit inheritance to certain tags using the variables
2916 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2917 :group 'org-tags
2918 :type '(choice
2919 (const :tag "No, don't list them" nil)
2920 (const :tag "Yes, do list them" t)
2921 (const :tag "List them, indented with leading dots" indented)))
2923 (defcustom org-tags-sort-function nil
2924 "When set, tags are sorted using this function as a comparator."
2925 :group 'org-tags
2926 :type '(choice
2927 (const :tag "No sorting" nil)
2928 (const :tag "Alphabetical" string<)
2929 (const :tag "Reverse alphabetical" string>)
2930 (function :tag "Custom function" nil)))
2932 (defvar org-tags-history nil
2933 "History of minibuffer reads for tags.")
2934 (defvar org-last-tags-completion-table nil
2935 "The last used completion table for tags.")
2936 (defvar org-after-tags-change-hook nil
2937 "Hook that is run after the tags in a line have changed.")
2939 (defgroup org-properties nil
2940 "Options concerning properties in Org-mode."
2941 :tag "Org Properties"
2942 :group 'org)
2944 (defcustom org-property-format "%-10s %s"
2945 "How property key/value pairs should be formatted by `indent-line'.
2946 When `indent-line' hits a property definition, it will format the line
2947 according to this format, mainly to make sure that the values are
2948 lined-up with respect to each other."
2949 :group 'org-properties
2950 :type 'string)
2952 (defcustom org-use-property-inheritance nil
2953 "Non-nil means properties apply also for sublevels.
2955 This setting is chiefly used during property searches. Turning it on can
2956 cause significant overhead when doing a search, which is why it is not
2957 on by default.
2959 When nil, only the properties directly given in the current entry count.
2960 When t, every property is inherited. The value may also be a list of
2961 properties that should have inheritance, or a regular expression matching
2962 properties that should be inherited.
2964 However, note that some special properties use inheritance under special
2965 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2966 and the properties ending in \"_ALL\" when they are used as descriptor
2967 for valid values of a property.
2969 Note for programmers:
2970 When querying an entry with `org-entry-get', you can control if inheritance
2971 should be used. By default, `org-entry-get' looks only at the local
2972 properties. You can request inheritance by setting the inherit argument
2973 to t (to force inheritance) or to `selective' (to respect the setting
2974 in this variable)."
2975 :group 'org-properties
2976 :type '(choice
2977 (const :tag "Not" nil)
2978 (const :tag "Always" t)
2979 (repeat :tag "Specific properties" (string :tag "Property"))
2980 (regexp :tag "Properties matched by regexp")))
2982 (defun org-property-inherit-p (property)
2983 "Check if PROPERTY is one that should be inherited."
2984 (cond
2985 ((eq org-use-property-inheritance t) t)
2986 ((not org-use-property-inheritance) nil)
2987 ((stringp org-use-property-inheritance)
2988 (string-match org-use-property-inheritance property))
2989 ((listp org-use-property-inheritance)
2990 (member property org-use-property-inheritance))
2991 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2993 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2994 "The default column format, if no other format has been defined.
2995 This variable can be set on the per-file basis by inserting a line
2997 #+COLUMNS: %25ITEM ....."
2998 :group 'org-properties
2999 :type 'string)
3001 (defcustom org-columns-ellipses ".."
3002 "The ellipses to be used when a field in column view is truncated.
3003 When this is the empty string, as many characters as possible are shown,
3004 but then there will be no visual indication that the field has been truncated.
3005 When this is a string of length N, the last N characters of a truncated
3006 field are replaced by this string. If the column is narrower than the
3007 ellipses string, only part of the ellipses string will be shown."
3008 :group 'org-properties
3009 :type 'string)
3011 (defcustom org-columns-modify-value-for-display-function nil
3012 "Function that modifies values for display in column view.
3013 For example, it can be used to cut out a certain part from a time stamp.
3014 The function must take 2 arguments:
3016 column-title The title of the column (*not* the property name)
3017 value The value that should be modified.
3019 The function should return the value that should be displayed,
3020 or nil if the normal value should be used."
3021 :group 'org-properties
3022 :type 'function)
3024 (defcustom org-effort-property "Effort"
3025 "The property that is being used to keep track of effort estimates.
3026 Effort estimates given in this property need to have the format H:MM."
3027 :group 'org-properties
3028 :group 'org-progress
3029 :type '(string :tag "Property"))
3031 (defconst org-global-properties-fixed
3032 '(("VISIBILITY_ALL" . "folded children content all")
3033 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3034 "List of property/value pairs that can be inherited by any entry.
3036 These are fixed values, for the preset properties. The user variable
3037 that can be used to add to this list is `org-global-properties'.
3039 The entries in this list are cons cells where the car is a property
3040 name and cdr is a string with the value. If the value represents
3041 multiple items like an \"_ALL\" property, separate the items by
3042 spaces.")
3044 (defcustom org-global-properties nil
3045 "List of property/value pairs that can be inherited by any entry.
3047 This list will be combined with the constant `org-global-properties-fixed'.
3049 The entries in this list are cons cells where the car is a property
3050 name and cdr is a string with the value.
3052 You can set buffer-local values for the same purpose in the variable
3053 `org-file-properties' this by adding lines like
3055 #+PROPERTY: NAME VALUE"
3056 :group 'org-properties
3057 :type '(repeat
3058 (cons (string :tag "Property")
3059 (string :tag "Value"))))
3061 (defvar org-file-properties nil
3062 "List of property/value pairs that can be inherited by any entry.
3063 Valid for the current buffer.
3064 This variable is populated from #+PROPERTY lines.")
3065 (make-variable-buffer-local 'org-file-properties)
3067 (defgroup org-agenda nil
3068 "Options concerning agenda views in Org-mode."
3069 :tag "Org Agenda"
3070 :group 'org)
3072 (defvar org-category nil
3073 "Variable used by org files to set a category for agenda display.
3074 Such files should use a file variable to set it, for example
3076 # -*- mode: org; org-category: \"ELisp\"
3078 or contain a special line
3080 #+CATEGORY: ELisp
3082 If the file does not specify a category, then file's base name
3083 is used instead.")
3084 (make-variable-buffer-local 'org-category)
3085 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3087 (defcustom org-agenda-files nil
3088 "The files to be used for agenda display.
3089 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3090 \\[org-remove-file]. You can also use customize to edit the list.
3092 If an entry is a directory, all files in that directory that are matched by
3093 `org-agenda-file-regexp' will be part of the file list.
3095 If the value of the variable is not a list but a single file name, then
3096 the list of agenda files is actually stored and maintained in that file, one
3097 agenda file per line. In this file paths can be given relative to
3098 `org-directory'. Tilde expansion and environment variable substitution
3099 are also made."
3100 :group 'org-agenda
3101 :type '(choice
3102 (repeat :tag "List of files and directories" file)
3103 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3105 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3106 "Regular expression to match files for `org-agenda-files'.
3107 If any element in the list in that variable contains a directory instead
3108 of a normal file, all files in that directory that are matched by this
3109 regular expression will be included."
3110 :group 'org-agenda
3111 :type 'regexp)
3113 (defcustom org-agenda-text-search-extra-files nil
3114 "List of extra files to be searched by text search commands.
3115 These files will be search in addition to the agenda files by the
3116 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3117 Note that these files will only be searched for text search commands,
3118 not for the other agenda views like todo lists, tag searches or the weekly
3119 agenda. This variable is intended to list notes and possibly archive files
3120 that should also be searched by these two commands.
3121 In fact, if the first element in the list is the symbol `agenda-archives',
3122 than all archive files of all agenda files will be added to the search
3123 scope."
3124 :group 'org-agenda
3125 :type '(set :greedy t
3126 (const :tag "Agenda Archives" agenda-archives)
3127 (repeat :inline t (file))))
3129 (if (fboundp 'defvaralias)
3130 (defvaralias 'org-agenda-multi-occur-extra-files
3131 'org-agenda-text-search-extra-files))
3133 (defcustom org-agenda-skip-unavailable-files nil
3134 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3135 A nil value means to remove them, after a query, from the list."
3136 :group 'org-agenda
3137 :type 'boolean)
3139 (defcustom org-calendar-to-agenda-key [?c]
3140 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3141 The command `org-calendar-goto-agenda' will be bound to this key. The
3142 default is the character `c' because then `c' can be used to switch back and
3143 forth between agenda and calendar."
3144 :group 'org-agenda
3145 :type 'sexp)
3147 (defcustom org-calendar-agenda-action-key [?k]
3148 "The key to be installed in `calendar-mode-map' for agenda-action.
3149 The command `org-agenda-action' will be bound to this key. The
3150 default is the character `k' because we use the same key in the agenda."
3151 :group 'org-agenda
3152 :type 'sexp)
3154 (defcustom org-calendar-insert-diary-entry-key [?i]
3155 "The key to be installed in `calendar-mode-map' for adding diary entries.
3156 This option is irrelevant until `org-agenda-diary-file' has been configured
3157 to point to an Org-mode file. When that is the case, the command
3158 `org-agenda-diary-entry' will be bound to the key given here, by default
3159 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3160 if you want to continue doing this, you need to change this to a different
3161 key."
3162 :group 'org-agenda
3163 :type 'sexp)
3165 (defcustom org-agenda-diary-file 'diary-file
3166 "File to which to add new entries with the `i' key in agenda and calendar.
3167 When this is the symbol `diary-file', the functionality in the Emacs
3168 calendar will be used to add entries to the `diary-file'. But when this
3169 points to a file, `org-agenda-diary-entry' will be used instead."
3170 :group 'org-agenda
3171 :type '(choice
3172 (const :tag "The standard Emacs diary file" diary-file)
3173 (file :tag "Special Org file diary entries")))
3175 (eval-after-load "calendar"
3176 '(progn
3177 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3178 'org-calendar-goto-agenda)
3179 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3180 'org-agenda-action)
3181 (add-hook 'calendar-mode-hook
3182 (lambda ()
3183 (unless (eq org-agenda-diary-file 'diary-file)
3184 (define-key calendar-mode-map
3185 org-calendar-insert-diary-entry-key
3186 'org-agenda-diary-entry))))))
3188 (defgroup org-latex nil
3189 "Options for embedding LaTeX code into Org-mode."
3190 :tag "Org LaTeX"
3191 :group 'org)
3193 (defcustom org-format-latex-options
3194 '(:foreground default :background default :scale 1.0
3195 :html-foreground "Black" :html-background "Transparent"
3196 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3197 "Options for creating images from LaTeX fragments.
3198 This is a property list with the following properties:
3199 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3200 `default' means use the foreground of the default face.
3201 :background the background color, or \"Transparent\".
3202 `default' means use the background of the default face.
3203 :scale a scaling factor for the size of the images, to get more pixels
3204 :html-foreground, :html-background, :html-scale
3205 the same numbers for HTML export.
3206 :matchers a list indicating which matchers should be used to
3207 find LaTeX fragments. Valid members of this list are:
3208 \"begin\" find environments
3209 \"$1\" find single characters surrounded by $.$
3210 \"$\" find math expressions surrounded by $...$
3211 \"$$\" find math expressions surrounded by $$....$$
3212 \"\\(\" find math expressions surrounded by \\(...\\)
3213 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3214 :group 'org-latex
3215 :type 'plist)
3217 (defcustom org-format-latex-signal-error t
3218 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3219 When nil, just push out a message."
3220 :group 'org-latex
3221 :type 'boolean)
3223 (defcustom org-format-latex-header "\\documentclass{article}
3224 \\usepackage[usenames]{color}
3225 \\usepackage{amsmath}
3226 \\usepackage[mathscr]{eucal}
3227 \\pagestyle{empty} % do not remove
3228 \[PACKAGES]
3229 \[DEFAULT-PACKAGES]
3230 % The settings below are copied from fullpage.sty
3231 \\setlength{\\textwidth}{\\paperwidth}
3232 \\addtolength{\\textwidth}{-3cm}
3233 \\setlength{\\oddsidemargin}{1.5cm}
3234 \\addtolength{\\oddsidemargin}{-2.54cm}
3235 \\setlength{\\evensidemargin}{\\oddsidemargin}
3236 \\setlength{\\textheight}{\\paperheight}
3237 \\addtolength{\\textheight}{-\\headheight}
3238 \\addtolength{\\textheight}{-\\headsep}
3239 \\addtolength{\\textheight}{-\\footskip}
3240 \\addtolength{\\textheight}{-3cm}
3241 \\setlength{\\topmargin}{1.5cm}
3242 \\addtolength{\\topmargin}{-2.54cm}"
3243 "The document header used for processing LaTeX fragments.
3244 It is imperative that this header make sure that no page number
3245 appears on the page. The package defined in the variables
3246 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3247 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3248 will be appended."
3249 :group 'org-latex
3250 :type 'string)
3252 (defvar org-format-latex-header-extra nil)
3254 (defun org-set-packages-alist (var val)
3255 "Set the packages alist and make sure it has 3 elements per entry."
3256 (set var (mapcar (lambda (x)
3257 (if (and (consp x) (= (length x) 2))
3258 (list (car x) (nth 1 x) t)
3260 val)))
3262 (defun org-get-packages-alist (var)
3264 "Get the packages alist and make sure it has 3 elements per entry."
3265 (mapcar (lambda (x)
3266 (if (and (consp x) (= (length x) 2))
3267 (list (car x) (nth 1 x) t)
3269 (default-value var)))
3271 ;; The following variables are defined here because is it also used
3272 ;; when formatting latex fragments. Originally it was part of the
3273 ;; LaTeX exporter, which is why the name includes "export".
3274 (defcustom org-export-latex-default-packages-alist
3275 '(("AUTO" "inputenc" t)
3276 ("T1" "fontenc" t)
3277 ("" "fixltx2e" nil)
3278 ("" "graphicx" t)
3279 ("" "longtable" nil)
3280 ("" "float" nil)
3281 ("" "wrapfig" nil)
3282 ("" "soul" t)
3283 ("" "textcomp" t)
3284 ("" "marvosym" t)
3285 ("" "wasysym" t)
3286 ("" "latexsym" t)
3287 ("" "amssymb" t)
3288 ("" "hyperref" nil)
3289 "\\tolerance=1000"
3291 "Alist of default packages to be inserted in the header.
3292 Change this only if one of the packages here causes an incompatibility
3293 with another package you are using.
3294 The packages in this list are needed by one part or another of Org-mode
3295 to function properly.
3297 - inputenc, fontenc: for basic font and character selection
3298 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3299 for interpreting the entities in `org-entities'. You can skip some of these
3300 packages if you don't use any of the symbols in it.
3301 - graphicx: for including images
3302 - float, wrapfig: for figure placement
3303 - longtable: for long tables
3304 - hyperref: for cross references
3306 Therefore you should not modify this variable unless you know what you
3307 are doing. The one reason to change it anyway is that you might be loading
3308 some other package that conflicts with one of the default packages.
3309 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3310 If SNIPPET-FLAG is t, the package also needs to be included when
3311 compiling LaTeX snippets into images for inclusion into HTML."
3312 :group 'org-export-latex
3313 :set 'org-set-packages-alist
3314 :get 'org-get-packages-alist
3315 :type '(repeat
3316 (choice
3317 (list :tag "options/package pair"
3318 (string :tag "options")
3319 (string :tag "package")
3320 (boolean :tag "Snippet"))
3321 (string :tag "A line of LaTeX"))))
3323 (defcustom org-export-latex-packages-alist nil
3324 "Alist of packages to be inserted in every LaTeX header.
3325 These will be inserted after `org-export-latex-default-packages-alist'.
3326 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3327 SNIPPET-FLAG, when t, indicates that this package is also needed when
3328 turning LaTeX snippets into images for inclusion into HTML.
3329 Make sure that you only list packages here which:
3330 - you want in every file
3331 - do not conflict with the default packages in
3332 `org-export-latex-default-packages-alist'
3333 - do not conflict with the setup in `org-format-latex-header'."
3334 :group 'org-export-latex
3335 :set 'org-set-packages-alist
3336 :get 'org-get-packages-alist
3337 :type '(repeat
3338 (choice
3339 (list :tag "options/package pair"
3340 (string :tag "options")
3341 (string :tag "package")
3342 (boolean :tag "Snippet"))
3343 (string :tag "A line of LaTeX"))))
3346 (defgroup org-appearance nil
3347 "Settings for Org-mode appearance."
3348 :tag "Org Appearance"
3349 :group 'org)
3351 (defcustom org-level-color-stars-only nil
3352 "Non-nil means fontify only the stars in each headline.
3353 When nil, the entire headline is fontified.
3354 Changing it requires restart of `font-lock-mode' to become effective
3355 also in regions already fontified."
3356 :group 'org-appearance
3357 :type 'boolean)
3359 (defcustom org-hide-leading-stars nil
3360 "Non-nil means hide the first N-1 stars in a headline.
3361 This works by using the face `org-hide' for these stars. This
3362 face is white for a light background, and black for a dark
3363 background. You may have to customize the face `org-hide' to
3364 make this work.
3365 Changing it requires restart of `font-lock-mode' to become effective
3366 also in regions already fontified.
3367 You may also set this on a per-file basis by adding one of the following
3368 lines to the buffer:
3370 #+STARTUP: hidestars
3371 #+STARTUP: showstars"
3372 :group 'org-appearance
3373 :type 'boolean)
3375 (defcustom org-hidden-keywords nil
3376 "List of symbols corresponding to keywords to be hidden the org buffer.
3377 For example, a value '(title) for this list will make the document's title
3378 appear in the buffer without the initial #+TITLE: keyword."
3379 :group 'org-appearance
3380 :type '(set (const :tag "#+AUTHOR" author)
3381 (const :tag "#+DATE" date)
3382 (const :tag "#+EMAIL" email)
3383 (const :tag "#+TITLE" title)))
3385 (defcustom org-fontify-done-headline nil
3386 "Non-nil means change the face of a headline if it is marked DONE.
3387 Normally, only the TODO/DONE keyword indicates the state of a headline.
3388 When this is non-nil, the headline after the keyword is set to the
3389 `org-headline-done' as an additional indication."
3390 :group 'org-appearance
3391 :type 'boolean)
3393 (defcustom org-fontify-emphasized-text t
3394 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3395 Changing this variable requires a restart of Emacs to take effect."
3396 :group 'org-appearance
3397 :type 'boolean)
3399 (defcustom org-fontify-whole-heading-line nil
3400 "Non-nil means fontify the whole line for headings.
3401 This is useful when setting a background color for the
3402 org-level-* faces."
3403 :group 'org-appearance
3404 :type 'boolean)
3406 (defcustom org-highlight-latex-fragments-and-specials nil
3407 "Non-nil means fontify what is treated specially by the exporters."
3408 :group 'org-appearance
3409 :type 'boolean)
3411 (defcustom org-hide-emphasis-markers nil
3412 "Non-nil mean font-lock should hide the emphasis marker characters."
3413 :group 'org-appearance
3414 :type 'boolean)
3416 (defcustom org-pretty-entities nil
3417 "Non-nil means show entities as UTF8 characters.
3418 When nil, the \\name form remains in the buffer."
3419 :group 'org-appearance
3420 :type 'boolean)
3422 (defcustom org-pretty-entities-include-sub-superscripts t
3423 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3424 :group 'org-appearance
3425 :type 'boolean)
3427 (defvar org-emph-re nil
3428 "Regular expression for matching emphasis.
3429 After a match, the match groups contain these elements:
3430 0 The match of the full regular expression, including the characters
3431 before and after the proper match
3432 1 The character before the proper match, or empty at beginning of line
3433 2 The proper match, including the leading and trailing markers
3434 3 The leading marker like * or /, indicating the type of highlighting
3435 4 The text between the emphasis markers, not including the markers
3436 5 The character after the match, empty at the end of a line")
3437 (defvar org-verbatim-re nil
3438 "Regular expression for matching verbatim text.")
3439 (defvar org-emphasis-regexp-components) ; defined just below
3440 (defvar org-emphasis-alist) ; defined just below
3441 (defun org-set-emph-re (var val)
3442 "Set variable and compute the emphasis regular expression."
3443 (set var val)
3444 (when (and (boundp 'org-emphasis-alist)
3445 (boundp 'org-emphasis-regexp-components)
3446 org-emphasis-alist org-emphasis-regexp-components)
3447 (let* ((e org-emphasis-regexp-components)
3448 (pre (car e))
3449 (post (nth 1 e))
3450 (border (nth 2 e))
3451 (body (nth 3 e))
3452 (nl (nth 4 e))
3453 (body1 (concat body "*?"))
3454 (markers (mapconcat 'car org-emphasis-alist ""))
3455 (vmarkers (mapconcat
3456 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3457 org-emphasis-alist "")))
3458 ;; make sure special characters appear at the right position in the class
3459 (if (string-match "\\^" markers)
3460 (setq markers (concat (replace-match "" t t markers) "^")))
3461 (if (string-match "-" markers)
3462 (setq markers (concat (replace-match "" t t markers) "-")))
3463 (if (string-match "\\^" vmarkers)
3464 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3465 (if (string-match "-" vmarkers)
3466 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3467 (if (> nl 0)
3468 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3469 (int-to-string nl) "\\}")))
3470 ;; Make the regexp
3471 (setq org-emph-re
3472 (concat "\\([" pre "]\\|^\\)"
3473 "\\("
3474 "\\([" markers "]\\)"
3475 "\\("
3476 "[^" border "]\\|"
3477 "[^" border "]"
3478 body1
3479 "[^" border "]"
3480 "\\)"
3481 "\\3\\)"
3482 "\\([" post "]\\|$\\)"))
3483 (setq org-verbatim-re
3484 (concat "\\([" pre "]\\|^\\)"
3485 "\\("
3486 "\\([" vmarkers "]\\)"
3487 "\\("
3488 "[^" border "]\\|"
3489 "[^" border "]"
3490 body1
3491 "[^" border "]"
3492 "\\)"
3493 "\\3\\)"
3494 "\\([" post "]\\|$\\)")))))
3496 (defcustom org-emphasis-regexp-components
3497 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3498 "Components used to build the regular expression for emphasis.
3499 This is a list with five entries. Terminology: In an emphasis string
3500 like \" *strong word* \", we call the initial space PREMATCH, the final
3501 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3502 and \"trong wor\" is the body. The different components in this variable
3503 specify what is allowed/forbidden in each part:
3505 pre Chars allowed as prematch. Beginning of line will be allowed too.
3506 post Chars allowed as postmatch. End of line will be allowed too.
3507 border The chars *forbidden* as border characters.
3508 body-regexp A regexp like \".\" to match a body character. Don't use
3509 non-shy groups here, and don't allow newline here.
3510 newline The maximum number of newlines allowed in an emphasis exp.
3512 Use customize to modify this, or restart Emacs after changing it."
3513 :group 'org-appearance
3514 :set 'org-set-emph-re
3515 :type '(list
3516 (sexp :tag "Allowed chars in pre ")
3517 (sexp :tag "Allowed chars in post ")
3518 (sexp :tag "Forbidden chars in border ")
3519 (sexp :tag "Regexp for body ")
3520 (integer :tag "number of newlines allowed")
3521 (option (boolean :tag "Please ignore this button"))))
3523 (defcustom org-emphasis-alist
3524 `(("*" bold "<b>" "</b>")
3525 ("/" italic "<i>" "</i>")
3526 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3527 ("=" org-code "<code>" "</code>" verbatim)
3528 ("~" org-verbatim "<code>" "</code>" verbatim)
3529 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3530 "<del>" "</del>")
3532 "Special syntax for emphasized text.
3533 Text starting and ending with a special character will be emphasized, for
3534 example *bold*, _underlined_ and /italic/. This variable sets the marker
3535 characters, the face to be used by font-lock for highlighting in Org-mode
3536 Emacs buffers, and the HTML tags to be used for this.
3537 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3538 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3539 Use customize to modify this, or restart Emacs after changing it."
3540 :group 'org-appearance
3541 :set 'org-set-emph-re
3542 :type '(repeat
3543 (list
3544 (string :tag "Marker character")
3545 (choice
3546 (face :tag "Font-lock-face")
3547 (plist :tag "Face property list"))
3548 (string :tag "HTML start tag")
3549 (string :tag "HTML end tag")
3550 (option (const verbatim)))))
3552 (defvar org-protecting-blocks
3553 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3554 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3555 This is needed for font-lock setup.")
3557 ;;; Miscellaneous options
3559 (defgroup org-completion nil
3560 "Completion in Org-mode."
3561 :tag "Org Completion"
3562 :group 'org)
3564 (defcustom org-completion-use-ido nil
3565 "Non-nil means use ido completion wherever possible.
3566 Note that `ido-mode' must be active for this variable to be relevant.
3567 If you decide to turn this variable on, you might well want to turn off
3568 `org-outline-path-complete-in-steps'.
3569 See also `org-completion-use-iswitchb'."
3570 :group 'org-completion
3571 :type 'boolean)
3573 (defcustom org-completion-use-iswitchb nil
3574 "Non-nil means use iswitchb completion wherever possible.
3575 Note that `iswitchb-mode' must be active for this variable to be relevant.
3576 If you decide to turn this variable on, you might well want to turn off
3577 `org-outline-path-complete-in-steps'.
3578 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3579 :group 'org-completion
3580 :type 'boolean)
3582 (defcustom org-completion-fallback-command 'hippie-expand
3583 "The expansion command called by \\[pcomplete] in normal context.
3584 Normal means, no org-mode-specific context."
3585 :group 'org-completion
3586 :type 'function)
3588 ;;; Functions and variables from their packages
3589 ;; Declared here to avoid compiler warnings
3591 ;; XEmacs only
3592 (defvar outline-mode-menu-heading)
3593 (defvar outline-mode-menu-show)
3594 (defvar outline-mode-menu-hide)
3595 (defvar zmacs-regions) ; XEmacs regions
3597 ;; Emacs only
3598 (defvar mark-active)
3600 ;; Various packages
3601 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3602 (declare-function calendar-forward-day "cal-move" (arg))
3603 (declare-function calendar-goto-date "cal-move" (date))
3604 (declare-function calendar-goto-today "cal-move" ())
3605 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3606 (defvar calc-embedded-close-formula)
3607 (defvar calc-embedded-open-formula)
3608 (declare-function cdlatex-tab "ext:cdlatex" ())
3609 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3610 (defvar font-lock-unfontify-region-function)
3611 (declare-function iswitchb-read-buffer "iswitchb"
3612 (prompt &optional default require-match start matches-set))
3613 (defvar iswitchb-temp-buflist)
3614 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3615 (defvar org-agenda-tags-todo-honor-ignore-options)
3616 (declare-function org-agenda-skip "org-agenda" ())
3617 (declare-function
3618 org-format-agenda-item "org-agenda"
3619 (extra txt &optional category tags dotime noprefix remove-re habitp))
3620 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3621 (declare-function org-agenda-change-all-lines "org-agenda"
3622 (newhead hdmarker &optional fixface just-this))
3623 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3624 (declare-function org-agenda-maybe-redo "org-agenda" ())
3625 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3626 (beg end))
3627 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3628 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3629 "org-agenda" (&optional end))
3630 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3631 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3632 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3633 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3634 (declare-function org-indent-mode "org-indent" (&optional arg))
3635 (declare-function parse-time-string "parse-time" (string))
3636 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3637 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3638 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3639 (defvar remember-data-file)
3640 (defvar texmathp-why)
3641 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3642 (declare-function table--at-cell-p "table" (position &optional object at-column))
3644 (defvar w3m-current-url)
3645 (defvar w3m-current-title)
3647 (defvar org-latex-regexps)
3649 ;;; Autoload and prepare some org modules
3651 ;; Some table stuff that needs to be defined here, because it is used
3652 ;; by the functions setting up org-mode or checking for table context.
3654 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3655 "Detect an org-type or table-type table.")
3656 (defconst org-table-line-regexp "^[ \t]*|"
3657 "Detect an org-type table line.")
3658 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3659 "Detect an org-type table line.")
3660 (defconst org-table-hline-regexp "^[ \t]*|-"
3661 "Detect an org-type table hline.")
3662 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3663 "Detect a table-type table hline.")
3664 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3665 "Detect the first line outside a table when searching from within it.
3666 This works for both table types.")
3668 ;; Autoload the functions in org-table.el that are needed by functions here.
3670 (eval-and-compile
3671 (org-autoload "org-table"
3672 '(org-table-align org-table-begin org-table-blank-field
3673 org-table-convert org-table-convert-region org-table-copy-down
3674 org-table-copy-region org-table-create
3675 org-table-create-or-convert-from-region
3676 org-table-create-with-table.el org-table-current-dline
3677 org-table-cut-region org-table-delete-column org-table-edit-field
3678 org-table-edit-formulas org-table-end org-table-eval-formula
3679 org-table-export org-table-field-info
3680 org-table-get-stored-formulas org-table-goto-column
3681 org-table-hline-and-move org-table-import org-table-insert-column
3682 org-table-insert-hline org-table-insert-row org-table-iterate
3683 org-table-justify-field-maybe org-table-kill-row
3684 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3685 org-table-move-column org-table-move-column-left
3686 org-table-move-column-right org-table-move-row
3687 org-table-move-row-down org-table-move-row-up
3688 org-table-next-field org-table-next-row org-table-paste-rectangle
3689 org-table-previous-field org-table-recalculate
3690 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3691 org-table-toggle-coordinate-overlays
3692 org-table-toggle-formula-debugger org-table-wrap-region
3693 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3694 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3695 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3697 (defun org-at-table-p (&optional table-type)
3698 "Return t if the cursor is inside an org-type table.
3699 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3700 (if org-enable-table-editor
3701 (save-excursion
3702 (beginning-of-line 1)
3703 (looking-at (if table-type org-table-any-line-regexp
3704 org-table-line-regexp)))
3705 nil))
3706 (defsubst org-table-p () (org-at-table-p))
3708 (defun org-at-table.el-p ()
3709 "Return t if and only if we are at a table.el table."
3710 (and (org-at-table-p 'any)
3711 (save-excursion
3712 (goto-char (org-table-begin 'any))
3713 (looking-at org-table1-hline-regexp))))
3714 (defun org-table-recognize-table.el ()
3715 "If there is a table.el table nearby, recognize it and move into it."
3716 (if org-table-tab-recognizes-table.el
3717 (if (org-at-table.el-p)
3718 (progn
3719 (beginning-of-line 1)
3720 (if (looking-at org-table-dataline-regexp)
3722 (if (looking-at org-table1-hline-regexp)
3723 (progn
3724 (beginning-of-line 2)
3725 (if (looking-at org-table-any-border-regexp)
3726 (beginning-of-line -1)))))
3727 (if (re-search-forward "|" (org-table-end t) t)
3728 (progn
3729 (require 'table)
3730 (if (table--at-cell-p (point))
3732 (message "recognizing table.el table...")
3733 (table-recognize-table)
3734 (message "recognizing table.el table...done")))
3735 (error "This should not happen"))
3737 nil)
3738 nil))
3740 (defun org-at-table-hline-p ()
3741 "Return t if the cursor is inside a hline in a table."
3742 (if org-enable-table-editor
3743 (save-excursion
3744 (beginning-of-line 1)
3745 (looking-at org-table-hline-regexp))
3746 nil))
3748 (defvar org-table-clean-did-remove-column nil)
3750 (defun org-table-map-tables (function &optional quietly)
3751 "Apply FUNCTION to the start of all tables in the buffer."
3752 (save-excursion
3753 (save-restriction
3754 (widen)
3755 (goto-char (point-min))
3756 (while (re-search-forward org-table-any-line-regexp nil t)
3757 (unless quietly
3758 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3759 (beginning-of-line 1)
3760 (when (looking-at org-table-line-regexp)
3761 (save-excursion (funcall function))
3762 (or (looking-at org-table-line-regexp)
3763 (forward-char 1)))
3764 (re-search-forward org-table-any-border-regexp nil 1))))
3765 (unless quietly (message "Mapping tables: done")))
3767 ;; Declare and autoload functions from org-exp.el & Co
3769 (declare-function org-default-export-plist "org-exp")
3770 (declare-function org-infile-export-plist "org-exp")
3771 (declare-function org-get-current-options "org-exp")
3772 (eval-and-compile
3773 (org-autoload "org-exp"
3774 '(org-export org-export-visible
3775 org-insert-export-options-template
3776 org-table-clean-before-export))
3777 (org-autoload "org-ascii"
3778 '(org-export-as-ascii org-export-ascii-preprocess
3779 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3780 org-export-region-as-ascii))
3781 (org-autoload "org-latex"
3782 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3783 org-replace-region-by-latex org-export-region-as-latex
3784 org-export-as-latex org-export-as-pdf
3785 org-export-as-pdf-and-open))
3786 (org-autoload "org-html"
3787 '(org-export-as-html-and-open
3788 org-export-as-html-batch org-export-as-html-to-buffer
3789 org-replace-region-by-html org-export-region-as-html
3790 org-export-as-html))
3791 (org-autoload "org-docbook"
3792 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3793 org-replace-region-by-docbook org-export-region-as-docbook
3794 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3795 org-export-as-docbook))
3796 (org-autoload "org-icalendar"
3797 '(org-export-icalendar-this-file
3798 org-export-icalendar-all-agenda-files
3799 org-export-icalendar-combine-agenda-files))
3800 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3801 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3803 ;; Declare and autoload functions from org-agenda.el
3805 (eval-and-compile
3806 (org-autoload "org-agenda"
3807 '(org-agenda org-agenda-list org-search-view
3808 org-todo-list org-tags-view org-agenda-list-stuck-projects
3809 org-diary org-agenda-to-appt
3810 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3812 ;; Autoload org-remember
3814 (eval-and-compile
3815 (org-autoload "org-remember"
3816 '(org-remember-insinuate org-remember-annotation
3817 org-remember-apply-template org-remember org-remember-handler)))
3819 (eval-and-compile
3820 (org-autoload "org-capture"
3821 '(org-capture org-capture-insert-template-here
3822 org-capture-import-remember-templates)))
3824 ;; Autoload org-clock.el
3826 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3827 (beg end))
3828 (declare-function org-clock-update-mode-line "org-clock" ())
3829 (declare-function org-resolve-clocks "org-clock"
3830 (&optional also-non-dangling-p prompt last-valid))
3831 (defvar org-clock-start-time)
3832 (defvar org-clock-marker (make-marker)
3833 "Marker recording the last clock-in.")
3834 (defvar org-clock-hd-marker (make-marker)
3835 "Marker recording the last clock-in, but the headline position.")
3836 (defvar org-clock-heading ""
3837 "The heading of the current clock entry.")
3838 (defun org-clock-is-active ()
3839 "Return non-nil if clock is currently running.
3840 The return value is actually the clock marker."
3841 (marker-buffer org-clock-marker))
3843 (eval-and-compile
3844 (org-autoload
3845 "org-clock"
3846 '(org-clock-in org-clock-out org-clock-cancel
3847 org-clock-goto org-clock-sum org-clock-display
3848 org-clock-remove-overlays org-clock-report
3849 org-clocktable-shift org-dblock-write:clocktable
3850 org-get-clocktable org-resolve-clocks)))
3852 (defun org-clock-update-time-maybe ()
3853 "If this is a CLOCK line, update it and return t.
3854 Otherwise, return nil."
3855 (interactive)
3856 (save-excursion
3857 (beginning-of-line 1)
3858 (skip-chars-forward " \t")
3859 (when (looking-at org-clock-string)
3860 (let ((re (concat "[ \t]*" org-clock-string
3861 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3862 "\\([ \t]*=>.*\\)?\\)?"))
3863 ts te h m s neg)
3864 (cond
3865 ((not (looking-at re))
3866 nil)
3867 ((not (match-end 2))
3868 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3869 (> org-clock-marker (point))
3870 (<= org-clock-marker (point-at-eol)))
3871 ;; The clock is running here
3872 (setq org-clock-start-time
3873 (apply 'encode-time
3874 (org-parse-time-string (match-string 1))))
3875 (org-clock-update-mode-line)))
3877 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3878 (end-of-line 1)
3879 (setq ts (match-string 1)
3880 te (match-string 3))
3881 (setq s (- (org-float-time
3882 (apply 'encode-time (org-parse-time-string te)))
3883 (org-float-time
3884 (apply 'encode-time (org-parse-time-string ts))))
3885 neg (< s 0)
3886 s (abs s)
3887 h (floor (/ s 3600))
3888 s (- s (* 3600 h))
3889 m (floor (/ s 60))
3890 s (- s (* 60 s)))
3891 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3892 t))))))
3894 (defun org-check-running-clock ()
3895 "Check if the current buffer contains the running clock.
3896 If yes, offer to stop it and to save the buffer with the changes."
3897 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3898 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3899 (buffer-name))))
3900 (org-clock-out)
3901 (when (y-or-n-p "Save changed buffer?")
3902 (save-buffer))))
3904 (defun org-clocktable-try-shift (dir n)
3905 "Check if this line starts a clock table, if yes, shift the time block."
3906 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3907 (org-clocktable-shift dir n)))
3909 ;; Autoload org-timer.el
3911 (eval-and-compile
3912 (org-autoload
3913 "org-timer"
3914 '(org-timer-start org-timer org-timer-item
3915 org-timer-change-times-in-region
3916 org-timer-set-timer
3917 org-timer-reset-timers
3918 org-timer-show-remaining-time)))
3920 ;; Autoload org-feed.el
3922 (eval-and-compile
3923 (org-autoload
3924 "org-feed"
3925 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3928 ;; Autoload org-indent.el
3930 ;; Define the variable already here, to make sure we have it.
3931 (defvar org-indent-mode nil
3932 "Non-nil if Org-Indent mode is enabled.
3933 Use the command `org-indent-mode' to change this variable.")
3935 (eval-and-compile
3936 (org-autoload
3937 "org-indent"
3938 '(org-indent-mode)))
3940 ;; Autoload org-mobile.el
3942 (eval-and-compile
3943 (org-autoload
3944 "org-mobile"
3945 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3947 ;; Autoload archiving code
3948 ;; The stuff that is needed for cycling and tags has to be defined here.
3950 (defgroup org-archive nil
3951 "Options concerning archiving in Org-mode."
3952 :tag "Org Archive"
3953 :group 'org-structure)
3955 (defcustom org-archive-location "%s_archive::"
3956 "The location where subtrees should be archived.
3958 The value of this variable is a string, consisting of two parts,
3959 separated by a double-colon. The first part is a filename and
3960 the second part is a headline.
3962 When the filename is omitted, archiving happens in the same file.
3963 %s in the filename will be replaced by the current file
3964 name (without the directory part). Archiving to a different file
3965 is useful to keep archived entries from contributing to the
3966 Org-mode Agenda.
3968 The archived entries will be filed as subtrees of the specified
3969 headline. When the headline is omitted, the subtrees are simply
3970 filed away at the end of the file, as top-level entries. Also in
3971 the heading you can use %s to represent the file name, this can be
3972 useful when using the same archive for a number of different files.
3974 Here are a few examples:
3975 \"%s_archive::\"
3976 If the current file is Projects.org, archive in file
3977 Projects.org_archive, as top-level trees. This is the default.
3979 \"::* Archived Tasks\"
3980 Archive in the current file, under the top-level headline
3981 \"* Archived Tasks\".
3983 \"~/org/archive.org::\"
3984 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3986 \"~/org/archive.org::From %s\"
3987 Archive in file ~/org/archive.org (absolute path), under headlines
3988 \"From FILENAME\" where file name is the current file name.
3990 \"basement::** Finished Tasks\"
3991 Archive in file ./basement (relative path), as level 3 trees
3992 below the level 2 heading \"** Finished Tasks\".
3994 You may set this option on a per-file basis by adding to the buffer a
3995 line like
3997 #+ARCHIVE: basement::** Finished Tasks
3999 You may also define it locally for a subtree by setting an ARCHIVE property
4000 in the entry. If such a property is found in an entry, or anywhere up
4001 the hierarchy, it will be used."
4002 :group 'org-archive
4003 :type 'string)
4005 (defcustom org-archive-tag "ARCHIVE"
4006 "The tag that marks a subtree as archived.
4007 An archived subtree does not open during visibility cycling, and does
4008 not contribute to the agenda listings.
4009 After changing this, font-lock must be restarted in the relevant buffers to
4010 get the proper fontification."
4011 :group 'org-archive
4012 :group 'org-keywords
4013 :type 'string)
4015 (defcustom org-agenda-skip-archived-trees t
4016 "Non-nil means the agenda will skip any items located in archived trees.
4017 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4018 variable is no longer recommended, you should leave it at the value t.
4019 Instead, use the key `v' to cycle the archives-mode in the agenda."
4020 :group 'org-archive
4021 :group 'org-agenda-skip
4022 :type 'boolean)
4024 (defcustom org-columns-skip-archived-trees t
4025 "Non-nil means ignore archived trees when creating column view."
4026 :group 'org-archive
4027 :group 'org-properties
4028 :type 'boolean)
4030 (defcustom org-cycle-open-archived-trees nil
4031 "Non-nil means `org-cycle' will open archived trees.
4032 An archived tree is a tree marked with the tag ARCHIVE.
4033 When nil, archived trees will stay folded. You can still open them with
4034 normal outline commands like `show-all', but not with the cycling commands."
4035 :group 'org-archive
4036 :group 'org-cycle
4037 :type 'boolean)
4039 (defcustom org-sparse-tree-open-archived-trees nil
4040 "Non-nil means sparse tree construction shows matches in archived trees.
4041 When nil, matches in these trees are highlighted, but the trees are kept in
4042 collapsed state."
4043 :group 'org-archive
4044 :group 'org-sparse-trees
4045 :type 'boolean)
4047 (defun org-cycle-hide-archived-subtrees (state)
4048 "Re-hide all archived subtrees after a visibility state change."
4049 (when (and (not org-cycle-open-archived-trees)
4050 (not (memq state '(overview folded))))
4051 (save-excursion
4052 (let* ((globalp (memq state '(contents all)))
4053 (beg (if globalp (point-min) (point)))
4054 (end (if globalp (point-max) (org-end-of-subtree t))))
4055 (org-hide-archived-subtrees beg end)
4056 (goto-char beg)
4057 (if (looking-at (concat ".*:" org-archive-tag ":"))
4058 (message "%s" (substitute-command-keys
4059 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4061 (defun org-force-cycle-archived ()
4062 "Cycle subtree even if it is archived."
4063 (interactive)
4064 (setq this-command 'org-cycle)
4065 (let ((org-cycle-open-archived-trees t))
4066 (call-interactively 'org-cycle)))
4068 (defun org-hide-archived-subtrees (beg end)
4069 "Re-hide all archived subtrees after a visibility state change."
4070 (save-excursion
4071 (let* ((re (concat ":" org-archive-tag ":")))
4072 (goto-char beg)
4073 (while (re-search-forward re end t)
4074 (when (org-on-heading-p)
4075 (org-flag-subtree t)
4076 (org-end-of-subtree t))))))
4078 (defun org-flag-subtree (flag)
4079 (save-excursion
4080 (org-back-to-heading t)
4081 (outline-end-of-heading)
4082 (outline-flag-region (point)
4083 (progn (org-end-of-subtree t) (point))
4084 flag)))
4086 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4088 (eval-and-compile
4089 (org-autoload "org-archive"
4090 '(org-add-archive-files org-archive-subtree
4091 org-archive-to-archive-sibling org-toggle-archive-tag
4092 org-archive-subtree-default
4093 org-archive-subtree-default-with-confirmation)))
4095 ;; Autoload Column View Code
4097 (declare-function org-columns-number-to-string "org-colview")
4098 (declare-function org-columns-get-format-and-top-level "org-colview")
4099 (declare-function org-columns-compute "org-colview")
4101 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4102 '(org-columns-number-to-string org-columns-get-format-and-top-level
4103 org-columns-compute org-agenda-columns org-columns-remove-overlays
4104 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4106 ;; Autoload ID code
4108 (declare-function org-id-store-link "org-id")
4109 (declare-function org-id-locations-load "org-id")
4110 (declare-function org-id-locations-save "org-id")
4111 (defvar org-id-track-globally)
4112 (org-autoload "org-id"
4113 '(org-id-get-create org-id-new org-id-copy org-id-get
4114 org-id-get-with-outline-path-completion
4115 org-id-get-with-outline-drilling org-id-store-link
4116 org-id-goto org-id-find org-id-store-link))
4118 ;; Autoload Plotting Code
4120 (org-autoload "org-plot"
4121 '(org-plot/gnuplot))
4123 ;;; Variables for pre-computed regular expressions, all buffer local
4125 (defvar org-drawer-regexp nil
4126 "Matches first line of a hidden block.")
4127 (make-variable-buffer-local 'org-drawer-regexp)
4128 (defvar org-todo-regexp nil
4129 "Matches any of the TODO state keywords.")
4130 (make-variable-buffer-local 'org-todo-regexp)
4131 (defvar org-not-done-regexp nil
4132 "Matches any of the TODO state keywords except the last one.")
4133 (make-variable-buffer-local 'org-not-done-regexp)
4134 (defvar org-not-done-heading-regexp nil
4135 "Matches a TODO headline that is not done.")
4136 (make-variable-buffer-local 'org-not-done-regexp)
4137 (defvar org-todo-line-regexp nil
4138 "Matches a headline and puts TODO state into group 2 if present.")
4139 (make-variable-buffer-local 'org-todo-line-regexp)
4140 (defvar org-complex-heading-regexp nil
4141 "Matches a headline and puts everything into groups:
4142 group 1: the stars
4143 group 2: The todo keyword, maybe
4144 group 3: Priority cookie
4145 group 4: True headline
4146 group 5: Tags")
4147 (make-variable-buffer-local 'org-complex-heading-regexp)
4148 (defvar org-complex-heading-regexp-format nil
4149 "Printf format to make regexp to match an exact headline.
4150 This regexp will match the headline of any node which hase the exact
4151 headline text that is put into the format, but may have any TODO state,
4152 priority and tags.")
4153 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4154 (defvar org-todo-line-tags-regexp nil
4155 "Matches a headline and puts TODO state into group 2 if present.
4156 Also put tags into group 4 if tags are present.")
4157 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4158 (defvar org-nl-done-regexp nil
4159 "Matches newline followed by a headline with the DONE keyword.")
4160 (make-variable-buffer-local 'org-nl-done-regexp)
4161 (defvar org-looking-at-done-regexp nil
4162 "Matches the DONE keyword a point.")
4163 (make-variable-buffer-local 'org-looking-at-done-regexp)
4164 (defvar org-ds-keyword-length 12
4165 "Maximum length of the Deadline and SCHEDULED keywords.")
4166 (make-variable-buffer-local 'org-ds-keyword-length)
4167 (defvar org-deadline-regexp nil
4168 "Matches the DEADLINE keyword.")
4169 (make-variable-buffer-local 'org-deadline-regexp)
4170 (defvar org-deadline-time-regexp nil
4171 "Matches the DEADLINE keyword together with a time stamp.")
4172 (make-variable-buffer-local 'org-deadline-time-regexp)
4173 (defvar org-deadline-line-regexp nil
4174 "Matches the DEADLINE keyword and the rest of the line.")
4175 (make-variable-buffer-local 'org-deadline-line-regexp)
4176 (defvar org-scheduled-regexp nil
4177 "Matches the SCHEDULED keyword.")
4178 (make-variable-buffer-local 'org-scheduled-regexp)
4179 (defvar org-scheduled-time-regexp nil
4180 "Matches the SCHEDULED keyword together with a time stamp.")
4181 (make-variable-buffer-local 'org-scheduled-time-regexp)
4182 (defvar org-closed-time-regexp nil
4183 "Matches the CLOSED keyword together with a time stamp.")
4184 (make-variable-buffer-local 'org-closed-time-regexp)
4186 (defvar org-keyword-time-regexp nil
4187 "Matches any of the 4 keywords, together with the time stamp.")
4188 (make-variable-buffer-local 'org-keyword-time-regexp)
4189 (defvar org-keyword-time-not-clock-regexp nil
4190 "Matches any of the 3 keywords, together with the time stamp.")
4191 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4192 (defvar org-maybe-keyword-time-regexp nil
4193 "Matches a timestamp, possibly preceded by a keyword.")
4194 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4195 (defvar org-planning-or-clock-line-re nil
4196 "Matches a line with planning or clock info.")
4197 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4198 (defvar org-all-time-keywords nil
4199 "List of time keywords.")
4200 (make-variable-buffer-local 'org-all-time-keywords)
4202 (defconst org-plain-time-of-day-regexp
4203 (concat
4204 "\\(\\<[012]?[0-9]"
4205 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4206 "\\(--?"
4207 "\\(\\<[012]?[0-9]"
4208 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4209 "\\)?")
4210 "Regular expression to match a plain time or time range.
4211 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4212 groups carry important information:
4213 0 the full match
4214 1 the first time, range or not
4215 8 the second time, if it is a range.")
4217 (defconst org-plain-time-extension-regexp
4218 (concat
4219 "\\(\\<[012]?[0-9]"
4220 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4221 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4222 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4223 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4224 groups carry important information:
4225 0 the full match
4226 7 hours of duration
4227 9 minutes of duration")
4229 (defconst org-stamp-time-of-day-regexp
4230 (concat
4231 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4232 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4233 "\\(--?"
4234 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4235 "Regular expression to match a timestamp time or time range.
4236 After a match, the following groups carry important information:
4237 0 the full match
4238 1 date plus weekday, for back referencing to make sure both times are on the same day
4239 2 the first time, range or not
4240 4 the second time, if it is a range.")
4242 (defconst org-startup-options
4243 '(("fold" org-startup-folded t)
4244 ("overview" org-startup-folded t)
4245 ("nofold" org-startup-folded nil)
4246 ("showall" org-startup-folded nil)
4247 ("showeverything" org-startup-folded showeverything)
4248 ("content" org-startup-folded content)
4249 ("indent" org-startup-indented t)
4250 ("noindent" org-startup-indented nil)
4251 ("hidestars" org-hide-leading-stars t)
4252 ("showstars" org-hide-leading-stars nil)
4253 ("odd" org-odd-levels-only t)
4254 ("oddeven" org-odd-levels-only nil)
4255 ("align" org-startup-align-all-tables t)
4256 ("noalign" org-startup-align-all-tables nil)
4257 ("inlineimages" org-startup-with-inline-images t)
4258 ("noinlineimages" org-startup-with-inline-images nil)
4259 ("customtime" org-display-custom-times t)
4260 ("logdone" org-log-done time)
4261 ("lognotedone" org-log-done note)
4262 ("nologdone" org-log-done nil)
4263 ("lognoteclock-out" org-log-note-clock-out t)
4264 ("nolognoteclock-out" org-log-note-clock-out nil)
4265 ("logrepeat" org-log-repeat state)
4266 ("lognoterepeat" org-log-repeat note)
4267 ("nologrepeat" org-log-repeat nil)
4268 ("logreschedule" org-log-reschedule time)
4269 ("lognotereschedule" org-log-reschedule note)
4270 ("nologreschedule" org-log-reschedule nil)
4271 ("logredeadline" org-log-redeadline time)
4272 ("lognoteredeadline" org-log-redeadline note)
4273 ("nologredeadline" org-log-redeadline nil)
4274 ("logrefile" org-log-refile time)
4275 ("lognoterefile" org-log-refile note)
4276 ("nologrefile" org-log-refile nil)
4277 ("fninline" org-footnote-define-inline t)
4278 ("nofninline" org-footnote-define-inline nil)
4279 ("fnlocal" org-footnote-section nil)
4280 ("fnauto" org-footnote-auto-label t)
4281 ("fnprompt" org-footnote-auto-label nil)
4282 ("fnconfirm" org-footnote-auto-label confirm)
4283 ("fnplain" org-footnote-auto-label plain)
4284 ("fnadjust" org-footnote-auto-adjust t)
4285 ("nofnadjust" org-footnote-auto-adjust nil)
4286 ("constcgs" constants-unit-system cgs)
4287 ("constSI" constants-unit-system SI)
4288 ("noptag" org-tag-persistent-alist nil)
4289 ("hideblocks" org-hide-block-startup t)
4290 ("nohideblocks" org-hide-block-startup nil)
4291 ("beamer" org-startup-with-beamer-mode t)
4292 ("entitiespretty" org-pretty-entities t)
4293 ("entitiesplain" org-pretty-entities nil))
4294 "Variable associated with STARTUP options for org-mode.
4295 Each element is a list of three items: The startup options as written
4296 in the #+STARTUP line, the corresponding variable, and the value to
4297 set this variable to if the option is found. An optional forth element PUSH
4298 means to push this value onto the list in the variable.")
4300 (defun org-set-regexps-and-options ()
4301 "Precompute regular expressions for current buffer."
4302 (when (org-mode-p)
4303 (org-set-local 'org-todo-kwd-alist nil)
4304 (org-set-local 'org-todo-key-alist nil)
4305 (org-set-local 'org-todo-key-trigger nil)
4306 (org-set-local 'org-todo-keywords-1 nil)
4307 (org-set-local 'org-done-keywords nil)
4308 (org-set-local 'org-todo-heads nil)
4309 (org-set-local 'org-todo-sets nil)
4310 (org-set-local 'org-todo-log-states nil)
4311 (org-set-local 'org-file-properties nil)
4312 (org-set-local 'org-file-tags nil)
4313 (let ((re (org-make-options-regexp
4314 '("CATEGORY" "TODO" "COLUMNS"
4315 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4316 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4317 "OPTIONS")
4318 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4319 (splitre "[ \t]+")
4320 (scripts org-use-sub-superscripts)
4321 kwds kws0 kwsa key log value cat arch tags const links hw dws
4322 tail sep kws1 prio props ftags drawers beamer-p
4323 ext-setup-or-nil setup-contents (start 0))
4324 (save-excursion
4325 (save-restriction
4326 (widen)
4327 (goto-char (point-min))
4328 (while (or (and ext-setup-or-nil
4329 (string-match re ext-setup-or-nil start)
4330 (setq start (match-end 0)))
4331 (and (setq ext-setup-or-nil nil start 0)
4332 (re-search-forward re nil t)))
4333 (setq key (upcase (match-string 1 ext-setup-or-nil))
4334 value (org-match-string-no-properties 2 ext-setup-or-nil))
4335 (if (stringp value) (setq value (org-trim value)))
4336 (cond
4337 ((equal key "CATEGORY")
4338 (setq cat value))
4339 ((member key '("SEQ_TODO" "TODO"))
4340 (push (cons 'sequence (org-split-string value splitre)) kwds))
4341 ((equal key "TYP_TODO")
4342 (push (cons 'type (org-split-string value splitre)) kwds))
4343 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4344 ;; general TODO-like setup
4345 (push (cons (intern (downcase (match-string 1 key)))
4346 (org-split-string value splitre)) kwds))
4347 ((equal key "TAGS")
4348 (setq tags (append tags (if tags '("\\n") nil)
4349 (org-split-string value splitre))))
4350 ((equal key "COLUMNS")
4351 (org-set-local 'org-columns-default-format value))
4352 ((equal key "LINK")
4353 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4354 (push (cons (match-string 1 value)
4355 (org-trim (match-string 2 value)))
4356 links)))
4357 ((equal key "PRIORITIES")
4358 (setq prio (org-split-string value " +")))
4359 ((equal key "PROPERTY")
4360 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4361 (push (cons (match-string 1 value) (match-string 2 value))
4362 props)))
4363 ((equal key "FILETAGS")
4364 (when (string-match "\\S-" value)
4365 (setq ftags
4366 (append
4367 ftags
4368 (apply 'append
4369 (mapcar (lambda (x) (org-split-string x ":"))
4370 (org-split-string value)))))))
4371 ((equal key "DRAWERS")
4372 (setq drawers (org-split-string value splitre)))
4373 ((equal key "CONSTANTS")
4374 (setq const (append const (org-split-string value splitre))))
4375 ((equal key "STARTUP")
4376 (let ((opts (org-split-string value splitre))
4377 l var val)
4378 (while (setq l (pop opts))
4379 (when (setq l (assoc l org-startup-options))
4380 (setq var (nth 1 l) val (nth 2 l))
4381 (if (not (nth 3 l))
4382 (set (make-local-variable var) val)
4383 (if (not (listp (symbol-value var)))
4384 (set (make-local-variable var) nil))
4385 (set (make-local-variable var) (symbol-value var))
4386 (add-to-list var val))))))
4387 ((equal key "ARCHIVE")
4388 (setq arch value)
4389 (remove-text-properties 0 (length arch)
4390 '(face t fontified t) arch))
4391 ((equal key "LATEX_CLASS")
4392 (setq beamer-p (equal value "beamer")))
4393 ((equal key "OPTIONS")
4394 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4395 (setq scripts (read (match-string 2 value)))))
4396 ((equal key "SETUPFILE")
4397 (setq setup-contents (org-file-contents
4398 (expand-file-name
4399 (org-remove-double-quotes value))
4400 'noerror))
4401 (if (not ext-setup-or-nil)
4402 (setq ext-setup-or-nil setup-contents start 0)
4403 (setq ext-setup-or-nil
4404 (concat (substring ext-setup-or-nil 0 start)
4405 "\n" setup-contents "\n"
4406 (substring ext-setup-or-nil start)))))
4407 ))))
4408 (org-set-local 'org-use-sub-superscripts scripts)
4409 (when cat
4410 (org-set-local 'org-category (intern cat))
4411 (push (cons "CATEGORY" cat) props))
4412 (when prio
4413 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4414 (setq prio (mapcar 'string-to-char prio))
4415 (org-set-local 'org-highest-priority (nth 0 prio))
4416 (org-set-local 'org-lowest-priority (nth 1 prio))
4417 (org-set-local 'org-default-priority (nth 2 prio)))
4418 (and props (org-set-local 'org-file-properties (nreverse props)))
4419 (and ftags (org-set-local 'org-file-tags
4420 (mapcar 'org-add-prop-inherited ftags)))
4421 (and drawers (org-set-local 'org-drawers drawers))
4422 (and arch (org-set-local 'org-archive-location arch))
4423 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4424 ;; Process the TODO keywords
4425 (unless kwds
4426 ;; Use the global values as if they had been given locally.
4427 (setq kwds (default-value 'org-todo-keywords))
4428 (if (stringp (car kwds))
4429 (setq kwds (list (cons org-todo-interpretation
4430 (default-value 'org-todo-keywords)))))
4431 (setq kwds (reverse kwds)))
4432 (setq kwds (nreverse kwds))
4433 (let (inter kws kw)
4434 (while (setq kws (pop kwds))
4435 (let ((kws (or
4436 (run-hook-with-args-until-success
4437 'org-todo-setup-filter-hook kws)
4438 kws)))
4439 (setq inter (pop kws) sep (member "|" kws)
4440 kws0 (delete "|" (copy-sequence kws))
4441 kwsa nil
4442 kws1 (mapcar
4443 (lambda (x)
4444 ;; 1 2
4445 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4446 (progn
4447 (setq kw (match-string 1 x)
4448 key (and (match-end 2) (match-string 2 x))
4449 log (org-extract-log-state-settings x))
4450 (push (cons kw (and key (string-to-char key))) kwsa)
4451 (and log (push log org-todo-log-states))
4453 (error "Invalid TODO keyword %s" x)))
4454 kws0)
4455 kwsa (if kwsa (append '((:startgroup))
4456 (nreverse kwsa)
4457 '((:endgroup))))
4458 hw (car kws1)
4459 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4460 tail (list inter hw (car dws) (org-last dws))))
4461 (add-to-list 'org-todo-heads hw 'append)
4462 (push kws1 org-todo-sets)
4463 (setq org-done-keywords (append org-done-keywords dws nil))
4464 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4465 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4466 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4467 (setq org-todo-sets (nreverse org-todo-sets)
4468 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4469 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4470 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4471 ;; Process the constants
4472 (when const
4473 (let (e cst)
4474 (while (setq e (pop const))
4475 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4476 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4477 (setq org-table-formula-constants-local cst)))
4479 ;; Process the tags.
4480 (when tags
4481 (let (e tgs)
4482 (while (setq e (pop tags))
4483 (cond
4484 ((equal e "{") (push '(:startgroup) tgs))
4485 ((equal e "}") (push '(:endgroup) tgs))
4486 ((equal e "\\n") (push '(:newline) tgs))
4487 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4488 (push (cons (match-string 1 e)
4489 (string-to-char (match-string 2 e)))
4490 tgs))
4491 (t (push (list e) tgs))))
4492 (org-set-local 'org-tag-alist nil)
4493 (while (setq e (pop tgs))
4494 (or (and (stringp (car e))
4495 (assoc (car e) org-tag-alist))
4496 (push e org-tag-alist)))))
4498 ;; Compute the regular expressions and other local variables
4499 (if (not org-done-keywords)
4500 (setq org-done-keywords (and org-todo-keywords-1
4501 (list (org-last org-todo-keywords-1)))))
4502 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4503 (length org-scheduled-string)
4504 (length org-clock-string)
4505 (length org-closed-string)))
4506 org-drawer-regexp
4507 (concat "^[ \t]*:\\("
4508 (mapconcat 'regexp-quote org-drawers "\\|")
4509 "\\):[ \t]*$")
4510 org-not-done-keywords
4511 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4512 org-todo-regexp
4513 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4514 "\\|") "\\)\\>")
4515 org-not-done-regexp
4516 (concat "\\<\\("
4517 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4518 "\\)\\>")
4519 org-not-done-heading-regexp
4520 (concat "^\\(\\*+\\)[ \t]+\\("
4521 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4522 "\\)\\>")
4523 org-todo-line-regexp
4524 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4525 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4526 "\\)\\>\\)?[ \t]*\\(.*\\)")
4527 org-complex-heading-regexp
4528 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4529 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4530 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4531 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4532 org-complex-heading-regexp-format
4533 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4534 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4535 "\\)\\>\\)?"
4536 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4537 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4538 "[ \t]*\\(%s\\)"
4539 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4540 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4541 org-nl-done-regexp
4542 (concat "\n\\*+[ \t]+"
4543 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4544 "\\)" "\\>")
4545 org-todo-line-tags-regexp
4546 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4547 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4548 (org-re
4549 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4550 org-looking-at-done-regexp
4551 (concat "^" "\\(?:"
4552 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4553 "\\>")
4554 org-deadline-regexp (concat "\\<" org-deadline-string)
4555 org-deadline-time-regexp
4556 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4557 org-deadline-line-regexp
4558 (concat "\\<\\(" org-deadline-string "\\).*")
4559 org-scheduled-regexp
4560 (concat "\\<" org-scheduled-string)
4561 org-scheduled-time-regexp
4562 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4563 org-closed-time-regexp
4564 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4565 org-keyword-time-regexp
4566 (concat "\\<\\(" org-scheduled-string
4567 "\\|" org-deadline-string
4568 "\\|" org-closed-string
4569 "\\|" org-clock-string "\\)"
4570 " *[[<]\\([^]>]+\\)[]>]")
4571 org-keyword-time-not-clock-regexp
4572 (concat "\\<\\(" org-scheduled-string
4573 "\\|" org-deadline-string
4574 "\\|" org-closed-string
4575 "\\)"
4576 " *[[<]\\([^]>]+\\)[]>]")
4577 org-maybe-keyword-time-regexp
4578 (concat "\\(\\<\\(" org-scheduled-string
4579 "\\|" org-deadline-string
4580 "\\|" org-closed-string
4581 "\\|" org-clock-string "\\)\\)?"
4582 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4583 org-planning-or-clock-line-re
4584 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4585 "\\|" org-deadline-string
4586 "\\|" org-closed-string "\\|" org-clock-string
4587 "\\)\\>\\)")
4588 org-all-time-keywords
4589 (mapcar (lambda (w) (substring w 0 -1))
4590 (list org-scheduled-string org-deadline-string
4591 org-clock-string org-closed-string))
4593 (org-compute-latex-and-specials-regexp)
4594 (org-set-font-lock-defaults))))
4596 (defun org-file-contents (file &optional noerror)
4597 "Return the contents of FILE, as a string."
4598 (if (or (not file)
4599 (not (file-readable-p file)))
4600 (if noerror
4601 (progn
4602 (message "Cannot read file \"%s\"" file)
4603 (ding) (sit-for 2)
4605 (error "Cannot read file \"%s\"" file))
4606 (with-temp-buffer
4607 (insert-file-contents file)
4608 (buffer-string))))
4610 (defun org-extract-log-state-settings (x)
4611 "Extract the log state setting from a TODO keyword string.
4612 This will extract info from a string like \"WAIT(w@/!)\"."
4613 (let (kw key log1 log2)
4614 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4615 (setq kw (match-string 1 x)
4616 key (and (match-end 2) (match-string 2 x))
4617 log1 (and (match-end 3) (match-string 3 x))
4618 log2 (and (match-end 4) (match-string 4 x)))
4619 (and (or log1 log2)
4620 (list kw
4621 (and log1 (if (equal log1 "!") 'time 'note))
4622 (and log2 (if (equal log2 "!") 'time 'note)))))))
4624 (defun org-remove-keyword-keys (list)
4625 "Remove a pair of parenthesis at the end of each string in LIST."
4626 (mapcar (lambda (x)
4627 (if (string-match "(.*)$" x)
4628 (substring x 0 (match-beginning 0))
4630 list))
4632 (defun org-assign-fast-keys (alist)
4633 "Assign fast keys to a keyword-key alist.
4634 Respect keys that are already there."
4635 (let (new e (alt ?0))
4636 (while (setq e (pop alist))
4637 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4638 (cdr e)) ;; Key already assigned.
4639 (push e new)
4640 (let ((clist (string-to-list (downcase (car e))))
4641 (used (append new alist)))
4642 (when (= (car clist) ?@)
4643 (pop clist))
4644 (while (and clist (rassoc (car clist) used))
4645 (pop clist))
4646 (unless clist
4647 (while (rassoc alt used)
4648 (incf alt)))
4649 (push (cons (car e) (or (car clist) alt)) new))))
4650 (nreverse new)))
4652 ;;; Some variables used in various places
4654 (defvar org-window-configuration nil
4655 "Used in various places to store a window configuration.")
4656 (defvar org-selected-window nil
4657 "Used in various places to store a window configuration.")
4658 (defvar org-finish-function nil
4659 "Function to be called when `C-c C-c' is used.
4660 This is for getting out of special buffers like remember.")
4663 ;; FIXME: Occasionally check by commenting these, to make sure
4664 ;; no other functions uses these, forgetting to let-bind them.
4665 (defvar entry)
4666 (defvar last-state)
4667 (defvar date)
4669 ;; Defined somewhere in this file, but used before definition.
4670 (defvar org-entities) ;; defined in org-entities.el
4671 (defvar org-struct-menu)
4672 (defvar org-org-menu)
4673 (defvar org-tbl-menu)
4675 ;;;; Define the Org-mode
4677 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4678 (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"))
4681 ;; We use a before-change function to check if a table might need
4682 ;; an update.
4683 (defvar org-table-may-need-update t
4684 "Indicates that a table might need an update.
4685 This variable is set by `org-before-change-function'.
4686 `org-table-align' sets it back to nil.")
4687 (defun org-before-change-function (beg end)
4688 "Every change indicates that a table might need an update."
4689 (setq org-table-may-need-update t))
4690 (defvar org-mode-map)
4691 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4692 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4693 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4694 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4695 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4696 (defvar org-table-buffer-is-an nil)
4697 (defconst org-outline-regexp "\\*+ ")
4699 ;;;###autoload
4700 (define-derived-mode org-mode outline-mode "Org"
4701 "Outline-based notes management and organizer, alias
4702 \"Carsten's outline-mode for keeping track of everything.\"
4704 Org-mode develops organizational tasks around a NOTES file which
4705 contains information about projects as plain text. Org-mode is
4706 implemented on top of outline-mode, which is ideal to keep the content
4707 of large files well structured. It supports ToDo items, deadlines and
4708 time stamps, which magically appear in the diary listing of the Emacs
4709 calendar. Tables are easily created with a built-in table editor.
4710 Plain text URL-like links connect to websites, emails (VM), Usenet
4711 messages (Gnus), BBDB entries, and any files related to the project.
4712 For printing and sharing of notes, an Org-mode file (or a part of it)
4713 can be exported as a structured ASCII or HTML file.
4715 The following commands are available:
4717 \\{org-mode-map}"
4719 ;; Get rid of Outline menus, they are not needed
4720 ;; Need to do this here because define-derived-mode sets up
4721 ;; the keymap so late. Still, it is a waste to call this each time
4722 ;; we switch another buffer into org-mode.
4723 (if (featurep 'xemacs)
4724 (when (boundp 'outline-mode-menu-heading)
4725 ;; Assume this is Greg's port, it uses easymenu
4726 (easy-menu-remove outline-mode-menu-heading)
4727 (easy-menu-remove outline-mode-menu-show)
4728 (easy-menu-remove outline-mode-menu-hide))
4729 (define-key org-mode-map [menu-bar headings] 'undefined)
4730 (define-key org-mode-map [menu-bar hide] 'undefined)
4731 (define-key org-mode-map [menu-bar show] 'undefined))
4733 (org-load-modules-maybe)
4734 (easy-menu-add org-org-menu)
4735 (easy-menu-add org-tbl-menu)
4736 (org-install-agenda-files-menu)
4737 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4738 (add-to-invisibility-spec '(org-cwidth))
4739 (add-to-invisibility-spec '(org-hide-block . t))
4740 (when (featurep 'xemacs)
4741 (org-set-local 'line-move-ignore-invisible t))
4742 (org-set-local 'outline-regexp org-outline-regexp)
4743 (org-set-local 'outline-level 'org-outline-level)
4744 (when (and org-ellipsis
4745 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4746 (fboundp 'make-glyph-code))
4747 (unless org-display-table
4748 (setq org-display-table (make-display-table)))
4749 (set-display-table-slot
4750 org-display-table 4
4751 (vconcat (mapcar
4752 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4753 org-ellipsis)))
4754 (if (stringp org-ellipsis) org-ellipsis "..."))))
4755 (setq buffer-display-table org-display-table))
4756 (org-set-regexps-and-options)
4757 (when (and org-tag-faces (not org-tags-special-faces-re))
4758 ;; tag faces set outside customize.... force initialization.
4759 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4760 ;; Calc embedded
4761 (org-set-local 'calc-embedded-open-mode "# ")
4762 (modify-syntax-entry ?@ "w")
4763 (if org-startup-truncated (setq truncate-lines t))
4764 (org-set-local 'font-lock-unfontify-region-function
4765 'org-unfontify-region)
4766 ;; Activate before-change-function
4767 (org-set-local 'org-table-may-need-update t)
4768 (org-add-hook 'before-change-functions 'org-before-change-function nil
4769 'local)
4770 ;; Check for running clock before killing a buffer
4771 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4772 ;; Paragraphs and auto-filling
4773 (org-set-autofill-regexps)
4774 (setq indent-line-function 'org-indent-line-function)
4775 (org-update-radio-target-regexp)
4776 ;; Beginning/end of defun
4777 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4778 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4779 ;; Next error for sparse trees
4780 (org-set-local 'next-error-function 'org-occur-next-match)
4781 ;; Make sure dependence stuff works reliably, even for users who set it
4782 ;; too late :-(
4783 (if org-enforce-todo-dependencies
4784 (add-hook 'org-blocker-hook
4785 'org-block-todo-from-children-or-siblings-or-parent)
4786 (remove-hook 'org-blocker-hook
4787 'org-block-todo-from-children-or-siblings-or-parent))
4788 (if org-enforce-todo-checkbox-dependencies
4789 (add-hook 'org-blocker-hook
4790 'org-block-todo-from-checkboxes)
4791 (remove-hook 'org-blocker-hook
4792 'org-block-todo-from-checkboxes))
4794 ;; Comment characters
4795 (org-set-local 'comment-start "#")
4796 (org-set-local 'comment-padding " ")
4798 ;; Align options lines
4799 (org-set-local
4800 'align-mode-rules-list
4801 '((org-in-buffer-settings
4802 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4803 (modes . '(org-mode)))))
4805 ;; Imenu
4806 (org-set-local 'imenu-create-index-function
4807 'org-imenu-get-tree)
4809 ;; Make isearch reveal context
4810 (if (or (featurep 'xemacs)
4811 (not (boundp 'outline-isearch-open-invisible-function)))
4812 ;; Emacs 21 and XEmacs make use of the hook
4813 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4814 ;; Emacs 22 deals with this through a special variable
4815 (org-set-local 'outline-isearch-open-invisible-function
4816 (lambda (&rest ignore) (org-show-context 'isearch))))
4818 ;; Turn on org-beamer-mode?
4819 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4821 ;; Setup the pcomplete hooks
4822 (set (make-local-variable 'pcomplete-command-completion-function)
4823 'org-pcomplete-initial)
4824 (set (make-local-variable 'pcomplete-command-name-function)
4825 'org-command-at-point)
4826 (set (make-local-variable 'pcomplete-default-completion-function)
4827 'ignore)
4828 (set (make-local-variable 'pcomplete-parse-arguments-function)
4829 'org-parse-arguments)
4830 (set (make-local-variable 'pcomplete-termination-string) "")
4832 ;; If empty file that did not turn on org-mode automatically, make it to.
4833 (if (and org-insert-mode-line-in-empty-file
4834 (org-called-interactively-p 'any)
4835 (= (point-min) (point-max)))
4836 (insert "# -*- mode: org -*-\n\n"))
4837 (unless org-inhibit-startup
4838 (when org-startup-align-all-tables
4839 (let ((bmp (buffer-modified-p)))
4840 (org-table-map-tables 'org-table-align 'quietly)
4841 (set-buffer-modified-p bmp)))
4842 (when org-startup-with-inline-images
4843 (org-display-inline-images))
4844 (when org-startup-indented
4845 (require 'org-indent)
4846 (org-indent-mode 1))
4847 (unless org-inhibit-startup-visibility-stuff
4848 (org-set-startup-visibility))))
4850 (when (fboundp 'abbrev-table-put)
4851 (abbrev-table-put org-mode-abbrev-table
4852 :parents (list text-mode-abbrev-table)))
4854 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4856 (defun org-current-time ()
4857 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4858 (if (> (car org-time-stamp-rounding-minutes) 1)
4859 (let ((r (car org-time-stamp-rounding-minutes))
4860 (time (decode-time)))
4861 (apply 'encode-time
4862 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4863 (nthcdr 2 time))))
4864 (current-time)))
4866 (defun org-today ()
4867 "Return today date, considering `org-extend-today-until'."
4868 (time-to-days
4869 (time-subtract (current-time)
4870 (list 0 (* 3600 org-extend-today-until) 0))))
4872 ;;;; Font-Lock stuff, including the activators
4874 (defvar org-mouse-map (make-sparse-keymap))
4875 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4876 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4877 (when org-mouse-1-follows-link
4878 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4879 (when org-tab-follows-link
4880 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4881 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4883 (require 'font-lock)
4885 (defconst org-non-link-chars "]\t\n\r<>")
4886 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4887 "shell" "elisp" "doi" "message"))
4888 (defvar org-link-types-re nil
4889 "Matches a link that has a url-like prefix like \"http:\"")
4890 (defvar org-link-re-with-space nil
4891 "Matches a link with spaces, optional angular brackets around it.")
4892 (defvar org-link-re-with-space2 nil
4893 "Matches a link with spaces, optional angular brackets around it.")
4894 (defvar org-link-re-with-space3 nil
4895 "Matches a link with spaces, only for internal part in bracket links.")
4896 (defvar org-angle-link-re nil
4897 "Matches link with angular brackets, spaces are allowed.")
4898 (defvar org-plain-link-re nil
4899 "Matches plain link, without spaces.")
4900 (defvar org-bracket-link-regexp nil
4901 "Matches a link in double brackets.")
4902 (defvar org-bracket-link-analytic-regexp nil
4903 "Regular expression used to analyze links.
4904 Here is what the match groups contain after a match:
4905 1: http:
4906 2: http
4907 3: path
4908 4: [desc]
4909 5: desc")
4910 (defvar org-bracket-link-analytic-regexp++ nil
4911 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4912 (defvar org-any-link-re nil
4913 "Regular expression matching any link.")
4915 (defcustom org-match-sexp-depth 3
4916 "Number of stacked braces for sub/superscript matching.
4917 This has to be set before loading org.el to be effective."
4918 :group 'org-export-translation ; ??????????????????????????/
4919 :type 'integer)
4921 (defun org-create-multibrace-regexp (left right n)
4922 "Create a regular expression which will match a balanced sexp.
4923 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4924 as single character strings.
4925 The regexp returned will match the entire expression including the
4926 delimiters. It will also define a single group which contains the
4927 match except for the outermost delimiters. The maximum depth of
4928 stacked delimiters is N. Escaping delimiters is not possible."
4929 (let* ((nothing (concat "[^" left right "]*?"))
4930 (or "\\|")
4931 (re nothing)
4932 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4933 (while (> n 1)
4934 (setq n (1- n)
4935 re (concat re or next)
4936 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4937 (concat left "\\(" re "\\)" right)))
4939 (defvar org-match-substring-regexp
4940 (concat
4941 "\\([^\\]\\)\\([_^]\\)\\("
4942 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4943 "\\|"
4944 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4945 "\\|"
4946 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4947 "The regular expression matching a sub- or superscript.")
4949 (defvar org-match-substring-with-braces-regexp
4950 (concat
4951 "\\([^\\]\\)\\([_^]\\)\\("
4952 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4953 "\\)")
4954 "The regular expression matching a sub- or superscript, forcing braces.")
4956 (defun org-make-link-regexps ()
4957 "Update the link regular expressions.
4958 This should be called after the variable `org-link-types' has changed."
4959 (setq org-link-types-re
4960 (concat
4961 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4962 org-link-re-with-space
4963 (concat
4964 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4965 "\\([^" org-non-link-chars " ]"
4966 "[^" org-non-link-chars "]*"
4967 "[^" org-non-link-chars " ]\\)>?")
4968 org-link-re-with-space2
4969 (concat
4970 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4971 "\\([^" org-non-link-chars " ]"
4972 "[^\t\n\r]*"
4973 "[^" org-non-link-chars " ]\\)>?")
4974 org-link-re-with-space3
4975 (concat
4976 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4977 "\\([^" org-non-link-chars " ]"
4978 "[^\t\n\r]*\\)")
4979 org-angle-link-re
4980 (concat
4981 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4982 "\\([^" org-non-link-chars " ]"
4983 "[^" org-non-link-chars "]*"
4984 "\\)>")
4985 org-plain-link-re
4986 (concat
4987 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4988 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4989 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4990 org-bracket-link-regexp
4991 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4992 org-bracket-link-analytic-regexp
4993 (concat
4994 "\\[\\["
4995 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4996 "\\([^]]+\\)"
4997 "\\]"
4998 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4999 "\\]")
5000 org-bracket-link-analytic-regexp++
5001 (concat
5002 "\\[\\["
5003 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5004 "\\([^]]+\\)"
5005 "\\]"
5006 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5007 "\\]")
5008 org-any-link-re
5009 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5010 org-angle-link-re "\\)\\|\\("
5011 org-plain-link-re "\\)")))
5013 (org-make-link-regexps)
5015 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5016 "Regular expression for fast time stamp matching.")
5017 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5018 "Regular expression for fast time stamp matching.")
5019 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5020 "Regular expression matching time strings for analysis.
5021 This one does not require the space after the date, so it can be used
5022 on a string that terminates immediately after the date.")
5023 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5024 "Regular expression matching time strings for analysis.")
5025 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5026 "Regular expression matching time stamps, with groups.")
5027 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5028 "Regular expression matching time stamps (also [..]), with groups.")
5029 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5030 "Regular expression matching a time stamp range.")
5031 (defconst org-tr-regexp-both
5032 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5033 "Regular expression matching a time stamp range.")
5034 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5035 org-ts-regexp "\\)?")
5036 "Regular expression matching a time stamp or time stamp range.")
5037 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5038 org-ts-regexp-both "\\)?")
5039 "Regular expression matching a time stamp or time stamp range.
5040 The time stamps may be either active or inactive.")
5042 (defvar org-emph-face nil)
5044 (defun org-do-emphasis-faces (limit)
5045 "Run through the buffer and add overlays to links."
5046 (let (rtn a)
5047 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5048 (if (not (= (char-after (match-beginning 3))
5049 (char-after (match-beginning 4))))
5050 (progn
5051 (setq rtn t)
5052 (setq a (assoc (match-string 3) org-emphasis-alist))
5053 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5054 'face
5055 (nth 1 a))
5056 (and (nth 4 a)
5057 (org-remove-flyspell-overlays-in
5058 (match-beginning 0) (match-end 0)))
5059 (add-text-properties (match-beginning 2) (match-end 2)
5060 '(font-lock-multiline t org-emphasis t))
5061 (when org-hide-emphasis-markers
5062 (add-text-properties (match-end 4) (match-beginning 5)
5063 '(invisible org-link))
5064 (add-text-properties (match-beginning 3) (match-end 3)
5065 '(invisible org-link)))))
5066 (backward-char 1))
5067 rtn))
5069 (defun org-emphasize (&optional char)
5070 "Insert or change an emphasis, i.e. a font like bold or italic.
5071 If there is an active region, change that region to a new emphasis.
5072 If there is no region, just insert the marker characters and position
5073 the cursor between them.
5074 CHAR should be either the marker character, or the first character of the
5075 HTML tag associated with that emphasis. If CHAR is a space, the means
5076 to remove the emphasis of the selected region.
5077 If char is not given (for example in an interactive call) it
5078 will be prompted for."
5079 (interactive)
5080 (let ((eal org-emphasis-alist) e det
5081 (erc org-emphasis-regexp-components)
5082 (prompt "")
5083 (string "") beg end move tag c s)
5084 (if (org-region-active-p)
5085 (setq beg (region-beginning) end (region-end)
5086 string (buffer-substring beg end))
5087 (setq move t))
5089 (while (setq e (pop eal))
5090 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5091 c (aref tag 0))
5092 (push (cons c (string-to-char (car e))) det)
5093 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5094 (substring tag 1)))))
5095 (setq det (nreverse det))
5096 (unless char
5097 (message "%s" (concat "Emphasis marker or tag:" prompt))
5098 (setq char (read-char-exclusive)))
5099 (setq char (or (cdr (assoc char det)) char))
5100 (if (equal char ?\ )
5101 (setq s "" move nil)
5102 (unless (assoc (char-to-string char) org-emphasis-alist)
5103 (error "No such emphasis marker: \"%c\"" char))
5104 (setq s (char-to-string char)))
5105 (while (and (> (length string) 1)
5106 (equal (substring string 0 1) (substring string -1))
5107 (assoc (substring string 0 1) org-emphasis-alist))
5108 (setq string (substring string 1 -1)))
5109 (setq string (concat s string s))
5110 (if beg (delete-region beg end))
5111 (unless (or (bolp)
5112 (string-match (concat "[" (nth 0 erc) "\n]")
5113 (char-to-string (char-before (point)))))
5114 (insert " "))
5115 (unless (or (eobp)
5116 (string-match (concat "[" (nth 1 erc) "\n]")
5117 (char-to-string (char-after (point)))))
5118 (insert " ") (backward-char 1))
5119 (insert string)
5120 (and move (backward-char 1))))
5122 (defconst org-nonsticky-props
5123 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5125 (defsubst org-rear-nonsticky-at (pos)
5126 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5128 (defun org-activate-plain-links (limit)
5129 "Run through the buffer and add overlays to links."
5130 (catch 'exit
5131 (let (f)
5132 (if (re-search-forward org-plain-link-re limit t)
5133 (progn
5134 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5135 (setq f (get-text-property (match-beginning 0) 'face))
5136 (if (or (eq f 'org-tag)
5137 (and (listp f) (memq 'org-tag f)))
5139 (add-text-properties (match-beginning 0) (match-end 0)
5140 (list 'mouse-face 'highlight
5141 'face 'org-link
5142 'keymap org-mouse-map))
5143 (org-rear-nonsticky-at (match-end 0)))
5144 t)))))
5146 (defun org-activate-code (limit)
5147 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5148 (progn
5149 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5150 (remove-text-properties (match-beginning 0) (match-end 0)
5151 '(display t invisible t intangible t))
5152 t)))
5154 (defcustom org-src-fontify-natively nil
5155 "When non-nil, fontify code in code blocks."
5156 :type 'boolean
5157 :group 'org-appearance
5158 :group 'org-babel)
5160 (defun org-fontify-meta-lines-and-blocks (limit)
5161 (condition-case nil
5162 (org-fontify-meta-lines-and-blocks-1 limit)
5163 (error (message "org-mode fontification error"))))
5165 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5166 "Fontify #+ lines and blocks, in the correct ways."
5167 (let ((case-fold-search t))
5168 (if (re-search-forward
5169 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5170 limit t)
5171 (let ((beg (match-beginning 0))
5172 (block-start (match-end 0))
5173 (block-end nil)
5174 (lang (match-string 7))
5175 (beg1 (line-beginning-position 2))
5176 (dc1 (downcase (match-string 2)))
5177 (dc3 (downcase (match-string 3)))
5178 end end1 quoting block-type ovl)
5179 (cond
5180 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5181 ;; a single line of backend-specific content
5182 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5183 (remove-text-properties (match-beginning 0) (match-end 0)
5184 '(display t invisible t intangible t))
5185 (add-text-properties (match-beginning 1) (match-end 3)
5186 '(font-lock-fontified t face org-meta-line))
5187 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5188 '(font-lock-fontified t face org-block))
5189 ; for backend-specific code
5191 ((and (match-end 4) (equal dc3 "begin"))
5192 ;; Truly a block
5193 (setq block-type (downcase (match-string 5))
5194 quoting (member block-type org-protecting-blocks))
5195 (when (re-search-forward
5196 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5197 nil t) ;; on purpose, we look further than LIMIT
5198 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5199 (setq block-end (match-beginning 0))
5200 (when quoting
5201 (remove-text-properties beg end
5202 '(display t invisible t intangible t)))
5203 (add-text-properties
5204 beg end
5205 '(font-lock-fontified t font-lock-multiline t))
5206 (add-text-properties beg beg1 '(face org-meta-line))
5207 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5208 ; for end_src
5209 (cond
5210 ((and lang org-src-fontify-natively)
5211 (org-src-font-lock-fontify-block lang block-start block-end)
5212 ;; remove old background overlays
5213 (mapc (lambda (ov)
5214 (if (eq (overlay-get ov 'face) 'org-block-background)
5215 (delete-overlay ov)))
5216 (overlays-at (/ (+ beg1 block-end) 2)))
5217 ;; add a background overlay
5218 (setq ovl (make-overlay beg1 block-end))
5219 (overlay-put ovl 'face 'org-block-background)
5220 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5221 (quoting
5222 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5223 ; end of source block
5224 ((not org-fontify-quote-and-verse-blocks))
5225 ((string= block-type "quote")
5226 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5227 ((string= block-type "verse")
5228 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5229 (add-text-properties beg beg1 '(face org-block-begin-line))
5230 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5232 ((member dc1 '("title:" "author:" "email:" "date:"))
5233 (add-text-properties
5234 beg (match-end 3)
5235 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5236 '(font-lock-fontified t invisible t)
5237 '(font-lock-fontified t face org-document-info-keyword)))
5238 (add-text-properties
5239 (match-beginning 6) (match-end 6)
5240 (if (string-equal dc1 "title:")
5241 '(font-lock-fontified t face org-document-title)
5242 '(font-lock-fontified t face org-document-info))))
5243 ((not (member (char-after beg) '(?\ ?\t)))
5244 ;; just any other in-buffer setting, but not indented
5245 (add-text-properties
5246 beg (1+ (match-end 0))
5247 '(font-lock-fontified t face org-meta-line))
5249 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5250 "orgtbl:" "tblfm:" "tblname:" "result:"
5251 "results:" "source:" "srcname:" "call:"))
5252 (and (match-end 4) (equal dc3 "attr")))
5253 (add-text-properties
5254 beg (match-end 0)
5255 '(font-lock-fontified t face org-meta-line))
5257 ((member dc3 '(" " ""))
5258 (add-text-properties
5259 beg (match-end 0)
5260 '(font-lock-fontified t face font-lock-comment-face)))
5261 (t nil))))))
5263 (defun org-activate-angle-links (limit)
5264 "Run through the buffer and add overlays to links."
5265 (if (re-search-forward org-angle-link-re limit t)
5266 (progn
5267 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5268 (add-text-properties (match-beginning 0) (match-end 0)
5269 (list 'mouse-face 'highlight
5270 'keymap org-mouse-map))
5271 (org-rear-nonsticky-at (match-end 0))
5272 t)))
5274 (defun org-activate-footnote-links (limit)
5275 "Run through the buffer and add overlays to footnotes."
5276 (let ((fn (org-footnote-next-reference-or-definition limit)))
5277 (when fn
5278 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5279 (org-remove-flyspell-overlays-in beg end)
5280 (add-text-properties beg end
5281 (list 'mouse-face 'highlight
5282 'keymap org-mouse-map
5283 'help-echo
5284 (if (= (point-at-bol) beg)
5285 "Footnote definition"
5286 "Footnote reference")
5287 'font-lock-fontified t
5288 'font-lock-multiline t
5289 'face 'org-footnote))))))
5291 (defun org-activate-bracket-links (limit)
5292 "Run through the buffer and add overlays to bracketed links."
5293 (if (re-search-forward org-bracket-link-regexp limit t)
5294 (let* ((help (concat "LINK: "
5295 (org-match-string-no-properties 1)))
5296 ;; FIXME: above we should remove the escapes.
5297 ;; but that requires another match, protecting match data,
5298 ;; a lot of overhead for font-lock.
5299 (ip (org-maybe-intangible
5300 (list 'invisible 'org-link
5301 'keymap org-mouse-map 'mouse-face 'highlight
5302 'font-lock-multiline t 'help-echo help)))
5303 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5304 'font-lock-multiline t 'help-echo help)))
5305 ;; We need to remove the invisible property here. Table narrowing
5306 ;; may have made some of this invisible.
5307 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5308 (remove-text-properties (match-beginning 0) (match-end 0)
5309 '(invisible nil))
5310 (if (match-end 3)
5311 (progn
5312 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5313 (org-rear-nonsticky-at (match-beginning 3))
5314 (add-text-properties (match-beginning 3) (match-end 3) vp)
5315 (org-rear-nonsticky-at (match-end 3))
5316 (add-text-properties (match-end 3) (match-end 0) ip)
5317 (org-rear-nonsticky-at (match-end 0)))
5318 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5319 (org-rear-nonsticky-at (match-beginning 1))
5320 (add-text-properties (match-beginning 1) (match-end 1) vp)
5321 (org-rear-nonsticky-at (match-end 1))
5322 (add-text-properties (match-end 1) (match-end 0) ip)
5323 (org-rear-nonsticky-at (match-end 0)))
5324 t)))
5326 (defun org-activate-dates (limit)
5327 "Run through the buffer and add overlays to dates."
5328 (if (re-search-forward org-tsr-regexp-both limit t)
5329 (progn
5330 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5331 (add-text-properties (match-beginning 0) (match-end 0)
5332 (list 'mouse-face 'highlight
5333 'keymap org-mouse-map))
5334 (org-rear-nonsticky-at (match-end 0))
5335 (when org-display-custom-times
5336 (if (match-end 3)
5337 (org-display-custom-time (match-beginning 3) (match-end 3)))
5338 (org-display-custom-time (match-beginning 1) (match-end 1)))
5339 t)))
5341 (defvar org-target-link-regexp nil
5342 "Regular expression matching radio targets in plain text.")
5343 (make-variable-buffer-local 'org-target-link-regexp)
5344 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5345 "Regular expression matching a link target.")
5346 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5347 "Regular expression matching a radio target.")
5348 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5349 "Regular expression matching any target.")
5351 (defun org-activate-target-links (limit)
5352 "Run through the buffer and add overlays to target matches."
5353 (when org-target-link-regexp
5354 (let ((case-fold-search t))
5355 (if (re-search-forward org-target-link-regexp limit t)
5356 (progn
5357 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5358 (add-text-properties (match-beginning 0) (match-end 0)
5359 (list 'mouse-face 'highlight
5360 'keymap org-mouse-map
5361 'help-echo "Radio target link"
5362 'org-linked-text t))
5363 (org-rear-nonsticky-at (match-end 0))
5364 t)))))
5366 (defun org-update-radio-target-regexp ()
5367 "Find all radio targets in this file and update the regular expression."
5368 (interactive)
5369 (when (memq 'radio org-activate-links)
5370 (setq org-target-link-regexp
5371 (org-make-target-link-regexp (org-all-targets 'radio)))
5372 (org-restart-font-lock)))
5374 (defun org-hide-wide-columns (limit)
5375 (let (s e)
5376 (setq s (text-property-any (point) (or limit (point-max))
5377 'org-cwidth t))
5378 (when s
5379 (setq e (next-single-property-change s 'org-cwidth))
5380 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5381 (goto-char e)
5382 t)))
5384 (defvar org-latex-and-specials-regexp nil
5385 "Regular expression for highlighting export special stuff.")
5386 (defvar org-match-substring-regexp)
5387 (defvar org-match-substring-with-braces-regexp)
5389 ;; This should be with the exporter code, but we also use if for font-locking
5390 (defconst org-export-html-special-string-regexps
5391 '(("\\\\-" . "&shy;")
5392 ("---\\([^-]\\)" . "&mdash;\\1")
5393 ("--\\([^-]\\)" . "&ndash;\\1")
5394 ("\\.\\.\\." . "&hellip;"))
5395 "Regular expressions for special string conversion.")
5398 (defun org-compute-latex-and-specials-regexp ()
5399 "Compute regular expression for stuff treated specially by exporters."
5400 (if (not org-highlight-latex-fragments-and-specials)
5401 (org-set-local 'org-latex-and-specials-regexp nil)
5402 (require 'org-exp)
5403 (let*
5404 ((matchers (plist-get org-format-latex-options :matchers))
5405 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5406 org-latex-regexps)))
5407 (org-export-allow-BIND nil)
5408 (options (org-combine-plists (org-default-export-plist)
5409 (org-infile-export-plist)))
5410 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5411 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5412 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5413 (org-export-html-expand (plist-get options :expand-quoted-html))
5414 (org-export-with-special-strings (plist-get options :special-strings))
5415 (re-sub
5416 (cond
5417 ((equal org-export-with-sub-superscripts '{})
5418 (list org-match-substring-with-braces-regexp))
5419 (org-export-with-sub-superscripts
5420 (list org-match-substring-regexp))
5421 (t nil)))
5422 (re-latex
5423 (if org-export-with-LaTeX-fragments
5424 (mapcar (lambda (x) (nth 1 x)) latexs)))
5425 (re-macros
5426 (if org-export-with-TeX-macros
5427 (list (concat "\\\\"
5428 (regexp-opt
5429 (append
5431 (delq nil
5432 (mapcar 'car-safe
5433 (append org-entities-user
5434 org-entities)))
5435 (if (boundp 'org-latex-entities)
5436 (mapcar (lambda (x)
5437 (or (car-safe x) x))
5438 org-latex-entities)
5439 nil))
5440 'words))) ; FIXME
5442 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5443 (re-special (if org-export-with-special-strings
5444 (mapcar (lambda (x) (car x))
5445 org-export-html-special-string-regexps)))
5446 (re-rest
5447 (delq nil
5448 (list
5449 (if org-export-html-expand "@<[^>\n]+>")
5450 ))))
5451 (org-set-local
5452 'org-latex-and-specials-regexp
5453 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5454 re-rest) "\\|")))))
5456 (defun org-do-latex-and-special-faces (limit)
5457 "Run through the buffer and add overlays to links."
5458 (when org-latex-and-specials-regexp
5459 (let (rtn d)
5460 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5461 limit t))
5462 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5463 'face))
5464 '(org-code org-verbatim underline)))
5465 (progn
5466 (setq rtn t
5467 d (cond ((member (char-after (1+ (match-beginning 0)))
5468 '(?_ ?^)) 1)
5469 (t 0)))
5470 (font-lock-prepend-text-property
5471 (+ d (match-beginning 0)) (match-end 0)
5472 'face 'org-latex-and-export-specials)
5473 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5474 '(font-lock-multiline t)))))
5475 rtn)))
5477 (defun org-restart-font-lock ()
5478 "Restart `font-lock-mode', to force refontification."
5479 (when (and (boundp 'font-lock-mode) font-lock-mode)
5480 (font-lock-mode -1)
5481 (font-lock-mode 1)))
5483 (defun org-all-targets (&optional radio)
5484 "Return a list of all targets in this file.
5485 With optional argument RADIO, only find radio targets."
5486 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5487 rtn)
5488 (save-excursion
5489 (goto-char (point-min))
5490 (while (re-search-forward re nil t)
5491 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5492 rtn)))
5494 (defun org-make-target-link-regexp (targets)
5495 "Make regular expression matching all strings in TARGETS.
5496 The regular expression finds the targets also if there is a line break
5497 between words."
5498 (and targets
5499 (concat
5500 "\\<\\("
5501 (mapconcat
5502 (lambda (x)
5503 (setq x (regexp-quote x))
5504 (while (string-match " +" x)
5505 (setq x (replace-match "\\s-+" t t x)))
5507 targets
5508 "\\|")
5509 "\\)\\>")))
5511 (defun org-activate-tags (limit)
5512 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5513 (progn
5514 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5515 (add-text-properties (match-beginning 1) (match-end 1)
5516 (list 'mouse-face 'highlight
5517 'keymap org-mouse-map))
5518 (org-rear-nonsticky-at (match-end 1))
5519 t)))
5521 (defun org-outline-level ()
5522 "Compute the outline level of the heading at point.
5523 This function assumes that the cursor is at the beginning of a line matched
5524 by `outline-regexp'. Otherwise it returns garbage.
5525 If this is called at a normal headline, the level is the number of stars.
5526 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5527 (save-excursion
5528 (looking-at outline-regexp)
5529 (1- (- (match-end 0) (match-beginning 0)))))
5531 (defvar org-font-lock-keywords nil)
5533 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5534 "Regular expression matching a property line.")
5536 (defvar org-font-lock-hook nil
5537 "Functions to be called for special font lock stuff.")
5539 (defvar org-font-lock-set-keywords-hook nil
5540 "Functions that can manipulate `org-font-lock-extra-keywords'.
5541 This is calles after `org-font-lock-extra-keywords' is defined, but before
5542 it is installed to be used by font lock. This can be useful if something
5543 needs to be inserted at a specific position in the font-lock sequence.")
5545 (defun org-font-lock-hook (limit)
5546 (run-hook-with-args 'org-font-lock-hook limit))
5548 (defun org-set-font-lock-defaults ()
5549 (let* ((em org-fontify-emphasized-text)
5550 (lk org-activate-links)
5551 (org-font-lock-extra-keywords
5552 (list
5553 ;; Call the hook
5554 '(org-font-lock-hook)
5555 ;; Headlines
5556 `(,(if org-fontify-whole-heading-line
5557 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5558 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5559 (1 (org-get-level-face 1))
5560 (2 (org-get-level-face 2))
5561 (3 (org-get-level-face 3)))
5562 ;; Table lines
5563 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5564 (1 'org-table t))
5565 ;; Table internals
5566 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5567 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5568 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5569 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5570 ;; Drawers
5571 (list org-drawer-regexp '(0 'org-special-keyword t))
5572 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5573 ;; Properties
5574 (list org-property-re
5575 '(1 'org-special-keyword t)
5576 '(3 'org-property-value t))
5577 ;; Links
5578 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5579 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5580 (if (memq 'plain lk) '(org-activate-plain-links))
5581 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5582 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5583 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5584 (if (memq 'footnote lk) '(org-activate-footnote-links))
5585 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5586 '(org-hide-wide-columns (0 nil append))
5587 ;; TODO lines
5588 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5589 '(1 (org-get-todo-face 1) t))
5590 ;; DONE
5591 (if org-fontify-done-headline
5592 (list (concat "^[*]+ +\\<\\("
5593 (mapconcat 'regexp-quote org-done-keywords "\\|")
5594 "\\)\\(.*\\)")
5595 '(2 'org-headline-done t))
5596 nil)
5597 ;; Priorities
5598 '(org-font-lock-add-priority-faces)
5599 ;; Tags
5600 '(org-font-lock-add-tag-faces)
5601 ;; Special keywords
5602 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5603 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5604 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5605 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5606 ;; Emphasis
5607 (if em
5608 (if (featurep 'xemacs)
5609 '(org-do-emphasis-faces (0 nil append))
5610 '(org-do-emphasis-faces)))
5611 ;; Checkboxes
5612 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5613 1 'org-checkbox prepend)
5614 (if (cdr (assq 'checkbox org-list-automatic-rules))
5615 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5616 (0 (org-get-checkbox-statistics-face) t)))
5617 ;; Description list items
5618 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5619 1 'bold prepend)
5620 ;; ARCHIVEd headings
5621 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5622 '(1 'org-archived prepend))
5623 ;; Specials
5624 '(org-do-latex-and-special-faces)
5625 '(org-fontify-entities)
5626 '(org-raise-scripts)
5627 ;; Code
5628 '(org-activate-code (1 'org-code t))
5629 ;; COMMENT
5630 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5631 "\\|" org-quote-string "\\)\\>")
5632 '(1 'org-special-keyword t))
5633 '("^#.*" (0 'font-lock-comment-face t))
5634 ;; Blocks and meta lines
5635 '(org-fontify-meta-lines-and-blocks)
5637 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5638 (run-hooks 'org-font-lock-set-keywords-hook)
5639 ;; Now set the full font-lock-keywords
5640 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5641 (org-set-local 'font-lock-defaults
5642 '(org-font-lock-keywords t nil nil backward-paragraph))
5643 (kill-local-variable 'font-lock-keywords) nil))
5645 (defun org-toggle-pretty-entities ()
5646 "Toggle the composition display of entities as UTF8 characters."
5647 (interactive)
5648 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5649 (org-restart-font-lock)
5650 (if org-pretty-entities
5651 (message "Entities are displayed as UTF8 characers")
5652 (save-restriction
5653 (widen)
5654 (org-decompose-region (point-min) (point-max))
5655 (message "Entities are displayed plain"))))
5657 (defun org-fontify-entities (limit)
5658 "Find an entity to fontify."
5659 (let (ee)
5660 (when org-pretty-entities
5661 (catch 'match
5662 (while (re-search-forward
5663 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5664 limit t)
5665 (if (and (not (org-in-indented-comment-line))
5666 (setq ee (org-entity-get (match-string 1)))
5667 (= (length (nth 6 ee)) 1))
5668 (progn
5669 (add-text-properties
5670 (match-beginning 0) (match-end 1)
5671 (list 'font-lock-fontified t))
5672 (compose-region (match-beginning 0) (match-end 1)
5673 (nth 6 ee) nil)
5674 (backward-char 1)
5675 (throw 'match t))))
5676 nil))))
5678 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5679 "Fontify string S like in Org-mode."
5680 (with-temp-buffer
5681 (insert s)
5682 (let ((org-odd-levels-only odd-levels))
5683 (org-mode)
5684 (font-lock-fontify-buffer)
5685 (buffer-string))))
5687 (defvar org-m nil)
5688 (defvar org-l nil)
5689 (defvar org-f nil)
5690 (defun org-get-level-face (n)
5691 "Get the right face for match N in font-lock matching of headlines."
5692 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5693 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5694 (if org-cycle-level-faces
5695 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5696 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5697 (cond
5698 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5699 ((eq n 2) org-f)
5700 (t (if org-level-color-stars-only nil org-f))))
5703 (defun org-get-todo-face (kwd)
5704 "Get the right face for a TODO keyword KWD.
5705 If KWD is a number, get the corresponding match group."
5706 (if (numberp kwd) (setq kwd (match-string kwd)))
5707 (or (org-face-from-face-or-color
5708 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5709 (and (member kwd org-done-keywords) 'org-done)
5710 'org-todo))
5712 (defun org-face-from-face-or-color (context inherit face-or-color)
5713 "Create a face list that inherits INHERIT, but sets the foreground color.
5714 When FACE-OR-COLOR is not a string, just return it."
5715 (if (stringp face-or-color)
5716 (list :inherit inherit
5717 (cdr (assoc context org-faces-easy-properties))
5718 face-or-color)
5719 face-or-color))
5721 (defun org-font-lock-add-tag-faces (limit)
5722 "Add the special tag faces."
5723 (when (and org-tag-faces org-tags-special-faces-re)
5724 (while (re-search-forward org-tags-special-faces-re limit t)
5725 (add-text-properties (match-beginning 1) (match-end 1)
5726 (list 'face (org-get-tag-face 1)
5727 'font-lock-fontified t))
5728 (backward-char 1))))
5730 (defun org-font-lock-add-priority-faces (limit)
5731 "Add the special priority faces."
5732 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5733 (add-text-properties
5734 (match-beginning 0) (match-end 0)
5735 (list 'face (or (org-face-from-face-or-color
5736 'priority 'org-special-keyword
5737 (cdr (assoc (char-after (match-beginning 1))
5738 org-priority-faces)))
5739 'org-special-keyword)
5740 'font-lock-fontified t))))
5742 (defun org-get-tag-face (kwd)
5743 "Get the right face for a TODO keyword KWD.
5744 If KWD is a number, get the corresponding match group."
5745 (if (numberp kwd) (setq kwd (match-string kwd)))
5746 (or (org-face-from-face-or-color
5747 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5748 'org-tag))
5750 (defun org-unfontify-region (beg end &optional maybe_loudly)
5751 "Remove fontification and activation overlays from links."
5752 (font-lock-default-unfontify-region beg end)
5753 (let* ((buffer-undo-list t)
5754 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5755 (inhibit-modification-hooks t)
5756 deactivate-mark buffer-file-name buffer-file-truename)
5757 (org-decompose-region beg end)
5758 (remove-text-properties
5759 beg end
5760 (if org-indent-mode
5761 ;; also remove line-prefix and wrap-prefix properties
5762 '(mouse-face t keymap t org-linked-text t
5763 invisible t intangible t
5764 line-prefix t wrap-prefix t
5765 org-no-flyspell t org-emphasis t)
5766 '(mouse-face t keymap t org-linked-text t
5767 invisible t intangible t
5768 org-no-flyspell t org-emphasis t)))
5769 (org-remove-font-lock-display-properties beg end)))
5771 (defconst org-script-display '(((raise -0.3) (height 0.7))
5772 ((raise 0.3) (height 0.7))
5773 ((raise -0.5))
5774 ((raise 0.5)))
5775 "Display properties for showing superscripts and subscripts.")
5777 (defun org-remove-font-lock-display-properties (beg end)
5778 "Remove specific display properties that have been added by font lock.
5779 The will remove the raise properties that are used to show superscripts
5780 and subscripts."
5781 (let (next prop)
5782 (while (< beg end)
5783 (setq next (next-single-property-change beg 'display nil end)
5784 prop (get-text-property beg 'display))
5785 (if (member prop org-script-display)
5786 (put-text-property beg next 'display nil))
5787 (setq beg next))))
5789 (defun org-raise-scripts (limit)
5790 "Add raise properties to sub/superscripts."
5791 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5792 (if (re-search-forward
5793 (if (eq org-use-sub-superscripts t)
5794 org-match-substring-regexp
5795 org-match-substring-with-braces-regexp)
5796 limit t)
5797 (let* ((pos (point)) table-p comment-p
5798 (mpos (match-beginning 3))
5799 (emph-p (get-text-property mpos 'org-emphasis))
5800 (link-p (get-text-property mpos 'mouse-face))
5801 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5802 (goto-char (point-at-bol))
5803 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5804 comment-p (org-looking-at-p "[ \t]*#"))
5805 (goto-char pos)
5806 ;; FIXME: Should we go back one character here, for a_b^c
5807 ;; (goto-char (1- pos)) ;????????????????????
5808 (if (or comment-p emph-p link-p keyw-p)
5810 (put-text-property (match-beginning 3) (match-end 0)
5811 'display
5812 (if (equal (char-after (match-beginning 2)) ?^)
5813 (nth (if table-p 3 1) org-script-display)
5814 (nth (if table-p 2 0) org-script-display)))
5815 (add-text-properties (match-beginning 2) (match-end 2)
5816 (list 'invisible t
5817 'org-dwidth t 'org-dwidth-n 1))
5818 (if (and (eq (char-after (match-beginning 3)) ?{)
5819 (eq (char-before (match-end 3)) ?}))
5820 (progn
5821 (add-text-properties
5822 (match-beginning 3) (1+ (match-beginning 3))
5823 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5824 (add-text-properties
5825 (1- (match-end 3)) (match-end 3)
5826 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5827 t)))))
5829 ;;;; Visibility cycling, including org-goto and indirect buffer
5831 ;;; Cycling
5833 (defvar org-cycle-global-status nil)
5834 (make-variable-buffer-local 'org-cycle-global-status)
5835 (defvar org-cycle-subtree-status nil)
5836 (make-variable-buffer-local 'org-cycle-subtree-status)
5838 ;;;###autoload
5840 (defvar org-inlinetask-min-level)
5842 (defun org-cycle (&optional arg)
5843 "TAB-action and visibility cycling for Org-mode.
5845 This is the command invoked in Org-mode by the TAB key. Its main purpose
5846 is outline visibility cycling, but it also invokes other actions
5847 in special contexts.
5849 - When this function is called with a prefix argument, rotate the entire
5850 buffer through 3 states (global cycling)
5851 1. OVERVIEW: Show only top-level headlines.
5852 2. CONTENTS: Show all headlines of all levels, but no body text.
5853 3. SHOW ALL: Show everything.
5854 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5855 determined by the variable `org-startup-folded', and by any VISIBILITY
5856 properties in the buffer.
5857 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5858 including any drawers.
5860 - When inside a table, re-align the table and move to the next field.
5862 - When point is at the beginning of a headline, rotate the subtree started
5863 by this line through 3 different states (local cycling)
5864 1. FOLDED: Only the main headline is shown.
5865 2. CHILDREN: The main headline and the direct children are shown.
5866 From this state, you can move to one of the children
5867 and zoom in further.
5868 3. SUBTREE: Show the entire subtree, including body text.
5869 If there is no subtree, switch directly from CHILDREN to FOLDED.
5871 - When point is at the beginning of an empty headline and the variable
5872 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5873 of the headline by demoting and promoting it to likely levels. This
5874 speeds up creation document structure by pressing TAB once or several
5875 times right after creating a new headline.
5877 - When there is a numeric prefix, go up to a heading with level ARG, do
5878 a `show-subtree' and return to the previous cursor position. If ARG
5879 is negative, go up that many levels.
5881 - When point is not at the beginning of a headline, execute the global
5882 binding for TAB, which is re-indenting the line. See the option
5883 `org-cycle-emulate-tab' for details.
5885 - Special case: if point is at the beginning of the buffer and there is
5886 no headline in line 1, this function will act as if called with prefix arg
5887 (C-u TAB, same as S-TAB) also when called without prefix arg.
5888 But only if also the variable `org-cycle-global-at-bob' is t."
5889 (interactive "P")
5890 (org-load-modules-maybe)
5891 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5892 (and org-cycle-level-after-item/entry-creation
5893 (or (org-cycle-level)
5894 (org-cycle-item-indentation))))
5895 (let* ((limit-level
5896 (or org-cycle-max-level
5897 (and (boundp 'org-inlinetask-min-level)
5898 org-inlinetask-min-level
5899 (1- org-inlinetask-min-level))))
5900 (nstars (and limit-level
5901 (if org-odd-levels-only
5902 (and limit-level (1- (* limit-level 2)))
5903 limit-level)))
5904 (outline-regexp
5905 (if (not (org-mode-p))
5906 outline-regexp
5907 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5908 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5909 (not (looking-at outline-regexp))))
5910 (org-cycle-hook
5911 (if bob-special
5912 (delq 'org-optimize-window-after-visibility-change
5913 (copy-sequence org-cycle-hook))
5914 org-cycle-hook))
5915 (pos (point)))
5917 (if (or bob-special (equal arg '(4)))
5918 ;; special case: use global cycling
5919 (setq arg t))
5921 (cond
5923 ((equal arg '(16))
5924 (setq last-command 'dummy)
5925 (org-set-startup-visibility)
5926 (message "Startup visibility, plus VISIBILITY properties"))
5928 ((equal arg '(64))
5929 (show-all)
5930 (message "Entire buffer visible, including drawers"))
5932 ;; Table: enter it or move to the next field.
5933 ((org-at-table-p 'any)
5934 (if (org-at-table.el-p)
5935 (message "Use C-c ' to edit table.el tables")
5936 (if arg (org-table-edit-field t)
5937 (org-table-justify-field-maybe)
5938 (call-interactively 'org-table-next-field))))
5940 ((run-hook-with-args-until-success
5941 'org-tab-after-check-for-table-hook))
5943 ;; Global cycling: delegate to `org-cycle-internal-global'.
5944 ((eq arg t) (org-cycle-internal-global))
5946 ;; Drawers: delegate to `org-flag-drawer'.
5947 ((and org-drawers org-drawer-regexp
5948 (save-excursion
5949 (beginning-of-line 1)
5950 (looking-at org-drawer-regexp)))
5951 (org-flag-drawer ; toggle block visibility
5952 (not (get-char-property (match-end 0) 'invisible))))
5954 ;; Show-subtree, ARG levels up from here.
5955 ((integerp arg)
5956 (save-excursion
5957 (org-back-to-heading)
5958 (outline-up-heading (if (< arg 0) (- arg)
5959 (- (funcall outline-level) arg)))
5960 (org-show-subtree)))
5962 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5963 ((and (featurep 'org-inlinetask)
5964 (org-inlinetask-at-task-p)
5965 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5966 (org-inlinetask-toggle-visibility))
5968 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5969 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5970 (save-excursion (beginning-of-line 1)
5971 (looking-at outline-regexp)))
5972 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5973 (org-cycle-internal-local))
5975 ;; From there: TAB emulation and template completion.
5976 (buffer-read-only (org-back-to-heading))
5978 ((run-hook-with-args-until-success
5979 'org-tab-after-check-for-cycling-hook))
5981 ((org-try-structure-completion))
5983 ((org-try-cdlatex-tab))
5985 ((run-hook-with-args-until-success
5986 'org-tab-before-tab-emulation-hook))
5988 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5989 (or (not (bolp))
5990 (not (looking-at outline-regexp))))
5991 (call-interactively (global-key-binding "\t")))
5993 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5994 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5995 (or (and (eq org-cycle-emulate-tab 'white)
5996 (= (match-end 0) (point-at-eol)))
5997 (and (eq org-cycle-emulate-tab 'whitestart)
5998 (>= (match-end 0) pos))))
6000 (eq org-cycle-emulate-tab t))
6001 (call-interactively (global-key-binding "\t")))
6003 (t (save-excursion
6004 (org-back-to-heading)
6005 (org-cycle)))))))
6007 (defun org-cycle-internal-global ()
6008 "Do the global cycling action."
6009 (cond
6010 ((and (eq last-command this-command)
6011 (eq org-cycle-global-status 'overview))
6012 ;; We just created the overview - now do table of contents
6013 ;; This can be slow in very large buffers, so indicate action
6014 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6015 (message "CONTENTS...")
6016 (org-content)
6017 (message "CONTENTS...done")
6018 (setq org-cycle-global-status 'contents)
6019 (run-hook-with-args 'org-cycle-hook 'contents))
6021 ((and (eq last-command this-command)
6022 (eq org-cycle-global-status 'contents))
6023 ;; We just showed the table of contents - now show everything
6024 (run-hook-with-args 'org-pre-cycle-hook 'all)
6025 (show-all)
6026 (message "SHOW ALL")
6027 (setq org-cycle-global-status 'all)
6028 (run-hook-with-args 'org-cycle-hook 'all))
6031 ;; Default action: go to overview
6032 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6033 (org-overview)
6034 (message "OVERVIEW")
6035 (setq org-cycle-global-status 'overview)
6036 (run-hook-with-args 'org-cycle-hook 'overview))))
6038 (defun org-cycle-internal-local ()
6039 "Do the local cycling action."
6040 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6041 ;; First, determine end of headline (EOH), end of subtree or item
6042 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6043 (save-excursion
6044 (if (org-at-item-p)
6045 (progn
6046 (beginning-of-line)
6047 (setq struct (org-list-struct))
6048 (setq eoh (point-at-eol))
6049 (setq eos (org-list-get-item-end-before-blank (point) struct))
6050 (setq has-children (org-list-has-child-p (point) struct)))
6051 (org-back-to-heading)
6052 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6053 (setq eos (save-excursion
6054 (org-end-of-subtree t)
6055 (unless (eobp)
6056 (skip-chars-forward " \t\n"))
6057 (if (eobp) (point) (1- (point)))))
6058 (setq has-children
6059 (or (save-excursion
6060 (let ((level (funcall outline-level)))
6061 (outline-next-heading)
6062 (and (org-at-heading-p t)
6063 (> (funcall outline-level) level))))
6064 (save-excursion
6065 (org-list-search-forward (org-item-beginning-re) eos t)))))
6066 ;; Determine end invisible part of buffer (EOL)
6067 (beginning-of-line 2)
6068 ;; XEmacs doesn't have `next-single-char-property-change'
6069 (if (featurep 'xemacs)
6070 (while (and (not (eobp)) ;; this is like `next-line'
6071 (get-char-property (1- (point)) 'invisible))
6072 (beginning-of-line 2))
6073 (while (and (not (eobp)) ;; this is like `next-line'
6074 (get-char-property (1- (point)) 'invisible))
6075 (goto-char (next-single-char-property-change (point) 'invisible))
6076 (and (eolp) (beginning-of-line 2))))
6077 (setq eol (point)))
6078 ;; Find out what to do next and set `this-command'
6079 (cond
6080 ((= eos eoh)
6081 ;; Nothing is hidden behind this heading
6082 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6083 (message "EMPTY ENTRY")
6084 (setq org-cycle-subtree-status nil)
6085 (save-excursion
6086 (goto-char eos)
6087 (outline-next-heading)
6088 (if (outline-invisible-p) (org-flag-heading nil))))
6089 ((and (or (>= eol eos)
6090 (not (string-match "\\S-" (buffer-substring eol eos))))
6091 (or has-children
6092 (not (setq children-skipped
6093 org-cycle-skip-children-state-if-no-children))))
6094 ;; Entire subtree is hidden in one line: children view
6095 (run-hook-with-args 'org-pre-cycle-hook 'children)
6096 (if (org-at-item-p)
6097 (org-list-set-item-visibility (point-at-bol) struct 'children)
6098 (org-show-entry)
6099 (show-children)
6100 ;; Fold every list in subtree to top-level items.
6101 (when (eq org-cycle-include-plain-lists 'integrate)
6102 (save-excursion
6103 (org-back-to-heading)
6104 (while (org-list-search-forward (org-item-beginning-re) eos t)
6105 (beginning-of-line 1)
6106 (let* ((struct (org-list-struct))
6107 (prevs (org-list-prevs-alist struct))
6108 (end (org-list-get-bottom-point struct)))
6109 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6110 (org-list-get-all-items (point) struct prevs))
6111 (goto-char end))))))
6112 (message "CHILDREN")
6113 (save-excursion
6114 (goto-char eos)
6115 (outline-next-heading)
6116 (if (outline-invisible-p) (org-flag-heading nil)))
6117 (setq org-cycle-subtree-status 'children)
6118 (run-hook-with-args 'org-cycle-hook 'children))
6119 ((or children-skipped
6120 (and (eq last-command this-command)
6121 (eq org-cycle-subtree-status 'children)))
6122 ;; We just showed the children, or no children are there,
6123 ;; now show everything.
6124 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6125 (outline-flag-region eoh eos nil)
6126 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6127 (setq org-cycle-subtree-status 'subtree)
6128 (run-hook-with-args 'org-cycle-hook 'subtree))
6130 ;; Default action: hide the subtree.
6131 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6132 (outline-flag-region eoh eos t)
6133 (message "FOLDED")
6134 (setq org-cycle-subtree-status 'folded)
6135 (run-hook-with-args 'org-cycle-hook 'folded)))))
6137 ;;;###autoload
6138 (defun org-global-cycle (&optional arg)
6139 "Cycle the global visibility. For details see `org-cycle'.
6140 With \\[universal-argument] prefix arg, switch to startup visibility.
6141 With a numeric prefix, show all headlines up to that level."
6142 (interactive "P")
6143 (let ((org-cycle-include-plain-lists
6144 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6145 (cond
6146 ((integerp arg)
6147 (show-all)
6148 (hide-sublevels arg)
6149 (setq org-cycle-global-status 'contents))
6150 ((equal arg '(4))
6151 (org-set-startup-visibility)
6152 (message "Startup visibility, plus VISIBILITY properties."))
6154 (org-cycle '(4))))))
6156 (defun org-set-startup-visibility ()
6157 "Set the visibility required by startup options and properties."
6158 (cond
6159 ((eq org-startup-folded t)
6160 (org-cycle '(4)))
6161 ((eq org-startup-folded 'content)
6162 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6163 (org-cycle '(4)) (org-cycle '(4)))))
6164 (unless (eq org-startup-folded 'showeverything)
6165 (if org-hide-block-startup (org-hide-block-all))
6166 (org-set-visibility-according-to-property 'no-cleanup)
6167 (org-cycle-hide-archived-subtrees 'all)
6168 (org-cycle-hide-drawers 'all)
6169 (org-cycle-show-empty-lines t)))
6171 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6172 "Switch subtree visibilities according to :VISIBILITY: property."
6173 (interactive)
6174 (let (org-show-entry-below state)
6175 (save-excursion
6176 (goto-char (point-min))
6177 (while (re-search-forward
6178 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6179 nil t)
6180 (setq state (match-string 1))
6181 (save-excursion
6182 (org-back-to-heading t)
6183 (hide-subtree)
6184 (org-reveal)
6185 (cond
6186 ((equal state '("fold" "folded"))
6187 (hide-subtree))
6188 ((equal state "children")
6189 (org-show-hidden-entry)
6190 (show-children))
6191 ((equal state "content")
6192 (save-excursion
6193 (save-restriction
6194 (org-narrow-to-subtree)
6195 (org-content))))
6196 ((member state '("all" "showall"))
6197 (show-subtree)))))
6198 (unless no-cleanup
6199 (org-cycle-hide-archived-subtrees 'all)
6200 (org-cycle-hide-drawers 'all)
6201 (org-cycle-show-empty-lines 'all)))))
6203 (defun org-overview ()
6204 "Switch to overview mode, showing only top-level headlines.
6205 Really, this shows all headlines with level equal or greater than the level
6206 of the first headline in the buffer. This is important, because if the
6207 first headline is not level one, then (hide-sublevels 1) gives confusing
6208 results."
6209 (interactive)
6210 (let ((level (save-excursion
6211 (goto-char (point-min))
6212 (if (re-search-forward (concat "^" outline-regexp) nil t)
6213 (progn
6214 (goto-char (match-beginning 0))
6215 (funcall outline-level))))))
6216 (and level (hide-sublevels level))))
6218 (defun org-content (&optional arg)
6219 "Show all headlines in the buffer, like a table of contents.
6220 With numerical argument N, show content up to level N."
6221 (interactive "P")
6222 (save-excursion
6223 ;; Visit all headings and show their offspring
6224 (and (integerp arg) (org-overview))
6225 (goto-char (point-max))
6226 (catch 'exit
6227 (while (and (progn (condition-case nil
6228 (outline-previous-visible-heading 1)
6229 (error (goto-char (point-min))))
6231 (looking-at outline-regexp))
6232 (if (integerp arg)
6233 (show-children (1- arg))
6234 (show-branches))
6235 (if (bobp) (throw 'exit nil))))))
6238 (defun org-optimize-window-after-visibility-change (state)
6239 "Adjust the window after a change in outline visibility.
6240 This function is the default value of the hook `org-cycle-hook'."
6241 (when (get-buffer-window (current-buffer))
6242 (cond
6243 ((eq state 'content) nil)
6244 ((eq state 'all) nil)
6245 ((eq state 'folded) nil)
6246 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6247 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6249 (defun org-remove-empty-overlays-at (pos)
6250 "Remove outline overlays that do not contain non-white stuff."
6251 (mapc
6252 (lambda (o)
6253 (and (eq 'outline (overlay-get o 'invisible))
6254 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6255 (overlay-end o))))
6256 (delete-overlay o)))
6257 (overlays-at pos)))
6259 (defun org-clean-visibility-after-subtree-move ()
6260 "Fix visibility issues after moving a subtree."
6261 ;; First, find a reasonable region to look at:
6262 ;; Start two siblings above, end three below
6263 (let* ((beg (save-excursion
6264 (and (org-get-last-sibling)
6265 (org-get-last-sibling))
6266 (point)))
6267 (end (save-excursion
6268 (and (org-get-next-sibling)
6269 (org-get-next-sibling)
6270 (org-get-next-sibling))
6271 (if (org-at-heading-p)
6272 (point-at-eol)
6273 (point))))
6274 (level (looking-at "\\*+"))
6275 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6276 (save-excursion
6277 (save-restriction
6278 (narrow-to-region beg end)
6279 (when re
6280 ;; Properly fold already folded siblings
6281 (goto-char (point-min))
6282 (while (re-search-forward re nil t)
6283 (if (and (not (outline-invisible-p))
6284 (save-excursion
6285 (goto-char (point-at-eol)) (outline-invisible-p)))
6286 (hide-entry))))
6287 (org-cycle-show-empty-lines 'overview)
6288 (org-cycle-hide-drawers 'overview)))))
6290 (defun org-cycle-show-empty-lines (state)
6291 "Show empty lines above all visible headlines.
6292 The region to be covered depends on STATE when called through
6293 `org-cycle-hook'. Lisp program can use t for STATE to get the
6294 entire buffer covered. Note that an empty line is only shown if there
6295 are at least `org-cycle-separator-lines' empty lines before the headline."
6296 (when (not (= org-cycle-separator-lines 0))
6297 (save-excursion
6298 (let* ((n (abs org-cycle-separator-lines))
6299 (re (cond
6300 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6301 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6302 (t (let ((ns (number-to-string (- n 2))))
6303 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6304 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6305 beg end b e)
6306 (cond
6307 ((memq state '(overview contents t))
6308 (setq beg (point-min) end (point-max)))
6309 ((memq state '(children folded))
6310 (setq beg (point) end (progn (org-end-of-subtree t t)
6311 (beginning-of-line 2)
6312 (point)))))
6313 (when beg
6314 (goto-char beg)
6315 (while (re-search-forward re end t)
6316 (unless (get-char-property (match-end 1) 'invisible)
6317 (setq e (match-end 1))
6318 (if (< org-cycle-separator-lines 0)
6319 (setq b (save-excursion
6320 (goto-char (match-beginning 0))
6321 (org-back-over-empty-lines)
6322 (if (save-excursion
6323 (goto-char (max (point-min) (1- (point))))
6324 (org-on-heading-p))
6325 (1- (point))
6326 (point))))
6327 (setq b (match-beginning 1)))
6328 (outline-flag-region b e nil)))))))
6329 ;; Never hide empty lines at the end of the file.
6330 (save-excursion
6331 (goto-char (point-max))
6332 (outline-previous-heading)
6333 (outline-end-of-heading)
6334 (if (and (looking-at "[ \t\n]+")
6335 (= (match-end 0) (point-max)))
6336 (outline-flag-region (point) (match-end 0) nil))))
6338 (defun org-show-empty-lines-in-parent ()
6339 "Move to the parent and re-show empty lines before visible headlines."
6340 (save-excursion
6341 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6342 (org-cycle-show-empty-lines context))))
6344 (defun org-files-list ()
6345 "Return `org-agenda-files' list, plus all open org-mode files.
6346 This is useful for operations that need to scan all of a user's
6347 open and agenda-wise Org files."
6348 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6349 (dolist (buf (buffer-list))
6350 (with-current-buffer buf
6351 (if (and (org-mode-p) (buffer-file-name))
6352 (let ((file (expand-file-name (buffer-file-name))))
6353 (unless (member file files)
6354 (push file files))))))
6355 files))
6357 (defsubst org-entry-beginning-position ()
6358 "Return the beginning position of the current entry."
6359 (save-excursion (outline-back-to-heading t) (point)))
6361 (defsubst org-entry-end-position ()
6362 "Return the end position of the current entry."
6363 (save-excursion (outline-next-heading) (point)))
6365 (defun org-cycle-hide-drawers (state)
6366 "Re-hide all drawers after a visibility state change."
6367 (when (and (org-mode-p)
6368 (not (memq state '(overview folded contents))))
6369 (save-excursion
6370 (let* ((globalp (memq state '(contents all)))
6371 (beg (if globalp (point-min) (point)))
6372 (end (if globalp (point-max)
6373 (if (eq state 'children)
6374 (save-excursion (outline-next-heading) (point))
6375 (org-end-of-subtree t)))))
6376 (goto-char beg)
6377 (while (re-search-forward org-drawer-regexp end t)
6378 (org-flag-drawer t))))))
6380 (defun org-flag-drawer (flag)
6381 (save-excursion
6382 (beginning-of-line 1)
6383 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6384 (let ((b (match-end 0))
6385 (outline-regexp org-outline-regexp))
6386 (if (re-search-forward
6387 "^[ \t]*:END:"
6388 (save-excursion (outline-next-heading) (point)) t)
6389 (outline-flag-region b (point-at-eol) flag)
6390 (error ":END: line missing at position %s" b))))))
6392 (defun org-subtree-end-visible-p ()
6393 "Is the end of the current subtree visible?"
6394 (pos-visible-in-window-p
6395 (save-excursion (org-end-of-subtree t) (point))))
6397 (defun org-first-headline-recenter (&optional N)
6398 "Move cursor to the first headline and recenter the headline.
6399 Optional argument N means put the headline into the Nth line of the window."
6400 (goto-char (point-min))
6401 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6402 (beginning-of-line)
6403 (recenter (prefix-numeric-value N))))
6405 ;;; Saving and restoring visibility
6407 (defun org-outline-overlay-data (&optional use-markers)
6408 "Return a list of the locations of all outline overlays.
6409 These are overlays with the `invisible' property value `outline'.
6410 The return value is a list of cons cells, with start and stop
6411 positions for each overlay.
6412 If USE-MARKERS is set, return the positions as markers."
6413 (let (beg end)
6414 (save-excursion
6415 (save-restriction
6416 (widen)
6417 (delq nil
6418 (mapcar (lambda (o)
6419 (when (eq (overlay-get o 'invisible) 'outline)
6420 (setq beg (overlay-start o)
6421 end (overlay-end o))
6422 (and beg end (> end beg)
6423 (if use-markers
6424 (cons (move-marker (make-marker) beg)
6425 (move-marker (make-marker) end))
6426 (cons beg end)))))
6427 (overlays-in (point-min) (point-max))))))))
6429 (defun org-set-outline-overlay-data (data)
6430 "Create visibility overlays for all positions in DATA.
6431 DATA should have been made by `org-outline-overlay-data'."
6432 (let (o)
6433 (save-excursion
6434 (save-restriction
6435 (widen)
6436 (show-all)
6437 (mapc (lambda (c)
6438 (setq o (make-overlay (car c) (cdr c)))
6439 (overlay-put o 'invisible 'outline))
6440 data)))))
6442 ;;; Folding of blocks
6444 (defconst org-block-regexp
6445 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6446 "Regular expression for hiding blocks.")
6448 (defvar org-hide-block-overlays nil
6449 "Overlays hiding blocks.")
6450 (make-variable-buffer-local 'org-hide-block-overlays)
6452 (defun org-block-map (function &optional start end)
6453 "Call FUNCTION at the head of all source blocks in the current buffer.
6454 Optional arguments START and END can be used to limit the range."
6455 (let ((start (or start (point-min)))
6456 (end (or end (point-max))))
6457 (save-excursion
6458 (goto-char start)
6459 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6460 (save-excursion
6461 (save-match-data
6462 (goto-char (match-beginning 0))
6463 (funcall function)))))))
6465 (defun org-hide-block-toggle-all ()
6466 "Toggle the visibility of all blocks in the current buffer."
6467 (org-block-map #'org-hide-block-toggle))
6469 (defun org-hide-block-all ()
6470 "Fold all blocks in the current buffer."
6471 (interactive)
6472 (org-show-block-all)
6473 (org-block-map #'org-hide-block-toggle-maybe))
6475 (defun org-show-block-all ()
6476 "Unfold all blocks in the current buffer."
6477 (interactive)
6478 (mapc 'delete-overlay org-hide-block-overlays)
6479 (setq org-hide-block-overlays nil))
6481 (defun org-hide-block-toggle-maybe ()
6482 "Toggle visibility of block at point."
6483 (interactive)
6484 (let ((case-fold-search t))
6485 (if (save-excursion
6486 (beginning-of-line 1)
6487 (looking-at org-block-regexp))
6488 (progn (org-hide-block-toggle)
6489 t) ;; to signal that we took action
6490 nil))) ;; to signal that we did not
6492 (defun org-hide-block-toggle (&optional force)
6493 "Toggle the visibility of the current block."
6494 (interactive)
6495 (save-excursion
6496 (beginning-of-line)
6497 (if (re-search-forward org-block-regexp nil t)
6498 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6499 (end (match-end 0)) ;; end of entire body
6501 (if (memq t (mapcar (lambda (overlay)
6502 (eq (overlay-get overlay 'invisible)
6503 'org-hide-block))
6504 (overlays-at start)))
6505 (if (or (not force) (eq force 'off))
6506 (mapc (lambda (ov)
6507 (when (member ov org-hide-block-overlays)
6508 (setq org-hide-block-overlays
6509 (delq ov org-hide-block-overlays)))
6510 (when (eq (overlay-get ov 'invisible)
6511 'org-hide-block)
6512 (delete-overlay ov)))
6513 (overlays-at start)))
6514 (setq ov (make-overlay start end))
6515 (overlay-put ov 'invisible 'org-hide-block)
6516 ;; make the block accessible to isearch
6517 (overlay-put
6518 ov 'isearch-open-invisible
6519 (lambda (ov)
6520 (when (member ov org-hide-block-overlays)
6521 (setq org-hide-block-overlays
6522 (delq ov org-hide-block-overlays)))
6523 (when (eq (overlay-get ov 'invisible)
6524 'org-hide-block)
6525 (delete-overlay ov))))
6526 (push ov org-hide-block-overlays)))
6527 (error "Not looking at a source block"))))
6529 ;; org-tab-after-check-for-cycling-hook
6530 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6531 ;; Remove overlays when changing major mode
6532 (add-hook 'org-mode-hook
6533 (lambda () (org-add-hook 'change-major-mode-hook
6534 'org-show-block-all 'append 'local)))
6536 ;;; Org-goto
6538 (defvar org-goto-window-configuration nil)
6539 (defvar org-goto-marker nil)
6540 (defvar org-goto-map
6541 (let ((map (make-sparse-keymap)))
6542 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6543 (while (setq cmd (pop cmds))
6544 (substitute-key-definition cmd cmd map global-map)))
6545 (suppress-keymap map)
6546 (org-defkey map "\C-m" 'org-goto-ret)
6547 (org-defkey map [(return)] 'org-goto-ret)
6548 (org-defkey map [(left)] 'org-goto-left)
6549 (org-defkey map [(right)] 'org-goto-right)
6550 (org-defkey map [(control ?g)] 'org-goto-quit)
6551 (org-defkey map "\C-i" 'org-cycle)
6552 (org-defkey map [(tab)] 'org-cycle)
6553 (org-defkey map [(down)] 'outline-next-visible-heading)
6554 (org-defkey map [(up)] 'outline-previous-visible-heading)
6555 (if org-goto-auto-isearch
6556 (if (fboundp 'define-key-after)
6557 (define-key-after map [t] 'org-goto-local-auto-isearch)
6558 nil)
6559 (org-defkey map "q" 'org-goto-quit)
6560 (org-defkey map "n" 'outline-next-visible-heading)
6561 (org-defkey map "p" 'outline-previous-visible-heading)
6562 (org-defkey map "f" 'outline-forward-same-level)
6563 (org-defkey map "b" 'outline-backward-same-level)
6564 (org-defkey map "u" 'outline-up-heading))
6565 (org-defkey map "/" 'org-occur)
6566 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6567 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6568 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6569 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6570 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6571 map))
6573 (defconst org-goto-help
6574 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6575 RET=jump to location [Q]uit and return to previous location
6576 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6578 (defvar org-goto-start-pos) ; dynamically scoped parameter
6580 ;; FIXME: Docstring does not mention both interfaces
6581 (defun org-goto (&optional alternative-interface)
6582 "Look up a different location in the current file, keeping current visibility.
6584 When you want look-up or go to a different location in a document, the
6585 fastest way is often to fold the entire buffer and then dive into the tree.
6586 This method has the disadvantage, that the previous location will be folded,
6587 which may not be what you want.
6589 This command works around this by showing a copy of the current buffer
6590 in an indirect buffer, in overview mode. You can dive into the tree in
6591 that copy, use org-occur and incremental search to find a location.
6592 When pressing RET or `Q', the command returns to the original buffer in
6593 which the visibility is still unchanged. After RET is will also jump to
6594 the location selected in the indirect buffer and expose the headline
6595 hierarchy above."
6596 (interactive "P")
6597 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6598 (org-refile-use-outline-path t)
6599 (org-refile-target-verify-function nil)
6600 (interface
6601 (if (not alternative-interface)
6602 org-goto-interface
6603 (if (eq org-goto-interface 'outline)
6604 'outline-path-completion
6605 'outline)))
6606 (org-goto-start-pos (point))
6607 (selected-point
6608 (if (eq interface 'outline)
6609 (car (org-get-location (current-buffer) org-goto-help))
6610 (let ((pa (org-refile-get-location "Goto")))
6611 (org-refile-check-position pa)
6612 (nth 3 pa)))))
6613 (if selected-point
6614 (progn
6615 (org-mark-ring-push org-goto-start-pos)
6616 (goto-char selected-point)
6617 (if (or (outline-invisible-p) (org-invisible-p2))
6618 (org-show-context 'org-goto)))
6619 (message "Quit"))))
6621 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6622 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6623 (defvar org-goto-local-auto-isearch-map) ; defined below
6625 (defun org-get-location (buf help)
6626 "Let the user select a location in the Org-mode buffer BUF.
6627 This function uses a recursive edit. It returns the selected position
6628 or nil."
6629 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6630 (isearch-hide-immediately nil)
6631 (isearch-search-fun-function
6632 (lambda () 'org-goto-local-search-headings))
6633 (org-goto-selected-point org-goto-exit-command)
6634 (pop-up-frames nil)
6635 (special-display-buffer-names nil)
6636 (special-display-regexps nil)
6637 (special-display-function nil))
6638 (save-excursion
6639 (save-window-excursion
6640 (delete-other-windows)
6641 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6642 (switch-to-buffer
6643 (condition-case nil
6644 (make-indirect-buffer (current-buffer) "*org-goto*")
6645 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6646 (with-output-to-temp-buffer "*Help*"
6647 (princ help))
6648 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6649 (setq buffer-read-only nil)
6650 (let ((org-startup-truncated t)
6651 (org-startup-folded nil)
6652 (org-startup-align-all-tables nil))
6653 (org-mode)
6654 (org-overview))
6655 (setq buffer-read-only t)
6656 (if (and (boundp 'org-goto-start-pos)
6657 (integer-or-marker-p org-goto-start-pos))
6658 (let ((org-show-hierarchy-above t)
6659 (org-show-siblings t)
6660 (org-show-following-heading t))
6661 (goto-char org-goto-start-pos)
6662 (and (outline-invisible-p) (org-show-context)))
6663 (goto-char (point-min)))
6664 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6665 (message "Select location and press RET")
6666 (use-local-map org-goto-map)
6667 (recursive-edit)
6669 (kill-buffer "*org-goto*")
6670 (cons org-goto-selected-point org-goto-exit-command)))
6672 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6673 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6674 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6675 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6677 (defun org-goto-local-search-headings (string bound noerror)
6678 "Search and make sure that any matches are in headlines."
6679 (catch 'return
6680 (while (if isearch-forward
6681 (search-forward string bound noerror)
6682 (search-backward string bound noerror))
6683 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6684 (and (member :headline context)
6685 (not (member :tags context))))
6686 (throw 'return (point))))))
6688 (defun org-goto-local-auto-isearch ()
6689 "Start isearch."
6690 (interactive)
6691 (goto-char (point-min))
6692 (let ((keys (this-command-keys)))
6693 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6694 (isearch-mode t)
6695 (isearch-process-search-char (string-to-char keys)))))
6697 (defun org-goto-ret (&optional arg)
6698 "Finish `org-goto' by going to the new location."
6699 (interactive "P")
6700 (setq org-goto-selected-point (point)
6701 org-goto-exit-command 'return)
6702 (throw 'exit nil))
6704 (defun org-goto-left ()
6705 "Finish `org-goto' by going to the new location."
6706 (interactive)
6707 (if (org-on-heading-p)
6708 (progn
6709 (beginning-of-line 1)
6710 (setq org-goto-selected-point (point)
6711 org-goto-exit-command 'left)
6712 (throw 'exit nil))
6713 (error "Not on a heading")))
6715 (defun org-goto-right ()
6716 "Finish `org-goto' by going to the new location."
6717 (interactive)
6718 (if (org-on-heading-p)
6719 (progn
6720 (setq org-goto-selected-point (point)
6721 org-goto-exit-command 'right)
6722 (throw 'exit nil))
6723 (error "Not on a heading")))
6725 (defun org-goto-quit ()
6726 "Finish `org-goto' without cursor motion."
6727 (interactive)
6728 (setq org-goto-selected-point nil)
6729 (setq org-goto-exit-command 'quit)
6730 (throw 'exit nil))
6732 ;;; Indirect buffer display of subtrees
6734 (defvar org-indirect-dedicated-frame nil
6735 "This is the frame being used for indirect tree display.")
6736 (defvar org-last-indirect-buffer nil)
6738 (defun org-tree-to-indirect-buffer (&optional arg)
6739 "Create indirect buffer and narrow it to current subtree.
6740 With numerical prefix ARG, go up to this level and then take that tree.
6741 If ARG is negative, go up that many levels.
6742 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6743 indirect buffer previously made with this command, to avoid proliferation of
6744 indirect buffers. However, when you call the command with a \
6745 \\[universal-argument] prefix, or
6746 when `org-indirect-buffer-display' is `new-frame', the last buffer
6747 is kept so that you can work with several indirect buffers at the same time.
6748 If `org-indirect-buffer-display' is `dedicated-frame', the \
6749 \\[universal-argument] prefix also
6750 requests that a new frame be made for the new buffer, so that the dedicated
6751 frame is not changed."
6752 (interactive "P")
6753 (let ((cbuf (current-buffer))
6754 (cwin (selected-window))
6755 (pos (point))
6756 beg end level heading ibuf)
6757 (save-excursion
6758 (org-back-to-heading t)
6759 (when (numberp arg)
6760 (setq level (org-outline-level))
6761 (if (< arg 0) (setq arg (+ level arg)))
6762 (while (> (setq level (org-outline-level)) arg)
6763 (outline-up-heading 1 t)))
6764 (setq beg (point)
6765 heading (org-get-heading))
6766 (org-end-of-subtree t t)
6767 (if (org-on-heading-p) (backward-char 1))
6768 (setq end (point)))
6769 (if (and (buffer-live-p org-last-indirect-buffer)
6770 (not (eq org-indirect-buffer-display 'new-frame))
6771 (not arg))
6772 (kill-buffer org-last-indirect-buffer))
6773 (setq ibuf (org-get-indirect-buffer cbuf)
6774 org-last-indirect-buffer ibuf)
6775 (cond
6776 ((or (eq org-indirect-buffer-display 'new-frame)
6777 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6778 (select-frame (make-frame))
6779 (delete-other-windows)
6780 (switch-to-buffer ibuf)
6781 (org-set-frame-title heading))
6782 ((eq org-indirect-buffer-display 'dedicated-frame)
6783 (raise-frame
6784 (select-frame (or (and org-indirect-dedicated-frame
6785 (frame-live-p org-indirect-dedicated-frame)
6786 org-indirect-dedicated-frame)
6787 (setq org-indirect-dedicated-frame (make-frame)))))
6788 (delete-other-windows)
6789 (switch-to-buffer ibuf)
6790 (org-set-frame-title (concat "Indirect: " heading)))
6791 ((eq org-indirect-buffer-display 'current-window)
6792 (switch-to-buffer ibuf))
6793 ((eq org-indirect-buffer-display 'other-window)
6794 (pop-to-buffer ibuf))
6795 (t (error "Invalid value")))
6796 (if (featurep 'xemacs)
6797 (save-excursion (org-mode) (turn-on-font-lock)))
6798 (narrow-to-region beg end)
6799 (show-all)
6800 (goto-char pos)
6801 (and (window-live-p cwin) (select-window cwin))))
6803 (defun org-get-indirect-buffer (&optional buffer)
6804 (setq buffer (or buffer (current-buffer)))
6805 (let ((n 1) (base (buffer-name buffer)) bname)
6806 (while (buffer-live-p
6807 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6808 (setq n (1+ n)))
6809 (condition-case nil
6810 (make-indirect-buffer buffer bname 'clone)
6811 (error (make-indirect-buffer buffer bname)))))
6813 (defun org-set-frame-title (title)
6814 "Set the title of the current frame to the string TITLE."
6815 ;; FIXME: how to name a single frame in XEmacs???
6816 (unless (featurep 'xemacs)
6817 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6819 ;;;; Structure editing
6821 ;;; Inserting headlines
6823 (defun org-previous-line-empty-p ()
6824 (save-excursion
6825 (and (not (bobp))
6826 (or (beginning-of-line 0) t)
6827 (save-match-data
6828 (looking-at "[ \t]*$")))))
6830 (defun org-insert-heading (&optional force-heading invisible-ok)
6831 "Insert a new heading or item with same depth at point.
6832 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6833 If point is at the beginning of a headline, insert a sibling before the
6834 current headline. If point is not at the beginning, split the line,
6835 create the new headline with the text in the current line after point
6836 \(but see also the variable `org-M-RET-may-split-line').
6838 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6839 This is important for non-interactive uses of the command."
6840 (interactive "P")
6841 (if (or (= (buffer-size) 0)
6842 (and (not (save-excursion
6843 (and (ignore-errors (org-back-to-heading invisible-ok))
6844 (org-on-heading-p))))
6845 (not (org-in-item-p))))
6846 (progn
6847 (insert "\n* ")
6848 (run-hooks 'org-insert-heading-hook))
6849 (when (or force-heading (not (org-insert-item)))
6850 (let* ((empty-line-p nil)
6851 (level nil)
6852 (on-heading (org-on-heading-p))
6853 (head (save-excursion
6854 (condition-case nil
6855 (progn
6856 (org-back-to-heading invisible-ok)
6857 (when (and (not on-heading)
6858 (featurep 'org-inlinetask)
6859 (integerp org-inlinetask-min-level)
6860 (>= (length (match-string 0))
6861 org-inlinetask-min-level))
6862 ;; Find a heading level before the inline task
6863 (while (and (setq level (org-up-heading-safe))
6864 (>= level org-inlinetask-min-level)))
6865 (if (org-on-heading-p)
6866 (org-back-to-heading invisible-ok)
6867 (error "This should not happen")))
6868 (setq empty-line-p (org-previous-line-empty-p))
6869 (match-string 0))
6870 (error "*"))))
6871 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6872 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6873 pos hide-previous previous-pos)
6874 (cond
6875 ((and (org-on-heading-p) (bolp)
6876 (or (bobp)
6877 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6878 ;; insert before the current line
6879 (open-line (if blank 2 1)))
6880 ((and (bolp)
6881 (not org-insert-heading-respect-content)
6882 (or (bobp)
6883 (save-excursion
6884 (backward-char 1) (not (outline-invisible-p)))))
6885 ;; insert right here
6886 nil)
6888 ;; somewhere in the line
6889 (save-excursion
6890 (setq previous-pos (point-at-bol))
6891 (end-of-line)
6892 (setq hide-previous (outline-invisible-p)))
6893 (and org-insert-heading-respect-content (org-show-subtree))
6894 (let ((split
6895 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6896 (save-excursion
6897 (let ((p (point)))
6898 (goto-char (point-at-bol))
6899 (and (looking-at org-complex-heading-regexp)
6900 (> p (match-beginning 4)))))))
6901 tags pos)
6902 (cond
6903 (org-insert-heading-respect-content
6904 (org-end-of-subtree nil t)
6905 (when (featurep 'org-inlinetask)
6906 (while (and (not (eobp))
6907 (looking-at "\\(\\*+\\)[ \t]+")
6908 (>= (length (match-string 1))
6909 org-inlinetask-min-level))
6910 (org-end-of-subtree nil t)))
6911 (or (bolp) (newline))
6912 (or (org-previous-line-empty-p)
6913 (and blank (newline)))
6914 (open-line 1))
6915 ((org-on-heading-p)
6916 (when hide-previous
6917 (show-children)
6918 (org-show-entry))
6919 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6920 (setq tags (and (match-end 2) (match-string 2)))
6921 (and (match-end 1)
6922 (delete-region (match-beginning 1) (match-end 1)))
6923 (setq pos (point-at-bol))
6924 (or split (end-of-line 1))
6925 (delete-horizontal-space)
6926 (if (string-match "\\`\\*+\\'"
6927 (buffer-substring (point-at-bol) (point)))
6928 (insert " "))
6929 (newline (if blank 2 1))
6930 (when tags
6931 (save-excursion
6932 (goto-char pos)
6933 (end-of-line 1)
6934 (insert " " tags)
6935 (org-set-tags nil 'align))))
6937 (or split (end-of-line 1))
6938 (newline (if blank 2 1)))))))
6939 (insert head) (just-one-space)
6940 (setq pos (point))
6941 (end-of-line 1)
6942 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6943 (when (and org-insert-heading-respect-content hide-previous)
6944 (save-excursion
6945 (goto-char previous-pos)
6946 (hide-subtree)))
6947 (run-hooks 'org-insert-heading-hook)))))
6949 (defun org-get-heading (&optional no-tags)
6950 "Return the heading of the current entry, without the stars."
6951 (save-excursion
6952 (org-back-to-heading t)
6953 (if (looking-at
6954 (if no-tags
6955 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6956 "\\*+[ \t]+\\([^\r\n]*\\)"))
6957 (match-string 1) "")))
6959 (defun org-heading-components ()
6960 "Return the components of the current heading.
6961 This is a list with the following elements:
6962 - the level as an integer
6963 - the reduced level, different if `org-odd-levels-only' is set.
6964 - the TODO keyword, or nil
6965 - the priority character, like ?A, or nil if no priority is given
6966 - the headline text itself, or the tags string if no headline text
6967 - the tags string, or nil."
6968 (save-excursion
6969 (org-back-to-heading t)
6970 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6971 (list (length (match-string 1))
6972 (org-reduced-level (length (match-string 1)))
6973 (org-match-string-no-properties 2)
6974 (and (match-end 3) (aref (match-string 3) 2))
6975 (org-match-string-no-properties 4)
6976 (org-match-string-no-properties 5)))))
6978 (defun org-get-entry ()
6979 "Get the entry text, after heading, entire subtree."
6980 (save-excursion
6981 (org-back-to-heading t)
6982 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6984 (defun org-insert-heading-after-current ()
6985 "Insert a new heading with same level as current, after current subtree."
6986 (interactive)
6987 (org-back-to-heading)
6988 (org-insert-heading)
6989 (org-move-subtree-down)
6990 (end-of-line 1))
6992 (defun org-insert-heading-respect-content ()
6993 (interactive)
6994 (let ((org-insert-heading-respect-content t))
6995 (org-insert-heading t)))
6997 (defun org-insert-todo-heading-respect-content (&optional force-state)
6998 (interactive "P")
6999 (let ((org-insert-heading-respect-content t))
7000 (org-insert-todo-heading force-state t)))
7002 (defun org-insert-todo-heading (arg &optional force-heading)
7003 "Insert a new heading with the same level and TODO state as current heading.
7004 If the heading has no TODO state, or if the state is DONE, use the first
7005 state (TODO by default). Also with prefix arg, force first state."
7006 (interactive "P")
7007 (when (or force-heading (not (org-insert-item 'checkbox)))
7008 (org-insert-heading force-heading)
7009 (save-excursion
7010 (org-back-to-heading)
7011 (outline-previous-heading)
7012 (looking-at org-todo-line-regexp))
7013 (let*
7014 ((new-mark-x
7015 (if (or arg
7016 (not (match-beginning 2))
7017 (member (match-string 2) org-done-keywords))
7018 (car org-todo-keywords-1)
7019 (match-string 2)))
7020 (new-mark
7022 (run-hook-with-args-until-success
7023 'org-todo-get-default-hook new-mark-x nil)
7024 new-mark-x)))
7025 (beginning-of-line 1)
7026 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7027 (if org-treat-insert-todo-heading-as-state-change
7028 (org-todo new-mark)
7029 (insert new-mark " "))))
7030 (when org-provide-todo-statistics
7031 (org-update-parent-todo-statistics))))
7033 (defun org-insert-subheading (arg)
7034 "Insert a new subheading and demote it.
7035 Works for outline headings and for plain lists alike."
7036 (interactive "P")
7037 (org-insert-heading arg)
7038 (cond
7039 ((org-on-heading-p) (org-do-demote))
7040 ((org-at-item-p) (org-indent-item))))
7042 (defun org-insert-todo-subheading (arg)
7043 "Insert a new subheading with TODO keyword or checkbox and demote it.
7044 Works for outline headings and for plain lists alike."
7045 (interactive "P")
7046 (org-insert-todo-heading arg)
7047 (cond
7048 ((org-on-heading-p) (org-do-demote))
7049 ((org-at-item-p) (org-indent-item))))
7051 ;;; Promotion and Demotion
7053 (defvar org-after-demote-entry-hook nil
7054 "Hook run after an entry has been demoted.
7055 The cursor will be at the beginning of the entry.
7056 When a subtree is being demoted, the hook will be called for each node.")
7058 (defvar org-after-promote-entry-hook nil
7059 "Hook run after an entry has been promoted.
7060 The cursor will be at the beginning of the entry.
7061 When a subtree is being promoted, the hook will be called for each node.")
7063 (defun org-promote-subtree ()
7064 "Promote the entire subtree.
7065 See also `org-promote'."
7066 (interactive)
7067 (save-excursion
7068 (org-with-limited-levels (org-map-tree 'org-promote)))
7069 (org-fix-position-after-promote))
7071 (defun org-demote-subtree ()
7072 "Demote the entire subtree. See `org-demote'.
7073 See also `org-promote'."
7074 (interactive)
7075 (save-excursion
7076 (org-with-limited-levels (org-map-tree 'org-demote)))
7077 (org-fix-position-after-promote))
7080 (defun org-do-promote ()
7081 "Promote the current heading higher up the tree.
7082 If the region is active in `transient-mark-mode', promote all headings
7083 in the region."
7084 (interactive)
7085 (save-excursion
7086 (if (org-region-active-p)
7087 (org-map-region 'org-promote (region-beginning) (region-end))
7088 (org-promote)))
7089 (org-fix-position-after-promote))
7091 (defun org-do-demote ()
7092 "Demote the current heading lower down the tree.
7093 If the region is active in `transient-mark-mode', demote all headings
7094 in the region."
7095 (interactive)
7096 (save-excursion
7097 (if (org-region-active-p)
7098 (org-map-region 'org-demote (region-beginning) (region-end))
7099 (org-demote)))
7100 (org-fix-position-after-promote))
7102 (defun org-fix-position-after-promote ()
7103 "Make sure that after pro/demotion cursor position is right."
7104 (let ((pos (point)))
7105 (when (save-excursion
7106 (beginning-of-line 1)
7107 (looking-at org-todo-line-regexp)
7108 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7109 (cond ((eobp) (insert " "))
7110 ((eolp) (insert " "))
7111 ((equal (char-after) ?\ ) (forward-char 1))))))
7113 (defun org-current-level ()
7114 "Return the level of the current entry, or nil if before the first headline.
7115 The level is the number of stars at the beginning of the headline."
7116 (save-excursion
7117 (org-with-limited-levels
7118 (ignore-errors
7119 (org-back-to-heading t)
7120 (funcall outline-level)))))
7122 (defun org-get-previous-line-level ()
7123 "Return the outline depth of the last headline before the current line.
7124 Returns 0 for the first headline in the buffer, and nil if before the
7125 first headline."
7126 (let ((current-level (org-current-level))
7127 (prev-level (when (> (line-number-at-pos) 1)
7128 (save-excursion
7129 (beginning-of-line 0)
7130 (org-current-level)))))
7131 (cond ((null current-level) nil) ; Before first headline
7132 ((null prev-level) 0) ; At first headline
7133 (prev-level))))
7135 (defun org-reduced-level (l)
7136 "Compute the effective level of a heading.
7137 This takes into account the setting of `org-odd-levels-only'."
7138 (cond
7139 ((zerop l) 0)
7140 (org-odd-levels-only (1+ (floor (/ l 2))))
7141 (t l)))
7143 (defun org-level-increment ()
7144 "Return the number of stars that will be added or removed at a
7145 time to headlines when structure editing, based on the value of
7146 `org-odd-levels-only'."
7147 (if org-odd-levels-only 2 1))
7149 (defun org-get-valid-level (level &optional change)
7150 "Rectify a level change under the influence of `org-odd-levels-only'
7151 LEVEL is a current level, CHANGE is by how much the level should be
7152 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7153 even level numbers will become the next higher odd number."
7154 (if org-odd-levels-only
7155 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7156 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7157 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7158 (max 1 (+ level (or change 0)))))
7160 (if (boundp 'define-obsolete-function-alias)
7161 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7162 (define-obsolete-function-alias 'org-get-legal-level
7163 'org-get-valid-level)
7164 (define-obsolete-function-alias 'org-get-legal-level
7165 'org-get-valid-level "23.1")))
7167 (defun org-promote ()
7168 "Promote the current heading higher up the tree.
7169 If the region is active in `transient-mark-mode', promote all headings
7170 in the region."
7171 (org-back-to-heading t)
7172 (let* ((level (save-match-data (funcall outline-level)))
7173 (after-change-functions (remove 'flyspell-after-change-function
7174 after-change-functions))
7175 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7176 (diff (abs (- level (length up-head) -1))))
7177 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7178 (replace-match up-head nil t)
7179 ;; Fixup tag positioning
7180 (and org-auto-align-tags (org-set-tags nil t))
7181 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7182 (run-hooks 'org-after-promote-entry-hook)))
7184 (defun org-demote ()
7185 "Demote the current heading lower down the tree.
7186 If the region is active in `transient-mark-mode', demote all headings
7187 in the region."
7188 (org-back-to-heading t)
7189 (let* ((level (save-match-data (funcall outline-level)))
7190 (after-change-functions (remove 'flyspell-after-change-function
7191 after-change-functions))
7192 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7193 (diff (abs (- level (length down-head) -1))))
7194 (replace-match down-head nil t)
7195 ;; Fixup tag positioning
7196 (and org-auto-align-tags (org-set-tags nil t))
7197 (if org-adapt-indentation (org-fixup-indentation diff))
7198 (run-hooks 'org-after-demote-entry-hook)))
7200 (defun org-cycle-level ()
7201 "Cycle the level of an empty headline through possible states.
7202 This goes first to child, then to parent, level, then up the hierarchy.
7203 After top level, it switches back to sibling level."
7204 (interactive)
7205 (let ((org-adapt-indentation nil))
7206 (when (org-point-at-end-of-empty-headline)
7207 (setq this-command 'org-cycle-level) ; Only needed for caching
7208 (let ((cur-level (org-current-level))
7209 (prev-level (org-get-previous-line-level)))
7210 (cond
7211 ;; If first headline in file, promote to top-level.
7212 ((= prev-level 0)
7213 (loop repeat (/ (- cur-level 1) (org-level-increment))
7214 do (org-do-promote)))
7215 ;; If same level as prev, demote one.
7216 ((= prev-level cur-level)
7217 (org-do-demote))
7218 ;; If parent is top-level, promote to top level if not already.
7219 ((= prev-level 1)
7220 (loop repeat (/ (- cur-level 1) (org-level-increment))
7221 do (org-do-promote)))
7222 ;; If top-level, return to prev-level.
7223 ((= cur-level 1)
7224 (loop repeat (/ (- prev-level 1) (org-level-increment))
7225 do (org-do-demote)))
7226 ;; If less than prev-level, promote one.
7227 ((< cur-level prev-level)
7228 (org-do-promote))
7229 ;; If deeper than prev-level, promote until higher than
7230 ;; prev-level.
7231 ((> cur-level prev-level)
7232 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7233 do (org-do-promote))))
7234 t))))
7236 (defun org-map-tree (fun)
7237 "Call FUN for every heading underneath the current one."
7238 (org-back-to-heading)
7239 (let ((level (funcall outline-level)))
7240 (save-excursion
7241 (funcall fun)
7242 (while (and (progn
7243 (outline-next-heading)
7244 (> (funcall outline-level) level))
7245 (not (eobp)))
7246 (funcall fun)))))
7248 (defun org-map-region (fun beg end)
7249 "Call FUN for every heading between BEG and END."
7250 (let ((org-ignore-region t))
7251 (save-excursion
7252 (setq end (copy-marker end))
7253 (goto-char beg)
7254 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7255 (< (point) end))
7256 (funcall fun))
7257 (while (and (progn
7258 (outline-next-heading)
7259 (< (point) end))
7260 (not (eobp)))
7261 (funcall fun)))))
7263 (defun org-fixup-indentation (diff)
7264 "Change the indentation in the current entry by DIFF.
7265 However, if any line in the current entry has no indentation, or if it
7266 would end up with no indentation after the change, nothing at all is done."
7267 (save-excursion
7268 (let ((end (save-excursion (outline-next-heading)
7269 (point-marker)))
7270 (prohibit (if (> diff 0)
7271 "^\\S-"
7272 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7273 col)
7274 (unless (save-excursion (end-of-line 1)
7275 (re-search-forward prohibit end t))
7276 (while (and (< (point) end)
7277 (re-search-forward "^[ \t]+" end t))
7278 (goto-char (match-end 0))
7279 (setq col (current-column))
7280 (if (< diff 0) (replace-match ""))
7281 (org-indent-to-column (+ diff col))))
7282 (move-marker end nil))))
7284 (defun org-convert-to-odd-levels ()
7285 "Convert an org-mode file with all levels allowed to one with odd levels.
7286 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7287 level 5 etc."
7288 (interactive)
7289 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7290 (let ((outline-regexp org-outline-regexp)
7291 (outline-level 'org-outline-level)
7292 (org-odd-levels-only nil) n)
7293 (save-excursion
7294 (goto-char (point-min))
7295 (while (re-search-forward "^\\*\\*+ " nil t)
7296 (setq n (- (length (match-string 0)) 2))
7297 (while (>= (setq n (1- n)) 0)
7298 (org-demote))
7299 (end-of-line 1))))))
7301 (defun org-convert-to-oddeven-levels ()
7302 "Convert an org-mode file with only odd levels to one with odd/even levels.
7303 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7304 file contains a section with an even level, conversion would
7305 destroy the structure of the file. An error is signaled in this
7306 case."
7307 (interactive)
7308 (goto-char (point-min))
7309 ;; First check if there are no even levels
7310 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7311 (org-show-context t)
7312 (error "Not all levels are odd in this file. Conversion not possible"))
7313 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7314 (let ((outline-regexp org-outline-regexp)
7315 (outline-level 'org-outline-level)
7316 (org-odd-levels-only nil) n)
7317 (save-excursion
7318 (goto-char (point-min))
7319 (while (re-search-forward "^\\*\\*+ " nil t)
7320 (setq n (/ (1- (length (match-string 0))) 2))
7321 (while (>= (setq n (1- n)) 0)
7322 (org-promote))
7323 (end-of-line 1))))))
7325 (defun org-tr-level (n)
7326 "Make N odd if required."
7327 (if org-odd-levels-only (1+ (/ n 2)) n))
7329 ;;; Vertical tree motion, cutting and pasting of subtrees
7331 (defun org-move-subtree-up (&optional arg)
7332 "Move the current subtree up past ARG headlines of the same level."
7333 (interactive "p")
7334 (org-move-subtree-down (- (prefix-numeric-value arg))))
7336 (defun org-move-subtree-down (&optional arg)
7337 "Move the current subtree down past ARG headlines of the same level."
7338 (interactive "p")
7339 (setq arg (prefix-numeric-value arg))
7340 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7341 'org-get-last-sibling))
7342 (ins-point (make-marker))
7343 (cnt (abs arg))
7344 (col (current-column))
7345 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7346 ;; Select the tree
7347 (org-back-to-heading)
7348 (setq beg0 (point))
7349 (save-excursion
7350 (setq ne-beg (org-back-over-empty-lines))
7351 (setq beg (point)))
7352 (save-match-data
7353 (save-excursion (outline-end-of-heading)
7354 (setq folded (outline-invisible-p)))
7355 (outline-end-of-subtree))
7356 (outline-next-heading)
7357 (setq ne-end (org-back-over-empty-lines))
7358 (setq end (point))
7359 (goto-char beg0)
7360 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7361 ;; include less whitespace
7362 (save-excursion
7363 (goto-char beg)
7364 (forward-line (- ne-beg ne-end))
7365 (setq beg (point))))
7366 ;; Find insertion point, with error handling
7367 (while (> cnt 0)
7368 (or (and (funcall movfunc) (looking-at outline-regexp))
7369 (progn (goto-char beg0)
7370 (error "Cannot move past superior level or buffer limit")))
7371 (setq cnt (1- cnt)))
7372 (if (> arg 0)
7373 ;; Moving forward - still need to move over subtree
7374 (progn (org-end-of-subtree t t)
7375 (save-excursion
7376 (org-back-over-empty-lines)
7377 (or (bolp) (newline)))))
7378 (setq ne-ins (org-back-over-empty-lines))
7379 (move-marker ins-point (point))
7380 (setq txt (buffer-substring beg end))
7381 (org-save-markers-in-region beg end)
7382 (delete-region beg end)
7383 (org-remove-empty-overlays-at beg)
7384 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7385 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7386 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7387 (let ((bbb (point)))
7388 (insert-before-markers txt)
7389 (org-reinstall-markers-in-region bbb)
7390 (move-marker ins-point bbb))
7391 (or (bolp) (insert "\n"))
7392 (setq ins-end (point))
7393 (goto-char ins-point)
7394 (org-skip-whitespace)
7395 (when (and (< arg 0)
7396 (org-first-sibling-p)
7397 (> ne-ins ne-beg))
7398 ;; Move whitespace back to beginning
7399 (save-excursion
7400 (goto-char ins-end)
7401 (let ((kill-whole-line t))
7402 (kill-line (- ne-ins ne-beg)) (point)))
7403 (insert (make-string (- ne-ins ne-beg) ?\n)))
7404 (move-marker ins-point nil)
7405 (if folded
7406 (hide-subtree)
7407 (org-show-entry)
7408 (show-children)
7409 (org-cycle-hide-drawers 'children))
7410 (org-clean-visibility-after-subtree-move)
7411 ;; move back to the initial column we were at
7412 (move-to-column col)))
7414 (defvar org-subtree-clip ""
7415 "Clipboard for cut and paste of subtrees.
7416 This is actually only a copy of the kill, because we use the normal kill
7417 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7419 (defvar org-subtree-clip-folded nil
7420 "Was the last copied subtree folded?
7421 This is used to fold the tree back after pasting.")
7423 (defun org-cut-subtree (&optional n)
7424 "Cut the current subtree into the clipboard.
7425 With prefix arg N, cut this many sequential subtrees.
7426 This is a short-hand for marking the subtree and then cutting it."
7427 (interactive "p")
7428 (org-copy-subtree n 'cut))
7430 (defun org-copy-subtree (&optional n cut force-store-markers)
7431 "Cut the current subtree into the clipboard.
7432 With prefix arg N, cut this many sequential subtrees.
7433 This is a short-hand for marking the subtree and then copying it.
7434 If CUT is non-nil, actually cut the subtree.
7435 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7436 of some markers in the region, even if CUT is non-nil. This is
7437 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7438 (interactive "p")
7439 (let (beg end folded (beg0 (point)))
7440 (if (org-called-interactively-p 'any)
7441 (org-back-to-heading nil) ; take what looks like a subtree
7442 (org-back-to-heading t)) ; take what is really there
7443 (org-back-over-empty-lines)
7444 (setq beg (point))
7445 (skip-chars-forward " \t\r\n")
7446 (save-match-data
7447 (save-excursion (outline-end-of-heading)
7448 (setq folded (outline-invisible-p)))
7449 (condition-case nil
7450 (org-forward-same-level (1- n) t)
7451 (error nil))
7452 (org-end-of-subtree t t))
7453 (org-back-over-empty-lines)
7454 (setq end (point))
7455 (goto-char beg0)
7456 (when (> end beg)
7457 (setq org-subtree-clip-folded folded)
7458 (when (or cut force-store-markers)
7459 (org-save-markers-in-region beg end))
7460 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7461 (setq org-subtree-clip (current-kill 0))
7462 (message "%s: Subtree(s) with %d characters"
7463 (if cut "Cut" "Copied")
7464 (length org-subtree-clip)))))
7466 (defun org-paste-subtree (&optional level tree for-yank)
7467 "Paste the clipboard as a subtree, with modification of headline level.
7468 The entire subtree is promoted or demoted in order to match a new headline
7469 level.
7471 If the cursor is at the beginning of a headline, the same level as
7472 that headline is used to paste the tree
7474 If not, the new level is derived from the *visible* headings
7475 before and after the insertion point, and taken to be the inferior headline
7476 level of the two. So if the previous visible heading is level 3 and the
7477 next is level 4 (or vice versa), level 4 will be used for insertion.
7478 This makes sure that the subtree remains an independent subtree and does
7479 not swallow low level entries.
7481 You can also force a different level, either by using a numeric prefix
7482 argument, or by inserting the heading marker by hand. For example, if the
7483 cursor is after \"*****\", then the tree will be shifted to level 5.
7485 If optional TREE is given, use this text instead of the kill ring.
7487 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7488 move back over whitespace before inserting, and move point to the end of
7489 the inserted text when done."
7490 (interactive "P")
7491 (setq tree (or tree (and kill-ring (current-kill 0))))
7492 (unless (org-kill-is-subtree-p tree)
7493 (error "%s"
7494 (substitute-command-keys
7495 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7496 (let* ((visp (not (outline-invisible-p)))
7497 (txt tree)
7498 (^re (concat "^\\(" outline-regexp "\\)"))
7499 (re (concat "\\(" outline-regexp "\\)"))
7500 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7502 (old-level (if (string-match ^re txt)
7503 (- (match-end 0) (match-beginning 0) 1)
7504 -1))
7505 (force-level (cond (level (prefix-numeric-value level))
7506 ((and (looking-at "[ \t]*$")
7507 (string-match
7508 ^re_ (buffer-substring
7509 (point-at-bol) (point))))
7510 (- (match-end 1) (match-beginning 1)))
7511 ((and (bolp)
7512 (looking-at org-outline-regexp))
7513 (- (match-end 0) (point) 1))
7514 (t nil)))
7515 (previous-level (save-excursion
7516 (condition-case nil
7517 (progn
7518 (outline-previous-visible-heading 1)
7519 (if (looking-at re)
7520 (- (match-end 0) (match-beginning 0) 1)
7522 (error 1))))
7523 (next-level (save-excursion
7524 (condition-case nil
7525 (progn
7526 (or (looking-at outline-regexp)
7527 (outline-next-visible-heading 1))
7528 (if (looking-at re)
7529 (- (match-end 0) (match-beginning 0) 1)
7531 (error 1))))
7532 (new-level (or force-level (max previous-level next-level)))
7533 (shift (if (or (= old-level -1)
7534 (= new-level -1)
7535 (= old-level new-level))
7537 (- new-level old-level)))
7538 (delta (if (> shift 0) -1 1))
7539 (func (if (> shift 0) 'org-demote 'org-promote))
7540 (org-odd-levels-only nil)
7541 beg end newend)
7542 ;; Remove the forced level indicator
7543 (if force-level
7544 (delete-region (point-at-bol) (point)))
7545 ;; Paste
7546 (beginning-of-line 1)
7547 (unless for-yank (org-back-over-empty-lines))
7548 (setq beg (point))
7549 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7550 (insert-before-markers txt)
7551 (unless (string-match "\n\\'" txt) (insert "\n"))
7552 (setq newend (point))
7553 (org-reinstall-markers-in-region beg)
7554 (setq end (point))
7555 (goto-char beg)
7556 (skip-chars-forward " \t\n\r")
7557 (setq beg (point))
7558 (if (and (outline-invisible-p) visp)
7559 (save-excursion (outline-show-heading)))
7560 ;; Shift if necessary
7561 (unless (= shift 0)
7562 (save-restriction
7563 (narrow-to-region beg end)
7564 (while (not (= shift 0))
7565 (org-map-region func (point-min) (point-max))
7566 (setq shift (+ delta shift)))
7567 (goto-char (point-min))
7568 (setq newend (point-max))))
7569 (when (or (org-called-interactively-p 'interactive) for-yank)
7570 (message "Clipboard pasted as level %d subtree" new-level))
7571 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7572 kill-ring
7573 (eq org-subtree-clip (current-kill 0))
7574 org-subtree-clip-folded)
7575 ;; The tree was folded before it was killed/copied
7576 (hide-subtree))
7577 (and for-yank (goto-char newend))))
7579 (defun org-kill-is-subtree-p (&optional txt)
7580 "Check if the current kill is an outline subtree, or a set of trees.
7581 Returns nil if kill does not start with a headline, or if the first
7582 headline level is not the largest headline level in the tree.
7583 So this will actually accept several entries of equal levels as well,
7584 which is OK for `org-paste-subtree'.
7585 If optional TXT is given, check this string instead of the current kill."
7586 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7587 (start-level (and kill
7588 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7589 org-outline-regexp "\\)")
7590 kill)
7591 (- (match-end 2) (match-beginning 2) 1)))
7592 (re (concat "^" org-outline-regexp))
7593 (start (1+ (or (match-beginning 2) -1))))
7594 (if (not start-level)
7595 (progn
7596 nil) ;; does not even start with a heading
7597 (catch 'exit
7598 (while (setq start (string-match re kill (1+ start)))
7599 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7600 (throw 'exit nil)))
7601 t))))
7603 (defvar org-markers-to-move nil
7604 "Markers that should be moved with a cut-and-paste operation.
7605 Those markers are stored together with their positions relative to
7606 the start of the region.")
7608 (defun org-save-markers-in-region (beg end)
7609 "Check markers in region.
7610 If these markers are between BEG and END, record their position relative
7611 to BEG, so that after moving the block of text, we can put the markers back
7612 into place.
7613 This function gets called just before an entry or tree gets cut from the
7614 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7615 called immediately, to move the markers with the entries."
7616 (setq org-markers-to-move nil)
7617 (when (featurep 'org-clock)
7618 (org-clock-save-markers-for-cut-and-paste beg end))
7619 (when (featurep 'org-agenda)
7620 (org-agenda-save-markers-for-cut-and-paste beg end)))
7622 (defun org-check-and-save-marker (marker beg end)
7623 "Check if MARKER is between BEG and END.
7624 If yes, remember the marker and the distance to BEG."
7625 (when (and (marker-buffer marker)
7626 (equal (marker-buffer marker) (current-buffer)))
7627 (if (and (>= marker beg) (< marker end))
7628 (push (cons marker (- marker beg)) org-markers-to-move))))
7630 (defun org-reinstall-markers-in-region (beg)
7631 "Move all remembered markers to their position relative to BEG."
7632 (mapc (lambda (x)
7633 (move-marker (car x) (+ beg (cdr x))))
7634 org-markers-to-move)
7635 (setq org-markers-to-move nil))
7637 (defun org-narrow-to-subtree ()
7638 "Narrow buffer to the current subtree."
7639 (interactive)
7640 (save-excursion
7641 (save-match-data
7642 (org-with-limited-levels
7643 (narrow-to-region
7644 (progn (org-back-to-heading t) (point))
7645 (progn (org-end-of-subtree t t)
7646 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7647 (point)))))))
7649 (defun org-narrow-to-block ()
7650 "Narrow buffer to the current block."
7651 (interactive)
7652 (let ((bstart "^[ \t]*#\\+begin")
7653 (bend "[ \t]*#\\+end")
7654 (case-fold-search t) ;; allow #+BEGIN
7655 b_start b_end)
7656 (if (org-in-regexps-block-p bstart bend)
7657 (progn
7658 (save-excursion (re-search-backward bstart nil t)
7659 (setq b_start (match-beginning 0)))
7660 (save-excursion (re-search-forward bend nil t)
7661 (setq b_end (match-end 0)))
7662 (narrow-to-region b_start b_end))
7663 (error "Not in a block"))))
7665 (eval-when-compile
7666 (defvar org-property-drawer-re))
7668 (defvar org-property-start-re) ;; defined below
7669 (defun org-clone-subtree-with-time-shift (n &optional shift)
7670 "Clone the task (subtree) at point N times.
7671 The clones will be inserted as siblings.
7673 In interactive use, the user will be prompted for the number of
7674 clones to be produced, and for a time SHIFT, which may be a
7675 repeater as used in time stamps, for example `+3d'.
7677 When a valid repeater is given and the entry contains any time
7678 stamps, the clones will become a sequence in time, with time
7679 stamps in the subtree shifted for each clone produced. If SHIFT
7680 is nil or the empty string, time stamps will be left alone. The
7681 ID property of the original subtree is removed.
7683 If the original subtree did contain time stamps with a repeater,
7684 the following will happen:
7685 - the repeater will be removed in each clone
7686 - an additional clone will be produced, with the current, unshifted
7687 date(s) in the entry.
7688 - the original entry will be placed *after* all the clones, with
7689 repeater intact.
7690 - the start days in the repeater in the original entry will be shifted
7691 to past the last clone.
7692 I this way you can spell out a number of instances of a repeating task,
7693 and still retain the repeater to cover future instances of the task."
7694 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7695 (let (beg end template task idprop
7696 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7697 (if (not (and (integerp n) (> n 0)))
7698 (error "Invalid number of replications %s" n))
7699 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7700 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7701 shift)))
7702 (error "Invalid shift specification %s" shift))
7703 (when doshift
7704 (setq shift-n (string-to-number (match-string 1 shift))
7705 shift-what (cdr (assoc (match-string 2 shift)
7706 '(("d" . day) ("w" . week)
7707 ("m" . month) ("y" . year))))))
7708 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7709 (setq nmin 1 nmax n)
7710 (org-back-to-heading t)
7711 (setq beg (point))
7712 (setq idprop (org-entry-get nil "ID"))
7713 (org-end-of-subtree t t)
7714 (or (bolp) (insert "\n"))
7715 (setq end (point))
7716 (setq template (buffer-substring beg end))
7717 (when (and doshift
7718 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7719 (delete-region beg end)
7720 (setq end beg)
7721 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7722 (goto-char end)
7723 (loop for n from nmin to nmax do
7724 ;; prepare clone
7725 (with-temp-buffer
7726 (insert template)
7727 (org-mode)
7728 (goto-char (point-min))
7729 (and idprop (if org-clone-delete-id
7730 (org-entry-delete nil "ID")
7731 (org-id-get-create t)))
7732 (while (re-search-forward org-property-start-re nil t)
7733 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7734 (goto-char (point-min))
7735 (when doshift
7736 (while (re-search-forward org-ts-regexp-both nil t)
7737 (org-timestamp-change (* n shift-n) shift-what))
7738 (unless (= n n-no-remove)
7739 (goto-char (point-min))
7740 (while (re-search-forward org-ts-regexp nil t)
7741 (save-excursion
7742 (goto-char (match-beginning 0))
7743 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7744 (delete-region (match-beginning 1) (match-end 1)))))))
7745 (setq task (buffer-string)))
7746 (insert task))
7747 (goto-char beg)))
7749 ;;; Outline Sorting
7751 (defun org-sort (with-case)
7752 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7753 Optional argument WITH-CASE means sort case-sensitively.
7754 With a double prefix argument, also remove duplicate entries."
7755 (interactive "P")
7756 (cond
7757 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7758 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7760 (org-call-with-arg 'org-sort-entries with-case))))
7762 (defun org-sort-remove-invisible (s)
7763 (remove-text-properties 0 (length s) org-rm-props s)
7764 (while (string-match org-bracket-link-regexp s)
7765 (setq s (replace-match (if (match-end 2)
7766 (match-string 3 s)
7767 (match-string 1 s)) t t s)))
7770 (defvar org-priority-regexp) ; defined later in the file
7772 (defvar org-after-sorting-entries-or-items-hook nil
7773 "Hook that is run after a bunch of entries or items have been sorted.
7774 When children are sorted, the cursor is in the parent line when this
7775 hook gets called. When a region or a plain list is sorted, the cursor
7776 will be in the first entry of the sorted region/list.")
7778 (defun org-sort-entries
7779 (&optional with-case sorting-type getkey-func compare-func property)
7780 "Sort entries on a certain level of an outline tree.
7781 If there is an active region, the entries in the region are sorted.
7782 Else, if the cursor is before the first entry, sort the top-level items.
7783 Else, the children of the entry at point are sorted.
7785 Sorting can be alphabetically, numerically, by date/time as given by
7786 a time stamp, by a property or by priority.
7788 The command prompts for the sorting type unless it has been given to the
7789 function through the SORTING-TYPE argument, which needs to be a character,
7790 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7791 precise meaning of each character:
7793 n Numerically, by converting the beginning of the entry/item to a number.
7794 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7795 t By date/time, either the first active time stamp in the entry, or, if
7796 none exist, by the first inactive one.
7797 s By the scheduled date/time.
7798 d By deadline date/time.
7799 c By creation time, which is assumed to be the first inactive time stamp
7800 at the beginning of a line.
7801 p By priority according to the cookie.
7802 r By the value of a property.
7804 Capital letters will reverse the sort order.
7806 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7807 called with point at the beginning of the record. It must return either
7808 a string or a number that should serve as the sorting key for that record.
7810 Comparing entries ignores case by default. However, with an optional argument
7811 WITH-CASE, the sorting considers case as well."
7812 (interactive "P")
7813 (let ((case-func (if with-case 'identity 'downcase))
7814 start beg end stars re re2
7815 txt what tmp)
7816 ;; Find beginning and end of region to sort
7817 (cond
7818 ((org-region-active-p)
7819 ;; we will sort the region
7820 (setq end (region-end)
7821 what "region")
7822 (goto-char (region-beginning))
7823 (if (not (org-on-heading-p)) (outline-next-heading))
7824 (setq start (point)))
7825 ((or (org-on-heading-p)
7826 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7827 ;; we will sort the children of the current headline
7828 (org-back-to-heading)
7829 (setq start (point)
7830 end (progn (org-end-of-subtree t t)
7831 (or (bolp) (insert "\n"))
7832 (org-back-over-empty-lines)
7833 (point))
7834 what "children")
7835 (goto-char start)
7836 (show-subtree)
7837 (outline-next-heading))
7839 ;; we will sort the top-level entries in this file
7840 (goto-char (point-min))
7841 (or (org-on-heading-p) (outline-next-heading))
7842 (setq start (point))
7843 (goto-char (point-max))
7844 (beginning-of-line 1)
7845 (when (looking-at ".*?\\S-")
7846 ;; File ends in a non-white line
7847 (end-of-line 1)
7848 (insert "\n"))
7849 (setq end (point-max))
7850 (setq what "top-level")
7851 (goto-char start)
7852 (show-all)))
7854 (setq beg (point))
7855 (if (>= beg end) (error "Nothing to sort"))
7857 (looking-at "\\(\\*+\\)")
7858 (setq stars (match-string 1)
7859 re (concat "^" (regexp-quote stars) " +")
7860 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7861 txt (buffer-substring beg end))
7862 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7863 (if (and (not (equal stars "*")) (string-match re2 txt))
7864 (error "Region to sort contains a level above the first entry"))
7866 (unless sorting-type
7867 (message
7868 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7869 [t]ime [s]cheduled [d]eadline [c]reated
7870 A/N/T/S/D/C/P/O/F means reversed:"
7871 what)
7872 (setq sorting-type (read-char-exclusive))
7874 (and (= (downcase sorting-type) ?f)
7875 (setq getkey-func
7876 (org-icompleting-read "Sort using function: "
7877 obarray 'fboundp t nil nil))
7878 (setq getkey-func (intern getkey-func)))
7880 (and (= (downcase sorting-type) ?r)
7881 (setq property
7882 (org-icompleting-read "Property: "
7883 (mapcar 'list (org-buffer-property-keys t))
7884 nil t))))
7886 (message "Sorting entries...")
7888 (save-restriction
7889 (narrow-to-region start end)
7890 (let ((dcst (downcase sorting-type))
7891 (case-fold-search nil)
7892 (now (current-time)))
7893 (sort-subr
7894 (/= dcst sorting-type)
7895 ;; This function moves to the beginning character of the "record" to
7896 ;; be sorted.
7897 (lambda nil
7898 (if (re-search-forward re nil t)
7899 (goto-char (match-beginning 0))
7900 (goto-char (point-max))))
7901 ;; This function moves to the last character of the "record" being
7902 ;; sorted.
7903 (lambda nil
7904 (save-match-data
7905 (condition-case nil
7906 (outline-forward-same-level 1)
7907 (error
7908 (goto-char (point-max))))))
7909 ;; This function returns the value that gets sorted against.
7910 (lambda nil
7911 (cond
7912 ((= dcst ?n)
7913 (if (looking-at org-complex-heading-regexp)
7914 (string-to-number (match-string 4))
7915 nil))
7916 ((= dcst ?a)
7917 (if (looking-at org-complex-heading-regexp)
7918 (funcall case-func (match-string 4))
7919 nil))
7920 ((= dcst ?t)
7921 (let ((end (save-excursion (outline-next-heading) (point))))
7922 (if (or (re-search-forward org-ts-regexp end t)
7923 (re-search-forward org-ts-regexp-both end t))
7924 (org-time-string-to-seconds (match-string 0))
7925 (org-float-time now))))
7926 ((= dcst ?c)
7927 (let ((end (save-excursion (outline-next-heading) (point))))
7928 (if (re-search-forward
7929 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7930 end t)
7931 (org-time-string-to-seconds (match-string 0))
7932 (org-float-time now))))
7933 ((= dcst ?s)
7934 (let ((end (save-excursion (outline-next-heading) (point))))
7935 (if (re-search-forward org-scheduled-time-regexp end t)
7936 (org-time-string-to-seconds (match-string 1))
7937 (org-float-time now))))
7938 ((= dcst ?d)
7939 (let ((end (save-excursion (outline-next-heading) (point))))
7940 (if (re-search-forward org-deadline-time-regexp end t)
7941 (org-time-string-to-seconds (match-string 1))
7942 (org-float-time now))))
7943 ((= dcst ?p)
7944 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7945 (string-to-char (match-string 2))
7946 org-default-priority))
7947 ((= dcst ?r)
7948 (or (org-entry-get nil property) ""))
7949 ((= dcst ?o)
7950 (if (looking-at org-complex-heading-regexp)
7951 (- 9999 (length (member (match-string 2)
7952 org-todo-keywords-1)))))
7953 ((= dcst ?f)
7954 (if getkey-func
7955 (progn
7956 (setq tmp (funcall getkey-func))
7957 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7958 tmp)
7959 (error "Invalid key function `%s'" getkey-func)))
7960 (t (error "Invalid sorting type `%c'" sorting-type))))
7962 (cond
7963 ((= dcst ?a) 'string<)
7964 ((= dcst ?f) compare-func)
7965 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7966 (t nil)))))
7967 (run-hooks 'org-after-sorting-entries-or-items-hook)
7968 (message "Sorting entries...done")))
7970 (defun org-do-sort (table what &optional with-case sorting-type)
7971 "Sort TABLE of WHAT according to SORTING-TYPE.
7972 The user will be prompted for the SORTING-TYPE if the call to this
7973 function does not specify it. WHAT is only for the prompt, to indicate
7974 what is being sorted. The sorting key will be extracted from
7975 the car of the elements of the table.
7976 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7977 (unless sorting-type
7978 (message
7979 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7980 what)
7981 (setq sorting-type (read-char-exclusive)))
7982 (let ((dcst (downcase sorting-type))
7983 extractfun comparefun)
7984 ;; Define the appropriate functions
7985 (cond
7986 ((= dcst ?n)
7987 (setq extractfun 'string-to-number
7988 comparefun (if (= dcst sorting-type) '< '>)))
7989 ((= dcst ?a)
7990 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7991 (lambda(x) (downcase (org-sort-remove-invisible x))))
7992 comparefun (if (= dcst sorting-type)
7993 'string<
7994 (lambda (a b) (and (not (string< a b))
7995 (not (string= a b)))))))
7996 ((= dcst ?t)
7997 (setq extractfun
7998 (lambda (x)
7999 (if (or (string-match org-ts-regexp x)
8000 (string-match org-ts-regexp-both x))
8001 (org-float-time
8002 (org-time-string-to-time (match-string 0 x)))
8004 comparefun (if (= dcst sorting-type) '< '>)))
8005 (t (error "Invalid sorting type `%c'" sorting-type)))
8007 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8008 table)
8009 (lambda (a b) (funcall comparefun (car a) (car b))))))
8012 ;;; The orgstruct minor mode
8014 ;; Define a minor mode which can be used in other modes in order to
8015 ;; integrate the org-mode structure editing commands.
8017 ;; This is really a hack, because the org-mode structure commands use
8018 ;; keys which normally belong to the major mode. Here is how it
8019 ;; works: The minor mode defines all the keys necessary to operate the
8020 ;; structure commands, but wraps the commands into a function which
8021 ;; tests if the cursor is currently at a headline or a plain list
8022 ;; item. If that is the case, the structure command is used,
8023 ;; temporarily setting many Org-mode variables like regular
8024 ;; expressions for filling etc. However, when any of those keys is
8025 ;; used at a different location, function uses `key-binding' to look
8026 ;; up if the key has an associated command in another currently active
8027 ;; keymap (minor modes, major mode, global), and executes that
8028 ;; command. There might be problems if any of the keys is otherwise
8029 ;; used as a prefix key.
8031 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8032 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8033 ;; addresses this by checking explicitly for both bindings.
8035 (defvar orgstruct-mode-map (make-sparse-keymap)
8036 "Keymap for the minor `orgstruct-mode'.")
8038 (defvar org-local-vars nil
8039 "List of local variables, for use by `orgstruct-mode'.")
8041 ;;;###autoload
8042 (define-minor-mode orgstruct-mode
8043 "Toggle the minor mode `orgstruct-mode'.
8044 This mode is for using Org-mode structure commands in other
8045 modes. The following keys behave as if Org-mode were active, if
8046 the cursor is on a headline, or on a plain list item (both as
8047 defined by Org-mode).
8049 M-up Move entry/item up
8050 M-down Move entry/item down
8051 M-left Promote
8052 M-right Demote
8053 M-S-up Move entry/item up
8054 M-S-down Move entry/item down
8055 M-S-left Promote subtree
8056 M-S-right Demote subtree
8057 M-q Fill paragraph and items like in Org-mode
8058 C-c ^ Sort entries
8059 C-c - Cycle list bullet
8060 TAB Cycle item visibility
8061 M-RET Insert new heading/item
8062 S-M-RET Insert new TODO heading / Checkbox item
8063 C-c C-c Set tags / toggle checkbox"
8064 nil " OrgStruct" nil
8065 (org-load-modules-maybe)
8066 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8068 ;;;###autoload
8069 (defun turn-on-orgstruct ()
8070 "Unconditionally turn on `orgstruct-mode'."
8071 (orgstruct-mode 1))
8073 (defun orgstruct++-mode (&optional arg)
8074 "Toggle `orgstruct-mode', the enhanced version of it.
8075 In addition to setting orgstruct-mode, this also exports all indentation
8076 and autofilling variables from org-mode into the buffer. It will also
8077 recognize item context in multiline items.
8078 Note that turning off orgstruct-mode will *not* remove the
8079 indentation/paragraph settings. This can only be done by refreshing the
8080 major mode, for example with \\[normal-mode]."
8081 (interactive "P")
8082 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8083 (if (< arg 1)
8084 (orgstruct-mode -1)
8085 (orgstruct-mode 1)
8086 (let (var val)
8087 (mapc
8088 (lambda (x)
8089 (when (string-match
8090 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8091 (symbol-name (car x)))
8092 (setq var (car x) val (nth 1 x))
8093 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8094 org-local-vars)
8095 (org-set-local 'orgstruct-is-++ t))))
8097 (defvar orgstruct-is-++ nil
8098 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8099 (make-variable-buffer-local 'orgstruct-is-++)
8101 ;;;###autoload
8102 (defun turn-on-orgstruct++ ()
8103 "Unconditionally turn on `orgstruct++-mode'."
8104 (orgstruct++-mode 1))
8106 (defun orgstruct-error ()
8107 "Error when there is no default binding for a structure key."
8108 (interactive)
8109 (error "This key has no function outside structure elements"))
8111 (defun orgstruct-setup ()
8112 "Setup orgstruct keymaps."
8113 (let ((nfunc 0)
8114 (bindings
8115 (list
8116 '([(meta up)] org-metaup)
8117 '([(meta down)] org-metadown)
8118 '([(meta left)] org-metaleft)
8119 '([(meta right)] org-metaright)
8120 '([(meta shift up)] org-shiftmetaup)
8121 '([(meta shift down)] org-shiftmetadown)
8122 '([(meta shift left)] org-shiftmetaleft)
8123 '([(meta shift right)] org-shiftmetaright)
8124 '([?\e (up)] org-metaup)
8125 '([?\e (down)] org-metadown)
8126 '([?\e (left)] org-metaleft)
8127 '([?\e (right)] org-metaright)
8128 '([?\e (shift up)] org-shiftmetaup)
8129 '([?\e (shift down)] org-shiftmetadown)
8130 '([?\e (shift left)] org-shiftmetaleft)
8131 '([?\e (shift right)] org-shiftmetaright)
8132 '([(shift up)] org-shiftup)
8133 '([(shift down)] org-shiftdown)
8134 '([(shift left)] org-shiftleft)
8135 '([(shift right)] org-shiftright)
8136 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8137 '("\M-q" fill-paragraph)
8138 '("\C-c^" org-sort)
8139 '("\C-c-" org-cycle-list-bullet)))
8140 elt key fun cmd)
8141 (while (setq elt (pop bindings))
8142 (setq nfunc (1+ nfunc))
8143 (setq key (org-key (car elt))
8144 fun (nth 1 elt)
8145 cmd (orgstruct-make-binding fun nfunc key))
8146 (org-defkey orgstruct-mode-map key cmd))
8148 ;; Special treatment needed for TAB and RET
8149 (org-defkey orgstruct-mode-map [(tab)]
8150 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8151 (org-defkey orgstruct-mode-map "\C-i"
8152 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8154 (org-defkey orgstruct-mode-map "\M-\C-m"
8155 (orgstruct-make-binding 'org-insert-heading 105
8156 "\M-\C-m" [(meta return)]))
8157 (org-defkey orgstruct-mode-map [(meta return)]
8158 (orgstruct-make-binding 'org-insert-heading 106
8159 [(meta return)] "\M-\C-m"))
8161 (org-defkey orgstruct-mode-map [(shift meta return)]
8162 (orgstruct-make-binding 'org-insert-todo-heading 107
8163 [(meta return)] "\M-\C-m"))
8165 (org-defkey orgstruct-mode-map "\e\C-m"
8166 (orgstruct-make-binding 'org-insert-heading 108
8167 "\e\C-m" [?\e (return)]))
8168 (org-defkey orgstruct-mode-map [?\e (return)]
8169 (orgstruct-make-binding 'org-insert-heading 109
8170 [?\e (return)] "\e\C-m"))
8171 (org-defkey orgstruct-mode-map [?\e (shift return)]
8172 (orgstruct-make-binding 'org-insert-todo-heading 110
8173 [?\e (return)] "\e\C-m"))
8175 (unless org-local-vars
8176 (setq org-local-vars (org-get-local-variables)))
8180 (defun orgstruct-make-binding (fun n &rest keys)
8181 "Create a function for binding in the structure minor mode.
8182 FUN is the command to call inside a table. N is used to create a unique
8183 command name. KEYS are keys that should be checked in for a command
8184 to execute outside of tables."
8185 (eval
8186 (list 'defun
8187 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8188 '(arg)
8189 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8190 "Outside of structure, run the binding of `"
8191 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8192 "'.")
8193 '(interactive "p")
8194 (list 'if
8195 `(org-context-p 'headline 'item
8196 (and orgstruct-is-++
8197 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8198 'item-body))
8199 (list 'org-run-like-in-org-mode (list 'quote fun))
8200 (list 'let '(orgstruct-mode)
8201 (list 'call-interactively
8202 (append '(or)
8203 (mapcar (lambda (k)
8204 (list 'key-binding k))
8205 keys)
8206 '('orgstruct-error))))))))
8208 (defun org-context-p (&rest contexts)
8209 "Check if local context is any of CONTEXTS.
8210 Possible values in the list of contexts are `table', `headline', and `item'."
8211 (let ((pos (point)))
8212 (goto-char (point-at-bol))
8213 (prog1 (or (and (memq 'table contexts)
8214 (looking-at "[ \t]*|"))
8215 (and (memq 'headline contexts)
8216 ;;????????? (looking-at "\\*+"))
8217 (looking-at outline-regexp))
8218 (and (memq 'item contexts)
8219 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8220 (and (memq 'item-body contexts)
8221 (org-in-item-p)))
8222 (goto-char pos))))
8224 (defun org-get-local-variables ()
8225 "Return a list of all local variables in an org-mode buffer."
8226 (let (varlist)
8227 (with-current-buffer (get-buffer-create "*Org tmp*")
8228 (erase-buffer)
8229 (org-mode)
8230 (setq varlist (buffer-local-variables)))
8231 (kill-buffer "*Org tmp*")
8232 (delq nil
8233 (mapcar
8234 (lambda (x)
8235 (setq x
8236 (if (symbolp x)
8237 (list x)
8238 (list (car x) (list 'quote (cdr x)))))
8239 (if (string-match
8240 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8241 (symbol-name (car x)))
8242 x nil))
8243 varlist))))
8245 (defun org-clone-local-variables (from-buffer &optional regexp)
8246 "Clone local variables from FROM-BUFFER.
8247 Optional argument REGEXP selects variables to clone."
8248 (mapc
8249 (lambda (pair)
8250 (and (symbolp (car pair))
8251 (or (null regexp)
8252 (string-match regexp (symbol-name (car pair))))
8253 (set (make-local-variable (car pair))
8254 (cdr pair))))
8255 (buffer-local-variables from-buffer)))
8257 ;;;###autoload
8258 (defun org-run-like-in-org-mode (cmd)
8259 "Run a command, pretending that the current buffer is in Org-mode.
8260 This will temporarily bind local variables that are typically bound in
8261 Org-mode to the values they have in Org-mode, and then interactively
8262 call CMD."
8263 (org-load-modules-maybe)
8264 (unless org-local-vars
8265 (setq org-local-vars (org-get-local-variables)))
8266 (eval (list 'let org-local-vars
8267 (list 'call-interactively (list 'quote cmd)))))
8269 ;;;; Archiving
8271 (defun org-get-category (&optional pos force-refresh)
8272 "Get the category applying to position POS."
8273 (if force-refresh (org-refresh-category-properties))
8274 (let ((pos (or pos (point))))
8275 (or (get-text-property pos 'org-category)
8276 (progn (org-refresh-category-properties)
8277 (get-text-property pos 'org-category)))))
8279 (defun org-refresh-category-properties ()
8280 "Refresh category text properties in the buffer."
8281 (let ((def-cat (cond
8282 ((null org-category)
8283 (if buffer-file-name
8284 (file-name-sans-extension
8285 (file-name-nondirectory buffer-file-name))
8286 "???"))
8287 ((symbolp org-category) (symbol-name org-category))
8288 (t org-category)))
8289 beg end cat pos optionp)
8290 (org-unmodified
8291 (save-excursion
8292 (save-restriction
8293 (widen)
8294 (goto-char (point-min))
8295 (put-text-property (point) (point-max) 'org-category def-cat)
8296 (while (re-search-forward
8297 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8298 (setq pos (match-end 0)
8299 optionp (equal (char-after (match-beginning 0)) ?#)
8300 cat (org-trim (match-string 2)))
8301 (if optionp
8302 (setq beg (point-at-bol) end (point-max))
8303 (org-back-to-heading t)
8304 (setq beg (point) end (org-end-of-subtree t t)))
8305 (put-text-property beg end 'org-category cat)
8306 (goto-char pos)))))))
8309 ;;;; Link Stuff
8311 ;;; Link abbreviations
8313 (defun org-link-expand-abbrev (link)
8314 "Apply replacements as defined in `org-link-abbrev-alist."
8315 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8316 (let* ((key (match-string 1 link))
8317 (as (or (assoc key org-link-abbrev-alist-local)
8318 (assoc key org-link-abbrev-alist)))
8319 (tag (and (match-end 2) (match-string 3 link)))
8320 rpl)
8321 (if (not as)
8322 link
8323 (setq rpl (cdr as))
8324 (cond
8325 ((symbolp rpl) (funcall rpl tag))
8326 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8327 ((string-match "%h" rpl)
8328 (replace-match (url-hexify-string (or tag "")) t t rpl))
8329 (t (concat rpl tag)))))
8330 link))
8332 ;;; Storing and inserting links
8334 (defvar org-insert-link-history nil
8335 "Minibuffer history for links inserted with `org-insert-link'.")
8337 (defvar org-stored-links nil
8338 "Contains the links stored with `org-store-link'.")
8340 (defvar org-store-link-plist nil
8341 "Plist with info about the most recently link created with `org-store-link'.")
8343 (defvar org-link-protocols nil
8344 "Link protocols added to Org-mode using `org-add-link-type'.")
8346 (defvar org-store-link-functions nil
8347 "List of functions that are called to create and store a link.
8348 Each function will be called in turn until one returns a non-nil
8349 value. Each function should check if it is responsible for creating
8350 this link (for example by looking at the major mode).
8351 If not, it must exit and return nil.
8352 If yes, it should return a non-nil value after a calling
8353 `org-store-link-props' with a list of properties and values.
8354 Special properties are:
8356 :type The link prefix, like \"http\". This must be given.
8357 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8358 This is obligatory as well.
8359 :description Optional default description for the second pair
8360 of brackets in an Org-mode link. The user can still change
8361 this when inserting this link into an Org-mode buffer.
8363 In addition to these, any additional properties can be specified
8364 and then used in remember templates.")
8366 (defun org-add-link-type (type &optional follow export)
8367 "Add TYPE to the list of `org-link-types'.
8368 Re-compute all regular expressions depending on `org-link-types'
8370 FOLLOW and EXPORT are two functions.
8372 FOLLOW should take the link path as the single argument and do whatever
8373 is necessary to follow the link, for example find a file or display
8374 a mail message.
8376 EXPORT should format the link path for export to one of the export formats.
8377 It should be a function accepting three arguments:
8379 path the path of the link, the text after the prefix (like \"http:\")
8380 desc the description of the link, if any, or a description added by
8381 org-export-normalize-links if there is none
8382 format the export format, a symbol like `html' or `latex' or `ascii'..
8384 The function may use the FORMAT information to return different values
8385 depending on the format. The return value will be put literally into
8386 the exported file. If the return value is nil, this means Org should
8387 do what it normally does with links which do not have EXPORT defined.
8389 Org-mode has a built-in default for exporting links. If you are happy with
8390 this default, there is no need to define an export function for the link
8391 type. For a simple example of an export function, see `org-bbdb.el'."
8392 (add-to-list 'org-link-types type t)
8393 (org-make-link-regexps)
8394 (if (assoc type org-link-protocols)
8395 (setcdr (assoc type org-link-protocols) (list follow export))
8396 (push (list type follow export) org-link-protocols)))
8398 (defvar org-agenda-buffer-name)
8400 ;;;###autoload
8401 (defun org-store-link (arg)
8402 "\\<org-mode-map>Store an org-link to the current location.
8403 This link is added to `org-stored-links' and can later be inserted
8404 into an org-buffer with \\[org-insert-link].
8406 For some link types, a prefix arg is interpreted:
8407 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8408 For file links, arg negates `org-context-in-file-links'."
8409 (interactive "P")
8410 (org-load-modules-maybe)
8411 (setq org-store-link-plist nil) ; reset
8412 (org-with-limited-levels
8413 (let (link cpltxt desc description search txt custom-id agenda-link)
8414 (cond
8416 ((run-hook-with-args-until-success 'org-store-link-functions)
8417 (setq link (plist-get org-store-link-plist :link)
8418 desc (or (plist-get org-store-link-plist :description) link)))
8420 ((equal (buffer-name) "*Org Edit Src Example*")
8421 (let (label gc)
8422 (while (or (not label)
8423 (save-excursion
8424 (save-restriction
8425 (widen)
8426 (goto-char (point-min))
8427 (re-search-forward
8428 (regexp-quote (format org-coderef-label-format label))
8429 nil t))))
8430 (when label (message "Label exists already") (sit-for 2))
8431 (setq label (read-string "Code line label: " label)))
8432 (end-of-line 1)
8433 (setq link (format org-coderef-label-format label))
8434 (setq gc (- 79 (length link)))
8435 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8436 (insert link)
8437 (setq link (concat "(" label ")") desc nil)))
8439 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8440 ;; We are in the agenda, link to referenced location
8441 (let ((m (or (get-text-property (point) 'org-hd-marker)
8442 (get-text-property (point) 'org-marker))))
8443 (when m
8444 (org-with-point-at m
8445 (setq agenda-link
8446 (if (org-called-interactively-p 'any)
8447 (call-interactively 'org-store-link)
8448 (org-store-link nil)))))))
8450 ((eq major-mode 'calendar-mode)
8451 (let ((cd (calendar-cursor-to-date)))
8452 (setq link
8453 (format-time-string
8454 (car org-time-stamp-formats)
8455 (apply 'encode-time
8456 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8457 nil nil nil))))
8458 (org-store-link-props :type "calendar" :date cd)))
8460 ((eq major-mode 'w3-mode)
8461 (setq cpltxt (if (and (buffer-name)
8462 (not (string-match "Untitled" (buffer-name))))
8463 (buffer-name)
8464 (url-view-url t))
8465 link (org-make-link (url-view-url t)))
8466 (org-store-link-props :type "w3" :url (url-view-url t)))
8468 ((eq major-mode 'w3m-mode)
8469 (setq cpltxt (or w3m-current-title w3m-current-url)
8470 link (org-make-link w3m-current-url))
8471 (org-store-link-props :type "w3m" :url (url-view-url t)))
8473 ((setq search (run-hook-with-args-until-success
8474 'org-create-file-search-functions))
8475 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8476 "::" search))
8477 (setq cpltxt (or description link)))
8479 ((eq major-mode 'image-mode)
8480 (setq cpltxt (concat "file:"
8481 (abbreviate-file-name buffer-file-name))
8482 link (org-make-link cpltxt))
8483 (org-store-link-props :type "image" :file buffer-file-name))
8485 ((eq major-mode 'dired-mode)
8486 ;; link to the file in the current line
8487 (let ((file (dired-get-filename nil t)))
8488 (setq file (if file
8489 (abbreviate-file-name
8490 (expand-file-name (dired-get-filename nil t)))
8491 ;; otherwise, no file so use current directory.
8492 default-directory))
8493 (setq cpltxt (concat "file:" file)
8494 link (org-make-link cpltxt))))
8496 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8497 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8498 (cond
8499 ((org-in-regexp "<<\\(.*?\\)>>")
8500 (setq cpltxt
8501 (concat "file:"
8502 (abbreviate-file-name
8503 (buffer-file-name (buffer-base-buffer)))
8504 "::" (match-string 1))
8505 link (org-make-link cpltxt)))
8506 ((and (featurep 'org-id)
8507 (or (eq org-link-to-org-use-id t)
8508 (and (eq org-link-to-org-use-id 'create-if-interactive)
8509 (org-called-interactively-p 'any))
8510 (and (eq org-link-to-org-use-id
8511 'create-if-interactive-and-no-custom-id)
8512 (org-called-interactively-p 'any)
8513 (not custom-id))
8514 (and org-link-to-org-use-id
8515 (org-entry-get nil "ID"))))
8516 ;; We can make a link using the ID.
8517 (setq link (condition-case nil
8518 (prog1 (org-id-store-link)
8519 (setq desc (plist-get org-store-link-plist
8520 :description)))
8521 (error
8522 ;; probably before first headline, link to file only
8523 (concat "file:"
8524 (abbreviate-file-name
8525 (buffer-file-name (buffer-base-buffer))))))))
8527 ;; Just link to current headline
8528 (setq cpltxt (concat "file:"
8529 (abbreviate-file-name
8530 (buffer-file-name (buffer-base-buffer)))))
8531 ;; Add a context search string
8532 (when (org-xor org-context-in-file-links arg)
8533 (setq txt (cond
8534 ((org-on-heading-p) nil)
8535 ((org-region-active-p)
8536 (buffer-substring (region-beginning) (region-end)))
8537 (t nil)))
8538 (when (or (null txt) (string-match "\\S-" txt))
8539 (setq cpltxt
8540 (concat cpltxt "::"
8541 (condition-case nil
8542 (org-make-org-heading-search-string txt)
8543 (error "")))
8544 desc (or (nth 4 (ignore-errors
8545 (org-heading-components))) "NONE"))))
8546 (if (string-match "::\\'" cpltxt)
8547 (setq cpltxt (substring cpltxt 0 -2)))
8548 (setq link (org-make-link cpltxt)))))
8550 ((buffer-file-name (buffer-base-buffer))
8551 ;; Just link to this file here.
8552 (setq cpltxt (concat "file:"
8553 (abbreviate-file-name
8554 (buffer-file-name (buffer-base-buffer)))))
8555 ;; Add a context string
8556 (when (org-xor org-context-in-file-links arg)
8557 (setq txt (if (org-region-active-p)
8558 (buffer-substring (region-beginning) (region-end))
8559 (buffer-substring (point-at-bol) (point-at-eol))))
8560 ;; Only use search option if there is some text.
8561 (when (string-match "\\S-" txt)
8562 (setq cpltxt
8563 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8564 desc "NONE")))
8565 (setq link (org-make-link cpltxt)))
8567 ((org-called-interactively-p 'interactive)
8568 (error "Cannot link to a buffer which is not visiting a file"))
8570 (t (setq link nil)))
8572 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8573 (setq link (or link cpltxt)
8574 desc (or desc cpltxt))
8575 (if (equal desc "NONE") (setq desc nil))
8577 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8578 (progn
8579 (setq org-stored-links
8580 (cons (list link desc) org-stored-links))
8581 (message "Stored: %s" (or desc link))
8582 (when custom-id
8583 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8584 "::#" custom-id))
8585 (setq org-stored-links
8586 (cons (list link desc) org-stored-links))))
8587 (or agenda-link (and link (org-make-link-string link desc)))))))
8589 (defun org-store-link-props (&rest plist)
8590 "Store link properties, extract names and addresses."
8591 (let (x adr)
8592 (when (setq x (plist-get plist :from))
8593 (setq adr (mail-extract-address-components x))
8594 (setq plist (plist-put plist :fromname (car adr)))
8595 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8596 (when (setq x (plist-get plist :to))
8597 (setq adr (mail-extract-address-components x))
8598 (setq plist (plist-put plist :toname (car adr)))
8599 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8600 (let ((from (plist-get plist :from))
8601 (to (plist-get plist :to)))
8602 (when (and from to org-from-is-user-regexp)
8603 (setq plist
8604 (plist-put plist :fromto
8605 (if (string-match org-from-is-user-regexp from)
8606 (concat "to %t")
8607 (concat "from %f"))))))
8608 (setq org-store-link-plist plist))
8610 (defun org-add-link-props (&rest plist)
8611 "Add these properties to the link property list."
8612 (let (key value)
8613 (while plist
8614 (setq key (pop plist) value (pop plist))
8615 (setq org-store-link-plist
8616 (plist-put org-store-link-plist key value)))))
8618 (defun org-email-link-description (&optional fmt)
8619 "Return the description part of an email link.
8620 This takes information from `org-store-link-plist' and formats it
8621 according to FMT (default from `org-email-link-description-format')."
8622 (setq fmt (or fmt org-email-link-description-format))
8623 (let* ((p org-store-link-plist)
8624 (to (plist-get p :toaddress))
8625 (from (plist-get p :fromaddress))
8626 (table
8627 (list
8628 (cons "%c" (plist-get p :fromto))
8629 (cons "%F" (plist-get p :from))
8630 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8631 (cons "%T" (plist-get p :to))
8632 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8633 (cons "%s" (plist-get p :subject))
8634 (cons "%d" (plist-get p :date))
8635 (cons "%m" (plist-get p :message-id)))))
8636 (when (string-match "%c" fmt)
8637 ;; Check if the user wrote this message
8638 (if (and org-from-is-user-regexp from to
8639 (save-match-data (string-match org-from-is-user-regexp from)))
8640 (setq fmt (replace-match "to %t" t t fmt))
8641 (setq fmt (replace-match "from %f" t t fmt))))
8642 (org-replace-escapes fmt table)))
8644 (defun org-make-org-heading-search-string (&optional string heading)
8645 "Make search string for STRING or current headline."
8646 (interactive)
8647 (let ((s (or string (org-get-heading)))
8648 (lines org-context-in-file-links))
8649 (unless (and string (not heading))
8650 ;; We are using a headline, clean up garbage in there.
8651 (if (string-match org-todo-regexp s)
8652 (setq s (replace-match "" t t s)))
8653 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8654 (setq s (replace-match "" t t s)))
8655 (setq s (org-trim s))
8656 (if (string-match (concat "^\\(" org-quote-string "\\|"
8657 org-comment-string "\\)") s)
8658 (setq s (replace-match "" t t s)))
8659 (while (string-match org-ts-regexp s)
8660 (setq s (replace-match "" t t s))))
8661 (or string (setq s (concat "*" s))) ; Add * for headlines
8662 (when (and string (integerp lines) (> lines 0))
8663 (let ((slines (org-split-string s "\n")))
8664 (when (< lines (length slines))
8665 (setq s (mapconcat
8666 'identity
8667 (reverse (nthcdr (- (length slines) lines)
8668 (reverse slines))) "\n")))))
8669 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8671 (defun org-make-link (&rest strings)
8672 "Concatenate STRINGS."
8673 (apply 'concat strings))
8675 (defun org-make-link-string (link &optional description)
8676 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8677 (unless (string-match "\\S-" link)
8678 (error "Empty link"))
8679 (when (and description
8680 (stringp description)
8681 (not (string-match "\\S-" description)))
8682 (setq description nil))
8683 (when (stringp description)
8684 ;; Remove brackets from the description, they are fatal.
8685 (while (string-match "\\[" description)
8686 (setq description (replace-match "{" t t description)))
8687 (while (string-match "\\]" description)
8688 (setq description (replace-match "}" t t description))))
8689 (when (equal link description)
8690 ;; No description needed, it is identical
8691 (setq description nil))
8692 (when (and (not description)
8693 (not (string-match (org-image-file-name-regexp) link))
8694 (not (equal link (org-link-escape link))))
8695 (setq description (org-extract-attributes link)))
8696 (setq link
8697 (cond ((string-match (org-image-file-name-regexp) link) link)
8698 ((string-match org-link-types-re link)
8699 (concat (match-string 1 link)
8700 (org-link-escape (substring link (match-end 1)))))
8701 (t (org-link-escape link))))
8702 (concat "[[" link "]"
8703 (if description (concat "[" description "]") "")
8704 "]"))
8706 (defconst org-link-escape-chars
8707 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8708 "List of characters that should be escaped in link.
8709 This is the list that is used for internal purposes.")
8711 (defvar org-url-encoding-use-url-hexify nil)
8713 (defconst org-link-escape-chars-browser
8714 '(?\ )
8715 "List of escapes for characters that are problematic in links.
8716 This is the list that is used before handing over to the browser.")
8718 (defun org-link-escape (text &optional table merge)
8719 "Return percent escaped representation of TEXT.
8720 TEXT is a string with the text to escape.
8721 Optional argument TABLE is a list with characters that should be
8722 escaped. When nil, `org-link-escape-chars' is used.
8723 If optional argument MERGE is set, merge TABLE into
8724 `org-link-escape-chars'."
8725 (if (and org-url-encoding-use-url-hexify (not table))
8726 (url-hexify-string text)
8727 (cond
8728 ((and table merge)
8729 (mapc (lambda (defchr)
8730 (unless (member defchr table)
8731 (setq table (cons defchr table)))) org-link-escape-chars))
8732 ((null table)
8733 (setq table org-link-escape-chars)))
8734 (mapconcat
8735 (lambda (char)
8736 (if (or (member char table)
8737 (< char 32) (= char 37) (> char 126))
8738 (mapconcat (lambda (sequence-element)
8739 (format "%%%.2X" sequence-element))
8740 (or (encode-coding-char char 'utf-8)
8741 (error "Unable to percent escape character: %s"
8742 (char-to-string char))) "")
8743 (char-to-string char))) text "")))
8745 (defun org-link-unescape (str)
8746 "Unhex hexified unicode strings as returned from the JavaScript function
8747 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8748 (unless (and (null str) (string= "" str))
8749 (let ((pos 0) (case-fold-search t) unhexed)
8750 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8751 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8752 (setq str (replace-match unhexed t t str))
8753 (setq pos (+ pos (length unhexed))))))
8754 str)
8756 (defun org-link-unescape-compound (hex)
8757 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8758 Note: this function also decodes single byte encodings like
8759 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8760 (save-match-data
8761 (let* ((bytes (cdr (split-string hex "%")))
8762 (ret "")
8763 (eat 0)
8764 (sum 0))
8765 (while bytes
8766 (let* ((val (string-to-number (pop bytes) 16))
8767 (shift-xor
8768 (if (= 0 eat)
8769 (cond
8770 ((>= val 252) (cons 6 252))
8771 ((>= val 248) (cons 5 248))
8772 ((>= val 240) (cons 4 240))
8773 ((>= val 224) (cons 3 224))
8774 ((>= val 192) (cons 2 192))
8775 (t (cons 0 0)))
8776 (cons 6 128))))
8777 (if (>= val 192) (setq eat (car shift-xor)))
8778 (setq val (logxor val (cdr shift-xor)))
8779 (setq sum (+ (lsh sum (car shift-xor)) val))
8780 (if (> eat 0) (setq eat (- eat 1)))
8781 (cond
8782 ((= 0 eat) ;multi byte
8783 (setq ret (concat ret (org-char-to-string sum)))
8784 (setq sum 0))
8785 ((not bytes) ; single byte(s)
8786 (setq ret (org-link-unescape-single-byte-sequence hex))))
8787 )) ;; end (while bytes
8788 ret )))
8790 (defun org-link-unescape-single-byte-sequence (hex)
8791 "Unhexify hex-encoded single byte character sequences."
8792 (mapconcat (lambda (byte)
8793 (char-to-string (string-to-number byte 16)))
8794 (cdr (split-string hex "%")) ""))
8796 (defun org-xor (a b)
8797 "Exclusive or."
8798 (if a (not b) b))
8800 (defun org-fixup-message-id-for-http (s)
8801 "Replace special characters in a message id, so it can be used in an http query."
8802 (when (string-match "%" s)
8803 (setq s (mapconcat (lambda (c)
8804 (if (eq c ?%)
8805 "%25"
8806 (char-to-string c)))
8807 s "")))
8808 (while (string-match "<" s)
8809 (setq s (replace-match "%3C" t t s)))
8810 (while (string-match ">" s)
8811 (setq s (replace-match "%3E" t t s)))
8812 (while (string-match "@" s)
8813 (setq s (replace-match "%40" t t s)))
8816 ;;;###autoload
8817 (defun org-insert-link-global ()
8818 "Insert a link like Org-mode does.
8819 This command can be called in any mode to insert a link in Org-mode syntax."
8820 (interactive)
8821 (org-load-modules-maybe)
8822 (org-run-like-in-org-mode 'org-insert-link))
8824 (defun org-insert-link (&optional complete-file link-location)
8825 "Insert a link. At the prompt, enter the link.
8827 Completion can be used to insert any of the link protocol prefixes like
8828 http or ftp in use.
8830 The history can be used to select a link previously stored with
8831 `org-store-link'. When the empty string is entered (i.e. if you just
8832 press RET at the prompt), the link defaults to the most recently
8833 stored link. As SPC triggers completion in the minibuffer, you need to
8834 use M-SPC or C-q SPC to force the insertion of a space character.
8836 You will also be prompted for a description, and if one is given, it will
8837 be displayed in the buffer instead of the link.
8839 If there is already a link at point, this command will allow you to edit link
8840 and description parts.
8842 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8843 be selected using completion. The path to the file will be relative to the
8844 current directory if the file is in the current directory or a subdirectory.
8845 Otherwise, the link will be the absolute path as completed in the minibuffer
8846 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8847 option `org-link-file-path-type'.
8849 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8850 the current directory or below.
8852 With three \\[universal-argument] prefixes, negate the meaning of
8853 `org-keep-stored-link-after-insertion'.
8855 If `org-make-link-description-function' is non-nil, this function will be
8856 called with the link target, and the result will be the default
8857 link description.
8859 If the LINK-LOCATION parameter is non-nil, this value will be
8860 used as the link location instead of reading one interactively."
8861 (interactive "P")
8862 (let* ((wcf (current-window-configuration))
8863 (region (if (org-region-active-p)
8864 (buffer-substring (region-beginning) (region-end))))
8865 (remove (and region (list (region-beginning) (region-end))))
8866 (desc region)
8867 tmphist ; byte-compile incorrectly complains about this
8868 (link link-location)
8869 entry file all-prefixes)
8870 (cond
8871 (link-location) ; specified by arg, just use it.
8872 ((org-in-regexp org-bracket-link-regexp 1)
8873 ;; We do have a link at point, and we are going to edit it.
8874 (setq remove (list (match-beginning 0) (match-end 0)))
8875 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8876 (setq link (read-string "Link: "
8877 (org-link-unescape
8878 (org-match-string-no-properties 1)))))
8879 ((or (org-in-regexp org-angle-link-re)
8880 (org-in-regexp org-plain-link-re))
8881 ;; Convert to bracket link
8882 (setq remove (list (match-beginning 0) (match-end 0))
8883 link (read-string "Link: "
8884 (org-remove-angle-brackets (match-string 0)))))
8885 ((member complete-file '((4) (16)))
8886 ;; Completing read for file names.
8887 (setq link (org-file-complete-link complete-file)))
8889 ;; Read link, with completion for stored links.
8890 (with-output-to-temp-buffer "*Org Links*"
8891 (princ "Insert a link.
8892 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8893 (when org-stored-links
8894 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8895 (princ (mapconcat
8896 (lambda (x)
8897 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8898 (reverse org-stored-links) "\n"))))
8899 (let ((cw (selected-window)))
8900 (select-window (get-buffer-window "*Org Links*" 'visible))
8901 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
8902 (unless (pos-visible-in-window-p (point-max))
8903 (org-fit-window-to-buffer))
8904 (and (window-live-p cw) (select-window cw)))
8905 ;; Fake a link history, containing the stored links.
8906 (setq tmphist (append (mapcar 'car org-stored-links)
8907 org-insert-link-history))
8908 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8909 (mapcar 'car org-link-abbrev-alist)
8910 org-link-types))
8911 (unwind-protect
8912 (progn
8913 (setq link
8914 (let ((org-completion-use-ido nil)
8915 (org-completion-use-iswitchb nil))
8916 (org-completing-read
8917 "Link: "
8918 (append
8919 (mapcar (lambda (x) (list (concat x ":")))
8920 all-prefixes)
8921 (mapcar 'car org-stored-links))
8922 nil nil nil
8923 'tmphist
8924 (car (car org-stored-links)))))
8925 (if (not (string-match "\\S-" link))
8926 (error "No link selected"))
8927 (if (or (member link all-prefixes)
8928 (and (equal ":" (substring link -1))
8929 (member (substring link 0 -1) all-prefixes)
8930 (setq link (substring link 0 -1))))
8931 (setq link (org-link-try-special-completion link))))
8932 (set-window-configuration wcf)
8933 (kill-buffer "*Org Links*"))
8934 (setq entry (assoc link org-stored-links))
8935 (or entry (push link org-insert-link-history))
8936 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8937 (not org-keep-stored-link-after-insertion))
8938 (setq org-stored-links (delq (assoc link org-stored-links)
8939 org-stored-links)))
8940 (setq desc (or desc (nth 1 entry)))))
8942 (if (string-match org-plain-link-re link)
8943 ;; URL-like link, normalize the use of angular brackets.
8944 (setq link (org-make-link (org-remove-angle-brackets link))))
8946 ;; Check if we are linking to the current file with a search option
8947 ;; If yes, simplify the link by using only the search option.
8948 (when (and buffer-file-name
8949 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8950 (let* ((path (match-string 1 link))
8951 (case-fold-search nil)
8952 (search (match-string 2 link)))
8953 (save-match-data
8954 (if (equal (file-truename buffer-file-name) (file-truename path))
8955 ;; We are linking to this same file, with a search option
8956 (setq link search)))))
8958 ;; Check if we can/should use a relative path. If yes, simplify the link
8959 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8960 (let* ((type (match-string 1 link))
8961 (path (match-string 2 link))
8962 (origpath path)
8963 (case-fold-search nil))
8964 (cond
8965 ((or (eq org-link-file-path-type 'absolute)
8966 (equal complete-file '(16)))
8967 (setq path (abbreviate-file-name (expand-file-name path))))
8968 ((eq org-link-file-path-type 'noabbrev)
8969 (setq path (expand-file-name path)))
8970 ((eq org-link-file-path-type 'relative)
8971 (setq path (file-relative-name path)))
8973 (save-match-data
8974 (if (string-match (concat "^" (regexp-quote
8975 (expand-file-name
8976 (file-name-as-directory
8977 default-directory))))
8978 (expand-file-name path))
8979 ;; We are linking a file with relative path name.
8980 (setq path (substring (expand-file-name path)
8981 (match-end 0)))
8982 (setq path (abbreviate-file-name (expand-file-name path)))))))
8983 (setq link (concat type path))
8984 (if (equal desc origpath)
8985 (setq desc path))))
8987 (if org-make-link-description-function
8988 (setq desc (funcall org-make-link-description-function link desc)))
8990 (setq desc (read-string "Description: " desc))
8991 (unless (string-match "\\S-" desc) (setq desc nil))
8992 (if remove (apply 'delete-region remove))
8993 (insert (org-make-link-string link desc))))
8995 (defun org-link-try-special-completion (type)
8996 "If there is completion support for link type TYPE, offer it."
8997 (let ((fun (intern (concat "org-" type "-complete-link"))))
8998 (if (functionp fun)
8999 (funcall fun)
9000 (read-string "Link (no completion support): " (concat type ":")))))
9002 (defun org-file-complete-link (&optional arg)
9003 "Create a file link using completion."
9004 (let (file link)
9005 (setq file (read-file-name "File: "))
9006 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9007 (pwd1 (file-name-as-directory (abbreviate-file-name
9008 (expand-file-name ".")))))
9009 (cond
9010 ((equal arg '(16))
9011 (setq link (org-make-link
9012 "file:"
9013 (abbreviate-file-name (expand-file-name file)))))
9014 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9015 (setq link (org-make-link "file:" (match-string 1 file))))
9016 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9017 (expand-file-name file))
9018 (setq link (org-make-link
9019 "file:" (match-string 1 (expand-file-name file)))))
9020 (t (setq link (org-make-link "file:" file)))))
9021 link))
9023 (defun org-completing-read (&rest args)
9024 "Completing-read with SPACE being a normal character."
9025 (let ((minibuffer-local-completion-map
9026 (copy-keymap minibuffer-local-completion-map)))
9027 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9028 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9029 (apply 'org-icompleting-read args)))
9031 (defun org-completing-read-no-i (&rest args)
9032 (let (org-completion-use-ido org-completion-use-iswitchb)
9033 (apply 'org-completing-read args)))
9035 (defun org-iswitchb-completing-read (prompt choices &rest args)
9036 "Use iswitch as a completing-read replacement to choose from choices.
9037 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9038 from."
9039 (let* ((iswitchb-use-virtual-buffers nil)
9040 (iswitchb-make-buflist-hook
9041 (lambda ()
9042 (setq iswitchb-temp-buflist choices))))
9043 (iswitchb-read-buffer prompt)))
9045 (defun org-icompleting-read (&rest args)
9046 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9047 (org-without-partial-completion
9048 (if (and org-completion-use-ido
9049 (fboundp 'ido-completing-read)
9050 (boundp 'ido-mode) ido-mode
9051 (listp (second args)))
9052 (let ((ido-enter-matching-directory nil))
9053 (apply 'ido-completing-read (concat (car args))
9054 (if (consp (car (nth 1 args)))
9055 (mapcar 'car (nth 1 args))
9056 (nth 1 args))
9057 (cddr args)))
9058 (if (and org-completion-use-iswitchb
9059 (boundp 'iswitchb-mode) iswitchb-mode
9060 (listp (second args)))
9061 (apply 'org-iswitchb-completing-read (concat (car args))
9062 (if (consp (car (nth 1 args)))
9063 (mapcar 'car (nth 1 args))
9064 (nth 1 args))
9065 (cddr args))
9066 (apply 'completing-read args)))))
9068 (defun org-extract-attributes (s)
9069 "Extract the attributes cookie from a string and set as text property."
9070 (let (a attr (start 0) key value)
9071 (save-match-data
9072 (when (string-match "{{\\([^}]+\\)}}$" s)
9073 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9074 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9075 (setq key (match-string 1 a) value (match-string 2 a)
9076 start (match-end 0)
9077 attr (plist-put attr (intern key) value))))
9078 (org-add-props s nil 'org-attr attr))
9081 (defun org-extract-attributes-from-string (tag)
9082 (let (key value attr)
9083 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9084 (setq key (match-string 1 tag) value (match-string 2 tag)
9085 tag (replace-match "" t t tag)
9086 attr (plist-put attr (intern key) value)))
9087 (cons tag attr)))
9089 (defun org-attributes-to-string (plist)
9090 "Format a property list into an HTML attribute list."
9091 (let ((s "") key value)
9092 (while plist
9093 (setq key (pop plist) value (pop plist))
9094 (and value
9095 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9098 ;;; Opening/following a link
9100 (defvar org-link-search-failed nil)
9102 (defvar org-open-link-functions nil
9103 "Hook for functions finding a plain text link.
9104 These functions must take a single argument, the link content.
9105 They will be called for links that look like [[link text][description]]
9106 when LINK TEXT does not have a protocol like \"http:\" and does not look
9107 like a filename (e.g. \"./blue.png\").
9109 These functions will be called *before* Org attempts to resolve the
9110 link by doing text searches in the current buffer - so if you want a
9111 link \"[[target]]\" to still find \"<<target>>\", your function should
9112 handle this as a special case.
9114 When the function does handle the link, it must return a non-nil value.
9115 If it decides that it is not responsible for this link, it must return
9116 nil to indicate that that Org-mode can continue with other options
9117 like exact and fuzzy text search.")
9119 (defun org-next-link ()
9120 "Move forward to the next link.
9121 If the link is in hidden text, expose it."
9122 (interactive)
9123 (when (and org-link-search-failed (eq this-command last-command))
9124 (goto-char (point-min))
9125 (message "Link search wrapped back to beginning of buffer"))
9126 (setq org-link-search-failed nil)
9127 (let* ((pos (point))
9128 (ct (org-context))
9129 (a (assoc :link ct)))
9130 (if a (goto-char (nth 2 a)))
9131 (if (re-search-forward org-any-link-re nil t)
9132 (progn
9133 (goto-char (match-beginning 0))
9134 (if (outline-invisible-p) (org-show-context)))
9135 (goto-char pos)
9136 (setq org-link-search-failed t)
9137 (error "No further link found"))))
9139 (defun org-previous-link ()
9140 "Move backward to the previous link.
9141 If the link is in hidden text, expose it."
9142 (interactive)
9143 (when (and org-link-search-failed (eq this-command last-command))
9144 (goto-char (point-max))
9145 (message "Link search wrapped back to end of buffer"))
9146 (setq org-link-search-failed nil)
9147 (let* ((pos (point))
9148 (ct (org-context))
9149 (a (assoc :link ct)))
9150 (if a (goto-char (nth 1 a)))
9151 (if (re-search-backward org-any-link-re nil t)
9152 (progn
9153 (goto-char (match-beginning 0))
9154 (if (outline-invisible-p) (org-show-context)))
9155 (goto-char pos)
9156 (setq org-link-search-failed t)
9157 (error "No further link found"))))
9159 (defun org-translate-link (s)
9160 "Translate a link string if a translation function has been defined."
9161 (if (and org-link-translation-function
9162 (fboundp org-link-translation-function)
9163 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9164 (progn
9165 (setq s (funcall org-link-translation-function
9166 (match-string 1) (match-string 2)))
9167 (concat (car s) ":" (cdr s)))
9170 (defun org-translate-link-from-planner (type path)
9171 "Translate a link from Emacs Planner syntax so that Org can follow it.
9172 This is still an experimental function, your mileage may vary."
9173 (cond
9174 ((member type '("http" "https" "news" "ftp"))
9175 ;; standard Internet links are the same.
9176 nil)
9177 ((and (equal type "irc") (string-match "^//" path))
9178 ;; Planner has two / at the beginning of an irc link, we have 1.
9179 ;; We should have zero, actually....
9180 (setq path (substring path 1)))
9181 ((and (equal type "lisp") (string-match "^/" path))
9182 ;; Planner has a slash, we do not.
9183 (setq type "elisp" path (substring path 1)))
9184 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9185 ;; A typical message link. Planner has the id after the final slash,
9186 ;; we separate it with a hash mark
9187 (setq path (concat (match-string 1 path) "#"
9188 (org-remove-angle-brackets (match-string 2 path)))))
9190 (cons type path))
9192 (defun org-find-file-at-mouse (ev)
9193 "Open file link or URL at mouse."
9194 (interactive "e")
9195 (mouse-set-point ev)
9196 (org-open-at-point 'in-emacs))
9198 (defun org-open-at-mouse (ev)
9199 "Open file link or URL at mouse."
9200 (interactive "e")
9201 (mouse-set-point ev)
9202 (if (eq major-mode 'org-agenda-mode)
9203 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9204 (org-open-at-point))
9206 (defvar org-window-config-before-follow-link nil
9207 "The window configuration before following a link.
9208 This is saved in case the need arises to restore it.")
9210 (defvar org-open-link-marker (make-marker)
9211 "Marker pointing to the location where `org-open-at-point; was called.")
9213 ;;;###autoload
9214 (defun org-open-at-point-global ()
9215 "Follow a link like Org-mode does.
9216 This command can be called in any mode to follow a link that has
9217 Org-mode syntax."
9218 (interactive)
9219 (org-run-like-in-org-mode 'org-open-at-point))
9221 ;;;###autoload
9222 (defun org-open-link-from-string (s &optional arg reference-buffer)
9223 "Open a link in the string S, as if it was in Org-mode."
9224 (interactive "sLink: \nP")
9225 (let ((reference-buffer (or reference-buffer (current-buffer))))
9226 (with-temp-buffer
9227 (let ((org-inhibit-startup t))
9228 (org-mode)
9229 (insert s)
9230 (goto-char (point-min))
9231 (when reference-buffer
9232 (setq org-link-abbrev-alist-local
9233 (with-current-buffer reference-buffer
9234 org-link-abbrev-alist-local)))
9235 (org-open-at-point arg reference-buffer)))))
9237 (defvar org-open-at-point-functions nil
9238 "Hook that is run when following a link at point.
9240 Functions in this hook must return t if they identify and follow
9241 a link at point. If they don't find anything interesting at point,
9242 they must return nil.")
9244 (defun org-open-at-point (&optional arg reference-buffer)
9245 "Open link at or after point.
9246 If there is no link at point, this function will search forward up to
9247 the end of the current line.
9248 Normally, files will be opened by an appropriate application. If the
9249 optional prefix argument ARG is non-nil, Emacs will visit the file.
9250 With a double prefix argument, try to open outside of Emacs, in the
9251 application the system uses for this file type."
9252 (interactive "P")
9253 ;; if in a code block, then open the block's results
9254 (unless (call-interactively #'org-babel-open-src-block-result)
9255 (org-load-modules-maybe)
9256 (move-marker org-open-link-marker (point))
9257 (setq org-window-config-before-follow-link (current-window-configuration))
9258 (org-remove-occur-highlights nil nil t)
9259 (cond
9260 ((and (org-on-heading-p)
9261 (not (org-in-regexp
9262 (concat org-plain-link-re "\\|"
9263 org-bracket-link-regexp "\\|"
9264 org-angle-link-re "\\|"
9265 "[ \t]:[^ \t\n]+:[ \t]*$")))
9266 (not (get-text-property (point) 'org-linked-text)))
9267 (or (org-offer-links-in-entry arg)
9268 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9269 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9270 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9271 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9272 (not (org-in-regexp org-bracket-link-regexp)))
9273 (org-footnote-action))
9275 (let (type path link line search (pos (point)))
9276 (catch 'match
9277 (save-excursion
9278 (skip-chars-forward "^]\n\r")
9279 (when (org-in-regexp org-bracket-link-regexp 1)
9280 (setq link (org-extract-attributes
9281 (org-link-unescape (org-match-string-no-properties 1))))
9282 (while (string-match " *\n *" link)
9283 (setq link (replace-match " " t t link)))
9284 (setq link (org-link-expand-abbrev link))
9285 (cond
9286 ((or (file-name-absolute-p link)
9287 (string-match "^\\.\\.?/" link))
9288 (setq type "file" path link))
9289 ((string-match org-link-re-with-space3 link)
9290 (setq type (match-string 1 link) path (match-string 2 link)))
9291 (t (setq type "thisfile" path link)))
9292 (throw 'match t)))
9294 (when (get-text-property (point) 'org-linked-text)
9295 (setq type "thisfile"
9296 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9297 (1+ (point)) (point))
9298 path (buffer-substring
9299 (or (previous-single-property-change pos 'org-linked-text)
9300 (point-min))
9301 (or (next-single-property-change pos 'org-linked-text)
9302 (point-max))))
9303 (throw 'match t))
9305 (save-excursion
9306 (when (or (org-in-regexp org-angle-link-re)
9307 (org-in-regexp org-plain-link-re))
9308 (setq type (match-string 1) path (match-string 2))
9309 (throw 'match t)))
9310 (save-excursion
9311 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9312 (setq type "tags"
9313 path (match-string 1))
9314 (while (string-match ":" path)
9315 (setq path (replace-match "+" t t path)))
9316 (throw 'match t)))
9317 (when (org-in-regexp "<\\([^><\n]+\\)>")
9318 (setq type "tree-match"
9319 path (match-string 1))
9320 (throw 'match t)))
9321 (unless path
9322 (error "No link found"))
9324 ;; switch back to reference buffer
9325 ;; needed when if called in a temporary buffer through
9326 ;; org-open-link-from-string
9327 (with-current-buffer (or reference-buffer (current-buffer))
9329 ;; Remove any trailing spaces in path
9330 (if (string-match " +\\'" path)
9331 (setq path (replace-match "" t t path)))
9332 (if (and org-link-translation-function
9333 (fboundp org-link-translation-function))
9334 ;; Check if we need to translate the link
9335 (let ((tmp (funcall org-link-translation-function type path)))
9336 (setq type (car tmp) path (cdr tmp))))
9338 (cond
9340 ((assoc type org-link-protocols)
9341 (funcall (nth 1 (assoc type org-link-protocols)) path))
9343 ((equal type "mailto")
9344 (let ((cmd (car org-link-mailto-program))
9345 (args (cdr org-link-mailto-program)) args1
9346 (address path) (subject "") a)
9347 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9348 (setq address (match-string 1 path)
9349 subject (org-link-escape (match-string 2 path))))
9350 (while args
9351 (cond
9352 ((not (stringp (car args))) (push (pop args) args1))
9353 (t (setq a (pop args))
9354 (if (string-match "%a" a)
9355 (setq a (replace-match address t t a)))
9356 (if (string-match "%s" a)
9357 (setq a (replace-match subject t t a)))
9358 (push a args1))))
9359 (apply cmd (nreverse args1))))
9361 ((member type '("http" "https" "ftp" "news"))
9362 (browse-url (concat type ":" (org-link-escape
9363 path org-link-escape-chars-browser))))
9365 ((string= type "doi")
9366 (browse-url (concat "http://dx.doi.org/"
9367 (org-link-escape
9368 path org-link-escape-chars-browser))))
9370 ((member type '("message"))
9371 (browse-url (concat type ":" path)))
9373 ((string= type "tags")
9374 (org-tags-view arg path))
9376 ((string= type "tree-match")
9377 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9379 ((string= type "file")
9380 (if (string-match "::\\([0-9]+\\)\\'" path)
9381 (setq line (string-to-number (match-string 1 path))
9382 path (substring path 0 (match-beginning 0)))
9383 (if (string-match "::\\(.+\\)\\'" path)
9384 (setq search (match-string 1 path)
9385 path (substring path 0 (match-beginning 0)))))
9386 (if (string-match "[*?{]" (file-name-nondirectory path))
9387 (dired path)
9388 (org-open-file path arg line search)))
9390 ((string= type "shell")
9391 (let ((cmd path))
9392 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9393 (string-match org-confirm-shell-link-not-regexp cmd))
9394 (not org-confirm-shell-link-function)
9395 (funcall org-confirm-shell-link-function
9396 (format "Execute \"%s\" in shell? "
9397 (org-add-props cmd nil
9398 'face 'org-warning))))
9399 (progn
9400 (message "Executing %s" cmd)
9401 (shell-command cmd))
9402 (error "Abort"))))
9404 ((string= type "elisp")
9405 (let ((cmd path))
9406 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9407 (string-match org-confirm-elisp-link-not-regexp cmd))
9408 (not org-confirm-elisp-link-function)
9409 (funcall org-confirm-elisp-link-function
9410 (format "Execute \"%s\" as elisp? "
9411 (org-add-props cmd nil
9412 'face 'org-warning))))
9413 (message "%s => %s" cmd
9414 (if (equal (string-to-char cmd) ?\()
9415 (eval (read cmd))
9416 (call-interactively (read cmd))))
9417 (error "Abort"))))
9419 ((and (string= type "thisfile")
9420 (run-hook-with-args-until-success
9421 'org-open-link-functions path)))
9423 ((string= type "thisfile")
9424 (if arg
9425 (switch-to-buffer-other-window
9426 (org-get-buffer-for-internal-link (current-buffer)))
9427 (org-mark-ring-push))
9428 (let ((cmd `(org-link-search
9429 ,path
9430 ,(cond ((equal arg '(4)) ''occur)
9431 ((equal arg '(16)) ''org-occur)
9432 (t nil))
9433 ,pos)))
9434 (condition-case nil (eval cmd)
9435 (error (progn (widen) (eval cmd))))))
9438 (browse-url-at-point)))))))
9439 (move-marker org-open-link-marker nil)
9440 (run-hook-with-args 'org-follow-link-hook)))
9442 (defun org-offer-links-in-entry (&optional nth zero)
9443 "Offer links in the current entry and follow the selected link.
9444 If there is only one link, follow it immediately as well.
9445 If NTH is an integer, immediately pick the NTH link found.
9446 If ZERO is a string, check also this string for a link, and if
9447 there is one, offer it as link number zero."
9448 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9449 "\\(" org-angle-link-re "\\)\\|"
9450 "\\(" org-plain-link-re "\\)"))
9451 (cnt ?0)
9452 (in-emacs (if (integerp nth) nil nth))
9453 have-zero end links link c)
9454 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9455 (push (match-string 0 zero) links)
9456 (setq cnt (1- cnt) have-zero t))
9457 (save-excursion
9458 (org-back-to-heading t)
9459 (setq end (save-excursion (outline-next-heading) (point)))
9460 (while (re-search-forward re end t)
9461 (push (match-string 0) links))
9462 (setq links (org-uniquify (reverse links))))
9464 (cond
9465 ((null links)
9466 (message "No links"))
9467 ((equal (length links) 1)
9468 (setq link (list (car links))))
9469 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9470 (setq link (nth (if have-zero nth (1- nth)) links)))
9471 (t ; we have to select a link
9472 (save-excursion
9473 (save-window-excursion
9474 (delete-other-windows)
9475 (with-output-to-temp-buffer "*Select Link*"
9476 (mapc (lambda (l)
9477 (if (not (string-match org-bracket-link-regexp l))
9478 (princ (format "[%c] %s\n" (incf cnt)
9479 (org-remove-angle-brackets l)))
9480 (if (match-end 3)
9481 (princ (format "[%c] %s (%s)\n" (incf cnt)
9482 (match-string 3 l) (match-string 1 l)))
9483 (princ (format "[%c] %s\n" (incf cnt)
9484 (match-string 1 l))))))
9485 links))
9486 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9487 (message "Select link to open, RET to open all:")
9488 (setq c (read-char-exclusive))
9489 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9490 (when (equal c ?q) (error "Abort"))
9491 (if (equal c ?\C-m)
9492 (setq link links)
9493 (setq nth (- c ?0))
9494 (if have-zero (setq nth (1+ nth)))
9495 (unless (and (integerp nth) (>= (length links) nth))
9496 (error "Invalid link selection"))
9497 (setq link (list (nth (1- nth) links))))))
9498 (if link
9499 (let ((buf (current-buffer)))
9500 (dolist (l link)
9501 (org-open-link-from-string l in-emacs buf))
9503 nil)))
9505 ;; Add special file links that specify the way of opening
9507 (org-add-link-type "file+sys" 'org-open-file-with-system)
9508 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9509 (defun org-open-file-with-system (path)
9510 "Open file at PATH using the system way of opening it."
9511 (org-open-file path 'system))
9512 (defun org-open-file-with-emacs (path)
9513 "Open file at PATH in Emacs."
9514 (org-open-file path 'emacs))
9515 (defun org-remove-file-link-modifiers ()
9516 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9517 (goto-char (point-min))
9518 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9519 (org-if-unprotected
9520 (replace-match "file:" t t))))
9521 (eval-after-load "org-exp"
9522 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9523 'org-remove-file-link-modifiers))
9525 ;;;; Time estimates
9527 (defun org-get-effort (&optional pom)
9528 "Get the effort estimate for the current entry."
9529 (org-entry-get pom org-effort-property))
9531 ;;; File search
9533 (defvar org-create-file-search-functions nil
9534 "List of functions to construct the right search string for a file link.
9535 These functions are called in turn with point at the location to
9536 which the link should point.
9538 A function in the hook should first test if it would like to
9539 handle this file type, for example by checking the `major-mode'
9540 or the file extension. If it decides not to handle this file, it
9541 should just return nil to give other functions a chance. If it
9542 does handle the file, it must return the search string to be used
9543 when following the link. The search string will be part of the
9544 file link, given after a double colon, and `org-open-at-point'
9545 will automatically search for it. If special measures must be
9546 taken to make the search successful, another function should be
9547 added to the companion hook `org-execute-file-search-functions',
9548 which see.
9550 A function in this hook may also use `setq' to set the variable
9551 `description' to provide a suggestion for the descriptive text to
9552 be used for this link when it gets inserted into an Org-mode
9553 buffer with \\[org-insert-link].")
9555 (defvar org-execute-file-search-functions nil
9556 "List of functions to execute a file search triggered by a link.
9558 Functions added to this hook must accept a single argument, the
9559 search string that was part of the file link, the part after the
9560 double colon. The function must first check if it would like to
9561 handle this search, for example by checking the `major-mode' or
9562 the file extension. If it decides not to handle this search, it
9563 should just return nil to give other functions a chance. If it
9564 does handle the search, it must return a non-nil value to keep
9565 other functions from trying.
9567 Each function can access the current prefix argument through the
9568 variable `current-prefix-argument'. Note that a single prefix is
9569 used to force opening a link in Emacs, so it may be good to only
9570 use a numeric or double prefix to guide the search function.
9572 In case this is needed, a function in this hook can also restore
9573 the window configuration before `org-open-at-point' was called using:
9575 (set-window-configuration org-window-config-before-follow-link)")
9577 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9578 (defun org-link-search (s &optional type avoid-pos)
9579 "Search for a link search option.
9580 If S is surrounded by forward slashes, it is interpreted as a
9581 regular expression. In org-mode files, this will create an `org-occur'
9582 sparse tree. In ordinary files, `occur' will be used to list matches.
9583 If the current buffer is in `dired-mode', grep will be used to search
9584 in all files. If AVOID-POS is given, ignore matches near that position."
9585 (let ((case-fold-search t)
9586 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9587 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9588 (append '(("") (" ") ("\t") ("\n"))
9589 org-emphasis-alist)
9590 "\\|") "\\)"))
9591 (pos (point))
9592 (pre nil) (post nil)
9593 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9594 (cond
9595 ;; First check if there are any special search functions
9596 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9597 ;; Now try the builtin stuff
9598 ((and (equal (string-to-char s0) ?#)
9599 (> (length s0) 1)
9600 (save-excursion
9601 (goto-char (point-min))
9602 (and
9603 (re-search-forward
9604 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9605 (setq type 'dedicated
9606 pos (match-beginning 0))))
9607 ;; There is an exact target for this
9608 (goto-char pos)
9609 (org-back-to-heading t)))
9610 ((save-excursion
9611 (goto-char (point-min))
9612 (and
9613 (re-search-forward
9614 (concat "<<" (regexp-quote s0) ">>") nil t)
9615 (setq type 'dedicated
9616 pos (match-beginning 0))))
9617 ;; There is an exact target for this
9618 (goto-char pos))
9619 ((and (string-match "^(\\(.*\\))$" s0)
9620 (save-excursion
9621 (goto-char (point-min))
9622 (and
9623 (re-search-forward
9624 (concat "[^[]" (regexp-quote
9625 (format org-coderef-label-format
9626 (match-string 1 s0))))
9627 nil t)
9628 (setq type 'dedicated
9629 pos (1+ (match-beginning 0))))))
9630 ;; There is a coderef target for this
9631 (goto-char pos))
9632 ((string-match "^/\\(.*\\)/$" s)
9633 ;; A regular expression
9634 (cond
9635 ((org-mode-p)
9636 (org-occur (match-string 1 s)))
9637 ;;((eq major-mode 'dired-mode)
9638 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9639 (t (org-do-occur (match-string 1 s)))))
9640 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9641 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9642 (goto-char (point-min))
9643 (cond
9644 ((let (case-fold-search)
9645 (re-search-forward (format org-complex-heading-regexp-format
9646 (regexp-quote s))
9647 nil t))
9648 ;; OK, found a match
9649 (setq type 'dedicated)
9650 (goto-char (match-beginning 0)))
9651 ((and (not org-link-search-inhibit-query)
9652 (eq org-link-search-must-match-exact-headline 'query-to-create)
9653 (y-or-n-p "No match - create this as a new heading? "))
9654 (goto-char (point-max))
9655 (or (bolp) (newline))
9656 (insert "* " s "\n")
9657 (beginning-of-line 0))
9659 (goto-char pos)
9660 (error "No match"))))
9662 ;; A normal search string
9663 (when (equal (string-to-char s) ?*)
9664 ;; Anchor on headlines, post may include tags.
9665 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9666 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9667 s (substring s 1)))
9668 (remove-text-properties
9669 0 (length s)
9670 '(face nil mouse-face nil keymap nil fontified nil) s)
9671 ;; Make a series of regular expressions to find a match
9672 (setq words (org-split-string s "[ \n\r\t]+")
9674 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9675 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9676 "\\)" markers)
9677 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9678 re2a (concat "[ \t\r\n]" re2a_)
9679 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9680 re4 (concat "[^a-zA-Z_]" re4_)
9682 re1 (concat pre re2 post)
9683 re3 (concat pre (if pre re4_ re4) post)
9684 re5 (concat pre ".*" re4)
9685 re2 (concat pre re2)
9686 re2a (concat pre (if pre re2a_ re2a))
9687 re4 (concat pre (if pre re4_ re4))
9688 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9689 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9690 re5 "\\)"
9692 (cond
9693 ((eq type 'org-occur) (org-occur reall))
9694 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9695 (t (goto-char (point-min))
9696 (setq type 'fuzzy)
9697 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9698 (org-search-not-self 1 re1 nil t)
9699 (org-search-not-self 1 re2 nil t)
9700 (org-search-not-self 1 re2a nil t)
9701 (org-search-not-self 1 re3 nil t)
9702 (org-search-not-self 1 re4 nil t)
9703 (org-search-not-self 1 re5 nil t)
9705 (goto-char (match-beginning 1))
9706 (goto-char pos)
9707 (error "No match"))))))
9708 (and (org-mode-p) (org-show-context 'link-search))
9709 type))
9711 (defun org-search-not-self (group &rest args)
9712 "Execute `re-search-forward', but only accept matches that do not
9713 enclose the position of `org-open-link-marker'."
9714 (let ((m org-open-link-marker))
9715 (catch 'exit
9716 (while (apply 're-search-forward args)
9717 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9718 (goto-char (match-end group))
9719 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9720 (> (match-beginning 0) (marker-position m))
9721 (< (match-end 0) (marker-position m)))
9722 (save-match-data
9723 (or (not (org-in-regexp
9724 org-bracket-link-analytic-regexp 1))
9725 (not (match-end 4)) ; no description
9726 (and (<= (match-beginning 4) (point))
9727 (>= (match-end 4) (point))))))
9728 (throw 'exit (point))))))))
9730 (defun org-get-buffer-for-internal-link (buffer)
9731 "Return a buffer to be used for displaying the link target of internal links."
9732 (cond
9733 ((not org-display-internal-link-with-indirect-buffer)
9734 buffer)
9735 ((string-match "(Clone)$" (buffer-name buffer))
9736 (message "Buffer is already a clone, not making another one")
9737 ;; we also do not modify visibility in this case
9738 buffer)
9739 (t ; make a new indirect buffer for displaying the link
9740 (let* ((bn (buffer-name buffer))
9741 (ibn (concat bn "(Clone)"))
9742 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9743 (with-current-buffer ib (org-overview))
9744 ib))))
9746 (defun org-do-occur (regexp &optional cleanup)
9747 "Call the Emacs command `occur'.
9748 If CLEANUP is non-nil, remove the printout of the regular expression
9749 in the *Occur* buffer. This is useful if the regex is long and not useful
9750 to read."
9751 (occur regexp)
9752 (when cleanup
9753 (let ((cwin (selected-window)) win beg end)
9754 (when (setq win (get-buffer-window "*Occur*"))
9755 (select-window win))
9756 (goto-char (point-min))
9757 (when (re-search-forward "match[a-z]+" nil t)
9758 (setq beg (match-end 0))
9759 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9760 (setq end (1- (match-beginning 0)))))
9761 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9762 (goto-char (point-min))
9763 (select-window cwin))))
9765 ;;; The mark ring for links jumps
9767 (defvar org-mark-ring nil
9768 "Mark ring for positions before jumps in Org-mode.")
9769 (defvar org-mark-ring-last-goto nil
9770 "Last position in the mark ring used to go back.")
9771 ;; Fill and close the ring
9772 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9773 (loop for i from 1 to org-mark-ring-length do
9774 (push (make-marker) org-mark-ring))
9775 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9776 org-mark-ring)
9778 (defun org-mark-ring-push (&optional pos buffer)
9779 "Put the current position or POS into the mark ring and rotate it."
9780 (interactive)
9781 (setq pos (or pos (point)))
9782 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9783 (move-marker (car org-mark-ring)
9784 (or pos (point))
9785 (or buffer (current-buffer)))
9786 (message "%s"
9787 (substitute-command-keys
9788 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9790 (defun org-mark-ring-goto (&optional n)
9791 "Jump to the previous position in the mark ring.
9792 With prefix arg N, jump back that many stored positions. When
9793 called several times in succession, walk through the entire ring.
9794 Org-mode commands jumping to a different position in the current file,
9795 or to another Org-mode file, automatically push the old position
9796 onto the ring."
9797 (interactive "p")
9798 (let (p m)
9799 (if (eq last-command this-command)
9800 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9801 (setq p org-mark-ring))
9802 (setq org-mark-ring-last-goto p)
9803 (setq m (car p))
9804 (switch-to-buffer (marker-buffer m))
9805 (goto-char m)
9806 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9808 (defun org-remove-angle-brackets (s)
9809 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9810 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9812 (defun org-add-angle-brackets (s)
9813 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9814 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9816 (defun org-remove-double-quotes (s)
9817 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9818 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9821 ;;; Following specific links
9823 (defun org-follow-timestamp-link ()
9824 (cond
9825 ((org-at-date-range-p t)
9826 (let ((org-agenda-start-on-weekday)
9827 (t1 (match-string 1))
9828 (t2 (match-string 2)))
9829 (setq t1 (time-to-days (org-time-string-to-time t1))
9830 t2 (time-to-days (org-time-string-to-time t2)))
9831 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9832 ((org-at-timestamp-p t)
9833 (org-agenda-list nil (time-to-days (org-time-string-to-time
9834 (substring (match-string 1) 0 10)))
9836 (t (error "This should not happen"))))
9839 ;;; Following file links
9840 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9841 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9842 (declare-function mailcap-mime-info
9843 "mailcap" (string &optional request no-decode))
9844 (defvar org-wait nil)
9845 (defun org-open-file (path &optional in-emacs line search)
9846 "Open the file at PATH.
9847 First, this expands any special file name abbreviations. Then the
9848 configuration variable `org-file-apps' is checked if it contains an
9849 entry for this file type, and if yes, the corresponding command is launched.
9851 If no application is found, Emacs simply visits the file.
9853 With optional prefix argument IN-EMACS, Emacs will visit the file.
9854 With a double \\[universal-argument] \\[universal-argument] \
9855 prefix arg, Org tries to avoid opening in Emacs
9856 and to use an external application to visit the file.
9858 Optional LINE specifies a line to go to, optional SEARCH a string
9859 to search for. If LINE or SEARCH is given, the file will be
9860 opened in Emacs, unless an entry from org-file-apps that makes
9861 use of groups in a regexp matches.
9862 If the file does not exist, an error is thrown."
9863 (let* ((file (if (equal path "")
9864 buffer-file-name
9865 (substitute-in-file-name (expand-file-name path))))
9866 (file-apps (append org-file-apps (org-default-apps)))
9867 (apps (org-remove-if
9868 'org-file-apps-entry-match-against-dlink-p file-apps))
9869 (apps-dlink (org-remove-if-not
9870 'org-file-apps-entry-match-against-dlink-p file-apps))
9871 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9872 (dirp (if remp nil (file-directory-p file)))
9873 (file (if (and dirp org-open-directory-means-index-dot-org)
9874 (concat (file-name-as-directory file) "index.org")
9875 file))
9876 (a-m-a-p (assq 'auto-mode apps))
9877 (dfile (downcase file))
9878 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9879 (link (cond ((and (eq line nil)
9880 (eq search nil))
9881 file)
9882 (line
9883 (concat file "::" (number-to-string line)))
9884 (search
9885 (concat file "::" search))))
9886 (dlink (downcase link))
9887 (old-buffer (current-buffer))
9888 (old-pos (point))
9889 (old-mode major-mode)
9890 ext cmd link-match-data)
9891 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9892 (setq ext (match-string 1 dfile))
9893 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9894 (setq ext (match-string 1 dfile))))
9895 (cond
9896 ((member in-emacs '((16) system))
9897 (setq cmd (cdr (assoc 'system apps))))
9898 (in-emacs (setq cmd 'emacs))
9900 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9901 (and dirp (cdr (assoc 'directory apps)))
9902 ; first, try matching against apps-dlink
9903 ; if we get a match here, store the match data for later
9904 (let ((match (assoc-default dlink apps-dlink
9905 'string-match)))
9906 (if match
9907 (progn (setq link-match-data (match-data))
9908 match)
9909 (progn (setq in-emacs (or in-emacs line search))
9910 nil))) ; if we have no match in apps-dlink,
9911 ; always open the file in emacs if line or search
9912 ; is given (for backwards compatibility)
9913 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9914 'string-match)
9915 (cdr (assoc ext apps))
9916 (cdr (assoc t apps))))))
9917 (when (eq cmd 'system)
9918 (setq cmd (cdr (assoc 'system apps))))
9919 (when (eq cmd 'default)
9920 (setq cmd (cdr (assoc t apps))))
9921 (when (eq cmd 'mailcap)
9922 (require 'mailcap)
9923 (mailcap-parse-mailcaps)
9924 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9925 (command (mailcap-mime-info mime-type)))
9926 (if (stringp command)
9927 (setq cmd command)
9928 (setq cmd 'emacs))))
9929 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9930 (not (file-exists-p file))
9931 (not org-open-non-existing-files))
9932 (error "No such file: %s" file))
9933 (cond
9934 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9935 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9936 (while (string-match "['\"]%s['\"]" cmd)
9937 (setq cmd (replace-match "%s" t t cmd)))
9938 (while (string-match "%s" cmd)
9939 (setq cmd (replace-match
9940 (save-match-data
9941 (shell-quote-argument
9942 (convert-standard-filename file)))
9943 t t cmd)))
9945 ;; Replace "%1", "%2" etc. in command with group matches from regex
9946 (save-match-data
9947 (let ((match-index 1)
9948 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9949 (set-match-data link-match-data)
9950 (while (<= match-index number-of-groups)
9951 (let ((regex (concat "%" (number-to-string match-index)))
9952 (replace-with (match-string match-index dlink)))
9953 (while (string-match regex cmd)
9954 (setq cmd (replace-match replace-with t t cmd))))
9955 (setq match-index (+ match-index 1)))))
9957 (save-window-excursion
9958 (start-process-shell-command cmd nil cmd)
9959 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9961 ((or (stringp cmd)
9962 (eq cmd 'emacs))
9963 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9964 (widen)
9965 (if line (org-goto-line line)
9966 (if search (org-link-search search))))
9967 ((consp cmd)
9968 (let ((file (convert-standard-filename file)))
9969 (save-match-data
9970 (set-match-data link-match-data)
9971 (eval cmd))))
9972 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9973 (and (org-mode-p) (eq old-mode 'org-mode)
9974 (or (not (equal old-buffer (current-buffer)))
9975 (not (equal old-pos (point))))
9976 (org-mark-ring-push old-pos old-buffer))))
9978 (defun org-file-apps-entry-match-against-dlink-p (entry)
9979 "This function returns non-nil if `entry' uses a regular
9980 expression which should be matched against the whole link by
9981 org-open-file.
9983 It assumes that is the case when the entry uses a regular
9984 expression which has at least one grouping construct and the
9985 action is either a lisp form or a command string containing
9986 '%1', i.e. using at least one subexpression match as a
9987 parameter."
9988 (let ((selector (car entry))
9989 (action (cdr entry)))
9990 (if (stringp selector)
9991 (and (> (regexp-opt-depth selector) 0)
9992 (or (and (stringp action)
9993 (string-match "%[0-9]" action))
9994 (consp action)))
9995 nil)))
9997 (defun org-default-apps ()
9998 "Return the default applications for this operating system."
9999 (cond
10000 ((eq system-type 'darwin)
10001 org-file-apps-defaults-macosx)
10002 ((eq system-type 'windows-nt)
10003 org-file-apps-defaults-windowsnt)
10004 (t org-file-apps-defaults-gnu)))
10006 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10007 "Convert extensions to regular expressions in the cars of LIST.
10008 Also, weed out any non-string entries, because the return value is used
10009 only for regexp matching.
10010 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10011 point to the symbol `emacs', indicating that the file should
10012 be opened in Emacs."
10013 (append
10014 (delq nil
10015 (mapcar (lambda (x)
10016 (if (not (stringp (car x)))
10018 (if (string-match "\\W" (car x))
10020 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10021 list))
10022 (if add-auto-mode
10023 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10025 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10026 (defun org-file-remote-p (file)
10027 "Test whether FILE specifies a location on a remote system.
10028 Return non-nil if the location is indeed remote.
10030 For example, the filename \"/user@host:/foo\" specifies a location
10031 on the system \"/user@host:\"."
10032 (cond ((fboundp 'file-remote-p)
10033 (file-remote-p file))
10034 ((fboundp 'tramp-handle-file-remote-p)
10035 (tramp-handle-file-remote-p file))
10036 ((and (boundp 'ange-ftp-name-format)
10037 (string-match (car ange-ftp-name-format) file))
10039 (t nil)))
10042 ;;;; Refiling
10044 (defun org-get-org-file ()
10045 "Read a filename, with default directory `org-directory'."
10046 (let ((default (or org-default-notes-file remember-data-file)))
10047 (read-file-name (format "File name [%s]: " default)
10048 (file-name-as-directory org-directory)
10049 default)))
10051 (defun org-notes-order-reversed-p ()
10052 "Check if the current file should receive notes in reversed order."
10053 (cond
10054 ((not org-reverse-note-order) nil)
10055 ((eq t org-reverse-note-order) t)
10056 ((not (listp org-reverse-note-order)) nil)
10057 (t (catch 'exit
10058 (let ((all org-reverse-note-order)
10059 entry)
10060 (while (setq entry (pop all))
10061 (if (string-match (car entry) buffer-file-name)
10062 (throw 'exit (cdr entry))))
10063 nil)))))
10065 (defvar org-refile-target-table nil
10066 "The list of refile targets, created by `org-refile'.")
10068 (defvar org-agenda-new-buffers nil
10069 "Buffers created to visit agenda files.")
10071 (defvar org-refile-cache nil
10072 "Cache for refile targets.")
10074 (defvar org-refile-markers nil
10075 "All the markers used for caching refile locations.")
10077 (defun org-refile-marker (pos)
10078 "Get a new refile marker, but only if caching is in use."
10079 (if (not org-refile-use-cache)
10081 (let ((m (make-marker)))
10082 (move-marker m pos)
10083 (push m org-refile-markers)
10084 m)))
10086 (defun org-refile-cache-clear ()
10087 "Clear the refile cache and disable all the markers."
10088 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10089 (setq org-refile-markers nil)
10090 (setq org-refile-cache nil)
10091 (message "Refile cache has been cleared"))
10093 (defun org-refile-cache-check-set (set)
10094 "Check if all the markers in the cache still have live buffers."
10095 (let (marker)
10096 (catch 'exit
10097 (while (and set (setq marker (nth 3 (pop set))))
10098 ;; if org-refile-use-outline-path is 'file, marker may be nil
10099 (when (and marker (null (marker-buffer marker)))
10100 (message "not found") (sit-for 3)
10101 (throw 'exit nil)))
10102 t)))
10104 (defun org-refile-cache-put (set &rest identifiers)
10105 "Push the refile targets SET into the cache, under IDENTIFIERS."
10106 (let* ((key (sha1 (prin1-to-string identifiers)))
10107 (entry (assoc key org-refile-cache)))
10108 (if entry
10109 (setcdr entry set)
10110 (push (cons key set) org-refile-cache))))
10112 (defun org-refile-cache-get (&rest identifiers)
10113 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10114 (cond
10115 ((not org-refile-cache) nil)
10116 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10118 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10119 org-refile-cache))))
10120 (and set (org-refile-cache-check-set set) set)))))
10122 (defun org-refile-get-targets (&optional default-buffer)
10123 "Produce a table with refile targets."
10124 (let ((case-fold-search nil)
10125 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10126 (entries (or org-refile-targets '((nil . (:level . 1)))))
10127 targets tgs txt re files f desc descre fast-path-p level pos0)
10128 (message "Getting targets...")
10129 (with-current-buffer (or default-buffer (current-buffer))
10130 (while (setq entry (pop entries))
10131 (setq files (car entry) desc (cdr entry))
10132 (setq fast-path-p nil)
10133 (cond
10134 ((null files) (setq files (list (current-buffer))))
10135 ((eq files 'org-agenda-files)
10136 (setq files (org-agenda-files 'unrestricted)))
10137 ((and (symbolp files) (fboundp files))
10138 (setq files (funcall files)))
10139 ((and (symbolp files) (boundp files))
10140 (setq files (symbol-value files))))
10141 (if (stringp files) (setq files (list files)))
10142 (cond
10143 ((eq (car desc) :tag)
10144 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10145 ((eq (car desc) :todo)
10146 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10147 ((eq (car desc) :regexp)
10148 (setq descre (cdr desc)))
10149 ((eq (car desc) :level)
10150 (setq descre (concat "^\\*\\{" (number-to-string
10151 (if org-odd-levels-only
10152 (1- (* 2 (cdr desc)))
10153 (cdr desc)))
10154 "\\}[ \t]")))
10155 ((eq (car desc) :maxlevel)
10156 (setq fast-path-p t)
10157 (setq descre (concat "^\\*\\{1," (number-to-string
10158 (if org-odd-levels-only
10159 (1- (* 2 (cdr desc)))
10160 (cdr desc)))
10161 "\\}[ \t]")))
10162 (t (error "Bad refiling target description %s" desc)))
10163 (while (setq f (pop files))
10164 (with-current-buffer
10165 (if (bufferp f) f (org-get-agenda-file-buffer f))
10167 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10168 (progn
10169 (if (bufferp f) (setq f (buffer-file-name
10170 (buffer-base-buffer f))))
10171 (setq f (and f (expand-file-name f)))
10172 (if (eq org-refile-use-outline-path 'file)
10173 (push (list (file-name-nondirectory f) f nil nil) tgs))
10174 (save-excursion
10175 (save-restriction
10176 (widen)
10177 (goto-char (point-min))
10178 (while (re-search-forward descre nil t)
10179 (goto-char (setq pos0 (point-at-bol)))
10180 (catch 'next
10181 (when org-refile-target-verify-function
10182 (save-match-data
10183 (or (funcall org-refile-target-verify-function)
10184 (throw 'next t))))
10185 (when (looking-at org-complex-heading-regexp)
10186 (setq level (org-reduced-level
10187 (- (match-end 1) (match-beginning 1)))
10188 txt (org-link-display-format (match-string 4))
10189 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10190 re (format org-complex-heading-regexp-format
10191 (regexp-quote (match-string 4))))
10192 (when org-refile-use-outline-path
10193 (setq txt (mapconcat
10194 'org-protect-slash
10195 (append
10196 (if (eq org-refile-use-outline-path
10197 'file)
10198 (list (file-name-nondirectory
10199 (buffer-file-name
10200 (buffer-base-buffer))))
10201 (if (eq org-refile-use-outline-path
10202 'full-file-path)
10203 (list (buffer-file-name
10204 (buffer-base-buffer)))))
10205 (org-get-outline-path fast-path-p
10206 level txt)
10207 (list txt))
10208 "/")))
10209 (push (list txt f re (org-refile-marker (point)))
10210 tgs)))
10211 (when (= (point) pos0)
10212 ;; verification function has not moved point
10213 (goto-char (point-at-eol))))))))
10214 (when org-refile-use-cache
10215 (org-refile-cache-put tgs (buffer-file-name) descre))
10216 (setq targets (append tgs targets))
10217 ))))
10218 (message "Getting targets...done")
10219 (nreverse targets)))
10221 (defun org-protect-slash (s)
10222 (while (string-match "/" s)
10223 (setq s (replace-match "\\" t t s)))
10226 (defvar org-olpa (make-vector 20 nil))
10228 (defun org-get-outline-path (&optional fastp level heading)
10229 "Return the outline path to the current entry, as a list.
10231 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10232 routine which makes outline path derivations for an entire file,
10233 avoiding backtracing. Refile target collection makes use of that."
10234 (if fastp
10235 (progn
10236 (if (> level 19)
10237 (error "Outline path failure, more than 19 levels"))
10238 (loop for i from level upto 19 do
10239 (aset org-olpa i nil))
10240 (prog1
10241 (delq nil (append org-olpa nil))
10242 (aset org-olpa level heading)))
10243 (let (rtn case-fold-search)
10244 (save-excursion
10245 (save-restriction
10246 (widen)
10247 (while (org-up-heading-safe)
10248 (when (looking-at org-complex-heading-regexp)
10249 (push (org-match-string-no-properties 4) rtn)))
10250 rtn)))))
10252 (defun org-format-outline-path (path &optional width prefix)
10253 "Format the outline path PATH for display.
10254 Width is the maximum number of characters that is available.
10255 Prefix is a prefix to be included in the returned string,
10256 such as the file name."
10257 (setq width (or width 79))
10258 (if prefix (setq width (- width (length prefix))))
10259 (if (not path)
10260 (or prefix "")
10261 (let* ((nsteps (length path))
10262 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10263 (maxwidth (if (<= total-width width)
10264 10000 ;; everything fits
10265 ;; we need to shorten the level headings
10266 (/ (- width nsteps) nsteps)))
10267 (org-odd-levels-only nil)
10268 (n 0)
10269 (total (1+ (length prefix))))
10270 (setq maxwidth (max maxwidth 10))
10271 (concat prefix
10272 (mapconcat
10273 (lambda (h)
10274 (setq n (1+ n))
10275 (if (and (= n nsteps) (< maxwidth 10000))
10276 (setq maxwidth (- total-width total)))
10277 (if (< (length h) maxwidth)
10278 (progn (setq total (+ total (length h) 1)) h)
10279 (setq h (substring h 0 (- maxwidth 2))
10280 total (+ total maxwidth 1))
10281 (if (string-match "[ \t]+\\'" h)
10282 (setq h (substring h 0 (match-beginning 0))))
10283 (setq h (concat h "..")))
10284 (org-add-props h nil 'face
10285 (nth (% (1- n) org-n-level-faces)
10286 org-level-faces))
10288 path "/")))))
10290 (defun org-display-outline-path (&optional file current)
10291 "Display the current outline path in the echo area."
10292 (interactive "P")
10293 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10294 (case-fold-search nil)
10295 (path (and (org-mode-p) (org-get-outline-path))))
10296 (if current (setq path (append path
10297 (save-excursion
10298 (org-back-to-heading t)
10299 (if (looking-at org-complex-heading-regexp)
10300 (list (match-string 4)))))))
10301 (message "%s"
10302 (org-format-outline-path
10303 path
10304 (1- (frame-width))
10305 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10307 (defvar org-refile-history nil
10308 "History for refiling operations.")
10310 (defvar org-after-refile-insert-hook nil
10311 "Hook run after `org-refile' has inserted its stuff at the new location.
10312 Note that this is still *before* the stuff will be removed from
10313 the *old* location.")
10315 (defvar org-capture-last-stored-marker)
10316 (defun org-refile (&optional goto default-buffer rfloc)
10317 "Move the entry at point to another heading.
10318 The list of target headings is compiled using the information in
10319 `org-refile-targets', which see. This list is created before each use
10320 and will therefore always be up-to-date.
10322 At the target location, the entry is filed as a subitem of the target heading.
10323 Depending on `org-reverse-note-order', the new subitem will either be the
10324 first or the last subitem.
10326 If there is an active region, all entries in that region will be moved.
10327 However, the region must fulfill the requirement that the first heading
10328 is the first one sets the top-level of the moved text - at most siblings
10329 below it are allowed.
10331 With prefix arg GOTO, the command will only visit the target location,
10332 not actually move anything.
10333 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10334 go to the location where the last refiling
10335 operation has put the subtree.
10336 With a prefix argument of `2', refile to the running clock.
10338 RFLOC can be a refile location obtained in a different way.
10340 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10342 If you are using target caching (see `org-refile-use-cache'),
10343 You have to clear the target cache in order to find new targets.
10344 This can be done with a 0 prefix: `C-0 C-c C-w'"
10345 (interactive "P")
10346 (if (member goto '(0 (64)))
10347 (org-refile-cache-clear)
10348 (let* ((cbuf (current-buffer))
10349 (regionp (org-region-active-p))
10350 (region-start (and regionp (region-beginning)))
10351 (region-end (and regionp (region-end)))
10352 (region-length (and regionp (- region-end region-start)))
10353 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10354 pos it nbuf file re level reversed)
10355 (setq last-command nil)
10356 (when regionp
10357 (goto-char region-start)
10358 (or (bolp) (goto-char (point-at-bol)))
10359 (setq region-start (point))
10360 (unless (org-kill-is-subtree-p
10361 (buffer-substring region-start region-end))
10362 (error "The region is not a (sequence of) subtree(s)")))
10363 (if (equal goto '(16))
10364 (org-refile-goto-last-stored)
10365 (when (or
10366 (and (equal goto 2)
10367 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10368 (prog1
10369 (setq it (list (or org-clock-heading "running clock")
10370 (buffer-file-name
10371 (marker-buffer org-clock-hd-marker))
10373 (marker-position org-clock-hd-marker)))
10374 (setq goto nil)))
10375 (setq it (or rfloc
10376 (save-excursion
10377 (org-refile-get-location
10378 (if goto "Goto" "Refile to") default-buffer
10379 org-refile-allow-creating-parent-nodes)))))
10380 (setq file (nth 1 it)
10381 re (nth 2 it)
10382 pos (nth 3 it))
10383 (if (and (not goto)
10385 (equal (buffer-file-name) file)
10386 (if regionp
10387 (and (>= pos region-start)
10388 (<= pos region-end))
10389 (and (>= pos (point))
10390 (< pos (save-excursion
10391 (org-end-of-subtree t t))))))
10392 (error "Cannot refile to position inside the tree or region"))
10394 (setq nbuf (or (find-buffer-visiting file)
10395 (find-file-noselect file)))
10396 (if goto
10397 (progn
10398 (switch-to-buffer nbuf)
10399 (goto-char pos)
10400 (org-show-context 'org-goto))
10401 (if regionp
10402 (progn
10403 (org-kill-new (buffer-substring region-start region-end))
10404 (org-save-markers-in-region region-start region-end))
10405 (org-copy-subtree 1 nil t))
10406 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10407 (find-file-noselect file)))
10408 (setq reversed (org-notes-order-reversed-p))
10409 (save-excursion
10410 (save-restriction
10411 (widen)
10412 (if pos
10413 (progn
10414 (goto-char pos)
10415 (looking-at outline-regexp)
10416 (setq level (org-get-valid-level (funcall outline-level) 1))
10417 (goto-char
10418 (if reversed
10419 (or (outline-next-heading) (point-max))
10420 (or (save-excursion (org-get-next-sibling))
10421 (org-end-of-subtree t t)
10422 (point-max)))))
10423 (setq level 1)
10424 (if (not reversed)
10425 (goto-char (point-max))
10426 (goto-char (point-min))
10427 (or (outline-next-heading) (goto-char (point-max)))))
10428 (if (not (bolp)) (newline))
10429 (org-paste-subtree level)
10430 (when org-log-refile
10431 (org-add-log-setup 'refile nil nil 'findpos
10432 org-log-refile)
10433 (unless (eq org-log-refile 'note)
10434 (save-excursion (org-add-log-note))))
10435 (and org-auto-align-tags (org-set-tags nil t))
10436 (bookmark-set "org-refile-last-stored")
10437 ;; If we are refiling for capture, make sure that the
10438 ;; last-capture pointers point here
10439 (when (org-bound-and-true-p org-refile-for-capture)
10440 (bookmark-set "org-capture-last-stored-marker")
10441 (move-marker org-capture-last-stored-marker (point)))
10442 (if (fboundp 'deactivate-mark) (deactivate-mark))
10443 (run-hooks 'org-after-refile-insert-hook))))
10444 (if regionp
10445 (delete-region (point) (+ (point) region-length))
10446 (org-cut-subtree))
10447 (when (featurep 'org-inlinetask)
10448 (org-inlinetask-remove-END-maybe))
10449 (setq org-markers-to-move nil)
10450 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10452 (defun org-refile-goto-last-stored ()
10453 "Go to the location where the last refile was stored."
10454 (interactive)
10455 (bookmark-jump "org-refile-last-stored")
10456 (message "This is the location of the last refile"))
10458 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10459 "Prompt the user for a refile location, using PROMPT.
10460 PROMPT should not be suffixed with a colon and a space, because
10461 this function appends the default value from
10462 `org-refile-history' automatically, if that is not empty."
10463 (let ((org-refile-targets org-refile-targets)
10464 (org-refile-use-outline-path org-refile-use-outline-path))
10465 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10466 (unless org-refile-target-table
10467 (error "No refile targets"))
10468 (let* ((prompt (concat prompt
10469 (and (car org-refile-history)
10470 (concat " (default " (car org-refile-history) ")"))
10471 ": "))
10472 (cbuf (current-buffer))
10473 (partial-completion-mode nil)
10474 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10475 (cfunc (if (and org-refile-use-outline-path
10476 org-outline-path-complete-in-steps)
10477 'org-olpath-completing-read
10478 'org-icompleting-read))
10479 (extra (if org-refile-use-outline-path "/" ""))
10480 (filename (and cfn (expand-file-name cfn)))
10481 (tbl (mapcar
10482 (lambda (x)
10483 (if (and (not (member org-refile-use-outline-path
10484 '(file full-file-path)))
10485 (not (equal filename (nth 1 x))))
10486 (cons (concat (car x) extra " ("
10487 (file-name-nondirectory (nth 1 x)) ")")
10488 (cdr x))
10489 (cons (concat (car x) extra) (cdr x))))
10490 org-refile-target-table))
10491 (completion-ignore-case t)
10492 pa answ parent-target child parent old-hist)
10493 (setq old-hist org-refile-history)
10494 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10495 nil 'org-refile-history (car org-refile-history)))
10496 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10497 (org-refile-check-position pa)
10498 (if pa
10499 (progn
10500 (when (or (not org-refile-history)
10501 (not (eq old-hist org-refile-history))
10502 (not (equal (car pa) (car org-refile-history))))
10503 (setq org-refile-history
10504 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10505 org-refile-history
10506 (cdr org-refile-history))))
10507 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10508 (pop org-refile-history)))
10510 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10511 (progn
10512 (setq parent (match-string 1 answ)
10513 child (match-string 2 answ))
10514 (setq parent-target (or (assoc parent tbl)
10515 (assoc (concat parent "/") tbl)))
10516 (when (and parent-target
10517 (or (eq new-nodes t)
10518 (and (eq new-nodes 'confirm)
10519 (y-or-n-p (format "Create new node \"%s\"? "
10520 child)))))
10521 (org-refile-new-child parent-target child)))
10522 (error "Invalid target location")))))
10524 (defun org-refile-check-position (refile-pointer)
10525 "Check if the refile pointer matches the readline to which it points."
10526 (let* ((file (nth 1 refile-pointer))
10527 (re (nth 2 refile-pointer))
10528 (pos (nth 3 refile-pointer))
10529 buffer)
10530 (when (org-string-nw-p re)
10531 (setq buffer (if (markerp pos)
10532 (marker-buffer pos)
10533 (or (find-buffer-visiting file)
10534 (find-file-noselect file))))
10535 (with-current-buffer buffer
10536 (save-excursion
10537 (save-restriction
10538 (widen)
10539 (goto-char pos)
10540 (beginning-of-line 1)
10541 (unless (org-looking-at-p re)
10542 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10544 (defun org-refile-new-child (parent-target child)
10545 "Use refile target PARENT-TARGET to add new CHILD below it."
10546 (unless parent-target
10547 (error "Cannot find parent for new node"))
10548 (let ((file (nth 1 parent-target))
10549 (pos (nth 3 parent-target))
10550 level)
10551 (with-current-buffer (or (find-buffer-visiting file)
10552 (find-file-noselect file))
10553 (save-excursion
10554 (save-restriction
10555 (widen)
10556 (if pos
10557 (goto-char pos)
10558 (goto-char (point-max))
10559 (if (not (bolp)) (newline)))
10560 (when (looking-at outline-regexp)
10561 (setq level (funcall outline-level))
10562 (org-end-of-subtree t t))
10563 (org-back-over-empty-lines)
10564 (insert "\n" (make-string
10565 (if pos (org-get-valid-level level 1) 1) ?*)
10566 " " child "\n")
10567 (beginning-of-line 0)
10568 (list (concat (car parent-target) "/" child) file "" (point)))))))
10570 (defun org-olpath-completing-read (prompt collection &rest args)
10571 "Read an outline path like a file name."
10572 (let ((thetable collection)
10573 (org-completion-use-ido nil) ; does not work with ido.
10574 (org-completion-use-iswitchb nil)) ; or iswitchb
10575 (apply
10576 'org-icompleting-read prompt
10577 (lambda (string predicate &optional flag)
10578 (let (rtn r f (l (length string)))
10579 (cond
10580 ((eq flag nil)
10581 ;; try completion
10582 (try-completion string thetable))
10583 ((eq flag t)
10584 ;; all-completions
10585 (setq rtn (all-completions string thetable predicate))
10586 (mapcar
10587 (lambda (x)
10588 (setq r (substring x l))
10589 (if (string-match " ([^)]*)$" x)
10590 (setq f (match-string 0 x))
10591 (setq f ""))
10592 (if (string-match "/" r)
10593 (concat string (substring r 0 (match-end 0)) f)
10595 rtn))
10596 ((eq flag 'lambda)
10597 ;; exact match?
10598 (assoc string thetable)))
10600 args)))
10602 ;;;; Dynamic blocks
10604 (defun org-find-dblock (name)
10605 "Find the first dynamic block with name NAME in the buffer.
10606 If not found, stay at current position and return nil."
10607 (let (pos)
10608 (save-excursion
10609 (goto-char (point-min))
10610 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10611 nil t)
10612 (match-beginning 0))))
10613 (if pos (goto-char pos))
10614 pos))
10616 (defconst org-dblock-start-re
10617 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10618 "Matches the start line of a dynamic block, with parameters.")
10620 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10621 "Matches the end of a dynamic block.")
10623 (defun org-create-dblock (plist)
10624 "Create a dynamic block section, with parameters taken from PLIST.
10625 PLIST must contain a :name entry which is used as name of the block."
10626 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10627 (end-of-line 1)
10628 (newline))
10629 (let ((col (current-column))
10630 (name (plist-get plist :name)))
10631 (insert "#+BEGIN: " name)
10632 (while plist
10633 (if (eq (car plist) :name)
10634 (setq plist (cddr plist))
10635 (insert " " (prin1-to-string (pop plist)))))
10636 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10637 (beginning-of-line -2)))
10639 (defun org-prepare-dblock ()
10640 "Prepare dynamic block for refresh.
10641 This empties the block, puts the cursor at the insert position and returns
10642 the property list including an extra property :name with the block name."
10643 (unless (looking-at org-dblock-start-re)
10644 (error "Not at a dynamic block"))
10645 (let* ((begdel (1+ (match-end 0)))
10646 (name (org-no-properties (match-string 1)))
10647 (params (append (list :name name)
10648 (read (concat "(" (match-string 3) ")")))))
10649 (save-excursion
10650 (beginning-of-line 1)
10651 (skip-chars-forward " \t")
10652 (setq params (plist-put params :indentation-column (current-column))))
10653 (unless (re-search-forward org-dblock-end-re nil t)
10654 (error "Dynamic block not terminated"))
10655 (setq params
10656 (append params
10657 (list :content (buffer-substring
10658 begdel (match-beginning 0)))))
10659 (delete-region begdel (match-beginning 0))
10660 (goto-char begdel)
10661 (open-line 1)
10662 params))
10664 (defun org-map-dblocks (&optional command)
10665 "Apply COMMAND to all dynamic blocks in the current buffer.
10666 If COMMAND is not given, use `org-update-dblock'."
10667 (let ((cmd (or command 'org-update-dblock)))
10668 (save-excursion
10669 (goto-char (point-min))
10670 (while (re-search-forward org-dblock-start-re nil t)
10671 (goto-char (match-beginning 0))
10672 (save-excursion
10673 (condition-case nil
10674 (funcall cmd)
10675 (error (message "Error during update of dynamic block"))))
10676 (unless (re-search-forward org-dblock-end-re nil t)
10677 (error "Dynamic block not terminated"))))))
10679 (defun org-dblock-update (&optional arg)
10680 "User command for updating dynamic blocks.
10681 Update the dynamic block at point. With prefix ARG, update all dynamic
10682 blocks in the buffer."
10683 (interactive "P")
10684 (if arg
10685 (org-update-all-dblocks)
10686 (or (looking-at org-dblock-start-re)
10687 (org-beginning-of-dblock))
10688 (org-update-dblock)))
10690 (defun org-update-dblock ()
10691 "Update the dynamic block at point.
10692 This means to empty the block, parse for parameters and then call
10693 the correct writing function."
10694 (interactive)
10695 (save-window-excursion
10696 (let* ((pos (point))
10697 (line (org-current-line))
10698 (params (org-prepare-dblock))
10699 (name (plist-get params :name))
10700 (indent (plist-get params :indentation-column))
10701 (cmd (intern (concat "org-dblock-write:" name))))
10702 (message "Updating dynamic block `%s' at line %d..." name line)
10703 (funcall cmd params)
10704 (message "Updating dynamic block `%s' at line %d...done" name line)
10705 (goto-char pos)
10706 (when (and indent (> indent 0))
10707 (setq indent (make-string indent ?\ ))
10708 (save-excursion
10709 (org-beginning-of-dblock)
10710 (forward-line 1)
10711 (while (not (looking-at org-dblock-end-re))
10712 (insert indent)
10713 (beginning-of-line 2))
10714 (when (looking-at org-dblock-end-re)
10715 (and (looking-at "[ \t]+")
10716 (replace-match ""))
10717 (insert indent)))))))
10719 (defun org-beginning-of-dblock ()
10720 "Find the beginning of the dynamic block at point.
10721 Error if there is no such block at point."
10722 (let ((pos (point))
10723 beg)
10724 (end-of-line 1)
10725 (if (and (re-search-backward org-dblock-start-re nil t)
10726 (setq beg (match-beginning 0))
10727 (re-search-forward org-dblock-end-re nil t)
10728 (> (match-end 0) pos))
10729 (goto-char beg)
10730 (goto-char pos)
10731 (error "Not in a dynamic block"))))
10733 (defun org-update-all-dblocks ()
10734 "Update all dynamic blocks in the buffer.
10735 This function can be used in a hook."
10736 (interactive)
10737 (when (org-mode-p)
10738 (org-map-dblocks 'org-update-dblock)))
10741 ;;;; Completion
10743 (defconst org-additional-option-like-keywords
10744 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10745 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10746 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10747 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10748 "BEGIN:" "END:"
10749 "ORGTBL" "TBLFM:" "TBLNAME:"
10750 "BEGIN_EXAMPLE" "END_EXAMPLE"
10751 "BEGIN_QUOTE" "END_QUOTE"
10752 "BEGIN_VERSE" "END_VERSE"
10753 "BEGIN_CENTER" "END_CENTER"
10754 "BEGIN_SRC" "END_SRC"
10755 "BEGIN_RESULT" "END_RESULT"
10756 "SOURCE:" "SRCNAME:" "FUNCTION:"
10757 "RESULTS:"
10758 "HEADER:" "HEADERS:"
10759 "BABEL:"
10760 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10761 "CAPTION:" "LABEL:"
10762 "SETUPFILE:"
10763 "INCLUDE:"
10764 "BIND:"
10765 "MACRO:"))
10767 (defcustom org-structure-template-alist
10769 ("s" "#+begin_src ?\n\n#+end_src"
10770 "<src lang=\"?\">\n\n</src>")
10771 ("e" "#+begin_example\n?\n#+end_example"
10772 "<example>\n?\n</example>")
10773 ("q" "#+begin_quote\n?\n#+end_quote"
10774 "<quote>\n?\n</quote>")
10775 ("v" "#+begin_verse\n?\n#+end_verse"
10776 "<verse>\n?\n/verse>")
10777 ("c" "#+begin_center\n?\n#+end_center"
10778 "<center>\n?\n/center>")
10779 ("l" "#+begin_latex\n?\n#+end_latex"
10780 "<literal style=\"latex\">\n?\n</literal>")
10781 ("L" "#+latex: "
10782 "<literal style=\"latex\">?</literal>")
10783 ("h" "#+begin_html\n?\n#+end_html"
10784 "<literal style=\"html\">\n?\n</literal>")
10785 ("H" "#+html: "
10786 "<literal style=\"html\">?</literal>")
10787 ("a" "#+begin_ascii\n?\n#+end_ascii")
10788 ("A" "#+ascii: ")
10789 ("i" "#+index: ?"
10790 "#+index: ?")
10791 ("I" "#+include %file ?"
10792 "<include file=%file markup=\"?\">")
10794 "Structure completion elements.
10795 This is a list of abbreviation keys and values. The value gets inserted
10796 if you type `<' followed by the key and then press the completion key,
10797 usually `M-TAB'. %file will be replaced by a file name after prompting
10798 for the file using completion. The cursor will be placed at the position
10799 of the `?` in the template.
10800 There are two templates for each key, the first uses the original Org syntax,
10801 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10802 the default when the /org-mtags.el/ module has been loaded. See also the
10803 variable `org-mtags-prefer-muse-templates'.
10804 This is an experimental feature, it is undecided if it is going to stay in."
10805 :group 'org-completion
10806 :type '(repeat
10807 (string :tag "Key")
10808 (string :tag "Template")
10809 (string :tag "Muse Template")))
10811 (defun org-try-structure-completion ()
10812 "Try to complete a structure template before point.
10813 This looks for strings like \"<e\" on an otherwise empty line and
10814 expands them."
10815 (let ((l (buffer-substring (point-at-bol) (point)))
10817 (when (and (looking-at "[ \t]*$")
10818 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10819 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10820 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10821 (match-beginning 1)) a)
10822 t)))
10824 (defun org-complete-expand-structure-template (start cell)
10825 "Expand a structure template."
10826 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10827 (rpl (nth (if musep 2 1) cell))
10828 (ind ""))
10829 (delete-region start (point))
10830 (when (string-match "\\`#\\+" rpl)
10831 (cond
10832 ((bolp))
10833 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10834 (setq ind (buffer-substring (point-at-bol) (point))))
10835 (t (newline))))
10836 (setq start (point))
10837 (if (string-match "%file" rpl)
10838 (setq rpl (replace-match
10839 (concat
10840 "\""
10841 (save-match-data
10842 (abbreviate-file-name (read-file-name "Include file: ")))
10843 "\"")
10844 t t rpl)))
10845 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10846 (concat "\n" ind)))
10847 (insert rpl)
10848 (if (re-search-backward "\\?" start t) (delete-char 1))))
10850 ;;;; TODO, DEADLINE, Comments
10852 (defun org-toggle-comment ()
10853 "Change the COMMENT state of an entry."
10854 (interactive)
10855 (save-excursion
10856 (org-back-to-heading)
10857 (let (case-fold-search)
10858 (if (looking-at (concat outline-regexp
10859 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10860 (replace-match "" t t nil 1)
10861 (if (looking-at outline-regexp)
10862 (progn
10863 (goto-char (match-end 0))
10864 (insert org-comment-string " ")))))))
10866 (defvar org-last-todo-state-is-todo nil
10867 "This is non-nil when the last TODO state change led to a TODO state.
10868 If the last change removed the TODO tag or switched to DONE, then
10869 this is nil.")
10871 (defvar org-setting-tags nil) ; dynamically skipped
10873 (defvar org-todo-setup-filter-hook nil
10874 "Hook for functions that pre-filter todo specs.
10875 Each function takes a todo spec and returns either nil or the spec
10876 transformed into canonical form." )
10878 (defvar org-todo-get-default-hook nil
10879 "Hook for functions that get a default item for todo.
10880 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10881 nil or a string to be used for the todo mark." )
10883 (defvar org-agenda-headline-snapshot-before-repeat)
10885 (defun org-todo (&optional arg)
10886 "Change the TODO state of an item.
10887 The state of an item is given by a keyword at the start of the heading,
10888 like
10889 *** TODO Write paper
10890 *** DONE Call mom
10892 The different keywords are specified in the variable `org-todo-keywords'.
10893 By default the available states are \"TODO\" and \"DONE\".
10894 So for this example: when the item starts with TODO, it is changed to DONE.
10895 When it starts with DONE, the DONE is removed. And when neither TODO nor
10896 DONE are present, add TODO at the beginning of the heading.
10898 With \\[universal-argument] prefix arg, use completion to determine the new \
10899 state.
10900 With numeric prefix arg, switch to that state.
10901 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10902 keywords (nextset).
10903 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10905 For calling through lisp, arg is also interpreted in the following way:
10906 'none -> empty state
10907 \"\"(empty string) -> switch to empty state
10908 'done -> switch to DONE
10909 'nextset -> switch to the next set of keywords
10910 'previousset -> switch to the previous set of keywords
10911 \"WAITING\" -> switch to the specified keyword, but only if it
10912 really is a member of `org-todo-keywords'."
10913 (interactive "P")
10914 (if (equal arg '(16)) (setq arg 'nextset))
10915 (let ((org-blocker-hook org-blocker-hook)
10916 (case-fold-search nil))
10917 (when (equal arg '(64))
10918 (setq arg nil org-blocker-hook nil))
10919 (when (and org-blocker-hook
10920 (or org-inhibit-blocking
10921 (org-entry-get nil "NOBLOCKING")))
10922 (setq org-blocker-hook nil))
10923 (save-excursion
10924 (catch 'exit
10925 (org-back-to-heading t)
10926 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10927 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10928 (looking-at " *"))
10929 (let* ((match-data (match-data))
10930 (startpos (point-at-bol))
10931 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10932 (org-log-done org-log-done)
10933 (org-log-repeat org-log-repeat)
10934 (org-todo-log-states org-todo-log-states)
10935 (this (match-string 1))
10936 (hl-pos (match-beginning 0))
10937 (head (org-get-todo-sequence-head this))
10938 (ass (assoc head org-todo-kwd-alist))
10939 (interpret (nth 1 ass))
10940 (done-word (nth 3 ass))
10941 (final-done-word (nth 4 ass))
10942 (last-state (or this ""))
10943 (completion-ignore-case t)
10944 (member (member this org-todo-keywords-1))
10945 (tail (cdr member))
10946 (state (cond
10947 ((and org-todo-key-trigger
10948 (or (and (equal arg '(4))
10949 (eq org-use-fast-todo-selection 'prefix))
10950 (and (not arg) org-use-fast-todo-selection
10951 (not (eq org-use-fast-todo-selection
10952 'prefix)))))
10953 ;; Use fast selection
10954 (org-fast-todo-selection))
10955 ((and (equal arg '(4))
10956 (or (not org-use-fast-todo-selection)
10957 (not org-todo-key-trigger)))
10958 ;; Read a state with completion
10959 (org-icompleting-read
10960 "State: " (mapcar (lambda(x) (list x))
10961 org-todo-keywords-1)
10962 nil t))
10963 ((eq arg 'right)
10964 (if this
10965 (if tail (car tail) nil)
10966 (car org-todo-keywords-1)))
10967 ((eq arg 'left)
10968 (if (equal member org-todo-keywords-1)
10970 (if this
10971 (nth (- (length org-todo-keywords-1)
10972 (length tail) 2)
10973 org-todo-keywords-1)
10974 (org-last org-todo-keywords-1))))
10975 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10976 (setq arg nil))) ; hack to fall back to cycling
10977 (arg
10978 ;; user or caller requests a specific state
10979 (cond
10980 ((equal arg "") nil)
10981 ((eq arg 'none) nil)
10982 ((eq arg 'done) (or done-word (car org-done-keywords)))
10983 ((eq arg 'nextset)
10984 (or (car (cdr (member head org-todo-heads)))
10985 (car org-todo-heads)))
10986 ((eq arg 'previousset)
10987 (let ((org-todo-heads (reverse org-todo-heads)))
10988 (or (car (cdr (member head org-todo-heads)))
10989 (car org-todo-heads))))
10990 ((car (member arg org-todo-keywords-1)))
10991 ((stringp arg)
10992 (error "State `%s' not valid in this file" arg))
10993 ((nth (1- (prefix-numeric-value arg))
10994 org-todo-keywords-1))))
10995 ((null member) (or head (car org-todo-keywords-1)))
10996 ((equal this final-done-word) nil) ;; -> make empty
10997 ((null tail) nil) ;; -> first entry
10998 ((memq interpret '(type priority))
10999 (if (eq this-command last-command)
11000 (car tail)
11001 (if (> (length tail) 0)
11002 (or done-word (car org-done-keywords))
11003 nil)))
11005 (car tail))))
11006 (state (or
11007 (run-hook-with-args-until-success
11008 'org-todo-get-default-hook state last-state)
11009 state))
11010 (next (if state (concat " " state " ") " "))
11011 (change-plist (list :type 'todo-state-change :from this :to state
11012 :position startpos))
11013 dolog now-done-p)
11014 (when org-blocker-hook
11015 (setq org-last-todo-state-is-todo
11016 (not (member this org-done-keywords)))
11017 (unless (save-excursion
11018 (save-match-data
11019 (org-with-wide-buffer
11020 (run-hook-with-args-until-failure
11021 'org-blocker-hook change-plist))))
11022 (if (org-called-interactively-p 'interactive)
11023 (error "TODO state change from %s to %s blocked" this state)
11024 ;; fail silently
11025 (message "TODO state change from %s to %s blocked" this state)
11026 (throw 'exit nil))))
11027 (store-match-data match-data)
11028 (replace-match next t t)
11029 (unless (pos-visible-in-window-p hl-pos)
11030 (message "TODO state changed to %s" (org-trim next)))
11031 (unless head
11032 (setq head (org-get-todo-sequence-head state)
11033 ass (assoc head org-todo-kwd-alist)
11034 interpret (nth 1 ass)
11035 done-word (nth 3 ass)
11036 final-done-word (nth 4 ass)))
11037 (when (memq arg '(nextset previousset))
11038 (message "Keyword-Set %d/%d: %s"
11039 (- (length org-todo-sets) -1
11040 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11041 (length org-todo-sets)
11042 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11043 (setq org-last-todo-state-is-todo
11044 (not (member state org-done-keywords)))
11045 (setq now-done-p (and (member state org-done-keywords)
11046 (not (member this org-done-keywords))))
11047 (and logging (org-local-logging logging))
11048 (when (and (or org-todo-log-states org-log-done)
11049 (not (eq org-inhibit-logging t))
11050 (not (memq arg '(nextset previousset))))
11051 ;; we need to look at recording a time and note
11052 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11053 (nth 2 (assoc this org-todo-log-states))))
11054 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11055 (setq dolog 'time))
11056 (when (and state
11057 (member state org-not-done-keywords)
11058 (not (member this org-not-done-keywords)))
11059 ;; This is now a todo state and was not one before
11060 ;; If there was a CLOSED time stamp, get rid of it.
11061 (org-add-planning-info nil nil 'closed))
11062 (when (and now-done-p org-log-done)
11063 ;; It is now done, and it was not done before
11064 (org-add-planning-info 'closed (org-current-time))
11065 (if (and (not dolog) (eq 'note org-log-done))
11066 (org-add-log-setup 'done state this 'findpos 'note)))
11067 (when (and state dolog)
11068 ;; This is a non-nil state, and we need to log it
11069 (org-add-log-setup 'state state this 'findpos dolog)))
11070 ;; Fixup tag positioning
11071 (org-todo-trigger-tag-changes state)
11072 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11073 (when org-provide-todo-statistics
11074 (org-update-parent-todo-statistics))
11075 (run-hooks 'org-after-todo-state-change-hook)
11076 (if (and arg (not (member state org-done-keywords)))
11077 (setq head (org-get-todo-sequence-head state)))
11078 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11079 ;; Do we need to trigger a repeat?
11080 (when now-done-p
11081 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11082 ;; This is for the agenda, take a snapshot of the headline.
11083 (save-match-data
11084 (setq org-agenda-headline-snapshot-before-repeat
11085 (org-get-heading))))
11086 (org-auto-repeat-maybe state))
11087 ;; Fixup cursor location if close to the keyword
11088 (if (and (outline-on-heading-p)
11089 (not (bolp))
11090 (save-excursion (beginning-of-line 1)
11091 (looking-at org-todo-line-regexp))
11092 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11093 (progn
11094 (goto-char (or (match-end 2) (match-end 1)))
11095 (and (looking-at " ") (just-one-space))))
11096 (when org-trigger-hook
11097 (save-excursion
11098 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11100 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11101 "Block turning an entry into a TODO, using the hierarchy.
11102 This checks whether the current task should be blocked from state
11103 changes. Such blocking occurs when:
11105 1. The task has children which are not all in a completed state.
11107 2. A task has a parent with the property :ORDERED:, and there
11108 are siblings prior to the current task with incomplete
11109 status.
11111 3. The parent of the task is blocked because it has siblings that should
11112 be done first, or is child of a block grandparent TODO entry."
11114 (if (not org-enforce-todo-dependencies)
11115 t ; if locally turned off don't block
11116 (catch 'dont-block
11117 ;; If this is not a todo state change, or if this entry is already DONE,
11118 ;; do not block
11119 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11120 (member (plist-get change-plist :from)
11121 (cons 'done org-done-keywords))
11122 (member (plist-get change-plist :to)
11123 (cons 'todo org-not-done-keywords))
11124 (not (plist-get change-plist :to)))
11125 (throw 'dont-block t))
11126 ;; If this task has children, and any are undone, it's blocked
11127 (save-excursion
11128 (org-back-to-heading t)
11129 (let ((this-level (funcall outline-level)))
11130 (outline-next-heading)
11131 (let ((child-level (funcall outline-level)))
11132 (while (and (not (eobp))
11133 (> child-level this-level))
11134 ;; this todo has children, check whether they are all
11135 ;; completed
11136 (if (and (not (org-entry-is-done-p))
11137 (org-entry-is-todo-p))
11138 (throw 'dont-block nil))
11139 (outline-next-heading)
11140 (setq child-level (funcall outline-level))))))
11141 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11142 ;; any previous siblings are undone, it's blocked
11143 (save-excursion
11144 (org-back-to-heading t)
11145 (let* ((pos (point))
11146 (parent-pos (and (org-up-heading-safe) (point))))
11147 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11148 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11149 (forward-line 1)
11150 (re-search-forward org-not-done-heading-regexp pos t))
11151 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11152 ;; Search further up the hierarchy, to see if an anchestor is blocked
11153 (while t
11154 (goto-char parent-pos)
11155 (if (not (looking-at org-not-done-heading-regexp))
11156 (throw 'dont-block t)) ; do not block, parent is not a TODO
11157 (setq pos (point))
11158 (setq parent-pos (and (org-up-heading-safe) (point)))
11159 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11160 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11161 (forward-line 1)
11162 (re-search-forward org-not-done-heading-regexp pos t))
11163 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11165 (defcustom org-track-ordered-property-with-tag nil
11166 "Should the ORDERED property also be shown as a tag?
11167 The ORDERED property decides if an entry should require subtasks to be
11168 completed in sequence. Since a property is not very visible, setting
11169 this option means that toggling the ORDERED property with the command
11170 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11171 not relevant for the behavior, but it makes things more visible.
11173 Note that toggling the tag with tags commands will not change the property
11174 and therefore not influence behavior!
11176 This can be t, meaning the tag ORDERED should be used, It can also be a
11177 string to select a different tag for this task."
11178 :group 'org-todo
11179 :type '(choice
11180 (const :tag "No tracking" nil)
11181 (const :tag "Track with ORDERED tag" t)
11182 (string :tag "Use other tag")))
11184 (defun org-toggle-ordered-property ()
11185 "Toggle the ORDERED property of the current entry.
11186 For better visibility, you can track the value of this property with a tag.
11187 See variable `org-track-ordered-property-with-tag'."
11188 (interactive)
11189 (let* ((t1 org-track-ordered-property-with-tag)
11190 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11191 (save-excursion
11192 (org-back-to-heading)
11193 (if (org-entry-get nil "ORDERED")
11194 (progn
11195 (org-delete-property "ORDERED")
11196 (and tag (org-toggle-tag tag 'off))
11197 (message "Subtasks can be completed in arbitrary order"))
11198 (org-entry-put nil "ORDERED" "t")
11199 (and tag (org-toggle-tag tag 'on))
11200 (message "Subtasks must be completed in sequence")))))
11202 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11203 (defun org-block-todo-from-checkboxes (change-plist)
11204 "Block turning an entry into a TODO, using checkboxes.
11205 This checks whether the current task should be blocked from state
11206 changes because there are unchecked boxes in this entry."
11207 (if (not org-enforce-todo-checkbox-dependencies)
11208 t ; if locally turned off don't block
11209 (catch 'dont-block
11210 ;; If this is not a todo state change, or if this entry is already DONE,
11211 ;; do not block
11212 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11213 (member (plist-get change-plist :from)
11214 (cons 'done org-done-keywords))
11215 (member (plist-get change-plist :to)
11216 (cons 'todo org-not-done-keywords))
11217 (not (plist-get change-plist :to)))
11218 (throw 'dont-block t))
11219 ;; If this task has checkboxes that are not checked, it's blocked
11220 (save-excursion
11221 (org-back-to-heading t)
11222 (let ((beg (point)) end)
11223 (outline-next-heading)
11224 (setq end (point))
11225 (goto-char beg)
11226 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11227 end t)
11228 (progn
11229 (if (boundp 'org-blocked-by-checkboxes)
11230 (setq org-blocked-by-checkboxes t))
11231 (throw 'dont-block nil)))))
11232 t))) ; do not block
11234 (defun org-entry-blocked-p ()
11235 "Is the current entry blocked?"
11236 (if (org-entry-get nil "NOBLOCKING")
11237 nil ;; Never block this entry
11238 (not
11239 (run-hook-with-args-until-failure
11240 'org-blocker-hook
11241 (list :type 'todo-state-change
11242 :position (point)
11243 :from 'todo
11244 :to 'done)))))
11246 (defun org-update-statistics-cookies (all)
11247 "Update the statistics cookie, either from TODO or from checkboxes.
11248 This should be called with the cursor in a line with a statistics cookie."
11249 (interactive "P")
11250 (if all
11251 (progn
11252 (org-update-checkbox-count 'all)
11253 (org-map-entries 'org-update-parent-todo-statistics))
11254 (if (not (org-on-heading-p))
11255 (org-update-checkbox-count)
11256 (let ((pos (move-marker (make-marker) (point)))
11257 end l1 l2)
11258 (ignore-errors (org-back-to-heading t))
11259 (if (not (org-on-heading-p))
11260 (org-update-checkbox-count)
11261 (setq l1 (org-outline-level))
11262 (setq end (save-excursion
11263 (outline-next-heading)
11264 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11265 (point)))
11266 (if (and (save-excursion
11267 (re-search-forward
11268 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11269 (not (save-excursion (re-search-forward
11270 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11271 (org-update-checkbox-count)
11272 (if (and l2 (> l2 l1))
11273 (progn
11274 (goto-char end)
11275 (org-update-parent-todo-statistics))
11276 (goto-char pos)
11277 (beginning-of-line 1)
11278 (while (re-search-forward
11279 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11280 (point-at-eol) t)
11281 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11282 (goto-char pos)
11283 (move-marker pos nil)))))
11285 (defvar org-entry-property-inherited-from) ;; defined below
11286 (defun org-update-parent-todo-statistics ()
11287 "Update any statistics cookie in the parent of the current headline.
11288 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11289 the entire subtree and this will travel up the hierarchy and update
11290 statistics everywhere."
11291 (interactive)
11292 (let* ((lim 0) prop
11293 (recursive (or (not org-hierarchical-todo-statistics)
11294 (string-match
11295 "\\<recursive\\>"
11296 (or (setq prop (org-entry-get
11297 nil "COOKIE_DATA" 'inherit)) ""))))
11298 (lim (or (and prop (marker-position
11299 org-entry-property-inherited-from))
11300 lim))
11301 (first t)
11302 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11303 level ltoggle l1 new ndel
11304 (cnt-all 0) (cnt-done 0) is-percent kwd
11305 checkbox-beg ov ovs ove cookie-present)
11306 (catch 'exit
11307 (save-excursion
11308 (beginning-of-line 1)
11309 (if (org-at-heading-p)
11310 (setq ltoggle (funcall outline-level))
11311 (error "This should not happen"))
11312 (while (and (setq level (org-up-heading-safe))
11313 (or recursive first)
11314 (>= (point) lim))
11315 (setq first nil cookie-present nil)
11316 (unless (and level
11317 (not (string-match
11318 "\\<checkbox\\>"
11319 (downcase
11320 (or (org-entry-get
11321 nil "COOKIE_DATA")
11322 "")))))
11323 (throw 'exit nil))
11324 (while (re-search-forward box-re (point-at-eol) t)
11325 (setq cnt-all 0 cnt-done 0 cookie-present t)
11326 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11327 (save-match-data
11328 (unless (outline-next-heading) (throw 'exit nil))
11329 (while (and (looking-at org-complex-heading-regexp)
11330 (> (setq l1 (length (match-string 1))) level))
11331 (setq kwd (and (or recursive (= l1 ltoggle))
11332 (match-string 2)))
11333 (if (or (eq org-provide-todo-statistics 'all-headlines)
11334 (and (listp org-provide-todo-statistics)
11335 (or (member kwd org-provide-todo-statistics)
11336 (member kwd org-done-keywords))))
11337 (setq cnt-all (1+ cnt-all))
11338 (if (eq org-provide-todo-statistics t)
11339 (and kwd (setq cnt-all (1+ cnt-all)))))
11340 (and (member kwd org-done-keywords)
11341 (setq cnt-done (1+ cnt-done)))
11342 (outline-next-heading)))
11343 (setq new
11344 (if is-percent
11345 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11346 (format "[%d/%d]" cnt-done cnt-all))
11347 ndel (- (match-end 0) checkbox-beg))
11348 ;; handle overlays when updating cookie from column view
11349 (when (setq ov (car (overlays-at checkbox-beg)))
11350 (setq ovs (overlay-start ov) ove (overlay-end ov))
11351 (delete-overlay ov))
11352 (goto-char checkbox-beg)
11353 (insert new)
11354 (delete-region (point) (+ (point) ndel))
11355 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11356 (when ov (move-overlay ov ovs ove)))
11357 (when cookie-present
11358 (run-hook-with-args 'org-after-todo-statistics-hook
11359 cnt-done (- cnt-all cnt-done))))))
11360 (run-hooks 'org-todo-statistics-hook)))
11362 (defvar org-after-todo-statistics-hook nil
11363 "Hook that is called after a TODO statistics cookie has been updated.
11364 Each function is called with two arguments: the number of not-done entries
11365 and the number of done entries.
11367 For example, the following function, when added to this hook, will switch
11368 an entry to DONE when all children are done, and back to TODO when new
11369 entries are set to a TODO status. Note that this hook is only called
11370 when there is a statistics cookie in the headline!
11372 (defun org-summary-todo (n-done n-not-done)
11373 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11374 (let (org-log-done org-log-states) ; turn off logging
11375 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11378 (defvar org-todo-statistics-hook nil
11379 "Hook that is run whenever Org thinks TODO statistics should be updated.
11380 This hook runs even if there is no statistics cookie present, in which case
11381 `org-after-todo-statistics-hook' would not run.")
11383 (defun org-todo-trigger-tag-changes (state)
11384 "Apply the changes defined in `org-todo-state-tags-triggers'."
11385 (let ((l org-todo-state-tags-triggers)
11386 changes)
11387 (when (or (not state) (equal state ""))
11388 (setq changes (append changes (cdr (assoc "" l)))))
11389 (when (and (stringp state) (> (length state) 0))
11390 (setq changes (append changes (cdr (assoc state l)))))
11391 (when (member state org-not-done-keywords)
11392 (setq changes (append changes (cdr (assoc 'todo l)))))
11393 (when (member state org-done-keywords)
11394 (setq changes (append changes (cdr (assoc 'done l)))))
11395 (dolist (c changes)
11396 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11398 (defun org-local-logging (value)
11399 "Get logging settings from a property VALUE."
11400 (let* (words w a)
11401 ;; directly set the variables, they are already local.
11402 (setq org-log-done nil
11403 org-log-repeat nil
11404 org-todo-log-states nil)
11405 (setq words (org-split-string value))
11406 (while (setq w (pop words))
11407 (cond
11408 ((setq a (assoc w org-startup-options))
11409 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11410 (set (nth 1 a) (nth 2 a))))
11411 ((setq a (org-extract-log-state-settings w))
11412 (and (member (car a) org-todo-keywords-1)
11413 (push a org-todo-log-states)))))))
11415 (defun org-get-todo-sequence-head (kwd)
11416 "Return the head of the TODO sequence to which KWD belongs.
11417 If KWD is not set, check if there is a text property remembering the
11418 right sequence."
11419 (let (p)
11420 (cond
11421 ((not kwd)
11422 (or (get-text-property (point-at-bol) 'org-todo-head)
11423 (progn
11424 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11425 nil (point-at-eol)))
11426 (get-text-property p 'org-todo-head))))
11427 ((not (member kwd org-todo-keywords-1))
11428 (car org-todo-keywords-1))
11429 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11431 (defun org-fast-todo-selection ()
11432 "Fast TODO keyword selection with single keys.
11433 Returns the new TODO keyword, or nil if no state change should occur."
11434 (let* ((fulltable org-todo-key-alist)
11435 (done-keywords org-done-keywords) ;; needed for the faces.
11436 (maxlen (apply 'max (mapcar
11437 (lambda (x)
11438 (if (stringp (car x)) (string-width (car x)) 0))
11439 fulltable)))
11440 (expert nil)
11441 (fwidth (+ maxlen 3 1 3))
11442 (ncol (/ (- (window-width) 4) fwidth))
11443 tg cnt e c tbl
11444 groups ingroup)
11445 (save-excursion
11446 (save-window-excursion
11447 (if expert
11448 (set-buffer (get-buffer-create " *Org todo*"))
11449 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11450 (erase-buffer)
11451 (org-set-local 'org-done-keywords done-keywords)
11452 (setq tbl fulltable cnt 0)
11453 (while (setq e (pop tbl))
11454 (cond
11455 ((equal e '(:startgroup))
11456 (push '() groups) (setq ingroup t)
11457 (when (not (= cnt 0))
11458 (setq cnt 0)
11459 (insert "\n"))
11460 (insert "{ "))
11461 ((equal e '(:endgroup))
11462 (setq ingroup nil cnt 0)
11463 (insert "}\n"))
11464 ((equal e '(:newline))
11465 (when (not (= cnt 0))
11466 (setq cnt 0)
11467 (insert "\n")
11468 (setq e (car tbl))
11469 (while (equal (car tbl) '(:newline))
11470 (insert "\n")
11471 (setq tbl (cdr tbl)))))
11473 (setq tg (car e) c (cdr e))
11474 (if ingroup (push tg (car groups)))
11475 (setq tg (org-add-props tg nil 'face
11476 (org-get-todo-face tg)))
11477 (if (and (= cnt 0) (not ingroup)) (insert " "))
11478 (insert "[" c "] " tg (make-string
11479 (- fwidth 4 (length tg)) ?\ ))
11480 (when (= (setq cnt (1+ cnt)) ncol)
11481 (insert "\n")
11482 (if ingroup (insert " "))
11483 (setq cnt 0)))))
11484 (insert "\n")
11485 (goto-char (point-min))
11486 (if (not expert) (org-fit-window-to-buffer))
11487 (message "[a-z..]:Set [SPC]:clear")
11488 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11489 (cond
11490 ((or (= c ?\C-g)
11491 (and (= c ?q) (not (rassoc c fulltable))))
11492 (setq quit-flag t))
11493 ((= c ?\ ) nil)
11494 ((setq e (rassoc c fulltable) tg (car e))
11496 (t (setq quit-flag t)))))))
11498 (defun org-entry-is-todo-p ()
11499 (member (org-get-todo-state) org-not-done-keywords))
11501 (defun org-entry-is-done-p ()
11502 (member (org-get-todo-state) org-done-keywords))
11504 (defun org-get-todo-state ()
11505 (save-excursion
11506 (org-back-to-heading t)
11507 (and (looking-at org-todo-line-regexp)
11508 (match-end 2)
11509 (match-string 2))))
11511 (defun org-at-date-range-p (&optional inactive-ok)
11512 "Is the cursor inside a date range?"
11513 (interactive)
11514 (save-excursion
11515 (catch 'exit
11516 (let ((pos (point)))
11517 (skip-chars-backward "^[<\r\n")
11518 (skip-chars-backward "<[")
11519 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11520 (>= (match-end 0) pos)
11521 (throw 'exit t))
11522 (skip-chars-backward "^<[\r\n")
11523 (skip-chars-backward "<[")
11524 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11525 (>= (match-end 0) pos)
11526 (throw 'exit t)))
11527 nil)))
11529 (defun org-get-repeat (&optional tagline)
11530 "Check if there is a deadline/schedule with repeater in this entry."
11531 (save-match-data
11532 (save-excursion
11533 (org-back-to-heading t)
11534 (and (re-search-forward (if tagline
11535 (concat tagline "\\s-*" org-repeat-re)
11536 org-repeat-re)
11537 (org-entry-end-position) t)
11538 (match-string-no-properties 1)))))
11540 (defvar org-last-changed-timestamp)
11541 (defvar org-last-inserted-timestamp)
11542 (defvar org-log-post-message)
11543 (defvar org-log-note-purpose)
11544 (defvar org-log-note-how)
11545 (defvar org-log-note-extra)
11546 (defun org-auto-repeat-maybe (done-word)
11547 "Check if the current headline contains a repeated deadline/schedule.
11548 If yes, set TODO state back to what it was and change the base date
11549 of repeating deadline/scheduled time stamps to new date.
11550 This function is run automatically after each state change to a DONE state."
11551 ;; last-state is dynamically scoped into this function
11552 (let* ((repeat (org-get-repeat))
11553 (aa (assoc last-state org-todo-kwd-alist))
11554 (interpret (nth 1 aa))
11555 (head (nth 2 aa))
11556 (whata '(("d" . day) ("m" . month) ("y" . year)))
11557 (msg "Entry repeats: ")
11558 (org-log-done nil)
11559 (org-todo-log-states nil)
11560 re type n what ts time to-state)
11561 (when repeat
11562 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11563 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11564 org-todo-repeat-to-state))
11565 (unless (and to-state (member to-state org-todo-keywords-1))
11566 (setq to-state (if (eq interpret 'type) last-state head)))
11567 (org-todo to-state)
11568 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11569 (org-entry-put nil "LAST_REPEAT" (format-time-string
11570 (org-time-stamp-format t t))))
11571 (when org-log-repeat
11572 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11573 (memq 'org-add-log-note post-command-hook))
11574 ;; OK, we are already setup for some record
11575 (if (eq org-log-repeat 'note)
11576 ;; make sure we take a note, not only a time stamp
11577 (setq org-log-note-how 'note))
11578 ;; Set up for taking a record
11579 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11580 last-state
11581 'findpos org-log-repeat)))
11582 (org-back-to-heading t)
11583 (org-add-planning-info nil nil 'closed)
11584 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11585 org-deadline-time-regexp "\\)\\|\\("
11586 org-ts-regexp "\\)"))
11587 (while (re-search-forward
11588 re (save-excursion (outline-next-heading) (point)) t)
11589 (setq type (if (match-end 1) org-scheduled-string
11590 (if (match-end 3) org-deadline-string "Plain:"))
11591 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11592 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11593 (setq n (string-to-number (match-string 2 ts))
11594 what (match-string 3 ts))
11595 (if (equal what "w") (setq n (* n 7) what "d"))
11596 ;; Preparation, see if we need to modify the start date for the change
11597 (when (match-end 1)
11598 (setq time (save-match-data (org-time-string-to-time ts)))
11599 (cond
11600 ((equal (match-string 1 ts) ".")
11601 ;; Shift starting date to today
11602 (org-timestamp-change
11603 (- (time-to-days (current-time)) (time-to-days time))
11604 'day))
11605 ((equal (match-string 1 ts) "+")
11606 (let ((nshiftmax 10) (nshift 0))
11607 (while (or (= nshift 0)
11608 (<= (time-to-days time)
11609 (time-to-days (current-time))))
11610 (when (= (incf nshift) nshiftmax)
11611 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11612 (error "Abort")))
11613 (org-timestamp-change n (cdr (assoc what whata)))
11614 (org-at-timestamp-p t)
11615 (setq ts (match-string 1))
11616 (setq time (save-match-data (org-time-string-to-time ts)))))
11617 (org-timestamp-change (- n) (cdr (assoc what whata)))
11618 ;; rematch, so that we have everything in place for the real shift
11619 (org-at-timestamp-p t)
11620 (setq ts (match-string 1))
11621 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11622 (org-timestamp-change n (cdr (assoc what whata)))
11623 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11624 (setq org-log-post-message msg)
11625 (message "%s" msg))))
11627 (defun org-show-todo-tree (arg)
11628 "Make a compact tree which shows all headlines marked with TODO.
11629 The tree will show the lines where the regexp matches, and all higher
11630 headlines above the match.
11631 With a \\[universal-argument] prefix, prompt for a regexp to match.
11632 With a numeric prefix N, construct a sparse tree for the Nth element
11633 of `org-todo-keywords-1'."
11634 (interactive "P")
11635 (let ((case-fold-search nil)
11636 (kwd-re
11637 (cond ((null arg) org-not-done-regexp)
11638 ((equal arg '(4))
11639 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11640 (mapcar 'list org-todo-keywords-1))))
11641 (concat "\\("
11642 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11643 "\\)\\>")))
11644 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11645 (regexp-quote (nth (1- (prefix-numeric-value arg))
11646 org-todo-keywords-1)))
11647 (t (error "Invalid prefix argument: %s" arg)))))
11648 (message "%d TODO entries found"
11649 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11651 (defun org-deadline (&optional remove time)
11652 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11653 With argument REMOVE, remove any deadline from the item.
11654 When TIME is set, it should be an internal time specification, and the
11655 scheduling will use the corresponding date."
11656 (interactive "P")
11657 (let* ((old-date (org-entry-get nil "DEADLINE"))
11658 (repeater (and old-date
11659 (string-match
11660 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11661 old-date)
11662 (match-string 1 old-date))))
11663 (if remove
11664 (progn
11665 (when (and old-date org-log-redeadline)
11666 (org-add-log-setup 'deldeadline nil old-date 'findpos
11667 org-log-redeadline))
11668 (org-remove-timestamp-with-keyword org-deadline-string)
11669 (message "Item no longer has a deadline."))
11670 (org-add-planning-info 'deadline time 'closed)
11671 (when (and old-date org-log-redeadline
11672 (not (equal old-date
11673 (substring org-last-inserted-timestamp 1 -1))))
11674 (org-add-log-setup 'redeadline nil old-date 'findpos
11675 org-log-redeadline))
11676 (when repeater
11677 (save-excursion
11678 (org-back-to-heading t)
11679 (when (re-search-forward (concat org-deadline-string " "
11680 org-last-inserted-timestamp)
11681 (save-excursion
11682 (outline-next-heading) (point)) t)
11683 (goto-char (1- (match-end 0)))
11684 (insert " " repeater)
11685 (setq org-last-inserted-timestamp
11686 (concat (substring org-last-inserted-timestamp 0 -1)
11687 " " repeater
11688 (substring org-last-inserted-timestamp -1))))))
11689 (message "Deadline on %s" org-last-inserted-timestamp))))
11691 (defun org-schedule (&optional remove time)
11692 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11693 With argument REMOVE, remove any scheduling date from the item.
11694 When TIME is set, it should be an internal time specification, and the
11695 scheduling will use the corresponding date."
11696 (interactive "P")
11697 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11698 (repeater (and old-date
11699 (string-match
11700 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11701 old-date)
11702 (match-string 1 old-date))))
11703 (if remove
11704 (progn
11705 (when (and old-date org-log-reschedule)
11706 (org-add-log-setup 'delschedule nil old-date 'findpos
11707 org-log-reschedule))
11708 (org-remove-timestamp-with-keyword org-scheduled-string)
11709 (message "Item is no longer scheduled."))
11710 (org-add-planning-info 'scheduled time 'closed)
11711 (when (and old-date org-log-reschedule
11712 (not (equal old-date
11713 (substring org-last-inserted-timestamp 1 -1))))
11714 (org-add-log-setup 'reschedule nil old-date 'findpos
11715 org-log-reschedule))
11716 (when repeater
11717 (save-excursion
11718 (org-back-to-heading t)
11719 (when (re-search-forward (concat org-scheduled-string " "
11720 org-last-inserted-timestamp)
11721 (save-excursion
11722 (outline-next-heading) (point)) t)
11723 (goto-char (1- (match-end 0)))
11724 (insert " " repeater)
11725 (setq org-last-inserted-timestamp
11726 (concat (substring org-last-inserted-timestamp 0 -1)
11727 " " repeater
11728 (substring org-last-inserted-timestamp -1))))))
11729 (message "Scheduled to %s" org-last-inserted-timestamp))))
11731 (defun org-get-scheduled-time (pom &optional inherit)
11732 "Get the scheduled time as a time tuple, of a format suitable
11733 for calling org-schedule with, or if there is no scheduling,
11734 returns nil."
11735 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11736 (when time
11737 (apply 'encode-time (org-parse-time-string time)))))
11739 (defun org-get-deadline-time (pom &optional inherit)
11740 "Get the deadline as a time tuple, of a format suitable for
11741 calling org-deadline with, or if there is no scheduling, returns
11742 nil."
11743 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11744 (when time
11745 (apply 'encode-time (org-parse-time-string time)))))
11747 (defun org-remove-timestamp-with-keyword (keyword)
11748 "Remove all time stamps with KEYWORD in the current entry."
11749 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11750 beg)
11751 (save-excursion
11752 (org-back-to-heading t)
11753 (setq beg (point))
11754 (outline-next-heading)
11755 (while (re-search-backward re beg t)
11756 (replace-match "")
11757 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11758 (equal (char-before) ?\ ))
11759 (backward-delete-char 1)
11760 (if (string-match "^[ \t]*$" (buffer-substring
11761 (point-at-bol) (point-at-eol)))
11762 (delete-region (point-at-bol)
11763 (min (point-max) (1+ (point-at-eol))))))))))
11765 (defun org-add-planning-info (what &optional time &rest remove)
11766 "Insert new timestamp with keyword in the line directly after the headline.
11767 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11768 If non is given, the user is prompted for a date.
11769 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11770 be removed."
11771 (interactive)
11772 (let (org-time-was-given org-end-time-was-given ts
11773 end default-time default-input)
11775 (catch 'exit
11776 (when (and (not time) (memq what '(scheduled deadline)))
11777 ;; Try to get a default date/time from existing timestamp
11778 (save-excursion
11779 (org-back-to-heading t)
11780 (setq end (save-excursion (outline-next-heading) (point)))
11781 (when (re-search-forward (if (eq what 'scheduled)
11782 org-scheduled-time-regexp
11783 org-deadline-time-regexp)
11784 end t)
11785 (setq ts (match-string 1)
11786 default-time
11787 (apply 'encode-time (org-parse-time-string ts))
11788 default-input (and ts (org-get-compact-tod ts))))))
11789 (when what
11790 ;; If necessary, get the time from the user
11791 (setq time (or time (org-read-date nil 'to-time nil nil
11792 default-time default-input))))
11794 (when (and org-insert-labeled-timestamps-at-point
11795 (member what '(scheduled deadline)))
11796 (insert
11797 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11798 (org-insert-time-stamp time org-time-was-given
11799 nil nil nil (list org-end-time-was-given))
11800 (setq what nil))
11801 (save-excursion
11802 (save-restriction
11803 (let (col list elt ts buffer-invisibility-spec)
11804 (org-back-to-heading t)
11805 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11806 (goto-char (match-end 1))
11807 (setq col (current-column))
11808 (goto-char (match-end 0))
11809 (if (eobp) (insert "\n") (forward-char 1))
11810 (when (and (not what)
11811 (not (looking-at
11812 (concat "[ \t]*"
11813 org-keyword-time-not-clock-regexp))))
11814 ;; Nothing to add, nothing to remove...... :-)
11815 (throw 'exit nil))
11816 (if (and (not (looking-at outline-regexp))
11817 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11818 "[^\r\n]*"))
11819 (not (equal (match-string 1) org-clock-string)))
11820 (narrow-to-region (match-beginning 0) (match-end 0))
11821 (insert-before-markers "\n")
11822 (backward-char 1)
11823 (narrow-to-region (point) (point))
11824 (and org-adapt-indentation (org-indent-to-column col)))
11825 ;; Check if we have to remove something.
11826 (setq list (cons what remove))
11827 (while list
11828 (setq elt (pop list))
11829 (goto-char (point-min))
11830 (when (or (and (eq elt 'scheduled)
11831 (re-search-forward org-scheduled-time-regexp nil t))
11832 (and (eq elt 'deadline)
11833 (re-search-forward org-deadline-time-regexp nil t))
11834 (and (eq elt 'closed)
11835 (re-search-forward org-closed-time-regexp nil t)))
11836 (replace-match "")
11837 (if (looking-at "--+<[^>]+>") (replace-match ""))
11838 (skip-chars-backward " ")
11839 (if (looking-at " +") (replace-match ""))))
11840 (goto-char (point-max))
11841 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11842 (when what
11843 (insert
11844 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11845 (cond ((eq what 'scheduled) org-scheduled-string)
11846 ((eq what 'deadline) org-deadline-string)
11847 ((eq what 'closed) org-closed-string))
11848 " ")
11849 (setq ts (org-insert-time-stamp
11850 time
11851 (or org-time-was-given
11852 (and (eq what 'closed) org-log-done-with-time))
11853 (eq what 'closed)
11854 nil nil (list org-end-time-was-given)))
11855 (end-of-line 1))
11856 (goto-char (point-min))
11857 (widen)
11858 (if (and (looking-at "[ \t]*\n")
11859 (equal (char-before) ?\n))
11860 (delete-region (1- (point)) (point-at-eol)))
11861 ts))))))
11863 (defvar org-log-note-marker (make-marker))
11864 (defvar org-log-note-purpose nil)
11865 (defvar org-log-note-state nil)
11866 (defvar org-log-note-previous-state nil)
11867 (defvar org-log-note-how nil)
11868 (defvar org-log-note-extra nil)
11869 (defvar org-log-note-window-configuration nil)
11870 (defvar org-log-note-return-to (make-marker))
11871 (defvar org-log-post-message nil
11872 "Message to be displayed after a log note has been stored.
11873 The auto-repeater uses this.")
11875 (defun org-add-note ()
11876 "Add a note to the current entry.
11877 This is done in the same way as adding a state change note."
11878 (interactive)
11879 (org-add-log-setup 'note nil nil 'findpos nil))
11881 (defvar org-property-end-re)
11882 (defun org-add-log-setup (&optional purpose state prev-state
11883 findpos how extra)
11884 "Set up the post command hook to take a note.
11885 If this is about to TODO state change, the new state is expected in STATE.
11886 When FINDPOS is non-nil, find the correct position for the note in
11887 the current entry. If not, assume that it can be inserted at point.
11888 HOW is an indicator what kind of note should be created.
11889 EXTRA is additional text that will be inserted into the notes buffer."
11890 (let* ((org-log-into-drawer (org-log-into-drawer))
11891 (drawer (cond ((stringp org-log-into-drawer)
11892 org-log-into-drawer)
11893 (org-log-into-drawer "LOGBOOK")
11894 (t nil))))
11895 (save-restriction
11896 (save-excursion
11897 (when findpos
11898 (org-back-to-heading t)
11899 (narrow-to-region (point) (save-excursion
11900 (outline-next-heading) (point)))
11901 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11902 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11903 "[^\r\n]*\\)?"))
11904 (goto-char (match-end 0))
11905 (cond
11906 (drawer
11907 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11908 nil t)
11909 (progn
11910 (goto-char (match-end 0))
11911 (or org-log-states-order-reversed
11912 (and (re-search-forward org-property-end-re nil t)
11913 (goto-char (1- (match-beginning 0))))))
11914 (insert "\n:" drawer ":\n:END:")
11915 (beginning-of-line 0)
11916 (org-indent-line-function)
11917 (beginning-of-line 2)
11918 (org-indent-line-function)
11919 (end-of-line 0)))
11920 ((and org-log-state-notes-insert-after-drawers
11921 (save-excursion
11922 (forward-line) (looking-at org-drawer-regexp)))
11923 (forward-line)
11924 (while (looking-at org-drawer-regexp)
11925 (goto-char (match-end 0))
11926 (re-search-forward org-property-end-re (point-max) t)
11927 (forward-line))
11928 (forward-line -1)))
11929 (unless org-log-states-order-reversed
11930 (and (= (char-after) ?\n) (forward-char 1))
11931 (org-skip-over-state-notes)
11932 (skip-chars-backward " \t\n\r")))
11933 (move-marker org-log-note-marker (point))
11934 (setq org-log-note-purpose purpose
11935 org-log-note-state state
11936 org-log-note-previous-state prev-state
11937 org-log-note-how how
11938 org-log-note-extra extra)
11939 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11941 (defun org-skip-over-state-notes ()
11942 "Skip past the list of State notes in an entry."
11943 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11944 (when (ignore-errors (goto-char (org-in-item-p)))
11945 (let* ((struct (org-list-struct))
11946 (prevs (org-list-prevs-alist struct)))
11947 (while (looking-at "[ \t]*- State")
11948 (goto-char (or (org-list-get-next-item (point) struct prevs)
11949 (org-list-get-item-end (point) struct)))))))
11951 (defun org-add-log-note (&optional purpose)
11952 "Pop up a window for taking a note, and add this note later at point."
11953 (remove-hook 'post-command-hook 'org-add-log-note)
11954 (setq org-log-note-window-configuration (current-window-configuration))
11955 (delete-other-windows)
11956 (move-marker org-log-note-return-to (point))
11957 (switch-to-buffer (marker-buffer org-log-note-marker))
11958 (goto-char org-log-note-marker)
11959 (org-switch-to-buffer-other-window "*Org Note*")
11960 (erase-buffer)
11961 (if (memq org-log-note-how '(time state))
11962 (let (current-prefix-arg) (org-store-log-note))
11963 (let ((org-inhibit-startup t)) (org-mode))
11964 (insert (format "# Insert note for %s.
11965 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11966 (cond
11967 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11968 ((eq org-log-note-purpose 'done) "closed todo item")
11969 ((eq org-log-note-purpose 'state)
11970 (format "state change from \"%s\" to \"%s\""
11971 (or org-log-note-previous-state "")
11972 (or org-log-note-state "")))
11973 ((eq org-log-note-purpose 'reschedule)
11974 "rescheduling")
11975 ((eq org-log-note-purpose 'delschedule)
11976 "no longer scheduled")
11977 ((eq org-log-note-purpose 'redeadline)
11978 "changing deadline")
11979 ((eq org-log-note-purpose 'deldeadline)
11980 "removing deadline")
11981 ((eq org-log-note-purpose 'refile)
11982 "refiling")
11983 ((eq org-log-note-purpose 'note)
11984 "this entry")
11985 (t (error "This should not happen")))))
11986 (if org-log-note-extra (insert org-log-note-extra))
11987 (org-set-local 'org-finish-function 'org-store-log-note)))
11989 (defvar org-note-abort nil) ; dynamically scoped
11990 (defun org-store-log-note ()
11991 "Finish taking a log note, and insert it to where it belongs."
11992 (let ((txt (buffer-string))
11993 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11994 lines ind bul)
11995 (kill-buffer (current-buffer))
11996 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11997 (setq txt (replace-match "" t t txt)))
11998 (if (string-match "\\s-+\\'" txt)
11999 (setq txt (replace-match "" t t txt)))
12000 (setq lines (org-split-string txt "\n"))
12001 (when (and note (string-match "\\S-" note))
12002 (setq note
12003 (org-replace-escapes
12004 note
12005 (list (cons "%u" (user-login-name))
12006 (cons "%U" user-full-name)
12007 (cons "%t" (format-time-string
12008 (org-time-stamp-format 'long 'inactive)
12009 (current-time)))
12010 (cons "%T" (format-time-string
12011 (org-time-stamp-format 'long nil)
12012 (current-time)))
12013 (cons "%s" (if org-log-note-state
12014 (concat "\"" org-log-note-state "\"")
12015 ""))
12016 (cons "%S" (if org-log-note-previous-state
12017 (concat "\"" org-log-note-previous-state "\"")
12018 "\"\"")))))
12019 (if lines (setq note (concat note " \\\\")))
12020 (push note lines))
12021 (when (or current-prefix-arg org-note-abort)
12022 (when org-log-into-drawer
12023 (org-remove-empty-drawer-at
12024 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12025 org-log-note-marker))
12026 (setq lines nil))
12027 (when lines
12028 (with-current-buffer (marker-buffer org-log-note-marker)
12029 (save-excursion
12030 (goto-char org-log-note-marker)
12031 (move-marker org-log-note-marker nil)
12032 (end-of-line 1)
12033 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12034 (setq ind (save-excursion
12035 (if (ignore-errors (goto-char (org-in-item-p)))
12036 (let ((struct (org-list-struct)))
12037 (org-list-get-ind
12038 (org-list-get-top-point struct) struct))
12039 (skip-chars-backward " \r\t\n")
12040 (cond
12041 ((and (org-at-heading-p)
12042 org-adapt-indentation)
12043 (1+ (org-current-level)))
12044 ((org-at-heading-p) 0)
12045 (t (org-get-indentation))))))
12046 (setq bul (org-list-bullet-string "-"))
12047 (org-indent-line-to ind)
12048 (insert bul (pop lines))
12049 (let ((ind-body (+ (length bul) ind)))
12050 (while lines
12051 (insert "\n")
12052 (org-indent-line-to ind-body)
12053 (insert (pop lines))))
12054 (message "Note stored")
12055 (org-back-to-heading t)
12056 (org-cycle-hide-drawers 'children)))))
12057 (set-window-configuration org-log-note-window-configuration)
12058 (with-current-buffer (marker-buffer org-log-note-return-to)
12059 (goto-char org-log-note-return-to))
12060 (move-marker org-log-note-return-to nil)
12061 (and org-log-post-message (message "%s" org-log-post-message)))
12063 (defun org-remove-empty-drawer-at (drawer pos)
12064 "Remove an empty drawer DRAWER at position POS.
12065 POS may also be a marker."
12066 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12067 (save-excursion
12068 (save-restriction
12069 (widen)
12070 (goto-char pos)
12071 (if (org-in-regexp
12072 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12073 (replace-match ""))))))
12075 (defun org-sparse-tree (&optional arg)
12076 "Create a sparse tree, prompt for the details.
12077 This command can create sparse trees. You first need to select the type
12078 of match used to create the tree:
12080 t Show all TODO entries.
12081 T Show entries with a specific TODO keyword.
12082 m Show entries selected by a tags/property match.
12083 p Enter a property name and its value (both with completion on existing
12084 names/values) and show entries with that property.
12085 r Show entries matching a regular expression (`/' can be used as well)
12086 d Show deadlines due within `org-deadline-warning-days'.
12087 b Show deadlines and scheduled items before a date.
12088 a Show deadlines and scheduled items after a date."
12089 (interactive "P")
12090 (let (ans kwd value)
12091 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12092 (setq ans (read-char-exclusive))
12093 (cond
12094 ((equal ans ?d)
12095 (call-interactively 'org-check-deadlines))
12096 ((equal ans ?b)
12097 (call-interactively 'org-check-before-date))
12098 ((equal ans ?a)
12099 (call-interactively 'org-check-after-date))
12100 ((equal ans ?t)
12101 (org-show-todo-tree nil))
12102 ((equal ans ?T)
12103 (org-show-todo-tree '(4)))
12104 ((member ans '(?T ?m))
12105 (call-interactively 'org-match-sparse-tree))
12106 ((member ans '(?p ?P))
12107 (setq kwd (org-icompleting-read "Property: "
12108 (mapcar 'list (org-buffer-property-keys))))
12109 (setq value (org-icompleting-read "Value: "
12110 (mapcar 'list (org-property-values kwd))))
12111 (unless (string-match "\\`{.*}\\'" value)
12112 (setq value (concat "\"" value "\"")))
12113 (org-match-sparse-tree arg (concat kwd "=" value)))
12114 ((member ans '(?r ?R ?/))
12115 (call-interactively 'org-occur))
12116 (t (error "No such sparse tree command \"%c\"" ans)))))
12118 (defvar org-occur-highlights nil
12119 "List of overlays used for occur matches.")
12120 (make-variable-buffer-local 'org-occur-highlights)
12121 (defvar org-occur-parameters nil
12122 "Parameters of the active org-occur calls.
12123 This is a list, each call to org-occur pushes as cons cell,
12124 containing the regular expression and the callback, onto the list.
12125 The list can contain several entries if `org-occur' has been called
12126 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12127 will only contain one set of parameters. When the highlights are
12128 removed (for example with `C-c C-c', or with the next edit (depending
12129 on `org-remove-highlights-with-change'), this variable is emptied
12130 as well.")
12131 (make-variable-buffer-local 'org-occur-parameters)
12133 (defun org-occur (regexp &optional keep-previous callback)
12134 "Make a compact tree which shows all matches of REGEXP.
12135 The tree will show the lines where the regexp matches, and all higher
12136 headlines above the match. It will also show the heading after the match,
12137 to make sure editing the matching entry is easy.
12138 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12139 call to `org-occur' will be kept, to allow stacking of calls to this
12140 command.
12141 If CALLBACK is non-nil, it is a function which is called to confirm
12142 that the match should indeed be shown."
12143 (interactive "sRegexp: \nP")
12144 (when (equal regexp "")
12145 (error "Regexp cannot be empty"))
12146 (unless keep-previous
12147 (org-remove-occur-highlights nil nil t))
12148 (push (cons regexp callback) org-occur-parameters)
12149 (let ((cnt 0))
12150 (save-excursion
12151 (goto-char (point-min))
12152 (if (or (not keep-previous) ; do not want to keep
12153 (not org-occur-highlights)) ; no previous matches
12154 ;; hide everything
12155 (org-overview))
12156 (while (re-search-forward regexp nil t)
12157 (when (or (not callback)
12158 (save-match-data (funcall callback)))
12159 (setq cnt (1+ cnt))
12160 (when org-highlight-sparse-tree-matches
12161 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12162 (org-show-context 'occur-tree))))
12163 (when org-remove-highlights-with-change
12164 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12165 nil 'local))
12166 (unless org-sparse-tree-open-archived-trees
12167 (org-hide-archived-subtrees (point-min) (point-max)))
12168 (run-hooks 'org-occur-hook)
12169 (if (org-called-interactively-p 'interactive)
12170 (message "%d match(es) for regexp %s" cnt regexp))
12171 cnt))
12173 (defun org-occur-next-match (&optional n reset)
12174 "Function for `next-error-function' to find sparse tree matches.
12175 N is the number of matches to move, when negative move backwards.
12176 RESET is entirely ignored - this function always goes back to the
12177 starting point when no match is found."
12178 (let* ((limit (if (< n 0) (point-min) (point-max)))
12179 (search-func (if (< n 0)
12180 'previous-single-char-property-change
12181 'next-single-char-property-change))
12182 (n (abs n))
12183 (pos (point))
12185 (catch 'exit
12186 (while (setq p1 (funcall search-func (point) 'org-type))
12187 (when (equal p1 limit)
12188 (goto-char pos)
12189 (error "No more matches"))
12190 (when (equal (get-char-property p1 'org-type) 'org-occur)
12191 (setq n (1- n))
12192 (when (= n 0)
12193 (goto-char p1)
12194 (throw 'exit (point))))
12195 (goto-char p1))
12196 (goto-char p1)
12197 (error "No more matches"))))
12199 (defun org-show-context (&optional key)
12200 "Make sure point and context are visible.
12201 How much context is shown depends upon the variables
12202 `org-show-hierarchy-above', `org-show-following-heading'. and
12203 `org-show-siblings'."
12204 (let ((heading-p (org-on-heading-p t))
12205 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12206 (following-p (org-get-alist-option org-show-following-heading key))
12207 (entry-p (org-get-alist-option org-show-entry-below key))
12208 (siblings-p (org-get-alist-option org-show-siblings key)))
12209 (catch 'exit
12210 ;; Show heading or entry text
12211 (if (and heading-p (not entry-p))
12212 (org-flag-heading nil) ; only show the heading
12213 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12214 (org-show-hidden-entry))) ; show entire entry
12215 (when following-p
12216 ;; Show next sibling, or heading below text
12217 (save-excursion
12218 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12219 (org-flag-heading nil))))
12220 (when siblings-p (org-show-siblings))
12221 (when hierarchy-p
12222 ;; show all higher headings, possibly with siblings
12223 (save-excursion
12224 (while (and (condition-case nil
12225 (progn (org-up-heading-all 1) t)
12226 (error nil))
12227 (not (bobp)))
12228 (org-flag-heading nil)
12229 (when siblings-p (org-show-siblings))))))))
12231 (defvar org-reveal-start-hook nil
12232 "Hook run before revealing a location.")
12234 (defun org-reveal (&optional siblings)
12235 "Show current entry, hierarchy above it, and the following headline.
12236 This can be used to show a consistent set of context around locations
12237 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12238 not t for the search context.
12240 With optional argument SIBLINGS, on each level of the hierarchy all
12241 siblings are shown. This repairs the tree structure to what it would
12242 look like when opened with hierarchical calls to `org-cycle'.
12243 With double optional argument \\[universal-argument] \\[universal-argument], \
12244 go to the parent and show the
12245 entire tree."
12246 (interactive "P")
12247 (run-hooks 'org-reveal-start-hook)
12248 (let ((org-show-hierarchy-above t)
12249 (org-show-following-heading t)
12250 (org-show-siblings (if siblings t org-show-siblings)))
12251 (org-show-context nil))
12252 (when (equal siblings '(16))
12253 (save-excursion
12254 (when (org-up-heading-safe)
12255 (org-show-subtree)
12256 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12258 (defun org-highlight-new-match (beg end)
12259 "Highlight from BEG to END and mark the highlight is an occur headline."
12260 (let ((ov (make-overlay beg end)))
12261 (overlay-put ov 'face 'secondary-selection)
12262 (overlay-put ov 'org-type 'org-occur)
12263 (push ov org-occur-highlights)))
12265 (defun org-remove-occur-highlights (&optional beg end noremove)
12266 "Remove the occur highlights from the buffer.
12267 BEG and END are ignored. If NOREMOVE is nil, remove this function
12268 from the `before-change-functions' in the current buffer."
12269 (interactive)
12270 (unless org-inhibit-highlight-removal
12271 (mapc 'delete-overlay org-occur-highlights)
12272 (setq org-occur-highlights nil)
12273 (setq org-occur-parameters nil)
12274 (unless noremove
12275 (remove-hook 'before-change-functions
12276 'org-remove-occur-highlights 'local))))
12278 ;;;; Priorities
12280 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12281 "Regular expression matching the priority indicator.")
12283 (defvar org-remove-priority-next-time nil)
12285 (defun org-priority-up ()
12286 "Increase the priority of the current item."
12287 (interactive)
12288 (org-priority 'up))
12290 (defun org-priority-down ()
12291 "Decrease the priority of the current item."
12292 (interactive)
12293 (org-priority 'down))
12295 (defun org-priority (&optional action)
12296 "Change the priority of an item by ARG.
12297 ACTION can be `set', `up', `down', or a character."
12298 (interactive)
12299 (unless org-enable-priority-commands
12300 (error "Priority commands are disabled"))
12301 (setq action (or action 'set))
12302 (let (current new news have remove)
12303 (save-excursion
12304 (org-back-to-heading t)
12305 (if (looking-at org-priority-regexp)
12306 (setq current (string-to-char (match-string 2))
12307 have t))
12308 (cond
12309 ((eq action 'remove)
12310 (setq remove t new ?\ ))
12311 ((or (eq action 'set)
12312 (if (featurep 'xemacs) (characterp action) (integerp action)))
12313 (if (not (eq action 'set))
12314 (setq new action)
12315 (message "Priority %c-%c, SPC to remove: "
12316 org-highest-priority org-lowest-priority)
12317 (save-match-data
12318 (setq new (read-char-exclusive))))
12319 (if (and (= (upcase org-highest-priority) org-highest-priority)
12320 (= (upcase org-lowest-priority) org-lowest-priority))
12321 (setq new (upcase new)))
12322 (cond ((equal new ?\ ) (setq remove t))
12323 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12324 (error "Priority must be between `%c' and `%c'"
12325 org-highest-priority org-lowest-priority))))
12326 ((eq action 'up)
12327 (setq new (if have
12328 (1- current) ; normal cycling
12329 ;; last priority was empty
12330 (if (eq last-command this-command)
12331 org-lowest-priority ; wrap around empty to lowest
12332 ;; default
12333 (if org-priority-start-cycle-with-default
12334 org-default-priority
12335 (1- org-default-priority))))))
12336 ((eq action 'down)
12337 (setq new (if have
12338 (1+ current) ; normal cycling
12339 ;; last priority was empty
12340 (if (eq last-command this-command)
12341 org-highest-priority ; wrap around empty to highest
12342 ;; default
12343 (if org-priority-start-cycle-with-default
12344 org-default-priority
12345 (1+ org-default-priority))))))
12346 (t (error "Invalid action")))
12347 (if (or (< (upcase new) org-highest-priority)
12348 (> (upcase new) org-lowest-priority))
12349 (if (and (memq action '(up down))
12350 (not have) (not (eq last-command this-command)))
12351 ;; `new' is from default priority
12352 (error
12353 "The default can not be set, see `org-default-priority' why")
12354 ;; normal cycling: `new' is beyond highest/lowest priority
12355 ;; and is wrapped around to the empty priority
12356 (setq remove t)))
12357 (setq news (format "%c" new))
12358 (if have
12359 (if remove
12360 (replace-match "" t t nil 1)
12361 (replace-match news t t nil 2))
12362 (if remove
12363 (error "No priority cookie found in line")
12364 (let ((case-fold-search nil))
12365 (looking-at org-todo-line-regexp))
12366 (if (match-end 2)
12367 (progn
12368 (goto-char (match-end 2))
12369 (insert " [#" news "]"))
12370 (goto-char (match-beginning 3))
12371 (insert "[#" news "] "))))
12372 (org-preserve-lc (org-set-tags nil 'align)))
12373 (if remove
12374 (message "Priority removed")
12375 (message "Priority of current item set to %s" news))))
12377 (defun org-get-priority (s)
12378 "Find priority cookie and return priority."
12379 (if (functionp org-get-priority-function)
12380 (funcall org-get-priority-function)
12381 (save-match-data
12382 (if (not (string-match org-priority-regexp s))
12383 (* 1000 (- org-lowest-priority org-default-priority))
12384 (* 1000 (- org-lowest-priority
12385 (string-to-char (match-string 2 s))))))))
12387 ;;;; Tags
12389 (defvar org-agenda-archives-mode)
12390 (defvar org-map-continue-from nil
12391 "Position from where mapping should continue.
12392 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12394 (defvar org-scanner-tags nil
12395 "The current tag list while the tags scanner is running.")
12396 (defvar org-trust-scanner-tags nil
12397 "Should `org-get-tags-at' use the tags for the scanner.
12398 This is for internal dynamical scoping only.
12399 When this is non-nil, the function `org-get-tags-at' will return the value
12400 of `org-scanner-tags' instead of building the list by itself. This
12401 can lead to large speed-ups when the tags scanner is used in a file with
12402 many entries, and when the list of tags is retrieved, for example to
12403 obtain a list of properties. Building the tags list for each entry in such
12404 a file becomes an N^2 operation - but with this variable set, it scales
12405 as N.")
12407 (defun org-scan-tags (action matcher &optional todo-only)
12408 "Scan headline tags with inheritance and produce output ACTION.
12410 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12411 or `agenda' to produce an entry list for an agenda view. It can also be
12412 a Lisp form or a function that should be called at each matched headline, in
12413 this case the return value is a list of all return values from these calls.
12415 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12416 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12417 only lines with a TODO keyword are included in the output."
12418 (require 'org-agenda)
12419 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12420 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12421 (org-re
12422 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12423 (props (list 'face 'default
12424 'done-face 'org-agenda-done
12425 'undone-face 'default
12426 'mouse-face 'highlight
12427 'org-not-done-regexp org-not-done-regexp
12428 'org-todo-regexp org-todo-regexp
12429 'help-echo
12430 (format "mouse-2 or RET jump to org file %s"
12431 (abbreviate-file-name
12432 (or (buffer-file-name (buffer-base-buffer))
12433 (buffer-name (buffer-base-buffer)))))))
12434 (case-fold-search nil)
12435 (org-map-continue-from nil)
12436 lspos tags tags-list
12437 (tags-alist (list (cons 0 org-file-tags)))
12438 (llast 0) rtn rtn1 level category i txt
12439 todo marker entry priority)
12440 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12441 (setq action (list 'lambda nil action)))
12442 (save-excursion
12443 (goto-char (point-min))
12444 (when (eq action 'sparse-tree)
12445 (org-overview)
12446 (org-remove-occur-highlights))
12447 (while (re-search-forward re nil t)
12448 (catch :skip
12449 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12450 tags (if (match-end 4) (org-match-string-no-properties 4)))
12451 (goto-char (setq lspos (match-beginning 0)))
12452 (setq level (org-reduced-level (funcall outline-level))
12453 category (org-get-category))
12454 (setq i llast llast level)
12455 ;; remove tag lists from same and sublevels
12456 (while (>= i level)
12457 (when (setq entry (assoc i tags-alist))
12458 (setq tags-alist (delete entry tags-alist)))
12459 (setq i (1- i)))
12460 ;; add the next tags
12461 (when tags
12462 (setq tags (org-split-string tags ":")
12463 tags-alist
12464 (cons (cons level tags) tags-alist)))
12465 ;; compile tags for current headline
12466 (setq tags-list
12467 (if org-use-tag-inheritance
12468 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12469 tags)
12470 org-scanner-tags tags-list)
12471 (when org-use-tag-inheritance
12472 (setcdr (car tags-alist)
12473 (mapcar (lambda (x)
12474 (setq x (copy-sequence x))
12475 (org-add-prop-inherited x))
12476 (cdar tags-alist))))
12477 (when (and tags org-use-tag-inheritance
12478 (or (not (eq t org-use-tag-inheritance))
12479 org-tags-exclude-from-inheritance))
12480 ;; selective inheritance, remove uninherited ones
12481 (setcdr (car tags-alist)
12482 (org-remove-uninherited-tags (cdar tags-alist))))
12483 (when (and
12485 ;; eval matcher only when the todo condition is OK
12486 (and (or (not todo-only) (member todo org-not-done-keywords))
12487 (let ((case-fold-search t)) (eval matcher)))
12489 ;; Call the skipper, but return t if it does not skip,
12490 ;; so that the `and' form continues evaluating
12491 (progn
12492 (unless (eq action 'sparse-tree) (org-agenda-skip))
12495 ;; Check if timestamps are deselecting this entry
12496 (or (not todo-only)
12497 (and (member todo org-not-done-keywords)
12498 (or (not org-agenda-tags-todo-honor-ignore-options)
12499 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12501 ;; Extra check for the archive tag
12502 ;; FIXME: Does the skipper already do this????
12504 (not (member org-archive-tag tags-list))
12505 ;; we have an archive tag, should we use this anyway?
12506 (or (not org-agenda-skip-archived-trees)
12507 (and (eq action 'agenda) org-agenda-archives-mode))))
12509 ;; select this headline
12511 (cond
12512 ((eq action 'sparse-tree)
12513 (and org-highlight-sparse-tree-matches
12514 (org-get-heading) (match-end 0)
12515 (org-highlight-new-match
12516 (match-beginning 0) (match-beginning 1)))
12517 (org-show-context 'tags-tree))
12518 ((eq action 'agenda)
12519 (setq txt (org-format-agenda-item
12521 (concat
12522 (if (eq org-tags-match-list-sublevels 'indented)
12523 (make-string (1- level) ?.) "")
12524 (org-get-heading))
12525 category
12526 tags-list
12528 priority (org-get-priority txt))
12529 (goto-char lspos)
12530 (setq marker (org-agenda-new-marker))
12531 (org-add-props txt props
12532 'org-marker marker 'org-hd-marker marker 'org-category category
12533 'todo-state todo
12534 'priority priority 'type "tagsmatch")
12535 (push txt rtn))
12536 ((functionp action)
12537 (setq org-map-continue-from nil)
12538 (save-excursion
12539 (setq rtn1 (funcall action))
12540 (push rtn1 rtn)))
12541 (t (error "Invalid action")))
12543 ;; if we are to skip sublevels, jump to end of subtree
12544 (unless org-tags-match-list-sublevels
12545 (org-end-of-subtree t)
12546 (backward-char 1))))
12547 ;; Get the correct position from where to continue
12548 (if org-map-continue-from
12549 (goto-char org-map-continue-from)
12550 (and (= (point) lspos) (end-of-line 1)))))
12551 (when (and (eq action 'sparse-tree)
12552 (not org-sparse-tree-open-archived-trees))
12553 (org-hide-archived-subtrees (point-min) (point-max)))
12554 (nreverse rtn)))
12556 (defun org-remove-uninherited-tags (tags)
12557 "Remove all tags that are not inherited from the list TAGS."
12558 (cond
12559 ((eq org-use-tag-inheritance t)
12560 (if org-tags-exclude-from-inheritance
12561 (org-delete-all org-tags-exclude-from-inheritance tags)
12562 tags))
12563 ((not org-use-tag-inheritance) nil)
12564 ((stringp org-use-tag-inheritance)
12565 (delq nil (mapcar
12566 (lambda (x)
12567 (if (and (string-match org-use-tag-inheritance x)
12568 (not (member x org-tags-exclude-from-inheritance)))
12569 x nil))
12570 tags)))
12571 ((listp org-use-tag-inheritance)
12572 (delq nil (mapcar
12573 (lambda (x)
12574 (if (member x org-use-tag-inheritance) x nil))
12575 tags)))))
12577 (defvar todo-only) ;; dynamically scoped
12579 (defun org-match-sparse-tree (&optional todo-only match)
12580 "Create a sparse tree according to tags string MATCH.
12581 MATCH can contain positive and negative selection of tags, like
12582 \"+WORK+URGENT-WITHBOSS\".
12583 If optional argument TODO-ONLY is non-nil, only select lines that are
12584 also TODO lines."
12585 (interactive "P")
12586 (org-prepare-agenda-buffers (list (current-buffer)))
12587 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12589 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12591 (defvar org-cached-props nil)
12592 (defun org-cached-entry-get (pom property)
12593 (if (or (eq t org-use-property-inheritance)
12594 (and (stringp org-use-property-inheritance)
12595 (string-match org-use-property-inheritance property))
12596 (and (listp org-use-property-inheritance)
12597 (member property org-use-property-inheritance)))
12598 ;; Caching is not possible, check it directly
12599 (org-entry-get pom property 'inherit)
12600 ;; Get all properties, so that we can do complicated checks easily
12601 (cdr (assoc property (or org-cached-props
12602 (setq org-cached-props
12603 (org-entry-properties pom)))))))
12605 (defun org-global-tags-completion-table (&optional files)
12606 "Return the list of all tags in all agenda buffer/files.
12607 Optional FILES argument is a list of files to which can be used
12608 instead of the agenda files."
12609 (save-excursion
12610 (org-uniquify
12611 (delq nil
12612 (apply 'append
12613 (mapcar
12614 (lambda (file)
12615 (set-buffer (find-file-noselect file))
12616 (append (org-get-buffer-tags)
12617 (mapcar (lambda (x) (if (stringp (car-safe x))
12618 (list (car-safe x)) nil))
12619 org-tag-alist)))
12620 (if (and files (car files))
12621 files
12622 (org-agenda-files))))))))
12624 (defun org-make-tags-matcher (match)
12625 "Create the TAGS/TODO matcher form for the selection string MATCH."
12626 ;; todo-only is scoped dynamically into this function, and the function
12627 ;; may change it if the matcher asks for it.
12628 (unless match
12629 ;; Get a new match request, with completion
12630 (let ((org-last-tags-completion-table
12631 (org-global-tags-completion-table)))
12632 (setq match (org-completing-read-no-i
12633 "Match: " 'org-tags-completion-function nil nil nil
12634 'org-tags-history))))
12636 ;; Parse the string and create a lisp form
12637 (let ((match0 match)
12638 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12639 minus tag mm
12640 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12641 orterms term orlist re-p str-p level-p level-op time-p
12642 prop-p pn pv po gv rest)
12643 (if (string-match "/+" match)
12644 ;; match contains also a todo-matching request
12645 (progn
12646 (setq tagsmatch (substring match 0 (match-beginning 0))
12647 todomatch (substring match (match-end 0)))
12648 (if (string-match "^!" todomatch)
12649 (setq todo-only t todomatch (substring todomatch 1)))
12650 (if (string-match "^\\s-*$" todomatch)
12651 (setq todomatch nil)))
12652 ;; only matching tags
12653 (setq tagsmatch match todomatch nil))
12655 ;; Make the tags matcher
12656 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12657 (setq tagsmatcher t)
12658 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12659 (while (setq term (pop orterms))
12660 (while (and (equal (substring term -1) "\\") orterms)
12661 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12662 (while (string-match re term)
12663 (setq rest (substring term (match-end 0))
12664 minus (and (match-end 1)
12665 (equal (match-string 1 term) "-"))
12666 tag (save-match-data (replace-regexp-in-string
12667 "\\\\-" "-"
12668 (match-string 2 term)))
12669 re-p (equal (string-to-char tag) ?{)
12670 level-p (match-end 4)
12671 prop-p (match-end 5)
12672 mm (cond
12673 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12674 (level-p
12675 (setq level-op (org-op-to-function (match-string 3 term)))
12676 `(,level-op level ,(string-to-number
12677 (match-string 4 term))))
12678 (prop-p
12679 (setq pn (match-string 5 term)
12680 po (match-string 6 term)
12681 pv (match-string 7 term)
12682 re-p (equal (string-to-char pv) ?{)
12683 str-p (equal (string-to-char pv) ?\")
12684 time-p (save-match-data
12685 (string-match "^\"[[<].*[]>]\"$" pv))
12686 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12687 (if time-p (setq pv (org-matcher-time pv)))
12688 (setq po (org-op-to-function po (if time-p 'time str-p)))
12689 (cond
12690 ((equal pn "CATEGORY")
12691 (setq gv '(get-text-property (point) 'org-category)))
12692 ((equal pn "TODO")
12693 (setq gv 'todo))
12695 (setq gv `(org-cached-entry-get nil ,pn))))
12696 (if re-p
12697 (if (eq po 'org<>)
12698 `(not (string-match ,pv (or ,gv "")))
12699 `(string-match ,pv (or ,gv "")))
12700 (if str-p
12701 `(,po (or ,gv "") ,pv)
12702 `(,po (string-to-number (or ,gv ""))
12703 ,(string-to-number pv) ))))
12704 (t `(member ,tag tags-list)))
12705 mm (if minus (list 'not mm) mm)
12706 term rest)
12707 (push mm tagsmatcher))
12708 (push (if (> (length tagsmatcher) 1)
12709 (cons 'and tagsmatcher)
12710 (car tagsmatcher))
12711 orlist)
12712 (setq tagsmatcher nil))
12713 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12714 (setq tagsmatcher
12715 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12716 ;; Make the todo matcher
12717 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12718 (setq todomatcher t)
12719 (setq orterms (org-split-string todomatch "|") orlist nil)
12720 (while (setq term (pop orterms))
12721 (while (string-match re term)
12722 (setq minus (and (match-end 1)
12723 (equal (match-string 1 term) "-"))
12724 kwd (match-string 2 term)
12725 re-p (equal (string-to-char kwd) ?{)
12726 term (substring term (match-end 0))
12727 mm (if re-p
12728 `(string-match ,(substring kwd 1 -1) todo)
12729 (list 'equal 'todo kwd))
12730 mm (if minus (list 'not mm) mm))
12731 (push mm todomatcher))
12732 (push (if (> (length todomatcher) 1)
12733 (cons 'and todomatcher)
12734 (car todomatcher))
12735 orlist)
12736 (setq todomatcher nil))
12737 (setq todomatcher (if (> (length orlist) 1)
12738 (cons 'or orlist) (car orlist))))
12740 ;; Return the string and lisp forms of the matcher
12741 (setq matcher (if todomatcher
12742 (list 'and tagsmatcher todomatcher)
12743 tagsmatcher))
12744 (cons match0 matcher)))
12746 (defun org-op-to-function (op &optional stringp)
12747 "Turn an operator into the appropriate function."
12748 (setq op
12749 (cond
12750 ((equal op "<" ) '(< string< org-time<))
12751 ((equal op ">" ) '(> org-string> org-time>))
12752 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12753 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12754 ((member op '("=" "==")) '(= string= org-time=))
12755 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12756 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12758 (defun org<> (a b) (not (= a b)))
12759 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12760 (defun org-string>= (a b) (not (string< a b)))
12761 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12762 (defun org-string<> (a b) (not (string= a b)))
12763 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12764 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12765 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12766 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12767 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12768 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12769 (defun org-2ft (s)
12770 "Convert S to a floating point time.
12771 If S is already a number, just return it. If it is a string, parse
12772 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12773 (cond
12774 ((numberp s) s)
12775 ((stringp s)
12776 (condition-case nil
12777 (float-time (apply 'encode-time (org-parse-time-string s)))
12778 (error 0.)))
12779 (t 0.)))
12781 (defun org-time-today ()
12782 "Time in seconds today at 0:00.
12783 Returns the float number of seconds since the beginning of the
12784 epoch to the beginning of today (00:00)."
12785 (float-time (apply 'encode-time
12786 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12788 (defun org-matcher-time (s)
12789 "Interpret a time comparison value."
12790 (save-match-data
12791 (cond
12792 ((string= s "<now>") (float-time))
12793 ((string= s "<today>") (org-time-today))
12794 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12795 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12796 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12797 (+ (org-time-today)
12798 (* (string-to-number (match-string 1 s))
12799 (cdr (assoc (match-string 2 s)
12800 '(("d" . 86400.0) ("w" . 604800.0)
12801 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12802 (t (org-2ft s)))))
12804 (defun org-match-any-p (re list)
12805 "Does re match any element of list?"
12806 (setq list (mapcar (lambda (x) (string-match re x)) list))
12807 (delq nil list))
12809 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12810 (defvar org-tags-overlay (make-overlay 1 1))
12811 (org-detach-overlay org-tags-overlay)
12813 (defun org-get-local-tags-at (&optional pos)
12814 "Get a list of tags defined in the current headline."
12815 (org-get-tags-at pos 'local))
12817 (defun org-get-local-tags ()
12818 "Get a list of tags defined in the current headline."
12819 (org-get-tags-at nil 'local))
12821 (defun org-get-tags-at (&optional pos local)
12822 "Get a list of all headline tags applicable at POS.
12823 POS defaults to point. If tags are inherited, the list contains
12824 the targets in the same sequence as the headlines appear, i.e.
12825 the tags of the current headline come last.
12826 When LOCAL is non-nil, only return tags from the current headline,
12827 ignore inherited ones."
12828 (interactive)
12829 (if (and org-trust-scanner-tags
12830 (or (not pos) (equal pos (point)))
12831 (not local))
12832 org-scanner-tags
12833 (let (tags ltags lastpos parent)
12834 (save-excursion
12835 (save-restriction
12836 (widen)
12837 (goto-char (or pos (point)))
12838 (save-match-data
12839 (catch 'done
12840 (condition-case nil
12841 (progn
12842 (org-back-to-heading t)
12843 (while (not (equal lastpos (point)))
12844 (setq lastpos (point))
12845 (when (looking-at
12846 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12847 (setq ltags (org-split-string
12848 (org-match-string-no-properties 1) ":"))
12849 (when parent
12850 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12851 (setq tags (append
12852 (if parent
12853 (org-remove-uninherited-tags ltags)
12854 ltags)
12855 tags)))
12856 (or org-use-tag-inheritance (throw 'done t))
12857 (if local (throw 'done t))
12858 (or (org-up-heading-safe) (error nil))
12859 (setq parent t)))
12860 (error nil)))))
12861 (if local
12862 tags
12863 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12865 (defun org-add-prop-inherited (s)
12866 (add-text-properties 0 (length s) '(inherited t) s)
12869 (defun org-toggle-tag (tag &optional onoff)
12870 "Toggle the tag TAG for the current line.
12871 If ONOFF is `on' or `off', don't toggle but set to this state."
12872 (let (res current)
12873 (save-excursion
12874 (org-back-to-heading t)
12875 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12876 (point-at-eol) t)
12877 (progn
12878 (setq current (match-string 1))
12879 (replace-match ""))
12880 (setq current ""))
12881 (setq current (nreverse (org-split-string current ":")))
12882 (cond
12883 ((eq onoff 'on)
12884 (setq res t)
12885 (or (member tag current) (push tag current)))
12886 ((eq onoff 'off)
12887 (or (not (member tag current)) (setq current (delete tag current))))
12888 (t (if (member tag current)
12889 (setq current (delete tag current))
12890 (setq res t)
12891 (push tag current))))
12892 (end-of-line 1)
12893 (if current
12894 (progn
12895 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12896 (org-set-tags nil t))
12897 (delete-horizontal-space))
12898 (run-hooks 'org-after-tags-change-hook))
12899 res))
12901 (defun org-align-tags-here (to-col)
12902 ;; Assumes that this is a headline
12903 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12904 (beginning-of-line 1)
12905 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12906 (< pos (match-beginning 2)))
12907 (progn
12908 (setq tags-l (- (match-end 2) (match-beginning 2)))
12909 (goto-char (match-beginning 1))
12910 (insert " ")
12911 (delete-region (point) (1+ (match-beginning 2)))
12912 (setq ncol (max (1+ (current-column))
12913 (1+ col)
12914 (if (> to-col 0)
12915 to-col
12916 (- (abs to-col) tags-l))))
12917 (setq p (point))
12918 (insert (make-string (- ncol (current-column)) ?\ ))
12919 (setq ncol (current-column))
12920 (when indent-tabs-mode (tabify p (point-at-eol)))
12921 (org-move-to-column (min ncol col) t))
12922 (goto-char pos))))
12924 (defun org-set-tags-command (&optional arg just-align)
12925 "Call the set-tags command for the current entry."
12926 (interactive "P")
12927 (if (org-on-heading-p)
12928 (org-set-tags arg just-align)
12929 (save-excursion
12930 (org-back-to-heading t)
12931 (org-set-tags arg just-align))))
12933 (defun org-set-tags-to (data)
12934 "Set the tags of the current entry to DATA, replacing the current tags.
12935 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12936 If DATA is nil or the empty string, any tags will be removed."
12937 (interactive "sTags: ")
12938 (setq data
12939 (cond
12940 ((eq data nil) "")
12941 ((equal data "") "")
12942 ((stringp data)
12943 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12944 ":"))
12945 ((listp data)
12946 (concat ":" (mapconcat 'identity data ":") ":"))
12947 (t nil)))
12948 (when data
12949 (save-excursion
12950 (org-back-to-heading t)
12951 (when (looking-at org-complex-heading-regexp)
12952 (if (match-end 5)
12953 (progn
12954 (goto-char (match-beginning 5))
12955 (insert data)
12956 (delete-region (point) (point-at-eol))
12957 (org-set-tags nil 'align))
12958 (goto-char (point-at-eol))
12959 (insert " " data)
12960 (org-set-tags nil 'align)))
12961 (beginning-of-line 1)
12962 (if (looking-at ".*?\\([ \t]+\\)$")
12963 (delete-region (match-beginning 1) (match-end 1))))))
12965 (defun org-align-all-tags ()
12966 "Align the tags i all headings."
12967 (interactive)
12968 (save-excursion
12969 (or (ignore-errors (org-back-to-heading t))
12970 (outline-next-heading))
12971 (if (org-on-heading-p)
12972 (org-set-tags t)
12973 (message "No headings"))))
12975 (defvar org-indent-indentation-per-level)
12976 (defun org-set-tags (&optional arg just-align)
12977 "Set the tags for the current headline.
12978 With prefix ARG, realign all tags in headings in the current buffer."
12979 (interactive "P")
12980 (let* ((re (concat "^" outline-regexp))
12981 (current (org-get-tags-string))
12982 (col (current-column))
12983 (org-setting-tags t)
12984 table current-tags inherited-tags ; computed below when needed
12985 tags p0 c0 c1 rpl di tc level)
12986 (if arg
12987 (save-excursion
12988 (goto-char (point-min))
12989 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12990 (while (re-search-forward re nil t)
12991 (org-set-tags nil t)
12992 (end-of-line 1)))
12993 (message "All tags realigned to column %d" org-tags-column))
12994 (if just-align
12995 (setq tags current)
12996 ;; Get a new set of tags from the user
12997 (save-excursion
12998 (setq table (append org-tag-persistent-alist
12999 (or org-tag-alist (org-get-buffer-tags))
13000 (and
13001 org-complete-tags-always-offer-all-agenda-tags
13002 (org-global-tags-completion-table
13003 (org-agenda-files))))
13004 org-last-tags-completion-table table
13005 current-tags (org-split-string current ":")
13006 inherited-tags (nreverse
13007 (nthcdr (length current-tags)
13008 (nreverse (org-get-tags-at))))
13009 tags
13010 (if (or (eq t org-use-fast-tag-selection)
13011 (and org-use-fast-tag-selection
13012 (delq nil (mapcar 'cdr table))))
13013 (org-fast-tag-selection
13014 current-tags inherited-tags table
13015 (if org-fast-tag-selection-include-todo
13016 org-todo-key-alist))
13017 (let ((org-add-colon-after-tag-completion t))
13018 (org-trim
13019 (org-icompleting-read "Tags: "
13020 'org-tags-completion-function
13021 nil nil current 'org-tags-history))))))
13022 (while (string-match "[-+&]+" tags)
13023 ;; No boolean logic, just a list
13024 (setq tags (replace-match ":" t t tags))))
13026 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13028 (if org-tags-sort-function
13029 (setq tags (mapconcat 'identity
13030 (sort (org-split-string
13031 tags (org-re "[^[:alnum:]_@#%]+"))
13032 org-tags-sort-function) ":")))
13034 (if (string-match "\\`[\t ]*\\'" tags)
13035 (setq tags "")
13036 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13037 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13039 ;; Insert new tags at the correct column
13040 (beginning-of-line 1)
13041 (setq level (or (and (looking-at org-outline-regexp)
13042 (- (match-end 0) (point) 1))
13044 (cond
13045 ((and (equal current "") (equal tags "")))
13046 ((re-search-forward
13047 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13048 (point-at-eol) t)
13049 (if (equal tags "")
13050 (setq rpl "")
13051 (goto-char (match-beginning 0))
13052 (setq c0 (current-column)
13053 ;; compute offset for the case of org-indent-mode active
13054 di (if org-indent-mode
13055 (* (1- org-indent-indentation-per-level) (1- level))
13057 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13058 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13059 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13060 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13061 (replace-match rpl t t)
13062 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13063 tags)
13064 (t (error "Tags alignment failed")))
13065 (org-move-to-column col)
13066 (unless just-align
13067 (run-hooks 'org-after-tags-change-hook)))))
13069 (defun org-change-tag-in-region (beg end tag off)
13070 "Add or remove TAG for each entry in the region.
13071 This works in the agenda, and also in an org-mode buffer."
13072 (interactive
13073 (list (region-beginning) (region-end)
13074 (let ((org-last-tags-completion-table
13075 (if (org-mode-p)
13076 (org-get-buffer-tags)
13077 (org-global-tags-completion-table))))
13078 (org-icompleting-read
13079 "Tag: " 'org-tags-completion-function nil nil nil
13080 'org-tags-history))
13081 (progn
13082 (message "[s]et or [r]emove? ")
13083 (equal (read-char-exclusive) ?r))))
13084 (if (fboundp 'deactivate-mark) (deactivate-mark))
13085 (let ((agendap (equal major-mode 'org-agenda-mode))
13086 l1 l2 m buf pos newhead (cnt 0))
13087 (goto-char end)
13088 (setq l2 (1- (org-current-line)))
13089 (goto-char beg)
13090 (setq l1 (org-current-line))
13091 (loop for l from l1 to l2 do
13092 (org-goto-line l)
13093 (setq m (get-text-property (point) 'org-hd-marker))
13094 (when (or (and (org-mode-p) (org-on-heading-p))
13095 (and agendap m))
13096 (setq buf (if agendap (marker-buffer m) (current-buffer))
13097 pos (if agendap m (point)))
13098 (with-current-buffer buf
13099 (save-excursion
13100 (save-restriction
13101 (goto-char pos)
13102 (setq cnt (1+ cnt))
13103 (org-toggle-tag tag (if off 'off 'on))
13104 (setq newhead (org-get-heading)))))
13105 (and agendap (org-agenda-change-all-lines newhead m))))
13106 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13108 (defun org-tags-completion-function (string predicate &optional flag)
13109 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13110 (confirm (lambda (x) (stringp (car x)))))
13111 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13112 (setq s1 (match-string 1 string)
13113 s2 (match-string 2 string))
13114 (setq s1 "" s2 string))
13115 (cond
13116 ((eq flag nil)
13117 ;; try completion
13118 (setq rtn (try-completion s2 ctable confirm))
13119 (if (stringp rtn)
13120 (setq rtn
13121 (concat s1 s2 (substring rtn (length s2))
13122 (if (and org-add-colon-after-tag-completion
13123 (assoc rtn ctable))
13124 ":" ""))))
13125 rtn)
13126 ((eq flag t)
13127 ;; all-completions
13128 (all-completions s2 ctable confirm)
13130 ((eq flag 'lambda)
13131 ;; exact match?
13132 (assoc s2 ctable)))
13135 (defun org-fast-tag-insert (kwd tags face &optional end)
13136 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13137 (insert (format "%-12s" (concat kwd ":"))
13138 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13139 (or end "")))
13141 (defun org-fast-tag-show-exit (flag)
13142 (save-excursion
13143 (org-goto-line 3)
13144 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13145 (replace-match ""))
13146 (when flag
13147 (end-of-line 1)
13148 (org-move-to-column (- (window-width) 19) t)
13149 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13151 (defun org-set-current-tags-overlay (current prefix)
13152 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13153 (if (featurep 'xemacs)
13154 (org-overlay-display org-tags-overlay (concat prefix s)
13155 'secondary-selection)
13156 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13157 (org-overlay-display org-tags-overlay (concat prefix s)))))
13159 (defvar org-last-tag-selection-key nil)
13160 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13161 "Fast tag selection with single keys.
13162 CURRENT is the current list of tags in the headline, INHERITED is the
13163 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13164 possibly with grouping information. TODO-TABLE is a similar table with
13165 TODO keywords, should these have keys assigned to them.
13166 If the keys are nil, a-z are automatically assigned.
13167 Returns the new tags string, or nil to not change the current settings."
13168 (let* ((fulltable (append table todo-table))
13169 (maxlen (apply 'max (mapcar
13170 (lambda (x)
13171 (if (stringp (car x)) (string-width (car x)) 0))
13172 fulltable)))
13173 (buf (current-buffer))
13174 (expert (eq org-fast-tag-selection-single-key 'expert))
13175 (buffer-tags nil)
13176 (fwidth (+ maxlen 3 1 3))
13177 (ncol (/ (- (window-width) 4) fwidth))
13178 (i-face 'org-done)
13179 (c-face 'org-todo)
13180 tg cnt e c char c1 c2 ntable tbl rtn
13181 ov-start ov-end ov-prefix
13182 (exit-after-next org-fast-tag-selection-single-key)
13183 (done-keywords org-done-keywords)
13184 groups ingroup)
13185 (save-excursion
13186 (beginning-of-line 1)
13187 (if (looking-at
13188 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13189 (setq ov-start (match-beginning 1)
13190 ov-end (match-end 1)
13191 ov-prefix "")
13192 (setq ov-start (1- (point-at-eol))
13193 ov-end (1+ ov-start))
13194 (skip-chars-forward "^\n\r")
13195 (setq ov-prefix
13196 (concat
13197 (buffer-substring (1- (point)) (point))
13198 (if (> (current-column) org-tags-column)
13200 (make-string (- org-tags-column (current-column)) ?\ ))))))
13201 (move-overlay org-tags-overlay ov-start ov-end)
13202 (save-window-excursion
13203 (if expert
13204 (set-buffer (get-buffer-create " *Org tags*"))
13205 (delete-other-windows)
13206 (split-window-vertically)
13207 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13208 (erase-buffer)
13209 (org-set-local 'org-done-keywords done-keywords)
13210 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13211 (org-fast-tag-insert "Current" current c-face "\n\n")
13212 (org-fast-tag-show-exit exit-after-next)
13213 (org-set-current-tags-overlay current ov-prefix)
13214 (setq tbl fulltable char ?a cnt 0)
13215 (while (setq e (pop tbl))
13216 (cond
13217 ((equal (car e) :startgroup)
13218 (push '() groups) (setq ingroup t)
13219 (when (not (= cnt 0))
13220 (setq cnt 0)
13221 (insert "\n"))
13222 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13223 ((equal (car e) :endgroup)
13224 (setq ingroup nil cnt 0)
13225 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13226 ((equal e '(:newline))
13227 (when (not (= cnt 0))
13228 (setq cnt 0)
13229 (insert "\n")
13230 (setq e (car tbl))
13231 (while (equal (car tbl) '(:newline))
13232 (insert "\n")
13233 (setq tbl (cdr tbl)))))
13235 (setq tg (copy-sequence (car e)) c2 nil)
13236 (if (cdr e)
13237 (setq c (cdr e))
13238 ;; automatically assign a character.
13239 (setq c1 (string-to-char
13240 (downcase (substring
13241 tg (if (= (string-to-char tg) ?@) 1 0)))))
13242 (if (or (rassoc c1 ntable) (rassoc c1 table))
13243 (while (or (rassoc char ntable) (rassoc char table))
13244 (setq char (1+ char)))
13245 (setq c2 c1))
13246 (setq c (or c2 char)))
13247 (if ingroup (push tg (car groups)))
13248 (setq tg (org-add-props tg nil 'face
13249 (cond
13250 ((not (assoc tg table))
13251 (org-get-todo-face tg))
13252 ((member tg current) c-face)
13253 ((member tg inherited) i-face)
13254 (t nil))))
13255 (if (and (= cnt 0) (not ingroup)) (insert " "))
13256 (insert "[" c "] " tg (make-string
13257 (- fwidth 4 (length tg)) ?\ ))
13258 (push (cons tg c) ntable)
13259 (when (= (setq cnt (1+ cnt)) ncol)
13260 (insert "\n")
13261 (if ingroup (insert " "))
13262 (setq cnt 0)))))
13263 (setq ntable (nreverse ntable))
13264 (insert "\n")
13265 (goto-char (point-min))
13266 (if (not expert) (org-fit-window-to-buffer))
13267 (setq rtn
13268 (catch 'exit
13269 (while t
13270 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13271 (if (not groups) "no " "")
13272 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13273 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13274 (setq org-last-tag-selection-key c)
13275 (cond
13276 ((= c ?\r) (throw 'exit t))
13277 ((= c ?!)
13278 (setq groups (not groups))
13279 (goto-char (point-min))
13280 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13281 ((= c ?\C-c)
13282 (if (not expert)
13283 (org-fast-tag-show-exit
13284 (setq exit-after-next (not exit-after-next)))
13285 (setq expert nil)
13286 (delete-other-windows)
13287 (set-window-buffer (split-window-vertically) " *Org tags*")
13288 (org-switch-to-buffer-other-window " *Org tags*")
13289 (org-fit-window-to-buffer)))
13290 ((or (= c ?\C-g)
13291 (and (= c ?q) (not (rassoc c ntable))))
13292 (org-detach-overlay org-tags-overlay)
13293 (setq quit-flag t))
13294 ((= c ?\ )
13295 (setq current nil)
13296 (if exit-after-next (setq exit-after-next 'now)))
13297 ((= c ?\t)
13298 (condition-case nil
13299 (setq tg (org-icompleting-read
13300 "Tag: "
13301 (or buffer-tags
13302 (with-current-buffer buf
13303 (org-get-buffer-tags)))))
13304 (quit (setq tg "")))
13305 (when (string-match "\\S-" tg)
13306 (add-to-list 'buffer-tags (list tg))
13307 (if (member tg current)
13308 (setq current (delete tg current))
13309 (push tg current)))
13310 (if exit-after-next (setq exit-after-next 'now)))
13311 ((setq e (rassoc c todo-table) tg (car e))
13312 (with-current-buffer buf
13313 (save-excursion (org-todo tg)))
13314 (if exit-after-next (setq exit-after-next 'now)))
13315 ((setq e (rassoc c ntable) tg (car e))
13316 (if (member tg current)
13317 (setq current (delete tg current))
13318 (loop for g in groups do
13319 (if (member tg g)
13320 (mapc (lambda (x)
13321 (setq current (delete x current)))
13322 g)))
13323 (push tg current))
13324 (if exit-after-next (setq exit-after-next 'now))))
13326 ;; Create a sorted list
13327 (setq current
13328 (sort current
13329 (lambda (a b)
13330 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13331 (if (eq exit-after-next 'now) (throw 'exit t))
13332 (goto-char (point-min))
13333 (beginning-of-line 2)
13334 (delete-region (point) (point-at-eol))
13335 (org-fast-tag-insert "Current" current c-face)
13336 (org-set-current-tags-overlay current ov-prefix)
13337 (while (re-search-forward
13338 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13339 (setq tg (match-string 1))
13340 (add-text-properties
13341 (match-beginning 1) (match-end 1)
13342 (list 'face
13343 (cond
13344 ((member tg current) c-face)
13345 ((member tg inherited) i-face)
13346 (t (get-text-property (match-beginning 1) 'face))))))
13347 (goto-char (point-min)))))
13348 (org-detach-overlay org-tags-overlay)
13349 (if rtn
13350 (mapconcat 'identity current ":")
13351 nil))))
13353 (defun org-get-tags-string ()
13354 "Get the TAGS string in the current headline."
13355 (unless (org-on-heading-p t)
13356 (error "Not on a heading"))
13357 (save-excursion
13358 (beginning-of-line 1)
13359 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13360 (org-match-string-no-properties 1)
13361 "")))
13363 (defun org-get-tags ()
13364 "Get the list of tags specified in the current headline."
13365 (org-split-string (org-get-tags-string) ":"))
13367 (defun org-get-buffer-tags ()
13368 "Get a table of all tags used in the buffer, for completion."
13369 (let (tags)
13370 (save-excursion
13371 (goto-char (point-min))
13372 (while (re-search-forward
13373 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13374 (when (equal (char-after (point-at-bol 0)) ?*)
13375 (mapc (lambda (x) (add-to-list 'tags x))
13376 (org-split-string (org-match-string-no-properties 1) ":")))))
13377 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13378 (mapcar 'list tags)))
13380 ;;;; The mapping API
13382 ;;;###autoload
13383 (defun org-map-entries (func &optional match scope &rest skip)
13384 "Call FUNC at each headline selected by MATCH in SCOPE.
13386 FUNC is a function or a lisp form. The function will be called without
13387 arguments, with the cursor positioned at the beginning of the headline.
13388 The return values of all calls to the function will be collected and
13389 returned as a list.
13391 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13392 does not need to preserve point. After evaluation, the cursor will be
13393 moved to the end of the line (presumably of the headline of the
13394 processed entry) and search continues from there. Under some
13395 circumstances, this may not produce the wanted results. For example,
13396 if you have removed (e.g. archived) the current (sub)tree it could
13397 mean that the next entry will be skipped entirely. In such cases, you
13398 can specify the position from where search should continue by making
13399 FUNC set the variable `org-map-continue-from' to the desired buffer
13400 position.
13402 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13403 Only headlines that are matched by this query will be considered during
13404 the iteration. When MATCH is nil or t, all headlines will be
13405 visited by the iteration.
13407 SCOPE determines the scope of this command. It can be any of:
13409 nil The current buffer, respecting the restriction if any
13410 tree The subtree started with the entry at point
13411 file The current buffer, without restriction
13412 file-with-archives
13413 The current buffer, and any archives associated with it
13414 agenda All agenda files
13415 agenda-with-archives
13416 All agenda files with any archive files associated with them
13417 \(file1 file2 ...)
13418 If this is a list, all files in the list will be scanned
13420 The remaining args are treated as settings for the skipping facilities of
13421 the scanner. The following items can be given here:
13423 archive skip trees with the archive tag.
13424 comment skip trees with the COMMENT keyword
13425 function or Emacs Lisp form:
13426 will be used as value for `org-agenda-skip-function', so whenever
13427 the function returns t, FUNC will not be called for that
13428 entry and search will continue from the point where the
13429 function leaves it.
13431 If your function needs to retrieve the tags including inherited tags
13432 at the *current* entry, you can use the value of the variable
13433 `org-scanner-tags' which will be much faster than getting the value
13434 with `org-get-tags-at'. If your function gets properties with
13435 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13436 to t around the call to `org-entry-properties' to get the same speedup.
13437 Note that if your function moves around to retrieve tags and properties at
13438 a *different* entry, you cannot use these techniques."
13439 (let* ((org-agenda-archives-mode nil) ; just to make sure
13440 (org-agenda-skip-archived-trees (memq 'archive skip))
13441 (org-agenda-skip-comment-trees (memq 'comment skip))
13442 (org-agenda-skip-function
13443 (car (org-delete-all '(comment archive) skip)))
13444 (org-tags-match-list-sublevels t)
13445 matcher file res
13446 org-todo-keywords-for-agenda
13447 org-done-keywords-for-agenda
13448 org-todo-keyword-alist-for-agenda
13449 org-drawers-for-agenda
13450 org-tag-alist-for-agenda)
13452 (cond
13453 ((eq match t) (setq matcher t))
13454 ((eq match nil) (setq matcher t))
13455 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13457 (save-excursion
13458 (save-restriction
13459 (when (eq scope 'tree)
13460 (org-back-to-heading t)
13461 (org-narrow-to-subtree)
13462 (setq scope nil))
13464 (if (not scope)
13465 (progn
13466 (org-prepare-agenda-buffers
13467 (list (buffer-file-name (current-buffer))))
13468 (setq res (org-scan-tags func matcher)))
13469 ;; Get the right scope
13470 (cond
13471 ((and scope (listp scope) (symbolp (car scope)))
13472 (setq scope (eval scope)))
13473 ((eq scope 'agenda)
13474 (setq scope (org-agenda-files t)))
13475 ((eq scope 'agenda-with-archives)
13476 (setq scope (org-agenda-files t))
13477 (setq scope (org-add-archive-files scope)))
13478 ((eq scope 'file)
13479 (setq scope (list (buffer-file-name))))
13480 ((eq scope 'file-with-archives)
13481 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13482 (org-prepare-agenda-buffers scope)
13483 (while (setq file (pop scope))
13484 (with-current-buffer (org-find-base-buffer-visiting file)
13485 (save-excursion
13486 (save-restriction
13487 (widen)
13488 (goto-char (point-min))
13489 (setq res (append res (org-scan-tags func matcher))))))))))
13490 res))
13492 ;;;; Properties
13494 ;;; Setting and retrieving properties
13496 (defconst org-special-properties
13497 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13498 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13499 "The special properties valid in Org-mode.
13501 These are properties that are not defined in the property drawer,
13502 but in some other way.")
13504 (defconst org-default-properties
13505 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13506 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13507 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13508 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13509 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13510 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13511 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13512 "Some properties that are used by Org-mode for various purposes.
13513 Being in this list makes sure that they are offered for completion.")
13515 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13516 "Regular expression matching the first line of a property drawer.")
13518 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13519 "Regular expression matching the last line of a property drawer.")
13521 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13522 "Regular expression matching the first line of a property drawer.")
13524 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13525 "Regular expression matching the first line of a property drawer.")
13527 (defconst org-property-drawer-re
13528 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13529 org-property-end-re "\\)\n?")
13530 "Matches an entire property drawer.")
13532 (defconst org-clock-drawer-re
13533 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13534 org-property-end-re "\\)\n?")
13535 "Matches an entire clock drawer.")
13537 (defsubst org-re-property (property)
13538 "Return a regexp matching PROPERTY.
13539 Match group 1 will be set to the value "
13540 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13542 (defun org-property-action ()
13543 "Do an action on properties."
13544 (interactive)
13545 (let (c)
13546 (org-at-property-p)
13547 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13548 (setq c (read-char-exclusive))
13549 (cond
13550 ((equal c ?s)
13551 (call-interactively 'org-set-property))
13552 ((equal c ?d)
13553 (call-interactively 'org-delete-property))
13554 ((equal c ?D)
13555 (call-interactively 'org-delete-property-globally))
13556 ((equal c ?c)
13557 (call-interactively 'org-compute-property-at-point))
13558 (t (error "No such property action %c" c)))))
13560 (defun org-set-effort (&optional value)
13561 "Set the effort property of the current entry.
13562 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13563 allowed value."
13564 (interactive "P")
13565 (if (equal value 0) (setq value 10))
13566 (let* ((completion-ignore-case t)
13567 (prop org-effort-property)
13568 (cur (org-entry-get nil prop))
13569 (allowed (org-property-get-allowed-values nil prop 'table))
13570 (existing (mapcar 'list (org-property-values prop)))
13572 (val (cond
13573 ((stringp value) value)
13574 ((and allowed (integerp value))
13575 (or (car (nth (1- value) allowed))
13576 (car (org-last allowed))))
13577 (allowed
13578 (message "Select 1-9,0, [RET%s]: %s"
13579 (if cur (concat "=" cur) "")
13580 (mapconcat 'car allowed " "))
13581 (setq rpl (read-char-exclusive))
13582 (if (equal rpl ?\r)
13584 (setq rpl (- rpl ?0))
13585 (if (equal rpl 0) (setq rpl 10))
13586 (if (and (> rpl 0) (<= rpl (length allowed)))
13587 (car (nth (1- rpl) allowed))
13588 (org-completing-read "Effort: " allowed nil))))
13590 (let (org-completion-use-ido org-completion-use-iswitchb)
13591 (org-completing-read
13592 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13593 (concat "[" cur "]") "")
13594 ": ")
13595 existing nil nil "" nil cur))))))
13596 (unless (equal (org-entry-get nil prop) val)
13597 (org-entry-put nil prop val))
13598 (message "%s is now %s" prop val)))
13600 (defun org-at-property-p ()
13601 "Is cursor inside a property drawer?"
13602 (save-excursion
13603 (beginning-of-line 1)
13604 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13605 (save-match-data ;; Used by calling procedures
13606 (let ((p (point))
13607 (range (unless (org-before-first-heading-p)
13608 (org-get-property-block))))
13609 (and range (<= (car range) p) (< p (cdr range))))))))
13611 (defun org-get-property-block (&optional beg end force)
13612 "Return the (beg . end) range of the body of the property drawer.
13613 BEG and END can be beginning and end of subtree, if not given
13614 they will be found.
13615 If the drawer does not exist and FORCE is non-nil, create the drawer."
13616 (catch 'exit
13617 (save-excursion
13618 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13619 (end (or end (progn (outline-next-heading) (point)))))
13620 (goto-char beg)
13621 (if (re-search-forward org-property-start-re end t)
13622 (setq beg (1+ (match-end 0)))
13623 (if force
13624 (save-excursion
13625 (org-insert-property-drawer)
13626 (setq end (progn (outline-next-heading) (point))))
13627 (throw 'exit nil))
13628 (goto-char beg)
13629 (if (re-search-forward org-property-start-re end t)
13630 (setq beg (1+ (match-end 0)))))
13631 (if (re-search-forward org-property-end-re end t)
13632 (setq end (match-beginning 0))
13633 (or force (throw 'exit nil))
13634 (goto-char beg)
13635 (setq end beg)
13636 (org-indent-line-function)
13637 (insert ":END:\n"))
13638 (cons beg end)))))
13640 (defun org-entry-properties (&optional pom which specific)
13641 "Get all properties of the entry at point-or-marker POM.
13642 This includes the TODO keyword, the tags, time strings for deadline,
13643 scheduled, and clocking, and any additional properties defined in the
13644 entry. The return value is an alist, keys may occur multiple times
13645 if the property key was used several times.
13646 POM may also be nil, in which case the current entry is used.
13647 If WHICH is nil or `all', get all properties. If WHICH is
13648 `special' or `standard', only get that subclass. If WHICH
13649 is a string only get exactly this property. SPECIFIC can be a string, the
13650 specific property we are interested in. Specifying it can speed
13651 things up because then unnecessary parsing is avoided."
13652 (setq which (or which 'all))
13653 (org-with-point-at pom
13654 (let ((clockstr (substring org-clock-string 0 -1))
13655 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13656 (case-fold-search nil)
13657 beg end range props sum-props key key1 value string clocksum)
13658 (save-excursion
13659 (when (condition-case nil
13660 (and (org-mode-p) (org-back-to-heading t))
13661 (error nil))
13662 (setq beg (point))
13663 (setq sum-props (get-text-property (point) 'org-summaries))
13664 (setq clocksum (get-text-property (point) :org-clock-minutes))
13665 (outline-next-heading)
13666 (setq end (point))
13667 (when (memq which '(all special))
13668 ;; Get the special properties, like TODO and tags
13669 (goto-char beg)
13670 (when (and (or (not specific) (string= specific "TODO"))
13671 (looking-at org-todo-line-regexp) (match-end 2))
13672 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13673 (when (and (or (not specific) (string= specific "PRIORITY"))
13674 (looking-at org-priority-regexp))
13675 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13676 (when (or (not specific) (string= specific "FILE"))
13677 (push (cons "FILE" buffer-file-name) props))
13678 (when (and (or (not specific) (string= specific "TAGS"))
13679 (setq value (org-get-tags-string))
13680 (string-match "\\S-" value))
13681 (push (cons "TAGS" value) props))
13682 (when (and (or (not specific) (string= specific "ALLTAGS"))
13683 (setq value (org-get-tags-at)))
13684 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13685 ":"))
13686 props))
13687 (when (or (not specific) (string= specific "BLOCKED"))
13688 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13689 (when (or (not specific)
13690 (member specific
13691 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13692 "TIMESTAMP" "TIMESTAMP_IA")))
13693 (catch 'match
13694 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13695 (setq key (if (match-end 1)
13696 (substring (org-match-string-no-properties 1)
13697 0 -1))
13698 string (if (equal key clockstr)
13699 (org-no-properties
13700 (org-trim
13701 (buffer-substring
13702 (match-beginning 3) (goto-char
13703 (point-at-eol)))))
13704 (substring (org-match-string-no-properties 3)
13705 1 -1)))
13706 ;; Get the correct property name from the key. This is
13707 ;; necessary if the user has configured time keywords.
13708 (setq key1 (concat key ":"))
13709 (cond
13710 ((not key)
13711 (setq key
13712 (if (= (char-after (match-beginning 3)) ?\[)
13713 "TIMESTAMP_IA" "TIMESTAMP")))
13714 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13715 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13716 ((equal key1 org-closed-string) (setq key "CLOSED"))
13717 ((equal key1 org-clock-string) (setq key "CLOCK")))
13718 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13719 (progn
13720 (push (cons key string) props)
13721 ;; no need to search further if match is found
13722 (throw 'match t))
13723 (when (or (equal key "CLOCK") (not (assoc key props)))
13724 (push (cons key string) props))))))
13727 (when (memq which '(all standard))
13728 ;; Get the standard properties, like :PROP: ...
13729 (setq range (org-get-property-block beg end))
13730 (when range
13731 (goto-char (car range))
13732 (while (re-search-forward
13733 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13734 (cdr range) t)
13735 (setq key (org-match-string-no-properties 1)
13736 value (org-trim (or (org-match-string-no-properties 2) "")))
13737 (unless (member key excluded)
13738 (push (cons key (or value "")) props)))))
13739 (if clocksum
13740 (push (cons "CLOCKSUM"
13741 (org-columns-number-to-string (/ (float clocksum) 60.)
13742 'add_times))
13743 props))
13744 (unless (assoc "CATEGORY" props)
13745 (push (cons "CATEGORY" (org-get-category)) props))
13746 (append sum-props (nreverse props)))))))
13748 (defun org-entry-get (pom property &optional inherit literal-nil)
13749 "Get value of PROPERTY for entry at point-or-marker POM.
13750 If INHERIT is non-nil and the entry does not have the property,
13751 then also check higher levels of the hierarchy.
13752 If INHERIT is the symbol `selective', use inheritance only if the setting
13753 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13754 If the property is present but empty, the return value is the empty string.
13755 If the property is not present at all, nil is returned.
13757 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13758 do not interpret it as the list atom nil. This is used for inheritance
13759 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13760 (org-with-point-at pom
13761 (if (and inherit (if (eq inherit 'selective)
13762 (org-property-inherit-p property)
13764 (org-entry-get-with-inheritance property literal-nil)
13765 (if (member property org-special-properties)
13766 ;; We need a special property. Use `org-entry-properties' to
13767 ;; retrieve it, but specify the wanted property
13768 (cdr (assoc property (org-entry-properties nil 'special property)))
13769 (let ((range (unless (org-before-first-heading-p)
13770 (org-get-property-block))))
13771 (if (and range
13772 (goto-char (car range))
13773 (re-search-forward
13774 (org-re-property property)
13775 (cdr range) t))
13776 ;; Found the property, return it.
13777 (if (match-end 1)
13778 (if literal-nil
13779 (org-match-string-no-properties 1)
13780 (org-not-nil (org-match-string-no-properties 1)))
13781 "")))))))
13783 (defun org-property-or-variable-value (var &optional inherit)
13784 "Check if there is a property fixing the value of VAR.
13785 If yes, return this value. If not, return the current value of the variable."
13786 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13787 (if (and prop (stringp prop) (string-match "\\S-" prop))
13788 (read prop)
13789 (symbol-value var))))
13791 (defun org-entry-delete (pom property)
13792 "Delete the property PROPERTY from entry at point-or-marker POM."
13793 (org-with-point-at pom
13794 (if (member property org-special-properties)
13795 nil ; cannot delete these properties.
13796 (let ((range (org-get-property-block)))
13797 (if (and range
13798 (goto-char (car range))
13799 (re-search-forward
13800 (org-re-property property)
13801 (cdr range) t))
13802 (progn
13803 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13805 nil)))))
13807 ;; Multi-values properties are properties that contain multiple values
13808 ;; These values are assumed to be single words, separated by whitespace.
13809 (defun org-entry-add-to-multivalued-property (pom property value)
13810 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13811 (let* ((old (org-entry-get pom property))
13812 (values (and old (org-split-string old "[ \t]"))))
13813 (setq value (org-entry-protect-space value))
13814 (unless (member value values)
13815 (setq values (cons value values))
13816 (org-entry-put pom property
13817 (mapconcat 'identity values " ")))))
13819 (defun org-entry-remove-from-multivalued-property (pom property value)
13820 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13821 (let* ((old (org-entry-get pom property))
13822 (values (and old (org-split-string old "[ \t]"))))
13823 (setq value (org-entry-protect-space value))
13824 (when (member value values)
13825 (setq values (delete value values))
13826 (org-entry-put pom property
13827 (mapconcat 'identity values " ")))))
13829 (defun org-entry-member-in-multivalued-property (pom property value)
13830 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13831 (let* ((old (org-entry-get pom property))
13832 (values (and old (org-split-string old "[ \t]"))))
13833 (setq value (org-entry-protect-space value))
13834 (member value values)))
13836 (defun org-entry-get-multivalued-property (pom property)
13837 "Return a list of values in a multivalued property."
13838 (let* ((value (org-entry-get pom property))
13839 (values (and value (org-split-string value "[ \t]"))))
13840 (mapcar 'org-entry-restore-space values)))
13842 (defun org-entry-put-multivalued-property (pom property &rest values)
13843 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13844 VALUES should be a list of strings. Spaces will be protected."
13845 (org-entry-put pom property
13846 (mapconcat 'org-entry-protect-space values " "))
13847 (let* ((value (org-entry-get pom property))
13848 (values (and value (org-split-string value "[ \t]"))))
13849 (mapcar 'org-entry-restore-space values)))
13851 (defun org-entry-protect-space (s)
13852 "Protect spaces and newline in string S."
13853 (while (string-match " " s)
13854 (setq s (replace-match "%20" t t s)))
13855 (while (string-match "\n" s)
13856 (setq s (replace-match "%0A" t t s)))
13859 (defun org-entry-restore-space (s)
13860 "Restore spaces and newline in string S."
13861 (while (string-match "%20" s)
13862 (setq s (replace-match " " t t s)))
13863 (while (string-match "%0A" s)
13864 (setq s (replace-match "\n" t t s)))
13867 (defvar org-entry-property-inherited-from (make-marker)
13868 "Marker pointing to the entry from where a property was inherited.
13869 Each call to `org-entry-get-with-inheritance' will set this marker to the
13870 location of the entry where the inheritance search matched. If there was
13871 no match, the marker will point nowhere.
13872 Note that also `org-entry-get' calls this function, if the INHERIT flag
13873 is set.")
13875 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13876 "Get entry property, and search higher levels if not present.
13877 The search will stop at the first ancestor which has the property defined.
13878 If the value found is \"nil\", return nil to show that the property
13879 should be considered as undefined (this is the meaning of nil here).
13880 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13881 (move-marker org-entry-property-inherited-from nil)
13882 (let (tmp)
13883 (unless (org-before-first-heading-p)
13884 (save-excursion
13885 (save-restriction
13886 (widen)
13887 (catch 'ex
13888 (while t
13889 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13890 (org-back-to-heading t)
13891 (move-marker org-entry-property-inherited-from (point))
13892 (throw 'ex tmp))
13893 (or (org-up-heading-safe) (throw 'ex nil)))))))
13894 (setq tmp (or tmp
13895 (cdr (assoc property org-file-properties))
13896 (cdr (assoc property org-global-properties))
13897 (cdr (assoc property org-global-properties-fixed))))
13898 (if literal-nil tmp (org-not-nil tmp))))
13900 (defvar org-property-changed-functions nil
13901 "Hook called when the value of a property has changed.
13902 Each hook function should accept two arguments, the name of the property
13903 and the new value.")
13905 (defun org-entry-put (pom property value)
13906 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13907 (org-with-point-at pom
13908 (org-back-to-heading t)
13909 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13910 range)
13911 (cond
13912 ((equal property "TODO")
13913 (when (and (stringp value) (string-match "\\S-" value)
13914 (not (member value org-todo-keywords-1)))
13915 (error "\"%s\" is not a valid TODO state" value))
13916 (if (or (not value)
13917 (not (string-match "\\S-" value)))
13918 (setq value 'none))
13919 (org-todo value)
13920 (org-set-tags nil 'align))
13921 ((equal property "PRIORITY")
13922 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13923 (string-to-char value) ?\ ))
13924 (org-set-tags nil 'align))
13925 ((equal property "SCHEDULED")
13926 (if (re-search-forward org-scheduled-time-regexp end t)
13927 (cond
13928 ((eq value 'earlier) (org-timestamp-change -1 'day))
13929 ((eq value 'later) (org-timestamp-change 1 'day))
13930 (t (call-interactively 'org-schedule)))
13931 (call-interactively 'org-schedule)))
13932 ((equal property "DEADLINE")
13933 (if (re-search-forward org-deadline-time-regexp end t)
13934 (cond
13935 ((eq value 'earlier) (org-timestamp-change -1 'day))
13936 ((eq value 'later) (org-timestamp-change 1 'day))
13937 (t (call-interactively 'org-deadline)))
13938 (call-interactively 'org-deadline)))
13939 ((member property org-special-properties)
13940 (error "The %s property can not yet be set with `org-entry-put'"
13941 property))
13942 (t ; a non-special property
13943 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13944 (setq range (org-get-property-block beg end 'force))
13945 (goto-char (car range))
13946 (if (re-search-forward
13947 (org-re-property property) (cdr range) t)
13948 (progn
13949 (delete-region (match-beginning 0) (match-end 0))
13950 (goto-char (match-beginning 0)))
13951 (goto-char (cdr range))
13952 (insert "\n")
13953 (backward-char 1)
13954 (org-indent-line-function))
13955 (insert ":" property ":")
13956 (and value (insert " " value))
13957 (org-indent-line-function)))))
13958 (run-hook-with-args 'org-property-changed-functions property value)))
13960 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13961 "Get all property keys in the current buffer.
13962 With INCLUDE-SPECIALS, also list the special properties that reflect things
13963 like tags and TODO state.
13964 With INCLUDE-DEFAULTS, also include properties that has special meaning
13965 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13966 and others.
13967 With INCLUDE-COLUMNS, also include property names given in COLUMN
13968 formats in the current buffer."
13969 (let (rtn range cfmt s p)
13970 (save-excursion
13971 (save-restriction
13972 (widen)
13973 (goto-char (point-min))
13974 (while (re-search-forward org-property-start-re nil t)
13975 (setq range (org-get-property-block))
13976 (goto-char (car range))
13977 (while (re-search-forward
13978 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13979 (cdr range) t)
13980 (add-to-list 'rtn (org-match-string-no-properties 1)))
13981 (outline-next-heading))))
13983 (when include-specials
13984 (setq rtn (append org-special-properties rtn)))
13986 (when include-defaults
13987 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13988 (add-to-list 'rtn org-effort-property))
13990 (when include-columns
13991 (save-excursion
13992 (save-restriction
13993 (widen)
13994 (goto-char (point-min))
13995 (while (re-search-forward
13996 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13997 nil t)
13998 (setq cfmt (match-string 2) s 0)
13999 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14000 cfmt s)
14001 (setq s (match-end 0)
14002 p (match-string 1 cfmt))
14003 (unless (or (equal p "ITEM")
14004 (member p org-special-properties))
14005 (add-to-list 'rtn (match-string 1 cfmt))))))))
14007 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14009 (defun org-property-values (key)
14010 "Return a list of all values of property KEY in the current buffer."
14011 (save-excursion
14012 (save-restriction
14013 (widen)
14014 (goto-char (point-min))
14015 (let ((re (org-re-property key))
14016 values)
14017 (while (re-search-forward re nil t)
14018 (add-to-list 'values (org-trim (match-string 1))))
14019 (delete "" values)))))
14021 (defun org-insert-property-drawer ()
14022 "Insert a property drawer into the current entry."
14023 (interactive)
14024 (org-back-to-heading t)
14025 (looking-at outline-regexp)
14026 (let ((indent (if org-adapt-indentation
14027 (- (match-end 0)(match-beginning 0))
14029 (beg (point))
14030 (re (concat "^[ \t]*" org-keyword-time-regexp))
14031 end hiddenp)
14032 (outline-next-heading)
14033 (setq end (point))
14034 (goto-char beg)
14035 (while (re-search-forward re end t))
14036 (setq hiddenp (outline-invisible-p))
14037 (end-of-line 1)
14038 (and (equal (char-after) ?\n) (forward-char 1))
14039 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14040 (if (member (match-string 1) '("CLOCK:" ":END:"))
14041 ;; just skip this line
14042 (beginning-of-line 2)
14043 ;; Drawer start, find the end
14044 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14045 (beginning-of-line 1)))
14046 (org-skip-over-state-notes)
14047 (skip-chars-backward " \t\n\r")
14048 (if (eq (char-before) ?*) (forward-char 1))
14049 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14050 (beginning-of-line 0)
14051 (org-indent-to-column indent)
14052 (beginning-of-line 2)
14053 (org-indent-to-column indent)
14054 (beginning-of-line 0)
14055 (if hiddenp
14056 (save-excursion
14057 (org-back-to-heading t)
14058 (hide-entry))
14059 (org-flag-drawer t))))
14061 (defvar org-property-set-functions-alist nil
14062 "Property set function alist.
14063 Each entry should have the following format:
14065 (PROPERTY . READ-FUNCTION)
14067 The read function will be called with the same argument as
14068 `org-completing-read'.")
14070 (defun org-set-property-function (property)
14071 "Get the function that should be used to set PROPERTY.
14072 This is computed according to `org-property-set-functions-alist'."
14073 (or (cdr (assoc property org-property-set-functions-alist))
14074 'org-completing-read))
14076 (defun org-read-property-value (property)
14077 "Read PROPERTY value from user."
14078 (let* ((completion-ignore-case t)
14079 (allowed (org-property-get-allowed-values nil property 'table))
14080 (cur (org-entry-get nil property))
14081 (prompt (concat property " value"
14082 (if (and cur (string-match "\\S-" cur))
14083 (concat " [" cur "]") "") ": "))
14084 (set-function (org-set-property-function property))
14085 (val (if allowed
14086 (funcall set-function prompt allowed nil
14087 (not (get-text-property 0 'org-unrestricted
14088 (caar allowed))))
14089 (let (org-completion-use-ido org-completion-use-iswitchb)
14090 (funcall set-function prompt
14091 (mapcar 'list (org-property-values property))
14092 nil nil "" nil cur)))))
14093 (if (equal val "")
14095 val)))
14097 (defun org-read-property-name ()
14098 "Read a property name."
14099 (let* ((completion-ignore-case t)
14100 (keys (org-buffer-property-keys nil t t))
14101 (default-prop (save-excursion
14102 (save-match-data
14103 (beginning-of-line)
14104 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14105 (null (string= (match-string 1) "END"))
14106 (match-string 1)))))
14107 (property (org-icompleting-read
14108 (concat "Property"
14109 (if default-prop (concat " [" default-prop "]") "")
14110 ": ")
14111 (mapcar 'list keys)
14112 nil nil nil nil
14113 default-prop
14115 (if (member property keys)
14116 property
14117 (or (cdr (assoc (downcase property)
14118 (mapcar (lambda (x) (cons (downcase x) x))
14119 keys)))
14120 property))))
14122 (defun org-set-property (property value)
14123 "In the current entry, set PROPERTY to VALUE.
14124 When called interactively, this will prompt for a property name, offering
14125 completion on existing and default properties. And then it will prompt
14126 for a value, offering completion either on allowed values (via an inherited
14127 xxx_ALL property) or on existing values in other instances of this property
14128 in the current file."
14129 (interactive (list nil nil))
14130 (let* ((property (or property (org-read-property-name)))
14131 (value (or value (org-read-property-value property))))
14132 (unless (equal (org-entry-get nil property) value)
14133 (org-entry-put nil property value))))
14135 (defun org-delete-property (property)
14136 "In the current entry, delete PROPERTY."
14137 (interactive
14138 (let* ((completion-ignore-case t)
14139 (prop (org-icompleting-read "Property: "
14140 (org-entry-properties nil 'standard))))
14141 (list prop)))
14142 (message "Property %s %s" property
14143 (if (org-entry-delete nil property)
14144 "deleted"
14145 "was not present in the entry")))
14147 (defun org-delete-property-globally (property)
14148 "Remove PROPERTY globally, from all entries."
14149 (interactive
14150 (let* ((completion-ignore-case t)
14151 (prop (org-icompleting-read
14152 "Globally remove property: "
14153 (mapcar 'list (org-buffer-property-keys)))))
14154 (list prop)))
14155 (save-excursion
14156 (save-restriction
14157 (widen)
14158 (goto-char (point-min))
14159 (let ((cnt 0))
14160 (while (re-search-forward
14161 (org-re-property property)
14162 nil t)
14163 (setq cnt (1+ cnt))
14164 (replace-match ""))
14165 (message "Property \"%s\" removed from %d entries" property cnt)))))
14167 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14169 (defun org-compute-property-at-point ()
14170 "Compute the property at point.
14171 This looks for an enclosing column format, extracts the operator and
14172 then applies it to the property in the column format's scope."
14173 (interactive)
14174 (unless (org-at-property-p)
14175 (error "Not at a property"))
14176 (let ((prop (org-match-string-no-properties 2)))
14177 (org-columns-get-format-and-top-level)
14178 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14179 (error "No operator defined for property %s" prop))
14180 (org-columns-compute prop)))
14182 (defvar org-property-allowed-value-functions nil
14183 "Hook for functions supplying allowed values for a specific property.
14184 The functions must take a single argument, the name of the property, and
14185 return a flat list of allowed values. If \":ETC\" is one of
14186 the values, this means that these values are intended as defaults for
14187 completion, but that other values should be allowed too.
14188 The functions must return nil if they are not responsible for this
14189 property.")
14191 (defun org-property-get-allowed-values (pom property &optional table)
14192 "Get allowed values for the property PROPERTY.
14193 When TABLE is non-nil, return an alist that can directly be used for
14194 completion."
14195 (let (vals)
14196 (cond
14197 ((equal property "TODO")
14198 (setq vals (org-with-point-at pom
14199 (append org-todo-keywords-1 '("")))))
14200 ((equal property "PRIORITY")
14201 (let ((n org-lowest-priority))
14202 (while (>= n org-highest-priority)
14203 (push (char-to-string n) vals)
14204 (setq n (1- n)))))
14205 ((member property org-special-properties))
14206 ((setq vals (run-hook-with-args-until-success
14207 'org-property-allowed-value-functions property)))
14209 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14210 (when (and vals (string-match "\\S-" vals))
14211 (setq vals (car (read-from-string (concat "(" vals ")"))))
14212 (setq vals (mapcar (lambda (x)
14213 (cond ((stringp x) x)
14214 ((numberp x) (number-to-string x))
14215 ((symbolp x) (symbol-name x))
14216 (t "???")))
14217 vals)))))
14218 (when (member ":ETC" vals)
14219 (setq vals (remove ":ETC" vals))
14220 (org-add-props (car vals) '(org-unrestricted t)))
14221 (if table (mapcar 'list vals) vals)))
14223 (defun org-property-previous-allowed-value (&optional previous)
14224 "Switch to the next allowed value for this property."
14225 (interactive)
14226 (org-property-next-allowed-value t))
14228 (defun org-property-next-allowed-value (&optional previous)
14229 "Switch to the next allowed value for this property."
14230 (interactive)
14231 (unless (org-at-property-p)
14232 (error "Not at a property"))
14233 (let* ((key (match-string 2))
14234 (value (match-string 3))
14235 (allowed (or (org-property-get-allowed-values (point) key)
14236 (and (member value '("[ ]" "[-]" "[X]"))
14237 '("[ ]" "[X]"))))
14238 nval)
14239 (unless allowed
14240 (error "Allowed values for this property have not been defined"))
14241 (if previous (setq allowed (reverse allowed)))
14242 (if (member value allowed)
14243 (setq nval (car (cdr (member value allowed)))))
14244 (setq nval (or nval (car allowed)))
14245 (if (equal nval value)
14246 (error "Only one allowed value for this property"))
14247 (org-at-property-p)
14248 (replace-match (concat " :" key ": " nval) t t)
14249 (org-indent-line-function)
14250 (beginning-of-line 1)
14251 (skip-chars-forward " \t")
14252 (run-hook-with-args 'org-property-changed-functions key nval)))
14254 (defun org-find-olp (path &optional this-buffer)
14255 "Return a marker pointing to the entry at outline path OLP.
14256 If anything goes wrong, throw an error.
14257 You can wrap this call to catch the error like this:
14259 (condition-case msg
14260 (org-mobile-locate-entry (match-string 4))
14261 (error (nth 1 msg)))
14263 The return value will then be either a string with the error message,
14264 or a marker if everything is OK.
14266 If THIS-BUFFER is set, the outline path does not contain a file,
14267 only headings."
14268 (let* ((file (if this-buffer buffer-file-name (pop path)))
14269 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14270 (level 1)
14271 (lmin 1)
14272 (lmax 1)
14273 limit re end found pos heading cnt flevel)
14274 (unless buffer (error "File not found :%s" file))
14275 (with-current-buffer buffer
14276 (save-excursion
14277 (save-restriction
14278 (widen)
14279 (setq limit (point-max))
14280 (goto-char (point-min))
14281 (while (setq heading (pop path))
14282 (setq re (format org-complex-heading-regexp-format
14283 (regexp-quote heading)))
14284 (setq cnt 0 pos (point))
14285 (while (re-search-forward re end t)
14286 (setq level (- (match-end 1) (match-beginning 1)))
14287 (if (and (>= level lmin) (<= level lmax))
14288 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14289 (when (= cnt 0) (error "Heading not found on level %d: %s"
14290 lmax heading))
14291 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14292 lmax heading))
14293 (goto-char found)
14294 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14295 (setq end (save-excursion (org-end-of-subtree t t))))
14296 (when (org-on-heading-p)
14297 (move-marker (make-marker) (point))))))))
14299 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14300 "Find node HEADING in BUFFER.
14301 Return a marker to the heading if it was found, or nil if not.
14302 If POS-ONLY is set, return just the position instead of a marker.
14304 The heading text must match exact, but it may have a TODO keyword,
14305 a priority cookie and tags in the standard locations."
14306 (with-current-buffer (or buffer (current-buffer))
14307 (save-excursion
14308 (save-restriction
14309 (widen)
14310 (goto-char (point-min))
14311 (let (case-fold-search)
14312 (if (re-search-forward
14313 (format org-complex-heading-regexp-format
14314 (regexp-quote heading)) nil t)
14315 (if pos-only
14316 (match-beginning 0)
14317 (move-marker (make-marker) (match-beginning 0)))))))))
14319 (defun org-find-exact-heading-in-directory (heading &optional dir)
14320 "Find Org node headline HEADING in all .org files in directory DIR.
14321 When the target headline is found, return a marker to this location."
14322 (let ((files (directory-files (or dir default-directory)
14323 nil "\\`[^.#].*\\.org\\'"))
14324 file visiting m buffer)
14325 (catch 'found
14326 (while (setq file (pop files))
14327 (message "trying %s" file)
14328 (setq visiting (org-find-base-buffer-visiting file))
14329 (setq buffer (or visiting (find-file-noselect file)))
14330 (setq m (org-find-exact-headline-in-buffer
14331 heading buffer))
14332 (when (and (not m) (not visiting)) (kill-buffer buffer))
14333 (and m (throw 'found m))))))
14335 (defun org-find-entry-with-id (ident)
14336 "Locate the entry that contains the ID property with exact value IDENT.
14337 IDENT can be a string, a symbol or a number, this function will search for
14338 the string representation of it.
14339 Return the position where this entry starts, or nil if there is no such entry."
14340 (interactive "sID: ")
14341 (let ((id (cond
14342 ((stringp ident) ident)
14343 ((symbol-name ident) (symbol-name ident))
14344 ((numberp ident) (number-to-string ident))
14345 (t (error "IDENT %s must be a string, symbol or number" ident))))
14346 (case-fold-search nil))
14347 (save-excursion
14348 (save-restriction
14349 (widen)
14350 (goto-char (point-min))
14351 (when (re-search-forward
14352 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14353 nil t)
14354 (org-back-to-heading t)
14355 (point))))))
14357 ;;;; Timestamps
14359 (defvar org-last-changed-timestamp nil)
14360 (defvar org-last-inserted-timestamp nil
14361 "The last time stamp inserted with `org-insert-time-stamp'.")
14362 (defvar org-time-was-given) ; dynamically scoped parameter
14363 (defvar org-end-time-was-given) ; dynamically scoped parameter
14364 (defvar org-ts-what) ; dynamically scoped parameter
14366 (defun org-time-stamp (arg &optional inactive)
14367 "Prompt for a date/time and insert a time stamp.
14368 If the user specifies a time like HH:MM, or if this command is called
14369 with a prefix argument, the time stamp will contain date and time.
14370 Otherwise, only the date will be included. All parts of a date not
14371 specified by the user will be filled in from the current date/time.
14372 So if you press just return without typing anything, the time stamp
14373 will represent the current date/time. If there is already a timestamp
14374 at the cursor, it will be modified."
14375 (interactive "P")
14376 (let* ((ts nil)
14377 (default-time
14378 ;; Default time is either today, or, when entering a range,
14379 ;; the range start.
14380 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14381 (save-excursion
14382 (re-search-backward
14383 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14384 (- (point) 20) t)))
14385 (apply 'encode-time (org-parse-time-string (match-string 1)))
14386 (current-time)))
14387 (default-input (and ts (org-get-compact-tod ts)))
14388 (repeater (save-excursion
14389 (save-match-data
14390 (beginning-of-line)
14391 (when (re-search-forward
14392 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14393 (save-excursion (progn (end-of-line) (point))) t)
14394 (match-string 0)))))
14395 org-time-was-given org-end-time-was-given time)
14396 (cond
14397 ((and (org-at-timestamp-p t)
14398 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14399 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14400 (insert "--")
14401 (setq time (let ((this-command this-command))
14402 (org-read-date arg 'totime nil nil
14403 default-time default-input)))
14404 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14405 ((org-at-timestamp-p t)
14406 (setq time (let ((this-command this-command))
14407 (org-read-date arg 'totime nil nil default-time default-input)))
14408 (when (org-at-timestamp-p t) ; just to get the match data
14409 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14410 (replace-match "")
14411 (setq org-last-changed-timestamp
14412 (org-insert-time-stamp
14413 time (or org-time-was-given arg)
14414 inactive nil nil (list org-end-time-was-given)))
14415 (when repeater (goto-char (1- (point))) (insert " " repeater)
14416 (setq org-last-changed-timestamp
14417 (concat (substring org-last-inserted-timestamp 0 -1)
14418 " " repeater ">"))))
14419 (message "Timestamp updated"))
14421 (setq time (let ((this-command this-command))
14422 (org-read-date arg 'totime nil nil default-time default-input)))
14423 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14424 nil nil (list org-end-time-was-given))))))
14426 ;; FIXME: can we use this for something else, like computing time differences?
14427 (defun org-get-compact-tod (s)
14428 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14429 (let* ((t1 (match-string 1 s))
14430 (h1 (string-to-number (match-string 2 s)))
14431 (m1 (string-to-number (match-string 3 s)))
14432 (t2 (and (match-end 4) (match-string 5 s)))
14433 (h2 (and t2 (string-to-number (match-string 6 s))))
14434 (m2 (and t2 (string-to-number (match-string 7 s))))
14435 dh dm)
14436 (if (not t2)
14438 (setq dh (- h2 h1) dm (- m2 m1))
14439 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14440 (concat t1 "+" (number-to-string dh)
14441 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14443 (defun org-time-stamp-inactive (&optional arg)
14444 "Insert an inactive time stamp.
14445 An inactive time stamp is enclosed in square brackets instead of angle
14446 brackets. It is inactive in the sense that it does not trigger agenda entries,
14447 does not link to the calendar and cannot be changed with the S-cursor keys.
14448 So these are more for recording a certain time/date."
14449 (interactive "P")
14450 (org-time-stamp arg 'inactive))
14452 (defvar org-date-ovl (make-overlay 1 1))
14453 (overlay-put org-date-ovl 'face 'org-warning)
14454 (org-detach-overlay org-date-ovl)
14456 (defvar org-ans1) ; dynamically scoped parameter
14457 (defvar org-ans2) ; dynamically scoped parameter
14459 (defvar org-plain-time-of-day-regexp) ; defined below
14461 (defvar org-overriding-default-time nil) ; dynamically scoped
14462 (defvar org-read-date-overlay nil)
14463 (defvar org-dcst nil) ; dynamically scoped
14464 (defvar org-read-date-history nil)
14465 (defvar org-read-date-final-answer nil)
14466 (defvar org-read-date-analyze-futurep nil)
14467 (defvar org-read-date-analyze-forced-year nil)
14469 (defun org-read-date (&optional with-time to-time from-string prompt
14470 default-time default-input)
14471 "Read a date, possibly a time, and make things smooth for the user.
14472 The prompt will suggest to enter an ISO date, but you can also enter anything
14473 which will at least partially be understood by `parse-time-string'.
14474 Unrecognized parts of the date will default to the current day, month, year,
14475 hour and minute. If this command is called to replace a timestamp at point,
14476 of to enter the second timestamp of a range, the default time is taken
14477 from the existing stamp. Furthermore, the command prefers the future,
14478 so if you are giving a date where the year is not given, and the day-month
14479 combination is already past in the current year, it will assume you
14480 mean next year. For details, see the manual. A few examples:
14482 3-2-5 --> 2003-02-05
14483 feb 15 --> currentyear-02-15
14484 2/15 --> currentyear-02-15
14485 sep 12 9 --> 2009-09-12
14486 12:45 --> today 12:45
14487 22 sept 0:34 --> currentyear-09-22 0:34
14488 12 --> currentyear-currentmonth-12
14489 Fri --> nearest Friday (today or later)
14490 etc.
14492 Furthermore you can specify a relative date by giving, as the *first* thing
14493 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14494 change in days weeks, months, years.
14495 With a single plus or minus, the date is relative to today. With a double
14496 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14497 +4d --> four days from today
14498 +4 --> same as above
14499 +2w --> two weeks from today
14500 ++5 --> five days from default date
14502 The function understands only English month and weekday abbreviations,
14503 but this can be configured with the variables `parse-time-months' and
14504 `parse-time-weekdays'.
14506 While prompting, a calendar is popped up - you can also select the
14507 date with the mouse (button 1). The calendar shows a period of three
14508 months. To scroll it to other months, use the keys `>' and `<'.
14509 If you don't like the calendar, turn it off with
14510 \(setq org-read-date-popup-calendar nil)
14512 With optional argument TO-TIME, the date will immediately be converted
14513 to an internal time.
14514 With an optional argument WITH-TIME, the prompt will suggest to also
14515 insert a time. Note that when WITH-TIME is not set, you can still
14516 enter a time, and this function will inform the calling routine about
14517 this change. The calling routine may then choose to change the format
14518 used to insert the time stamp into the buffer to include the time.
14519 With optional argument FROM-STRING, read from this string instead from
14520 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14521 the time/date that is used for everything that is not specified by the
14522 user."
14523 (require 'parse-time)
14524 (let* ((org-time-stamp-rounding-minutes
14525 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14526 (org-dcst org-display-custom-times)
14527 (ct (org-current-time))
14528 (def (or org-overriding-default-time default-time ct))
14529 (defdecode (decode-time def))
14530 (dummy (progn
14531 (when (< (nth 2 defdecode) org-extend-today-until)
14532 (setcar (nthcdr 2 defdecode) -1)
14533 (setcar (nthcdr 1 defdecode) 59)
14534 (setq def (apply 'encode-time defdecode)
14535 defdecode (decode-time def)))))
14536 (calendar-frame-setup nil)
14537 (calendar-setup nil)
14538 (calendar-move-hook nil)
14539 (calendar-view-diary-initially-flag nil)
14540 (calendar-view-holidays-initially-flag nil)
14541 (timestr (format-time-string
14542 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14543 (prompt (concat (if prompt (concat prompt " ") "")
14544 (format "Date+time [%s]: " timestr)))
14545 ans (org-ans0 "") org-ans1 org-ans2 final)
14547 (cond
14548 (from-string (setq ans from-string))
14549 (org-read-date-popup-calendar
14550 (save-excursion
14551 (save-window-excursion
14552 (calendar)
14553 (unwind-protect
14554 (progn
14555 (calendar-forward-day (- (time-to-days def)
14556 (calendar-absolute-from-gregorian
14557 (calendar-current-date))))
14558 (org-eval-in-calendar nil t)
14559 (let* ((old-map (current-local-map))
14560 (map (copy-keymap calendar-mode-map))
14561 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14562 (org-defkey map (kbd "RET") 'org-calendar-select)
14563 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14564 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14565 (org-defkey minibuffer-local-map [(meta shift left)]
14566 (lambda () (interactive)
14567 (org-eval-in-calendar '(calendar-backward-month 1))))
14568 (org-defkey minibuffer-local-map [(meta shift right)]
14569 (lambda () (interactive)
14570 (org-eval-in-calendar '(calendar-forward-month 1))))
14571 (org-defkey minibuffer-local-map [(meta shift up)]
14572 (lambda () (interactive)
14573 (org-eval-in-calendar '(calendar-backward-year 1))))
14574 (org-defkey minibuffer-local-map [(meta shift down)]
14575 (lambda () (interactive)
14576 (org-eval-in-calendar '(calendar-forward-year 1))))
14577 (org-defkey minibuffer-local-map [?\e (shift left)]
14578 (lambda () (interactive)
14579 (org-eval-in-calendar '(calendar-backward-month 1))))
14580 (org-defkey minibuffer-local-map [?\e (shift right)]
14581 (lambda () (interactive)
14582 (org-eval-in-calendar '(calendar-forward-month 1))))
14583 (org-defkey minibuffer-local-map [?\e (shift up)]
14584 (lambda () (interactive)
14585 (org-eval-in-calendar '(calendar-backward-year 1))))
14586 (org-defkey minibuffer-local-map [?\e (shift down)]
14587 (lambda () (interactive)
14588 (org-eval-in-calendar '(calendar-forward-year 1))))
14589 (org-defkey minibuffer-local-map [(shift up)]
14590 (lambda () (interactive)
14591 (org-eval-in-calendar '(calendar-backward-week 1))))
14592 (org-defkey minibuffer-local-map [(shift down)]
14593 (lambda () (interactive)
14594 (org-eval-in-calendar '(calendar-forward-week 1))))
14595 (org-defkey minibuffer-local-map [(shift left)]
14596 (lambda () (interactive)
14597 (org-eval-in-calendar '(calendar-backward-day 1))))
14598 (org-defkey minibuffer-local-map [(shift right)]
14599 (lambda () (interactive)
14600 (org-eval-in-calendar '(calendar-forward-day 1))))
14601 (org-defkey minibuffer-local-map ">"
14602 (lambda () (interactive)
14603 (org-eval-in-calendar '(scroll-calendar-left 1))))
14604 (org-defkey minibuffer-local-map "<"
14605 (lambda () (interactive)
14606 (org-eval-in-calendar '(scroll-calendar-right 1))))
14607 (org-defkey minibuffer-local-map "\C-v"
14608 (lambda () (interactive)
14609 (org-eval-in-calendar
14610 '(calendar-scroll-left-three-months 1))))
14611 (org-defkey minibuffer-local-map "\M-v"
14612 (lambda () (interactive)
14613 (org-eval-in-calendar
14614 '(calendar-scroll-right-three-months 1))))
14615 (run-hooks 'org-read-date-minibuffer-setup-hook)
14616 (unwind-protect
14617 (progn
14618 (use-local-map map)
14619 (add-hook 'post-command-hook 'org-read-date-display)
14620 (setq org-ans0 (read-string prompt default-input
14621 'org-read-date-history nil))
14622 ;; org-ans0: from prompt
14623 ;; org-ans1: from mouse click
14624 ;; org-ans2: from calendar motion
14625 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14626 (remove-hook 'post-command-hook 'org-read-date-display)
14627 (use-local-map old-map)
14628 (when org-read-date-overlay
14629 (delete-overlay org-read-date-overlay)
14630 (setq org-read-date-overlay nil)))))
14631 (bury-buffer "*Calendar*")))))
14633 (t ; Naked prompt only
14634 (unwind-protect
14635 (setq ans (read-string prompt default-input
14636 'org-read-date-history timestr))
14637 (when org-read-date-overlay
14638 (delete-overlay org-read-date-overlay)
14639 (setq org-read-date-overlay nil)))))
14641 (setq final (org-read-date-analyze ans def defdecode))
14643 (when org-read-date-analyze-forced-year
14644 (message "Year was forced into %s"
14645 (if org-read-date-force-compatible-dates
14646 "compatible range (1970-2037)"
14647 "range representable on this machine"))
14648 (ding))
14650 ;; One round trip to get rid of 34th of August and stuff like that....
14651 (setq final (decode-time (apply 'encode-time final)))
14653 (setq org-read-date-final-answer ans)
14655 (if to-time
14656 (apply 'encode-time final)
14657 (if (and (boundp 'org-time-was-given) org-time-was-given)
14658 (format "%04d-%02d-%02d %02d:%02d"
14659 (nth 5 final) (nth 4 final) (nth 3 final)
14660 (nth 2 final) (nth 1 final))
14661 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14663 (defvar def)
14664 (defvar defdecode)
14665 (defvar with-time)
14666 (defun org-read-date-display ()
14667 "Display the current date prompt interpretation in the minibuffer."
14668 (when org-read-date-display-live
14669 (when org-read-date-overlay
14670 (delete-overlay org-read-date-overlay))
14671 (let ((p (point)))
14672 (end-of-line 1)
14673 (while (not (equal (buffer-substring
14674 (max (point-min) (- (point) 4)) (point))
14675 " "))
14676 (insert " "))
14677 (goto-char p))
14678 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14679 " " (or org-ans1 org-ans2)))
14680 (org-end-time-was-given nil)
14681 (f (org-read-date-analyze ans def defdecode))
14682 (fmts (if org-dcst
14683 org-time-stamp-custom-formats
14684 org-time-stamp-formats))
14685 (fmt (if (or with-time
14686 (and (boundp 'org-time-was-given) org-time-was-given))
14687 (cdr fmts)
14688 (car fmts)))
14689 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14690 (when (and org-end-time-was-given
14691 (string-match org-plain-time-of-day-regexp txt))
14692 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14693 org-end-time-was-given
14694 (substring txt (match-end 0)))))
14695 (when org-read-date-analyze-futurep
14696 (setq txt (concat txt " (=>F)")))
14697 (setq org-read-date-overlay
14698 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14699 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14701 (defun org-read-date-analyze (ans def defdecode)
14702 "Analyze the combined answer of the date prompt."
14703 ;; FIXME: cleanup and comment
14704 (let ((nowdecode (decode-time (current-time)))
14705 delta deltan deltaw deltadef year month day
14706 hour minute second wday pm h2 m2 tl wday1
14707 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14708 (setq org-read-date-analyze-futurep nil
14709 org-read-date-analyze-forced-year nil)
14710 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14711 (setq ans "+0"))
14713 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14714 (setq ans (replace-match "" t t ans)
14715 deltan (car delta)
14716 deltaw (nth 1 delta)
14717 deltadef (nth 2 delta)))
14719 ;; Check if there is an iso week date in there
14720 ;; If yes, store the info and postpone interpreting it until the rest
14721 ;; of the parsing is done
14722 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14723 (setq iso-year (if (match-end 1)
14724 (org-small-year-to-year
14725 (string-to-number (match-string 1 ans))))
14726 iso-weekday (if (match-end 3)
14727 (string-to-number (match-string 3 ans)))
14728 iso-week (string-to-number (match-string 2 ans)))
14729 (setq ans (replace-match "" t t ans)))
14731 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14732 (when (string-match
14733 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14734 (setq year (if (match-end 2)
14735 (string-to-number (match-string 2 ans))
14736 (progn (setq kill-year t)
14737 (string-to-number (format-time-string "%Y"))))
14738 month (string-to-number (match-string 3 ans))
14739 day (string-to-number (match-string 4 ans)))
14740 (if (< year 100) (setq year (+ 2000 year)))
14741 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14742 t nil ans)))
14744 ;; Help matching dottet european dates
14745 (when (string-match
14746 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14747 (setq year (if (match-end 3)
14748 (string-to-number (match-string 3 ans))
14749 (progn (setq kill-year t)
14750 (string-to-number (format-time-string "%Y"))))
14751 day (string-to-number (match-string 1 ans))
14752 month (string-to-number (match-string 2 ans))
14753 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14754 t nil ans)))
14756 ;; Help matching american dates, like 5/30 or 5/30/7
14757 (when (string-match
14758 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14759 (setq year (if (match-end 4)
14760 (string-to-number (match-string 4 ans))
14761 (progn (setq kill-year t)
14762 (string-to-number (format-time-string "%Y"))))
14763 month (string-to-number (match-string 1 ans))
14764 day (string-to-number (match-string 2 ans)))
14765 (if (< year 100) (setq year (+ 2000 year)))
14766 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14767 t nil ans)))
14768 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14769 ;; If there is a time with am/pm, and *no* time without it, we convert
14770 ;; so that matching will be successful.
14771 (loop for i from 1 to 2 do ; twice, for end time as well
14772 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14773 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14774 (setq hour (string-to-number (match-string 1 ans))
14775 minute (if (match-end 3)
14776 (string-to-number (match-string 3 ans))
14778 pm (equal ?p
14779 (string-to-char (downcase (match-string 4 ans)))))
14780 (if (and (= hour 12) (not pm))
14781 (setq hour 0)
14782 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14783 (setq ans (replace-match (format "%02d:%02d" hour minute)
14784 t t ans))))
14786 ;; Check if a time range is given as a duration
14787 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14788 (setq hour (string-to-number (match-string 1 ans))
14789 h2 (+ hour (string-to-number (match-string 3 ans)))
14790 minute (string-to-number (match-string 2 ans))
14791 m2 (+ minute (if (match-end 5) (string-to-number
14792 (match-string 5 ans))0)))
14793 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14794 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14795 t t ans)))
14797 ;; Check if there is a time range
14798 (when (boundp 'org-end-time-was-given)
14799 (setq org-time-was-given nil)
14800 (when (and (string-match org-plain-time-of-day-regexp ans)
14801 (match-end 8))
14802 (setq org-end-time-was-given (match-string 8 ans))
14803 (setq ans (concat (substring ans 0 (match-beginning 7))
14804 (substring ans (match-end 7))))))
14806 (setq tl (parse-time-string ans)
14807 day (or (nth 3 tl) (nth 3 defdecode))
14808 month (or (nth 4 tl)
14809 (if (and org-read-date-prefer-future
14810 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14811 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14812 (nth 4 defdecode)))
14813 year (or (and (not kill-year) (nth 5 tl))
14814 (if (and org-read-date-prefer-future
14815 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14816 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14817 (nth 5 defdecode)))
14818 hour (or (nth 2 tl) (nth 2 defdecode))
14819 minute (or (nth 1 tl) (nth 1 defdecode))
14820 second (or (nth 0 tl) 0)
14821 wday (nth 6 tl))
14823 (when (and (eq org-read-date-prefer-future 'time)
14824 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14825 (equal day (nth 3 nowdecode))
14826 (equal month (nth 4 nowdecode))
14827 (equal year (nth 5 nowdecode))
14828 (nth 2 tl)
14829 (or (< (nth 2 tl) (nth 2 nowdecode))
14830 (and (= (nth 2 tl) (nth 2 nowdecode))
14831 (nth 1 tl)
14832 (< (nth 1 tl) (nth 1 nowdecode)))))
14833 (setq day (1+ day)
14834 futurep t))
14836 ;; Special date definitions below
14837 (cond
14838 (iso-week
14839 ;; There was an iso week
14840 (require 'cal-iso)
14841 (setq futurep nil)
14842 (setq year (or iso-year year)
14843 day (or iso-weekday wday 1)
14844 wday nil ; to make sure that the trigger below does not match
14845 iso-date (calendar-gregorian-from-absolute
14846 (calendar-absolute-from-iso
14847 (list iso-week day year))))
14848 ; FIXME: Should we also push ISO weeks into the future?
14849 ; (when (and org-read-date-prefer-future
14850 ; (not iso-year)
14851 ; (< (calendar-absolute-from-gregorian iso-date)
14852 ; (time-to-days (current-time))))
14853 ; (setq year (1+ year)
14854 ; iso-date (calendar-gregorian-from-absolute
14855 ; (calendar-absolute-from-iso
14856 ; (list iso-week day year)))))
14857 (setq month (car iso-date)
14858 year (nth 2 iso-date)
14859 day (nth 1 iso-date)))
14860 (deltan
14861 (setq futurep nil)
14862 (unless deltadef
14863 (let ((now (decode-time (current-time))))
14864 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14865 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14866 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14867 ((equal deltaw "m") (setq month (+ month deltan)))
14868 ((equal deltaw "y") (setq year (+ year deltan)))))
14869 ((and wday (not (nth 3 tl)))
14870 (setq futurep nil)
14871 ;; Weekday was given, but no day, so pick that day in the week
14872 ;; on or after the derived date.
14873 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14874 (unless (equal wday wday1)
14875 (setq day (+ day (% (- wday wday1 -7) 7))))))
14876 (if (and (boundp 'org-time-was-given)
14877 (nth 2 tl))
14878 (setq org-time-was-given t))
14879 (if (< year 100) (setq year (+ 2000 year)))
14880 ;; Check of the date is representable
14881 (if org-read-date-force-compatible-dates
14882 (progn
14883 (if (< year 1970)
14884 (setq year 1970 org-read-date-analyze-forced-year t))
14885 (if (> year 2037)
14886 (setq year 2037 org-read-date-analyze-forced-year t)))
14887 (condition-case nil
14888 (ignore (encode-time second minute hour day month year))
14889 (error
14890 (setq year (nth 5 defdecode))
14891 (setq org-read-date-analyze-forced-year t))))
14892 (setq org-read-date-analyze-futurep futurep)
14893 (list second minute hour day month year)))
14895 (defvar parse-time-weekdays)
14897 (defun org-read-date-get-relative (s today default)
14898 "Check string S for special relative date string.
14899 TODAY and DEFAULT are internal times, for today and for a default.
14900 Return shift list (N what def-flag)
14901 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14902 N is the number of WHATs to shift.
14903 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14904 the DEFAULT date rather than TODAY."
14905 (when (and
14906 (string-match
14907 (concat
14908 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14909 "\\([0-9]+\\)?"
14910 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14911 "\\([ \t]\\|$\\)") s)
14912 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14913 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14914 (string-to-char (substring (match-string 1 s) -1))
14915 ?+))
14916 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14917 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14918 (what (if (match-end 3) (match-string 3 s) "d"))
14919 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14920 (date (if rel default today))
14921 (wday (nth 6 (decode-time date)))
14922 delta)
14923 (if wday1
14924 (progn
14925 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14926 (if (= dir ?-) (setq delta (- delta 7)))
14927 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14928 (list delta "d" rel))
14929 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14931 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14932 "Turn a user-specified date into the internal representation.
14933 The internal representation needed by the calendar is (month day year).
14934 This is a wrapper to handle the brain-dead convention in calendar that
14935 user function argument order change dependent on argument order."
14936 (if (boundp 'calendar-date-style)
14937 (cond
14938 ((eq calendar-date-style 'american)
14939 (list arg1 arg2 arg3))
14940 ((eq calendar-date-style 'european)
14941 (list arg2 arg1 arg3))
14942 ((eq calendar-date-style 'iso)
14943 (list arg2 arg3 arg1)))
14944 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14945 (if (org-bound-and-true-p european-calendar-style)
14946 (list arg2 arg1 arg3)
14947 (list arg1 arg2 arg3)))))
14949 (defun org-eval-in-calendar (form &optional keepdate)
14950 "Eval FORM in the calendar window and return to current window.
14951 Also, store the cursor date in variable org-ans2."
14952 (let ((sf (selected-frame))
14953 (sw (selected-window)))
14954 (select-window (get-buffer-window "*Calendar*" t))
14955 (eval form)
14956 (when (and (not keepdate) (calendar-cursor-to-date))
14957 (let* ((date (calendar-cursor-to-date))
14958 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14959 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14960 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14961 (select-window sw)
14962 (org-select-frame-set-input-focus sf)))
14964 (defun org-calendar-select ()
14965 "Return to `org-read-date' with the date currently selected.
14966 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14967 (interactive)
14968 (when (calendar-cursor-to-date)
14969 (let* ((date (calendar-cursor-to-date))
14970 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14971 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14972 (if (active-minibuffer-window) (exit-minibuffer))))
14974 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14975 "Insert a date stamp for the date given by the internal TIME.
14976 WITH-HM means use the stamp format that includes the time of the day.
14977 INACTIVE means use square brackets instead of angular ones, so that the
14978 stamp will not contribute to the agenda.
14979 PRE and POST are optional strings to be inserted before and after the
14980 stamp.
14981 The command returns the inserted time stamp."
14982 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14983 stamp)
14984 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14985 (insert-before-markers (or pre ""))
14986 (when (listp extra)
14987 (setq extra (car extra))
14988 (if (and (stringp extra)
14989 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14990 (setq extra (format "-%02d:%02d"
14991 (string-to-number (match-string 1 extra))
14992 (string-to-number (match-string 2 extra))))
14993 (setq extra nil)))
14994 (when extra
14995 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14996 (insert-before-markers (setq stamp (format-time-string fmt time)))
14997 (insert-before-markers (or post ""))
14998 (setq org-last-inserted-timestamp stamp)))
15000 (defun org-toggle-time-stamp-overlays ()
15001 "Toggle the use of custom time stamp formats."
15002 (interactive)
15003 (setq org-display-custom-times (not org-display-custom-times))
15004 (unless org-display-custom-times
15005 (let ((p (point-min)) (bmp (buffer-modified-p)))
15006 (while (setq p (next-single-property-change p 'display))
15007 (if (and (get-text-property p 'display)
15008 (eq (get-text-property p 'face) 'org-date))
15009 (remove-text-properties
15010 p (setq p (next-single-property-change p 'display))
15011 '(display t))))
15012 (set-buffer-modified-p bmp)))
15013 (if (featurep 'xemacs)
15014 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15015 (org-restart-font-lock)
15016 (setq org-table-may-need-update t)
15017 (if org-display-custom-times
15018 (message "Time stamps are overlayed with custom format")
15019 (message "Time stamp overlays removed")))
15021 (defun org-display-custom-time (beg end)
15022 "Overlay modified time stamp format over timestamp between BEG and END."
15023 (let* ((ts (buffer-substring beg end))
15024 t1 w1 with-hm tf time str w2 (off 0))
15025 (save-match-data
15026 (setq t1 (org-parse-time-string ts t))
15027 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15028 (setq off (- (match-end 0) (match-beginning 0)))))
15029 (setq end (- end off))
15030 (setq w1 (- end beg)
15031 with-hm (and (nth 1 t1) (nth 2 t1))
15032 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15033 time (org-fix-decoded-time t1)
15034 str (org-add-props
15035 (format-time-string
15036 (substring tf 1 -1) (apply 'encode-time time))
15037 nil 'mouse-face 'highlight)
15038 w2 (length str))
15039 (if (not (= w2 w1))
15040 (add-text-properties (1+ beg) (+ 2 beg)
15041 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15042 (if (featurep 'xemacs)
15043 (progn
15044 (put-text-property beg end 'invisible t)
15045 (put-text-property beg end 'end-glyph (make-glyph str)))
15046 (put-text-property beg end 'display str))))
15048 (defun org-translate-time (string)
15049 "Translate all timestamps in STRING to custom format.
15050 But do this only if the variable `org-display-custom-times' is set."
15051 (when org-display-custom-times
15052 (save-match-data
15053 (let* ((start 0)
15054 (re org-ts-regexp-both)
15055 t1 with-hm inactive tf time str beg end)
15056 (while (setq start (string-match re string start))
15057 (setq beg (match-beginning 0)
15058 end (match-end 0)
15059 t1 (save-match-data
15060 (org-parse-time-string (substring string beg end) t))
15061 with-hm (and (nth 1 t1) (nth 2 t1))
15062 inactive (equal (substring string beg (1+ beg)) "[")
15063 tf (funcall (if with-hm 'cdr 'car)
15064 org-time-stamp-custom-formats)
15065 time (org-fix-decoded-time t1)
15066 str (format-time-string
15067 (concat
15068 (if inactive "[" "<") (substring tf 1 -1)
15069 (if inactive "]" ">"))
15070 (apply 'encode-time time))
15071 string (replace-match str t t string)
15072 start (+ start (length str)))))))
15073 string)
15075 (defun org-fix-decoded-time (time)
15076 "Set 0 instead of nil for the first 6 elements of time.
15077 Don't touch the rest."
15078 (let ((n 0))
15079 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15081 (defun org-days-to-time (timestamp-string)
15082 "Difference between TIMESTAMP-STRING and now in days."
15083 (- (time-to-days (org-time-string-to-time timestamp-string))
15084 (time-to-days (current-time))))
15086 (defun org-deadline-close (timestamp-string &optional ndays)
15087 "Is the time in TIMESTAMP-STRING close to the current date?"
15088 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15089 (and (< (org-days-to-time timestamp-string) ndays)
15090 (not (org-entry-is-done-p))))
15092 (defun org-get-wdays (ts)
15093 "Get the deadline lead time appropriate for timestring TS."
15094 (cond
15095 ((<= org-deadline-warning-days 0)
15096 ;; 0 or negative, enforce this value no matter what
15097 (- org-deadline-warning-days))
15098 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15099 ;; lead time is specified.
15100 (floor (* (string-to-number (match-string 1 ts))
15101 (cdr (assoc (match-string 2 ts)
15102 '(("d" . 1) ("w" . 7)
15103 ("m" . 30.4) ("y" . 365.25)))))))
15104 ;; go for the default.
15105 (t org-deadline-warning-days)))
15107 (defun org-calendar-select-mouse (ev)
15108 "Return to `org-read-date' with the date currently selected.
15109 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15110 (interactive "e")
15111 (mouse-set-point ev)
15112 (when (calendar-cursor-to-date)
15113 (let* ((date (calendar-cursor-to-date))
15114 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15115 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15116 (if (active-minibuffer-window) (exit-minibuffer))))
15118 (defun org-check-deadlines (ndays)
15119 "Check if there are any deadlines due or past due.
15120 A deadline is considered due if it happens within `org-deadline-warning-days'
15121 days from today's date. If the deadline appears in an entry marked DONE,
15122 it is not shown. The prefix arg NDAYS can be used to test that many
15123 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15124 (interactive "P")
15125 (let* ((org-warn-days
15126 (cond
15127 ((equal ndays '(4)) 100000)
15128 (ndays (prefix-numeric-value ndays))
15129 (t (abs org-deadline-warning-days))))
15130 (case-fold-search nil)
15131 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15132 (callback
15133 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15135 (message "%d deadlines past-due or due within %d days"
15136 (org-occur regexp nil callback)
15137 org-warn-days)))
15139 (defun org-check-before-date (date)
15140 "Check if there are deadlines or scheduled entries before DATE."
15141 (interactive (list (org-read-date)))
15142 (let ((case-fold-search nil)
15143 (regexp (concat "\\<\\(" org-deadline-string
15144 "\\|" org-scheduled-string
15145 "\\) *<\\([^>]+\\)>"))
15146 (callback
15147 (lambda () (time-less-p
15148 (org-time-string-to-time (match-string 2))
15149 (org-time-string-to-time date)))))
15150 (message "%d entries before %s"
15151 (org-occur regexp nil callback) date)))
15153 (defun org-check-after-date (date)
15154 "Check if there are deadlines or scheduled entries after DATE."
15155 (interactive (list (org-read-date)))
15156 (let ((case-fold-search nil)
15157 (regexp (concat "\\<\\(" org-deadline-string
15158 "\\|" org-scheduled-string
15159 "\\) *<\\([^>]+\\)>"))
15160 (callback
15161 (lambda () (not
15162 (time-less-p
15163 (org-time-string-to-time (match-string 2))
15164 (org-time-string-to-time date))))))
15165 (message "%d entries after %s"
15166 (org-occur regexp nil callback) date)))
15168 (defun org-evaluate-time-range (&optional to-buffer)
15169 "Evaluate a time range by computing the difference between start and end.
15170 Normally the result is just printed in the echo area, but with prefix arg
15171 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15172 If the time range is actually in a table, the result is inserted into the
15173 next column.
15174 For time difference computation, a year is assumed to be exactly 365
15175 days in order to avoid rounding problems."
15176 (interactive "P")
15178 (org-clock-update-time-maybe)
15179 (save-excursion
15180 (unless (org-at-date-range-p t)
15181 (goto-char (point-at-bol))
15182 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15183 (if (not (org-at-date-range-p t))
15184 (error "Not at a time-stamp range, and none found in current line")))
15185 (let* ((ts1 (match-string 1))
15186 (ts2 (match-string 2))
15187 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15188 (match-end (match-end 0))
15189 (time1 (org-time-string-to-time ts1))
15190 (time2 (org-time-string-to-time ts2))
15191 (t1 (org-float-time time1))
15192 (t2 (org-float-time time2))
15193 (diff (abs (- t2 t1)))
15194 (negative (< (- t2 t1) 0))
15195 ;; (ys (floor (* 365 24 60 60)))
15196 (ds (* 24 60 60))
15197 (hs (* 60 60))
15198 (fy "%dy %dd %02d:%02d")
15199 (fy1 "%dy %dd")
15200 (fd "%dd %02d:%02d")
15201 (fd1 "%dd")
15202 (fh "%02d:%02d")
15203 y d h m align)
15204 (if havetime
15205 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15207 d (floor (/ diff ds)) diff (mod diff ds)
15208 h (floor (/ diff hs)) diff (mod diff hs)
15209 m (floor (/ diff 60)))
15210 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15212 d (floor (+ (/ diff ds) 0.5))
15213 h 0 m 0))
15214 (if (not to-buffer)
15215 (message "%s" (org-make-tdiff-string y d h m))
15216 (if (org-at-table-p)
15217 (progn
15218 (goto-char match-end)
15219 (setq align t)
15220 (and (looking-at " *|") (goto-char (match-end 0))))
15221 (goto-char match-end))
15222 (if (looking-at
15223 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15224 (replace-match ""))
15225 (if negative (insert " -"))
15226 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15227 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15228 (insert " " (format fh h m))))
15229 (if align (org-table-align))
15230 (message "Time difference inserted")))))
15232 (defun org-make-tdiff-string (y d h m)
15233 (let ((fmt "")
15234 (l nil))
15235 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15236 l (push y l)))
15237 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15238 l (push d l)))
15239 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15240 l (push h l)))
15241 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15242 l (push m l)))
15243 (apply 'format fmt (nreverse l))))
15245 (defun org-time-string-to-time (s)
15246 (apply 'encode-time (org-parse-time-string s)))
15247 (defun org-time-string-to-seconds (s)
15248 (org-float-time (org-time-string-to-time s)))
15250 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15251 "Convert a time stamp to an absolute day number.
15252 If there is a specifier for a cyclic time stamp, get the closest date to
15253 DAYNR.
15254 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15255 The variable date is bound by the calendar when this is called."
15256 (cond
15257 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15258 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15259 daynr
15260 (+ daynr 1000)))
15261 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15262 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15263 (time-to-days (current-time))) (match-string 0 s)
15264 prefer show-all))
15265 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15267 (defun org-days-to-iso-week (days)
15268 "Return the iso week number."
15269 (require 'cal-iso)
15270 (car (calendar-iso-from-absolute days)))
15272 (defun org-small-year-to-year (year)
15273 "Convert 2-digit years into 4-digit years.
15274 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15275 The year 2000 cannot be abbreviated. Any year larger than 99
15276 is returned unchanged."
15277 (if (< year 38)
15278 (setq year (+ 2000 year))
15279 (if (< year 100)
15280 (setq year (+ 1900 year))))
15281 year)
15283 (defun org-time-from-absolute (d)
15284 "Return the time corresponding to date D.
15285 D may be an absolute day number, or a calendar-type list (month day year)."
15286 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15287 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15289 (defun org-calendar-holiday ()
15290 "List of holidays, for Diary display in Org-mode."
15291 (require 'holidays)
15292 (let ((hl (funcall
15293 (if (fboundp 'calendar-check-holidays)
15294 'calendar-check-holidays 'check-calendar-holidays) date)))
15295 (if hl (mapconcat 'identity hl "; "))))
15297 (defun org-diary-sexp-entry (sexp entry date)
15298 "Process a SEXP diary ENTRY for DATE."
15299 (require 'diary-lib)
15300 (let ((result (if calendar-debug-sexp
15301 (let ((stack-trace-on-error t))
15302 (eval (car (read-from-string sexp))))
15303 (condition-case nil
15304 (eval (car (read-from-string sexp)))
15305 (error
15306 (beep)
15307 (message "Bad sexp at line %d in %s: %s"
15308 (org-current-line)
15309 (buffer-file-name) sexp)
15310 (sleep-for 2))))))
15311 (cond ((stringp result) (split-string result "; "))
15312 ((and (consp result)
15313 (not (consp (cdr result)))
15314 (stringp (cdr result))) (cdr result))
15315 ((and (consp result)
15316 (stringp (car result))) result)
15317 (result entry)
15318 (t nil))))
15320 (defun org-diary-to-ical-string (frombuf)
15321 "Get iCalendar entries from diary entries in buffer FROMBUF.
15322 This uses the icalendar.el library."
15323 (let* ((tmpdir (if (featurep 'xemacs)
15324 (temp-directory)
15325 temporary-file-directory))
15326 (tmpfile (make-temp-name
15327 (expand-file-name "orgics" tmpdir)))
15328 buf rtn b e)
15329 (with-current-buffer frombuf
15330 (icalendar-export-region (point-min) (point-max) tmpfile)
15331 (setq buf (find-buffer-visiting tmpfile))
15332 (set-buffer buf)
15333 (goto-char (point-min))
15334 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15335 (setq b (match-beginning 0)))
15336 (goto-char (point-max))
15337 (if (re-search-backward "^END:VEVENT" nil t)
15338 (setq e (match-end 0)))
15339 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15340 (kill-buffer buf)
15341 (delete-file tmpfile)
15342 rtn))
15344 (defun org-closest-date (start current change prefer show-all)
15345 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15346 When PREFER is `past', return a date that is either CURRENT or past.
15347 When PREFER is `future', return a date that is either CURRENT or future.
15348 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15349 ;; Make the proper lists from the dates
15350 (catch 'exit
15351 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15352 dn dw sday cday n1 n2 n0
15353 d m y y1 y2 date1 date2 nmonths nm ny m2)
15355 (setq start (org-date-to-gregorian start)
15356 current (org-date-to-gregorian
15357 (if show-all
15358 current
15359 (time-to-days (current-time))))
15360 sday (calendar-absolute-from-gregorian start)
15361 cday (calendar-absolute-from-gregorian current))
15363 (if (<= cday sday) (throw 'exit sday))
15365 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15366 (setq dn (string-to-number (match-string 1 change))
15367 dw (cdr (assoc (match-string 2 change) a1)))
15368 (error "Invalid change specifier: %s" change))
15369 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15370 (cond
15371 ((eq dw 'day)
15372 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15373 n2 (+ n1 dn)))
15374 ((eq dw 'year)
15375 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15376 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15377 (setq date1 (list m d y1)
15378 n1 (calendar-absolute-from-gregorian date1)
15379 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15380 n2 (calendar-absolute-from-gregorian date2)))
15381 ((eq dw 'month)
15382 ;; approx number of month between the two dates
15383 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15384 ;; How often does dn fit in there?
15385 (setq d (nth 1 start) m (car start) y (nth 2 start)
15386 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15387 m (+ m nm)
15388 ny (floor (/ m 12))
15389 y (+ y ny)
15390 m (- m (* ny 12)))
15391 (while (> m 12) (setq m (- m 12) y (1+ y)))
15392 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15393 (setq m2 (+ m dn) y2 y)
15394 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15395 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15396 (while (<= n2 cday)
15397 (setq n1 n2 m m2 y y2)
15398 (setq m2 (+ m dn) y2 y)
15399 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15400 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15401 ;; Make sure n1 is the earlier date
15402 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15403 (if show-all
15404 (cond
15405 ((eq prefer 'past) (if (= cday n2) n2 n1))
15406 ((eq prefer 'future) (if (= cday n1) n1 n2))
15407 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15408 (cond
15409 ((eq prefer 'past) (if (= cday n2) n2 n1))
15410 ((eq prefer 'future) (if (= cday n1) n1 n2))
15411 (t (if (= cday n1) n1 n2)))))))
15413 (defun org-date-to-gregorian (date)
15414 "Turn any specification of DATE into a Gregorian date for the calendar."
15415 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15416 ((and (listp date) (= (length date) 3)) date)
15417 ((stringp date)
15418 (setq date (org-parse-time-string date))
15419 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15420 ((listp date)
15421 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15423 (defun org-parse-time-string (s &optional nodefault)
15424 "Parse the standard Org-mode time string.
15425 This should be a lot faster than the normal `parse-time-string'.
15426 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15427 hour and minute fields will be nil if not given."
15428 (if (string-match org-ts-regexp0 s)
15429 (list 0
15430 (if (or (match-beginning 8) (not nodefault))
15431 (string-to-number (or (match-string 8 s) "0")))
15432 (if (or (match-beginning 7) (not nodefault))
15433 (string-to-number (or (match-string 7 s) "0")))
15434 (string-to-number (match-string 4 s))
15435 (string-to-number (match-string 3 s))
15436 (string-to-number (match-string 2 s))
15437 nil nil nil)
15438 (error "Not a standard Org-mode time string: %s" s)))
15440 (defun org-timestamp-up (&optional arg)
15441 "Increase the date item at the cursor by one.
15442 If the cursor is on the year, change the year. If it is on the month or
15443 the day, change that.
15444 With prefix ARG, change by that many units."
15445 (interactive "p")
15446 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15448 (defun org-timestamp-down (&optional arg)
15449 "Decrease the date item at the cursor by one.
15450 If the cursor is on the year, change the year. If it is on the month or
15451 the day, change that.
15452 With prefix ARG, change by that many units."
15453 (interactive "p")
15454 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15456 (defun org-timestamp-up-day (&optional arg)
15457 "Increase the date in the time stamp by one day.
15458 With prefix ARG, change that many days."
15459 (interactive "p")
15460 (if (and (not (org-at-timestamp-p t))
15461 (org-on-heading-p))
15462 (org-todo 'up)
15463 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15465 (defun org-timestamp-down-day (&optional arg)
15466 "Decrease the date in the time stamp by one day.
15467 With prefix ARG, change that many days."
15468 (interactive "p")
15469 (if (and (not (org-at-timestamp-p t))
15470 (org-on-heading-p))
15471 (org-todo 'down)
15472 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15474 (defun org-at-timestamp-p (&optional inactive-ok)
15475 "Determine if the cursor is in or at a timestamp."
15476 (interactive)
15477 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15478 (pos (point))
15479 (ans (or (looking-at tsr)
15480 (save-excursion
15481 (skip-chars-backward "^[<\n\r\t")
15482 (if (> (point) (point-min)) (backward-char 1))
15483 (and (looking-at tsr)
15484 (> (- (match-end 0) pos) -1))))))
15485 (and ans
15486 (boundp 'org-ts-what)
15487 (setq org-ts-what
15488 (cond
15489 ((= pos (match-beginning 0)) 'bracket)
15490 ((= pos (1- (match-end 0))) 'bracket)
15491 ((org-pos-in-match-range pos 2) 'year)
15492 ((org-pos-in-match-range pos 3) 'month)
15493 ((org-pos-in-match-range pos 7) 'hour)
15494 ((org-pos-in-match-range pos 8) 'minute)
15495 ((or (org-pos-in-match-range pos 4)
15496 (org-pos-in-match-range pos 5)) 'day)
15497 ((and (> pos (or (match-end 8) (match-end 5)))
15498 (< pos (match-end 0)))
15499 (- pos (or (match-end 8) (match-end 5))))
15500 (t 'day))))
15501 ans))
15503 (defun org-toggle-timestamp-type ()
15504 "Toggle the type (<active> or [inactive]) of a time stamp."
15505 (interactive)
15506 (when (org-at-timestamp-p t)
15507 (let ((beg (match-beginning 0)) (end (match-end 0))
15508 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15509 (save-excursion
15510 (goto-char beg)
15511 (while (re-search-forward "[][<>]" end t)
15512 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15513 t t)))
15514 (message "Timestamp is now %sactive"
15515 (if (equal (char-after beg) ?<) "" "in")))))
15517 (defun org-timestamp-change (n &optional what updown)
15518 "Change the date in the time stamp at point.
15519 The date will be changed by N times WHAT. WHAT can be `day', `month',
15520 `year', `minute', `second'. If WHAT is not given, the cursor position
15521 in the timestamp determines what will be changed."
15522 (let ((pos (point))
15523 with-hm inactive
15524 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15525 org-ts-what
15526 extra rem
15527 ts time time0)
15528 (if (not (org-at-timestamp-p t))
15529 (error "Not at a timestamp"))
15530 (if (and (not what) (eq org-ts-what 'bracket))
15531 (org-toggle-timestamp-type)
15532 (if (and (not what) (not (eq org-ts-what 'day))
15533 org-display-custom-times
15534 (get-text-property (point) 'display)
15535 (not (get-text-property (1- (point)) 'display)))
15536 (setq org-ts-what 'day))
15537 (setq org-ts-what (or what org-ts-what)
15538 inactive (= (char-after (match-beginning 0)) ?\[)
15539 ts (match-string 0))
15540 (replace-match "")
15541 (if (string-match
15542 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15544 (setq extra (match-string 1 ts)))
15545 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15546 (setq with-hm t))
15547 (setq time0 (org-parse-time-string ts))
15548 (when (and updown
15549 (eq org-ts-what 'minute)
15550 (not current-prefix-arg))
15551 ;; This looks like s-up and s-down. Change by one rounding step.
15552 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15553 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15554 (setcar (cdr time0) (+ (nth 1 time0)
15555 (if (> n 0) (- rem) (- dm rem))))))
15556 (setq time
15557 (encode-time (or (car time0) 0)
15558 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15559 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15560 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15561 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15562 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15563 (nthcdr 6 time0)))
15564 (when (and (member org-ts-what '(hour minute))
15565 extra
15566 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15567 (setq extra (org-modify-ts-extra
15568 extra
15569 (if (eq org-ts-what 'hour) 2 5)
15570 n dm)))
15571 (when (integerp org-ts-what)
15572 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15573 (if (eq what 'calendar)
15574 (let ((cal-date (org-get-date-from-calendar)))
15575 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15576 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15577 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15578 (setcar time0 (or (car time0) 0))
15579 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15580 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15581 (setq time (apply 'encode-time time0))))
15582 (setq org-last-changed-timestamp
15583 (org-insert-time-stamp time with-hm inactive nil nil extra))
15584 (org-clock-update-time-maybe)
15585 (goto-char pos)
15586 ;; Try to recenter the calendar window, if any
15587 (if (and org-calendar-follow-timestamp-change
15588 (get-buffer-window "*Calendar*" t)
15589 (memq org-ts-what '(day month year)))
15590 (org-recenter-calendar (time-to-days time))))))
15592 (defun org-modify-ts-extra (s pos n dm)
15593 "Change the different parts of the lead-time and repeat fields in timestamp."
15594 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15595 ng h m new rem)
15596 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15597 (cond
15598 ((or (org-pos-in-match-range pos 2)
15599 (org-pos-in-match-range pos 3))
15600 (setq m (string-to-number (match-string 3 s))
15601 h (string-to-number (match-string 2 s)))
15602 (if (org-pos-in-match-range pos 2)
15603 (setq h (+ h n))
15604 (setq n (* dm (org-no-warnings (signum n))))
15605 (when (not (= 0 (setq rem (% m dm))))
15606 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15607 (setq m (+ m n)))
15608 (if (< m 0) (setq m (+ m 60) h (1- h)))
15609 (if (> m 59) (setq m (- m 60) h (1+ h)))
15610 (setq h (min 24 (max 0 h)))
15611 (setq ng 1 new (format "-%02d:%02d" h m)))
15612 ((org-pos-in-match-range pos 6)
15613 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15614 ((org-pos-in-match-range pos 5)
15615 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15617 ((org-pos-in-match-range pos 9)
15618 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15619 ((org-pos-in-match-range pos 8)
15620 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15622 (when ng
15623 (setq s (concat
15624 (substring s 0 (match-beginning ng))
15626 (substring s (match-end ng))))))
15629 (defun org-recenter-calendar (date)
15630 "If the calendar is visible, recenter it to DATE."
15631 (let* ((win (selected-window))
15632 (cwin (get-buffer-window "*Calendar*" t))
15633 (calendar-move-hook nil))
15634 (when cwin
15635 (select-window cwin)
15636 (calendar-goto-date (if (listp date) date
15637 (calendar-gregorian-from-absolute date)))
15638 (select-window win))))
15640 (defun org-goto-calendar (&optional arg)
15641 "Go to the Emacs calendar at the current date.
15642 If there is a time stamp in the current line, go to that date.
15643 A prefix ARG can be used to force the current date."
15644 (interactive "P")
15645 (let ((tsr org-ts-regexp) diff
15646 (calendar-move-hook nil)
15647 (calendar-view-holidays-initially-flag nil)
15648 (calendar-view-diary-initially-flag nil))
15649 (if (or (org-at-timestamp-p)
15650 (save-excursion
15651 (beginning-of-line 1)
15652 (looking-at (concat ".*" tsr))))
15653 (let ((d1 (time-to-days (current-time)))
15654 (d2 (time-to-days
15655 (org-time-string-to-time (match-string 1)))))
15656 (setq diff (- d2 d1))))
15657 (calendar)
15658 (calendar-goto-today)
15659 (if (and diff (not arg)) (calendar-forward-day diff))))
15661 (defun org-get-date-from-calendar ()
15662 "Return a list (month day year) of date at point in calendar."
15663 (with-current-buffer "*Calendar*"
15664 (save-match-data
15665 (calendar-cursor-to-date))))
15667 (defun org-date-from-calendar ()
15668 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15669 If there is already a time stamp at the cursor position, update it."
15670 (interactive)
15671 (if (org-at-timestamp-p t)
15672 (org-timestamp-change 0 'calendar)
15673 (let ((cal-date (org-get-date-from-calendar)))
15674 (org-insert-time-stamp
15675 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15677 (defun org-minutes-to-hh:mm-string (m)
15678 "Compute H:MM from a number of minutes."
15679 (let ((h (/ m 60)))
15680 (setq m (- m (* 60 h)))
15681 (format org-time-clocksum-format h m)))
15683 (defun org-hh:mm-string-to-minutes (s)
15684 "Convert a string H:MM to a number of minutes.
15685 If the string is just a number, interpret it as minutes.
15686 In fact, the first hh:mm or number in the string will be taken,
15687 there can be extra stuff in the string.
15688 If no number is found, the return value is 0."
15689 (cond
15690 ((integerp s) s)
15691 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15692 (+ (* (string-to-number (match-string 1 s)) 60)
15693 (string-to-number (match-string 2 s))))
15694 ((string-match "\\([0-9]+\\)" s)
15695 (string-to-number (match-string 1 s)))
15696 (t 0)))
15698 (defcustom org-effort-durations
15699 `(("h" . 60)
15700 ("d" . ,(* 60 8))
15701 ("w" . ,(* 60 8 5))
15702 ("m" . ,(* 60 8 5 4))
15703 ("y" . ,(* 60 8 5 40)))
15704 "Conversion factor to minutes for an effort modifier.
15706 Each entry has the form (MODIFIER . MINUTES).
15708 In an effort string, a number followed by MODIFIER is multiplied
15709 by the specified number of MINUTES to obtain an effort in
15710 minutes.
15712 For example, if the value of this variable is ((\"hours\" . 60)), then an
15713 effort string \"2hours\" is equivalent to 120 minutes."
15714 :group 'org-agenda
15715 :type '(alist :key-type (string :tag "Modifier")
15716 :value-type (number :tag "Minutes")))
15718 (defun org-duration-string-to-minutes (s)
15719 "Convert a duration string S to minutes.
15721 A bare number is interpreted as minutes, modifiers can be set by
15722 customizing `org-effort-durations' (which see).
15724 Entries containing a colon are interpreted as H:MM by
15725 `org-hh:mm-string-to-minutes'."
15726 (let ((result 0)
15727 (re (concat "\\([0-9]+\\) *\\("
15728 (regexp-opt (mapcar 'car org-effort-durations))
15729 "\\)")))
15730 (while (string-match re s)
15731 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15732 (string-to-number (match-string 1 s))))
15733 (setq s (replace-match "" nil t s)))
15734 (incf result (org-hh:mm-string-to-minutes s))
15735 result))
15737 ;;;; Files
15739 (defun org-save-all-org-buffers ()
15740 "Save all Org-mode buffers without user confirmation."
15741 (interactive)
15742 (message "Saving all Org-mode buffers...")
15743 (save-some-buffers t 'org-mode-p)
15744 (when (featurep 'org-id) (org-id-locations-save))
15745 (message "Saving all Org-mode buffers... done"))
15747 (defun org-revert-all-org-buffers ()
15748 "Revert all Org-mode buffers.
15749 Prompt for confirmation when there are unsaved changes.
15750 Be sure you know what you are doing before letting this function
15751 overwrite your changes.
15753 This function is useful in a setup where one tracks org files
15754 with a version control system, to revert on one machine after pulling
15755 changes from another. I believe the procedure must be like this:
15757 1. M-x org-save-all-org-buffers
15758 2. Pull changes from the other machine, resolve conflicts
15759 3. M-x org-revert-all-org-buffers"
15760 (interactive)
15761 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15762 (error "Abort"))
15763 (save-excursion
15764 (save-window-excursion
15765 (mapc
15766 (lambda (b)
15767 (when (and (with-current-buffer b (org-mode-p))
15768 (with-current-buffer b buffer-file-name))
15769 (switch-to-buffer b)
15770 (revert-buffer t 'no-confirm)))
15771 (buffer-list))
15772 (when (and (featurep 'org-id) org-id-track-globally)
15773 (org-id-locations-load)))))
15775 ;;;; Agenda files
15777 ;;;###autoload
15778 (defun org-switchb (&optional arg)
15779 "Switch between Org buffers.
15780 With a prefix argument, restrict available to files.
15781 With two prefix arguments, restrict available buffers to agenda files.
15783 Defaults to `iswitchb' for buffer name completion.
15784 Set `org-completion-use-ido' to make it use ido instead."
15785 (interactive "P")
15786 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15787 ((equal arg '(16)) (org-buffer-list 'agenda))
15788 (t (org-buffer-list))))
15789 (org-completion-use-iswitchb org-completion-use-iswitchb)
15790 (org-completion-use-ido org-completion-use-ido))
15791 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15792 (setq org-completion-use-iswitchb t))
15793 (switch-to-buffer
15794 (org-icompleting-read "Org buffer: "
15795 (mapcar 'list (mapcar 'buffer-name blist))
15796 nil t))))
15798 ;;; Define some older names previously used for this functionality
15799 ;;;###autoload
15800 (defalias 'org-ido-switchb 'org-switchb)
15801 ;;;###autoload
15802 (defalias 'org-iswitchb 'org-switchb)
15804 (defun org-buffer-list (&optional predicate exclude-tmp)
15805 "Return a list of Org buffers.
15806 PREDICATE can be `export', `files' or `agenda'.
15808 export restrict the list to Export buffers.
15809 files restrict the list to buffers visiting Org files.
15810 agenda restrict the list to buffers visiting agenda files.
15812 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15813 (let* ((bfn nil)
15814 (agenda-files (and (eq predicate 'agenda)
15815 (mapcar 'file-truename (org-agenda-files t))))
15816 (filter
15817 (cond
15818 ((eq predicate 'files)
15819 (lambda (b) (with-current-buffer b (org-mode-p))))
15820 ((eq predicate 'export)
15821 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15822 ((eq predicate 'agenda)
15823 (lambda (b)
15824 (with-current-buffer b
15825 (and (org-mode-p)
15826 (setq bfn (buffer-file-name b))
15827 (member (file-truename bfn) agenda-files)))))
15828 (t (lambda (b) (with-current-buffer b
15829 (or (org-mode-p)
15830 (string-match "\*Org .*Export"
15831 (buffer-name b)))))))))
15832 (delq nil
15833 (mapcar
15834 (lambda(b)
15835 (if (and (funcall filter b)
15836 (or (not exclude-tmp)
15837 (not (string-match "tmp" (buffer-name b)))))
15839 nil))
15840 (buffer-list)))))
15842 (defun org-agenda-files (&optional unrestricted archives)
15843 "Get the list of agenda files.
15844 Optional UNRESTRICTED means return the full list even if a restriction
15845 is currently in place.
15846 When ARCHIVES is t, include all archive files that are really being
15847 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15848 `org-agenda-archives-mode' is t."
15849 (let ((files
15850 (cond
15851 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15852 ((stringp org-agenda-files) (org-read-agenda-file-list))
15853 ((listp org-agenda-files) org-agenda-files)
15854 (t (error "Invalid value of `org-agenda-files'")))))
15855 (setq files (apply 'append
15856 (mapcar (lambda (f)
15857 (if (file-directory-p f)
15858 (directory-files
15859 f t org-agenda-file-regexp)
15860 (list f)))
15861 files)))
15862 (when org-agenda-skip-unavailable-files
15863 (setq files (delq nil
15864 (mapcar (function
15865 (lambda (file)
15866 (and (file-readable-p file) file)))
15867 files))))
15868 (when (or (eq archives t)
15869 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15870 (setq files (org-add-archive-files files)))
15871 files))
15873 (defun org-agenda-file-p (&optional file)
15874 "Return non-nil, if FILE is an agenda file.
15875 If FILE is omitted, use the file associated with the current
15876 buffer."
15877 (member (or file (buffer-file-name))
15878 (org-agenda-files t)))
15880 (defun org-edit-agenda-file-list ()
15881 "Edit the list of agenda files.
15882 Depending on setup, this either uses customize to edit the variable
15883 `org-agenda-files', or it visits the file that is holding the list. In the
15884 latter case, the buffer is set up in a way that saving it automatically kills
15885 the buffer and restores the previous window configuration."
15886 (interactive)
15887 (if (stringp org-agenda-files)
15888 (let ((cw (current-window-configuration)))
15889 (find-file org-agenda-files)
15890 (org-set-local 'org-window-configuration cw)
15891 (org-add-hook 'after-save-hook
15892 (lambda ()
15893 (set-window-configuration
15894 (prog1 org-window-configuration
15895 (kill-buffer (current-buffer))))
15896 (org-install-agenda-files-menu)
15897 (message "New agenda file list installed"))
15898 nil 'local)
15899 (message "%s" (substitute-command-keys
15900 "Edit list and finish with \\[save-buffer]")))
15901 (customize-variable 'org-agenda-files)))
15903 (defun org-store-new-agenda-file-list (list)
15904 "Set new value for the agenda file list and save it correctly."
15905 (if (stringp org-agenda-files)
15906 (let ((fe (org-read-agenda-file-list t)) b u)
15907 (while (setq b (find-buffer-visiting org-agenda-files))
15908 (kill-buffer b))
15909 (with-temp-file org-agenda-files
15910 (insert
15911 (mapconcat
15912 (lambda (f) ;; Keep un-expanded entries.
15913 (if (setq u (assoc f fe))
15914 (cdr u)
15916 list "\n")
15917 "\n")))
15918 (let ((org-mode-hook nil) (org-inhibit-startup t)
15919 (org-insert-mode-line-in-empty-file nil))
15920 (setq org-agenda-files list)
15921 (customize-save-variable 'org-agenda-files org-agenda-files))))
15923 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15924 "Read the list of agenda files from a file.
15925 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15926 filenames, used by `org-store-new-agenda-file-list' to write back
15927 un-expanded file names."
15928 (when (file-directory-p org-agenda-files)
15929 (error "`org-agenda-files' cannot be a single directory"))
15930 (when (stringp org-agenda-files)
15931 (with-temp-buffer
15932 (insert-file-contents org-agenda-files)
15933 (mapcar
15934 (lambda (f)
15935 (let ((e (expand-file-name (substitute-in-file-name f)
15936 org-directory)))
15937 (if pair-with-expansion
15938 (cons e f)
15939 e)))
15940 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15942 ;;;###autoload
15943 (defun org-cycle-agenda-files ()
15944 "Cycle through the files in `org-agenda-files'.
15945 If the current buffer visits an agenda file, find the next one in the list.
15946 If the current buffer does not, find the first agenda file."
15947 (interactive)
15948 (let* ((fs (org-agenda-files t))
15949 (files (append fs (list (car fs))))
15950 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15951 file)
15952 (unless files (error "No agenda files"))
15953 (catch 'exit
15954 (while (setq file (pop files))
15955 (if (equal (file-truename file) tcf)
15956 (when (car files)
15957 (find-file (car files))
15958 (throw 'exit t))))
15959 (find-file (car fs)))
15960 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15962 (defun org-agenda-file-to-front (&optional to-end)
15963 "Move/add the current file to the top of the agenda file list.
15964 If the file is not present in the list, it is added to the front. If it is
15965 present, it is moved there. With optional argument TO-END, add/move to the
15966 end of the list."
15967 (interactive "P")
15968 (let ((org-agenda-skip-unavailable-files nil)
15969 (file-alist (mapcar (lambda (x)
15970 (cons (file-truename x) x))
15971 (org-agenda-files t)))
15972 (ctf (file-truename buffer-file-name))
15973 x had)
15974 (setq x (assoc ctf file-alist) had x)
15976 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15977 (if to-end
15978 (setq file-alist (append (delq x file-alist) (list x)))
15979 (setq file-alist (cons x (delq x file-alist))))
15980 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15981 (org-install-agenda-files-menu)
15982 (message "File %s to %s of agenda file list"
15983 (if had "moved" "added") (if to-end "end" "front"))))
15985 (defun org-remove-file (&optional file)
15986 "Remove current file from the list of files in variable `org-agenda-files'.
15987 These are the files which are being checked for agenda entries.
15988 Optional argument FILE means use this file instead of the current."
15989 (interactive)
15990 (let* ((org-agenda-skip-unavailable-files nil)
15991 (file (or file buffer-file-name))
15992 (true-file (file-truename file))
15993 (afile (abbreviate-file-name file))
15994 (files (delq nil (mapcar
15995 (lambda (x)
15996 (if (equal true-file
15997 (file-truename x))
15998 nil x))
15999 (org-agenda-files t)))))
16000 (if (not (= (length files) (length (org-agenda-files t))))
16001 (progn
16002 (org-store-new-agenda-file-list files)
16003 (org-install-agenda-files-menu)
16004 (message "Removed file: %s" afile))
16005 (message "File was not in list: %s (not removed)" afile))))
16007 (defun org-file-menu-entry (file)
16008 (vector file (list 'find-file file) t))
16010 (defun org-check-agenda-file (file)
16011 "Make sure FILE exists. If not, ask user what to do."
16012 (when (not (file-exists-p file))
16013 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16014 (abbreviate-file-name file))
16015 (let ((r (downcase (read-char-exclusive))))
16016 (cond
16017 ((equal r ?r)
16018 (org-remove-file file)
16019 (throw 'nextfile t))
16020 (t (error "Abort"))))))
16022 (defun org-get-agenda-file-buffer (file)
16023 "Get a buffer visiting FILE. If the buffer needs to be created, add
16024 it to the list of buffers which might be released later."
16025 (let ((buf (org-find-base-buffer-visiting file)))
16026 (if buf
16027 buf ; just return it
16028 ;; Make a new buffer and remember it
16029 (setq buf (find-file-noselect file))
16030 (if buf (push buf org-agenda-new-buffers))
16031 buf)))
16033 (defun org-release-buffers (blist)
16034 "Release all buffers in list, asking the user for confirmation when needed.
16035 When a buffer is unmodified, it is just killed. When modified, it is saved
16036 \(if the user agrees) and then killed."
16037 (let (buf file)
16038 (while (setq buf (pop blist))
16039 (setq file (buffer-file-name buf))
16040 (when (and (buffer-modified-p buf)
16041 file
16042 (y-or-n-p (format "Save file %s? " file)))
16043 (with-current-buffer buf (save-buffer)))
16044 (kill-buffer buf))))
16046 (defun org-prepare-agenda-buffers (files)
16047 "Create buffers for all agenda files, protect archived trees and comments."
16048 (interactive)
16049 (let ((pa '(:org-archived t))
16050 (pc '(:org-comment t))
16051 (pall '(:org-archived t :org-comment t))
16052 (inhibit-read-only t)
16053 (rea (concat ":" org-archive-tag ":"))
16054 bmp file re)
16055 (save-excursion
16056 (save-restriction
16057 (while (setq file (pop files))
16058 (catch 'nextfile
16059 (if (bufferp file)
16060 (set-buffer file)
16061 (org-check-agenda-file file)
16062 (set-buffer (org-get-agenda-file-buffer file)))
16063 (widen)
16064 (setq bmp (buffer-modified-p))
16065 (org-refresh-category-properties)
16066 (setq org-todo-keywords-for-agenda
16067 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16068 (setq org-done-keywords-for-agenda
16069 (append org-done-keywords-for-agenda org-done-keywords))
16070 (setq org-todo-keyword-alist-for-agenda
16071 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16072 (setq org-drawers-for-agenda
16073 (append org-drawers-for-agenda org-drawers))
16074 (setq org-tag-alist-for-agenda
16075 (append org-tag-alist-for-agenda org-tag-alist))
16077 (save-excursion
16078 (remove-text-properties (point-min) (point-max) pall)
16079 (when org-agenda-skip-archived-trees
16080 (goto-char (point-min))
16081 (while (re-search-forward rea nil t)
16082 (if (org-on-heading-p t)
16083 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16084 (goto-char (point-min))
16085 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16086 (while (re-search-forward re nil t)
16087 (add-text-properties
16088 (match-beginning 0) (org-end-of-subtree t) pc)))
16089 (set-buffer-modified-p bmp)))))
16090 (setq org-todo-keywords-for-agenda
16091 (org-uniquify org-todo-keywords-for-agenda))
16092 (setq org-todo-keyword-alist-for-agenda
16093 (org-uniquify org-todo-keyword-alist-for-agenda)
16094 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16096 ;;;; Embedded LaTeX
16098 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16099 "Keymap for the minor `org-cdlatex-mode'.")
16101 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16102 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16103 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16104 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16105 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16107 (defvar org-cdlatex-texmathp-advice-is-done nil
16108 "Flag remembering if we have applied the advice to texmathp already.")
16110 (define-minor-mode org-cdlatex-mode
16111 "Toggle the minor `org-cdlatex-mode'.
16112 This mode supports entering LaTeX environment and math in LaTeX fragments
16113 in Org-mode.
16114 \\{org-cdlatex-mode-map}"
16115 nil " OCDL" nil
16116 (when org-cdlatex-mode (require 'cdlatex))
16117 (unless org-cdlatex-texmathp-advice-is-done
16118 (setq org-cdlatex-texmathp-advice-is-done t)
16119 (defadvice texmathp (around org-math-always-on activate)
16120 "Always return t in org-mode buffers.
16121 This is because we want to insert math symbols without dollars even outside
16122 the LaTeX math segments. If Orgmode thinks that point is actually inside
16123 an embedded LaTeX fragment, let texmathp do its job.
16124 \\[org-cdlatex-mode-map]"
16125 (interactive)
16126 (let (p)
16127 (cond
16128 ((not (org-mode-p)) ad-do-it)
16129 ((eq this-command 'cdlatex-math-symbol)
16130 (setq ad-return-value t
16131 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16133 (let ((p (org-inside-LaTeX-fragment-p)))
16134 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16135 (setq ad-return-value t
16136 texmathp-why '("Org-mode embedded math" . 0))
16137 (if p ad-do-it)))))))))
16139 (defun turn-on-org-cdlatex ()
16140 "Unconditionally turn on `org-cdlatex-mode'."
16141 (org-cdlatex-mode 1))
16143 (defun org-inside-LaTeX-fragment-p ()
16144 "Test if point is inside a LaTeX fragment.
16145 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16146 sequence appearing also before point.
16147 Even though the matchers for math are configurable, this function assumes
16148 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16149 delimiters are skipped when they have been removed by customization.
16150 The return value is nil, or a cons cell with the delimiter and the
16151 position of this delimiter.
16153 This function does a reasonably good job, but can locally be fooled by
16154 for example currency specifications. For example it will assume being in
16155 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16156 fragments that are properly closed, but during editing, we have to live
16157 with the uncertainty caused by missing closing delimiters. This function
16158 looks only before point, not after."
16159 (catch 'exit
16160 (let ((pos (point))
16161 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16162 (lim (progn
16163 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16164 (point)))
16165 dd-on str (start 0) m re)
16166 (goto-char pos)
16167 (when dodollar
16168 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16169 re (nth 1 (assoc "$" org-latex-regexps)))
16170 (while (string-match re str start)
16171 (cond
16172 ((= (match-end 0) (length str))
16173 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16174 ((= (match-end 0) (- (length str) 5))
16175 (throw 'exit nil))
16176 (t (setq start (match-end 0))))))
16177 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16178 (goto-char pos)
16179 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16180 (and (match-beginning 2) (throw 'exit nil))
16181 ;; count $$
16182 (while (re-search-backward "\\$\\$" lim t)
16183 (setq dd-on (not dd-on)))
16184 (goto-char pos)
16185 (if dd-on (cons "$$" m))))))
16187 (defun org-inside-latex-macro-p ()
16188 "Is point inside a LaTeX macro or its arguments?"
16189 (save-match-data
16190 (org-in-regexp
16191 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16193 (defun org-try-cdlatex-tab ()
16194 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16195 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16196 - inside a LaTeX fragment, or
16197 - after the first word in a line, where an abbreviation expansion could
16198 insert a LaTeX environment."
16199 (when org-cdlatex-mode
16200 (cond
16201 ((save-excursion
16202 (skip-chars-backward "a-zA-Z0-9*")
16203 (skip-chars-backward " \t")
16204 (bolp))
16205 (cdlatex-tab) t)
16206 ((org-inside-LaTeX-fragment-p)
16207 (cdlatex-tab) t)
16208 (t nil))))
16210 (defun org-cdlatex-underscore-caret (&optional arg)
16211 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16212 Revert to the normal definition outside of these fragments."
16213 (interactive "P")
16214 (if (org-inside-LaTeX-fragment-p)
16215 (call-interactively 'cdlatex-sub-superscript)
16216 (let (org-cdlatex-mode)
16217 (call-interactively (key-binding (vector last-input-event))))))
16219 (defun org-cdlatex-math-modify (&optional arg)
16220 "Execute `cdlatex-math-modify' in LaTeX fragments.
16221 Revert to the normal definition outside of these fragments."
16222 (interactive "P")
16223 (if (org-inside-LaTeX-fragment-p)
16224 (call-interactively 'cdlatex-math-modify)
16225 (let (org-cdlatex-mode)
16226 (call-interactively (key-binding (vector last-input-event))))))
16228 (defvar org-latex-fragment-image-overlays nil
16229 "List of overlays carrying the images of latex fragments.")
16230 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16232 (defun org-remove-latex-fragment-image-overlays ()
16233 "Remove all overlays with LaTeX fragment images in current buffer."
16234 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16235 (setq org-latex-fragment-image-overlays nil))
16237 (defun org-preview-latex-fragment (&optional subtree)
16238 "Preview the LaTeX fragment at point, or all locally or globally.
16239 If the cursor is in a LaTeX fragment, create the image and overlay
16240 it over the source code. If there is no fragment at point, display
16241 all fragments in the current text, from one headline to the next. With
16242 prefix SUBTREE, display all fragments in the current subtree. With a
16243 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16244 the cursor is before the first headline,
16245 display all fragments in the buffer.
16246 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16247 (interactive "P")
16248 (org-remove-latex-fragment-image-overlays)
16249 (save-excursion
16250 (save-restriction
16251 (let (beg end at msg)
16252 (cond
16253 ((or (equal subtree '(16))
16254 (not (save-excursion
16255 (re-search-backward (concat "^" outline-regexp) nil t))))
16256 (setq beg (point-min) end (point-max)
16257 msg "Creating images for buffer...%s"))
16258 ((equal subtree '(4))
16259 (org-back-to-heading)
16260 (setq beg (point) end (org-end-of-subtree t)
16261 msg "Creating images for subtree...%s"))
16263 (if (setq at (org-inside-LaTeX-fragment-p))
16264 (goto-char (max (point-min) (- (cdr at) 2)))
16265 (org-back-to-heading))
16266 (setq beg (point) end (progn (outline-next-heading) (point))
16267 msg (if at "Creating image...%s"
16268 "Creating images for entry...%s"))))
16269 (message msg "")
16270 (narrow-to-region beg end)
16271 (goto-char beg)
16272 (org-format-latex
16273 (concat "ltxpng/" (file-name-sans-extension
16274 (file-name-nondirectory
16275 buffer-file-name)))
16276 default-directory 'overlays msg at 'forbuffer 'dvipng)
16277 (message msg "done. Use `C-c C-c' to remove images.")))))
16279 (defvar org-latex-regexps
16280 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16281 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16282 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16283 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16284 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16285 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16286 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16287 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16288 "Regular expressions for matching embedded LaTeX.")
16290 (defvar org-export-have-math nil) ;; dynamic scoping
16291 (defun org-format-latex (prefix &optional dir overlays msg at
16292 forbuffer processing-type)
16293 "Replace LaTeX fragments with links to an image, and produce images.
16294 Some of the options can be changed using the variable
16295 `org-format-latex-options'."
16296 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16297 (let* ((prefixnodir (file-name-nondirectory prefix))
16298 (absprefix (expand-file-name prefix dir))
16299 (todir (file-name-directory absprefix))
16300 (opt org-format-latex-options)
16301 (matchers (plist-get opt :matchers))
16302 (re-list org-latex-regexps)
16303 (org-format-latex-header-extra
16304 (plist-get (org-infile-export-plist) :latex-header-extra))
16305 (cnt 0) txt hash link beg end re e checkdir
16306 executables-checked string
16307 m n block linkfile movefile ov)
16308 ;; Check the different regular expressions
16309 (while (setq e (pop re-list))
16310 (setq m (car e) re (nth 1 e) n (nth 2 e)
16311 block (if (nth 3 e) "\n\n" ""))
16312 (when (member m matchers)
16313 (goto-char (point-min))
16314 (while (re-search-forward re nil t)
16315 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16316 (not (get-text-property (match-beginning n)
16317 'org-protected))
16318 (or (not overlays)
16319 (not (eq (get-char-property (match-beginning n)
16320 'org-overlay-type)
16321 'org-latex-overlay))))
16322 (setq org-export-have-math t)
16323 (cond
16324 ((eq processing-type 'verbatim)
16325 ;; Leave the text verbatim, just protect it
16326 (add-text-properties (match-beginning n) (match-end n)
16327 '(org-protected t)))
16328 ((eq processing-type 'mathjax)
16329 ;; Prepare for MathJax processing
16330 (setq string (match-string n))
16331 (if (member m '("$" "$1"))
16332 (save-excursion
16333 (delete-region (match-beginning n) (match-end n))
16334 (goto-char (match-beginning n))
16335 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16336 "\\)")
16337 '(org-protected t))))
16338 (add-text-properties (match-beginning n) (match-end n)
16339 '(org-protected t))))
16340 ((or (eq processing-type 'dvipng) t)
16341 ;; Process to an image
16342 (setq txt (match-string n)
16343 beg (match-beginning n) end (match-end n)
16344 cnt (1+ cnt))
16345 (let (print-length print-level) ; make sure full list is printed
16346 (setq hash (sha1 (prin1-to-string
16347 (list org-format-latex-header
16348 org-format-latex-header-extra
16349 org-export-latex-default-packages-alist
16350 org-export-latex-packages-alist
16351 org-format-latex-options
16352 forbuffer txt)))
16353 linkfile (format "%s_%s.png" prefix hash)
16354 movefile (format "%s_%s.png" absprefix hash)))
16355 (setq link (concat block "[[file:" linkfile "]]" block))
16356 (if msg (message msg cnt))
16357 (goto-char beg)
16358 (unless checkdir ; make sure the directory exists
16359 (setq checkdir t)
16360 (or (file-directory-p todir) (make-directory todir t)))
16362 (unless executables-checked
16363 (org-check-external-command
16364 "latex" "needed to convert LaTeX fragments to images")
16365 (org-check-external-command
16366 "dvipng" "needed to convert LaTeX fragments to images")
16367 (setq executables-checked t))
16369 (unless (file-exists-p movefile)
16370 (org-create-formula-image
16371 txt movefile opt forbuffer))
16372 (if overlays
16373 (progn
16374 (mapc (lambda (o)
16375 (if (eq (overlay-get o 'org-overlay-type)
16376 'org-latex-overlay)
16377 (delete-overlay o)))
16378 (overlays-in beg end))
16379 (setq ov (make-overlay beg end))
16380 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16381 (if (featurep 'xemacs)
16382 (progn
16383 (overlay-put ov 'invisible t)
16384 (overlay-put
16385 ov 'end-glyph
16386 (make-glyph (vector 'png :file movefile))))
16387 (overlay-put
16388 ov 'display
16389 (list 'image :type 'png :file movefile :ascent 'center)))
16390 (push ov org-latex-fragment-image-overlays)
16391 (goto-char end))
16392 (delete-region beg end)
16393 (insert (org-add-props link
16394 (list 'org-latex-src
16395 (replace-regexp-in-string
16396 "\"" "" txt)))))))))))))
16398 ;; This function borrows from Ganesh Swami's latex2png.el
16399 (defun org-create-formula-image (string tofile options buffer)
16400 "This calls dvipng."
16401 (require 'org-latex)
16402 (let* ((tmpdir (if (featurep 'xemacs)
16403 (temp-directory)
16404 temporary-file-directory))
16405 (texfilebase (make-temp-name
16406 (expand-file-name "orgtex" tmpdir)))
16407 (texfile (concat texfilebase ".tex"))
16408 (dvifile (concat texfilebase ".dvi"))
16409 (pngfile (concat texfilebase ".png"))
16410 (fnh (if (featurep 'xemacs)
16411 (font-height (get-face-font 'default))
16412 (face-attribute 'default :height nil)))
16413 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16414 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16415 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16416 "Black"))
16417 (bg (or (plist-get options (if buffer :background :html-background))
16418 "Transparent")))
16419 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16420 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16421 (with-temp-file texfile
16422 (insert (org-splice-latex-header
16423 org-format-latex-header
16424 org-export-latex-default-packages-alist
16425 org-export-latex-packages-alist t
16426 org-format-latex-header-extra))
16427 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16428 (require 'org-latex)
16429 (org-export-latex-fix-inputenc))
16430 (let ((dir default-directory))
16431 (condition-case nil
16432 (progn
16433 (cd tmpdir)
16434 (call-process "latex" nil nil nil texfile))
16435 (error nil))
16436 (cd dir))
16437 (if (not (file-exists-p dvifile))
16438 (progn (message "Failed to create dvi file from %s" texfile) nil)
16439 (condition-case nil
16440 (call-process "dvipng" nil nil nil
16441 "-fg" fg "-bg" bg
16442 "-D" dpi
16443 ;;"-x" scale "-y" scale
16444 "-T" "tight"
16445 "-o" pngfile
16446 dvifile)
16447 (error nil))
16448 (if (not (file-exists-p pngfile))
16449 (if org-format-latex-signal-error
16450 (error "Failed to create png file from %s" texfile)
16451 (message "Failed to create png file from %s" texfile)
16452 nil)
16453 ;; Use the requested file name and clean up
16454 (copy-file pngfile tofile 'replace)
16455 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16456 (delete-file (concat texfilebase e)))
16457 pngfile))))
16459 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16460 "Fill a LaTeX header template TPL.
16461 In the template, the following place holders will be recognized:
16463 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16464 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16465 [PACKAGES] \\usepackage statements for PKG
16466 [NO-PACKAGES] do not include PKG
16467 [EXTRA] the string EXTRA
16468 [NO-EXTRA] do not include EXTRA
16470 For backward compatibility, if both the positive and the negative place
16471 holder is missing, the positive one (without the \"NO-\") will be
16472 assumed to be present at the end of the template.
16473 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16474 EXTRA is a string.
16475 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16476 (let (rpl (end ""))
16477 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16478 (setq rpl (if (or (match-end 1) (not def-pkg))
16479 "" (org-latex-packages-to-string def-pkg snippets-p t))
16480 tpl (replace-match rpl t t tpl))
16481 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16483 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16484 (setq rpl (if (or (match-end 1) (not pkg))
16485 "" (org-latex-packages-to-string pkg snippets-p t))
16486 tpl (replace-match rpl t t tpl))
16487 (if pkg (setq end
16488 (concat end "\n"
16489 (org-latex-packages-to-string pkg snippets-p)))))
16491 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16492 (setq rpl (if (or (match-end 1) (not extra))
16493 "" (concat extra "\n"))
16494 tpl (replace-match rpl t t tpl))
16495 (if (and extra (string-match "\\S-" extra))
16496 (setq end (concat end "\n" extra))))
16498 (if (string-match "\\S-" end)
16499 (concat tpl "\n" end)
16500 tpl)))
16502 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16503 "Turn an alist of packages into a string with the \\usepackage macros."
16504 (setq pkg (mapconcat (lambda(p)
16505 (cond
16506 ((stringp p) p)
16507 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16508 (format "%% Package %s omitted" (cadr p)))
16509 ((equal "" (car p))
16510 (format "\\usepackage{%s}" (cadr p)))
16512 (format "\\usepackage[%s]{%s}"
16513 (car p) (cadr p)))))
16515 "\n"))
16516 (if newline (concat pkg "\n") pkg))
16518 (defun org-dvipng-color (attr)
16519 "Return an rgb color specification for dvipng."
16520 (apply 'format "rgb %s %s %s"
16521 (mapcar 'org-normalize-color
16522 (color-values (face-attribute 'default attr nil)))))
16524 (defun org-normalize-color (value)
16525 "Return string to be used as color value for an RGB component."
16526 (format "%g" (/ value 65535.0)))
16528 ;; Image display
16531 (defvar org-inline-image-overlays nil)
16532 (make-variable-buffer-local 'org-inline-image-overlays)
16534 (defun org-toggle-inline-images (&optional include-linked)
16535 "Toggle the display of inline images.
16536 INCLUDE-LINKED is passed to `org-display-inline-images'."
16537 (interactive "P")
16538 (if org-inline-image-overlays
16539 (progn
16540 (org-remove-inline-images)
16541 (message "Inline image display turned off"))
16542 (org-display-inline-images include-linked)
16543 (if org-inline-image-overlays
16544 (message "%d images displayed inline"
16545 (length org-inline-image-overlays))
16546 (message "No images to display inline"))))
16548 (defun org-display-inline-images (&optional include-linked refresh beg end)
16549 "Display inline images.
16550 Normally only links without a description part are inlined, because this
16551 is how it will work for export. When INCLUDE-LINKED is set, also links
16552 with a description part will be inlined. This can be nice for a quick
16553 look at those images, but it does not reflect what exported files will look
16554 like.
16555 When REFRESH is set, refresh existing images between BEG and END.
16556 This will create new image displays only if necessary.
16557 BEG and END default to the buffer boundaries."
16558 (interactive "P")
16559 (unless refresh
16560 (org-remove-inline-images)
16561 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16562 (save-excursion
16563 (save-restriction
16564 (widen)
16565 (setq beg (or beg (point-min)) end (or end (point-max)))
16566 (goto-char (point-min))
16567 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16568 (substring (org-image-file-name-regexp) 0 -2)
16569 "\\)\\]" (if include-linked "" "\\]")))
16570 old file ov img)
16571 (while (re-search-forward re end t)
16572 (setq old (get-char-property-and-overlay (match-beginning 1)
16573 'org-image-overlay))
16574 (setq file (expand-file-name
16575 (concat (or (match-string 3) "") (match-string 4))))
16576 (when (file-exists-p file)
16577 (if (and (car-safe old) refresh)
16578 (image-refresh (overlay-get (cdr old) 'display))
16579 (setq img (save-match-data (create-image file)))
16580 (when img
16581 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16582 (overlay-put ov 'display img)
16583 (overlay-put ov 'face 'default)
16584 (overlay-put ov 'org-image-overlay t)
16585 (overlay-put ov 'modification-hooks
16586 (list 'org-display-inline-modification-hook))
16587 (push ov org-inline-image-overlays)))))))))
16589 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16590 "Remove inline-display overlay if a corresponding region is modified."
16591 (let ((inhibit-modification-hooks t))
16592 (when (and ov after)
16593 (delete ov org-inline-image-overlays)
16594 (delete-overlay ov))))
16596 (defun org-remove-inline-images ()
16597 "Remove inline display of images."
16598 (interactive)
16599 (mapc 'delete-overlay org-inline-image-overlays)
16600 (setq org-inline-image-overlays nil))
16602 ;;;; Key bindings
16604 ;; Make `C-c C-x' a prefix key
16605 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16607 ;; TAB key with modifiers
16608 (org-defkey org-mode-map "\C-i" 'org-cycle)
16609 (org-defkey org-mode-map [(tab)] 'org-cycle)
16610 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16611 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16612 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16613 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16614 ;; The following line is necessary under Suse GNU/Linux
16615 (unless (featurep 'xemacs)
16616 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16617 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16618 (define-key org-mode-map [backtab] 'org-shifttab)
16620 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16621 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16622 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16624 ;; Cursor keys with modifiers
16625 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16626 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16627 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16628 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16630 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16631 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16632 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16633 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16635 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16636 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16637 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16638 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16640 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16641 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16643 ;; Babel keys
16644 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16645 (mapc (lambda (pair)
16646 (define-key org-babel-map (car pair) (cdr pair)))
16647 org-babel-key-bindings)
16649 ;;; Extra keys for tty access.
16650 ;; We only set them when really needed because otherwise the
16651 ;; menus don't show the simple keys
16653 (when (or org-use-extra-keys
16654 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16655 (not window-system))
16656 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16657 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16658 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16659 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16660 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16661 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16662 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16663 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16664 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16665 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16666 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16667 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16668 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16669 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16670 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16671 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16672 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16673 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16674 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16675 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16676 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16677 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16678 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16679 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16680 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16681 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16682 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16683 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16685 ;; All the other keys
16687 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16688 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16689 (if (boundp 'narrow-map)
16690 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16691 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16692 (if (boundp 'narrow-map)
16693 (org-defkey narrow-map "b" 'org-narrow-to-block)
16694 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16695 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16696 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16697 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16698 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16699 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16700 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16701 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16702 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16703 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16704 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16705 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16706 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16707 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16708 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16709 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16710 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16711 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16712 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16713 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16714 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16715 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16716 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16717 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16718 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16719 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16720 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16721 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16722 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16723 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16724 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16725 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16726 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16727 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16728 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16729 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16730 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16731 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16732 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16733 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16734 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16735 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16736 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16737 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16738 (org-defkey org-mode-map "\C-c^" 'org-sort)
16739 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16740 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16741 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16742 (org-defkey org-mode-map "\C-m" 'org-return)
16743 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16744 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16745 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16746 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16747 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16748 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16749 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16750 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16751 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16752 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16753 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16754 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16755 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16756 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16757 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16758 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16759 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16760 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16761 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16762 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16763 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16764 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16766 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16767 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16768 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16769 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16771 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16772 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16773 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16774 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16775 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16776 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16777 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16778 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16779 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16780 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16781 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16782 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16783 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16784 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16785 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16786 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16787 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16788 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16790 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16791 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16792 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16793 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16794 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16796 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16798 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16800 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16801 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16803 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16806 (when (featurep 'xemacs)
16807 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16810 (defconst org-speed-commands-default
16812 ("Outline Navigation")
16813 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16814 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16815 ("f" . (org-speed-move-safe 'org-forward-same-level))
16816 ("b" . (org-speed-move-safe 'org-backward-same-level))
16817 ("u" . (org-speed-move-safe 'outline-up-heading))
16818 ("j" . org-goto)
16819 ("g" . (org-refile t))
16820 ("Outline Visibility")
16821 ("c" . org-cycle)
16822 ("C" . org-shifttab)
16823 (" " . org-display-outline-path)
16824 ("Outline Structure Editing")
16825 ("U" . org-shiftmetaup)
16826 ("D" . org-shiftmetadown)
16827 ("r" . org-metaright)
16828 ("l" . org-metaleft)
16829 ("R" . org-shiftmetaright)
16830 ("L" . org-shiftmetaleft)
16831 ("i" . (progn (forward-char 1) (call-interactively
16832 'org-insert-heading-respect-content)))
16833 ("^" . org-sort)
16834 ("w" . org-refile)
16835 ("a" . org-archive-subtree-default-with-confirmation)
16836 ("." . org-mark-subtree)
16837 ("Clock Commands")
16838 ("I" . org-clock-in)
16839 ("O" . org-clock-out)
16840 ("Meta Data Editing")
16841 ("t" . org-todo)
16842 ("0" . (org-priority ?\ ))
16843 ("1" . (org-priority ?A))
16844 ("2" . (org-priority ?B))
16845 ("3" . (org-priority ?C))
16846 (";" . org-set-tags-command)
16847 ("e" . org-set-effort)
16848 ("Agenda Views etc")
16849 ("v" . org-agenda)
16850 ("/" . org-sparse-tree)
16851 ("Misc")
16852 ("o" . org-open-at-point)
16853 ("?" . org-speed-command-help)
16854 ("<" . (org-agenda-set-restriction-lock 'subtree))
16855 (">" . (org-agenda-remove-restriction-lock))
16857 "The default speed commands.")
16859 (defun org-print-speed-command (e)
16860 (if (> (length (car e)) 1)
16861 (progn
16862 (princ "\n")
16863 (princ (car e))
16864 (princ "\n")
16865 (princ (make-string (length (car e)) ?-))
16866 (princ "\n"))
16867 (princ (car e))
16868 (princ " ")
16869 (if (symbolp (cdr e))
16870 (princ (symbol-name (cdr e)))
16871 (prin1 (cdr e)))
16872 (princ "\n")))
16874 (defun org-speed-command-help ()
16875 "Show the available speed commands."
16876 (interactive)
16877 (if (not org-use-speed-commands)
16878 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16879 (with-output-to-temp-buffer "*Help*"
16880 (princ "User-defined Speed commands\n===========================\n")
16881 (mapc 'org-print-speed-command org-speed-commands-user)
16882 (princ "\n")
16883 (princ "Built-in Speed commands\n=======================\n")
16884 (mapc 'org-print-speed-command org-speed-commands-default))
16885 (with-current-buffer "*Help*"
16886 (setq truncate-lines t))))
16888 (defun org-speed-move-safe (cmd)
16889 "Execute CMD, but make sure that the cursor always ends up in a headline.
16890 If not, return to the original position and throw an error."
16891 (interactive)
16892 (let ((pos (point)))
16893 (call-interactively cmd)
16894 (unless (and (bolp) (org-on-heading-p))
16895 (goto-char pos)
16896 (error "Boundary reached while executing %s" cmd))))
16898 (defvar org-self-insert-command-undo-counter 0)
16900 (defvar org-table-auto-blank-field) ; defined in org-table.el
16901 (defvar org-speed-command nil)
16903 (defun org-speed-command-default-hook (keys)
16904 "Hook for activating single-letter speed commands.
16905 `org-speed-commands-default' specifies a minimal command set. Use
16906 `org-speed-commands-user' for further customization."
16907 (when (or (and (bolp) (looking-at outline-regexp))
16908 (and (functionp org-use-speed-commands)
16909 (funcall org-use-speed-commands)))
16910 (cdr (assoc keys (append org-speed-commands-user
16911 org-speed-commands-default)))))
16913 (defun org-babel-speed-command-hook (keys)
16914 "Hook for activating single-letter code block commands."
16915 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16916 (cdr (assoc keys org-babel-key-bindings))))
16918 (defcustom org-speed-command-hook
16919 '(org-speed-command-default-hook org-babel-speed-command-hook)
16920 "Hook for activating speed commands at strategic locations.
16921 Hook functions are called in sequence until a valid handler is
16922 found.
16924 Each hook takes a single argument, a user-pressed command key
16925 which is also a `self-insert-command' from the global map.
16927 Within the hook, examine the cursor position and the command key
16928 and return nil or a valid handler as appropriate. Handler could
16929 be one of an interactive command, a function, or a form.
16931 Set `org-use-speed-commands' to non-nil value to enable this
16932 hook. The default setting is `org-speed-command-default-hook'."
16933 :group 'org-structure
16934 :type 'hook)
16936 (defun org-self-insert-command (N)
16937 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16938 If the cursor is in a table looking at whitespace, the whitespace is
16939 overwritten, and the table is not marked as requiring realignment."
16940 (interactive "p")
16941 (cond
16942 ((and org-use-speed-commands
16943 (setq org-speed-command
16944 (run-hook-with-args-until-success
16945 'org-speed-command-hook (this-command-keys))))
16946 (cond
16947 ((commandp org-speed-command)
16948 (setq this-command org-speed-command)
16949 (call-interactively org-speed-command))
16950 ((functionp org-speed-command)
16951 (funcall org-speed-command))
16952 ((and org-speed-command (listp org-speed-command))
16953 (eval org-speed-command))
16954 (t (let (org-use-speed-commands)
16955 (call-interactively 'org-self-insert-command)))))
16956 ((and
16957 (org-table-p)
16958 (progn
16959 ;; check if we blank the field, and if that triggers align
16960 (and (featurep 'org-table) org-table-auto-blank-field
16961 (member last-command
16962 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16963 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16964 ;; got extra space, this field does not determine column width
16965 (let (org-table-may-need-update) (org-table-blank-field))
16966 ;; no extra space, this field may determine column width
16967 (org-table-blank-field)))
16969 (eq N 1)
16970 (looking-at "[^|\n]* |"))
16971 (let (org-table-may-need-update)
16972 (goto-char (1- (match-end 0)))
16973 (delete-char -1)
16974 (goto-char (match-beginning 0))
16975 (self-insert-command N)))
16977 (setq org-table-may-need-update t)
16978 (self-insert-command N)
16979 (org-fix-tags-on-the-fly)
16980 (if org-self-insert-cluster-for-undo
16981 (if (not (eq last-command 'org-self-insert-command))
16982 (setq org-self-insert-command-undo-counter 1)
16983 (if (>= org-self-insert-command-undo-counter 20)
16984 (setq org-self-insert-command-undo-counter 1)
16985 (and (> org-self-insert-command-undo-counter 0)
16986 buffer-undo-list (listp buffer-undo-list)
16987 (not (cadr buffer-undo-list)) ; remove nil entry
16988 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16989 (setq org-self-insert-command-undo-counter
16990 (1+ org-self-insert-command-undo-counter))))))))
16992 (defun org-fix-tags-on-the-fly ()
16993 (when (and (equal (char-after (point-at-bol)) ?*)
16994 (org-on-heading-p))
16995 (org-align-tags-here org-tags-column)))
16997 (defun org-delete-backward-char (N)
16998 "Like `delete-backward-char', insert whitespace at field end in tables.
16999 When deleting backwards, in tables this function will insert whitespace in
17000 front of the next \"|\" separator, to keep the table aligned. The table will
17001 still be marked for re-alignment if the field did fill the entire column,
17002 because, in this case the deletion might narrow the column."
17003 (interactive "p")
17004 (if (and (org-table-p)
17005 (eq N 1)
17006 (string-match "|" (buffer-substring (point-at-bol) (point)))
17007 (looking-at ".*?|"))
17008 (let ((pos (point))
17009 (noalign (looking-at "[^|\n\r]* |"))
17010 (c org-table-may-need-update))
17011 (backward-delete-char N)
17012 (if (not overwrite-mode)
17013 (progn
17014 (skip-chars-forward "^|")
17015 (insert " ")
17016 (goto-char (1- pos))))
17017 ;; noalign: if there were two spaces at the end, this field
17018 ;; does not determine the width of the column.
17019 (if noalign (setq org-table-may-need-update c)))
17020 (backward-delete-char N)
17021 (org-fix-tags-on-the-fly)))
17023 (defun org-delete-char (N)
17024 "Like `delete-char', but insert whitespace at field end in tables.
17025 When deleting characters, in tables this function will insert whitespace in
17026 front of the next \"|\" separator, to keep the table aligned. The table will
17027 still be marked for re-alignment if the field did fill the entire column,
17028 because, in this case the deletion might narrow the column."
17029 (interactive "p")
17030 (if (and (org-table-p)
17031 (not (bolp))
17032 (not (= (char-after) ?|))
17033 (eq N 1))
17034 (if (looking-at ".*?|")
17035 (let ((pos (point))
17036 (noalign (looking-at "[^|\n\r]* |"))
17037 (c org-table-may-need-update))
17038 (replace-match (concat
17039 (substring (match-string 0) 1 -1)
17040 " |"))
17041 (goto-char pos)
17042 ;; noalign: if there were two spaces at the end, this field
17043 ;; does not determine the width of the column.
17044 (if noalign (setq org-table-may-need-update c)))
17045 (delete-char N))
17046 (delete-char N)
17047 (org-fix-tags-on-the-fly)))
17049 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17050 (put 'org-self-insert-command 'delete-selection t)
17051 (put 'orgtbl-self-insert-command 'delete-selection t)
17052 (put 'org-delete-char 'delete-selection 'supersede)
17053 (put 'org-delete-backward-char 'delete-selection 'supersede)
17054 (put 'org-yank 'delete-selection 'yank)
17056 ;; Make `flyspell-mode' delay after some commands
17057 (put 'org-self-insert-command 'flyspell-delayed t)
17058 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17059 (put 'org-delete-char 'flyspell-delayed t)
17060 (put 'org-delete-backward-char 'flyspell-delayed t)
17062 ;; Make pabbrev-mode expand after org-mode commands
17063 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17064 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17066 ;; How to do this: Measure non-white length of current string
17067 ;; If equal to column width, we should realign.
17069 (defun org-remap (map &rest commands)
17070 "In MAP, remap the functions given in COMMANDS.
17071 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17072 (let (new old)
17073 (while commands
17074 (setq old (pop commands) new (pop commands))
17075 (if (fboundp 'command-remapping)
17076 (org-defkey map (vector 'remap old) new)
17077 (substitute-key-definition old new map global-map)))))
17079 (when (eq org-enable-table-editor 'optimized)
17080 ;; If the user wants maximum table support, we need to hijack
17081 ;; some standard editing functions
17082 (org-remap org-mode-map
17083 'self-insert-command 'org-self-insert-command
17084 'delete-char 'org-delete-char
17085 'delete-backward-char 'org-delete-backward-char)
17086 (org-defkey org-mode-map "|" 'org-force-self-insert))
17088 (defvar org-ctrl-c-ctrl-c-hook nil
17089 "Hook for functions attaching themselves to `C-c C-c'.
17090 This can be used to add additional functionality to the C-c C-c key which
17091 executes context-dependent commands.
17092 Each function will be called with no arguments. The function must check
17093 if the context is appropriate for it to act. If yes, it should do its
17094 thing and then return a non-nil value. If the context is wrong,
17095 just do nothing and return nil.")
17097 (defvar org-tab-first-hook nil
17098 "Hook for functions to attach themselves to TAB.
17099 See `org-ctrl-c-ctrl-c-hook' for more information.
17100 This hook runs as the first action when TAB is pressed, even before
17101 `org-cycle' messes around with the `outline-regexp' to cater for
17102 inline tasks and plain list item folding.
17103 If any function in this hook returns t, any other actions that
17104 would have been caused by TAB (such as table field motion or visibility
17105 cycling) will not occur.")
17107 (defvar org-tab-after-check-for-table-hook nil
17108 "Hook for functions to attach themselves to TAB.
17109 See `org-ctrl-c-ctrl-c-hook' for more information.
17110 This hook runs after it has been established that the cursor is not in a
17111 table, but before checking if the cursor is in a headline or if global cycling
17112 should be done.
17113 If any function in this hook returns t, not other actions like visibility
17114 cycling will be done.")
17116 (defvar org-tab-after-check-for-cycling-hook nil
17117 "Hook for functions to attach themselves to TAB.
17118 See `org-ctrl-c-ctrl-c-hook' for more information.
17119 This hook runs after it has been established that not table field motion and
17120 not visibility should be done because of current context. This is probably
17121 the place where a package like yasnippets can hook in.")
17123 (defvar org-tab-before-tab-emulation-hook nil
17124 "Hook for functions to attach themselves to TAB.
17125 See `org-ctrl-c-ctrl-c-hook' for more information.
17126 This hook runs after every other options for TAB have been exhausted, but
17127 before indentation and \t insertion takes place.")
17129 (defvar org-metaleft-hook nil
17130 "Hook for functions attaching themselves to `M-left'.
17131 See `org-ctrl-c-ctrl-c-hook' for more information.")
17132 (defvar org-metaright-hook nil
17133 "Hook for functions attaching themselves to `M-right'.
17134 See `org-ctrl-c-ctrl-c-hook' for more information.")
17135 (defvar org-metaup-hook nil
17136 "Hook for functions attaching themselves to `M-up'.
17137 See `org-ctrl-c-ctrl-c-hook' for more information.")
17138 (defvar org-metadown-hook nil
17139 "Hook for functions attaching themselves to `M-down'.
17140 See `org-ctrl-c-ctrl-c-hook' for more information.")
17141 (defvar org-shiftmetaleft-hook nil
17142 "Hook for functions attaching themselves to `M-S-left'.
17143 See `org-ctrl-c-ctrl-c-hook' for more information.")
17144 (defvar org-shiftmetaright-hook nil
17145 "Hook for functions attaching themselves to `M-S-right'.
17146 See `org-ctrl-c-ctrl-c-hook' for more information.")
17147 (defvar org-shiftmetaup-hook nil
17148 "Hook for functions attaching themselves to `M-S-up'.
17149 See `org-ctrl-c-ctrl-c-hook' for more information.")
17150 (defvar org-shiftmetadown-hook nil
17151 "Hook for functions attaching themselves to `M-S-down'.
17152 See `org-ctrl-c-ctrl-c-hook' for more information.")
17153 (defvar org-metareturn-hook nil
17154 "Hook for functions attaching themselves to `M-RET'.
17155 See `org-ctrl-c-ctrl-c-hook' for more information.")
17156 (defvar org-shiftup-hook nil
17157 "Hook for functions attaching themselves to `S-up'.
17158 See `org-ctrl-c-ctrl-c-hook' for more information.")
17159 (defvar org-shiftup-final-hook nil
17160 "Hook for functions attaching themselves to `S-up'.
17161 This one runs after all other options except shift-select have been excluded.
17162 See `org-ctrl-c-ctrl-c-hook' for more information.")
17163 (defvar org-shiftdown-hook nil
17164 "Hook for functions attaching themselves to `S-down'.
17165 See `org-ctrl-c-ctrl-c-hook' for more information.")
17166 (defvar org-shiftdown-final-hook nil
17167 "Hook for functions attaching themselves to `S-down'.
17168 This one runs after all other options except shift-select have been excluded.
17169 See `org-ctrl-c-ctrl-c-hook' for more information.")
17170 (defvar org-shiftleft-hook nil
17171 "Hook for functions attaching themselves to `S-left'.
17172 See `org-ctrl-c-ctrl-c-hook' for more information.")
17173 (defvar org-shiftleft-final-hook nil
17174 "Hook for functions attaching themselves to `S-left'.
17175 This one runs after all other options except shift-select have been excluded.
17176 See `org-ctrl-c-ctrl-c-hook' for more information.")
17177 (defvar org-shiftright-hook nil
17178 "Hook for functions attaching themselves to `S-right'.
17179 See `org-ctrl-c-ctrl-c-hook' for more information.")
17180 (defvar org-shiftright-final-hook nil
17181 "Hook for functions attaching themselves to `S-right'.
17182 This one runs after all other options except shift-select have been excluded.
17183 See `org-ctrl-c-ctrl-c-hook' for more information.")
17185 (defun org-modifier-cursor-error ()
17186 "Throw an error, a modified cursor command was applied in wrong context."
17187 (error "This command is active in special context like tables, headlines or items"))
17189 (defun org-shiftselect-error ()
17190 "Throw an error because Shift-Cursor command was applied in wrong context."
17191 (if (and (boundp 'shift-select-mode) shift-select-mode)
17192 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17193 (error "This command works only in special context like headlines or timestamps")))
17195 (defun org-call-for-shift-select (cmd)
17196 (let ((this-command-keys-shift-translated t))
17197 (call-interactively cmd)))
17199 (defun org-shifttab (&optional arg)
17200 "Global visibility cycling or move to previous table field.
17201 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17202 on context.
17203 See the individual commands for more information."
17204 (interactive "P")
17205 (cond
17206 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17207 ((integerp arg)
17208 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17209 (message "Content view to level: %d" arg)
17210 (org-content (prefix-numeric-value arg2))
17211 (setq org-cycle-global-status 'overview)))
17212 (t (call-interactively 'org-global-cycle))))
17214 (defun org-shiftmetaleft ()
17215 "Promote subtree or delete table column.
17216 Calls `org-promote-subtree', `org-outdent-item',
17217 or `org-table-delete-column', depending on context.
17218 See the individual commands for more information."
17219 (interactive)
17220 (cond
17221 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17222 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17223 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17224 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17225 (t (org-modifier-cursor-error))))
17227 (defun org-shiftmetaright ()
17228 "Demote subtree or insert table column.
17229 Calls `org-demote-subtree', `org-indent-item',
17230 or `org-table-insert-column', depending on context.
17231 See the individual commands for more information."
17232 (interactive)
17233 (cond
17234 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17235 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17236 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17237 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17238 (t (org-modifier-cursor-error))))
17240 (defun org-shiftmetaup (&optional arg)
17241 "Move subtree up or kill table row.
17242 Calls `org-move-subtree-up' or `org-table-kill-row' or
17243 `org-move-item-up' depending on context. See the individual commands
17244 for more information."
17245 (interactive "P")
17246 (cond
17247 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17248 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17249 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17250 ((org-at-item-p) (call-interactively 'org-move-item-up))
17251 (t (org-modifier-cursor-error))))
17253 (defun org-shiftmetadown (&optional arg)
17254 "Move subtree down or insert table row.
17255 Calls `org-move-subtree-down' or `org-table-insert-row' or
17256 `org-move-item-down', depending on context. See the individual
17257 commands for more information."
17258 (interactive "P")
17259 (cond
17260 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17261 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17262 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17263 ((org-at-item-p) (call-interactively 'org-move-item-down))
17264 (t (org-modifier-cursor-error))))
17266 (defsubst org-hidden-tree-error ()
17267 (error
17268 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17270 (defun org-metaleft (&optional arg)
17271 "Promote heading or move table column to left.
17272 Calls `org-do-promote' or `org-table-move-column', depending on context.
17273 With no specific context, calls the Emacs default `backward-word'.
17274 See the individual commands for more information."
17275 (interactive "P")
17276 (cond
17277 ((run-hook-with-args-until-success 'org-metaleft-hook))
17278 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17279 ((org-with-limited-levels
17280 (or (org-on-heading-p)
17281 (and (org-region-active-p)
17282 (save-excursion
17283 (goto-char (region-beginning))
17284 (org-on-heading-p)))))
17285 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17286 (call-interactively 'org-do-promote))
17287 ;; At an inline task.
17288 ((org-on-heading-p)
17289 (call-interactively 'org-inlinetask-promote))
17290 ((or (org-at-item-p)
17291 (and (org-region-active-p)
17292 (save-excursion
17293 (goto-char (region-beginning))
17294 (org-at-item-p))))
17295 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17296 (call-interactively 'org-outdent-item))
17297 (t (call-interactively 'backward-word))))
17299 (defun org-metaright (&optional arg)
17300 "Demote subtree or move table column to right.
17301 Calls `org-do-demote' or `org-table-move-column', depending on context.
17302 With no specific context, calls the Emacs default `forward-word'.
17303 See the individual commands for more information."
17304 (interactive "P")
17305 (cond
17306 ((run-hook-with-args-until-success 'org-metaright-hook))
17307 ((org-at-table-p) (call-interactively 'org-table-move-column))
17308 ((org-with-limited-levels
17309 (or (org-on-heading-p)
17310 (and (org-region-active-p)
17311 (save-excursion
17312 (goto-char (region-beginning))
17313 (org-on-heading-p)))))
17314 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17315 (call-interactively 'org-do-demote))
17316 ;; At an inline task.
17317 ((org-on-heading-p)
17318 (call-interactively 'org-inlinetask-demote))
17319 ((or (org-at-item-p)
17320 (and (org-region-active-p)
17321 (save-excursion
17322 (goto-char (region-beginning))
17323 (org-at-item-p))))
17324 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17325 (call-interactively 'org-indent-item))
17326 (t (call-interactively 'forward-word))))
17328 (defun org-check-for-hidden (what)
17329 "Check if there are hidden headlines/items in the current visual line.
17330 WHAT can be either `headlines' or `items'. If the current line is
17331 an outline or item heading and it has a folded subtree below it,
17332 this function returns t, nil otherwise."
17333 (let ((re (cond
17334 ((eq what 'headlines) (concat "^" org-outline-regexp))
17335 ((eq what 'items) (org-item-beginning-re))
17336 (t (error "This should not happen"))))
17337 beg end)
17338 (save-excursion
17339 (catch 'exit
17340 (unless (org-region-active-p)
17341 (setq beg (point-at-bol))
17342 (beginning-of-line 2)
17343 (while (and (not (eobp)) ;; this is like `next-line'
17344 (get-char-property (1- (point)) 'invisible))
17345 (beginning-of-line 2))
17346 (setq end (point))
17347 (goto-char beg)
17348 (goto-char (point-at-eol))
17349 (setq end (max end (point)))
17350 (while (re-search-forward re end t)
17351 (if (get-char-property (match-beginning 0) 'invisible)
17352 (throw 'exit t))))
17353 nil))))
17355 (defun org-metaup (&optional arg)
17356 "Move subtree up or move table row up.
17357 Calls `org-move-subtree-up' or `org-table-move-row' or
17358 `org-move-item-up', depending on context. See the individual commands
17359 for more information."
17360 (interactive "P")
17361 (cond
17362 ((run-hook-with-args-until-success 'org-metaup-hook))
17363 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17364 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17365 ((org-at-item-p) (call-interactively 'org-move-item-up))
17366 (t (transpose-lines 1) (beginning-of-line -1))))
17368 (defun org-metadown (&optional arg)
17369 "Move subtree down or move table row down.
17370 Calls `org-move-subtree-down' or `org-table-move-row' or
17371 `org-move-item-down', depending on context. See the individual
17372 commands for more information."
17373 (interactive "P")
17374 (cond
17375 ((run-hook-with-args-until-success 'org-metadown-hook))
17376 ((org-at-table-p) (call-interactively 'org-table-move-row))
17377 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17378 ((org-at-item-p) (call-interactively 'org-move-item-down))
17379 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17381 (defun org-shiftup (&optional arg)
17382 "Increase item in timestamp or increase priority of current headline.
17383 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17384 depending on context. See the individual commands for more information."
17385 (interactive "P")
17386 (cond
17387 ((run-hook-with-args-until-success 'org-shiftup-hook))
17388 ((and org-support-shift-select (org-region-active-p))
17389 (org-call-for-shift-select 'previous-line))
17390 ((org-at-timestamp-p t)
17391 (call-interactively (if org-edit-timestamp-down-means-later
17392 'org-timestamp-down 'org-timestamp-up)))
17393 ((and (not (eq org-support-shift-select 'always))
17394 org-enable-priority-commands
17395 (org-on-heading-p))
17396 (call-interactively 'org-priority-up))
17397 ((and (not org-support-shift-select) (org-at-item-p))
17398 (call-interactively 'org-previous-item))
17399 ((org-clocktable-try-shift 'up arg))
17400 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17401 (org-support-shift-select
17402 (org-call-for-shift-select 'previous-line))
17403 (t (org-shiftselect-error))))
17405 (defun org-shiftdown (&optional arg)
17406 "Decrease item in timestamp or decrease priority of current headline.
17407 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17408 depending on context. See the individual commands for more information."
17409 (interactive "P")
17410 (cond
17411 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17412 ((and org-support-shift-select (org-region-active-p))
17413 (org-call-for-shift-select 'next-line))
17414 ((org-at-timestamp-p t)
17415 (call-interactively (if org-edit-timestamp-down-means-later
17416 'org-timestamp-up 'org-timestamp-down)))
17417 ((and (not (eq org-support-shift-select 'always))
17418 org-enable-priority-commands
17419 (org-on-heading-p))
17420 (call-interactively 'org-priority-down))
17421 ((and (not org-support-shift-select) (org-at-item-p))
17422 (call-interactively 'org-next-item))
17423 ((org-clocktable-try-shift 'down arg))
17424 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17425 (org-support-shift-select
17426 (org-call-for-shift-select 'next-line))
17427 (t (org-shiftselect-error))))
17429 (defun org-shiftright (&optional arg)
17430 "Cycle the thing at point or in the current line, depending on context.
17431 Depending on context, this does one of the following:
17433 - switch a timestamp at point one day into the future
17434 - on a headline, switch to the next TODO keyword.
17435 - on an item, switch entire list to the next bullet type
17436 - on a property line, switch to the next allowed value
17437 - on a clocktable definition line, move time block into the future"
17438 (interactive "P")
17439 (cond
17440 ((run-hook-with-args-until-success 'org-shiftright-hook))
17441 ((and org-support-shift-select (org-region-active-p))
17442 (org-call-for-shift-select 'forward-char))
17443 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17444 ((and (not (eq org-support-shift-select 'always))
17445 (org-on-heading-p))
17446 (let ((org-inhibit-logging
17447 (not org-treat-S-cursor-todo-selection-as-state-change))
17448 (org-inhibit-blocking
17449 (not org-treat-S-cursor-todo-selection-as-state-change)))
17450 (org-call-with-arg 'org-todo 'right)))
17451 ((or (and org-support-shift-select
17452 (not (eq org-support-shift-select 'always))
17453 (org-at-item-bullet-p))
17454 (and (not org-support-shift-select) (org-at-item-p)))
17455 (org-call-with-arg 'org-cycle-list-bullet nil))
17456 ((and (not (eq org-support-shift-select 'always))
17457 (org-at-property-p))
17458 (call-interactively 'org-property-next-allowed-value))
17459 ((org-clocktable-try-shift 'right arg))
17460 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17461 (org-support-shift-select
17462 (org-call-for-shift-select 'forward-char))
17463 (t (org-shiftselect-error))))
17465 (defun org-shiftleft (&optional arg)
17466 "Cycle the thing at point or in the current line, depending on context.
17467 Depending on context, this does one of the following:
17469 - switch a timestamp at point one day into the past
17470 - on a headline, switch to the previous TODO keyword.
17471 - on an item, switch entire list to the previous bullet type
17472 - on a property line, switch to the previous allowed value
17473 - on a clocktable definition line, move time block into the past"
17474 (interactive "P")
17475 (cond
17476 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17477 ((and org-support-shift-select (org-region-active-p))
17478 (org-call-for-shift-select 'backward-char))
17479 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17480 ((and (not (eq org-support-shift-select 'always))
17481 (org-on-heading-p))
17482 (let ((org-inhibit-logging
17483 (not org-treat-S-cursor-todo-selection-as-state-change))
17484 (org-inhibit-blocking
17485 (not org-treat-S-cursor-todo-selection-as-state-change)))
17486 (org-call-with-arg 'org-todo 'left)))
17487 ((or (and org-support-shift-select
17488 (not (eq org-support-shift-select 'always))
17489 (org-at-item-bullet-p))
17490 (and (not org-support-shift-select) (org-at-item-p)))
17491 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17492 ((and (not (eq org-support-shift-select 'always))
17493 (org-at-property-p))
17494 (call-interactively 'org-property-previous-allowed-value))
17495 ((org-clocktable-try-shift 'left arg))
17496 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17497 (org-support-shift-select
17498 (org-call-for-shift-select 'backward-char))
17499 (t (org-shiftselect-error))))
17501 (defun org-shiftcontrolright ()
17502 "Switch to next TODO set."
17503 (interactive)
17504 (cond
17505 ((and org-support-shift-select (org-region-active-p))
17506 (org-call-for-shift-select 'forward-word))
17507 ((and (not (eq org-support-shift-select 'always))
17508 (org-on-heading-p))
17509 (org-call-with-arg 'org-todo 'nextset))
17510 (org-support-shift-select
17511 (org-call-for-shift-select 'forward-word))
17512 (t (org-shiftselect-error))))
17514 (defun org-shiftcontrolleft ()
17515 "Switch to previous TODO set."
17516 (interactive)
17517 (cond
17518 ((and org-support-shift-select (org-region-active-p))
17519 (org-call-for-shift-select 'backward-word))
17520 ((and (not (eq org-support-shift-select 'always))
17521 (org-on-heading-p))
17522 (org-call-with-arg 'org-todo 'previousset))
17523 (org-support-shift-select
17524 (org-call-for-shift-select 'backward-word))
17525 (t (org-shiftselect-error))))
17527 (defun org-ctrl-c-ret ()
17528 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17529 (interactive)
17530 (cond
17531 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17532 (t (call-interactively 'org-insert-heading))))
17534 (defun org-copy-special ()
17535 "Copy region in table or copy current subtree.
17536 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17537 See the individual commands for more information."
17538 (interactive)
17539 (call-interactively
17540 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17542 (defun org-cut-special ()
17543 "Cut region in table or cut current subtree.
17544 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17545 See the individual commands for more information."
17546 (interactive)
17547 (call-interactively
17548 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17550 (defun org-paste-special (arg)
17551 "Paste rectangular region into table, or past subtree relative to level.
17552 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17553 See the individual commands for more information."
17554 (interactive "P")
17555 (if (org-at-table-p)
17556 (org-table-paste-rectangle)
17557 (org-paste-subtree arg)))
17559 (defun org-edit-special (&optional arg)
17560 "Call a special editor for the stuff at point.
17561 When at a table, call the formula editor with `org-table-edit-formulas'.
17562 When at the first line of an src example, call `org-edit-src-code'.
17563 When in an #+include line, visit the include file. Otherwise call
17564 `ffap' to visit the file at point."
17565 (interactive)
17566 ;; possibly prep session before editing source
17567 (when arg
17568 (let* ((info (org-babel-get-src-block-info))
17569 (lang (nth 0 info))
17570 (params (nth 2 info))
17571 (session (cdr (assoc :session params))))
17572 (when (and info session) ;; we are in a source-code block with a session
17573 (funcall
17574 (intern (concat "org-babel-prep-session:" lang)) session params))))
17575 (cond ;; proceed with `org-edit-special'
17576 ((save-excursion
17577 (beginning-of-line 1)
17578 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17579 (find-file (org-trim (match-string 1))))
17580 ((org-edit-src-code))
17581 ((org-edit-fixed-width-region))
17582 ((org-at-table.el-p)
17583 (org-edit-src-code))
17584 ((or (org-at-table-p)
17585 (save-excursion
17586 (beginning-of-line 1)
17587 (looking-at "[ \t]*#\\+TBLFM:")))
17588 (call-interactively 'org-table-edit-formulas))
17589 (t (call-interactively 'ffap))))
17591 (defun org-ctrl-c-ctrl-c (&optional arg)
17592 "Set tags in headline, or update according to changed information at point.
17594 This command does many different things, depending on context:
17596 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17597 this is what we do.
17599 - If the cursor is on a statistics cookie, update it.
17601 - If the cursor is in a headline, prompt for tags and insert them
17602 into the current line, aligned to `org-tags-column'. When called
17603 with prefix arg, realign all tags in the current buffer.
17605 - If the cursor is in one of the special #+KEYWORD lines, this
17606 triggers scanning the buffer for these lines and updating the
17607 information.
17609 - If the cursor is inside a table, realign the table. This command
17610 works even if the automatic table editor has been turned off.
17612 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17613 the entire table.
17615 - If the cursor is at a footnote reference or definition, jump to
17616 the corresponding definition or references, respectively.
17618 - If the cursor is a the beginning of a dynamic block, update it.
17620 - If the current buffer is a capture buffer, close note and file it.
17622 - If the cursor is on a <<<target>>>, update radio targets and
17623 corresponding links in this buffer.
17625 - If the cursor is on a numbered item in a plain list, renumber the
17626 ordered list.
17628 - If the cursor is on a checkbox, toggle it.
17630 - If the cursor is on a code block, evaluate it. The variable
17631 `org-confirm-babel-evaluate' can be used to control prompting
17632 before code block evaluation, by default every code block
17633 evaluation requires confirmation. Code block evaluation can be
17634 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17635 (interactive "P")
17636 (let ((org-enable-table-editor t))
17637 (cond
17638 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17639 org-occur-highlights
17640 org-latex-fragment-image-overlays)
17641 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17642 (org-remove-occur-highlights)
17643 (org-remove-latex-fragment-image-overlays)
17644 (message "Temporary highlights/overlays removed from current buffer"))
17645 ((and (local-variable-p 'org-finish-function (current-buffer))
17646 (fboundp org-finish-function))
17647 (funcall org-finish-function))
17648 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17649 ((or (looking-at org-property-start-re)
17650 (org-at-property-p))
17651 (call-interactively 'org-property-action))
17652 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17653 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17654 (or (org-on-heading-p) (org-at-item-p)))
17655 (call-interactively 'org-update-statistics-cookies))
17656 ((org-on-heading-p) (call-interactively 'org-set-tags))
17657 ((org-at-table.el-p)
17658 (message "Use C-c ' to edit table.el tables"))
17659 ((org-at-table-p)
17660 (org-table-maybe-eval-formula)
17661 (if arg
17662 (call-interactively 'org-table-recalculate)
17663 (org-table-maybe-recalculate-line))
17664 (call-interactively 'org-table-align)
17665 (orgtbl-send-table 'maybe))
17666 ((or (org-footnote-at-reference-p)
17667 (org-footnote-at-definition-p))
17668 (call-interactively 'org-footnote-action))
17669 ((org-at-item-checkbox-p)
17670 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17671 ;; list only if at top item.
17672 (let* ((cbox (match-string 1))
17673 (struct (org-list-struct))
17674 (old-struct (copy-tree struct))
17675 (parents (org-list-parents-alist struct))
17676 (prevs (org-list-prevs-alist struct))
17677 (orderedp (org-entry-get nil "ORDERED"))
17678 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17679 block-item)
17680 ;; Use a light version of `org-toggle-checkbox' to avoid
17681 ;; computing list structure twice.
17682 (org-list-set-checkbox (point-at-bol) struct
17683 (cond
17684 ((equal arg '(16)) "[-]")
17685 ((equal arg '(4)) nil)
17686 ((equal "[X]" cbox) "[ ]")
17687 (t "[X]")))
17688 (org-list-struct-fix-ind struct parents)
17689 (org-list-struct-fix-bul struct prevs)
17690 (setq block-item
17691 (org-list-struct-fix-box struct parents prevs orderedp))
17692 (when block-item
17693 (message
17694 "Checkboxes were removed due to unchecked box at line %d"
17695 (org-current-line block-item)))
17696 (org-list-struct-apply-struct struct old-struct)
17697 (org-update-checkbox-count-maybe)
17698 (when firstp (org-list-send-list 'maybe))))
17699 ((org-at-item-p)
17700 ;; Cursor at an item: repair list. Do checkbox related actions
17701 ;; only if function was called with an argument. Send list only
17702 ;; if at top item.
17703 (let* ((struct (org-list-struct))
17704 (old-struct (copy-tree struct))
17705 (parents (org-list-parents-alist struct))
17706 (prevs (org-list-prevs-alist struct))
17707 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17708 (org-list-struct-fix-ind struct parents)
17709 (org-list-struct-fix-bul struct prevs)
17710 (when arg
17711 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17712 (org-list-struct-fix-box struct parents prevs))
17713 (org-list-struct-apply-struct struct old-struct)
17714 (when arg (org-update-checkbox-count-maybe))
17715 (when firstp (org-list-send-list 'maybe))))
17716 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17717 ;; Dynamic block
17718 (beginning-of-line 1)
17719 (save-excursion (org-update-dblock)))
17720 ((save-excursion
17721 (beginning-of-line 1)
17722 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17723 (cond
17724 ((equal (match-string 1) "TBLFM")
17725 ;; Recalculate the table before this line
17726 (save-excursion
17727 (beginning-of-line 1)
17728 (skip-chars-backward " \r\n\t")
17729 (if (org-at-table-p)
17730 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17732 (let ((org-inhibit-startup-visibility-stuff t)
17733 (org-startup-align-all-tables nil))
17734 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17735 (message "Local setup has been refreshed"))))
17736 ((org-clock-update-time-maybe))
17737 (t (error "C-c C-c can do nothing useful at this location")))))
17739 (defun org-mode-restart ()
17740 "Restart Org-mode, to scan again for special lines.
17741 Also updates the keyword regular expressions."
17742 (interactive)
17743 (org-mode)
17744 (message "Org-mode restarted"))
17746 (defun org-kill-note-or-show-branches ()
17747 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17748 (interactive)
17749 (if (not org-finish-function)
17750 (progn
17751 (hide-subtree)
17752 (call-interactively 'show-branches))
17753 (let ((org-note-abort t))
17754 (funcall org-finish-function))))
17756 (defun org-return (&optional indent)
17757 "Goto next table row or insert a newline.
17758 Calls `org-table-next-row' or `newline', depending on context.
17759 See the individual commands for more information."
17760 (interactive)
17761 (cond
17762 ((bobp) (if indent (newline-and-indent) (newline)))
17763 ((org-at-table-p)
17764 (org-table-justify-field-maybe)
17765 (call-interactively 'org-table-next-row))
17766 ;; when `newline-and-indent' is called within a list, make sure
17767 ;; text moved stays inside the item.
17768 ((and (org-in-item-p) indent)
17769 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17770 (progn
17771 (newline)
17772 (org-indent-line-to (length (match-string 0))))
17773 (let ((ind (org-get-indentation)))
17774 (newline)
17775 (if (org-looking-back org-list-end-re)
17776 (org-indent-line-function)
17777 (org-indent-line-to ind)))))
17778 ((and org-return-follows-link
17779 (eq (get-text-property (point) 'face) 'org-link))
17780 (call-interactively 'org-open-at-point))
17781 ((and (org-at-heading-p)
17782 (looking-at
17783 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17784 (org-show-entry)
17785 (end-of-line 1)
17786 (newline))
17787 (t (if indent (newline-and-indent) (newline)))))
17789 (defun org-return-indent ()
17790 "Goto next table row or insert a newline and indent.
17791 Calls `org-table-next-row' or `newline-and-indent', depending on
17792 context. See the individual commands for more information."
17793 (interactive)
17794 (org-return t))
17796 (defun org-ctrl-c-star ()
17797 "Compute table, or change heading status of lines.
17798 Calls `org-table-recalculate' or `org-toggle-heading',
17799 depending on context."
17800 (interactive)
17801 (cond
17802 ((org-at-table-p)
17803 (call-interactively 'org-table-recalculate))
17805 ;; Convert all lines in region to list items
17806 (call-interactively 'org-toggle-heading))))
17808 (defun org-ctrl-c-minus ()
17809 "Insert separator line in table or modify bullet status of line.
17810 Also turns a plain line or a region of lines into list items.
17811 Calls `org-table-insert-hline', `org-toggle-item', or
17812 `org-cycle-list-bullet', depending on context."
17813 (interactive)
17814 (cond
17815 ((org-at-table-p)
17816 (call-interactively 'org-table-insert-hline))
17817 ((org-region-active-p)
17818 (call-interactively 'org-toggle-item))
17819 ((org-in-item-p)
17820 (call-interactively 'org-cycle-list-bullet))
17822 (call-interactively 'org-toggle-item))))
17824 (defun org-toggle-item (arg)
17825 "Convert headings or normal lines to items, items to normal lines.
17826 If there is no active region, only the current line is considered.
17828 If the first non blank line in the region is an headline, convert
17829 all headlines to items, shifting text accordingly.
17831 If it is an item, convert all items to normal lines.
17833 If it is normal text, change region into an item. With a prefix
17834 argument ARG, change each line in region into an item."
17835 (interactive "P")
17836 (let ((shift-text
17837 (function
17838 ;; Shift text in current section to IND, from point to END.
17839 ;; The function leaves point to END line.
17840 (lambda (ind end)
17841 (let ((min-i 1000) (end (copy-marker end)))
17842 ;; First determine the minimum indentation (MIN-I) of
17843 ;; the text.
17844 (save-excursion
17845 (catch 'exit
17846 (while (< (point) end)
17847 (let ((i (org-get-indentation)))
17848 (cond
17849 ;; Skip blank lines and inline tasks.
17850 ((looking-at "^[ \t]*$"))
17851 ((looking-at "^\\*+ "))
17852 ;; We can't find less than 0 indentation.
17853 ((zerop i) (throw 'exit (setq min-i 0)))
17854 ((< i min-i) (setq min-i i))))
17855 (forward-line))))
17856 ;; Then indent each line so that a line indented to
17857 ;; MIN-I becomes indented to IND. Ignore blank lines
17858 ;; and inline tasks in the process.
17859 (let ((delta (- ind min-i)))
17860 (while (< (point) end)
17861 (unless (or (looking-at "^[ \t]*$")
17862 (looking-at "^\\*+ "))
17863 (org-indent-line-to (+ (org-get-indentation) delta)))
17864 (forward-line)))))))
17865 (skip-blanks
17866 (function
17867 ;; Return beginning of first non-blank line, starting from
17868 ;; line at POS.
17869 (lambda (pos)
17870 (save-excursion
17871 (goto-char pos)
17872 (skip-chars-forward " \r\t\n")
17873 (point-at-bol)))))
17874 beg end)
17875 ;; Determine boundaries of changes.
17876 (if (org-region-active-p)
17877 (setq beg (funcall skip-blanks (region-beginning))
17878 end (copy-marker (region-end)))
17879 (setq beg (funcall skip-blanks (point-at-bol))
17880 end (copy-marker (point-at-eol))))
17881 ;; Depending on the starting line, choose an action on the text
17882 ;; between BEG and END.
17883 (org-with-limited-levels
17884 (save-excursion
17885 (goto-char beg)
17886 (cond
17887 ;; Case 1. Start at an item: de-itemize. Note that it only
17888 ;; happens when a region is active: `org-ctrl-c-minus'
17889 ;; would call `org-cycle-list-bullet' otherwise.
17890 ((org-at-item-p)
17891 (while (< (point) end)
17892 (when (org-at-item-p)
17893 (skip-chars-forward " \t")
17894 (delete-region (point) (match-end 0)))
17895 (forward-line)))
17896 ;; Case 2. Start at an heading: convert to items.
17897 ((org-on-heading-p)
17898 (let* ((bul (org-list-bullet-string "-"))
17899 (bul-len (length bul))
17900 ;; Indentation of the first heading. It should be
17901 ;; relative to the indentation of its parent, if any.
17902 (start-ind (save-excursion
17903 (cond
17904 ((not org-adapt-indentation) 0)
17905 ((not (outline-previous-heading)) 0)
17906 (t (length (match-string 0))))))
17907 ;; Level of first heading. Further headings will be
17908 ;; compared to it to determine hierarchy in the list.
17909 (ref-level (org-reduced-level (org-outline-level))))
17910 (while (< (point) end)
17911 (let* ((level (org-reduced-level (org-outline-level)))
17912 (delta (max 0 (- level ref-level))))
17913 ;; If current headline is less indented than the first
17914 ;; one, set it as reference, in order to preserve
17915 ;; subtrees.
17916 (when (< level ref-level) (setq ref-level level))
17917 (replace-match bul t t)
17918 (org-indent-line-to (+ start-ind (* delta bul-len)))
17919 ;; Ensure all text down to END (or SECTION-END) belongs
17920 ;; to the newly created item.
17921 (let ((section-end (save-excursion
17922 (or (outline-next-heading) (point)))))
17923 (forward-line)
17924 (funcall shift-text
17925 (+ start-ind (* (1+ delta) bul-len))
17926 (min end section-end)))))))
17927 ;; Case 3. Normal line with ARG: turn each non-item line into
17928 ;; an item.
17929 (arg
17930 (while (< (point) end)
17931 (unless (or (org-on-heading-p) (org-at-item-p))
17932 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17933 (replace-match
17934 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17935 (forward-line)))
17936 ;; Case 4. Normal line without ARG: make the first line of
17937 ;; region an item, and shift indentation of others
17938 ;; lines to set them as item's body.
17939 (t (let* ((bul (org-list-bullet-string "-"))
17940 (bul-len (length bul))
17941 (ref-ind (org-get-indentation)))
17942 (skip-chars-forward " \t")
17943 (insert bul)
17944 (forward-line)
17945 (while (< (point) end)
17946 ;; Ensure that lines less indented than first one
17947 ;; still get included in item body.
17948 (funcall shift-text
17949 (+ ref-ind bul-len)
17950 (min end (save-excursion (or (outline-next-heading)
17951 (point)))))
17952 (forward-line)))))))))
17954 (defun org-toggle-heading (&optional nstars)
17955 "Convert headings to normal text, or items or text to headings.
17956 If there is no active region, only the current line is considered.
17958 If the first non blank line is an headline, remove the stars from
17959 all headlines in the region.
17961 If it is a plain list item, turn all plain list items into headings.
17963 If it is a normal line, turn each and every normal line (i.e. not
17964 an heading or an item) in the region into a heading.
17966 When converting a line into a heading, the number of stars is chosen
17967 such that the lines become children of the current entry. However,
17968 when a prefix argument is given, its value determines the number of
17969 stars to add."
17970 (interactive "P")
17971 (let ((skip-blanks
17972 (function
17973 ;; Return beginning of first non-blank line, starting from
17974 ;; line at POS.
17975 (lambda (pos)
17976 (save-excursion
17977 (goto-char pos)
17978 (skip-chars-forward " \r\t\n")
17979 (point-at-bol)))))
17980 beg end)
17981 ;; Determine boundaries of changes. If region ends at a bol, do
17982 ;; not consider the last line to be in the region.
17983 (if (org-region-active-p)
17984 (setq beg (funcall skip-blanks (region-beginning))
17985 end (copy-marker (save-excursion
17986 (goto-char (region-end))
17987 (if (bolp) (point) (point-at-eol)))))
17988 (setq beg (funcall skip-blanks (point-at-bol))
17989 end (copy-marker (point-at-eol))))
17990 ;; Ensure inline tasks don't count as headings.
17991 (org-with-limited-levels
17992 (save-excursion
17993 (goto-char beg)
17994 (cond
17995 ;; Case 1. Started at an heading: de-star headings.
17996 ((org-on-heading-p)
17997 (while (< (point) end)
17998 (when (org-on-heading-p t)
17999 (looking-at outline-regexp) (replace-match ""))
18000 (forward-line)))
18001 ;; Case 2. Started at an item: change items into headlines.
18002 ;; One star will be added by `org-list-to-subtree'.
18003 ((org-at-item-p)
18004 (let* ((stars (make-string
18005 (if nstars
18006 ;; subtract the star that will be added again by
18007 ;; `org-list-to-subtree'
18008 (1- (prefix-numeric-value current-prefix-arg))
18009 (or (org-current-level) 0))
18010 ?*))
18011 (add-stars
18012 (cond (nstars "") ; stars from prefix only
18013 ((equal stars "") "") ; before first heading
18014 (org-odd-levels-only "*") ; inside heading, odd
18015 (t "")))) ; inside heading, oddeven
18016 (while (< (point) end)
18017 (when (org-at-item-p)
18018 ;; Pay attention to cases when region ends before list.
18019 (let* ((struct (org-list-struct))
18020 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18021 (save-restriction
18022 (narrow-to-region (point) list-end)
18023 (insert
18024 (org-list-to-subtree
18025 (org-list-parse-list t)
18026 '(:istart (concat stars add-stars (funcall get-stars depth))
18027 :icount (concat stars add-stars (funcall get-stars depth))))))))
18028 (forward-line))))
18029 ;; Case 3. Started at normal text: make every line an heading,
18030 ;; skipping headlines and items.
18031 (t (let* ((stars (make-string
18032 (if nstars
18033 (prefix-numeric-value current-prefix-arg)
18034 (or (org-current-level) 0))
18035 ?*))
18036 (add-stars
18037 (cond (nstars "") ; stars from prefix only
18038 ((equal stars "") "*") ; before first heading
18039 (org-odd-levels-only "**") ; inside heading, odd
18040 (t "*"))) ; inside heading, oddeven
18041 (rpl (concat stars add-stars " ")))
18042 (while (< (point) end)
18043 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18044 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18045 (replace-match (concat rpl (match-string 2))))
18046 (forward-line)))))))))
18048 (defun org-meta-return (&optional arg)
18049 "Insert a new heading or wrap a region in a table.
18050 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18051 See the individual commands for more information."
18052 (interactive "P")
18053 (cond
18054 ((run-hook-with-args-until-success 'org-metareturn-hook))
18055 ((org-at-table-p)
18056 (call-interactively 'org-table-wrap-region))
18057 (t (call-interactively 'org-insert-heading))))
18059 ;;; Menu entries
18061 ;; Define the Org-mode menus
18062 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18063 '("Tbl"
18064 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18065 ["Next Field" org-cycle (org-at-table-p)]
18066 ["Previous Field" org-shifttab (org-at-table-p)]
18067 ["Next Row" org-return (org-at-table-p)]
18068 "--"
18069 ["Blank Field" org-table-blank-field (org-at-table-p)]
18070 ["Edit Field" org-table-edit-field (org-at-table-p)]
18071 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18072 "--"
18073 ("Column"
18074 ["Move Column Left" org-metaleft (org-at-table-p)]
18075 ["Move Column Right" org-metaright (org-at-table-p)]
18076 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18077 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18078 ("Row"
18079 ["Move Row Up" org-metaup (org-at-table-p)]
18080 ["Move Row Down" org-metadown (org-at-table-p)]
18081 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18082 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18083 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18084 "--"
18085 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18086 ("Rectangle"
18087 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18088 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18089 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18090 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18091 "--"
18092 ("Calculate"
18093 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18094 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18095 ["Edit Formulas" org-edit-special (org-at-table-p)]
18096 "--"
18097 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18098 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18099 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18100 "--"
18101 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18102 "--"
18103 ["Sum Column/Rectangle" org-table-sum
18104 (or (org-at-table-p) (org-region-active-p))]
18105 ["Which Column?" org-table-current-column (org-at-table-p)])
18106 ["Debug Formulas"
18107 org-table-toggle-formula-debugger
18108 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18109 ["Show Col/Row Numbers"
18110 org-table-toggle-coordinate-overlays
18111 :style toggle
18112 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18113 "--"
18114 ["Create" org-table-create (and (not (org-at-table-p))
18115 org-enable-table-editor)]
18116 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18117 ["Import from File" org-table-import (not (org-at-table-p))]
18118 ["Export to File" org-table-export (org-at-table-p)]
18119 "--"
18120 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18122 (easy-menu-define org-org-menu org-mode-map "Org menu"
18123 '("Org"
18124 ("Show/Hide"
18125 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18126 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18127 ["Sparse Tree..." org-sparse-tree t]
18128 ["Reveal Context" org-reveal t]
18129 ["Show All" show-all t]
18130 "--"
18131 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18132 "--"
18133 ["New Heading" org-insert-heading t]
18134 ("Navigate Headings"
18135 ["Up" outline-up-heading t]
18136 ["Next" outline-next-visible-heading t]
18137 ["Previous" outline-previous-visible-heading t]
18138 ["Next Same Level" outline-forward-same-level t]
18139 ["Previous Same Level" outline-backward-same-level t]
18140 "--"
18141 ["Jump" org-goto t])
18142 ("Edit Structure"
18143 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18144 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18145 "--"
18146 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18147 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18148 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18149 "--"
18150 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18151 "--"
18152 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18153 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18154 ["Demote Heading" org-metaright (not (org-at-table-p))]
18155 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18156 "--"
18157 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18158 "--"
18159 ["Convert to odd levels" org-convert-to-odd-levels t]
18160 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18161 ("Editing"
18162 ["Emphasis..." org-emphasize t]
18163 ["Edit Source Example" org-edit-special t]
18164 "--"
18165 ["Footnote new/jump" org-footnote-action t]
18166 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18167 ("Archive"
18168 ["Archive (default method)" org-archive-subtree-default t]
18169 "--"
18170 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18171 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18172 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18174 "--"
18175 ("Hyperlinks"
18176 ["Store Link (Global)" org-store-link t]
18177 ["Find existing link to here" org-occur-link-in-agenda-files t]
18178 ["Insert Link" org-insert-link t]
18179 ["Follow Link" org-open-at-point t]
18180 "--"
18181 ["Next link" org-next-link t]
18182 ["Previous link" org-previous-link t]
18183 "--"
18184 ["Descriptive Links"
18185 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18186 :style radio
18187 :selected (member '(org-link) buffer-invisibility-spec)]
18188 ["Literal Links"
18189 (progn
18190 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18191 :style radio
18192 :selected (not (member '(org-link) buffer-invisibility-spec))])
18193 "--"
18194 ("TODO Lists"
18195 ["TODO/DONE/-" org-todo t]
18196 ("Select keyword"
18197 ["Next keyword" org-shiftright (org-on-heading-p)]
18198 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18199 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18200 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18201 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18202 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18203 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18204 "--"
18205 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18206 :selected org-enforce-todo-dependencies :style toggle :active t]
18207 "Settings for tree at point"
18208 ["Do Children sequentially" org-toggle-ordered-property :style radio
18209 :selected (org-entry-get nil "ORDERED")
18210 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18211 ["Do Children parallel" org-toggle-ordered-property :style radio
18212 :selected (not (org-entry-get nil "ORDERED"))
18213 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18214 "--"
18215 ["Set Priority" org-priority t]
18216 ["Priority Up" org-shiftup t]
18217 ["Priority Down" org-shiftdown t]
18218 "--"
18219 ["Get news from all feeds" org-feed-update-all t]
18220 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18221 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18222 ("TAGS and Properties"
18223 ["Set Tags" org-set-tags-command t]
18224 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18225 "--"
18226 ["Set property" org-set-property t]
18227 ["Column view of properties" org-columns t]
18228 ["Insert Column View DBlock" org-insert-columns-dblock t])
18229 ("Dates and Scheduling"
18230 ["Timestamp" org-time-stamp t]
18231 ["Timestamp (inactive)" org-time-stamp-inactive t]
18232 ("Change Date"
18233 ["1 Day Later" org-shiftright t]
18234 ["1 Day Earlier" org-shiftleft t]
18235 ["1 ... Later" org-shiftup t]
18236 ["1 ... Earlier" org-shiftdown t])
18237 ["Compute Time Range" org-evaluate-time-range t]
18238 ["Schedule Item" org-schedule t]
18239 ["Deadline" org-deadline t]
18240 "--"
18241 ["Custom time format" org-toggle-time-stamp-overlays
18242 :style radio :selected org-display-custom-times]
18243 "--"
18244 ["Goto Calendar" org-goto-calendar t]
18245 ["Date from Calendar" org-date-from-calendar t]
18246 "--"
18247 ["Start/Restart Timer" org-timer-start t]
18248 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18249 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18250 ["Insert Timer String" org-timer t]
18251 ["Insert Timer Item" org-timer-item t])
18252 ("Logging work"
18253 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18254 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18255 ["Clock out" org-clock-out t]
18256 ["Clock cancel" org-clock-cancel t]
18257 "--"
18258 ["Mark as default task" org-clock-mark-default-task t]
18259 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18260 ["Goto running clock" org-clock-goto t]
18261 "--"
18262 ["Display times" org-clock-display t]
18263 ["Create clock table" org-clock-report t]
18264 "--"
18265 ["Record DONE time"
18266 (progn (setq org-log-done (not org-log-done))
18267 (message "Switching to %s will %s record a timestamp"
18268 (car org-done-keywords)
18269 (if org-log-done "automatically" "not")))
18270 :style toggle :selected org-log-done])
18271 "--"
18272 ["Agenda Command..." org-agenda t]
18273 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18274 ("File List for Agenda")
18275 ("Special views current file"
18276 ["TODO Tree" org-show-todo-tree t]
18277 ["Check Deadlines" org-check-deadlines t]
18278 ["Timeline" org-timeline t]
18279 ["Tags/Property tree" org-match-sparse-tree t])
18280 "--"
18281 ["Export/Publish..." org-export t]
18282 ("LaTeX"
18283 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18284 :selected org-cdlatex-mode]
18285 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18286 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18287 ["Modify math symbol" org-cdlatex-math-modify
18288 (org-inside-LaTeX-fragment-p)]
18289 ["Insert citation" org-reftex-citation t]
18290 "--"
18291 ["Template for BEAMER" org-insert-beamer-options-template t])
18292 "--"
18293 ("MobileOrg"
18294 ["Push Files and Views" org-mobile-push t]
18295 ["Get Captured and Flagged" org-mobile-pull t]
18296 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18297 "--"
18298 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18299 "--"
18300 ("Documentation"
18301 ["Show Version" org-version t]
18302 ["Info Documentation" org-info t])
18303 ("Customize"
18304 ["Browse Org Group" org-customize t]
18305 "--"
18306 ["Expand This Menu" org-create-customize-menu
18307 (fboundp 'customize-menu-create)])
18308 ["Send bug report" org-submit-bug-report t]
18309 "--"
18310 ("Refresh/Reload"
18311 ["Refresh setup current buffer" org-mode-restart t]
18312 ["Reload Org (after update)" org-reload t]
18313 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18316 (defun org-info (&optional node)
18317 "Read documentation for Org-mode in the info system.
18318 With optional NODE, go directly to that node."
18319 (interactive)
18320 (info (format "(org)%s" (or node ""))))
18322 ;;;###autoload
18323 (defun org-submit-bug-report ()
18324 "Submit a bug report on Org-mode via mail.
18326 Don't hesitate to report any problems or inaccurate documentation.
18328 If you don't have setup sending mail from (X)Emacs, please copy the
18329 output buffer into your mail program, as it gives us important
18330 information about your Org-mode version and configuration."
18331 (interactive)
18332 (require 'reporter)
18333 (org-load-modules-maybe)
18334 (org-require-autoloaded-modules)
18335 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18336 (reporter-submit-bug-report
18337 "emacs-orgmode@gnu.org"
18338 (org-version)
18339 (let (list)
18340 (save-window-excursion
18341 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18342 (delete-other-windows)
18343 (erase-buffer)
18344 (insert "You are about to submit a bug report to the Org-mode mailing list.
18346 We would like to add your full Org-mode and Outline configuration to the
18347 bug report. This greatly simplifies the work of the maintainer and
18348 other experts on the mailing list.
18350 HOWEVER, some variables you have customized may contain private
18351 information. The names of customers, colleagues, or friends, might
18352 appear in the form of file names, tags, todo states, or search strings.
18353 If you answer yes to the prompt, you might want to check and remove
18354 such private information before sending the email.")
18355 (add-text-properties (point-min) (point-max) '(face org-warning))
18356 (when (yes-or-no-p "Include your Org-mode configuration ")
18357 (mapatoms
18358 (lambda (v)
18359 (and (boundp v)
18360 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18361 (or (and (symbol-value v)
18362 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18363 (and
18364 (get v 'custom-type) (get v 'standard-value)
18365 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18366 (push v list)))))
18367 (kill-buffer (get-buffer "*Warn about privacy*"))
18368 list))
18369 nil nil
18370 "Remember to cover the basics, that is, what you expected to happen and
18371 what in fact did happen. You don't know how to make a good report? See
18373 http://orgmode.org/manual/Feedback.html#Feedback
18375 Your bug report will be posted to the Org-mode mailing list.
18376 ------------------------------------------------------------------------")
18377 (save-excursion
18378 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18379 (replace-match "\\1Bug: \\3 [\\2]")))))
18382 (defun org-install-agenda-files-menu ()
18383 (let ((bl (buffer-list)))
18384 (save-excursion
18385 (while bl
18386 (set-buffer (pop bl))
18387 (if (org-mode-p) (setq bl nil)))
18388 (when (org-mode-p)
18389 (easy-menu-change
18390 '("Org") "File List for Agenda"
18391 (append
18392 (list
18393 ["Edit File List" (org-edit-agenda-file-list) t]
18394 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18395 ["Remove Current File from List" org-remove-file t]
18396 ["Cycle through agenda files" org-cycle-agenda-files t]
18397 ["Occur in all agenda files" org-occur-in-agenda-files t]
18398 "--")
18399 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18401 ;;;; Documentation
18403 ;;;###autoload
18404 (defun org-require-autoloaded-modules ()
18405 (interactive)
18406 (mapc 'require
18407 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18408 org-docbook org-exp org-html org-icalendar
18409 org-id org-latex
18410 org-publish org-remember org-table
18411 org-timer org-xoxo)))
18413 ;;;###autoload
18414 (defun org-reload (&optional uncompiled)
18415 "Reload all org lisp files.
18416 With prefix arg UNCOMPILED, load the uncompiled versions."
18417 (interactive "P")
18418 (require 'find-func)
18419 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18420 (dir-org (file-name-directory (org-find-library-name "org")))
18421 (dir-org-contrib (ignore-errors
18422 (file-name-directory
18423 (org-find-library-name "org-contribdir"))))
18424 (babel-files
18425 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18426 (append (list nil "comint" "eval" "exp" "keys"
18427 "lob" "ref" "table" "tangle")
18428 (delq nil
18429 (mapcar
18430 (lambda (lang)
18431 (when (cdr lang) (symbol-name (car lang))))
18432 org-babel-load-languages)))))
18433 (files
18434 (append (directory-files dir-org t file-re)
18435 babel-files
18436 (and dir-org-contrib
18437 (directory-files dir-org-contrib t file-re))))
18438 (remove-re (concat (if (featurep 'xemacs)
18439 "org-colview" "org-colview-xemacs")
18440 "\\'")))
18441 (setq files (mapcar 'file-name-sans-extension files))
18442 (setq files (mapcar
18443 (lambda (x) (if (string-match remove-re x) nil x))
18444 files))
18445 (setq files (delq nil files))
18446 (mapc
18447 (lambda (f)
18448 (when (featurep (intern (file-name-nondirectory f)))
18449 (if (and (not uncompiled)
18450 (file-exists-p (concat f ".elc")))
18451 (load (concat f ".elc") nil nil t)
18452 (load (concat f ".el") nil nil t))))
18453 files))
18454 (org-version))
18456 ;;;###autoload
18457 (defun org-customize ()
18458 "Call the customize function with org as argument."
18459 (interactive)
18460 (org-load-modules-maybe)
18461 (org-require-autoloaded-modules)
18462 (customize-browse 'org))
18464 (defun org-create-customize-menu ()
18465 "Create a full customization menu for Org-mode, insert it into the menu."
18466 (interactive)
18467 (org-load-modules-maybe)
18468 (org-require-autoloaded-modules)
18469 (if (fboundp 'customize-menu-create)
18470 (progn
18471 (easy-menu-change
18472 '("Org") "Customize"
18473 `(["Browse Org group" org-customize t]
18474 "--"
18475 ,(customize-menu-create 'org)
18476 ["Set" Custom-set t]
18477 ["Save" Custom-save t]
18478 ["Reset to Current" Custom-reset-current t]
18479 ["Reset to Saved" Custom-reset-saved t]
18480 ["Reset to Standard Settings" Custom-reset-standard t]))
18481 (message "\"Org\"-menu now contains full customization menu"))
18482 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18484 ;;;; Miscellaneous stuff
18486 ;;; Generally useful functions
18488 (defun org-get-at-bol (property)
18489 "Get text property PROPERTY at beginning of line."
18490 (get-text-property (point-at-bol) property))
18492 (defun org-find-text-property-in-string (prop s)
18493 "Return the first non-nil value of property PROP in string S."
18494 (or (get-text-property 0 prop s)
18495 (get-text-property (or (next-single-property-change 0 prop s) 0)
18496 prop s)))
18498 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18499 "Display the given MESSAGE as a warning."
18500 (if (fboundp 'display-warning)
18501 (display-warning 'org message
18502 (if (featurep 'xemacs) 'warning :warning))
18503 (let ((buf (get-buffer-create "*Org warnings*")))
18504 (with-current-buffer buf
18505 (goto-char (point-max))
18506 (insert "Warning (Org): " message)
18507 (unless (bolp)
18508 (newline)))
18509 (display-buffer buf)
18510 (sit-for 0))))
18512 (defun org-eval (form)
18513 "Eval FORM and return result."
18514 (condition-case error
18515 (eval form)
18516 (error (format "%%![Error: %s]" error))))
18518 (defun org-in-commented-line ()
18519 "Is point in a line starting with `#'?"
18520 (equal (char-after (point-at-bol)) ?#))
18522 (defun org-in-indented-comment-line ()
18523 "Is point in a line starting with `#' after some white space?"
18524 (save-excursion
18525 (save-match-data
18526 (goto-char (point-at-bol))
18527 (looking-at "[ \t]*#"))))
18529 (defun org-in-verbatim-emphasis ()
18530 (save-match-data
18531 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18533 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18534 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18535 (if (and marker (marker-buffer marker)
18536 (buffer-live-p (marker-buffer marker)))
18537 (progn
18538 (switch-to-buffer (marker-buffer marker))
18539 (if (or (> marker (point-max)) (< marker (point-min)))
18540 (widen))
18541 (goto-char marker)
18542 (org-show-context 'org-goto))
18543 (if bookmark
18544 (bookmark-jump bookmark)
18545 (error "Cannot find location"))))
18547 (defun org-quote-csv-field (s)
18548 "Quote field for inclusion in CSV material."
18549 (if (string-match "[\",]" s)
18550 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18553 (defun org-force-self-insert (N)
18554 "Needed to enforce self-insert under remapping."
18555 (interactive "p")
18556 (self-insert-command N))
18558 (defun org-string-width (s)
18559 "Compute width of string, ignoring invisible characters.
18560 This ignores character with invisibility property `org-link', and also
18561 characters with property `org-cwidth', because these will become invisible
18562 upon the next fontification round."
18563 (let (b l)
18564 (when (or (eq t buffer-invisibility-spec)
18565 (assq 'org-link buffer-invisibility-spec))
18566 (while (setq b (text-property-any 0 (length s)
18567 'invisible 'org-link s))
18568 (setq s (concat (substring s 0 b)
18569 (substring s (or (next-single-property-change
18570 b 'invisible s) (length s)))))))
18571 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18572 (setq s (concat (substring s 0 b)
18573 (substring s (or (next-single-property-change
18574 b 'org-cwidth s) (length s))))))
18575 (setq l (string-width s) b -1)
18576 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18577 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18580 (defun org-shorten-string (s maxlength)
18581 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18582 If the string is shorter or has length MAXLENGTH, just return the
18583 original string. If it is longer, the functions finds a space in the
18584 string, breaks this string off at that locations and adds three dots
18585 as ellipsis. Including the ellipsis, the string will not be longer
18586 than MAXLENGTH. If finding a good breaking point in the string does
18587 not work, the string is just chopped off in the middle of a word
18588 if necessary."
18589 (if (<= (length s) maxlength)
18591 (let* ((n (max (- maxlength 4) 1))
18592 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18593 (if (string-match re s)
18594 (concat (match-string 1 s) "...")
18595 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18597 (defun org-get-indentation (&optional line)
18598 "Get the indentation of the current line, interpreting tabs.
18599 When LINE is given, assume it represents a line and compute its indentation."
18600 (if line
18601 (if (string-match "^ *" (org-remove-tabs line))
18602 (match-end 0))
18603 (save-excursion
18604 (beginning-of-line 1)
18605 (skip-chars-forward " \t")
18606 (current-column))))
18608 (defun org-get-string-indentation (s)
18609 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18610 (let ((n -1) (i 0) (w tab-width) c)
18611 (catch 'exit
18612 (while (< (setq n (1+ n)) (length s))
18613 (setq c (aref s n))
18614 (cond ((= c ?\ ) (setq i (1+ i)))
18615 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18616 (t (throw 'exit t)))))
18619 (defun org-remove-tabs (s &optional width)
18620 "Replace tabulators in S with spaces.
18621 Assumes that s is a single line, starting in column 0."
18622 (setq width (or width tab-width))
18623 (while (string-match "\t" s)
18624 (setq s (replace-match
18625 (make-string
18626 (- (* width (/ (+ (match-beginning 0) width) width))
18627 (match-beginning 0)) ?\ )
18628 t t s)))
18631 (defun org-fix-indentation (line ind)
18632 "Fix indentation in LINE.
18633 IND is a cons cell with target and minimum indentation.
18634 If the current indentation in LINE is smaller than the minimum,
18635 leave it alone. If it is larger than ind, set it to the target."
18636 (let* ((l (org-remove-tabs line))
18637 (i (org-get-indentation l))
18638 (i1 (car ind)) (i2 (cdr ind)))
18639 (if (>= i i2) (setq l (substring line i2)))
18640 (if (> i1 0)
18641 (concat (make-string i1 ?\ ) l)
18642 l)))
18644 (defun org-remove-indentation (code &optional n)
18645 "Remove the maximum common indentation from the lines in CODE.
18646 N may optionally be the number of spaces to remove."
18647 (with-temp-buffer
18648 (insert code)
18649 (org-do-remove-indentation n)
18650 (buffer-string)))
18652 (defun org-do-remove-indentation (&optional n)
18653 "Remove the maximum common indentation from the buffer."
18654 (untabify (point-min) (point-max))
18655 (let ((min 10000) re)
18656 (if n
18657 (setq min n)
18658 (goto-char (point-min))
18659 (while (re-search-forward "^ *[^ \n]" nil t)
18660 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18661 (unless (or (= min 0) (= min 10000))
18662 (setq re (format "^ \\{%d\\}" min))
18663 (goto-char (point-min))
18664 (while (re-search-forward re nil t)
18665 (replace-match "")
18666 (end-of-line 1))
18667 min)))
18669 (defun org-fill-template (template alist)
18670 "Find each %key of ALIST in TEMPLATE and replace it."
18671 (let ((case-fold-search nil)
18672 entry key value)
18673 (setq alist (sort (copy-sequence alist)
18674 (lambda (a b) (< (length (car a)) (length (car b))))))
18675 (while (setq entry (pop alist))
18676 (setq template
18677 (replace-regexp-in-string
18678 (concat "%" (regexp-quote (car entry)))
18679 (cdr entry) template t t)))
18680 template))
18682 (defun org-base-buffer (buffer)
18683 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18684 (if (not buffer)
18685 buffer
18686 (or (buffer-base-buffer buffer)
18687 buffer)))
18689 (defun org-trim (s)
18690 "Remove whitespace at beginning and end of string."
18691 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18692 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18695 (defun org-wrap (string &optional width lines)
18696 "Wrap string to either a number of lines, or a width in characters.
18697 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18698 that costs. If there is a word longer than WIDTH, the text is actually
18699 wrapped to the length of that word.
18700 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18701 many lines, whatever width that takes.
18702 The return value is a list of lines, without newlines at the end."
18703 (let* ((words (org-split-string string "[ \t\n]+"))
18704 (maxword (apply 'max (mapcar 'org-string-width words)))
18705 w ll)
18706 (cond (width
18707 (org-do-wrap words (max maxword width)))
18708 (lines
18709 (setq w maxword)
18710 (setq ll (org-do-wrap words maxword))
18711 (if (<= (length ll) lines)
18713 (setq ll words)
18714 (while (> (length ll) lines)
18715 (setq w (1+ w))
18716 (setq ll (org-do-wrap words w)))
18717 ll))
18718 (t (error "Cannot wrap this")))))
18720 (defun org-do-wrap (words width)
18721 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18722 (let (lines line)
18723 (while words
18724 (setq line (pop words))
18725 (while (and words (< (+ (length line) (length (car words))) width))
18726 (setq line (concat line " " (pop words))))
18727 (setq lines (push line lines)))
18728 (nreverse lines)))
18730 (defun org-split-string (string &optional separators)
18731 "Splits STRING into substrings at SEPARATORS.
18732 No empty strings are returned if there are matches at the beginning
18733 and end of string."
18734 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18735 (start 0)
18736 notfirst
18737 (list nil))
18738 (while (and (string-match rexp string
18739 (if (and notfirst
18740 (= start (match-beginning 0))
18741 (< start (length string)))
18742 (1+ start) start))
18743 (< (match-beginning 0) (length string)))
18744 (setq notfirst t)
18745 (or (eq (match-beginning 0) 0)
18746 (and (eq (match-beginning 0) (match-end 0))
18747 (eq (match-beginning 0) start))
18748 (setq list
18749 (cons (substring string start (match-beginning 0))
18750 list)))
18751 (setq start (match-end 0)))
18752 (or (eq start (length string))
18753 (setq list
18754 (cons (substring string start)
18755 list)))
18756 (nreverse list)))
18758 (defun org-quote-vert (s)
18759 "Replace \"|\" with \"\\vert\"."
18760 (while (string-match "|" s)
18761 (setq s (replace-match "\\vert" t t s)))
18764 (defun org-uuidgen-p (s)
18765 "Is S an ID created by UUIDGEN?"
18766 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18768 (defun org-context ()
18769 "Return a list of contexts of the current cursor position.
18770 If several contexts apply, all are returned.
18771 Each context entry is a list with a symbol naming the context, and
18772 two positions indicating start and end of the context. Possible
18773 contexts are:
18775 :headline anywhere in a headline
18776 :headline-stars on the leading stars in a headline
18777 :todo-keyword on a TODO keyword (including DONE) in a headline
18778 :tags on the TAGS in a headline
18779 :priority on the priority cookie in a headline
18780 :item on the first line of a plain list item
18781 :item-bullet on the bullet/number of a plain list item
18782 :checkbox on the checkbox in a plain list item
18783 :table in an org-mode table
18784 :table-special on a special filed in a table
18785 :table-table in a table.el table
18786 :link on a hyperlink
18787 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18788 :target on a <<target>>
18789 :radio-target on a <<<radio-target>>>
18790 :latex-fragment on a LaTeX fragment
18791 :latex-preview on a LaTeX fragment with overlayed preview image
18793 This function expects the position to be visible because it uses font-lock
18794 faces as a help to recognize the following contexts: :table-special, :link,
18795 and :keyword."
18796 (let* ((f (get-text-property (point) 'face))
18797 (faces (if (listp f) f (list f)))
18798 (p (point)) clist o)
18799 ;; First the large context
18800 (cond
18801 ((org-on-heading-p t)
18802 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18803 (when (progn
18804 (beginning-of-line 1)
18805 (looking-at org-todo-line-tags-regexp))
18806 (push (org-point-in-group p 1 :headline-stars) clist)
18807 (push (org-point-in-group p 2 :todo-keyword) clist)
18808 (push (org-point-in-group p 4 :tags) clist))
18809 (goto-char p)
18810 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18811 (if (looking-at "\\[#[A-Z0-9]\\]")
18812 (push (org-point-in-group p 0 :priority) clist)))
18814 ((org-at-item-p)
18815 (push (org-point-in-group p 2 :item-bullet) clist)
18816 (push (list :item (point-at-bol)
18817 (save-excursion (org-end-of-item) (point)))
18818 clist)
18819 (and (org-at-item-checkbox-p)
18820 (push (org-point-in-group p 0 :checkbox) clist)))
18822 ((org-at-table-p)
18823 (push (list :table (org-table-begin) (org-table-end)) clist)
18824 (if (memq 'org-formula faces)
18825 (push (list :table-special
18826 (previous-single-property-change p 'face)
18827 (next-single-property-change p 'face)) clist)))
18828 ((org-at-table-p 'any)
18829 (push (list :table-table) clist)))
18830 (goto-char p)
18832 ;; Now the small context
18833 (cond
18834 ((org-at-timestamp-p)
18835 (push (org-point-in-group p 0 :timestamp) clist))
18836 ((memq 'org-link faces)
18837 (push (list :link
18838 (previous-single-property-change p 'face)
18839 (next-single-property-change p 'face)) clist))
18840 ((memq 'org-special-keyword faces)
18841 (push (list :keyword
18842 (previous-single-property-change p 'face)
18843 (next-single-property-change p 'face)) clist))
18844 ((org-on-target-p)
18845 (push (org-point-in-group p 0 :target) clist)
18846 (goto-char (1- (match-beginning 0)))
18847 (if (looking-at org-radio-target-regexp)
18848 (push (org-point-in-group p 0 :radio-target) clist))
18849 (goto-char p))
18850 ((setq o (car (delq nil
18851 (mapcar
18852 (lambda (x)
18853 (if (memq x org-latex-fragment-image-overlays) x))
18854 (overlays-at (point))))))
18855 (push (list :latex-fragment
18856 (overlay-start o) (overlay-end o)) clist)
18857 (push (list :latex-preview
18858 (overlay-start o) (overlay-end o)) clist))
18859 ((org-inside-LaTeX-fragment-p)
18860 ;; FIXME: positions wrong.
18861 (push (list :latex-fragment (point) (point)) clist)))
18863 (setq clist (nreverse (delq nil clist)))
18864 clist))
18866 ;; FIXME: Compare with at-regexp-p Do we need both?
18867 (defun org-in-regexp (re &optional nlines visually)
18868 "Check if point is inside a match of regexp.
18869 Normally only the current line is checked, but you can include NLINES extra
18870 lines both before and after point into the search.
18871 If VISUALLY is set, require that the cursor is not after the match but
18872 really on, so that the block visually is on the match."
18873 (catch 'exit
18874 (let ((pos (point))
18875 (eol (point-at-eol (+ 1 (or nlines 0))))
18876 (inc (if visually 1 0)))
18877 (save-excursion
18878 (beginning-of-line (- 1 (or nlines 0)))
18879 (while (re-search-forward re eol t)
18880 (if (and (<= (match-beginning 0) pos)
18881 (>= (+ inc (match-end 0)) pos))
18882 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18884 (defun org-at-regexp-p (regexp)
18885 "Is point inside a match of REGEXP in the current line?"
18886 (catch 'exit
18887 (save-excursion
18888 (let ((pos (point)) (end (point-at-eol)))
18889 (beginning-of-line 1)
18890 (while (re-search-forward regexp end t)
18891 (if (and (<= (match-beginning 0) pos)
18892 (>= (match-end 0) pos))
18893 (throw 'exit t)))
18894 nil))))
18896 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18897 "Return t if the current point is between matches of START-RE and END-RE.
18898 This will also return t if point is on one of the two matches or
18899 in an unfinished block. END-RE can be a string or a form
18900 returning a string.
18902 An optional third argument bounds the search for START-RE. It
18903 defaults to previous heading or `point-min'."
18904 (let ((pos (point))
18905 (limit (or bound (save-excursion (outline-previous-heading)))))
18906 (save-excursion
18907 ;; we're on a block when point is on start-re...
18908 (or (org-at-regexp-p start-re)
18909 ;; ... or start-re can be found above...
18910 (and (re-search-backward start-re limit t)
18911 ;; ... but no end-re between start-re and point.
18912 (not (re-search-forward (eval end-re) pos t)))))))
18914 (defun org-occur-in-agenda-files (regexp &optional nlines)
18915 "Call `multi-occur' with buffers for all agenda files."
18916 (interactive "sOrg-files matching: \np")
18917 (let* ((files (org-agenda-files))
18918 (tnames (mapcar 'file-truename files))
18919 (extra org-agenda-text-search-extra-files)
18921 (when (eq (car extra) 'agenda-archives)
18922 (setq extra (cdr extra))
18923 (setq files (org-add-archive-files files)))
18924 (while (setq f (pop extra))
18925 (unless (member (file-truename f) tnames)
18926 (add-to-list 'files f 'append)
18927 (add-to-list 'tnames (file-truename f) 'append)))
18928 (multi-occur
18929 (mapcar (lambda (x)
18930 (with-current-buffer
18931 (or (get-file-buffer x) (find-file-noselect x))
18932 (widen)
18933 (current-buffer)))
18934 files)
18935 regexp)))
18937 (if (boundp 'occur-mode-find-occurrence-hook)
18938 ;; Emacs 23
18939 (add-hook 'occur-mode-find-occurrence-hook
18940 (lambda ()
18941 (when (org-mode-p)
18942 (org-reveal))))
18943 ;; Emacs 22
18944 (defadvice occur-mode-goto-occurrence
18945 (after org-occur-reveal activate)
18946 (and (org-mode-p) (org-reveal)))
18947 (defadvice occur-mode-goto-occurrence-other-window
18948 (after org-occur-reveal activate)
18949 (and (org-mode-p) (org-reveal)))
18950 (defadvice occur-mode-display-occurrence
18951 (after org-occur-reveal activate)
18952 (when (org-mode-p)
18953 (let ((pos (occur-mode-find-occurrence)))
18954 (with-current-buffer (marker-buffer pos)
18955 (save-excursion
18956 (goto-char pos)
18957 (org-reveal)))))))
18959 (defun org-occur-link-in-agenda-files ()
18960 "Create a link and search for it in the agendas.
18961 The link is not stored in `org-stored-links', it is just created
18962 for the search purpose."
18963 (interactive)
18964 (let ((link (condition-case nil
18965 (org-store-link nil)
18966 (error "Unable to create a link to here"))))
18967 (org-occur-in-agenda-files (regexp-quote link))))
18969 (defun org-uniquify (list)
18970 "Remove duplicate elements from LIST."
18971 (let (res)
18972 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18973 res))
18975 (defun org-delete-all (elts list)
18976 "Remove all elements in ELTS from LIST."
18977 (while elts
18978 (setq list (delete (pop elts) list)))
18979 list)
18981 (defun org-count (cl-item cl-seq)
18982 "Count the number of occurrences of ITEM in SEQ.
18983 Taken from `count' in cl-seq.el with all keyword arguments removed."
18984 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18985 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18986 (while (< cl-start cl-end)
18987 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18988 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18989 (setq cl-start (1+ cl-start)))
18990 cl-count))
18992 (defun org-remove-if (predicate seq)
18993 "Remove everything from SEQ that fulfills PREDICATE."
18994 (let (res e)
18995 (while seq
18996 (setq e (pop seq))
18997 (if (not (funcall predicate e)) (push e res)))
18998 (nreverse res)))
19000 (defun org-remove-if-not (predicate seq)
19001 "Remove everything from SEQ that does not fulfill PREDICATE."
19002 (let (res e)
19003 (while seq
19004 (setq e (pop seq))
19005 (if (funcall predicate e) (push e res)))
19006 (nreverse res)))
19008 (defun org-back-over-empty-lines ()
19009 "Move backwards over whitespace, to the beginning of the first empty line.
19010 Returns the number of empty lines passed."
19011 (let ((pos (point)))
19012 (if (cdr (assoc 'heading org-blank-before-new-entry))
19013 (skip-chars-backward " \t\n\r")
19014 (forward-line -1))
19015 (beginning-of-line 2)
19016 (goto-char (min (point) pos))
19017 (count-lines (point) pos)))
19019 (defun org-skip-whitespace ()
19020 (skip-chars-forward " \t\n\r"))
19022 (defun org-point-in-group (point group &optional context)
19023 "Check if POINT is in match-group GROUP.
19024 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19025 match. If the match group does not exist or point is not inside it,
19026 return nil."
19027 (and (match-beginning group)
19028 (>= point (match-beginning group))
19029 (<= point (match-end group))
19030 (if context
19031 (list context (match-beginning group) (match-end group))
19032 t)))
19034 (defun org-switch-to-buffer-other-window (&rest args)
19035 "Switch to buffer in a second window on the current frame.
19036 In particular, do not allow pop-up frames.
19037 Returns the newly created buffer."
19038 (let (pop-up-frames special-display-buffer-names special-display-regexps
19039 special-display-function)
19040 (apply 'switch-to-buffer-other-window args)))
19042 (defun org-combine-plists (&rest plists)
19043 "Create a single property list from all plists in PLISTS.
19044 The process starts by copying the first list, and then setting properties
19045 from the other lists. Settings in the last list are the most significant
19046 ones and overrule settings in the other lists."
19047 (let ((rtn (copy-sequence (pop plists)))
19048 p v ls)
19049 (while plists
19050 (setq ls (pop plists))
19051 (while ls
19052 (setq p (pop ls) v (pop ls))
19053 (setq rtn (plist-put rtn p v))))
19054 rtn))
19056 (defun org-move-line-down (arg)
19057 "Move the current line down. With prefix argument, move it past ARG lines."
19058 (interactive "p")
19059 (let ((col (current-column))
19060 beg end pos)
19061 (beginning-of-line 1) (setq beg (point))
19062 (beginning-of-line 2) (setq end (point))
19063 (beginning-of-line (+ 1 arg))
19064 (setq pos (move-marker (make-marker) (point)))
19065 (insert (delete-and-extract-region beg end))
19066 (goto-char pos)
19067 (org-move-to-column col)))
19069 (defun org-move-line-up (arg)
19070 "Move the current line up. With prefix argument, move it past ARG lines."
19071 (interactive "p")
19072 (let ((col (current-column))
19073 beg end pos)
19074 (beginning-of-line 1) (setq beg (point))
19075 (beginning-of-line 2) (setq end (point))
19076 (beginning-of-line (- arg))
19077 (setq pos (move-marker (make-marker) (point)))
19078 (insert (delete-and-extract-region beg end))
19079 (goto-char pos)
19080 (org-move-to-column col)))
19082 (defun org-replace-escapes (string table)
19083 "Replace %-escapes in STRING with values in TABLE.
19084 TABLE is an association list with keys like \"%a\" and string values.
19085 The sequences in STRING may contain normal field width and padding information,
19086 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19087 so values can contain further %-escapes if they are define later in TABLE."
19088 (let ((tbl (copy-alist table))
19089 (case-fold-search nil)
19090 (pchg 0)
19091 e re rpl)
19092 (while (setq e (pop tbl))
19093 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19094 (when (and (cdr e) (string-match re (cdr e)))
19095 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19096 (safe "SREF"))
19097 (add-text-properties 0 3 (list 'sref sref) safe)
19098 (setcdr e (replace-match safe t t (cdr e)))))
19099 (while (string-match re string)
19100 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19101 (cdr e)))
19102 (setq string (replace-match rpl t t string))))
19103 (while (setq pchg (next-property-change pchg string))
19104 (let ((sref (get-text-property pchg 'sref string)))
19105 (when (and sref (string-match "SREF" string pchg))
19106 (setq string (replace-match sref t t string)))))
19107 string))
19109 (defun org-sublist (list start end)
19110 "Return a section of LIST, from START to END.
19111 Counting starts at 1."
19112 (let (rtn (c start))
19113 (setq list (nthcdr (1- start) list))
19114 (while (and list (<= c end))
19115 (push (pop list) rtn)
19116 (setq c (1+ c)))
19117 (nreverse rtn)))
19119 (defun org-find-base-buffer-visiting (file)
19120 "Like `find-buffer-visiting' but always return the base buffer and
19121 not an indirect buffer."
19122 (let ((buf (or (get-file-buffer file)
19123 (find-buffer-visiting file))))
19124 (if buf
19125 (or (buffer-base-buffer buf) buf)
19126 nil)))
19128 (defun org-image-file-name-regexp (&optional extensions)
19129 "Return regexp matching the file names of images.
19130 If EXTENSIONS is given, only match these."
19131 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19132 (image-file-name-regexp)
19133 (let ((image-file-name-extensions
19134 (or extensions
19135 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19136 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19137 (concat "\\."
19138 (regexp-opt (nconc (mapcar 'upcase
19139 image-file-name-extensions)
19140 image-file-name-extensions)
19142 "\\'"))))
19144 (defun org-file-image-p (file &optional extensions)
19145 "Return non-nil if FILE is an image."
19146 (save-match-data
19147 (string-match (org-image-file-name-regexp extensions) file)))
19149 (defun org-get-cursor-date ()
19150 "Return the date at cursor in as a time.
19151 This works in the calendar and in the agenda, anywhere else it just
19152 returns the current time."
19153 (let (date day defd)
19154 (cond
19155 ((eq major-mode 'calendar-mode)
19156 (setq date (calendar-cursor-to-date)
19157 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19158 ((eq major-mode 'org-agenda-mode)
19159 (setq day (get-text-property (point) 'day))
19160 (if day
19161 (setq date (calendar-gregorian-from-absolute day)
19162 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19163 (nth 2 date))))))
19164 (or defd (current-time))))
19166 (defvar org-agenda-action-marker (make-marker)
19167 "Marker pointing to the entry for the next agenda action.")
19169 (defun org-mark-entry-for-agenda-action ()
19170 "Mark the current entry as target of an agenda action.
19171 Agenda actions are actions executed from the agenda with the key `k',
19172 which make use of the date at the cursor."
19173 (interactive)
19174 (move-marker org-agenda-action-marker
19175 (save-excursion (org-back-to-heading t) (point))
19176 (current-buffer))
19177 (message
19178 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19180 (defun org-mark-subtree ()
19181 "Mark the current subtree.
19182 This puts point at the start of the current subtree, and mark at the end.
19184 If point is in an inline task, mark that task instead."
19185 (interactive)
19186 (let ((inline-task-p
19187 (and (featurep 'org-inlinetask)
19188 (org-inlinetask-in-task-p)))
19189 (beg))
19190 ;; Get beginning of subtree
19191 (cond
19192 (inline-task-p (org-inlinetask-goto-beginning))
19193 ((org-at-heading-p) (beginning-of-line))
19194 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19195 (setq beg (point))
19196 ;; Get end of it
19197 (if inline-task-p
19198 (org-inlinetask-goto-end)
19199 (org-end-of-subtree))
19200 ;; Mark zone
19201 (push-mark (point) nil t)
19202 (goto-char beg)))
19204 ;;; Paragraph filling stuff.
19205 ;; We want this to be just right, so use the full arsenal.
19207 (defun org-indent-line-function ()
19208 "Indent line depending on context."
19209 (interactive)
19210 (let* ((pos (point))
19211 (itemp (org-at-item-p))
19212 (case-fold-search t)
19213 (org-drawer-regexp (or org-drawer-regexp "\000"))
19214 (inline-task-p (and (featurep 'org-inlinetask)
19215 (org-inlinetask-in-task-p)))
19216 (inline-re (and inline-task-p
19217 (org-inlinetask-outline-regexp)))
19218 column)
19219 (beginning-of-line 1)
19220 (cond
19221 ;; Comments
19222 ((looking-at "# ") (setq column 0))
19223 ;; Headings
19224 ((looking-at "\\*+ ") (setq column 0))
19225 ;; Included files
19226 ((looking-at "#\\+include:") (setq column 0))
19227 ;; Footnote definition
19228 ((looking-at org-footnote-definition-re) (setq column 0))
19229 ;; Literal examples
19230 ((looking-at "[ \t]*:[ \t]")
19231 (setq column (org-get-indentation))) ; do nothing
19232 ;; Lists
19233 ((ignore-errors (goto-char (org-in-item-p)))
19234 (setq column (if itemp
19235 (org-get-indentation)
19236 (org-list-item-body-column (point))))
19237 (goto-char pos))
19238 ;; Drawers
19239 ((and (looking-at "[ \t]*:END:")
19240 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19241 (save-excursion
19242 (goto-char (1- (match-beginning 1)))
19243 (setq column (current-column))))
19244 ;; Special blocks
19245 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19246 (save-excursion
19247 (re-search-backward
19248 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19249 (setq column (org-get-indentation (match-string 0))))
19250 ((and (not (looking-at "[ \t]*#\\+begin_"))
19251 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19252 (save-excursion
19253 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19254 (setq column
19255 (if (equal (downcase (match-string 1)) "src")
19256 ;; src blocks: let `org-edit-src-exit' handle them
19257 (org-get-indentation)
19258 (org-get-indentation (match-string 0)))))
19259 ;; This line has nothing special, look at the previous relevant
19260 ;; line to compute indentation
19262 (beginning-of-line 0)
19263 (while (and (not (bobp))
19264 (not (looking-at org-drawer-regexp))
19265 ;; When point started in an inline task, do not move
19266 ;; above task starting line.
19267 (not (and inline-task-p (looking-at inline-re)))
19268 ;; Skip drawers, blocks, empty lines, verbatim,
19269 ;; comments, tables, footnotes definitions, lists,
19270 ;; inline tasks.
19271 (or (and (looking-at "[ \t]*:END:")
19272 (re-search-backward org-drawer-regexp nil t))
19273 (and (looking-at "[ \t]*#\\+end_")
19274 (re-search-backward "[ \t]*#\\+begin_"nil t))
19275 (looking-at "[ \t]*[\n:#|]")
19276 (looking-at org-footnote-definition-re)
19277 (and (ignore-errors (goto-char (org-in-item-p)))
19278 (goto-char
19279 (org-list-get-top-point (org-list-struct))))
19280 (and (not inline-task-p)
19281 (featurep 'org-inlinetask)
19282 (org-inlinetask-in-task-p)
19283 (or (org-inlinetask-goto-beginning) t))))
19284 (beginning-of-line 0))
19285 (cond
19286 ;; There was an heading above.
19287 ((looking-at "\\*+[ \t]+")
19288 (if (not org-adapt-indentation)
19289 (setq column 0)
19290 (goto-char (match-end 0))
19291 (setq column (current-column))))
19292 ;; A drawer had started and is unfinished
19293 ((looking-at org-drawer-regexp)
19294 (goto-char (1- (match-beginning 1)))
19295 (setq column (current-column)))
19296 ;; Else, nothing noticeable found: get indentation and go on.
19297 (t (setq column (org-get-indentation))))))
19298 ;; Now apply indentation and move cursor accordingly
19299 (goto-char pos)
19300 (if (<= (current-column) (current-indentation))
19301 (org-indent-line-to column)
19302 (save-excursion (org-indent-line-to column)))
19303 ;; Special polishing for properties, see `org-property-format'
19304 (setq column (current-column))
19305 (beginning-of-line 1)
19306 (if (looking-at
19307 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19308 (replace-match (concat (match-string 1)
19309 (format org-property-format
19310 (match-string 2) (match-string 3)))
19311 t t))
19312 (org-move-to-column column)))
19314 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19315 "Variable to store copy of `adaptive-fill-regexp'.
19316 Since `adaptive-fill-regexp' is set to never match, we need to
19317 store a backup of its value before entering `org-mode' so that
19318 the functionality can be provided as a fall-back.")
19320 (defun org-set-autofill-regexps ()
19321 (interactive)
19322 ;; In the paragraph separator we include headlines, because filling
19323 ;; text in a line directly attached to a headline would otherwise
19324 ;; fill the headline as well.
19325 (org-set-local 'comment-start-skip "^#+[ \t]*")
19326 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19327 ;; The paragraph starter includes hand-formatted lists.
19328 (org-set-local
19329 'paragraph-start
19330 (concat
19331 "\f" "\\|"
19332 "[ ]*$" "\\|"
19333 "\\*+ " "\\|"
19334 "[ \t]*#" "\\|"
19335 (org-item-re) "\\|"
19336 "[ \t]*[:|]" "\\|"
19337 "\\$\\$" "\\|"
19338 "\\\\\\(begin\\|end\\|[][]\\)"))
19339 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19340 ;; But only if the user has not turned off tables or fixed-width regions
19341 (org-set-local
19342 'auto-fill-inhibit-regexp
19343 (concat "\\*+ \\|#\\+"
19344 "\\|[ \t]*" org-keyword-time-regexp
19345 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19346 (concat
19347 "\\|[ \t]*["
19348 (if org-enable-table-editor "|" "")
19349 (if org-enable-fixed-width-editor ":" "")
19350 "]"))))
19351 ;; We use our own fill-paragraph function, to make sure that tables
19352 ;; and fixed-width regions are not wrapped. That function will pass
19353 ;; through to `fill-paragraph' when appropriate.
19354 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19355 ;; Prevent auto-fill from inserting unwanted new items.
19356 (org-set-local 'fill-nobreak-predicate
19357 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19358 fill-nobreak-predicate
19359 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19360 ;; Adaptive filling: To get full control, first make sure that
19361 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19362 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19363 (org-set-local 'org-adaptive-fill-regexp-backup
19364 adaptive-fill-regexp))
19365 (org-set-local 'adaptive-fill-regexp "\000")
19366 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19367 (org-set-local 'adaptive-fill-function
19368 'org-adaptive-fill-function)
19369 (org-set-local
19370 'align-mode-rules-list
19371 '((org-in-buffer-settings
19372 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19373 (modes . '(org-mode))))))
19375 (defun org-fill-item-nobreak-p ()
19376 "Non-nil when a line break at point would insert a new item."
19377 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19379 (defun org-fill-paragraph (&optional justify)
19380 "Re-align a table, pass through to fill-paragraph if no table."
19381 (let ((table-p (org-at-table-p))
19382 (table.el-p (org-at-table.el-p))
19383 (itemp (org-in-item-p)))
19384 (cond ((and (equal (char-after (point-at-bol)) ?*)
19385 (save-excursion (goto-char (point-at-bol))
19386 (looking-at outline-regexp)))
19387 t) ; skip headlines
19388 (table.el-p t) ; skip table.el tables
19389 (table-p (org-table-align) t) ; align Org tables
19390 (itemp ; align text in items
19391 (let* ((struct (save-excursion (goto-char itemp)
19392 (org-list-struct)))
19393 (parents (org-list-parents-alist struct))
19394 (children (org-list-get-children itemp struct parents))
19395 beg end prev next prefix)
19396 ;; Determine in which part of item point is: before
19397 ;; first child, after last child, between two
19398 ;; sub-lists, or simply in item if there's no child.
19399 (cond
19400 ((not children)
19401 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19402 beg itemp
19403 end (org-list-get-item-end itemp struct)))
19404 ((< (point) (setq next (car children)))
19405 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19406 beg itemp
19407 end next))
19408 ((> (point) (setq prev (car (last children))))
19409 (setq beg (org-list-get-item-end prev struct)
19410 end (org-list-get-item-end itemp struct)
19411 prefix (save-excursion
19412 (goto-char beg)
19413 (skip-chars-forward " \t")
19414 (make-string (current-column) ?\ ))))
19415 (t (catch 'exit
19416 (while (setq next (pop children))
19417 (if (> (point) next)
19418 (setq prev next)
19419 (setq beg (org-list-get-item-end prev struct)
19420 end next
19421 prefix (save-excursion
19422 (goto-char beg)
19423 (skip-chars-forward " \t")
19424 (make-string (current-column) ?\ )))
19425 (throw 'exit nil))))))
19426 ;; Use `fill-paragraph' with buffer narrowed to item
19427 ;; without any child, and with our computed PREFIX.
19428 (flet ((fill-context-prefix (from to &optional flr) prefix))
19429 (save-restriction
19430 (narrow-to-region beg end)
19431 (save-excursion (fill-paragraph justify)))) t))
19432 ;; Special case where point is not in a list but is on
19433 ;; a paragraph adjacent to a list: make sure this paragraph
19434 ;; doesn't get merged with the end of the list by narrowing
19435 ;; buffer first.
19436 ((save-excursion (forward-paragraph -1)
19437 (setq itemp (org-in-item-p)))
19438 (let ((struct (save-excursion (goto-char itemp)
19439 (org-list-struct))))
19440 (save-restriction
19441 (narrow-to-region (org-list-get-bottom-point struct)
19442 (save-excursion (forward-paragraph 1)
19443 (point)))
19444 (fill-paragraph justify) t)))
19445 ;; Else simply call `fill-paragraph'.
19446 (t nil))))
19448 ;; For reference, this is the default value of adaptive-fill-regexp
19449 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19451 (defun org-adaptive-fill-function ()
19452 "Return a fill prefix for org-mode files."
19453 (let (itemp)
19454 (save-excursion
19455 (cond
19456 ;; Comment line
19457 ((looking-at "#[ \t]+")
19458 (match-string-no-properties 0))
19459 ;; Plain list item
19460 ((org-at-item-p)
19461 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19462 ;; Point is in a list after `backward-paragraph': original
19463 ;; point wasn't in the list, or filling would have been taken
19464 ;; care of by `org-auto-fill-function', but the list and the
19465 ;; real paragraph are not separated by a blank line. Thus, move
19466 ;; point after the list to go back to real paragraph and
19467 ;; determine fill-prefix.
19468 ((setq itemp (org-in-item-p))
19469 (goto-char itemp)
19470 (let* ((struct (org-list-struct))
19471 (bottom (org-list-get-bottom-point struct)))
19472 (goto-char bottom)
19473 (make-string (org-get-indentation) ?\ )))
19474 ;; Other text
19475 ((looking-at org-adaptive-fill-regexp-backup)
19476 (match-string-no-properties 0))))))
19478 (defun org-auto-fill-function ()
19479 "Auto-fill function."
19480 (let (itemp prefix)
19481 ;; When in a list, compute an appropriate fill-prefix and make
19482 ;; sure it will be used by `do-auto-fill'.
19483 (if (setq itemp (org-in-item-p))
19484 (progn
19485 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19486 (flet ((fill-context-prefix (from to &optional flr) prefix))
19487 (do-auto-fill)))
19488 ;; Else just use `do-auto-fill'.
19489 (do-auto-fill))))
19491 ;;; Other stuff.
19493 (defun org-toggle-fixed-width-section (arg)
19494 "Toggle the fixed-width export.
19495 If there is no active region, the QUOTE keyword at the current headline is
19496 inserted or removed. When present, it causes the text between this headline
19497 and the next to be exported as fixed-width text, and unmodified.
19498 If there is an active region, this command adds or removes a colon as the
19499 first character of this line. If the first character of a line is a colon,
19500 this line is also exported in fixed-width font."
19501 (interactive "P")
19502 (let* ((cc 0)
19503 (regionp (org-region-active-p))
19504 (beg (if regionp (region-beginning) (point)))
19505 (end (if regionp (region-end)))
19506 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19507 (case-fold-search nil)
19508 (re "[ \t]*\\(: \\)")
19509 off)
19510 (if regionp
19511 (save-excursion
19512 (goto-char beg)
19513 (setq cc (current-column))
19514 (beginning-of-line 1)
19515 (setq off (looking-at re))
19516 (while (> nlines 0)
19517 (setq nlines (1- nlines))
19518 (beginning-of-line 1)
19519 (cond
19520 (arg
19521 (org-move-to-column cc t)
19522 (insert ": \n")
19523 (forward-line -1))
19524 ((and off (looking-at re))
19525 (replace-match "" t t nil 1))
19526 ((not off) (org-move-to-column cc t) (insert ": ")))
19527 (forward-line 1)))
19528 (save-excursion
19529 (org-back-to-heading)
19530 (if (looking-at (concat outline-regexp
19531 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19532 (replace-match "" t t nil 1)
19533 (if (looking-at outline-regexp)
19534 (progn
19535 (goto-char (match-end 0))
19536 (insert org-quote-string " "))))))))
19538 (defun org-reftex-citation ()
19539 "Use reftex-citation to insert a citation into the buffer.
19540 This looks for a line like
19542 #+BIBLIOGRAPHY: foo plain option:-d
19544 and derives from it that foo.bib is the bibliography file relevant
19545 for this document. It then installs the necessary environment for RefTeX
19546 to work in this buffer and calls `reftex-citation' to insert a citation
19547 into the buffer.
19549 Export of such citations to both LaTeX and HTML is handled by the contributed
19550 package org-exp-bibtex by Taru Karttunen."
19551 (interactive)
19552 (let ((reftex-docstruct-symbol 'rds)
19553 (reftex-cite-format "\\cite{%l}")
19554 rds bib)
19555 (save-excursion
19556 (save-restriction
19557 (widen)
19558 (let ((case-fold-search t)
19559 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19560 (if (not (save-excursion
19561 (or (re-search-forward re nil t)
19562 (re-search-backward re nil t))))
19563 (error "No bibliography defined in file")
19564 (setq bib (concat (match-string 1) ".bib")
19565 rds (list (list 'bib bib)))))))
19566 (call-interactively 'reftex-citation)))
19568 ;;;; Functions extending outline functionality
19570 (defun org-beginning-of-line (&optional arg)
19571 "Go to the beginning of the current line. If that is invisible, continue
19572 to a visible line beginning. This makes the function of C-a more intuitive.
19573 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19574 first attempt, and only move to after the tags when the cursor is already
19575 beyond the end of the headline."
19576 (interactive "P")
19577 (let ((pos (point))
19578 (special (if (consp org-special-ctrl-a/e)
19579 (car org-special-ctrl-a/e)
19580 org-special-ctrl-a/e))
19581 refpos)
19582 (if (org-bound-and-true-p line-move-visual)
19583 (beginning-of-visual-line 1)
19584 (beginning-of-line 1))
19585 (if (and arg (fboundp 'move-beginning-of-line))
19586 (call-interactively 'move-beginning-of-line)
19587 (if (bobp)
19589 (backward-char 1)
19590 (if (org-truely-invisible-p)
19591 (while (and (not (bobp)) (org-truely-invisible-p))
19592 (backward-char 1)
19593 (beginning-of-line 1))
19594 (forward-char 1))))
19595 (when special
19596 (cond
19597 ((and (looking-at org-complex-heading-regexp)
19598 (= (char-after (match-end 1)) ?\ ))
19599 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19600 (point-at-eol)))
19601 (goto-char
19602 (if (eq special t)
19603 (cond ((> pos refpos) refpos)
19604 ((= pos (point)) refpos)
19605 (t (point)))
19606 (cond ((> pos (point)) (point))
19607 ((not (eq last-command this-command)) (point))
19608 (t refpos)))))
19609 ((org-at-item-p)
19610 (goto-char
19611 (if (eq special t)
19612 (cond ((> pos (match-end 0)) (match-end 0))
19613 ((= pos (point)) (match-end 0))
19614 (t (point)))
19615 (cond ((> pos (point)) (point))
19616 ((not (eq last-command this-command)) (point))
19617 (t (match-end 0))))))))
19618 (org-no-warnings
19619 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19621 (defun org-end-of-line (&optional arg)
19622 "Go to the end of the line.
19623 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19624 first attempt, and only move to after the tags when the cursor is already
19625 beyond the end of the headline."
19626 (interactive "P")
19627 (let ((special (if (consp org-special-ctrl-a/e)
19628 (cdr org-special-ctrl-a/e)
19629 org-special-ctrl-a/e)))
19630 (if (or (not special)
19631 (not (org-on-heading-p))
19632 arg)
19633 (call-interactively
19634 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19635 ((fboundp 'move-end-of-line) 'move-end-of-line)
19636 (t 'end-of-line)))
19637 (let ((pos (point)))
19638 (beginning-of-line 1)
19639 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19640 (if (eq special t)
19641 (if (or (< pos (match-beginning 1))
19642 (= pos (match-end 0)))
19643 (goto-char (match-beginning 1))
19644 (goto-char (match-end 0)))
19645 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19646 (goto-char (match-end 0))
19647 (goto-char (match-beginning 1))))
19648 (call-interactively (if (fboundp 'move-end-of-line)
19649 'move-end-of-line
19650 'end-of-line)))))
19651 (org-no-warnings
19652 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19654 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19655 (define-key org-mode-map "\C-e" 'org-end-of-line)
19657 (defun org-backward-sentence (&optional arg)
19658 "Go to beginning of sentence, or beginning of table field.
19659 This will call `backward-sentence' or `org-table-beginning-of-field',
19660 depending on context."
19661 (interactive "P")
19662 (cond
19663 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19664 (t (call-interactively 'backward-sentence))))
19666 (defun org-forward-sentence (&optional arg)
19667 "Go to end of sentence, or end of table field.
19668 This will call `forward-sentence' or `org-table-end-of-field',
19669 depending on context."
19670 (interactive "P")
19671 (cond
19672 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19673 (t (call-interactively 'forward-sentence))))
19675 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19676 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19678 (defun org-kill-line (&optional arg)
19679 "Kill line, to tags or end of line."
19680 (interactive "P")
19681 (cond
19682 ((or (not org-special-ctrl-k)
19683 (bolp)
19684 (not (org-on-heading-p)))
19685 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19686 org-ctrl-k-protect-subtree)
19687 (if (or (eq org-ctrl-k-protect-subtree 'error)
19688 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19689 (error "C-k aborted - would kill hidden subtree")))
19690 (call-interactively 'kill-line))
19691 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19692 (kill-region (point) (match-beginning 1))
19693 (org-set-tags nil t))
19694 (t (kill-region (point) (point-at-eol)))))
19696 (define-key org-mode-map "\C-k" 'org-kill-line)
19698 (defun org-yank (&optional arg)
19699 "Yank. If the kill is a subtree, treat it specially.
19700 This command will look at the current kill and check if is a single
19701 subtree, or a series of subtrees[1]. If it passes the test, and if the
19702 cursor is at the beginning of a line or after the stars of a currently
19703 empty headline, then the yank is handled specially. How exactly depends
19704 on the value of the following variables, both set by default.
19706 org-yank-folded-subtrees
19707 When set, the subtree(s) will be folded after insertion, but only
19708 if doing so would now swallow text after the yanked text.
19710 org-yank-adjusted-subtrees
19711 When set, the subtree will be promoted or demoted in order to
19712 fit into the local outline tree structure, which means that the level
19713 will be adjusted so that it becomes the smaller one of the two
19714 *visible* surrounding headings.
19716 Any prefix to this command will cause `yank' to be called directly with
19717 no special treatment. In particular, a simple \\[universal-argument] prefix \
19718 will just
19719 plainly yank the text as it is.
19721 \[1] The test checks if the first non-white line is a heading
19722 and if there are no other headings with fewer stars."
19723 (interactive "P")
19724 (org-yank-generic 'yank arg))
19726 (defun org-yank-generic (command arg)
19727 "Perform some yank-like command.
19729 This function implements the behavior described in the `org-yank'
19730 documentation. However, it has been generalized to work for any
19731 interactive command with similar behavior."
19733 ;; pretend to be command COMMAND
19734 (setq this-command command)
19736 (if arg
19737 (call-interactively command)
19739 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19740 (and (org-kill-is-subtree-p)
19741 (or (bolp)
19742 (and (looking-at "[ \t]*$")
19743 (string-match
19744 "\\`\\*+\\'"
19745 (buffer-substring (point-at-bol) (point)))))))
19746 swallowp)
19747 (cond
19748 ((and subtreep org-yank-folded-subtrees)
19749 (let ((beg (point))
19750 end)
19751 (if (and subtreep org-yank-adjusted-subtrees)
19752 (org-paste-subtree nil nil 'for-yank)
19753 (call-interactively command))
19755 (setq end (point))
19756 (goto-char beg)
19757 (when (and (bolp) subtreep
19758 (not (setq swallowp
19759 (org-yank-folding-would-swallow-text beg end))))
19760 (or (looking-at outline-regexp)
19761 (re-search-forward (concat "^" outline-regexp) end t))
19762 (while (and (< (point) end) (looking-at outline-regexp))
19763 (hide-subtree)
19764 (org-cycle-show-empty-lines 'folded)
19765 (condition-case nil
19766 (outline-forward-same-level 1)
19767 (error (goto-char end)))))
19768 (when swallowp
19769 (message
19770 "Inserted text not folded because that would swallow text"))
19772 (goto-char end)
19773 (skip-chars-forward " \t\n\r")
19774 (beginning-of-line 1)
19775 (push-mark beg 'nomsg)))
19776 ((and subtreep org-yank-adjusted-subtrees)
19777 (let ((beg (point-at-bol)))
19778 (org-paste-subtree nil nil 'for-yank)
19779 (push-mark beg 'nomsg)))
19781 (call-interactively command))))))
19783 (defun org-yank-folding-would-swallow-text (beg end)
19784 "Would hide-subtree at BEG swallow any text after END?"
19785 (let (level)
19786 (save-excursion
19787 (goto-char beg)
19788 (when (or (looking-at outline-regexp)
19789 (re-search-forward (concat "^" outline-regexp) end t))
19790 (setq level (org-outline-level)))
19791 (goto-char end)
19792 (skip-chars-forward " \t\r\n\v\f")
19793 (if (or (eobp)
19794 (and (bolp) (looking-at org-outline-regexp)
19795 (<= (org-outline-level) level)))
19796 nil ; Nothing would be swallowed
19797 t)))) ; something would swallow
19799 (define-key org-mode-map "\C-y" 'org-yank)
19801 (defun org-truely-invisible-p ()
19802 "Check if point is at a character currently not visible.
19803 This version does not only check the character property, but also
19804 `visible-mode'."
19805 ;; Early versions of noutline don't have `outline-invisible-p'.
19806 (if (org-bound-and-true-p visible-mode)
19808 (outline-invisible-p)))
19810 (defun org-invisible-p2 ()
19811 "Check if point is at a character currently not visible."
19812 (save-excursion
19813 (if (and (eolp) (not (bobp))) (backward-char 1))
19814 ;; Early versions of noutline don't have `outline-invisible-p'.
19815 (outline-invisible-p)))
19817 (defun org-back-to-heading (&optional invisible-ok)
19818 "Call `outline-back-to-heading', but provide a better error message."
19819 (condition-case nil
19820 (outline-back-to-heading invisible-ok)
19821 (error (error "Before first headline at position %d in buffer %s"
19822 (point) (current-buffer)))))
19824 (defun org-beginning-of-defun ()
19825 "Go to the beginning of the subtree, i.e. back to the heading."
19826 (org-back-to-heading))
19827 (defun org-end-of-defun ()
19828 "Go to the end of the subtree."
19829 (org-end-of-subtree nil t))
19831 (defun org-before-first-heading-p ()
19832 "Before first heading?"
19833 (save-excursion
19834 (end-of-line)
19835 (null (re-search-backward "^\\*+ " nil t))))
19837 (defun org-on-heading-p (&optional ignored)
19838 (outline-on-heading-p t))
19839 (defun org-at-heading-p (&optional ignored)
19840 (outline-on-heading-p t))
19842 (defun org-point-at-end-of-empty-headline ()
19843 "If point is at the end of an empty headline, return t, else nil.
19844 If the heading only contains a TODO keyword, it is still still considered
19845 empty."
19846 (and (looking-at "[ \t]*$")
19847 (save-excursion
19848 (beginning-of-line 1)
19849 (let ((case-fold-search nil))
19850 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19851 "\\)?[ \t]*$"))))))
19852 (defun org-at-heading-or-item-p ()
19853 (or (org-on-heading-p) (org-at-item-p)))
19855 (defun org-on-target-p ()
19856 (or (org-in-regexp org-radio-target-regexp)
19857 (org-in-regexp org-target-regexp)))
19859 (defun org-up-heading-all (arg)
19860 "Move to the heading line of which the present line is a subheading.
19861 This function considers both visible and invisible heading lines.
19862 With argument, move up ARG levels."
19863 (if (fboundp 'outline-up-heading-all)
19864 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19865 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19867 (defun org-up-heading-safe ()
19868 "Move to the heading line of which the present line is a subheading.
19869 This version will not throw an error. It will return the level of the
19870 headline found, or nil if no higher level is found.
19872 Also, this function will be a lot faster than `outline-up-heading',
19873 because it relies on stars being the outline starters. This can really
19874 make a significant difference in outlines with very many siblings."
19875 (let (start-level re)
19876 (org-back-to-heading t)
19877 (setq start-level (funcall outline-level))
19878 (if (equal start-level 1)
19880 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19881 (if (re-search-backward re nil t)
19882 (funcall outline-level)))))
19884 (defun org-first-sibling-p ()
19885 "Is this heading the first child of its parents?"
19886 (interactive)
19887 (let ((re (concat "^" outline-regexp))
19888 level l)
19889 (unless (org-at-heading-p t)
19890 (error "Not at a heading"))
19891 (setq level (funcall outline-level))
19892 (save-excursion
19893 (if (not (re-search-backward re nil t))
19895 (setq l (funcall outline-level))
19896 (< l level)))))
19898 (defun org-goto-sibling (&optional previous)
19899 "Goto the next sibling, even if it is invisible.
19900 When PREVIOUS is set, go to the previous sibling instead. Returns t
19901 when a sibling was found. When none is found, return nil and don't
19902 move point."
19903 (let ((fun (if previous 're-search-backward 're-search-forward))
19904 (pos (point))
19905 (re (concat "^" outline-regexp))
19906 level l)
19907 (when (condition-case nil (org-back-to-heading t) (error nil))
19908 (setq level (funcall outline-level))
19909 (catch 'exit
19910 (or previous (forward-char 1))
19911 (while (funcall fun re nil t)
19912 (setq l (funcall outline-level))
19913 (when (< l level) (goto-char pos) (throw 'exit nil))
19914 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19915 (goto-char pos)
19916 nil))))
19918 (defun org-show-siblings ()
19919 "Show all siblings of the current headline."
19920 (save-excursion
19921 (while (org-goto-sibling) (org-flag-heading nil)))
19922 (save-excursion
19923 (while (org-goto-sibling 'previous)
19924 (org-flag-heading nil))))
19926 (defun org-goto-first-child ()
19927 "Goto the first child, even if it is invisible.
19928 Return t when a child was found. Otherwise don't move point and
19929 return nil."
19930 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19931 (when (condition-case nil (org-back-to-heading t) (error nil))
19932 (setq level (outline-level))
19933 (forward-char 1)
19934 (if (and (re-search-forward re nil t) (> (outline-level) level))
19935 (progn (goto-char (match-beginning 0)) t)
19936 (goto-char pos) nil))))
19938 (defun org-show-hidden-entry ()
19939 "Show an entry where even the heading is hidden."
19940 (save-excursion
19941 (org-show-entry)))
19943 (defun org-flag-heading (flag &optional entry)
19944 "Flag the current heading. FLAG non-nil means make invisible.
19945 When ENTRY is non-nil, show the entire entry."
19946 (save-excursion
19947 (org-back-to-heading t)
19948 ;; Check if we should show the entire entry
19949 (if entry
19950 (progn
19951 (org-show-entry)
19952 (save-excursion
19953 (and (outline-next-heading)
19954 (org-flag-heading nil))))
19955 (outline-flag-region (max (point-min) (1- (point)))
19956 (save-excursion (outline-end-of-heading) (point))
19957 flag))))
19959 (defun org-get-next-sibling ()
19960 "Move to next heading of the same level, and return point.
19961 If there is no such heading, return nil.
19962 This is like outline-next-sibling, but invisible headings are ok."
19963 (let ((level (funcall outline-level)))
19964 (outline-next-heading)
19965 (while (and (not (eobp)) (> (funcall outline-level) level))
19966 (outline-next-heading))
19967 (if (or (eobp) (< (funcall outline-level) level))
19969 (point))))
19971 (defun org-get-last-sibling ()
19972 "Move to previous heading of the same level, and return point.
19973 If there is no such heading, return nil."
19974 (let ((opoint (point))
19975 (level (funcall outline-level)))
19976 (outline-previous-heading)
19977 (when (and (/= (point) opoint) (outline-on-heading-p t))
19978 (while (and (> (funcall outline-level) level)
19979 (not (bobp)))
19980 (outline-previous-heading))
19981 (if (< (funcall outline-level) level)
19983 (point)))))
19985 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19986 ;; This contains an exact copy of the original function, but it uses
19987 ;; `org-back-to-heading', to make it work also in invisible
19988 ;; trees. And is uses an invisible-OK argument.
19989 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19990 ;; Furthermore, when used inside Org, finding the end of a large subtree
19991 ;; with many children and grandchildren etc, this can be much faster
19992 ;; than the outline version.
19993 (org-back-to-heading invisible-OK)
19994 (let ((first t)
19995 (level (funcall outline-level)))
19996 (if (and (org-mode-p) (< level 1000))
19997 ;; A true heading (not a plain list item), in Org-mode
19998 ;; This means we can easily find the end by looking
19999 ;; only for the right number of stars. Using a regexp to do
20000 ;; this is so much faster than using a Lisp loop.
20001 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20002 (forward-char 1)
20003 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20004 ;; something else, do it the slow way
20005 (while (and (not (eobp))
20006 (or first (> (funcall outline-level) level)))
20007 (setq first nil)
20008 (outline-next-heading)))
20009 (unless to-heading
20010 (if (memq (preceding-char) '(?\n ?\^M))
20011 (progn
20012 ;; Go to end of line before heading
20013 (forward-char -1)
20014 (if (memq (preceding-char) '(?\n ?\^M))
20015 ;; leave blank line before heading
20016 (forward-char -1))))))
20017 (point))
20019 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20020 "Use Org version in org-mode, for dramatic speed-up."
20021 (if (org-mode-p)
20022 (progn
20023 (org-end-of-subtree nil t)
20024 (unless (eobp) (backward-char 1)))
20025 ad-do-it))
20027 (defun org-end-of-meta-data-and-drawers ()
20028 "Jump to the first text after meta data and drawers in the current entry.
20029 This will move over empty lines, lines with planning time stamps,
20030 clocking lines, and drawers."
20031 (org-back-to-heading t)
20032 (let ((end (save-excursion (outline-next-heading) (point)))
20033 (re (concat "[ \t]*$"
20034 "\\|" org-drawer-regexp
20035 "\\|" "[ \t]*" org-keyword-time-regexp)))
20036 (while (re-search-forward re end 'move)
20037 (forward-line 1))))
20039 (defun org-forward-same-level (arg &optional invisible-ok)
20040 "Move forward to the arg'th subheading at same level as this one.
20041 Stop at the first and last subheadings of a superior heading.
20042 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20043 it wil also look at invisible ones."
20044 (interactive "p")
20045 (org-back-to-heading invisible-ok)
20046 (org-on-heading-p)
20047 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20048 (re (format "^\\*\\{1,%d\\} " level))
20050 (forward-char 1)
20051 (while (> arg 0)
20052 (while (and (re-search-forward re nil 'move)
20053 (setq l (- (match-end 0) (match-beginning 0) 1))
20054 (= l level)
20055 (not invisible-ok)
20056 (progn (backward-char 1) (outline-invisible-p)))
20057 (if (< l level) (setq arg 1)))
20058 (setq arg (1- arg)))
20059 (beginning-of-line 1)))
20061 (defun org-backward-same-level (arg &optional invisible-ok)
20062 "Move backward to the arg'th subheading at same level as this one.
20063 Stop at the first and last subheadings of a superior heading."
20064 (interactive "p")
20065 (org-back-to-heading)
20066 (org-on-heading-p)
20067 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20068 (re (format "^\\*\\{1,%d\\} " level))
20070 (while (> arg 0)
20071 (while (and (re-search-backward re nil 'move)
20072 (setq l (- (match-end 0) (match-beginning 0) 1))
20073 (= l level)
20074 (not invisible-ok)
20075 (outline-invisible-p))
20076 (if (< l level) (setq arg 1)))
20077 (setq arg (1- arg)))))
20079 (defun org-show-subtree ()
20080 "Show everything after this heading at deeper levels."
20081 (outline-flag-region
20082 (point)
20083 (save-excursion
20084 (org-end-of-subtree t t))
20085 nil))
20087 (defun org-show-entry ()
20088 "Show the body directly following this heading.
20089 Show the heading too, if it is currently invisible."
20090 (interactive)
20091 (save-excursion
20092 (condition-case nil
20093 (progn
20094 (org-back-to-heading t)
20095 (outline-flag-region
20096 (max (point-min) (1- (point)))
20097 (save-excursion
20098 (if (re-search-forward
20099 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20100 (match-beginning 1)
20101 (point-max)))
20102 nil)
20103 (org-cycle-hide-drawers 'children))
20104 (error nil))))
20106 (defun org-make-options-regexp (kwds &optional extra)
20107 "Make a regular expression for keyword lines."
20108 (concat
20110 "#?[ \t]*\\+\\("
20111 (mapconcat 'regexp-quote kwds "\\|")
20112 (if extra (concat "\\|" extra))
20113 "\\):[ \t]*"
20114 "\\(.*\\)"))
20116 ;; Make isearch reveal the necessary context
20117 (defun org-isearch-end ()
20118 "Reveal context after isearch exits."
20119 (when isearch-success ; only if search was successful
20120 (if (featurep 'xemacs)
20121 ;; Under XEmacs, the hook is run in the correct place,
20122 ;; we directly show the context.
20123 (org-show-context 'isearch)
20124 ;; In Emacs the hook runs *before* restoring the overlays.
20125 ;; So we have to use a one-time post-command-hook to do this.
20126 ;; (Emacs 22 has a special variable, see function `org-mode')
20127 (unless (and (boundp 'isearch-mode-end-hook-quit)
20128 isearch-mode-end-hook-quit)
20129 ;; Only when the isearch was not quitted.
20130 (org-add-hook 'post-command-hook 'org-isearch-post-command
20131 'append 'local)))))
20133 (defun org-isearch-post-command ()
20134 "Remove self from hook, and show context."
20135 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20136 (org-show-context 'isearch))
20139 ;;;; Integration with and fixes for other packages
20141 ;;; Imenu support
20143 (defvar org-imenu-markers nil
20144 "All markers currently used by Imenu.")
20145 (make-variable-buffer-local 'org-imenu-markers)
20147 (defun org-imenu-new-marker (&optional pos)
20148 "Return a new marker for use by Imenu, and remember the marker."
20149 (let ((m (make-marker)))
20150 (move-marker m (or pos (point)))
20151 (push m org-imenu-markers)
20154 (defun org-imenu-get-tree ()
20155 "Produce the index for Imenu."
20156 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20157 (setq org-imenu-markers nil)
20158 (let* ((n org-imenu-depth)
20159 (re (concat "^" outline-regexp))
20160 (subs (make-vector (1+ n) nil))
20161 (last-level 0)
20162 m level head)
20163 (save-excursion
20164 (save-restriction
20165 (widen)
20166 (goto-char (point-max))
20167 (while (re-search-backward re nil t)
20168 (setq level (org-reduced-level (funcall outline-level)))
20169 (when (<= level n)
20170 (looking-at org-complex-heading-regexp)
20171 (setq head (org-link-display-format
20172 (org-match-string-no-properties 4))
20173 m (org-imenu-new-marker))
20174 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20175 (if (>= level last-level)
20176 (push (cons head m) (aref subs level))
20177 (push (cons head (aref subs (1+ level))) (aref subs level))
20178 (loop for i from (1+ level) to n do (aset subs i nil)))
20179 (setq last-level level)))))
20180 (aref subs 1)))
20182 (eval-after-load "imenu"
20183 '(progn
20184 (add-hook 'imenu-after-jump-hook
20185 (lambda ()
20186 (if (org-mode-p)
20187 (org-show-context 'org-goto))))))
20189 (defun org-link-display-format (link)
20190 "Replace a link with either the description, or the link target
20191 if no description is present"
20192 (save-match-data
20193 (if (string-match org-bracket-link-analytic-regexp link)
20194 (replace-match (if (match-end 5)
20195 (match-string 5 link)
20196 (concat (match-string 1 link)
20197 (match-string 3 link)))
20198 nil t link)
20199 link)))
20201 ;; Speedbar support
20203 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20204 "Overlay marking the agenda restriction line in speedbar.")
20205 (overlay-put org-speedbar-restriction-lock-overlay
20206 'face 'org-agenda-restriction-lock)
20207 (overlay-put org-speedbar-restriction-lock-overlay
20208 'help-echo "Agendas are currently limited to this item.")
20209 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20211 (defun org-speedbar-set-agenda-restriction ()
20212 "Restrict future agenda commands to the location at point in speedbar.
20213 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20214 (interactive)
20215 (require 'org-agenda)
20216 (let (p m tp np dir txt)
20217 (cond
20218 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20219 'org-imenu t))
20220 (setq m (get-text-property p 'org-imenu-marker))
20221 (with-current-buffer (marker-buffer m)
20222 (goto-char m)
20223 (org-agenda-set-restriction-lock 'subtree)))
20224 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20225 'speedbar-function 'speedbar-find-file))
20226 (setq tp (previous-single-property-change
20227 (1+ p) 'speedbar-function)
20228 np (next-single-property-change
20229 tp 'speedbar-function)
20230 dir (speedbar-line-directory)
20231 txt (buffer-substring-no-properties (or tp (point-min))
20232 (or np (point-max))))
20233 (with-current-buffer (find-file-noselect
20234 (let ((default-directory dir))
20235 (expand-file-name txt)))
20236 (unless (org-mode-p)
20237 (error "Cannot restrict to non-Org-mode file"))
20238 (org-agenda-set-restriction-lock 'file)))
20239 (t (error "Don't know how to restrict Org-mode's agenda")))
20240 (move-overlay org-speedbar-restriction-lock-overlay
20241 (point-at-bol) (point-at-eol))
20242 (setq current-prefix-arg nil)
20243 (org-agenda-maybe-redo)))
20245 (eval-after-load "speedbar"
20246 '(progn
20247 (speedbar-add-supported-extension ".org")
20248 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20249 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20250 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20251 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20252 (add-hook 'speedbar-visiting-tag-hook
20253 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20255 ;;; Fixes and Hacks for problems with other packages
20257 ;; Make flyspell not check words in links, to not mess up our keymap
20258 (defun org-mode-flyspell-verify ()
20259 "Don't let flyspell put overlays at active buttons, or on
20260 {todo,all-time,additional-option-like}-keywords."
20261 (let ((pos (max (1- (point)) (point-min)))
20262 (word (thing-at-point 'word)))
20263 (and (not (get-text-property pos 'keymap))
20264 (not (get-text-property pos 'org-no-flyspell))
20265 (not (member word org-todo-keywords-1))
20266 (not (member word org-all-time-keywords))
20267 (not (member word org-additional-option-like-keywords)))))
20269 (defun org-remove-flyspell-overlays-in (beg end)
20270 "Remove flyspell overlays in region."
20271 (and (org-bound-and-true-p flyspell-mode)
20272 (fboundp 'flyspell-delete-region-overlays)
20273 (flyspell-delete-region-overlays beg end))
20274 (add-text-properties beg end '(org-no-flyspell t)))
20276 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20277 (eval-after-load "bookmark"
20278 '(if (boundp 'bookmark-after-jump-hook)
20279 ;; We can use the hook
20280 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20281 ;; Hook not available, use advice
20282 (defadvice bookmark-jump (after org-make-visible activate)
20283 "Make the position visible."
20284 (org-bookmark-jump-unhide))))
20286 ;; Make sure saveplace shows the location if it was hidden
20287 (eval-after-load "saveplace"
20288 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20289 "Make the position visible."
20290 (org-bookmark-jump-unhide)))
20292 ;; Make sure ecb shows the location if it was hidden
20293 (eval-after-load "ecb"
20294 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20295 "Make hierarchy visible when jumping into location from ECB tree buffer."
20296 (if (org-mode-p)
20297 (org-show-context))))
20299 (defun org-bookmark-jump-unhide ()
20300 "Unhide the current position, to show the bookmark location."
20301 (and (org-mode-p)
20302 (or (outline-invisible-p)
20303 (save-excursion (goto-char (max (point-min) (1- (point))))
20304 (outline-invisible-p)))
20305 (org-show-context 'bookmark-jump)))
20307 ;; Make session.el ignore our circular variable
20308 (eval-after-load "session"
20309 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20311 ;;;; Experimental code
20313 (defun org-closed-in-range ()
20314 "Sparse tree of items closed in a certain time range.
20315 Still experimental, may disappear in the future."
20316 (interactive)
20317 ;; Get the time interval from the user.
20318 (let* ((time1 (org-float-time
20319 (org-read-date nil 'to-time nil "Starting date: ")))
20320 (time2 (org-float-time
20321 (org-read-date nil 'to-time nil "End date:")))
20322 ;; callback function
20323 (callback (lambda ()
20324 (let ((time
20325 (org-float-time
20326 (apply 'encode-time
20327 (org-parse-time-string
20328 (match-string 1))))))
20329 ;; check if time in interval
20330 (and (>= time time1) (<= time time2))))))
20331 ;; make tree, check each match with the callback
20332 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20334 ;;;; Finish up
20336 (provide 'org)
20338 (run-hooks 'org-load-hook)
20340 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20342 ;;; org.el ends here