org.el (org-display-inline-images): allow more characters for image filenames.
[org-mode.git] / lisp / org.el
blobb00a0d5c6791f34596d805ca1281acb30e930fb5
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
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: 6.36trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
79 (unless (boundp 'calendar-view-holidays-initially-flag)
80 (defvaralias 'calendar-view-holidays-initially-flag
81 'view-calendar-holidays-initially))
82 (unless (boundp 'calendar-view-diary-initially-flag)
83 (defvaralias 'calendar-view-diary-initially-flag
84 'view-diary-entries-initially))
85 (unless (boundp 'diary-fancy-buffer)
86 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
88 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
89 ;; the file noutline.el being loaded.
90 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
91 ;; We require noutline, which might be provided in outline.el
92 (require 'outline) (require 'noutline)
93 ;; Other stuff we need.
94 (require 'time-date)
95 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
96 (require 'easymenu)
97 (require 'overlay)
99 (require 'org-macs)
100 (require 'org-entities)
101 (require 'org-compat)
102 (require 'org-faces)
103 (require 'org-list)
104 (require 'org-src)
105 (require 'org-footnote)
107 ;;;; Customization variables
108 (defcustom org-clone-delete-id nil
109 "Remove ID property of clones of a subtree.
110 When non-nil, clones of a subtree don't inherit the ID property.
111 Otherwise they inherit the ID property with a new unique
112 identifier."
113 :type 'boolean
114 :group 'org-id)
116 ;;; Version
118 (defconst org-version "6.36trans"
119 "The version number of the file org.el.")
121 (defun org-version (&optional here)
122 "Show the org-mode version in the echo area.
123 With prefix arg HERE, insert it at point."
124 (interactive "P")
125 (let* ((origin default-directory)
126 (version org-version)
127 (git-version)
128 (dir (concat (file-name-directory (locate-library "org")) "../" )))
129 (when (and (file-exists-p (expand-file-name ".git" dir))
130 (executable-find "git"))
131 (unwind-protect
132 (progn
133 (cd dir)
134 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
135 (with-current-buffer "*Shell Command Output*"
136 (goto-char (point-min))
137 (setq git-version (buffer-substring (point) (point-at-eol))))
138 (subst-char-in-string ?- ?. git-version t)
139 (when (string-match "\\S-"
140 (shell-command-to-string
141 "git diff-index --name-only HEAD --"))
142 (setq git-version (concat git-version ".dirty")))
143 (setq version (concat version " (" git-version ")"))))
144 (cd origin)))
145 (setq version (format "Org-mode version %s" version))
146 (if here (insert version))
147 (message version)))
149 ;;; Compatibility constants
151 ;;; The custom variables
153 (defgroup org nil
154 "Outline-based notes management and organizer."
155 :tag "Org"
156 :group 'outlines
157 :group 'calendar)
159 (defcustom org-mode-hook nil
160 "Mode hook for Org-mode, run after the mode was turned on."
161 :group 'org
162 :type 'hook)
164 (defcustom org-load-hook nil
165 "Hook that is run after org.el has been loaded."
166 :group 'org
167 :type 'hook)
169 (defvar org-modules) ; defined below
170 (defvar org-modules-loaded nil
171 "Have the modules been loaded already?")
173 (defun org-load-modules-maybe (&optional force)
174 "Load all extensions listed in `org-modules'."
175 (when (or force (not org-modules-loaded))
176 (mapc (lambda (ext)
177 (condition-case nil (require ext)
178 (error (message "Problems while trying to load feature `%s'" ext))))
179 org-modules)
180 (setq org-modules-loaded t)))
182 (defun org-set-modules (var value)
183 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
184 (set var value)
185 (when (featurep 'org)
186 (org-load-modules-maybe 'force)))
188 (when (org-bound-and-true-p org-modules)
189 (let ((a (member 'org-infojs org-modules)))
190 (and a (setcar a 'org-jsinfo))))
192 (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)
193 "Modules that should always be loaded together with org.el.
194 If a description starts with <C>, the file is not part of Emacs
195 and loading it will require that you have downloaded and properly installed
196 the org-mode distribution.
198 You can also use this system to load external packages (i.e. neither Org
199 core modules, nor modules from the CONTRIB directory). Just add symbols
200 to the end of the list. If the package is called org-xyz.el, then you need
201 to add the symbol `xyz', and the package must have a call to
203 (provide 'org-xyz)"
204 :group 'org
205 :set 'org-set-modules
206 :type
207 '(set :greedy t
208 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
209 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
210 (const :tag " crypt: Encryption of subtrees" org-crypt)
211 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
212 (const :tag " docview: Links to doc-view buffers" org-docview)
213 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
214 (const :tag " id: Global IDs for identifying entries" org-id)
215 (const :tag " info: Links to Info nodes" org-info)
216 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
217 (const :tag " habit: Track your consistency with habits" org-habit)
218 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
219 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
220 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
221 (const :tag " mew Links to Mew folders/messages" org-mew)
222 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
223 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
224 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
225 (const :tag " vm: Links to VM folders/messages" org-vm)
226 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
227 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
228 (const :tag " mouse: Additional mouse support" org-mouse)
230 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
231 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
232 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
233 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
234 (const :tag "C collector: Collect properties into tables" org-collector)
235 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
236 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
237 (const :tag "C eval: Include command output as text" org-eval)
238 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
239 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
240 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
241 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
242 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
244 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
246 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
247 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
248 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
249 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
250 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
251 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
252 (const :tag "C mtags: Support for muse-like tags" org-mtags)
253 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
254 (const :tag "C registry: A registry for Org-mode links" org-registry)
255 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
256 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
257 (const :tag "C secretary: Team management with org-mode" org-secretary)
258 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
259 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
260 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
261 (const :tag "C track: Keep up with Org-mode development" org-track)
262 (const :tag "C TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
263 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
265 (defcustom org-support-shift-select nil
266 "Non-nil means make shift-cursor commands select text when possible.
268 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
269 selecting a region, or enlarge thusly regions started in this way.
270 In Org-mode, in special contexts, these same keys are used for other
271 purposes, important enough to compete with shift selection. Org tries
272 to balance these needs by supporting `shift-select-mode' outside these
273 special contexts, under control of this variable.
275 The default of this variable is nil, to avoid confusing behavior. Shifted
276 cursor keys will then execute Org commands in the following contexts:
277 - on a headline, changing TODO state (left/right) and priority (up/down)
278 - on a time stamp, changing the time
279 - in a plain list item, changing the bullet type
280 - in a property definition line, switching between allowed values
281 - in the BEGIN line of a clock table (changing the time block).
282 Outside these contexts, the commands will throw an error.
284 When this variable is t and the cursor is not in a special context,
285 Org-mode will support shift-selection for making and enlarging regions.
286 To make this more effective, the bullet cycling will no longer happen
287 anywhere in an item line, but only if the cursor is exactly on the bullet.
289 If you set this variable to the symbol `always', then the keys
290 will not be special in headlines, property lines, and item lines, to make
291 shift selection work there as well. If this is what you want, you can
292 use the following alternative commands: `C-c C-t' and `C-c ,' to
293 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
294 TODO sets, `C-c -' to cycle item bullet types, and properties can be
295 edited by hand or in column view.
297 However, when the cursor is on a timestamp, shift-cursor commands
298 will still edit the time stamp - this is just too good to give up.
300 XEmacs user should have this variable set to nil, because shift-select-mode
301 is Emacs 23 only."
302 :group 'org
303 :type '(choice
304 (const :tag "Never" nil)
305 (const :tag "When outside special context" t)
306 (const :tag "Everywhere except timestamps" always)))
308 (defgroup org-startup nil
309 "Options concerning startup of Org-mode."
310 :tag "Org Startup"
311 :group 'org)
313 (defcustom org-startup-folded t
314 "Non-nil means entering Org-mode will switch to OVERVIEW.
315 This can also be configured on a per-file basis by adding one of
316 the following lines anywhere in the buffer:
318 #+STARTUP: fold (or `overview', this is equivalent)
319 #+STARTUP: nofold (or `showall', this is equivalent)
320 #+STARTUP: content
321 #+STARTUP: showeverything"
322 :group 'org-startup
323 :type '(choice
324 (const :tag "nofold: show all" nil)
325 (const :tag "fold: overview" t)
326 (const :tag "content: all headlines" content)
327 (const :tag "show everything, even drawers" showeverything)))
329 (defcustom org-startup-truncated t
330 "Non-nil means entering Org-mode will set `truncate-lines'.
331 This is useful since some lines containing links can be very long and
332 uninteresting. Also tables look terrible when wrapped."
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-startup-indented nil
337 "Non-nil means turn on `org-indent-mode' on startup.
338 This can also be configured on a per-file basis by adding one of
339 the following lines anywhere in the buffer:
341 #+STARTUP: indent
342 #+STARTUP: noindent"
343 :group 'org-structure
344 :type '(choice
345 (const :tag "Not" nil)
346 (const :tag "Globally (slow on startup in large files)" t)))
348 (defcustom org-use-sub-superscripts t
349 "Non-nil means interpret \"_\" and \"^\" for export.
350 When this option is turned on, you can use TeX-like syntax for sub- and
351 superscripts. Several characters after \"_\" or \"^\" will be
352 considered as a single item - so grouping with {} is normally not
353 needed. For example, the following things will be parsed as single
354 sub- or superscripts.
356 10^24 or 10^tau several digits will be considered 1 item.
357 10^-12 or 10^-tau a leading sign with digits or a word
358 x^2-y^3 will be read as x^2 - y^3, because items are
359 terminated by almost any nonword/nondigit char.
360 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
362 Still, ambiguity is possible - so when in doubt use {} to enclose the
363 sub/superscript. If you set this variable to the symbol `{}',
364 the braces are *required* in order to trigger interpretations as
365 sub/superscript. This can be helpful in documents that need \"_\"
366 frequently in plain text.
368 Not all export backends support this, but HTML does.
370 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
371 :group 'org-startup
372 :group 'org-export-translation
373 :type '(choice
374 (const :tag "Always interpret" t)
375 (const :tag "Only with braces" {})
376 (const :tag "Never interpret" nil)))
378 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts)
381 (defcustom org-startup-with-beamer-mode nil
382 "Non-nil means turn on `org-beamer-mode' on startup.
383 This can also be configured on a per-file basis by adding one of
384 the following lines anywhere in the buffer:
386 #+STARTUP: beamer"
387 :group 'org-startup
388 :type 'boolean)
390 (defcustom org-startup-align-all-tables nil
391 "Non-nil means align all tables when visiting a file.
392 This is useful when the column width in tables is forced with <N> cookies
393 in table fields. Such tables will look correct only after the first re-align.
394 This can also be configured on a per-file basis by adding one of
395 the following lines anywhere in the buffer:
396 #+STARTUP: align
397 #+STARTUP: noalign"
398 :group 'org-startup
399 :type 'boolean)
401 (defcustom org-insert-mode-line-in-empty-file nil
402 "Non-nil means insert the first line setting Org-mode in empty files.
403 When the function `org-mode' is called interactively in an empty file, this
404 normally means that the file name does not automatically trigger Org-mode.
405 To ensure that the file will always be in Org-mode in the future, a
406 line enforcing Org-mode will be inserted into the buffer, if this option
407 has been set."
408 :group 'org-startup
409 :type 'boolean)
411 (defcustom org-replace-disputed-keys nil
412 "Non-nil means use alternative key bindings for some keys.
413 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
414 These keys are also used by other packages like shift-selection-mode'
415 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
416 If you want to use Org-mode together with one of these other modes,
417 or more generally if you would like to move some Org-mode commands to
418 other keys, set this variable and configure the keys with the variable
419 `org-disputed-keys'.
421 This option is only relevant at load-time of Org-mode, and must be set
422 *before* org.el is loaded. Changing it requires a restart of Emacs to
423 become effective."
424 :group 'org-startup
425 :type 'boolean)
427 (defcustom org-use-extra-keys nil
428 "Non-nil means use extra key sequence definitions for certain
429 commands. This happens automatically if you run XEmacs or if
430 window-system is nil. This variable lets you do the same
431 manually. You must set it before loading org.
433 Example: on Carbon Emacs 22 running graphically, with an external
434 keyboard on a Powerbook, the default way of setting M-left might
435 not work for either Alt or ESC. Setting this variable will make
436 it work for ESC."
437 :group 'org-startup
438 :type 'boolean)
440 (if (fboundp 'defvaralias)
441 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
443 (defcustom org-disputed-keys
444 '(([(shift up)] . [(meta p)])
445 ([(shift down)] . [(meta n)])
446 ([(shift left)] . [(meta -)])
447 ([(shift right)] . [(meta +)])
448 ([(control shift right)] . [(meta shift +)])
449 ([(control shift left)] . [(meta shift -)]))
450 "Keys for which Org-mode and other modes compete.
451 This is an alist, cars are the default keys, second element specifies
452 the alternative to use when `org-replace-disputed-keys' is t.
454 Keys can be specified in any syntax supported by `define-key'.
455 The value of this option takes effect only at Org-mode's startup,
456 therefore you'll have to restart Emacs to apply it after changing."
457 :group 'org-startup
458 :type 'alist)
460 (defun org-key (key)
461 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
462 Or return the original if not disputed.
463 Also apply the trnaslations defined in `org-xemacs-key-equivalents'."
464 (when org-replace-disputed-keys
465 (let* ((nkey (key-description key))
466 (x (org-find-if (lambda (x)
467 (equal (key-description (car x)) nkey))
468 org-disputed-keys)))
469 (setq key (if x (cdr x) key))))
470 (when (featurep 'xemacs)
471 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
472 key)
474 (defun org-find-if (predicate seq)
475 (catch 'exit
476 (while seq
477 (if (funcall predicate (car seq))
478 (throw 'exit (car seq))
479 (pop seq)))))
481 (defun org-defkey (keymap key def)
482 "Define a key, possibly translated, as returned by `org-key'."
483 (define-key keymap (org-key key) def))
485 (defcustom org-ellipsis nil
486 "The ellipsis to use in the Org-mode outline.
487 When nil, just use the standard three dots. When a string, use that instead,
488 When a face, use the standard 3 dots, but with the specified face.
489 The change affects only Org-mode (which will then use its own display table).
490 Changing this requires executing `M-x org-mode' in a buffer to become
491 effective."
492 :group 'org-startup
493 :type '(choice (const :tag "Default" nil)
494 (face :tag "Face" :value org-warning)
495 (string :tag "String" :value "...#")))
497 (defvar org-display-table nil
498 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
500 (defgroup org-keywords nil
501 "Keywords in Org-mode."
502 :tag "Org Keywords"
503 :group 'org)
505 (defcustom org-deadline-string "DEADLINE:"
506 "String to mark deadline entries.
507 A deadline is this string, followed by a time stamp. Should be a word,
508 terminated by a colon. You can insert a schedule keyword and
509 a timestamp with \\[org-deadline].
510 Changes become only effective after restarting Emacs."
511 :group 'org-keywords
512 :type 'string)
514 (defcustom org-scheduled-string "SCHEDULED:"
515 "String to mark scheduled TODO entries.
516 A schedule is this string, followed by a time stamp. Should be a word,
517 terminated by a colon. You can insert a schedule keyword and
518 a timestamp with \\[org-schedule].
519 Changes become only effective after restarting Emacs."
520 :group 'org-keywords
521 :type 'string)
523 (defcustom org-closed-string "CLOSED:"
524 "String used as the prefix for timestamps logging closing a TODO entry."
525 :group 'org-keywords
526 :type 'string)
528 (defcustom org-clock-string "CLOCK:"
529 "String used as prefix for timestamps clocking work hours on an item."
530 :group 'org-keywords
531 :type 'string)
533 (defcustom org-comment-string "COMMENT"
534 "Entries starting with this keyword will never be exported.
535 An entry can be toggled between COMMENT and normal with
536 \\[org-toggle-comment].
537 Changes become only effective after restarting Emacs."
538 :group 'org-keywords
539 :type 'string)
541 (defcustom org-quote-string "QUOTE"
542 "Entries starting with this keyword will be exported in fixed-width font.
543 Quoting applies only to the text in the entry following the headline, and does
544 not extend beyond the next headline, even if that is lower level.
545 An entry can be toggled between QUOTE and normal with
546 \\[org-toggle-fixed-width-section]."
547 :group 'org-keywords
548 :type 'string)
550 (defconst org-repeat-re
551 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
552 "Regular expression for specifying repeated events.
553 After a match, group 1 contains the repeat expression.")
555 (defgroup org-structure nil
556 "Options concerning the general structure of Org-mode files."
557 :tag "Org Structure"
558 :group 'org)
560 (defgroup org-reveal-location nil
561 "Options about how to make context of a location visible."
562 :tag "Org Reveal Location"
563 :group 'org-structure)
565 (defconst org-context-choice
566 '(choice
567 (const :tag "Always" t)
568 (const :tag "Never" nil)
569 (repeat :greedy t :tag "Individual contexts"
570 (cons
571 (choice :tag "Context"
572 (const agenda)
573 (const org-goto)
574 (const occur-tree)
575 (const tags-tree)
576 (const link-search)
577 (const mark-goto)
578 (const bookmark-jump)
579 (const isearch)
580 (const default))
581 (boolean))))
582 "Contexts for the reveal options.")
584 (defcustom org-show-hierarchy-above '((default . t))
585 "Non-nil means show full hierarchy when revealing a location.
586 Org-mode often shows locations in an org-mode file which might have
587 been invisible before. When this is set, the hierarchy of headings
588 above the exposed location is shown.
589 Turning this off for example for sparse trees makes them very compact.
590 Instead of t, this can also be an alist specifying this option for different
591 contexts. Valid contexts are
592 agenda when exposing an entry from the agenda
593 org-goto when using the command `org-goto' on key C-c C-j
594 occur-tree when using the command `org-occur' on key C-c /
595 tags-tree when constructing a sparse tree based on tags matches
596 link-search when exposing search matches associated with a link
597 mark-goto when exposing the jump goal of a mark
598 bookmark-jump when exposing a bookmark location
599 isearch when exiting from an incremental search
600 default default for all contexts not set explicitly"
601 :group 'org-reveal-location
602 :type org-context-choice)
604 (defcustom org-show-following-heading '((default . nil))
605 "Non-nil means show following heading when revealing a location.
606 Org-mode often shows locations in an org-mode file which might have
607 been invisible before. When this is set, the heading following the
608 match is shown.
609 Turning this off for example for sparse trees makes them very compact,
610 but makes it harder to edit the location of the match. In such a case,
611 use the command \\[org-reveal] to show more context.
612 Instead of t, this can also be an alist specifying this option for different
613 contexts. See `org-show-hierarchy-above' for valid contexts."
614 :group 'org-reveal-location
615 :type org-context-choice)
617 (defcustom org-show-siblings '((default . nil) (isearch t))
618 "Non-nil means show all sibling heading when revealing a location.
619 Org-mode often shows locations in an org-mode file which might have
620 been invisible before. When this is set, the sibling of the current entry
621 heading are all made visible. If `org-show-hierarchy-above' is t,
622 the same happens on each level of the hierarchy above the current entry.
624 By default this is on for the isearch context, off for all other contexts.
625 Turning this off for example for sparse trees makes them very compact,
626 but makes it harder to edit the location of the match. In such a case,
627 use the command \\[org-reveal] to show more context.
628 Instead of t, this can also be an alist specifying this option for different
629 contexts. See `org-show-hierarchy-above' for valid contexts."
630 :group 'org-reveal-location
631 :type org-context-choice)
633 (defcustom org-show-entry-below '((default . nil))
634 "Non-nil means show the entry below a headline when revealing a location.
635 Org-mode often shows locations in an org-mode file which might have
636 been invisible before. When this is set, the text below the headline that is
637 exposed is also shown.
639 By default this is off for all contexts.
640 Instead of t, this can also be an alist specifying this option for different
641 contexts. See `org-show-hierarchy-above' for valid contexts."
642 :group 'org-reveal-location
643 :type org-context-choice)
645 (defcustom org-indirect-buffer-display 'other-window
646 "How should indirect tree buffers be displayed?
647 This applies to indirect buffers created with the commands
648 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
649 Valid values are:
650 current-window Display in the current window
651 other-window Just display in another window.
652 dedicated-frame Create one new frame, and re-use it each time.
653 new-frame Make a new frame each time. Note that in this case
654 previously-made indirect buffers are kept, and you need to
655 kill these buffers yourself."
656 :group 'org-structure
657 :group 'org-agenda-windows
658 :type '(choice
659 (const :tag "In current window" current-window)
660 (const :tag "In current frame, other window" other-window)
661 (const :tag "Each time a new frame" new-frame)
662 (const :tag "One dedicated frame" dedicated-frame)))
664 (defcustom org-use-speed-commands nil
665 "Non-nil means activate single letter commands at beginning of a headline.
666 This may also be a function to test for appropriate locations where speed
667 commands should be active."
668 :group 'org-structure
669 :type '(choice
670 (const :tag "Never" nil)
671 (const :tag "At beginning of headline stars" t)
672 (function)))
674 (defcustom org-speed-commands-user nil
675 "Alist of additional speed commands.
676 This list will be checked before `org-speed-commands-default'
677 when the variable `org-use-speed-commands' is non-nil
678 and when the cursor is at the beginning of a headline.
679 The car if each entry is a string with a single letter, which must
680 be assigned to `self-insert-command' in the global map.
681 The cdr is either a command to be called interactively, a function
682 to be called, or a form to be evaluated.
683 An entry that is just a list with a single string will be interpreted
684 as a descriptive headline that will be added when listing the speed
685 copmmands in the Help buffer using the `?' speed command."
686 :group 'org-structure
687 :type '(repeat :value ("k" . ignore)
688 (choice :value ("k" . ignore)
689 (list :tag "Descriptive Headline" (string :tag "Headline"))
690 (cons :tag "Letter and Command"
691 (string :tag "Command letter")
692 (choice
693 (function)
694 (sexp))))))
696 (defgroup org-cycle nil
697 "Options concerning visibility cycling in Org-mode."
698 :tag "Org Cycle"
699 :group 'org-structure)
701 (defcustom org-cycle-skip-children-state-if-no-children t
702 "Non-nil means skip CHILDREN state in entries that don't have any."
703 :group 'org-cycle
704 :type 'boolean)
706 (defcustom org-cycle-max-level nil
707 "Maximum level which should still be subject to visibility cycling.
708 Levels higher than this will, for cycling, be treated as text, not a headline.
709 When `org-odd-levels-only' is set, a value of N in this variable actually
710 means 2N-1 stars as the limiting headline.
711 When nil, cycle all levels.
712 Note that the limiting level of cycling is also influenced by
713 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
714 `org-inlinetask-min-level' is, cycling will be limited to levels one less
715 than its value."
716 :group 'org-cycle
717 :type '(choice
718 (const :tag "No limit" nil)
719 (integer :tag "Maximum level")))
721 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
722 "Names of drawers. Drawers are not opened by cycling on the headline above.
723 Drawers only open with a TAB on the drawer line itself. A drawer looks like
724 this:
725 :DRAWERNAME:
726 .....
727 :END:
728 The drawer \"PROPERTIES\" is special for capturing properties through
729 the property API.
731 Drawers can be defined on the per-file basis with a line like:
733 #+DRAWERS: HIDDEN STATE PROPERTIES"
734 :group 'org-structure
735 :group 'org-cycle
736 :type '(repeat (string :tag "Drawer Name")))
738 (defcustom org-hide-block-startup nil
739 "Non-nil means entering Org-mode will fold all blocks.
740 This can also be set in on a per-file basis with
742 #+STARTUP: hideblocks
743 #+STARTUP: showblocks"
744 :group 'org-startup
745 :group 'org-cycle
746 :type 'boolean)
748 (defcustom org-cycle-global-at-bob nil
749 "Cycle globally if cursor is at beginning of buffer and not at a headline.
750 This makes it possible to do global cycling without having to use S-TAB or
751 C-u TAB. For this special case to work, the first line of the buffer
752 must not be a headline - it may be empty or some other text. When used in
753 this way, `org-cycle-hook' is disables temporarily, to make sure the
754 cursor stays at the beginning of the buffer.
755 When this option is nil, don't do anything special at the beginning
756 of the buffer."
757 :group 'org-cycle
758 :type 'boolean)
760 (defcustom org-cycle-level-after-item/entry-creation t
761 "Non-nil means cycle entry level or item indentation in new empty entries.
763 When the cursor is at the end of an empty headline, i.e with only stars
764 and maybe a TODO keyword, TAB will then switch the entry to become a child,
765 and then all possible anchestor states, before returning to the original state.
766 This makes data entry extremely fast: M-RET to create a new headline,
767 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
769 When the cursor is at the end of an empty plain list item, one TAB will
770 make it a subitem, two or more tabs will back up to make this an item
771 higher up in the item hierarchy."
772 :group 'org-cycle
773 :type 'boolean)
775 (defcustom org-cycle-emulate-tab t
776 "Where should `org-cycle' emulate TAB.
777 nil Never
778 white Only in completely white lines
779 whitestart Only at the beginning of lines, before the first non-white char
780 t Everywhere except in headlines
781 exc-hl-bol Everywhere except at the start of a headline
782 If TAB is used in a place where it does not emulate TAB, the current subtree
783 visibility is cycled."
784 :group 'org-cycle
785 :type '(choice (const :tag "Never" nil)
786 (const :tag "Only in completely white lines" white)
787 (const :tag "Before first char in a line" whitestart)
788 (const :tag "Everywhere except in headlines" t)
789 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
792 (defcustom org-cycle-separator-lines 2
793 "Number of empty lines needed to keep an empty line between collapsed trees.
794 If you leave an empty line between the end of a subtree and the following
795 headline, this empty line is hidden when the subtree is folded.
796 Org-mode will leave (exactly) one empty line visible if the number of
797 empty lines is equal or larger to the number given in this variable.
798 So the default 2 means at least 2 empty lines after the end of a subtree
799 are needed to produce free space between a collapsed subtree and the
800 following headline.
802 If the number is negative, and the number of empty lines is at least -N,
803 all empty lines are shown.
805 Special case: when 0, never leave empty lines in collapsed view."
806 :group 'org-cycle
807 :type 'integer)
808 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
810 (defcustom org-pre-cycle-hook nil
811 "Hook that is run before visibility cycling is happening.
812 The function(s) in this hook must accept a single argument which indicates
813 the new state that will be set right after running this hook. The
814 argument is a symbol. Before a global state change, it can have the values
815 `overview', `content', or `all'. Before a local state change, it can have
816 the values `folded', `children', or `subtree'."
817 :group 'org-cycle
818 :type 'hook)
820 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
821 org-cycle-hide-drawers
822 org-cycle-show-empty-lines
823 org-optimize-window-after-visibility-change)
824 "Hook that is run after `org-cycle' has changed the buffer visibility.
825 The function(s) in this hook must accept a single argument which indicates
826 the new state that was set by the most recent `org-cycle' command. The
827 argument is a symbol. After a global state change, it can have the values
828 `overview', `content', or `all'. After a local state change, it can have
829 the values `folded', `children', or `subtree'."
830 :group 'org-cycle
831 :type 'hook)
833 (defgroup org-edit-structure nil
834 "Options concerning structure editing in Org-mode."
835 :tag "Org Edit Structure"
836 :group 'org-structure)
838 (defcustom org-odd-levels-only nil
839 "Non-nil means skip even levels and only use odd levels for the outline.
840 This has the effect that two stars are being added/taken away in
841 promotion/demotion commands. It also influences how levels are
842 handled by the exporters.
843 Changing it requires restart of `font-lock-mode' to become effective
844 for fontification also in regions already fontified.
845 You may also set this on a per-file basis by adding one of the following
846 lines to the buffer:
848 #+STARTUP: odd
849 #+STARTUP: oddeven"
850 :group 'org-edit-structure
851 :group 'org-appearance
852 :type 'boolean)
854 (defcustom org-adapt-indentation t
855 "Non-nil means adapt indentation to outline node level.
857 When this variable is set, Org assumes that you write outlines by
858 indenting text in each node to align with the headline (after the stars).
859 The following issues are influenced by this variable:
861 - When this is set and the *entire* text in an entry is indented, the
862 indentation is increased by one space in a demotion command, and
863 decreased by one in a promotion command. If any line in the entry
864 body starts with text at column 0, indentation is not changed at all.
866 - Property drawers and planning information is inserted indented when
867 this variable s set. When nil, they will not be indented.
869 - TAB indents a line relative to context. The lines below a headline
870 will be indented when this variable is set.
872 Note that this is all about true indentation, by adding and removing
873 space characters. See also `org-indent.el' which does level-dependent
874 indentation in a virtual way, i.e. at display time in Emacs."
875 :group 'org-edit-structure
876 :type 'boolean)
878 (defcustom org-special-ctrl-a/e nil
879 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
881 When t, `C-a' will bring back the cursor to the beginning of the
882 headline text, i.e. after the stars and after a possible TODO keyword.
883 In an item, this will be the position after the bullet.
884 When the cursor is already at that position, another `C-a' will bring
885 it to the beginning of the line.
887 `C-e' will jump to the end of the headline, ignoring the presence of tags
888 in the headline. A second `C-e' will then jump to the true end of the
889 line, after any tags. This also means that, when this variable is
890 non-nil, `C-e' also will never jump beyond the end of the heading of a
891 folded section, i.e. not after the ellipses.
893 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
894 going to the true line boundary first. Only a directly following, identical
895 keypress will bring the cursor to the special positions.
897 This may also be a cons cell where the behavior for `C-a' and `C-e' is
898 set separately."
899 :group 'org-edit-structure
900 :type '(choice
901 (const :tag "off" nil)
902 (const :tag "on: after stars/bullet and before tags first" t)
903 (const :tag "reversed: true line boundary first" reversed)
904 (cons :tag "Set C-a and C-e separately"
905 (choice :tag "Special C-a"
906 (const :tag "off" nil)
907 (const :tag "on: after stars/bullet first" t)
908 (const :tag "reversed: before stars/bullet first" reversed))
909 (choice :tag "Special C-e"
910 (const :tag "off" nil)
911 (const :tag "on: before tags first" t)
912 (const :tag "reversed: after tags first" reversed)))))
913 (if (fboundp 'defvaralias)
914 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
916 (defcustom org-special-ctrl-k nil
917 "Non-nil means `C-k' will behave specially in headlines.
918 When nil, `C-k' will call the default `kill-line' command.
919 When t, the following will happen while the cursor is in the headline:
921 - When the cursor is at the beginning of a headline, kill the entire
922 line and possible the folded subtree below the line.
923 - When in the middle of the headline text, kill the headline up to the tags.
924 - When after the headline text, kill the tags."
925 :group 'org-edit-structure
926 :type 'boolean)
928 (defcustom org-ctrl-k-protect-subtree nil
929 "Non-nil means, do not delete a hidden subtree with C-k.
930 When set to the symbol `error', simply throw an error when C-k is
931 used to kill (part-of) a headline that has hidden text behind it.
932 Any other non-nil value will result in a query to the user, if it is
933 OK to kill that hidden subtree. When nil, kill without remorse."
934 :group 'org-edit-structure
935 :type '(choice
936 (const :tag "Do not protect hidden subtrees" nil)
937 (const :tag "Protect hidden subtrees with a security query" t)
938 (const :tag "Never kill a hidden subtree with C-k" error)))
940 (defcustom org-yank-folded-subtrees t
941 "Non-nil means when yanking subtrees, fold them.
942 If the kill is a single subtree, or a sequence of subtrees, i.e. if
943 it starts with a heading and all other headings in it are either children
944 or siblings, then fold all the subtrees. However, do this only if no
945 text after the yank would be swallowed into a folded tree by this action."
946 :group 'org-edit-structure
947 :type 'boolean)
949 (defcustom org-yank-adjusted-subtrees nil
950 "Non-nil means when yanking subtrees, adjust the level.
951 With this setting, `org-paste-subtree' is used to insert the subtree, see
952 this function for details."
953 :group 'org-edit-structure
954 :type 'boolean)
956 (defcustom org-M-RET-may-split-line '((default . t))
957 "Non-nil means M-RET will split the line at the cursor position.
958 When nil, it will go to the end of the line before making a
959 new line.
960 You may also set this option in a different way for different
961 contexts. Valid contexts are:
963 headline when creating a new headline
964 item when creating a new item
965 table in a table field
966 default the value to be used for all contexts not explicitly
967 customized"
968 :group 'org-structure
969 :group 'org-table
970 :type '(choice
971 (const :tag "Always" t)
972 (const :tag "Never" nil)
973 (repeat :greedy t :tag "Individual contexts"
974 (cons
975 (choice :tag "Context"
976 (const headline)
977 (const item)
978 (const table)
979 (const default))
980 (boolean)))))
983 (defcustom org-insert-heading-respect-content nil
984 "Non-nil means insert new headings after the current subtree.
985 When nil, the new heading is created directly after the current line.
986 The commands \\[org-insert-heading-respect-content] and
987 \\[org-insert-todo-heading-respect-content] turn this variable on
988 for the duration of the command."
989 :group 'org-structure
990 :type 'boolean)
992 (defcustom org-blank-before-new-entry '((heading . auto)
993 (plain-list-item . auto))
994 "Should `org-insert-heading' leave a blank line before new heading/item?
995 The value is an alist, with `heading' and `plain-list-item' as car,
996 and a boolean flag as cdr. For plain lists, if the variable
997 `org-empty-line-terminates-plain-lists' is set, the setting here
998 is ignored and no empty line is inserted, to keep the list in tact."
999 :group 'org-edit-structure
1000 :type '(list
1001 (cons (const heading)
1002 (choice (const :tag "Never" nil)
1003 (const :tag "Always" t)
1004 (const :tag "Auto" auto)))
1005 (cons (const plain-list-item)
1006 (choice (const :tag "Never" nil)
1007 (const :tag "Always" t)
1008 (const :tag "Auto" auto)))))
1010 (defcustom org-insert-heading-hook nil
1011 "Hook being run after inserting a new heading."
1012 :group 'org-edit-structure
1013 :type 'hook)
1015 (defcustom org-enable-fixed-width-editor t
1016 "Non-nil means lines starting with \":\" are treated as fixed-width.
1017 This currently only means they are never auto-wrapped.
1018 When nil, such lines will be treated like ordinary lines.
1019 See also the QUOTE keyword."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1024 (defcustom org-goto-auto-isearch t
1025 "Non-nil means typing characters in org-goto starts incremental search."
1026 :group 'org-edit-structure
1027 :type 'boolean)
1029 (defgroup org-sparse-trees nil
1030 "Options concerning sparse trees in Org-mode."
1031 :tag "Org Sparse Trees"
1032 :group 'org-structure)
1034 (defcustom org-highlight-sparse-tree-matches t
1035 "Non-nil means highlight all matches that define a sparse tree.
1036 The highlights will automatically disappear the next time the buffer is
1037 changed by an edit command."
1038 :group 'org-sparse-trees
1039 :type 'boolean)
1041 (defcustom org-remove-highlights-with-change t
1042 "Non-nil means any change to the buffer will remove temporary highlights.
1043 Such highlights are created by `org-occur' and `org-clock-display'.
1044 When nil, `C-c C-c needs to be used to get rid of the highlights.
1045 The highlights created by `org-preview-latex-fragment' always need
1046 `C-c C-c' to be removed."
1047 :group 'org-sparse-trees
1048 :group 'org-time
1049 :type 'boolean)
1052 (defcustom org-occur-hook '(org-first-headline-recenter)
1053 "Hook that is run after `org-occur' has constructed a sparse tree.
1054 This can be used to recenter the window to show as much of the structure
1055 as possible."
1056 :group 'org-sparse-trees
1057 :type 'hook)
1059 (defgroup org-imenu-and-speedbar nil
1060 "Options concerning imenu and speedbar in Org-mode."
1061 :tag "Org Imenu and Speedbar"
1062 :group 'org-structure)
1064 (defcustom org-imenu-depth 2
1065 "The maximum level for Imenu access to Org-mode headlines.
1066 This also applied for speedbar access."
1067 :group 'org-imenu-and-speedbar
1068 :type 'integer)
1070 (defgroup org-table nil
1071 "Options concerning tables in Org-mode."
1072 :tag "Org Table"
1073 :group 'org)
1075 (defcustom org-enable-table-editor 'optimized
1076 "Non-nil means lines starting with \"|\" are handled by the table editor.
1077 When nil, such lines will be treated like ordinary lines.
1079 When equal to the symbol `optimized', the table editor will be optimized to
1080 do the following:
1081 - Automatic overwrite mode in front of whitespace in table fields.
1082 This makes the structure of the table stay in tact as long as the edited
1083 field does not exceed the column width.
1084 - Minimize the number of realigns. Normally, the table is aligned each time
1085 TAB or RET are pressed to move to another field. With optimization this
1086 happens only if changes to a field might have changed the column width.
1087 Optimization requires replacing the functions `self-insert-command',
1088 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1089 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1090 very good at guessing when a re-align will be necessary, but you can always
1091 force one with \\[org-ctrl-c-ctrl-c].
1093 If you would like to use the optimized version in Org-mode, but the
1094 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1096 This variable can be used to turn on and off the table editor during a session,
1097 but in order to toggle optimization, a restart is required.
1099 See also the variable `org-table-auto-blank-field'."
1100 :group 'org-table
1101 :type '(choice
1102 (const :tag "off" nil)
1103 (const :tag "on" t)
1104 (const :tag "on, optimized" optimized)))
1106 (defcustom org-self-insert-cluster-for-undo t
1107 "Non-nil means cluster self-insert commands for undo when possible.
1108 If this is set, then, like in the Emacs command loop, 20 consecutive
1109 characters will be undone together.
1110 This is configurable, because there is some impact on typing performance."
1111 :group 'org-table
1112 :type 'boolean)
1114 (defcustom org-table-tab-recognizes-table.el t
1115 "Non-nil means TAB will automatically notice a table.el table.
1116 When it sees such a table, it moves point into it and - if necessary -
1117 calls `table-recognize-table'."
1118 :group 'org-table-editing
1119 :type 'boolean)
1121 (defgroup org-link nil
1122 "Options concerning links in Org-mode."
1123 :tag "Org Link"
1124 :group 'org)
1126 (defvar org-link-abbrev-alist-local nil
1127 "Buffer-local version of `org-link-abbrev-alist', which see.
1128 The value of this is taken from the #+LINK lines.")
1129 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1131 (defcustom org-link-abbrev-alist nil
1132 "Alist of link abbreviations.
1133 The car of each element is a string, to be replaced at the start of a link.
1134 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1135 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1137 [[linkkey:tag][description]]
1139 The 'linkkey' must be a word word, starting with a letter, followed
1140 by letters, numbers, '-' or '_'.
1142 If REPLACE is a string, the tag will simply be appended to create the link.
1143 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1144 the placeholder \"%h\" will cause a url-encoded version of the tag to
1145 be inserted at that point (see the function `url-hexify-string').
1147 REPLACE may also be a function that will be called with the tag as the
1148 only argument to create the link, which should be returned as a string.
1150 See the manual for examples."
1151 :group 'org-link
1152 :type '(repeat
1153 (cons
1154 (string :tag "Protocol")
1155 (choice
1156 (string :tag "Format")
1157 (function)))))
1159 (defcustom org-descriptive-links t
1160 "Non-nil means hide link part and only show description of bracket links.
1161 Bracket links are like [[link][description]]. This variable sets the initial
1162 state in new org-mode buffers. The setting can then be toggled on a
1163 per-buffer basis from the Org->Hyperlinks menu."
1164 :group 'org-link
1165 :type 'boolean)
1167 (defcustom org-link-file-path-type 'adaptive
1168 "How the path name in file links should be stored.
1169 Valid values are:
1171 relative Relative to the current directory, i.e. the directory of the file
1172 into which the link is being inserted.
1173 absolute Absolute path, if possible with ~ for home directory.
1174 noabbrev Absolute path, no abbreviation of home directory.
1175 adaptive Use relative path for files in the current directory and sub-
1176 directories of it. For other files, use an absolute path."
1177 :group 'org-link
1178 :type '(choice
1179 (const relative)
1180 (const absolute)
1181 (const noabbrev)
1182 (const adaptive)))
1184 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1185 "Types of links that should be activated in Org-mode files.
1186 This is a list of symbols, each leading to the activation of a certain link
1187 type. In principle, it does not hurt to turn on most link types - there may
1188 be a small gain when turning off unused link types. The types are:
1190 bracket The recommended [[link][description]] or [[link]] links with hiding.
1191 angular Links in angular brackets that may contain whitespace like
1192 <bbdb:Carsten Dominik>.
1193 plain Plain links in normal text, no whitespace, like http://google.com.
1194 radio Text that is matched by a radio target, see manual for details.
1195 tag Tag settings in a headline (link to tag search).
1196 date Time stamps (link to calendar).
1197 footnote Footnote labels.
1199 Changing this variable requires a restart of Emacs to become effective."
1200 :group 'org-link
1201 :type '(set :greedy t
1202 (const :tag "Double bracket links (new style)" bracket)
1203 (const :tag "Angular bracket links (old style)" angular)
1204 (const :tag "Plain text links" plain)
1205 (const :tag "Radio target matches" radio)
1206 (const :tag "Tags" tag)
1207 (const :tag "Timestamps" date)
1208 (const :tag "Footnotes" footnote)))
1210 (defcustom org-make-link-description-function nil
1211 "Function to use to generate link descriptions from links. If
1212 nil the link location will be used. This function must take two
1213 parameters; the first is the link and the second the description
1214 org-insert-link has generated, and should return the description
1215 to use."
1216 :group 'org-link
1217 :type 'function)
1219 (defgroup org-link-store nil
1220 "Options concerning storing links in Org-mode."
1221 :tag "Org Store Link"
1222 :group 'org-link)
1224 (defcustom org-email-link-description-format "Email %c: %.30s"
1225 "Format of the description part of a link to an email or usenet message.
1226 The following %-escapes will be replaced by corresponding information:
1228 %F full \"From\" field
1229 %f name, taken from \"From\" field, address if no name
1230 %T full \"To\" field
1231 %t first name in \"To\" field, address if no name
1232 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1233 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1234 %s subject
1235 %m message-id.
1237 You may use normal field width specification between the % and the letter.
1238 This is for example useful to limit the length of the subject.
1240 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1241 :group 'org-link-store
1242 :type 'string)
1244 (defcustom org-from-is-user-regexp
1245 (let (r1 r2)
1246 (when (and user-mail-address (not (string= user-mail-address "")))
1247 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1248 (when (and user-full-name (not (string= user-full-name "")))
1249 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1250 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1251 "Regexp matched against the \"From:\" header of an email or usenet message.
1252 It should match if the message is from the user him/herself."
1253 :group 'org-link-store
1254 :type 'regexp)
1256 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1257 "Non-nil means storing a link to an Org file will use entry IDs.
1259 Note that before this variable is even considered, org-id must be loaded,
1260 so please customize `org-modules' and turn it on.
1262 The variable can have the following values:
1264 t Create an ID if needed to make a link to the current entry.
1266 create-if-interactive
1267 If `org-store-link' is called directly (interactively, as a user
1268 command), do create an ID to support the link. But when doing the
1269 job for remember, only use the ID if it already exists. The
1270 purpose of this setting is to avoid proliferation of unwanted
1271 IDs, just because you happen to be in an Org file when you
1272 call `org-remember' that automatically and preemptively
1273 creates a link. If you do want to get an ID link in a remember
1274 template to an entry not having an ID, create it first by
1275 explicitly creating a link to it, using `C-c C-l' first.
1277 create-if-interactive-and-no-custom-id
1278 Like create-if-interactive, but do not create an ID if there is
1279 a CUSTOM_ID property defined in the entry. This is the default.
1281 use-existing
1282 Use existing ID, do not create one.
1284 nil Never use an ID to make a link, instead link using a text search for
1285 the headline text."
1286 :group 'org-link-store
1287 :type '(choice
1288 (const :tag "Create ID to make link" t)
1289 (const :tag "Create if storing link interactively"
1290 create-if-interactive)
1291 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1292 create-if-interactive-and-no-custom-id)
1293 (const :tag "Only use existing" use-existing)
1294 (const :tag "Do not use ID to create link" nil)))
1296 (defcustom org-context-in-file-links t
1297 "Non-nil means file links from `org-store-link' contain context.
1298 A search string will be added to the file name with :: as separator and
1299 used to find the context when the link is activated by the command
1300 `org-open-at-point'.
1301 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1302 negates this setting for the duration of the command."
1303 :group 'org-link-store
1304 :type 'boolean)
1306 (defcustom org-keep-stored-link-after-insertion nil
1307 "Non-nil means keep link in list for entire session.
1309 The command `org-store-link' adds a link pointing to the current
1310 location to an internal list. These links accumulate during a session.
1311 The command `org-insert-link' can be used to insert links into any
1312 Org-mode file (offering completion for all stored links). When this
1313 option is nil, every link which has been inserted once using \\[org-insert-link]
1314 will be removed from the list, to make completing the unused links
1315 more efficient."
1316 :group 'org-link-store
1317 :type 'boolean)
1319 (defgroup org-link-follow nil
1320 "Options concerning following links in Org-mode."
1321 :tag "Org Follow Link"
1322 :group 'org-link)
1324 (defcustom org-link-translation-function nil
1325 "Function to translate links with different syntax to Org syntax.
1326 This can be used to translate links created for example by the Planner
1327 or emacs-wiki packages to Org syntax.
1328 The function must accept two parameters, a TYPE containing the link
1329 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1330 which is everything after the link protocol. It should return a cons
1331 with possibly modified values of type and path.
1332 Org contains a function for this, so if you set this variable to
1333 `org-translate-link-from-planner', you should be able follow many
1334 links created by planner."
1335 :group 'org-link-follow
1336 :type 'function)
1338 (defcustom org-follow-link-hook nil
1339 "Hook that is run after a link has been followed."
1340 :group 'org-link-follow
1341 :type 'hook)
1343 (defcustom org-tab-follows-link nil
1344 "Non-nil means on links TAB will follow the link.
1345 Needs to be set before org.el is loaded.
1346 This really should not be used, it does not make sense, and the
1347 implementation is bad."
1348 :group 'org-link-follow
1349 :type 'boolean)
1351 (defcustom org-return-follows-link nil
1352 "Non-nil means on links RET will follow the link."
1353 :group 'org-link-follow
1354 :type 'boolean)
1356 (defcustom org-mouse-1-follows-link
1357 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1358 "Non-nil means mouse-1 on a link will follow the link.
1359 A longer mouse click will still set point. Does not work on XEmacs.
1360 Needs to be set before org.el is loaded."
1361 :group 'org-link-follow
1362 :type 'boolean)
1364 (defcustom org-mark-ring-length 4
1365 "Number of different positions to be recorded in the ring
1366 Changing this requires a restart of Emacs to work correctly."
1367 :group 'org-link-follow
1368 :type 'integer)
1370 (defcustom org-link-frame-setup
1371 '((vm . vm-visit-folder-other-frame)
1372 (gnus . gnus-other-frame)
1373 (file . find-file-other-window))
1374 "Setup the frame configuration for following links.
1375 When following a link with Emacs, it may often be useful to display
1376 this link in another window or frame. This variable can be used to
1377 set this up for the different types of links.
1378 For VM, use any of
1379 `vm-visit-folder'
1380 `vm-visit-folder-other-frame'
1381 For Gnus, use any of
1382 `gnus'
1383 `gnus-other-frame'
1384 `org-gnus-no-new-news'
1385 For FILE, use any of
1386 `find-file'
1387 `find-file-other-window'
1388 `find-file-other-frame'
1389 For the calendar, use the variable `calendar-setup'.
1390 For BBDB, it is currently only possible to display the matches in
1391 another window."
1392 :group 'org-link-follow
1393 :type '(list
1394 (cons (const vm)
1395 (choice
1396 (const vm-visit-folder)
1397 (const vm-visit-folder-other-window)
1398 (const vm-visit-folder-other-frame)))
1399 (cons (const gnus)
1400 (choice
1401 (const gnus)
1402 (const gnus-other-frame)
1403 (const org-gnus-no-new-news)))
1404 (cons (const file)
1405 (choice
1406 (const find-file)
1407 (const find-file-other-window)
1408 (const find-file-other-frame)))))
1410 (defcustom org-display-internal-link-with-indirect-buffer nil
1411 "Non-nil means use indirect buffer to display infile links.
1412 Activating internal links (from one location in a file to another location
1413 in the same file) normally just jumps to the location. When the link is
1414 activated with a C-u prefix (or with mouse-3), the link is displayed in
1415 another window. When this option is set, the other window actually displays
1416 an indirect buffer clone of the current buffer, to avoid any visibility
1417 changes to the current buffer."
1418 :group 'org-link-follow
1419 :type 'boolean)
1421 (defcustom org-open-non-existing-files nil
1422 "Non-nil means `org-open-file' will open non-existing files.
1423 When nil, an error will be generated.
1424 This variable applies only to external applications because they
1425 might choke on non-existing files. If the link is to a file that
1426 will be opened in Emacs, the variable is ignored."
1427 :group 'org-link-follow
1428 :type 'boolean)
1430 (defcustom org-open-directory-means-index-dot-org nil
1431 "Non-nil means a link to a directory really means to index.org.
1432 When nil, following a directory link will run dired or open a finder/explorer
1433 window on that directory."
1434 :group 'org-link-follow
1435 :type 'boolean)
1437 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1438 "Function and arguments to call for following mailto links.
1439 This is a list with the first element being a lisp function, and the
1440 remaining elements being arguments to the function. In string arguments,
1441 %a will be replaced by the address, and %s will be replaced by the subject
1442 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1443 :group 'org-link-follow
1444 :type '(choice
1445 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1446 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1447 (const :tag "message-mail" (message-mail "%a" "%s"))
1448 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1450 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1451 "Non-nil means ask for confirmation before executing shell links.
1452 Shell links can be dangerous: just think about a link
1454 [[shell:rm -rf ~/*][Google Search]]
1456 This link would show up in your Org-mode document as \"Google Search\",
1457 but really it would remove your entire home directory.
1458 Therefore we advise against setting this variable to nil.
1459 Just change it to `y-or-n-p' if you want to confirm with a
1460 single keystroke rather than having to type \"yes\"."
1461 :group 'org-link-follow
1462 :type '(choice
1463 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1464 (const :tag "with y-or-n (faster)" y-or-n-p)
1465 (const :tag "no confirmation (dangerous)" nil)))
1467 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1468 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1469 Elisp links can be dangerous: just think about a link
1471 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1473 This link would show up in your Org-mode document as \"Google Search\",
1474 but really it would remove your entire home directory.
1475 Therefore we advise against setting this variable to nil.
1476 Just change it to `y-or-n-p' if you want to confirm with a
1477 single keystroke rather than having to type \"yes\"."
1478 :group 'org-link-follow
1479 :type '(choice
1480 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1481 (const :tag "with y-or-n (faster)" y-or-n-p)
1482 (const :tag "no confirmation (dangerous)" nil)))
1484 (defconst org-file-apps-defaults-gnu
1485 '((remote . emacs)
1486 (system . mailcap)
1487 (t . mailcap))
1488 "Default file applications on a UNIX or GNU/Linux system.
1489 See `org-file-apps'.")
1491 (defconst org-file-apps-defaults-macosx
1492 '((remote . emacs)
1493 (t . "open %s")
1494 (system . "open %s")
1495 ("ps.gz" . "gv %s")
1496 ("eps.gz" . "gv %s")
1497 ("dvi" . "xdvi %s")
1498 ("fig" . "xfig %s"))
1499 "Default file applications on a MacOS X system.
1500 The system \"open\" is known as a default, but we use X11 applications
1501 for some files for which the OS does not have a good default.
1502 See `org-file-apps'.")
1504 (defconst org-file-apps-defaults-windowsnt
1505 (list
1506 '(remote . emacs)
1507 (cons t
1508 (list (if (featurep 'xemacs)
1509 'mswindows-shell-execute
1510 'w32-shell-execute)
1511 "open" 'file))
1512 (cons 'system
1513 (list (if (featurep 'xemacs)
1514 'mswindows-shell-execute
1515 'w32-shell-execute)
1516 "open" 'file)))
1517 "Default file applications on a Windows NT system.
1518 The system \"open\" is used for most files.
1519 See `org-file-apps'.")
1521 (defcustom org-file-apps
1523 (auto-mode . emacs)
1524 ("\\.mm\\'" . default)
1525 ("\\.x?html?\\'" . default)
1526 ("\\.pdf\\'" . default)
1528 "External applications for opening `file:path' items in a document.
1529 Org-mode uses system defaults for different file types, but
1530 you can use this variable to set the application for a given file
1531 extension. The entries in this list are cons cells where the car identifies
1532 files and the cdr the corresponding command. Possible values for the
1533 file identifier are
1534 \"string\" A string as a file identifier can be interpreted in different
1535 ways, depending on its contents:
1537 - Alphanumeric characters only:
1538 Match links with this file extension.
1539 Example: (\"pdf\" . \"evince %s\")
1540 to open PDFs with evince.
1542 - Regular expression: Match links where the
1543 filename matches the regexp. If you want to
1544 use groups here, use shy groups.
1546 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1547 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1548 to open *.html and *.xhtml with firefox.
1550 - Regular expression which contains (non-shy) groups:
1551 Match links where the whole link, including \"::\", and
1552 anything after that, matches the regexp.
1553 In a custom command string, %1, %2, etc. are replaced with
1554 the parts of the link that were matched by the groups.
1555 For backwards compatibility, if a command string is given
1556 that does not use any of the group matches, this case is
1557 handled identically to the second one (i.e. match against
1558 file name only).
1560 In a custom lisp form, you can access the group matches with
1561 (match-string n link).
1563 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1564 to open [[file:document.pdf::5]] with evince at page 5.
1566 `directory' Matches a directory
1567 `remote' Matches a remote file, accessible through tramp or efs.
1568 Remote files most likely should be visited through Emacs
1569 because external applications cannot handle such paths.
1570 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1571 so all files Emacs knows how to handle. Using this with
1572 command `emacs' will open most files in Emacs. Beware that this
1573 will also open html files inside Emacs, unless you add
1574 (\"html\" . default) to the list as well.
1575 t Default for files not matched by any of the other options.
1576 `system' The system command to open files, like `open' on Windows
1577 and Mac OS X, and mailcap under GNU/Linux. This is the command
1578 that will be selected if you call `C-c C-o' with a double
1579 `C-u C-u' prefix.
1581 Possible values for the command are:
1582 `emacs' The file will be visited by the current Emacs process.
1583 `default' Use the default application for this file type, which is the
1584 association for t in the list, most likely in the system-specific
1585 part.
1586 This can be used to overrule an unwanted setting in the
1587 system-specific variable.
1588 `system' Use the system command for opening files, like \"open\".
1589 This command is specified by the entry whose car is `system'.
1590 Most likely, the system-specific version of this variable
1591 does define this command, but you can overrule/replace it
1592 here.
1593 string A command to be executed by a shell; %s will be replaced
1594 by the path to the file.
1595 sexp A Lisp form which will be evaluated. The file path will
1596 be available in the Lisp variable `file'.
1597 For more examples, see the system specific constants
1598 `org-file-apps-defaults-macosx'
1599 `org-file-apps-defaults-windowsnt'
1600 `org-file-apps-defaults-gnu'."
1601 :group 'org-link-follow
1602 :type '(repeat
1603 (cons (choice :value ""
1604 (string :tag "Extension")
1605 (const :tag "System command to open files" system)
1606 (const :tag "Default for unrecognized files" t)
1607 (const :tag "Remote file" remote)
1608 (const :tag "Links to a directory" directory)
1609 (const :tag "Any files that have Emacs modes"
1610 auto-mode))
1611 (choice :value ""
1612 (const :tag "Visit with Emacs" emacs)
1613 (const :tag "Use default" default)
1614 (const :tag "Use the system command" system)
1615 (string :tag "Command")
1616 (sexp :tag "Lisp form")))))
1620 (defgroup org-refile nil
1621 "Options concerning refiling entries in Org-mode."
1622 :tag "Org Refile"
1623 :group 'org)
1625 (defcustom org-directory "~/org"
1626 "Directory with org files.
1627 This is just a default location to look for Org files. There is no need
1628 at all to put your files into this directory. It is only used in the
1629 following situations:
1631 1. When a remember template specifies a target file that is not an
1632 absolute path. The path will then be interpreted relative to
1633 `org-directory'
1634 2. When a remember note is filed away in an interactive way (when exiting the
1635 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1636 with `org-directory' as the default path."
1637 :group 'org-refile
1638 :group 'org-remember
1639 :type 'directory)
1641 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1642 "Default target for storing notes.
1643 Used by the hooks for remember.el. This can be a string, or nil to mean
1644 the value of `remember-data-file'.
1645 You can set this on a per-template basis with the variable
1646 `org-remember-templates'."
1647 :group 'org-refile
1648 :group 'org-remember
1649 :type '(choice
1650 (const :tag "Default from remember-data-file" nil)
1651 file))
1653 (defcustom org-goto-interface 'outline
1654 "The default interface to be used for `org-goto'.
1655 Allowed values are:
1656 outline The interface shows an outline of the relevant file
1657 and the correct heading is found by moving through
1658 the outline or by searching with incremental search.
1659 outline-path-completion Headlines in the current buffer are offered via
1660 completion. This is the interface also used by
1661 the refile command."
1662 :group 'org-refile
1663 :type '(choice
1664 (const :tag "Outline" outline)
1665 (const :tag "Outline-path-completion" outline-path-completion)))
1667 (defcustom org-goto-max-level 5
1668 "Maximum level to be considered when running org-goto with refile interface."
1669 :group 'org-refile
1670 :type 'integer)
1672 (defcustom org-reverse-note-order nil
1673 "Non-nil means store new notes at the beginning of a file or entry.
1674 When nil, new notes will be filed to the end of a file or entry.
1675 This can also be a list with cons cells of regular expressions that
1676 are matched against file names, and values."
1677 :group 'org-remember
1678 :group 'org-refile
1679 :type '(choice
1680 (const :tag "Reverse always" t)
1681 (const :tag "Reverse never" nil)
1682 (repeat :tag "By file name regexp"
1683 (cons regexp boolean))))
1685 (defcustom org-log-refile nil
1686 "Information to record when a task is refiled.
1688 Possible values are:
1690 nil Don't add anything
1691 time Add a time stamp to the task
1692 note Prompt for a note and add it with template `org-log-note-headings'
1694 This option can also be set with on a per-file-basis with
1696 #+STARTUP: nologrefile
1697 #+STARTUP: logrefile
1698 #+STARTUP: lognoterefile
1700 You can have local logging settings for a subtree by setting the LOGGING
1701 property to one or more of these keywords.
1703 When bulk-refiling from the agenda, the value `note' is forbidden and
1704 will temporarily be changed to `time'."
1705 :group 'org-refile
1706 :group 'org-progress
1707 :type '(choice
1708 (const :tag "No logging" nil)
1709 (const :tag "Record timestamp" time)
1710 (const :tag "Record timestamp with note." note)))
1712 (defcustom org-refile-targets nil
1713 "Targets for refiling entries with \\[org-refile].
1714 This is list of cons cells. Each cell contains:
1715 - a specification of the files to be considered, either a list of files,
1716 or a symbol whose function or variable value will be used to retrieve
1717 a file name or a list of file names. If you use `org-agenda-files' for
1718 that, all agenda files will be scanned for targets. Nil means consider
1719 headings in the current buffer.
1720 - A specification of how to find candidate refile targets. This may be
1721 any of:
1722 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1723 This tag has to be present in all target headlines, inheritance will
1724 not be considered.
1725 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1726 todo keyword.
1727 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1728 headlines that are refiling targets.
1729 - a cons cell (:level . N). Any headline of level N is considered a target.
1730 Note that, when `org-odd-levels-only' is set, level corresponds to
1731 order in hierarchy, not to the number of stars.
1732 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1733 Note that, when `org-odd-levels-only' is set, level corresponds to
1734 order in hierarchy, not to the number of stars.
1736 You can set the variable `org-refile-target-verify-function' to a function
1737 to verify each headline found by the simple critery above.
1739 When this variable is nil, all top-level headlines in the current buffer
1740 are used, equivalent to the value `((nil . (:level . 1))'."
1741 :group 'org-refile
1742 :type '(repeat
1743 (cons
1744 (choice :value org-agenda-files
1745 (const :tag "All agenda files" org-agenda-files)
1746 (const :tag "Current buffer" nil)
1747 (function) (variable) (file))
1748 (choice :tag "Identify target headline by"
1749 (cons :tag "Specific tag" (const :value :tag) (string))
1750 (cons :tag "TODO keyword" (const :value :todo) (string))
1751 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1752 (cons :tag "Level number" (const :value :level) (integer))
1753 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1755 (defcustom org-refile-target-verify-function nil
1756 "Function to verify if the headline at point should be a refile target.
1757 The function will be called without arguments, with point at the
1758 beginning of the headline. It should return t and leave point
1759 where it is if the headline is a valid target for refiling.
1761 If the target should not be selected, the function must return nil.
1762 In addition to this, it may move point to a place from where the search
1763 should be continued. For example, the function may decide that the entire
1764 subtree of the current entry should be excluded and move point to the end
1765 of the subtree."
1766 :group 'org-refile
1767 :type 'function)
1769 (defcustom org-refile-use-cache nil
1770 "Non-nil means cache refile targets to speed up the process.
1771 The cache for a particular file will be updated automatically when
1772 the buffer has been killed, or when any of the marker used for flagging
1773 refile targets no longer points at a live buffer.
1774 If you have added new entries to a buffer that might themselves be targets,
1775 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1776 find that easier, `C-u C-u C-u C-c C-w'."
1777 :group 'org-refile
1778 :type 'boolean)
1780 (defcustom org-refile-use-outline-path nil
1781 "Non-nil means provide refile targets as paths.
1782 So a level 3 headline will be available as level1/level2/level3.
1784 When the value is `file', also include the file name (without directory)
1785 into the path. In this case, you can also stop the completion after
1786 the file name, to get entries inserted as top level in the file.
1788 When `full-file-path', include the full file path."
1789 :group 'org-refile
1790 :type '(choice
1791 (const :tag "Not" nil)
1792 (const :tag "Yes" t)
1793 (const :tag "Start with file name" file)
1794 (const :tag "Start with full file path" full-file-path)))
1796 (defcustom org-outline-path-complete-in-steps t
1797 "Non-nil means complete the outline path in hierarchical steps.
1798 When Org-mode uses the refile interface to select an outline path
1799 \(see variable `org-refile-use-outline-path'), the completion of
1800 the path can be done is a single go, or if can be done in steps down
1801 the headline hierarchy. Going in steps is probably the best if you
1802 do not use a special completion package like `ido' or `icicles'.
1803 However, when using these packages, going in one step can be very
1804 fast, while still showing the whole path to the entry."
1805 :group 'org-refile
1806 :type 'boolean)
1808 (defcustom org-refile-allow-creating-parent-nodes nil
1809 "Non-nil means allow to create new nodes as refile targets.
1810 New nodes are then created by adding \"/new node name\" to the completion
1811 of an existing node. When the value of this variable is `confirm',
1812 new node creation must be confirmed by the user (recommended)
1813 When nil, the completion must match an existing entry.
1815 Note that, if the new heading is not seen by the criteria
1816 listed in `org-refile-targets', multiple instances of the same
1817 heading would be created by trying again to file under the new
1818 heading."
1819 :group 'org-refile
1820 :type '(choice
1821 (const :tag "Never" nil)
1822 (const :tag "Always" t)
1823 (const :tag "Prompt for confirmation" confirm)))
1825 (defgroup org-todo nil
1826 "Options concerning TODO items in Org-mode."
1827 :tag "Org TODO"
1828 :group 'org)
1830 (defgroup org-progress nil
1831 "Options concerning Progress logging in Org-mode."
1832 :tag "Org Progress"
1833 :group 'org-time)
1835 (defvar org-todo-interpretation-widgets
1837 (:tag "Sequence (cycling hits every state)" sequence)
1838 (:tag "Type (cycling directly to DONE)" type))
1839 "The available interpretation symbols for customizing
1840 `org-todo-keywords'.
1841 Interested libraries should add to this list.")
1843 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1844 "List of TODO entry keyword sequences and their interpretation.
1845 \\<org-mode-map>This is a list of sequences.
1847 Each sequence starts with a symbol, either `sequence' or `type',
1848 indicating if the keywords should be interpreted as a sequence of
1849 action steps, or as different types of TODO items. The first
1850 keywords are states requiring action - these states will select a headline
1851 for inclusion into the global TODO list Org-mode produces. If one of
1852 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1853 signify that no further action is necessary. If \"|\" is not found,
1854 the last keyword is treated as the only DONE state of the sequence.
1856 The command \\[org-todo] cycles an entry through these states, and one
1857 additional state where no keyword is present. For details about this
1858 cycling, see the manual.
1860 TODO keywords and interpretation can also be set on a per-file basis with
1861 the special #+SEQ_TODO and #+TYP_TODO lines.
1863 Each keyword can optionally specify a character for fast state selection
1864 \(in combination with the variable `org-use-fast-todo-selection')
1865 and specifiers for state change logging, using the same syntax
1866 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1867 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1868 indicates to record a time stamp each time this state is selected.
1870 Each keyword may also specify if a timestamp or a note should be
1871 recorded when entering or leaving the state, by adding additional
1872 characters in the parenthesis after the keyword. This looks like this:
1873 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1874 record only the time of the state change. With X and Y being either
1875 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1876 Y when leaving the state if and only if the *target* state does not
1877 define X. You may omit any of the fast-selection key or X or /Y,
1878 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1880 For backward compatibility, this variable may also be just a list
1881 of keywords - in this case the interpretation (sequence or type) will be
1882 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1883 :group 'org-todo
1884 :group 'org-keywords
1885 :type '(choice
1886 (repeat :tag "Old syntax, just keywords"
1887 (string :tag "Keyword"))
1888 (repeat :tag "New syntax"
1889 (cons
1890 (choice
1891 :tag "Interpretation"
1892 ;;Quick and dirty way to see
1893 ;;`org-todo-interpretations'. This takes the
1894 ;;place of item arguments
1895 :convert-widget
1896 (lambda (widget)
1897 (widget-put widget
1898 :args (mapcar
1899 #'(lambda (x)
1900 (widget-convert
1901 (cons 'const x)))
1902 org-todo-interpretation-widgets))
1903 widget))
1904 (repeat
1905 (string :tag "Keyword"))))))
1907 (defvar org-todo-keywords-1 nil
1908 "All TODO and DONE keywords active in a buffer.")
1909 (make-variable-buffer-local 'org-todo-keywords-1)
1910 (defvar org-todo-keywords-for-agenda nil)
1911 (defvar org-done-keywords-for-agenda nil)
1912 (defvar org-drawers-for-agenda nil)
1913 (defvar org-todo-keyword-alist-for-agenda nil)
1914 (defvar org-tag-alist-for-agenda nil)
1915 (defvar org-agenda-contributing-files nil)
1916 (defvar org-not-done-keywords nil)
1917 (make-variable-buffer-local 'org-not-done-keywords)
1918 (defvar org-done-keywords nil)
1919 (make-variable-buffer-local 'org-done-keywords)
1920 (defvar org-todo-heads nil)
1921 (make-variable-buffer-local 'org-todo-heads)
1922 (defvar org-todo-sets nil)
1923 (make-variable-buffer-local 'org-todo-sets)
1924 (defvar org-todo-log-states nil)
1925 (make-variable-buffer-local 'org-todo-log-states)
1926 (defvar org-todo-kwd-alist nil)
1927 (make-variable-buffer-local 'org-todo-kwd-alist)
1928 (defvar org-todo-key-alist nil)
1929 (make-variable-buffer-local 'org-todo-key-alist)
1930 (defvar org-todo-key-trigger nil)
1931 (make-variable-buffer-local 'org-todo-key-trigger)
1933 (defcustom org-todo-interpretation 'sequence
1934 "Controls how TODO keywords are interpreted.
1935 This variable is in principle obsolete and is only used for
1936 backward compatibility, if the interpretation of todo keywords is
1937 not given already in `org-todo-keywords'. See that variable for
1938 more information."
1939 :group 'org-todo
1940 :group 'org-keywords
1941 :type '(choice (const sequence)
1942 (const type)))
1944 (defcustom org-use-fast-todo-selection t
1945 "Non-nil means use the fast todo selection scheme with C-c C-t.
1946 This variable describes if and under what circumstances the cycling
1947 mechanism for TODO keywords will be replaced by a single-key, direct
1948 selection scheme.
1950 When nil, fast selection is never used.
1952 When the symbol `prefix', it will be used when `org-todo' is called with
1953 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1954 in an agenda buffer.
1956 When t, fast selection is used by default. In this case, the prefix
1957 argument forces cycling instead.
1959 In all cases, the special interface is only used if access keys have actually
1960 been assigned by the user, i.e. if keywords in the configuration are followed
1961 by a letter in parenthesis, like TODO(t)."
1962 :group 'org-todo
1963 :type '(choice
1964 (const :tag "Never" nil)
1965 (const :tag "By default" t)
1966 (const :tag "Only with C-u C-c C-t" prefix)))
1968 (defcustom org-provide-todo-statistics t
1969 "Non-nil means update todo statistics after insert and toggle.
1970 ALL-HEADLINES means update todo statistics by including headlines
1971 with no TODO keyword as well, counting them as not done.
1972 A list of TODO keywords means the same, but skip keywords that are
1973 not in this list.
1975 When this is set, todo statistics is updated in the parent of the
1976 current entry each time a todo state is changed."
1977 :group 'org-todo
1978 :type '(choice
1979 (const :tag "Yes, only for TODO entries" t)
1980 (const :tag "Yes, including all entries" 'all-headlines)
1981 (repeat :tag "Yes, for TODOs in this list"
1982 (string :tag "TODO keyword"))
1983 (other :tag "No TODO statistics" nil)))
1985 (defcustom org-hierarchical-todo-statistics t
1986 "Non-nil means TODO statistics covers just direct children.
1987 When nil, all entries in the subtree are considered.
1988 This has only an effect if `org-provide-todo-statistics' is set.
1989 To set this to nil for only a single subtree, use a COOKIE_DATA
1990 property and include the word \"recursive\" into the value."
1991 :group 'org-todo
1992 :type 'boolean)
1994 (defcustom org-after-todo-state-change-hook nil
1995 "Hook which is run after the state of a TODO item was changed.
1996 The new state (a string with a TODO keyword, or nil) is available in the
1997 Lisp variable `state'."
1998 :group 'org-todo
1999 :type 'hook)
2001 (defvar org-blocker-hook nil
2002 "Hook for functions that are allowed to block a state change.
2004 Each function gets as its single argument a property list, see
2005 `org-trigger-hook' for more information about this list.
2007 If any of the functions in this hook returns nil, the state change
2008 is blocked.")
2010 (defvar org-trigger-hook nil
2011 "Hook for functions that are triggered by a state change.
2013 Each function gets as its single argument a property list with at least
2014 the following elements:
2016 (:type type-of-change :position pos-at-entry-start
2017 :from old-state :to new-state)
2019 Depending on the type, more properties may be present.
2021 This mechanism is currently implemented for:
2023 TODO state changes
2024 ------------------
2025 :type todo-state-change
2026 :from previous state (keyword as a string), or nil, or a symbol
2027 'todo' or 'done', to indicate the general type of state.
2028 :to new state, like in :from")
2030 (defcustom org-enforce-todo-dependencies nil
2031 "Non-nil means undone TODO entries will block switching the parent to DONE.
2032 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2033 be blocked if any prior sibling is not yet done.
2034 Finally, if the parent is blocked because of ordered siblings of its own,
2035 the child will also be blocked.
2036 This variable needs to be set before org.el is loaded, and you need to
2037 restart Emacs after a change to make the change effective. The only way
2038 to change is while Emacs is running is through the customize interface."
2039 :set (lambda (var val)
2040 (set var val)
2041 (if val
2042 (add-hook 'org-blocker-hook
2043 'org-block-todo-from-children-or-siblings-or-parent)
2044 (remove-hook 'org-blocker-hook
2045 'org-block-todo-from-children-or-siblings-or-parent)))
2046 :group 'org-todo
2047 :type 'boolean)
2049 (defcustom org-enforce-todo-checkbox-dependencies nil
2050 "Non-nil means unchecked boxes will block switching the parent to DONE.
2051 When this is nil, checkboxes have no influence on switching TODO states.
2052 When non-nil, you first need to check off all check boxes before the TODO
2053 entry can be switched to DONE.
2054 This variable needs to be set before org.el is loaded, and you need to
2055 restart Emacs after a change to make the change effective. The only way
2056 to change is while Emacs is running is through the customize interface."
2057 :set (lambda (var val)
2058 (set var val)
2059 (if val
2060 (add-hook 'org-blocker-hook
2061 'org-block-todo-from-checkboxes)
2062 (remove-hook 'org-blocker-hook
2063 'org-block-todo-from-checkboxes)))
2064 :group 'org-todo
2065 :type 'boolean)
2067 (defcustom org-treat-insert-todo-heading-as-state-change nil
2068 "Non-nil means inserting a TODO heading is treated as state change.
2069 So when the command \\[org-insert-todo-heading] is used, state change
2070 logging will apply if appropriate. When nil, the new TODO item will
2071 be inserted directly, and no logging will take place."
2072 :group 'org-todo
2073 :type 'boolean)
2075 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2076 "Non-nil means switching TODO states with S-cursor counts as state change.
2077 This is the default behavior. However, setting this to nil allows a
2078 convenient way to select a TODO state and bypass any logging associated
2079 with that."
2080 :group 'org-todo
2081 :type 'boolean)
2083 (defcustom org-todo-state-tags-triggers nil
2084 "Tag changes that should be triggered by TODO state changes.
2085 This is a list. Each entry is
2087 (state-change (tag . flag) .......)
2089 State-change can be a string with a state, and empty string to indicate the
2090 state that has no TODO keyword, or it can be one of the symbols `todo'
2091 or `done', meaning any not-done or done state, respectively."
2092 :group 'org-todo
2093 :group 'org-tags
2094 :type '(repeat
2095 (cons (choice :tag "When changing to"
2096 (const :tag "Not-done state" todo)
2097 (const :tag "Done state" done)
2098 (string :tag "State"))
2099 (repeat
2100 (cons :tag "Tag action"
2101 (string :tag "Tag")
2102 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2104 (defcustom org-log-done nil
2105 "Information to record when a task moves to the DONE state.
2107 Possible values are:
2109 nil Don't add anything, just change the keyword
2110 time Add a time stamp to the task
2111 note Prompt for a note and add it with template `org-log-note-headings'
2113 This option can also be set with on a per-file-basis with
2115 #+STARTUP: nologdone
2116 #+STARTUP: logdone
2117 #+STARTUP: lognotedone
2119 You can have local logging settings for a subtree by setting the LOGGING
2120 property to one or more of these keywords."
2121 :group 'org-todo
2122 :group 'org-progress
2123 :type '(choice
2124 (const :tag "No logging" nil)
2125 (const :tag "Record CLOSED timestamp" time)
2126 (const :tag "Record CLOSED timestamp with note." note)))
2128 ;; Normalize old uses of org-log-done.
2129 (cond
2130 ((eq org-log-done t) (setq org-log-done 'time))
2131 ((and (listp org-log-done) (memq 'done org-log-done))
2132 (setq org-log-done 'note)))
2134 (defcustom org-log-reschedule nil
2135 "Information to record when the scheduling date of a tasks is modified.
2137 Possible values are:
2139 nil Don't add anything, just change the date
2140 time Add a time stamp to the task
2141 note Prompt for a note and add it with template `org-log-note-headings'
2143 This option can also be set with on a per-file-basis with
2145 #+STARTUP: nologreschedule
2146 #+STARTUP: logreschedule
2147 #+STARTUP: lognotereschedule"
2148 :group 'org-todo
2149 :group 'org-progress
2150 :type '(choice
2151 (const :tag "No logging" nil)
2152 (const :tag "Record timestamp" time)
2153 (const :tag "Record timestamp with note." note)))
2155 (defcustom org-log-redeadline nil
2156 "Information to record when the deadline date of a tasks is modified.
2158 Possible values are:
2160 nil Don't add anything, just change the date
2161 time Add a time stamp to the task
2162 note Prompt for a note and add it with template `org-log-note-headings'
2164 This option can also be set with on a per-file-basis with
2166 #+STARTUP: nologredeadline
2167 #+STARTUP: logredeadline
2168 #+STARTUP: lognoteredeadline
2170 You can have local logging settings for a subtree by setting the LOGGING
2171 property to one or more of these keywords."
2172 :group 'org-todo
2173 :group 'org-progress
2174 :type '(choice
2175 (const :tag "No logging" nil)
2176 (const :tag "Record timestamp" time)
2177 (const :tag "Record timestamp with note." note)))
2179 (defcustom org-log-note-clock-out nil
2180 "Non-nil means record a note when clocking out of an item.
2181 This can also be configured on a per-file basis by adding one of
2182 the following lines anywhere in the buffer:
2184 #+STARTUP: lognoteclock-out
2185 #+STARTUP: nolognoteclock-out"
2186 :group 'org-todo
2187 :group 'org-progress
2188 :type 'boolean)
2190 (defcustom org-log-done-with-time t
2191 "Non-nil means the CLOSED time stamp will contain date and time.
2192 When nil, only the date will be recorded."
2193 :group 'org-progress
2194 :type 'boolean)
2196 (defcustom org-log-note-headings
2197 '((done . "CLOSING NOTE %t")
2198 (state . "State %-12s from %-12S %t")
2199 (note . "Note taken on %t")
2200 (reschedule . "Rescheduled from %S on %t")
2201 (delschedule . "Not scheduled, was %S on %t")
2202 (redeadline . "New deadline from %S on %t")
2203 (deldeadline . "Removed deadline, was %S on %t")
2204 (refile . "Refiled on %t")
2205 (clock-out . ""))
2206 "Headings for notes added to entries.
2207 The value is an alist, with the car being a symbol indicating the note
2208 context, and the cdr is the heading to be used. The heading may also be the
2209 empty string.
2210 %t in the heading will be replaced by a time stamp.
2211 %T will be an acive time stamp instead the default inacive one
2212 %s will be replaced by the new TODO state, in double quotes.
2213 %S will be replaced by the old TODO state, in double quotes.
2214 %u will be replaced by the user name.
2215 %U will be replaced by the full user name.
2217 In fact, it is not a good idea to change the `state' entry, because
2218 agenda log mode depends on the format of these entries."
2219 :group 'org-todo
2220 :group 'org-progress
2221 :type '(list :greedy t
2222 (cons (const :tag "Heading when closing an item" done) string)
2223 (cons (const :tag
2224 "Heading when changing todo state (todo sequence only)"
2225 state) string)
2226 (cons (const :tag "Heading when just taking a note" note) string)
2227 (cons (const :tag "Heading when clocking out" clock-out) string)
2228 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2229 (cons (const :tag "Heading when rescheduling" reschedule) string)
2230 (cons (const :tag "Heading when changing deadline" redeadline) string)
2231 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2232 (cons (const :tag "Heading when refiling" refile) string)))
2234 (unless (assq 'note org-log-note-headings)
2235 (push '(note . "%t") org-log-note-headings))
2237 (defcustom org-log-into-drawer nil
2238 "Non-nil means insert state change notes and time stamps into a drawer.
2239 When nil, state changes notes will be inserted after the headline and
2240 any scheduling and clock lines, but not inside a drawer.
2242 The value of this variable should be the name of the drawer to use.
2243 LOGBOOK is proposed at the default drawer for this purpose, you can
2244 also set this to a string to define the drawer of your choice.
2246 A value of t is also allowed, representing \"LOGBOOK\".
2248 If this variable is set, `org-log-state-notes-insert-after-drawers'
2249 will be ignored.
2251 You can set the property LOG_INTO_DRAWER to overrule this setting for
2252 a subtree."
2253 :group 'org-todo
2254 :group 'org-progress
2255 :type '(choice
2256 (const :tag "Not into a drawer" nil)
2257 (const :tag "LOGBOOK" t)
2258 (string :tag "Other")))
2260 (if (fboundp 'defvaralias)
2261 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2263 (defun org-log-into-drawer ()
2264 "Return the value of `org-log-into-drawer', but let properties overrule.
2265 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2266 used instead of the default value."
2267 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2268 (cond
2269 ((or (not p) (equal p "nil")) org-log-into-drawer)
2270 ((equal p "t") "LOGBOOK")
2271 (t p))))
2273 (defcustom org-log-state-notes-insert-after-drawers nil
2274 "Non-nil means insert state change notes after any drawers in entry.
2275 Only the drawers that *immediately* follow the headline and the
2276 deadline/scheduled line are skipped.
2277 When nil, insert notes right after the heading and perhaps the line
2278 with deadline/scheduling if present.
2280 This variable will have no effect if `org-log-into-drawer' is
2281 set."
2282 :group 'org-todo
2283 :group 'org-progress
2284 :type 'boolean)
2286 (defcustom org-log-states-order-reversed t
2287 "Non-nil means the latest state note will be directly after heading.
2288 When nil, the state change notes will be ordered according to time."
2289 :group 'org-todo
2290 :group 'org-progress
2291 :type 'boolean)
2293 (defcustom org-todo-repeat-to-state nil
2294 "The TODO state to which a repeater should return the repeating task.
2295 By default this is the first task in a TODO sequence, or the previous state
2296 in a TODO_TYP set. But you can specify another task here.
2297 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2298 :group 'org-todo
2299 :type '(choice (const :tag "Head of sequence" nil)
2300 (string :tag "Specific state")))
2302 (defcustom org-log-repeat 'time
2303 "Non-nil means record moving through the DONE state when triggering repeat.
2304 An auto-repeating task is immediately switched back to TODO when
2305 marked DONE. If you are not logging state changes (by adding \"@\"
2306 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2307 record a closing note, there will be no record of the task moving
2308 through DONE. This variable forces taking a note anyway.
2310 nil Don't force a record
2311 time Record a time stamp
2312 note Record a note
2314 This option can also be set with on a per-file-basis with
2316 #+STARTUP: logrepeat
2317 #+STARTUP: lognoterepeat
2318 #+STARTUP: nologrepeat
2320 You can have local logging settings for a subtree by setting the LOGGING
2321 property to one or more of these keywords."
2322 :group 'org-todo
2323 :group 'org-progress
2324 :type '(choice
2325 (const :tag "Don't force a record" nil)
2326 (const :tag "Force recording the DONE state" time)
2327 (const :tag "Force recording a note with the DONE state" note)))
2330 (defgroup org-priorities nil
2331 "Priorities in Org-mode."
2332 :tag "Org Priorities"
2333 :group 'org-todo)
2335 (defcustom org-enable-priority-commands t
2336 "Non-nil means priority commands are active.
2337 When nil, these commands will be disabled, so that you never accidentally
2338 set a priority."
2339 :group 'org-priorities
2340 :type 'boolean)
2342 (defcustom org-highest-priority ?A
2343 "The highest priority of TODO items. A character like ?A, ?B etc.
2344 Must have a smaller ASCII number than `org-lowest-priority'."
2345 :group 'org-priorities
2346 :type 'character)
2348 (defcustom org-lowest-priority ?C
2349 "The lowest priority of TODO items. A character like ?A, ?B etc.
2350 Must have a larger ASCII number than `org-highest-priority'."
2351 :group 'org-priorities
2352 :type 'character)
2354 (defcustom org-default-priority ?B
2355 "The default priority of TODO items.
2356 This is the priority an item get if no explicit priority is given."
2357 :group 'org-priorities
2358 :type 'character)
2360 (defcustom org-priority-start-cycle-with-default t
2361 "Non-nil means start with default priority when starting to cycle.
2362 When this is nil, the first step in the cycle will be (depending on the
2363 command used) one higher or lower that the default priority."
2364 :group 'org-priorities
2365 :type 'boolean)
2367 (defgroup org-time nil
2368 "Options concerning time stamps and deadlines in Org-mode."
2369 :tag "Org Time"
2370 :group 'org)
2372 (defcustom org-insert-labeled-timestamps-at-point nil
2373 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2374 When nil, these labeled time stamps are forces into the second line of an
2375 entry, just after the headline. When scheduling from the global TODO list,
2376 the time stamp will always be forced into the second line."
2377 :group 'org-time
2378 :type 'boolean)
2380 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2381 "Formats for `format-time-string' which are used for time stamps.
2382 It is not recommended to change this constant.")
2384 (defcustom org-time-stamp-rounding-minutes '(0 5)
2385 "Number of minutes to round time stamps to.
2386 These are two values, the first applies when first creating a time stamp.
2387 The second applies when changing it with the commands `S-up' and `S-down'.
2388 When changing the time stamp, this means that it will change in steps
2389 of N minutes, as given by the second value.
2391 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2392 numbers should be factors of 60, so for example 5, 10, 15.
2394 When this is larger than 1, you can still force an exact time-stamp by using
2395 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2396 and by using a prefix arg to `S-up/down' to specify the exact number
2397 of minutes to shift."
2398 :group 'org-time
2399 :get '(lambda (var) ; Make sure both elements are there
2400 (if (integerp (default-value var))
2401 (list (default-value var) 5)
2402 (default-value var)))
2403 :type '(list
2404 (integer :tag "when inserting times")
2405 (integer :tag "when modifying times")))
2407 ;; Normalize old customizations of this variable.
2408 (when (integerp org-time-stamp-rounding-minutes)
2409 (setq org-time-stamp-rounding-minutes
2410 (list org-time-stamp-rounding-minutes
2411 org-time-stamp-rounding-minutes)))
2413 (defcustom org-display-custom-times nil
2414 "Non-nil means overlay custom formats over all time stamps.
2415 The formats are defined through the variable `org-time-stamp-custom-formats'.
2416 To turn this on on a per-file basis, insert anywhere in the file:
2417 #+STARTUP: customtime"
2418 :group 'org-time
2419 :set 'set-default
2420 :type 'sexp)
2421 (make-variable-buffer-local 'org-display-custom-times)
2423 (defcustom org-time-stamp-custom-formats
2424 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2425 "Custom formats for time stamps. See `format-time-string' for the syntax.
2426 These are overlayed over the default ISO format if the variable
2427 `org-display-custom-times' is set. Time like %H:%M should be at the
2428 end of the second format. The custom formats are also honored by export
2429 commands, if custom time display is turned on at the time of export."
2430 :group 'org-time
2431 :type 'sexp)
2433 (defun org-time-stamp-format (&optional long inactive)
2434 "Get the right format for a time string."
2435 (let ((f (if long (cdr org-time-stamp-formats)
2436 (car org-time-stamp-formats))))
2437 (if inactive
2438 (concat "[" (substring f 1 -1) "]")
2439 f)))
2441 (defcustom org-time-clocksum-format "%d:%02d"
2442 "The format string used when creating CLOCKSUM lines, or when
2443 org-mode generates a time duration."
2444 :group 'org-time
2445 :type 'string)
2447 (defcustom org-time-clocksum-use-fractional nil
2448 "If non-nil, \\[org-clock-display] uses fractional times.
2449 org-mode generates a time duration."
2450 :group 'org-time
2451 :type 'boolean)
2453 (defcustom org-time-clocksum-fractional-format "%.2f"
2454 "The format string used when creating CLOCKSUM lines, or when
2455 org-mode generates a time duration."
2456 :group 'org-time
2457 :type 'string)
2459 (defcustom org-deadline-warning-days 14
2460 "No. of days before expiration during which a deadline becomes active.
2461 This variable governs the display in sparse trees and in the agenda.
2462 When 0 or negative, it means use this number (the absolute value of it)
2463 even if a deadline has a different individual lead time specified.
2465 Custom commands can set this variable in the options section."
2466 :group 'org-time
2467 :group 'org-agenda-daily/weekly
2468 :type 'integer)
2470 (defcustom org-read-date-prefer-future t
2471 "Non-nil means assume future for incomplete date input from user.
2472 This affects the following situations:
2473 1. The user gives a month but not a year.
2474 For example, if it is april and you enter \"feb 2\", this will be read
2475 as feb 2, *next* year. \"May 5\", however, will be this year.
2476 2. The user gives a day, but no month.
2477 For example, if today is the 15th, and you enter \"3\", Org-mode will
2478 read this as the third of *next* month. However, if you enter \"17\",
2479 it will be considered as *this* month.
2481 If you set this variable to the symbol `time', then also the following
2482 will work:
2484 3. If the user gives a time, but no day. If the time is before now,
2485 to will be interpreted as tomorrow.
2487 Currently none of this works for ISO week specifications.
2489 When this option is nil, the current day, month and year will always be
2490 used as defaults."
2491 :group 'org-time
2492 :type '(choice
2493 (const :tag "Never" nil)
2494 (const :tag "Check month and day" t)
2495 (const :tag "Check month, day, and time" time)))
2497 (defcustom org-read-date-display-live t
2498 "Non-nil means display current interpretation of date prompt live.
2499 This display will be in an overlay, in the minibuffer."
2500 :group 'org-time
2501 :type 'boolean)
2503 (defcustom org-read-date-popup-calendar t
2504 "Non-nil means pop up a calendar when prompting for a date.
2505 In the calendar, the date can be selected with mouse-1. However, the
2506 minibuffer will also be active, and you can simply enter the date as well.
2507 When nil, only the minibuffer will be available."
2508 :group 'org-time
2509 :type 'boolean)
2510 (if (fboundp 'defvaralias)
2511 (defvaralias 'org-popup-calendar-for-date-prompt
2512 'org-read-date-popup-calendar))
2514 (defcustom org-read-date-minibuffer-setup-hook nil
2515 "Hook to be used to set up keys for the date/time interface.
2516 Add key definitions to `minibuffer-local-map', which will be a temporary
2517 copy."
2518 :group 'org-time
2519 :type 'hook)
2521 (defcustom org-extend-today-until 0
2522 "The hour when your day really ends. Must be an integer.
2523 This has influence for the following applications:
2524 - When switching the agenda to \"today\". It it is still earlier than
2525 the time given here, the day recognized as TODAY is actually yesterday.
2526 - When a date is read from the user and it is still before the time given
2527 here, the current date and time will be assumed to be yesterday, 23:59.
2528 Also, timestamps inserted in remember templates follow this rule.
2530 IMPORTANT: This is a feature whose implementation is and likely will
2531 remain incomplete. Really, it is only here because past midnight seems to
2532 be the favorite working time of John Wiegley :-)"
2533 :group 'org-time
2534 :type 'integer)
2536 (defcustom org-edit-timestamp-down-means-later nil
2537 "Non-nil means S-down will increase the time in a time stamp.
2538 When nil, S-up will increase."
2539 :group 'org-time
2540 :type 'boolean)
2542 (defcustom org-calendar-follow-timestamp-change t
2543 "Non-nil means make the calendar window follow timestamp changes.
2544 When a timestamp is modified and the calendar window is visible, it will be
2545 moved to the new date."
2546 :group 'org-time
2547 :type 'boolean)
2549 (defgroup org-tags nil
2550 "Options concerning tags in Org-mode."
2551 :tag "Org Tags"
2552 :group 'org)
2554 (defcustom org-tag-alist nil
2555 "List of tags allowed in Org-mode files.
2556 When this list is nil, Org-mode will base TAG input on what is already in the
2557 buffer.
2558 The value of this variable is an alist, the car of each entry must be a
2559 keyword as a string, the cdr may be a character that is used to select
2560 that tag through the fast-tag-selection interface.
2561 See the manual for details."
2562 :group 'org-tags
2563 :type '(repeat
2564 (choice
2565 (cons (string :tag "Tag name")
2566 (character :tag "Access char"))
2567 (list :tag "Start radio group"
2568 (const :startgroup)
2569 (option (string :tag "Group description")))
2570 (list :tag "End radio group"
2571 (const :endgroup)
2572 (option (string :tag "Group description")))
2573 (const :tag "New line" (:newline)))))
2575 (defcustom org-tag-persistent-alist nil
2576 "List of tags that will always appear in all Org-mode files.
2577 This is in addition to any in buffer settings or customizations
2578 of `org-tag-alist'.
2579 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2580 The value of this variable is an alist, the car of each entry must be a
2581 keyword as a string, the cdr may be a character that is used to select
2582 that tag through the fast-tag-selection interface.
2583 See the manual for details.
2584 To disable these tags on a per-file basis, insert anywhere in the file:
2585 #+STARTUP: noptag"
2586 :group 'org-tags
2587 :type '(repeat
2588 (choice
2589 (cons (string :tag "Tag name")
2590 (character :tag "Access char"))
2591 (const :tag "Start radio group" (:startgroup))
2592 (const :tag "End radio group" (:endgroup))
2593 (const :tag "New line" (:newline)))))
2595 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2596 "If non-nil, always offer completion for all tags of all agenda files.
2597 Instead of customizing this variable directly, you might want to
2598 set it locally for remember buffers, because there no list of
2599 tags in that file can be created dynamically (there are none).
2601 (add-hook 'org-remember-mode-hook
2602 (lambda ()
2603 (set (make-local-variable
2604 'org-complete-tags-always-offer-all-agenda-tags)
2605 t)))"
2606 :group 'org-tags
2607 :type 'boolean)
2609 (defvar org-file-tags nil
2610 "List of tags that can be inherited by all entries in the file.
2611 The tags will be inherited if the variable `org-use-tag-inheritance'
2612 says they should be.
2613 This variable is populated from #+FILETAGS lines.")
2615 (defcustom org-use-fast-tag-selection 'auto
2616 "Non-nil means use fast tag selection scheme.
2617 This is a special interface to select and deselect tags with single keys.
2618 When nil, fast selection is never used.
2619 When the symbol `auto', fast selection is used if and only if selection
2620 characters for tags have been configured, either through the variable
2621 `org-tag-alist' or through a #+TAGS line in the buffer.
2622 When t, fast selection is always used and selection keys are assigned
2623 automatically if necessary."
2624 :group 'org-tags
2625 :type '(choice
2626 (const :tag "Always" t)
2627 (const :tag "Never" nil)
2628 (const :tag "When selection characters are configured" 'auto)))
2630 (defcustom org-fast-tag-selection-single-key nil
2631 "Non-nil means fast tag selection exits after first change.
2632 When nil, you have to press RET to exit it.
2633 During fast tag selection, you can toggle this flag with `C-c'.
2634 This variable can also have the value `expert'. In this case, the window
2635 displaying the tags menu is not even shown, until you press C-c again."
2636 :group 'org-tags
2637 :type '(choice
2638 (const :tag "No" nil)
2639 (const :tag "Yes" t)
2640 (const :tag "Expert" expert)))
2642 (defvar org-fast-tag-selection-include-todo nil
2643 "Non-nil means fast tags selection interface will also offer TODO states.
2644 This is an undocumented feature, you should not rely on it.")
2646 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2647 "The column to which tags should be indented in a headline.
2648 If this number is positive, it specifies the column. If it is negative,
2649 it means that the tags should be flushright to that column. For example,
2650 -80 works well for a normal 80 character screen."
2651 :group 'org-tags
2652 :type 'integer)
2654 (defcustom org-auto-align-tags t
2655 "Non-nil means realign tags after pro/demotion of TODO state change.
2656 These operations change the length of a headline and therefore shift
2657 the tags around. With this options turned on, after each such operation
2658 the tags are again aligned to `org-tags-column'."
2659 :group 'org-tags
2660 :type 'boolean)
2662 (defcustom org-use-tag-inheritance t
2663 "Non-nil means tags in levels apply also for sublevels.
2664 When nil, only the tags directly given in a specific line apply there.
2665 This may also be a list of tags that should be inherited, or a regexp that
2666 matches tags that should be inherited. Additional control is possible
2667 with the variable `org-tags-exclude-from-inheritance' which gives an
2668 explicit list of tags to be excluded from inheritance., even if the value of
2669 `org-use-tag-inheritance' would select it for inheritance.
2671 If this option is t, a match early-on in a tree can lead to a large
2672 number of matches in the subtree when constructing the agenda or creating
2673 a sparse tree. If you only want to see the first match in a tree during
2674 a search, check out the variable `org-tags-match-list-sublevels'."
2675 :group 'org-tags
2676 :type '(choice
2677 (const :tag "Not" nil)
2678 (const :tag "Always" t)
2679 (repeat :tag "Specific tags" (string :tag "Tag"))
2680 (regexp :tag "Tags matched by regexp")))
2682 (defcustom org-tags-exclude-from-inheritance nil
2683 "List of tags that should never be inherited.
2684 This is a way to exclude a few tags from inheritance. For way to do
2685 the opposite, to actively allow inheritance for selected tags,
2686 see the variable `org-use-tag-inheritance'."
2687 :group 'org-tags
2688 :type '(repeat (string :tag "Tag")))
2690 (defun org-tag-inherit-p (tag)
2691 "Check if TAG is one that should be inherited."
2692 (cond
2693 ((member tag org-tags-exclude-from-inheritance) nil)
2694 ((eq org-use-tag-inheritance t) t)
2695 ((not org-use-tag-inheritance) nil)
2696 ((stringp org-use-tag-inheritance)
2697 (string-match org-use-tag-inheritance tag))
2698 ((listp org-use-tag-inheritance)
2699 (member tag org-use-tag-inheritance))
2700 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2702 (defcustom org-tags-match-list-sublevels t
2703 "Non-nil means list also sublevels of headlines matching a search.
2704 This variable applies to tags/property searches, and also to stuck
2705 projects because this search is based on a tags match as well.
2707 When set to the symbol `indented', sublevels are indented with
2708 leading dots.
2710 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2711 the sublevels of a headline matching a tag search often also match
2712 the same search. Listing all of them can create very long lists.
2713 Setting this variable to nil causes subtrees of a match to be skipped.
2715 This variable is semi-obsolete and probably should always be true. It
2716 is better to limit inheritance to certain tags using the variables
2717 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2718 :group 'org-tags
2719 :type '(choice
2720 (const :tag "No, don't list them" nil)
2721 (const :tag "Yes, do list them" t)
2722 (const :tag "List them, indented with leading dots" indented)))
2724 (defcustom org-tags-sort-function nil
2725 "When set, tags are sorted using this function as a comparator"
2726 :group 'org-tags
2727 :type '(choice
2728 (const :tag "No sorting" nil)
2729 (const :tag "Alphabetical" string<)
2730 (const :tag "Reverse alphabetical" string>)
2731 (function :tag "Custom function" nil)))
2733 (defvar org-tags-history nil
2734 "History of minibuffer reads for tags.")
2735 (defvar org-last-tags-completion-table nil
2736 "The last used completion table for tags.")
2737 (defvar org-after-tags-change-hook nil
2738 "Hook that is run after the tags in a line have changed.")
2740 (defgroup org-properties nil
2741 "Options concerning properties in Org-mode."
2742 :tag "Org Properties"
2743 :group 'org)
2745 (defcustom org-property-format "%-10s %s"
2746 "How property key/value pairs should be formatted by `indent-line'.
2747 When `indent-line' hits a property definition, it will format the line
2748 according to this format, mainly to make sure that the values are
2749 lined-up with respect to each other."
2750 :group 'org-properties
2751 :type 'string)
2753 (defcustom org-use-property-inheritance nil
2754 "Non-nil means properties apply also for sublevels.
2756 This setting is chiefly used during property searches. Turning it on can
2757 cause significant overhead when doing a search, which is why it is not
2758 on by default.
2760 When nil, only the properties directly given in the current entry count.
2761 When t, every property is inherited. The value may also be a list of
2762 properties that should have inheritance, or a regular expression matching
2763 properties that should be inherited.
2765 However, note that some special properties use inheritance under special
2766 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2767 and the properties ending in \"_ALL\" when they are used as descriptor
2768 for valid values of a property.
2770 Note for programmers:
2771 When querying an entry with `org-entry-get', you can control if inheritance
2772 should be used. By default, `org-entry-get' looks only at the local
2773 properties. You can request inheritance by setting the inherit argument
2774 to t (to force inheritance) or to `selective' (to respect the setting
2775 in this variable)."
2776 :group 'org-properties
2777 :type '(choice
2778 (const :tag "Not" nil)
2779 (const :tag "Always" t)
2780 (repeat :tag "Specific properties" (string :tag "Property"))
2781 (regexp :tag "Properties matched by regexp")))
2783 (defun org-property-inherit-p (property)
2784 "Check if PROPERTY is one that should be inherited."
2785 (cond
2786 ((eq org-use-property-inheritance t) t)
2787 ((not org-use-property-inheritance) nil)
2788 ((stringp org-use-property-inheritance)
2789 (string-match org-use-property-inheritance property))
2790 ((listp org-use-property-inheritance)
2791 (member property org-use-property-inheritance))
2792 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2794 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2795 "The default column format, if no other format has been defined.
2796 This variable can be set on the per-file basis by inserting a line
2798 #+COLUMNS: %25ITEM ....."
2799 :group 'org-properties
2800 :type 'string)
2802 (defcustom org-columns-ellipses ".."
2803 "The ellipses to be used when a field in column view is truncated.
2804 When this is the empty string, as many characters as possible are shown,
2805 but then there will be no visual indication that the field has been truncated.
2806 When this is a string of length N, the last N characters of a truncated
2807 field are replaced by this string. If the column is narrower than the
2808 ellipses string, only part of the ellipses string will be shown."
2809 :group 'org-properties
2810 :type 'string)
2812 (defcustom org-columns-modify-value-for-display-function nil
2813 "Function that modifies values for display in column view.
2814 For example, it can be used to cut out a certain part from a time stamp.
2815 The function must take 2 arguments:
2817 column-title The title of the column (*not* the property name)
2818 value The value that should be modified.
2820 The function should return the value that should be displayed,
2821 or nil if the normal value should be used."
2822 :group 'org-properties
2823 :type 'function)
2825 (defcustom org-effort-property "Effort"
2826 "The property that is being used to keep track of effort estimates.
2827 Effort estimates given in this property need to have the format H:MM."
2828 :group 'org-properties
2829 :group 'org-progress
2830 :type '(string :tag "Property"))
2832 (defconst org-global-properties-fixed
2833 '(("VISIBILITY_ALL" . "folded children content all")
2834 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2835 "List of property/value pairs that can be inherited by any entry.
2837 These are fixed values, for the preset properties. The user variable
2838 that can be used to add to this list is `org-global-properties'.
2840 The entries in this list are cons cells where the car is a property
2841 name and cdr is a string with the value. If the value represents
2842 multiple items like an \"_ALL\" property, separate the items by
2843 spaces.")
2845 (defcustom org-global-properties nil
2846 "List of property/value pairs that can be inherited by any entry.
2848 This list will be combined with the constant `org-global-properties-fixed'.
2850 The entries in this list are cons cells where the car is a property
2851 name and cdr is a string with the value.
2853 You can set buffer-local values for the same purpose in the variable
2854 `org-file-properties' this by adding lines like
2856 #+PROPERTY: NAME VALUE"
2857 :group 'org-properties
2858 :type '(repeat
2859 (cons (string :tag "Property")
2860 (string :tag "Value"))))
2862 (defvar org-file-properties nil
2863 "List of property/value pairs that can be inherited by any entry.
2864 Valid for the current buffer.
2865 This variable is populated from #+PROPERTY lines.")
2866 (make-variable-buffer-local 'org-file-properties)
2868 (defgroup org-agenda nil
2869 "Options concerning agenda views in Org-mode."
2870 :tag "Org Agenda"
2871 :group 'org)
2873 (defvar org-category nil
2874 "Variable used by org files to set a category for agenda display.
2875 Such files should use a file variable to set it, for example
2877 # -*- mode: org; org-category: \"ELisp\"
2879 or contain a special line
2881 #+CATEGORY: ELisp
2883 If the file does not specify a category, then file's base name
2884 is used instead.")
2885 (make-variable-buffer-local 'org-category)
2886 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2888 (defcustom org-agenda-files nil
2889 "The files to be used for agenda display.
2890 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2891 \\[org-remove-file]. You can also use customize to edit the list.
2893 If an entry is a directory, all files in that directory that are matched by
2894 `org-agenda-file-regexp' will be part of the file list.
2896 If the value of the variable is not a list but a single file name, then
2897 the list of agenda files is actually stored and maintained in that file, one
2898 agenda file per line. In this file paths can be given relative to
2899 `org-directory'. Tilde expansion and environment variable substitution
2900 are also made."
2901 :group 'org-agenda
2902 :type '(choice
2903 (repeat :tag "List of files and directories" file)
2904 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2906 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2907 "Regular expression to match files for `org-agenda-files'.
2908 If any element in the list in that variable contains a directory instead
2909 of a normal file, all files in that directory that are matched by this
2910 regular expression will be included."
2911 :group 'org-agenda
2912 :type 'regexp)
2914 (defcustom org-agenda-text-search-extra-files nil
2915 "List of extra files to be searched by text search commands.
2916 These files will be search in addition to the agenda files by the
2917 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2918 Note that these files will only be searched for text search commands,
2919 not for the other agenda views like todo lists, tag searches or the weekly
2920 agenda. This variable is intended to list notes and possibly archive files
2921 that should also be searched by these two commands.
2922 In fact, if the first element in the list is the symbol `agenda-archives',
2923 than all archive files of all agenda files will be added to the search
2924 scope."
2925 :group 'org-agenda
2926 :type '(set :greedy t
2927 (const :tag "Agenda Archives" agenda-archives)
2928 (repeat :inline t (file))))
2930 (if (fboundp 'defvaralias)
2931 (defvaralias 'org-agenda-multi-occur-extra-files
2932 'org-agenda-text-search-extra-files))
2934 (defcustom org-agenda-skip-unavailable-files nil
2935 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2936 A nil value means to remove them, after a query, from the list."
2937 :group 'org-agenda
2938 :type 'boolean)
2940 (defcustom org-calendar-to-agenda-key [?c]
2941 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2942 The command `org-calendar-goto-agenda' will be bound to this key. The
2943 default is the character `c' because then `c' can be used to switch back and
2944 forth between agenda and calendar."
2945 :group 'org-agenda
2946 :type 'sexp)
2948 (defcustom org-calendar-agenda-action-key [?k]
2949 "The key to be installed in `calendar-mode-map' for agenda-action.
2950 The command `org-agenda-action' will be bound to this key. The
2951 default is the character `k' because we use the same key in the agenda."
2952 :group 'org-agenda
2953 :type 'sexp)
2955 (defcustom org-calendar-insert-diary-entry-key [?i]
2956 "The key to be installed in `calendar-mode-map' for adding diary entries.
2957 This option is irrelevant until `org-agenda-diary-file' has been configured
2958 to point to an Org-mode file. When that is the case, the command
2959 `org-agenda-diary-entry' will be bound to the key given here, by default
2960 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2961 if you want to continue doing this, you need to change this to a different
2962 key."
2963 :group 'org-agenda
2964 :type 'sexp)
2966 (defcustom org-agenda-diary-file 'diary-file
2967 "File to which to add new entries with the `i' key in agenda and calendar.
2968 When this is the symbol `diary-file', the functionality in the Emacs
2969 calendar will be used to add entries to the `diary-file'. But when this
2970 points to a file, `org-agenda-diary-entry' will be used instead."
2971 :group 'org-agenda
2972 :type '(choice
2973 (const :tag "The standard Emacs diary file" diary-file)
2974 (file :tag "Special Org file diary entries")))
2976 (eval-after-load "calendar"
2977 '(progn
2978 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2979 'org-calendar-goto-agenda)
2980 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2981 'org-agenda-action)
2982 (add-hook 'calendar-mode-hook
2983 (lambda ()
2984 (unless (eq org-agenda-diary-file 'diary-file)
2985 (define-key calendar-mode-map
2986 org-calendar-insert-diary-entry-key
2987 'org-agenda-diary-entry))))))
2989 (defgroup org-latex nil
2990 "Options for embedding LaTeX code into Org-mode."
2991 :tag "Org LaTeX"
2992 :group 'org)
2994 (defcustom org-format-latex-options
2995 '(:foreground default :background default :scale 1.0
2996 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2997 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2998 "Options for creating images from LaTeX fragments.
2999 This is a property list with the following properties:
3000 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3001 `default' means use the foreground of the default face.
3002 :background the background color, or \"Transparent\".
3003 `default' means use the background of the default face.
3004 :scale a scaling factor for the size of the images.
3005 :html-foreground, :html-background, :html-scale
3006 the same numbers for HTML export.
3007 :matchers a list indicating which matchers should be used to
3008 find LaTeX fragments. Valid members of this list are:
3009 \"begin\" find environments
3010 \"$1\" find single characters surrounded by $.$
3011 \"$\" find math expressions surrounded by $...$
3012 \"$$\" find math expressions surrounded by $$....$$
3013 \"\\(\" find math expressions surrounded by \\(...\\)
3014 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3015 :group 'org-latex
3016 :type 'plist)
3018 (defcustom org-format-latex-signal-error t
3019 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3020 When nil, just push out a message."
3021 :group 'org-latex
3022 :type 'boolean)
3024 (defcustom org-format-latex-header "\\documentclass{article}
3025 \\usepackage[usenames]{color}
3026 \\usepackage{amsmath}
3027 \\usepackage[mathscr]{eucal}
3028 \\pagestyle{empty} % do not remove
3029 \[PACKAGES]
3030 \[DEFAULT-PACKAGES]
3031 % The settings below are copied from fullpage.sty
3032 \\setlength{\\textwidth}{\\paperwidth}
3033 \\addtolength{\\textwidth}{-3cm}
3034 \\setlength{\\oddsidemargin}{1.5cm}
3035 \\addtolength{\\oddsidemargin}{-2.54cm}
3036 \\setlength{\\evensidemargin}{\\oddsidemargin}
3037 \\setlength{\\textheight}{\\paperheight}
3038 \\addtolength{\\textheight}{-\\headheight}
3039 \\addtolength{\\textheight}{-\\headsep}
3040 \\addtolength{\\textheight}{-\\footskip}
3041 \\addtolength{\\textheight}{-3cm}
3042 \\setlength{\\topmargin}{1.5cm}
3043 \\addtolength{\\topmargin}{-2.54cm}"
3044 "The document header used for processing LaTeX fragments.
3045 It is imperative that this header make sure that no page number
3046 appears on the page. The package defined in the variables
3047 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3048 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3049 will be appended."
3050 :group 'org-latex
3051 :type 'string)
3053 (defvar org-format-latex-header-extra nil)
3055 (defun org-set-packages-alist (var val)
3056 "Set the packages alist and make sure it has 3 elements per entry."
3057 (set var (mapcar (lambda (x)
3058 (if (and (consp x) (= (length x) 2))
3059 (list (car x) (nth 1 x) t)
3061 val)))
3063 (defun org-get-packages-alist (var)
3065 "Get the packages alist and make sure it has 3 elements per entry."
3066 (mapcar (lambda (x)
3067 (if (and (consp x) (= (length x) 2))
3068 (list (car x) (nth 1 x) t)
3070 (default-value var)))
3072 ;; The following variables are defined here because is it also used
3073 ;; when formatting latex fragments. Originally it was part of the
3074 ;; LaTeX exporter, which is why the name includes "export".
3075 (defcustom org-export-latex-default-packages-alist
3076 '(("AUTO" "inputenc" t)
3077 ("T1" "fontenc" t)
3078 ("" "fixltx2e" nil)
3079 ("" "graphicx" t)
3080 ("" "longtable" nil)
3081 ("" "float" nil)
3082 ("" "wrapfig" nil)
3083 ("" "soul" t)
3084 ("" "t1enc" t)
3085 ("" "textcomp" t)
3086 ("" "marvosym" t)
3087 ("" "wasysym" t)
3088 ("" "latexsym" t)
3089 ("" "amssymb" t)
3090 ("" "hyperref" nil)
3091 "\\tolerance=1000"
3093 "Alist of default packages to be inserted in the header.
3094 Change this only if one of the packages here causes an incompatibility
3095 with another package you are using.
3096 The packages in this list are needed by one part or another of Org-mode
3097 to function properly.
3099 - inputenc, fontenc, t1enc: for basic font and character selection
3100 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3101 for interpreting the entities in `org-entities'. You can skip some of these
3102 packages if you don't use any of the symbols in it.
3103 - graphicx: for including images
3104 - float, wrapfig: for figure placement
3105 - longtable: for long tables
3106 - hyperref: for cross references
3108 Therefore you should not modify this variable unless you know what you
3109 are doing. The one reason to change it anyway is that you might be loading
3110 some other package that conflicts with one of the default packages.
3111 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3112 If SNIPPET-FLAG is t, the package also needs to be included when
3113 compiling LaTeX snippets into images for inclusion into HTML."
3114 :group 'org-export-latex
3115 :set 'org-set-packages-alist
3116 :get 'org-get-packages-alist
3117 :type '(repeat
3118 (choice
3119 (list :tag "options/package pair"
3120 (string :tag "options")
3121 (string :tag "package")
3122 (boolean :tag "Snippet"))
3123 (string :tag "A line of LaTeX"))))
3125 (defcustom org-export-latex-packages-alist nil
3126 "Alist of packages to be inserted in every LaTeX header.
3127 These will be inserted after `org-export-latex-default-packages-alist'.
3128 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3129 SNIPPET-FLAG, when t, indicates that this package is also needed when
3130 turning LaTeX snippets into images for inclusion into HTML.
3131 Make sure that you only list packages here which:
3132 - you want in every file
3133 - do not conflict with the default packages in
3134 `org-export-latex-default-packages-alist'
3135 - do not conflict with the setup in `org-format-latex-header'."
3136 :group 'org-export-latex
3137 :set 'org-set-packages-alist
3138 :get 'org-get-packages-alist
3139 :type '(repeat
3140 (choice
3141 (list :tag "options/package pair"
3142 (string :tag "options")
3143 (string :tag "package")
3144 (boolean :tag "Snippet"))
3145 (string :tag "A line of LaTeX"))))
3148 (defgroup org-appearance nil
3149 "Settings for Org-mode appearance."
3150 :tag "Org Appearance"
3151 :group 'org)
3153 (defcustom org-level-color-stars-only nil
3154 "Non-nil means fontify only the stars in each headline.
3155 When nil, the entire headline is fontified.
3156 Changing it requires restart of `font-lock-mode' to become effective
3157 also in regions already fontified."
3158 :group 'org-appearance
3159 :type 'boolean)
3161 (defcustom org-hide-leading-stars nil
3162 "Non-nil means hide the first N-1 stars in a headline.
3163 This works by using the face `org-hide' for these stars. This
3164 face is white for a light background, and black for a dark
3165 background. You may have to customize the face `org-hide' to
3166 make this work.
3167 Changing it requires restart of `font-lock-mode' to become effective
3168 also in regions already fontified.
3169 You may also set this on a per-file basis by adding one of the following
3170 lines to the buffer:
3172 #+STARTUP: hidestars
3173 #+STARTUP: showstars"
3174 :group 'org-appearance
3175 :type 'boolean)
3177 (defcustom org-hidden-keywords nil
3178 "List of keywords that should be hidden when typed in the org buffer.
3179 For example, add #+TITLE to this list in order to make the
3180 document title appear in the buffer without the initial #+TITLE:
3181 keyword."
3182 :group 'org-appearance
3183 :type '(set (const :tag "#+AUTHOR" author)
3184 (const :tag "#+DATE" date)
3185 (const :tag "#+EMAIL" email)
3186 (const :tag "#+TITLE" title)))
3188 (defcustom org-fontify-done-headline nil
3189 "Non-nil means change the face of a headline if it is marked DONE.
3190 Normally, only the TODO/DONE keyword indicates the state of a headline.
3191 When this is non-nil, the headline after the keyword is set to the
3192 `org-headline-done' as an additional indication."
3193 :group 'org-appearance
3194 :type 'boolean)
3196 (defcustom org-fontify-emphasized-text t
3197 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3198 Changing this variable requires a restart of Emacs to take effect."
3199 :group 'org-appearance
3200 :type 'boolean)
3202 (defcustom org-fontify-whole-heading-line nil
3203 "Non-nil means fontify the whole line for headings.
3204 This is useful when setting a background color for the
3205 org-level-* faces."
3206 :group 'org-appearance
3207 :type 'boolean)
3209 (defcustom org-highlight-latex-fragments-and-specials nil
3210 "Non-nil means fontify what is treated specially by the exporters."
3211 :group 'org-appearance
3212 :type 'boolean)
3214 (defcustom org-hide-emphasis-markers nil
3215 "Non-nil mean font-lock should hide the emphasis marker characters."
3216 :group 'org-appearance
3217 :type 'boolean)
3219 (defcustom org-pretty-entities nil
3220 "Non-nil means show entities as UTF8 characters.
3221 When nil, the \\name form remains in the buffer."
3222 :group 'org-appearance
3223 :type 'boolean)
3225 (defcustom org-pretty-entities-include-sub-superscripts t
3226 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3227 :group 'org-appearance
3228 :type 'boolean)
3230 (defvar org-emph-re nil
3231 "Regular expression for matching emphasis.
3232 After a match, the match groups contain these elements:
3233 1 The character before the proper match, or empty at beginning of line
3234 2 The proper match, including the leading and trailing markers
3235 3 The leading marker like * or /, indicating the type of highlighting
3236 4 The text between the emphasis markers, not including the markers
3237 5 The character after the match, empty at the end of a line")
3238 (defvar org-verbatim-re nil
3239 "Regular expression for matching verbatim text.")
3240 (defvar org-emphasis-regexp-components) ; defined just below
3241 (defvar org-emphasis-alist) ; defined just below
3242 (defun org-set-emph-re (var val)
3243 "Set variable and compute the emphasis regular expression."
3244 (set var val)
3245 (when (and (boundp 'org-emphasis-alist)
3246 (boundp 'org-emphasis-regexp-components)
3247 org-emphasis-alist org-emphasis-regexp-components)
3248 (let* ((e org-emphasis-regexp-components)
3249 (pre (car e))
3250 (post (nth 1 e))
3251 (border (nth 2 e))
3252 (body (nth 3 e))
3253 (nl (nth 4 e))
3254 (body1 (concat body "*?"))
3255 (markers (mapconcat 'car org-emphasis-alist ""))
3256 (vmarkers (mapconcat
3257 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3258 org-emphasis-alist "")))
3259 ;; make sure special characters appear at the right position in the class
3260 (if (string-match "\\^" markers)
3261 (setq markers (concat (replace-match "" t t markers) "^")))
3262 (if (string-match "-" markers)
3263 (setq markers (concat (replace-match "" t t markers) "-")))
3264 (if (string-match "\\^" vmarkers)
3265 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3266 (if (string-match "-" vmarkers)
3267 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3268 (if (> nl 0)
3269 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3270 (int-to-string nl) "\\}")))
3271 ;; Make the regexp
3272 (setq org-emph-re
3273 (concat "\\([" pre "]\\|^\\)"
3274 "\\("
3275 "\\([" markers "]\\)"
3276 "\\("
3277 "[^" border "]\\|"
3278 "[^" border "]"
3279 body1
3280 "[^" border "]"
3281 "\\)"
3282 "\\3\\)"
3283 "\\([" post "]\\|$\\)"))
3284 (setq org-verbatim-re
3285 (concat "\\([" pre "]\\|^\\)"
3286 "\\("
3287 "\\([" vmarkers "]\\)"
3288 "\\("
3289 "[^" border "]\\|"
3290 "[^" border "]"
3291 body1
3292 "[^" border "]"
3293 "\\)"
3294 "\\3\\)"
3295 "\\([" post "]\\|$\\)")))))
3297 (defcustom org-emphasis-regexp-components
3298 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3299 "Components used to build the regular expression for emphasis.
3300 This is a list with 6 entries. Terminology: In an emphasis string
3301 like \" *strong word* \", we call the initial space PREMATCH, the final
3302 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3303 and \"trong wor\" is the body. The different components in this variable
3304 specify what is allowed/forbidden in each part:
3306 pre Chars allowed as prematch. Beginning of line will be allowed too.
3307 post Chars allowed as postmatch. End of line will be allowed too.
3308 border The chars *forbidden* as border characters.
3309 body-regexp A regexp like \".\" to match a body character. Don't use
3310 non-shy groups here, and don't allow newline here.
3311 newline The maximum number of newlines allowed in an emphasis exp.
3313 Use customize to modify this, or restart Emacs after changing it."
3314 :group 'org-appearance
3315 :set 'org-set-emph-re
3316 :type '(list
3317 (sexp :tag "Allowed chars in pre ")
3318 (sexp :tag "Allowed chars in post ")
3319 (sexp :tag "Forbidden chars in border ")
3320 (sexp :tag "Regexp for body ")
3321 (integer :tag "number of newlines allowed")
3322 (option (boolean :tag "Please ignore this button"))))
3324 (defcustom org-emphasis-alist
3325 `(("*" bold "<b>" "</b>")
3326 ("/" italic "<i>" "</i>")
3327 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3328 ("=" org-code "<code>" "</code>" verbatim)
3329 ("~" org-verbatim "<code>" "</code>" verbatim)
3330 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3331 "<del>" "</del>")
3333 "Special syntax for emphasized text.
3334 Text starting and ending with a special character will be emphasized, for
3335 example *bold*, _underlined_ and /italic/. This variable sets the marker
3336 characters, the face to be used by font-lock for highlighting in Org-mode
3337 Emacs buffers, and the HTML tags to be used for this.
3338 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3339 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3340 Use customize to modify this, or restart Emacs after changing it."
3341 :group 'org-appearance
3342 :set 'org-set-emph-re
3343 :type '(repeat
3344 (list
3345 (string :tag "Marker character")
3346 (choice
3347 (face :tag "Font-lock-face")
3348 (plist :tag "Face property list"))
3349 (string :tag "HTML start tag")
3350 (string :tag "HTML end tag")
3351 (option (const verbatim)))))
3353 (defvar org-protecting-blocks
3354 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3355 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3356 This is needed for font-lock setup.")
3358 ;;; Miscellaneous options
3360 (defgroup org-completion nil
3361 "Completion in Org-mode."
3362 :tag "Org Completion"
3363 :group 'org)
3365 (defcustom org-completion-use-ido nil
3366 "Non-nil means use ido completion wherever possible.
3367 Note that `ido-mode' must be active for this variable to be relevant.
3368 If you decide to turn this variable on, you might well want to turn off
3369 `org-outline-path-complete-in-steps'.
3370 See also `org-completion-use-iswitchb'."
3371 :group 'org-completion
3372 :type 'boolean)
3374 (defcustom org-completion-use-iswitchb nil
3375 "Non-nil means use iswitchb completion wherever possible.
3376 Note that `iswitchb-mode' must be active for this variable to be relevant.
3377 If you decide to turn this variable on, you might well want to turn off
3378 `org-outline-path-complete-in-steps'.
3379 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3380 :group 'org-completion
3381 :type 'boolean)
3383 (defcustom org-completion-fallback-command 'hippie-expand
3384 "The expansion command called by \\[org-complete] in normal context.
3385 Normal means no org-mode-specific context."
3386 :group 'org-completion
3387 :type 'function)
3389 ;;; Functions and variables from their packages
3390 ;; Declared here to avoid compiler warnings
3392 ;; XEmacs only
3393 (defvar outline-mode-menu-heading)
3394 (defvar outline-mode-menu-show)
3395 (defvar outline-mode-menu-hide)
3396 (defvar zmacs-regions) ; XEmacs regions
3398 ;; Emacs only
3399 (defvar mark-active)
3401 ;; Various packages
3402 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3403 (declare-function calendar-forward-day "cal-move" (arg))
3404 (declare-function calendar-goto-date "cal-move" (date))
3405 (declare-function calendar-goto-today "cal-move" ())
3406 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3407 (defvar calc-embedded-close-formula)
3408 (defvar calc-embedded-open-formula)
3409 (declare-function cdlatex-tab "ext:cdlatex" ())
3410 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3411 (defvar font-lock-unfontify-region-function)
3412 (declare-function iswitchb-read-buffer "iswitchb"
3413 (prompt &optional default require-match start matches-set))
3414 (defvar iswitchb-temp-buflist)
3415 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3416 (defvar org-agenda-tags-todo-honor-ignore-options)
3417 (declare-function org-agenda-skip "org-agenda" ())
3418 (declare-function
3419 org-format-agenda-item "org-agenda"
3420 (extra txt &optional category tags dotime noprefix remove-re habitp))
3421 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3422 (declare-function org-agenda-change-all-lines "org-agenda"
3423 (newhead hdmarker &optional fixface just-this))
3424 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3425 (declare-function org-agenda-maybe-redo "org-agenda" ())
3426 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3427 (beg end))
3428 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3429 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3430 "org-agenda" (&optional end))
3431 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3432 (declare-function org-indent-mode "org-indent" (&optional arg))
3433 (declare-function parse-time-string "parse-time" (string))
3434 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3435 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3436 (defvar remember-data-file)
3437 (defvar texmathp-why)
3438 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3439 (declare-function table--at-cell-p "table" (position &optional object at-column))
3441 (defvar w3m-current-url)
3442 (defvar w3m-current-title)
3444 (defvar org-latex-regexps)
3446 ;;; Autoload and prepare some org modules
3448 ;; Some table stuff that needs to be defined here, because it is used
3449 ;; by the functions setting up org-mode or checking for table context.
3451 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3452 "Detects an org-type or table-type table.")
3453 (defconst org-table-line-regexp "^[ \t]*|"
3454 "Detects an org-type table line.")
3455 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3456 "Detects an org-type table line.")
3457 (defconst org-table-hline-regexp "^[ \t]*|-"
3458 "Detects an org-type table hline.")
3459 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3460 "Detects a table-type table hline.")
3461 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3462 "Searching from within a table (any type) this finds the first line
3463 outside the table.")
3465 ;; Autoload the functions in org-table.el that are needed by functions here.
3467 (eval-and-compile
3468 (org-autoload "org-table"
3469 '(org-table-align org-table-begin org-table-blank-field
3470 org-table-convert org-table-convert-region org-table-copy-down
3471 org-table-copy-region org-table-create
3472 org-table-create-or-convert-from-region
3473 org-table-create-with-table.el org-table-current-dline
3474 org-table-cut-region org-table-delete-column org-table-edit-field
3475 org-table-edit-formulas org-table-end org-table-eval-formula
3476 org-table-export org-table-field-info
3477 org-table-get-stored-formulas org-table-goto-column
3478 org-table-hline-and-move org-table-import org-table-insert-column
3479 org-table-insert-hline org-table-insert-row org-table-iterate
3480 org-table-justify-field-maybe org-table-kill-row
3481 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3482 org-table-move-column org-table-move-column-left
3483 org-table-move-column-right org-table-move-row
3484 org-table-move-row-down org-table-move-row-up
3485 org-table-next-field org-table-next-row org-table-paste-rectangle
3486 org-table-previous-field org-table-recalculate
3487 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3488 org-table-toggle-coordinate-overlays
3489 org-table-toggle-formula-debugger org-table-wrap-region
3490 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3492 (defun org-at-table-p (&optional table-type)
3493 "Return t if the cursor is inside an org-type table.
3494 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3495 (if org-enable-table-editor
3496 (save-excursion
3497 (beginning-of-line 1)
3498 (looking-at (if table-type org-table-any-line-regexp
3499 org-table-line-regexp)))
3500 nil))
3501 (defsubst org-table-p () (org-at-table-p))
3503 (defun org-at-table.el-p ()
3504 "Return t if and only if we are at a table.el table."
3505 (and (org-at-table-p 'any)
3506 (save-excursion
3507 (goto-char (org-table-begin 'any))
3508 (looking-at org-table1-hline-regexp))))
3509 (defun org-table-recognize-table.el ()
3510 "If there is a table.el table nearby, recognize it and move into it."
3511 (if org-table-tab-recognizes-table.el
3512 (if (org-at-table.el-p)
3513 (progn
3514 (beginning-of-line 1)
3515 (if (looking-at org-table-dataline-regexp)
3517 (if (looking-at org-table1-hline-regexp)
3518 (progn
3519 (beginning-of-line 2)
3520 (if (looking-at org-table-any-border-regexp)
3521 (beginning-of-line -1)))))
3522 (if (re-search-forward "|" (org-table-end t) t)
3523 (progn
3524 (require 'table)
3525 (if (table--at-cell-p (point))
3527 (message "recognizing table.el table...")
3528 (table-recognize-table)
3529 (message "recognizing table.el table...done")))
3530 (error "This should not happen..."))
3532 nil)
3533 nil))
3535 (defun org-at-table-hline-p ()
3536 "Return t if the cursor is inside a hline in a table."
3537 (if org-enable-table-editor
3538 (save-excursion
3539 (beginning-of-line 1)
3540 (looking-at org-table-hline-regexp))
3541 nil))
3543 (defvar org-table-clean-did-remove-column nil)
3545 (defun org-table-map-tables (function &optional quietly)
3546 "Apply FUNCTION to the start of all tables in the buffer."
3547 (save-excursion
3548 (save-restriction
3549 (widen)
3550 (goto-char (point-min))
3551 (while (re-search-forward org-table-any-line-regexp nil t)
3552 (unless quietly
3553 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3554 (beginning-of-line 1)
3555 (when (looking-at org-table-line-regexp)
3556 (save-excursion (funcall function))
3557 (or (looking-at org-table-line-regexp)
3558 (forward-char 1)))
3559 (re-search-forward org-table-any-border-regexp nil 1))))
3560 (unless quietly (message "Mapping tables: done")))
3562 ;; Declare and autoload functions from org-exp.el & Co
3564 (declare-function org-default-export-plist "org-exp")
3565 (declare-function org-infile-export-plist "org-exp")
3566 (declare-function org-get-current-options "org-exp")
3567 (eval-and-compile
3568 (org-autoload "org-exp"
3569 '(org-export org-export-visible
3570 org-insert-export-options-template
3571 org-table-clean-before-export))
3572 (org-autoload "org-ascii"
3573 '(org-export-as-ascii org-export-ascii-preprocess
3574 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3575 org-export-region-as-ascii))
3576 (org-autoload "org-latex"
3577 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3578 org-replace-region-by-latex org-export-region-as-latex
3579 org-export-as-latex org-export-as-pdf
3580 org-export-as-pdf-and-open))
3581 (org-autoload "org-html"
3582 '(org-export-as-html-and-open
3583 org-export-as-html-batch org-export-as-html-to-buffer
3584 org-replace-region-by-html org-export-region-as-html
3585 org-export-as-html))
3586 (org-autoload "org-docbook"
3587 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3588 org-replace-region-by-docbook org-export-region-as-docbook
3589 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3590 org-export-as-docbook))
3591 (org-autoload "org-icalendar"
3592 '(org-export-icalendar-this-file
3593 org-export-icalendar-all-agenda-files
3594 org-export-icalendar-combine-agenda-files))
3595 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3596 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3598 ;; Declare and autoload functions from org-agenda.el
3600 (eval-and-compile
3601 (org-autoload "org-agenda"
3602 '(org-agenda org-agenda-list org-search-view
3603 org-todo-list org-tags-view org-agenda-list-stuck-projects
3604 org-diary org-agenda-to-appt
3605 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3607 ;; Autoload org-remember
3609 (eval-and-compile
3610 (org-autoload "org-remember"
3611 '(org-remember-insinuate org-remember-annotation
3612 org-remember-apply-template org-remember org-remember-handler)))
3614 ;; Autoload org-clock.el
3617 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3618 (beg end))
3619 (declare-function org-clock-update-mode-line "org-clock" ())
3620 (declare-function org-resolve-clocks "org-clock"
3621 (&optional also-non-dangling-p prompt last-valid))
3622 (defvar org-clock-start-time)
3623 (defvar org-clock-marker (make-marker)
3624 "Marker recording the last clock-in.")
3625 (defvar org-clock-hd-marker (make-marker)
3626 "Marker recording the last clock-in, but the headline position.")
3627 (defvar org-clock-heading ""
3628 "The heading of the current clock entry.")
3629 (defun org-clock-is-active ()
3630 "Return non-nil if clock is currently running.
3631 The return value is actually the clock marker."
3632 (marker-buffer org-clock-marker))
3634 (eval-and-compile
3635 (org-autoload
3636 "org-clock"
3637 '(org-clock-in org-clock-out org-clock-cancel
3638 org-clock-goto org-clock-sum org-clock-display
3639 org-clock-remove-overlays org-clock-report
3640 org-clocktable-shift org-dblock-write:clocktable
3641 org-get-clocktable org-resolve-clocks)))
3643 (defun org-clock-update-time-maybe ()
3644 "If this is a CLOCK line, update it and return t.
3645 Otherwise, return nil."
3646 (interactive)
3647 (save-excursion
3648 (beginning-of-line 1)
3649 (skip-chars-forward " \t")
3650 (when (looking-at org-clock-string)
3651 (let ((re (concat "[ \t]*" org-clock-string
3652 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3653 "\\([ \t]*=>.*\\)?\\)?"))
3654 ts te h m s neg)
3655 (cond
3656 ((not (looking-at re))
3657 nil)
3658 ((not (match-end 2))
3659 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3660 (> org-clock-marker (point))
3661 (<= org-clock-marker (point-at-eol)))
3662 ;; The clock is running here
3663 (setq org-clock-start-time
3664 (apply 'encode-time
3665 (org-parse-time-string (match-string 1))))
3666 (org-clock-update-mode-line)))
3668 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3669 (end-of-line 1)
3670 (setq ts (match-string 1)
3671 te (match-string 3))
3672 (setq s (- (org-float-time
3673 (apply 'encode-time (org-parse-time-string te)))
3674 (org-float-time
3675 (apply 'encode-time (org-parse-time-string ts))))
3676 neg (< s 0)
3677 s (abs s)
3678 h (floor (/ s 3600))
3679 s (- s (* 3600 h))
3680 m (floor (/ s 60))
3681 s (- s (* 60 s)))
3682 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3683 t))))))
3685 (defun org-check-running-clock ()
3686 "Check if the current buffer contains the running clock.
3687 If yes, offer to stop it and to save the buffer with the changes."
3688 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3689 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3690 (buffer-name))))
3691 (org-clock-out)
3692 (when (y-or-n-p "Save changed buffer?")
3693 (save-buffer))))
3695 (defun org-clocktable-try-shift (dir n)
3696 "Check if this line starts a clock table, if yes, shift the time block."
3697 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3698 (org-clocktable-shift dir n)))
3700 ;; Autoload org-timer.el
3702 (eval-and-compile
3703 (org-autoload
3704 "org-timer"
3705 '(org-timer-start org-timer org-timer-item
3706 org-timer-change-times-in-region
3707 org-timer-set-timer
3708 org-timer-reset-timers
3709 org-timer-show-remaining-time)))
3711 ;; Autoload org-feed.el
3713 (eval-and-compile
3714 (org-autoload
3715 "org-feed"
3716 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3719 ;; Autoload org-indent.el
3721 ;; Define the variable already here, to make sure we have it.
3722 (defvar org-indent-mode nil
3723 "Non-nil if Org-Indent mode is enabled.
3724 Use the command `org-indent-mode' to change this variable.")
3726 (eval-and-compile
3727 (org-autoload
3728 "org-indent"
3729 '(org-indent-mode)))
3731 ;; Autoload org-mobile.el
3733 (eval-and-compile
3734 (org-autoload
3735 "org-mobile"
3736 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3738 ;; Autoload archiving code
3739 ;; The stuff that is needed for cycling and tags has to be defined here.
3741 (defgroup org-archive nil
3742 "Options concerning archiving in Org-mode."
3743 :tag "Org Archive"
3744 :group 'org-structure)
3746 (defcustom org-archive-location "%s_archive::"
3747 "The location where subtrees should be archived.
3749 The value of this variable is a string, consisting of two parts,
3750 separated by a double-colon. The first part is a filename and
3751 the second part is a headline.
3753 When the filename is omitted, archiving happens in the same file.
3754 %s in the filename will be replaced by the current file
3755 name (without the directory part). Archiving to a different file
3756 is useful to keep archived entries from contributing to the
3757 Org-mode Agenda.
3759 The archived entries will be filed as subtrees of the specified
3760 headline. When the headline is omitted, the subtrees are simply
3761 filed away at the end of the file, as top-level entries. Also in
3762 the heading you can use %s to represent the file name, this can be
3763 useful when using the same archive for a number of different files.
3765 Here are a few examples:
3766 \"%s_archive::\"
3767 If the current file is Projects.org, archive in file
3768 Projects.org_archive, as top-level trees. This is the default.
3770 \"::* Archived Tasks\"
3771 Archive in the current file, under the top-level headline
3772 \"* Archived Tasks\".
3774 \"~/org/archive.org::\"
3775 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3777 \"~/org/archive.org::From %s\"
3778 Archive in file ~/org/archive.org (absolute path), under headlines
3779 \"From FILENAME\" where file name is the current file name.
3781 \"basement::** Finished Tasks\"
3782 Archive in file ./basement (relative path), as level 3 trees
3783 below the level 2 heading \"** Finished Tasks\".
3785 You may set this option on a per-file basis by adding to the buffer a
3786 line like
3788 #+ARCHIVE: basement::** Finished Tasks
3790 You may also define it locally for a subtree by setting an ARCHIVE property
3791 in the entry. If such a property is found in an entry, or anywhere up
3792 the hierarchy, it will be used."
3793 :group 'org-archive
3794 :type 'string)
3796 (defcustom org-archive-tag "ARCHIVE"
3797 "The tag that marks a subtree as archived.
3798 An archived subtree does not open during visibility cycling, and does
3799 not contribute to the agenda listings.
3800 After changing this, font-lock must be restarted in the relevant buffers to
3801 get the proper fontification."
3802 :group 'org-archive
3803 :group 'org-keywords
3804 :type 'string)
3806 (defcustom org-agenda-skip-archived-trees t
3807 "Non-nil means the agenda will skip any items located in archived trees.
3808 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3809 variable is no longer recommended, you should leave it at the value t.
3810 Instead, use the key `v' to cycle the archives-mode in the agenda."
3811 :group 'org-archive
3812 :group 'org-agenda-skip
3813 :type 'boolean)
3815 (defcustom org-columns-skip-archived-trees t
3816 "Non-nil means ignore archived trees when creating column view."
3817 :group 'org-archive
3818 :group 'org-properties
3819 :type 'boolean)
3821 (defcustom org-cycle-open-archived-trees nil
3822 "Non-nil means `org-cycle' will open archived trees.
3823 An archived tree is a tree marked with the tag ARCHIVE.
3824 When nil, archived trees will stay folded. You can still open them with
3825 normal outline commands like `show-all', but not with the cycling commands."
3826 :group 'org-archive
3827 :group 'org-cycle
3828 :type 'boolean)
3830 (defcustom org-sparse-tree-open-archived-trees nil
3831 "Non-nil means sparse tree construction shows matches in archived trees.
3832 When nil, matches in these trees are highlighted, but the trees are kept in
3833 collapsed state."
3834 :group 'org-archive
3835 :group 'org-sparse-trees
3836 :type 'boolean)
3838 (defun org-cycle-hide-archived-subtrees (state)
3839 "Re-hide all archived subtrees after a visibility state change."
3840 (when (and (not org-cycle-open-archived-trees)
3841 (not (memq state '(overview folded))))
3842 (save-excursion
3843 (let* ((globalp (memq state '(contents all)))
3844 (beg (if globalp (point-min) (point)))
3845 (end (if globalp (point-max) (org-end-of-subtree t))))
3846 (org-hide-archived-subtrees beg end)
3847 (goto-char beg)
3848 (if (looking-at (concat ".*:" org-archive-tag ":"))
3849 (message "%s" (substitute-command-keys
3850 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3852 (defun org-force-cycle-archived ()
3853 "Cycle subtree even if it is archived."
3854 (interactive)
3855 (setq this-command 'org-cycle)
3856 (let ((org-cycle-open-archived-trees t))
3857 (call-interactively 'org-cycle)))
3859 (defun org-hide-archived-subtrees (beg end)
3860 "Re-hide all archived subtrees after a visibility state change."
3861 (save-excursion
3862 (let* ((re (concat ":" org-archive-tag ":")))
3863 (goto-char beg)
3864 (while (re-search-forward re end t)
3865 (when (org-on-heading-p)
3866 (org-flag-subtree t)
3867 (org-end-of-subtree t))))))
3869 (defun org-flag-subtree (flag)
3870 (save-excursion
3871 (org-back-to-heading t)
3872 (outline-end-of-heading)
3873 (outline-flag-region (point)
3874 (progn (org-end-of-subtree t) (point))
3875 flag)))
3877 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3879 (eval-and-compile
3880 (org-autoload "org-archive"
3881 '(org-add-archive-files org-archive-subtree
3882 org-archive-to-archive-sibling org-toggle-archive-tag
3883 org-archive-subtree-default
3884 org-archive-subtree-default-with-confirmation)))
3886 ;; Autoload Column View Code
3888 (declare-function org-columns-number-to-string "org-colview")
3889 (declare-function org-columns-get-format-and-top-level "org-colview")
3890 (declare-function org-columns-compute "org-colview")
3892 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3893 '(org-columns-number-to-string org-columns-get-format-and-top-level
3894 org-columns-compute org-agenda-columns org-columns-remove-overlays
3895 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3897 ;; Autoload ID code
3899 (declare-function org-id-store-link "org-id")
3900 (declare-function org-id-locations-load "org-id")
3901 (declare-function org-id-locations-save "org-id")
3902 (defvar org-id-track-globally)
3903 (org-autoload "org-id"
3904 '(org-id-get-create org-id-new org-id-copy org-id-get
3905 org-id-get-with-outline-path-completion
3906 org-id-get-with-outline-drilling
3907 org-id-goto org-id-find org-id-store-link))
3909 ;; Autoload Plotting Code
3911 (org-autoload "org-plot"
3912 '(org-plot/gnuplot))
3914 ;;; Variables for pre-computed regular expressions, all buffer local
3916 (defvar org-drawer-regexp nil
3917 "Matches first line of a hidden block.")
3918 (make-variable-buffer-local 'org-drawer-regexp)
3919 (defvar org-todo-regexp nil
3920 "Matches any of the TODO state keywords.")
3921 (make-variable-buffer-local 'org-todo-regexp)
3922 (defvar org-not-done-regexp nil
3923 "Matches any of the TODO state keywords except the last one.")
3924 (make-variable-buffer-local 'org-not-done-regexp)
3925 (defvar org-not-done-heading-regexp nil
3926 "Matches a TODO headline that is not done.")
3927 (make-variable-buffer-local 'org-not-done-regexp)
3928 (defvar org-todo-line-regexp nil
3929 "Matches a headline and puts TODO state into group 2 if present.")
3930 (make-variable-buffer-local 'org-todo-line-regexp)
3931 (defvar org-complex-heading-regexp nil
3932 "Matches a headline and puts everything into groups:
3933 group 1: the stars
3934 group 2: The todo keyword, maybe
3935 group 3: Priority cookie
3936 group 4: True headline
3937 group 5: Tags")
3938 (make-variable-buffer-local 'org-complex-heading-regexp)
3939 (defvar org-complex-heading-regexp-format nil)
3940 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3941 (defvar org-todo-line-tags-regexp nil
3942 "Matches a headline and puts TODO state into group 2 if present.
3943 Also put tags into group 4 if tags are present.")
3944 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3945 (defvar org-nl-done-regexp nil
3946 "Matches newline followed by a headline with the DONE keyword.")
3947 (make-variable-buffer-local 'org-nl-done-regexp)
3948 (defvar org-looking-at-done-regexp nil
3949 "Matches the DONE keyword a point.")
3950 (make-variable-buffer-local 'org-looking-at-done-regexp)
3951 (defvar org-ds-keyword-length 12
3952 "Maximum length of the Deadline and SCHEDULED keywords.")
3953 (make-variable-buffer-local 'org-ds-keyword-length)
3954 (defvar org-deadline-regexp nil
3955 "Matches the DEADLINE keyword.")
3956 (make-variable-buffer-local 'org-deadline-regexp)
3957 (defvar org-deadline-time-regexp nil
3958 "Matches the DEADLINE keyword together with a time stamp.")
3959 (make-variable-buffer-local 'org-deadline-time-regexp)
3960 (defvar org-deadline-line-regexp nil
3961 "Matches the DEADLINE keyword and the rest of the line.")
3962 (make-variable-buffer-local 'org-deadline-line-regexp)
3963 (defvar org-scheduled-regexp nil
3964 "Matches the SCHEDULED keyword.")
3965 (make-variable-buffer-local 'org-scheduled-regexp)
3966 (defvar org-scheduled-time-regexp nil
3967 "Matches the SCHEDULED keyword together with a time stamp.")
3968 (make-variable-buffer-local 'org-scheduled-time-regexp)
3969 (defvar org-closed-time-regexp nil
3970 "Matches the CLOSED keyword together with a time stamp.")
3971 (make-variable-buffer-local 'org-closed-time-regexp)
3973 (defvar org-keyword-time-regexp nil
3974 "Matches any of the 4 keywords, together with the time stamp.")
3975 (make-variable-buffer-local 'org-keyword-time-regexp)
3976 (defvar org-keyword-time-not-clock-regexp nil
3977 "Matches any of the 3 keywords, together with the time stamp.")
3978 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3979 (defvar org-maybe-keyword-time-regexp nil
3980 "Matches a timestamp, possibly preceeded by a keyword.")
3981 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3982 (defvar org-planning-or-clock-line-re nil
3983 "Matches a line with planning or clock info.")
3984 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3985 (defvar org-all-time-keywords nil
3986 "List of time keywords.")
3987 (make-variable-buffer-local 'org-all-time-keywords)
3989 (defconst org-plain-time-of-day-regexp
3990 (concat
3991 "\\(\\<[012]?[0-9]"
3992 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3993 "\\(--?"
3994 "\\(\\<[012]?[0-9]"
3995 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3996 "\\)?")
3997 "Regular expression to match a plain time or time range.
3998 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3999 groups carry important information:
4000 0 the full match
4001 1 the first time, range or not
4002 8 the second time, if it is a range.")
4004 (defconst org-plain-time-extension-regexp
4005 (concat
4006 "\\(\\<[012]?[0-9]"
4007 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4008 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4009 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4010 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4011 groups carry important information:
4012 0 the full match
4013 7 hours of duration
4014 9 minutes of duration")
4016 (defconst org-stamp-time-of-day-regexp
4017 (concat
4018 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4019 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4020 "\\(--?"
4021 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4022 "Regular expression to match a timestamp time or time range.
4023 After a match, the following groups carry important information:
4024 0 the full match
4025 1 date plus weekday, for back referencing to make sure both times are on the same day
4026 2 the first time, range or not
4027 4 the second time, if it is a range.")
4029 (defconst org-startup-options
4030 '(("fold" org-startup-folded t)
4031 ("overview" org-startup-folded t)
4032 ("nofold" org-startup-folded nil)
4033 ("showall" org-startup-folded nil)
4034 ("showeverything" org-startup-folded showeverything)
4035 ("content" org-startup-folded content)
4036 ("indent" org-startup-indented t)
4037 ("noindent" org-startup-indented nil)
4038 ("hidestars" org-hide-leading-stars t)
4039 ("showstars" org-hide-leading-stars nil)
4040 ("odd" org-odd-levels-only t)
4041 ("oddeven" org-odd-levels-only nil)
4042 ("align" org-startup-align-all-tables t)
4043 ("noalign" org-startup-align-all-tables nil)
4044 ("customtime" org-display-custom-times t)
4045 ("logdone" org-log-done time)
4046 ("lognotedone" org-log-done note)
4047 ("nologdone" org-log-done nil)
4048 ("lognoteclock-out" org-log-note-clock-out t)
4049 ("nolognoteclock-out" org-log-note-clock-out nil)
4050 ("logrepeat" org-log-repeat state)
4051 ("lognoterepeat" org-log-repeat note)
4052 ("nologrepeat" org-log-repeat nil)
4053 ("logreschedule" org-log-reschedule time)
4054 ("lognotereschedule" org-log-reschedule note)
4055 ("nologreschedule" org-log-reschedule nil)
4056 ("logredeadline" org-log-redeadline time)
4057 ("lognoteredeadline" org-log-redeadline note)
4058 ("nologredeadline" org-log-redeadline nil)
4059 ("logrefile" org-log-refile time)
4060 ("lognoterefile" org-log-refile note)
4061 ("nologrefile" org-log-refile nil)
4062 ("fninline" org-footnote-define-inline t)
4063 ("nofninline" org-footnote-define-inline nil)
4064 ("fnlocal" org-footnote-section nil)
4065 ("fnauto" org-footnote-auto-label t)
4066 ("fnprompt" org-footnote-auto-label nil)
4067 ("fnconfirm" org-footnote-auto-label confirm)
4068 ("fnplain" org-footnote-auto-label plain)
4069 ("fnadjust" org-footnote-auto-adjust t)
4070 ("nofnadjust" org-footnote-auto-adjust nil)
4071 ("constcgs" constants-unit-system cgs)
4072 ("constSI" constants-unit-system SI)
4073 ("noptag" org-tag-persistent-alist nil)
4074 ("hideblocks" org-hide-block-startup t)
4075 ("nohideblocks" org-hide-block-startup nil)
4076 ("beamer" org-startup-with-beamer-mode t)
4077 ("entitiespretty" org-pretty-entities t)
4078 ("entitiesplain" org-pretty-entities nil))
4079 "Variable associated with STARTUP options for org-mode.
4080 Each element is a list of three items: The startup options as written
4081 in the #+STARTUP line, the corresponding variable, and the value to
4082 set this variable to if the option is found. An optional forth element PUSH
4083 means to push this value onto the list in the variable.")
4085 (defun org-set-regexps-and-options ()
4086 "Precompute regular expressions for current buffer."
4087 (when (org-mode-p)
4088 (org-set-local 'org-todo-kwd-alist nil)
4089 (org-set-local 'org-todo-key-alist nil)
4090 (org-set-local 'org-todo-key-trigger nil)
4091 (org-set-local 'org-todo-keywords-1 nil)
4092 (org-set-local 'org-done-keywords nil)
4093 (org-set-local 'org-todo-heads nil)
4094 (org-set-local 'org-todo-sets nil)
4095 (org-set-local 'org-todo-log-states nil)
4096 (org-set-local 'org-file-properties nil)
4097 (org-set-local 'org-file-tags nil)
4098 (let ((re (org-make-options-regexp
4099 '("CATEGORY" "TODO" "COLUMNS"
4100 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4101 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4102 "OPTIONS")
4103 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4104 (splitre "[ \t]+")
4105 (scripts org-use-sub-superscripts)
4106 kwds kws0 kwsa key log value cat arch tags const links hw dws
4107 tail sep kws1 prio props ftags drawers beamer-p
4108 ext-setup-or-nil setup-contents (start 0))
4109 (save-excursion
4110 (save-restriction
4111 (widen)
4112 (goto-char (point-min))
4113 (while (or (and ext-setup-or-nil
4114 (string-match re ext-setup-or-nil start)
4115 (setq start (match-end 0)))
4116 (and (setq ext-setup-or-nil nil start 0)
4117 (re-search-forward re nil t)))
4118 (setq key (upcase (match-string 1 ext-setup-or-nil))
4119 value (org-match-string-no-properties 2 ext-setup-or-nil))
4120 (if (stringp value) (setq value (org-trim value)))
4121 (cond
4122 ((equal key "CATEGORY")
4123 (setq cat value))
4124 ((member key '("SEQ_TODO" "TODO"))
4125 (push (cons 'sequence (org-split-string value splitre)) kwds))
4126 ((equal key "TYP_TODO")
4127 (push (cons 'type (org-split-string value splitre)) kwds))
4128 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4129 ;; general TODO-like setup
4130 (push (cons (intern (downcase (match-string 1 key)))
4131 (org-split-string value splitre)) kwds))
4132 ((equal key "TAGS")
4133 (setq tags (append tags (if tags '("\\n") nil)
4134 (org-split-string value splitre))))
4135 ((equal key "COLUMNS")
4136 (org-set-local 'org-columns-default-format value))
4137 ((equal key "LINK")
4138 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4139 (push (cons (match-string 1 value)
4140 (org-trim (match-string 2 value)))
4141 links)))
4142 ((equal key "PRIORITIES")
4143 (setq prio (org-split-string value " +")))
4144 ((equal key "PROPERTY")
4145 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4146 (push (cons (match-string 1 value) (match-string 2 value))
4147 props)))
4148 ((equal key "FILETAGS")
4149 (when (string-match "\\S-" value)
4150 (setq ftags
4151 (append
4152 ftags
4153 (apply 'append
4154 (mapcar (lambda (x) (org-split-string x ":"))
4155 (org-split-string value)))))))
4156 ((equal key "DRAWERS")
4157 (setq drawers (org-split-string value splitre)))
4158 ((equal key "CONSTANTS")
4159 (setq const (append const (org-split-string value splitre))))
4160 ((equal key "STARTUP")
4161 (let ((opts (org-split-string value splitre))
4162 l var val)
4163 (while (setq l (pop opts))
4164 (when (setq l (assoc l org-startup-options))
4165 (setq var (nth 1 l) val (nth 2 l))
4166 (if (not (nth 3 l))
4167 (set (make-local-variable var) val)
4168 (if (not (listp (symbol-value var)))
4169 (set (make-local-variable var) nil))
4170 (set (make-local-variable var) (symbol-value var))
4171 (add-to-list var val))))))
4172 ((equal key "ARCHIVE")
4173 (setq arch value)
4174 (remove-text-properties 0 (length arch)
4175 '(face t fontified t) arch))
4176 ((equal key "LATEX_CLASS")
4177 (setq beamer-p (equal value "beamer")))
4178 ((equal key "OPTIONS")
4179 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4180 (setq scripts (read (match-string 2 value)))))
4181 ((equal key "SETUPFILE")
4182 (setq setup-contents (org-file-contents
4183 (expand-file-name
4184 (org-remove-double-quotes value))
4185 'noerror))
4186 (if (not ext-setup-or-nil)
4187 (setq ext-setup-or-nil setup-contents start 0)
4188 (setq ext-setup-or-nil
4189 (concat (substring ext-setup-or-nil 0 start)
4190 "\n" setup-contents "\n"
4191 (substring ext-setup-or-nil start)))))
4192 ))))
4193 (org-set-local 'org-use-sub-superscripts scripts)
4194 (when cat
4195 (org-set-local 'org-category (intern cat))
4196 (push (cons "CATEGORY" cat) props))
4197 (when prio
4198 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4199 (setq prio (mapcar 'string-to-char prio))
4200 (org-set-local 'org-highest-priority (nth 0 prio))
4201 (org-set-local 'org-lowest-priority (nth 1 prio))
4202 (org-set-local 'org-default-priority (nth 2 prio)))
4203 (and props (org-set-local 'org-file-properties (nreverse props)))
4204 (and ftags (org-set-local 'org-file-tags
4205 (mapcar 'org-add-prop-inherited ftags)))
4206 (and drawers (org-set-local 'org-drawers drawers))
4207 (and arch (org-set-local 'org-archive-location arch))
4208 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4209 ;; Process the TODO keywords
4210 (unless kwds
4211 ;; Use the global values as if they had been given locally.
4212 (setq kwds (default-value 'org-todo-keywords))
4213 (if (stringp (car kwds))
4214 (setq kwds (list (cons org-todo-interpretation
4215 (default-value 'org-todo-keywords)))))
4216 (setq kwds (reverse kwds)))
4217 (setq kwds (nreverse kwds))
4218 (let (inter kws kw)
4219 (while (setq kws (pop kwds))
4220 (let ((kws (or
4221 (run-hook-with-args-until-success
4222 'org-todo-setup-filter-hook kws)
4223 kws)))
4224 (setq inter (pop kws) sep (member "|" kws)
4225 kws0 (delete "|" (copy-sequence kws))
4226 kwsa nil
4227 kws1 (mapcar
4228 (lambda (x)
4229 ;; 1 2
4230 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4231 (progn
4232 (setq kw (match-string 1 x)
4233 key (and (match-end 2) (match-string 2 x))
4234 log (org-extract-log-state-settings x))
4235 (push (cons kw (and key (string-to-char key))) kwsa)
4236 (and log (push log org-todo-log-states))
4238 (error "Invalid TODO keyword %s" x)))
4239 kws0)
4240 kwsa (if kwsa (append '((:startgroup))
4241 (nreverse kwsa)
4242 '((:endgroup))))
4243 hw (car kws1)
4244 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4245 tail (list inter hw (car dws) (org-last dws))))
4246 (add-to-list 'org-todo-heads hw 'append)
4247 (push kws1 org-todo-sets)
4248 (setq org-done-keywords (append org-done-keywords dws nil))
4249 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4250 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4251 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4252 (setq org-todo-sets (nreverse org-todo-sets)
4253 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4254 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4255 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4256 ;; Process the constants
4257 (when const
4258 (let (e cst)
4259 (while (setq e (pop const))
4260 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4261 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4262 (setq org-table-formula-constants-local cst)))
4264 ;; Process the tags.
4265 (when tags
4266 (let (e tgs)
4267 (while (setq e (pop tags))
4268 (cond
4269 ((equal e "{") (push '(:startgroup) tgs))
4270 ((equal e "}") (push '(:endgroup) tgs))
4271 ((equal e "\\n") (push '(:newline) tgs))
4272 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4273 (push (cons (match-string 1 e)
4274 (string-to-char (match-string 2 e)))
4275 tgs))
4276 (t (push (list e) tgs))))
4277 (org-set-local 'org-tag-alist nil)
4278 (while (setq e (pop tgs))
4279 (or (and (stringp (car e))
4280 (assoc (car e) org-tag-alist))
4281 (push e org-tag-alist)))))
4283 ;; Compute the regular expressions and other local variables
4284 (if (not org-done-keywords)
4285 (setq org-done-keywords (and org-todo-keywords-1
4286 (list (org-last org-todo-keywords-1)))))
4287 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4288 (length org-scheduled-string)
4289 (length org-clock-string)
4290 (length org-closed-string)))
4291 org-drawer-regexp
4292 (concat "^[ \t]*:\\("
4293 (mapconcat 'regexp-quote org-drawers "\\|")
4294 "\\):[ \t]*$")
4295 org-not-done-keywords
4296 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4297 org-todo-regexp
4298 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4299 "\\|") "\\)\\>")
4300 org-not-done-regexp
4301 (concat "\\<\\("
4302 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4303 "\\)\\>")
4304 org-not-done-heading-regexp
4305 (concat "^\\(\\*+\\)[ \t]+\\("
4306 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4307 "\\)\\>")
4308 org-todo-line-regexp
4309 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4310 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4311 "\\)\\>\\)?[ \t]*\\(.*\\)")
4312 org-complex-heading-regexp
4313 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4314 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4315 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4316 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4317 org-complex-heading-regexp-format
4318 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4319 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4320 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4321 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4322 org-nl-done-regexp
4323 (concat "\n\\*+[ \t]+"
4324 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4325 "\\)" "\\>")
4326 org-todo-line-tags-regexp
4327 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4328 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4329 (org-re
4330 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4331 org-looking-at-done-regexp
4332 (concat "^" "\\(?:"
4333 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4334 "\\>")
4335 org-deadline-regexp (concat "\\<" org-deadline-string)
4336 org-deadline-time-regexp
4337 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4338 org-deadline-line-regexp
4339 (concat "\\<\\(" org-deadline-string "\\).*")
4340 org-scheduled-regexp
4341 (concat "\\<" org-scheduled-string)
4342 org-scheduled-time-regexp
4343 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4344 org-closed-time-regexp
4345 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4346 org-keyword-time-regexp
4347 (concat "\\<\\(" org-scheduled-string
4348 "\\|" org-deadline-string
4349 "\\|" org-closed-string
4350 "\\|" org-clock-string "\\)"
4351 " *[[<]\\([^]>]+\\)[]>]")
4352 org-keyword-time-not-clock-regexp
4353 (concat "\\<\\(" org-scheduled-string
4354 "\\|" org-deadline-string
4355 "\\|" org-closed-string
4356 "\\)"
4357 " *[[<]\\([^]>]+\\)[]>]")
4358 org-maybe-keyword-time-regexp
4359 (concat "\\(\\<\\(" org-scheduled-string
4360 "\\|" org-deadline-string
4361 "\\|" org-closed-string
4362 "\\|" org-clock-string "\\)\\)?"
4363 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4364 org-planning-or-clock-line-re
4365 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4366 "\\|" org-deadline-string
4367 "\\|" org-closed-string "\\|" org-clock-string
4368 "\\)\\>\\)")
4369 org-all-time-keywords
4370 (mapcar (lambda (w) (substring w 0 -1))
4371 (list org-scheduled-string org-deadline-string
4372 org-clock-string org-closed-string))
4374 (org-compute-latex-and-specials-regexp)
4375 (org-set-font-lock-defaults))))
4377 (defun org-file-contents (file &optional noerror)
4378 "Return the contents of FILE, as a string."
4379 (if (or (not file)
4380 (not (file-readable-p file)))
4381 (if noerror
4382 (progn
4383 (message "Cannot read file \"%s\"" file)
4384 (ding) (sit-for 2)
4386 (error "Cannot read file \"%s\"" file))
4387 (with-temp-buffer
4388 (insert-file-contents file)
4389 (buffer-string))))
4391 (defun org-extract-log-state-settings (x)
4392 "Extract the log state setting from a TODO keyword string.
4393 This will extract info from a string like \"WAIT(w@/!)\"."
4394 (let (kw key log1 log2)
4395 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4396 (setq kw (match-string 1 x)
4397 key (and (match-end 2) (match-string 2 x))
4398 log1 (and (match-end 3) (match-string 3 x))
4399 log2 (and (match-end 4) (match-string 4 x)))
4400 (and (or log1 log2)
4401 (list kw
4402 (and log1 (if (equal log1 "!") 'time 'note))
4403 (and log2 (if (equal log2 "!") 'time 'note)))))))
4405 (defun org-remove-keyword-keys (list)
4406 "Remove a pair of parenthesis at the end of each string in LIST."
4407 (mapcar (lambda (x)
4408 (if (string-match "(.*)$" x)
4409 (substring x 0 (match-beginning 0))
4411 list))
4413 (defun org-assign-fast-keys (alist)
4414 "Assign fast keys to a keyword-key alist.
4415 Respect keys that are already there."
4416 (let (new e (alt ?0))
4417 (while (setq e (pop alist))
4418 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4419 (cdr e)) ;; Key already assigned.
4420 (push e new)
4421 (let ((clist (string-to-list (downcase (car e))))
4422 (used (append new alist)))
4423 (when (= (car clist) ?@)
4424 (pop clist))
4425 (while (and clist (rassoc (car clist) used))
4426 (pop clist))
4427 (unless clist
4428 (while (rassoc alt used)
4429 (incf alt)))
4430 (push (cons (car e) (or (car clist) alt)) new))))
4431 (nreverse new)))
4433 ;;; Some variables used in various places
4435 (defvar org-window-configuration nil
4436 "Used in various places to store a window configuration.")
4437 (defvar org-selected-window nil
4438 "Used in various places to store a window configuration.")
4439 (defvar org-finish-function nil
4440 "Function to be called when `C-c C-c' is used.
4441 This is for getting out of special buffers like remember.")
4444 ;; FIXME: Occasionally check by commenting these, to make sure
4445 ;; no other functions uses these, forgetting to let-bind them.
4446 (defvar entry)
4447 (defvar last-state)
4448 (defvar date)
4450 ;; Defined somewhere in this file, but used before definition.
4451 (defvar org-entities) ;; defined in org-entities.el
4452 (defvar org-struct-menu)
4453 (defvar org-org-menu)
4454 (defvar org-tbl-menu)
4456 ;;;; Define the Org-mode
4458 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4459 (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."))
4462 ;; We use a before-change function to check if a table might need
4463 ;; an update.
4464 (defvar org-table-may-need-update t
4465 "Indicates that a table might need an update.
4466 This variable is set by `org-before-change-function'.
4467 `org-table-align' sets it back to nil.")
4468 (defun org-before-change-function (beg end)
4469 "Every change indicates that a table might need an update."
4470 (setq org-table-may-need-update t))
4471 (defvar org-mode-map)
4472 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4473 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4474 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4475 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4476 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4477 (defvar org-table-buffer-is-an nil)
4478 (defconst org-outline-regexp "\\*+ ")
4480 ;;;###autoload
4481 (define-derived-mode org-mode outline-mode "Org"
4482 "Outline-based notes management and organizer, alias
4483 \"Carsten's outline-mode for keeping track of everything.\"
4485 Org-mode develops organizational tasks around a NOTES file which
4486 contains information about projects as plain text. Org-mode is
4487 implemented on top of outline-mode, which is ideal to keep the content
4488 of large files well structured. It supports ToDo items, deadlines and
4489 time stamps, which magically appear in the diary listing of the Emacs
4490 calendar. Tables are easily created with a built-in table editor.
4491 Plain text URL-like links connect to websites, emails (VM), Usenet
4492 messages (Gnus), BBDB entries, and any files related to the project.
4493 For printing and sharing of notes, an Org-mode file (or a part of it)
4494 can be exported as a structured ASCII or HTML file.
4496 The following commands are available:
4498 \\{org-mode-map}"
4500 ;; Get rid of Outline menus, they are not needed
4501 ;; Need to do this here because define-derived-mode sets up
4502 ;; the keymap so late. Still, it is a waste to call this each time
4503 ;; we switch another buffer into org-mode.
4504 (if (featurep 'xemacs)
4505 (when (boundp 'outline-mode-menu-heading)
4506 ;; Assume this is Greg's port, it uses easymenu
4507 (easy-menu-remove outline-mode-menu-heading)
4508 (easy-menu-remove outline-mode-menu-show)
4509 (easy-menu-remove outline-mode-menu-hide))
4510 (define-key org-mode-map [menu-bar headings] 'undefined)
4511 (define-key org-mode-map [menu-bar hide] 'undefined)
4512 (define-key org-mode-map [menu-bar show] 'undefined))
4514 (org-load-modules-maybe)
4515 (easy-menu-add org-org-menu)
4516 (easy-menu-add org-tbl-menu)
4517 (org-install-agenda-files-menu)
4518 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4519 (add-to-invisibility-spec '(org-cwidth))
4520 (add-to-invisibility-spec '(org-hide-block . t))
4521 (when (featurep 'xemacs)
4522 (org-set-local 'line-move-ignore-invisible t))
4523 (org-set-local 'outline-regexp org-outline-regexp)
4524 (org-set-local 'outline-level 'org-outline-level)
4525 (when (and org-ellipsis
4526 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4527 (fboundp 'make-glyph-code))
4528 (unless org-display-table
4529 (setq org-display-table (make-display-table)))
4530 (set-display-table-slot
4531 org-display-table 4
4532 (vconcat (mapcar
4533 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4534 org-ellipsis)))
4535 (if (stringp org-ellipsis) org-ellipsis "..."))))
4536 (setq buffer-display-table org-display-table))
4537 (org-set-regexps-and-options)
4538 (when (and org-tag-faces (not org-tags-special-faces-re))
4539 ;; tag faces set outside customize.... force initialization.
4540 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4541 ;; Calc embedded
4542 (org-set-local 'calc-embedded-open-mode "# ")
4543 (modify-syntax-entry ?@ "w")
4544 (if org-startup-truncated (setq truncate-lines t))
4545 (org-set-local 'font-lock-unfontify-region-function
4546 'org-unfontify-region)
4547 ;; Activate before-change-function
4548 (org-set-local 'org-table-may-need-update t)
4549 (org-add-hook 'before-change-functions 'org-before-change-function nil
4550 'local)
4551 ;; Check for running clock before killing a buffer
4552 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4553 ;; Paragraphs and auto-filling
4554 (org-set-autofill-regexps)
4555 (setq indent-line-function 'org-indent-line-function)
4556 (org-update-radio-target-regexp)
4557 ;; Beginning/end of defun
4558 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4559 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4560 ;; Make sure dependence stuff works reliably, even for users who set it
4561 ;; too late :-(
4562 (if org-enforce-todo-dependencies
4563 (add-hook 'org-blocker-hook
4564 'org-block-todo-from-children-or-siblings-or-parent)
4565 (remove-hook 'org-blocker-hook
4566 'org-block-todo-from-children-or-siblings-or-parent))
4567 (if org-enforce-todo-checkbox-dependencies
4568 (add-hook 'org-blocker-hook
4569 'org-block-todo-from-checkboxes)
4570 (remove-hook 'org-blocker-hook
4571 'org-block-todo-from-checkboxes))
4573 ;; Comment characters
4574 ;; (org-set-local 'comment-start "#")
4575 (org-set-local 'comment-padding " ")
4576 (modify-syntax-entry ?# "<")
4577 ;; (modify-syntax-entry ?\n ">")
4579 ;; Align options lines
4580 (org-set-local
4581 'align-mode-rules-list
4582 '((org-in-buffer-settings
4583 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4584 (modes . '(org-mode)))))
4586 ;; Imenu
4587 (org-set-local 'imenu-create-index-function
4588 'org-imenu-get-tree)
4590 ;; Make isearch reveal context
4591 (if (or (featurep 'xemacs)
4592 (not (boundp 'outline-isearch-open-invisible-function)))
4593 ;; Emacs 21 and XEmacs make use of the hook
4594 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4595 ;; Emacs 22 deals with this through a special variable
4596 (org-set-local 'outline-isearch-open-invisible-function
4597 (lambda (&rest ignore) (org-show-context 'isearch))))
4599 ;; Turn on org-beamer-mode?
4600 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4602 ;; If empty file that did not turn on org-mode automatically, make it to.
4603 (if (and org-insert-mode-line-in-empty-file
4604 (interactive-p)
4605 (= (point-min) (point-max)))
4606 (insert "# -*- mode: org -*-\n\n"))
4607 (unless org-inhibit-startup
4608 (when org-startup-align-all-tables
4609 (let ((bmp (buffer-modified-p)))
4610 (org-table-map-tables 'org-table-align 'quietly)
4611 (set-buffer-modified-p bmp)))
4612 (when org-startup-indented
4613 (require 'org-indent)
4614 (org-indent-mode 1))
4615 (unless org-inhibit-startup-visibility-stuff
4616 (org-set-startup-visibility))))
4618 (when (fboundp 'abbrev-table-put)
4619 (abbrev-table-put org-mode-abbrev-table
4620 :parents (list text-mode-abbrev-table)))
4622 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4624 (defun org-current-time ()
4625 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4626 (if (> (car org-time-stamp-rounding-minutes) 1)
4627 (let ((r (car org-time-stamp-rounding-minutes))
4628 (time (decode-time)))
4629 (apply 'encode-time
4630 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4631 (nthcdr 2 time))))
4632 (current-time)))
4634 ;;;; Font-Lock stuff, including the activators
4636 (defvar org-mouse-map (make-sparse-keymap))
4637 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4638 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4639 (when org-mouse-1-follows-link
4640 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4641 (when org-tab-follows-link
4642 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4643 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4645 (require 'font-lock)
4647 (defconst org-non-link-chars "]\t\n\r<>")
4648 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4649 "shell" "elisp" "doi"))
4650 (defvar org-link-types-re nil
4651 "Matches a link that has a url-like prefix like \"http:\"")
4652 (defvar org-link-re-with-space nil
4653 "Matches a link with spaces, optional angular brackets around it.")
4654 (defvar org-link-re-with-space2 nil
4655 "Matches a link with spaces, optional angular brackets around it.")
4656 (defvar org-link-re-with-space3 nil
4657 "Matches a link with spaces, only for internal part in bracket links.")
4658 (defvar org-angle-link-re nil
4659 "Matches link with angular brackets, spaces are allowed.")
4660 (defvar org-plain-link-re nil
4661 "Matches plain link, without spaces.")
4662 (defvar org-bracket-link-regexp nil
4663 "Matches a link in double brackets.")
4664 (defvar org-bracket-link-analytic-regexp nil
4665 "Regular expression used to analyze links.
4666 Here is what the match groups contain after a match:
4667 1: http:
4668 2: http
4669 3: path
4670 4: [desc]
4671 5: desc")
4672 (defvar org-bracket-link-analytic-regexp++ nil
4673 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4674 (defvar org-any-link-re nil
4675 "Regular expression matching any link.")
4677 (defcustom org-match-sexp-depth 3
4678 "Number of stacked braces for sub/superscript matching.
4679 This has to be set before loading org.el to be effective."
4680 :group 'org-export-translation ; ??????????????????????????/
4681 :type 'integer)
4683 (defun org-create-multibrace-regexp (left right n)
4684 "Create a regular expression which will match a balanced sexp.
4685 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4686 as single character strings.
4687 The regexp returned will match the entire expression including the
4688 delimiters. It will also define a single group which contains the
4689 match except for the outermost delimiters. The maximum depth of
4690 stacked delimiters is N. Escaping delimiters is not possible."
4691 (let* ((nothing (concat "[^" left right "]*?"))
4692 (or "\\|")
4693 (re nothing)
4694 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4695 (while (> n 1)
4696 (setq n (1- n)
4697 re (concat re or next)
4698 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4699 (concat left "\\(" re "\\)" right)))
4701 (defvar org-match-substring-regexp
4702 (concat
4703 "\\([^\\]\\)\\([_^]\\)\\("
4704 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4705 "\\|"
4706 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4707 "\\|"
4708 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4709 "The regular expression matching a sub- or superscript.")
4711 (defvar org-match-substring-with-braces-regexp
4712 (concat
4713 "\\([^\\]\\)\\([_^]\\)\\("
4714 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4715 "\\)")
4716 "The regular expression matching a sub- or superscript, forcing braces.")
4718 (defun org-make-link-regexps ()
4719 "Update the link regular expressions.
4720 This should be called after the variable `org-link-types' has changed."
4721 (setq org-link-types-re
4722 (concat
4723 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4724 org-link-re-with-space
4725 (concat
4726 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4727 "\\([^" org-non-link-chars " ]"
4728 "[^" org-non-link-chars "]*"
4729 "[^" org-non-link-chars " ]\\)>?")
4730 org-link-re-with-space2
4731 (concat
4732 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4733 "\\([^" org-non-link-chars " ]"
4734 "[^\t\n\r]*"
4735 "[^" org-non-link-chars " ]\\)>?")
4736 org-link-re-with-space3
4737 (concat
4738 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4739 "\\([^" org-non-link-chars " ]"
4740 "[^\t\n\r]*\\)")
4741 org-angle-link-re
4742 (concat
4743 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4744 "\\([^" org-non-link-chars " ]"
4745 "[^" org-non-link-chars "]*"
4746 "\\)>")
4747 org-plain-link-re
4748 (concat
4749 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4750 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4751 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4752 org-bracket-link-regexp
4753 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4754 org-bracket-link-analytic-regexp
4755 (concat
4756 "\\[\\["
4757 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4758 "\\([^]]+\\)"
4759 "\\]"
4760 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4761 "\\]")
4762 org-bracket-link-analytic-regexp++
4763 (concat
4764 "\\[\\["
4765 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4766 "\\([^]]+\\)"
4767 "\\]"
4768 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4769 "\\]")
4770 org-any-link-re
4771 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4772 org-angle-link-re "\\)\\|\\("
4773 org-plain-link-re "\\)")))
4775 (org-make-link-regexps)
4777 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4778 "Regular expression for fast time stamp matching.")
4779 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4780 "Regular expression for fast time stamp matching.")
4781 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4782 "Regular expression matching time strings for analysis.
4783 This one does not require the space after the date, so it can be used
4784 on a string that terminates immediately after the date.")
4785 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4786 "Regular expression matching time strings for analysis.")
4787 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4788 "Regular expression matching time stamps, with groups.")
4789 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4790 "Regular expression matching time stamps (also [..]), with groups.")
4791 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4792 "Regular expression matching a time stamp range.")
4793 (defconst org-tr-regexp-both
4794 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4795 "Regular expression matching a time stamp range.")
4796 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4797 org-ts-regexp "\\)?")
4798 "Regular expression matching a time stamp or time stamp range.")
4799 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4800 org-ts-regexp-both "\\)?")
4801 "Regular expression matching a time stamp or time stamp range.
4802 The time stamps may be either active or inactive.")
4804 (defvar org-emph-face nil)
4806 (defun org-do-emphasis-faces (limit)
4807 "Run through the buffer and add overlays to links."
4808 (let (rtn a)
4809 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4810 (if (not (= (char-after (match-beginning 3))
4811 (char-after (match-beginning 4))))
4812 (progn
4813 (setq rtn t)
4814 (setq a (assoc (match-string 3) org-emphasis-alist))
4815 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4816 'face
4817 (nth 1 a))
4818 (and (nth 4 a)
4819 (org-remove-flyspell-overlays-in
4820 (match-beginning 0) (match-end 0)))
4821 (add-text-properties (match-beginning 2) (match-end 2)
4822 '(font-lock-multiline t org-emphasis t))
4823 (when org-hide-emphasis-markers
4824 (add-text-properties (match-end 4) (match-beginning 5)
4825 '(invisible org-link))
4826 (add-text-properties (match-beginning 3) (match-end 3)
4827 '(invisible org-link)))))
4828 (backward-char 1))
4829 rtn))
4831 (defun org-emphasize (&optional char)
4832 "Insert or change an emphasis, i.e. a font like bold or italic.
4833 If there is an active region, change that region to a new emphasis.
4834 If there is no region, just insert the marker characters and position
4835 the cursor between them.
4836 CHAR should be either the marker character, or the first character of the
4837 HTML tag associated with that emphasis. If CHAR is a space, the means
4838 to remove the emphasis of the selected region.
4839 If char is not given (for example in an interactive call) it
4840 will be prompted for."
4841 (interactive)
4842 (let ((eal org-emphasis-alist) e det
4843 (erc org-emphasis-regexp-components)
4844 (prompt "")
4845 (string "") beg end move tag c s)
4846 (if (org-region-active-p)
4847 (setq beg (region-beginning) end (region-end)
4848 string (buffer-substring beg end))
4849 (setq move t))
4851 (while (setq e (pop eal))
4852 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4853 c (aref tag 0))
4854 (push (cons c (string-to-char (car e))) det)
4855 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4856 (substring tag 1)))))
4857 (setq det (nreverse det))
4858 (unless char
4859 (message "%s" (concat "Emphasis marker or tag:" prompt))
4860 (setq char (read-char-exclusive)))
4861 (setq char (or (cdr (assoc char det)) char))
4862 (if (equal char ?\ )
4863 (setq s "" move nil)
4864 (unless (assoc (char-to-string char) org-emphasis-alist)
4865 (error "No such emphasis marker: \"%c\"" char))
4866 (setq s (char-to-string char)))
4867 (while (and (> (length string) 1)
4868 (equal (substring string 0 1) (substring string -1))
4869 (assoc (substring string 0 1) org-emphasis-alist))
4870 (setq string (substring string 1 -1)))
4871 (setq string (concat s string s))
4872 (if beg (delete-region beg end))
4873 (unless (or (bolp)
4874 (string-match (concat "[" (nth 0 erc) "\n]")
4875 (char-to-string (char-before (point)))))
4876 (insert " "))
4877 (unless (or (eobp)
4878 (string-match (concat "[" (nth 1 erc) "\n]")
4879 (char-to-string (char-after (point)))))
4880 (insert " ") (backward-char 1))
4881 (insert string)
4882 (and move (backward-char 1))))
4884 (defconst org-nonsticky-props
4885 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4887 (defsubst org-rear-nonsticky-at (pos)
4888 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4890 (defun org-activate-plain-links (limit)
4891 "Run through the buffer and add overlays to links."
4892 (catch 'exit
4893 (let (f)
4894 (if (re-search-forward org-plain-link-re limit t)
4895 (progn
4896 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4897 (setq f (get-text-property (match-beginning 0) 'face))
4898 (if (or (eq f 'org-tag)
4899 (and (listp f) (memq 'org-tag f)))
4901 (add-text-properties (match-beginning 0) (match-end 0)
4902 (list 'mouse-face 'highlight
4903 'face 'org-link
4904 'keymap org-mouse-map))
4905 (org-rear-nonsticky-at (match-end 0)))
4906 t)))))
4908 (defun org-activate-code (limit)
4909 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4910 (progn
4911 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4912 (remove-text-properties (match-beginning 0) (match-end 0)
4913 '(display t invisible t intangible t))
4914 t)))
4916 (defun org-fontify-meta-lines-and-blocks (limit)
4917 "Fontify #+ lines and blocks, in the correct ways."
4918 (let ((case-fold-search t))
4919 (if (re-search-forward
4920 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4921 limit t)
4922 (let ((beg (match-beginning 0))
4923 (beg1 (line-beginning-position 2))
4924 (dc1 (downcase (match-string 2)))
4925 (dc3 (downcase (match-string 3)))
4926 end end1 quoting block-type)
4927 (cond
4928 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4929 ;; a single line of backend-specific content
4930 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4931 (remove-text-properties (match-beginning 0) (match-end 0)
4932 '(display t invisible t intangible t))
4933 (add-text-properties (match-beginning 1) (match-end 3)
4934 '(font-lock-fontified t face org-meta-line))
4935 (add-text-properties (match-beginning 6) (match-end 6)
4936 '(font-lock-fontified t face org-block))
4938 ((and (match-end 4) (equal dc3 "begin"))
4939 ;; Truly a block
4940 (setq block-type (downcase (match-string 5))
4941 quoting (member block-type org-protecting-blocks))
4942 (when (re-search-forward
4943 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4944 nil t) ;; on purpose, we look further than LIMIT
4945 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4946 (when quoting
4947 (remove-text-properties beg end
4948 '(display t invisible t intangible t)))
4949 (add-text-properties
4950 beg end
4951 '(font-lock-fontified t font-lock-multiline t))
4952 (add-text-properties beg beg1 '(face org-meta-line))
4953 (add-text-properties end1 end '(face org-meta-line))
4954 (cond
4955 (quoting
4956 (add-text-properties beg1 end1 '(face org-block)))
4957 ((not org-fontify-quote-and-verse-blocks))
4958 ((string= block-type "quote")
4959 (add-text-properties beg1 end1 '(face org-quote)))
4960 ((string= block-type "verse")
4961 (add-text-properties beg1 end1 '(face org-verse))))
4963 ((member dc1 '("title:" "author:" "email:" "date:"))
4964 (add-text-properties
4965 beg (match-end 3)
4966 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4967 '(font-lock-fontified t invisible t)
4968 '(font-lock-fontified t face org-document-info-keyword)))
4969 (add-text-properties
4970 (match-beginning 6) (match-end 6)
4971 (if (string-equal dc1 "title:")
4972 '(font-lock-fontified t face org-document-title)
4973 '(font-lock-fontified t face org-document-info))))
4974 ((not (member (char-after beg) '(?\ ?\t)))
4975 ;; just any other in-buffer setting, but not indented
4976 (add-text-properties
4977 beg (match-end 0)
4978 '(font-lock-fontified t face org-meta-line))
4980 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4981 "orgtbl:" "tblfm:" "tblname:" "result:"
4982 "results:" "source:" "srcname:" "call:"))
4983 (and (match-end 4) (equal dc3 "attr")))
4984 (add-text-properties
4985 beg (match-end 0)
4986 '(font-lock-fontified t face org-meta-line))
4988 ((member dc3 '(" " ""))
4989 (add-text-properties
4990 beg (match-end 0)
4991 '(font-lock-fontified t face font-lock-comment-face)))
4992 (t nil))))))
4994 (defun org-activate-angle-links (limit)
4995 "Run through the buffer and add overlays to links."
4996 (if (re-search-forward org-angle-link-re limit t)
4997 (progn
4998 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4999 (add-text-properties (match-beginning 0) (match-end 0)
5000 (list 'mouse-face 'highlight
5001 'keymap org-mouse-map))
5002 (org-rear-nonsticky-at (match-end 0))
5003 t)))
5005 (defun org-activate-footnote-links (limit)
5006 "Run through the buffer and add overlays to links."
5007 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5008 limit t)
5009 (progn
5010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5011 (add-text-properties (match-beginning 2) (match-end 2)
5012 (list 'mouse-face 'highlight
5013 'keymap org-mouse-map
5014 'help-echo
5015 (if (= (point-at-bol) (match-beginning 2))
5016 "Footnote definition"
5017 "Footnote reference")
5019 (org-rear-nonsticky-at (match-end 2))
5020 t)))
5022 (defun org-activate-bracket-links (limit)
5023 "Run through the buffer and add overlays to bracketed links."
5024 (if (re-search-forward org-bracket-link-regexp limit t)
5025 (let* ((help (concat "LINK: "
5026 (org-match-string-no-properties 1)))
5027 ;; FIXME: above we should remove the escapes.
5028 ;; but that requires another match, protecting match data,
5029 ;; a lot of overhead for font-lock.
5030 (ip (org-maybe-intangible
5031 (list 'invisible 'org-link
5032 'keymap org-mouse-map 'mouse-face 'highlight
5033 'font-lock-multiline t 'help-echo help)))
5034 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5035 'font-lock-multiline t 'help-echo help)))
5036 ;; We need to remove the invisible property here. Table narrowing
5037 ;; may have made some of this invisible.
5038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5039 (remove-text-properties (match-beginning 0) (match-end 0)
5040 '(invisible nil))
5041 (if (match-end 3)
5042 (progn
5043 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5044 (org-rear-nonsticky-at (match-beginning 3))
5045 (add-text-properties (match-beginning 3) (match-end 3) vp)
5046 (org-rear-nonsticky-at (match-end 3))
5047 (add-text-properties (match-end 3) (match-end 0) ip)
5048 (org-rear-nonsticky-at (match-end 0)))
5049 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5050 (org-rear-nonsticky-at (match-beginning 1))
5051 (add-text-properties (match-beginning 1) (match-end 1) vp)
5052 (org-rear-nonsticky-at (match-end 1))
5053 (add-text-properties (match-end 1) (match-end 0) ip)
5054 (org-rear-nonsticky-at (match-end 0)))
5055 t)))
5057 (defun org-activate-dates (limit)
5058 "Run through the buffer and add overlays to dates."
5059 (if (re-search-forward org-tsr-regexp-both limit t)
5060 (progn
5061 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5062 (add-text-properties (match-beginning 0) (match-end 0)
5063 (list 'mouse-face 'highlight
5064 'keymap org-mouse-map))
5065 (org-rear-nonsticky-at (match-end 0))
5066 (when org-display-custom-times
5067 (if (match-end 3)
5068 (org-display-custom-time (match-beginning 3) (match-end 3)))
5069 (org-display-custom-time (match-beginning 1) (match-end 1)))
5070 t)))
5072 (defvar org-target-link-regexp nil
5073 "Regular expression matching radio targets in plain text.")
5074 (make-variable-buffer-local 'org-target-link-regexp)
5075 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5076 "Regular expression matching a link target.")
5077 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5078 "Regular expression matching a radio target.")
5079 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5080 "Regular expression matching any target.")
5082 (defun org-activate-target-links (limit)
5083 "Run through the buffer and add overlays to target matches."
5084 (when org-target-link-regexp
5085 (let ((case-fold-search t))
5086 (if (re-search-forward org-target-link-regexp limit t)
5087 (progn
5088 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5089 (add-text-properties (match-beginning 0) (match-end 0)
5090 (list 'mouse-face 'highlight
5091 'keymap org-mouse-map
5092 'help-echo "Radio target link"
5093 'org-linked-text t))
5094 (org-rear-nonsticky-at (match-end 0))
5095 t)))))
5097 (defun org-update-radio-target-regexp ()
5098 "Find all radio targets in this file and update the regular expression."
5099 (interactive)
5100 (when (memq 'radio org-activate-links)
5101 (setq org-target-link-regexp
5102 (org-make-target-link-regexp (org-all-targets 'radio)))
5103 (org-restart-font-lock)))
5105 (defun org-hide-wide-columns (limit)
5106 (let (s e)
5107 (setq s (text-property-any (point) (or limit (point-max))
5108 'org-cwidth t))
5109 (when s
5110 (setq e (next-single-property-change s 'org-cwidth))
5111 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5112 (goto-char e)
5113 t)))
5115 (defvar org-latex-and-specials-regexp nil
5116 "Regular expression for highlighting export special stuff.")
5117 (defvar org-match-substring-regexp)
5118 (defvar org-match-substring-with-braces-regexp)
5120 ;; This should be with the exporter code, but we also use if for font-locking
5121 (defconst org-export-html-special-string-regexps
5122 '(("\\\\-" . "&shy;")
5123 ("---\\([^-]\\)" . "&mdash;\\1")
5124 ("--\\([^-]\\)" . "&ndash;\\1")
5125 ("\\.\\.\\." . "&hellip;"))
5126 "Regular expressions for special string conversion.")
5129 (defun org-compute-latex-and-specials-regexp ()
5130 "Compute regular expression for stuff treated specially by exporters."
5131 (if (not org-highlight-latex-fragments-and-specials)
5132 (org-set-local 'org-latex-and-specials-regexp nil)
5133 (require 'org-exp)
5134 (let*
5135 ((matchers (plist-get org-format-latex-options :matchers))
5136 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5137 org-latex-regexps)))
5138 (org-export-allow-BIND nil)
5139 (options (org-combine-plists (org-default-export-plist)
5140 (org-infile-export-plist)))
5141 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5142 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5143 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5144 (org-export-html-expand (plist-get options :expand-quoted-html))
5145 (org-export-with-special-strings (plist-get options :special-strings))
5146 (re-sub
5147 (cond
5148 ((equal org-export-with-sub-superscripts '{})
5149 (list org-match-substring-with-braces-regexp))
5150 (org-export-with-sub-superscripts
5151 (list org-match-substring-regexp))
5152 (t nil)))
5153 (re-latex
5154 (if org-export-with-LaTeX-fragments
5155 (mapcar (lambda (x) (nth 1 x)) latexs)))
5156 (re-macros
5157 (if org-export-with-TeX-macros
5158 (list (concat "\\\\"
5159 (regexp-opt
5160 (append (mapcar 'car (append org-entities-user
5161 org-entities))
5162 (if (boundp 'org-latex-entities)
5163 (mapcar (lambda (x)
5164 (or (car-safe x) x))
5165 org-latex-entities)
5166 nil))
5167 'words))) ; FIXME
5169 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5170 (re-special (if org-export-with-special-strings
5171 (mapcar (lambda (x) (car x))
5172 org-export-html-special-string-regexps)))
5173 (re-rest
5174 (delq nil
5175 (list
5176 (if org-export-html-expand "@<[^>\n]+>")
5177 ))))
5178 (org-set-local
5179 'org-latex-and-specials-regexp
5180 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5181 re-rest) "\\|")))))
5183 (defun org-do-latex-and-special-faces (limit)
5184 "Run through the buffer and add overlays to links."
5185 (when org-latex-and-specials-regexp
5186 (let (rtn d)
5187 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5188 limit t))
5189 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5190 'face))
5191 '(org-code org-verbatim underline)))
5192 (progn
5193 (setq rtn t
5194 d (cond ((member (char-after (1+ (match-beginning 0)))
5195 '(?_ ?^)) 1)
5196 (t 0)))
5197 (font-lock-prepend-text-property
5198 (+ d (match-beginning 0)) (match-end 0)
5199 'face 'org-latex-and-export-specials)
5200 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5201 '(font-lock-multiline t)))))
5202 rtn)))
5204 (defun org-restart-font-lock ()
5205 "Restart font-lock-mode, to force refontification."
5206 (when (and (boundp 'font-lock-mode) font-lock-mode)
5207 (font-lock-mode -1)
5208 (font-lock-mode 1)))
5210 (defun org-all-targets (&optional radio)
5211 "Return a list of all targets in this file.
5212 With optional argument RADIO, only find radio targets."
5213 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5214 rtn)
5215 (save-excursion
5216 (goto-char (point-min))
5217 (while (re-search-forward re nil t)
5218 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5219 rtn)))
5221 (defun org-make-target-link-regexp (targets)
5222 "Make regular expression matching all strings in TARGETS.
5223 The regular expression finds the targets also if there is a line break
5224 between words."
5225 (and targets
5226 (concat
5227 "\\<\\("
5228 (mapconcat
5229 (lambda (x)
5230 (while (string-match " +" x)
5231 (setq x (replace-match "\\s-+" t t x)))
5233 targets
5234 "\\|")
5235 "\\)\\>")))
5237 (defun org-activate-tags (limit)
5238 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5239 (progn
5240 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5241 (add-text-properties (match-beginning 1) (match-end 1)
5242 (list 'mouse-face 'highlight
5243 'keymap org-mouse-map))
5244 (org-rear-nonsticky-at (match-end 1))
5245 t)))
5247 (defun org-outline-level ()
5248 "Compute the outline level of the heading at point.
5249 This function assumes that the cursor is at the beginning of a line matched
5250 by outline-regexp. Otherwise it returns garbage.
5251 If this is called at a normal headline, the level is the number of stars.
5252 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5253 For plain list items, if they are matched by `outline-regexp', this returns
5254 1000 plus the line indentation."
5255 (save-excursion
5256 (looking-at outline-regexp)
5257 (if (match-beginning 1)
5258 (+ (org-get-string-indentation (match-string 1)) 1000)
5259 (1- (- (match-end 0) (match-beginning 0))))))
5261 (defvar org-font-lock-keywords nil)
5263 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5264 "Regular expression matching a property line.")
5266 (defvar org-font-lock-hook nil
5267 "Functions to be called for special font lock stuff.")
5269 (defun org-font-lock-hook (limit)
5270 (run-hook-with-args 'org-font-lock-hook limit))
5272 (defun org-set-font-lock-defaults ()
5273 (let* ((em org-fontify-emphasized-text)
5274 (lk org-activate-links)
5275 (org-font-lock-extra-keywords
5276 (list
5277 ;; Call the hook
5278 '(org-font-lock-hook)
5279 ;; Headlines
5280 `(,(if org-fontify-whole-heading-line
5281 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5282 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5283 (1 (org-get-level-face 1))
5284 (2 (org-get-level-face 2))
5285 (3 (org-get-level-face 3)))
5286 ;; Table lines
5287 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5288 (1 'org-table t))
5289 ;; Table internals
5290 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5291 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5292 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5293 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5294 ;; Drawers
5295 (list org-drawer-regexp '(0 'org-special-keyword t))
5296 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5297 ;; Properties
5298 (list org-property-re
5299 '(1 'org-special-keyword t)
5300 '(3 'org-property-value t))
5301 ;; Links
5302 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5303 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5304 (if (memq 'plain lk) '(org-activate-plain-links))
5305 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5306 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5307 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5308 (if (memq 'footnote lk) '(org-activate-footnote-links
5309 (2 'org-footnote t)))
5310 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5311 '(org-hide-wide-columns (0 nil append))
5312 ;; TODO lines
5313 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5314 '(1 (org-get-todo-face 1) t))
5315 ;; DONE
5316 (if org-fontify-done-headline
5317 (list (concat "^[*]+ +\\<\\("
5318 (mapconcat 'regexp-quote org-done-keywords "\\|")
5319 "\\)\\(.*\\)")
5320 '(2 'org-headline-done t))
5321 nil)
5322 ;; Priorities
5323 '(org-font-lock-add-priority-faces)
5324 ;; Tags
5325 '(org-font-lock-add-tag-faces)
5326 ;; Special keywords
5327 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5328 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5329 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5330 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5331 ;; Emphasis
5332 (if em
5333 (if (featurep 'xemacs)
5334 '(org-do-emphasis-faces (0 nil append))
5335 '(org-do-emphasis-faces)))
5336 ;; Checkboxes
5337 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5338 2 'org-checkbox prepend)
5339 (if org-provide-checkbox-statistics
5340 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5341 (0 (org-get-checkbox-statistics-face) t)))
5342 ;; Description list items
5343 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5344 2 'bold prepend)
5345 ;; ARCHIVEd headings
5346 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5347 '(1 'org-archived prepend))
5348 ;; Specials
5349 '(org-do-latex-and-special-faces)
5350 '(org-fontify-entities)
5351 '(org-raise-scripts)
5352 ;; Code
5353 '(org-activate-code (1 'org-code t))
5354 ;; COMMENT
5355 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5356 "\\|" org-quote-string "\\)\\>")
5357 '(1 'org-special-keyword t))
5358 '("^#.*" (0 'font-lock-comment-face t))
5359 ;; Blocks and meta lines
5360 '(org-fontify-meta-lines-and-blocks)
5362 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5363 ;; Now set the full font-lock-keywords
5364 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5365 (org-set-local 'font-lock-defaults
5366 '(org-font-lock-keywords t nil nil backward-paragraph))
5367 (kill-local-variable 'font-lock-keywords) nil))
5369 (defun org-toggle-pretty-entities ()
5370 "Toggle the compostion display of entities as UTF8 characters."
5371 (interactive)
5372 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5373 (org-restart-font-lock)
5374 (if org-pretty-entities
5375 (message "Entities are displayed as UTF8 characers")
5376 (save-restriction
5377 (widen)
5378 (decompose-region (point-min) (point-max))
5379 (message "Entities are displayed plain"))))
5381 (defun org-fontify-entities (limit)
5382 "Find an entity to fontify."
5383 (let (ee)
5384 (when org-pretty-entities
5385 (catch 'match
5386 (while (re-search-forward
5387 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5388 limit t)
5389 (if (and (not (org-in-indented-comment-line))
5390 (setq ee (org-entity-get (match-string 1)))
5391 (= (length (nth 6 ee)) 1))
5392 (progn
5393 (add-text-properties
5394 (match-beginning 0) (match-end 1)
5395 (list 'font-lock-fontified t))
5396 (compose-region (match-beginning 0) (match-end 1)
5397 (nth 6 ee) nil)
5398 (backward-char 1)
5399 (throw 'match t))))
5400 nil))))
5402 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5403 "Fontify string S like in Org-mode"
5404 (with-temp-buffer
5405 (insert s)
5406 (let ((org-odd-levels-only odd-levels))
5407 (org-mode)
5408 (font-lock-fontify-buffer)
5409 (buffer-string))))
5411 (defvar org-m nil)
5412 (defvar org-l nil)
5413 (defvar org-f nil)
5414 (defun org-get-level-face (n)
5415 "Get the right face for match N in font-lock matching of headlines."
5416 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5417 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5418 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5419 (cond
5420 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5421 ((eq n 2) org-f)
5422 (t (if org-level-color-stars-only nil org-f))))
5424 (defun org-get-todo-face (kwd)
5425 "Get the right face for a TODO keyword KWD.
5426 If KWD is a number, get the corresponding match group."
5427 (if (numberp kwd) (setq kwd (match-string kwd)))
5428 (or (org-face-from-face-or-color
5429 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5430 (and (member kwd org-done-keywords) 'org-done)
5431 'org-todo))
5433 (defun org-face-from-face-or-color (context inherit face-or-color)
5434 "Create a face list that inherits INHERIT, but sets the foreground color.
5435 When FACE-OR-COLOR is not a string, just return it."
5436 (if (stringp face-or-color)
5437 (list :inherit inherit
5438 (cdr (assoc context org-faces-easy-properties))
5439 face-or-color)
5440 face-or-color))
5442 (defun org-font-lock-add-tag-faces (limit)
5443 "Add the special tag faces."
5444 (when (and org-tag-faces org-tags-special-faces-re)
5445 (while (re-search-forward org-tags-special-faces-re limit t)
5446 (add-text-properties (match-beginning 1) (match-end 1)
5447 (list 'face (org-get-tag-face 1)
5448 'font-lock-fontified t))
5449 (backward-char 1))))
5451 (defun org-font-lock-add-priority-faces (limit)
5452 "Add the special priority faces."
5453 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5454 (add-text-properties
5455 (match-beginning 0) (match-end 0)
5456 (list 'face (or (org-face-from-face-or-color
5457 'priority 'org-special-keyword
5458 (cdr (assoc (char-after (match-beginning 1))
5459 org-priority-faces)))
5460 'org-special-keyword)
5461 'font-lock-fontified t))))
5463 (defun org-get-tag-face (kwd)
5464 "Get the right face for a TODO keyword KWD.
5465 If KWD is a number, get the corresponding match group."
5466 (if (numberp kwd) (setq kwd (match-string kwd)))
5467 (or (org-face-from-face-or-color
5468 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5469 'org-tag))
5471 (defun org-unfontify-region (beg end &optional maybe_loudly)
5472 "Remove fontification and activation overlays from links."
5473 (font-lock-default-unfontify-region beg end)
5474 (let* ((buffer-undo-list t)
5475 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5476 (inhibit-modification-hooks t)
5477 deactivate-mark buffer-file-name buffer-file-truename)
5478 (decompose-region beg end)
5479 (remove-text-properties
5480 beg end
5481 (if org-indent-mode
5482 ;; also remove line-prefix and wrap-prefix properties
5483 '(mouse-face t keymap t org-linked-text t
5484 invisible t intangible t
5485 line-prefix t wrap-prefix t
5486 org-no-flyspell t org-emphasis t)
5487 '(mouse-face t keymap t org-linked-text t
5488 invisible t intangible t
5489 org-no-flyspell t org-emphasis t)))
5490 (org-remove-font-lock-display-properties beg end)))
5492 (defconst org-script-display '(((raise -0.3) (height 0.7))
5493 ((raise 0.3) (height 0.7))
5494 ((raise -0.5))
5495 ((raise 0.5)))
5496 "Display properties for showing superscripts and subscripts.")
5498 (defun org-remove-font-lock-display-properties (beg end)
5499 "Remove specific display properties that have been added by font lock.
5500 The will remove the raise properties that are used to show superscripts
5501 and subscriipts."
5502 (let (next prop)
5503 (while (< beg end)
5504 (setq next (next-single-property-change beg 'display nil end)
5505 prop (get-text-property beg 'display))
5506 (if (member prop org-script-display)
5507 (put-text-property beg next 'display nil))
5508 (setq beg next))))
5510 (defun org-raise-scripts (limit)
5511 "Add raise properties to sub/superscripts."
5512 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5513 (if (re-search-forward
5514 (if (eq org-use-sub-superscripts t)
5515 org-match-substring-regexp
5516 org-match-substring-with-braces-regexp)
5517 limit t)
5518 (let* ((pos (point)) table-p comment-p
5519 (mpos (match-beginning 3))
5520 (emph-p (get-text-property mpos 'org-emphasis))
5521 (link-p (get-text-property mpos 'mouse-face))
5522 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5523 (goto-char (point-at-bol))
5524 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5525 comment-p (org-looking-at-p "[ \t]*#"))
5526 (goto-char pos)
5527 (if (or comment-p emph-p link-p keyw-p)
5529 (put-text-property (match-beginning 3) (match-end 0)
5530 'display
5531 (if (equal (char-after (match-beginning 2)) ?^)
5532 (nth (if table-p 3 1) org-script-display)
5533 (nth (if table-p 2 0) org-script-display)))
5534 (add-text-properties (match-beginning 2) (match-end 2)
5535 (list 'invisible t
5536 'org-dwidth t 'org-dwidth-n 1))
5537 (if (and (eq (char-after (match-beginning 3)) ?{)
5538 (eq (char-before (match-end 3)) ?}))
5539 (progn
5540 (add-text-properties
5541 (match-beginning 3) (1+ (match-beginning 3))
5542 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5543 (add-text-properties
5544 (1- (match-end 3)) (match-end 3)
5545 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5546 t)))))
5548 ;;;; Visibility cycling, including org-goto and indirect buffer
5550 ;;; Cycling
5552 (defvar org-cycle-global-status nil)
5553 (make-variable-buffer-local 'org-cycle-global-status)
5554 (defvar org-cycle-subtree-status nil)
5555 (make-variable-buffer-local 'org-cycle-subtree-status)
5557 ;;;###autoload
5559 (defvar org-inlinetask-min-level)
5561 (defun org-cycle (&optional arg)
5562 "TAB-action and visibility cycling for Org-mode.
5564 This is the command invoked in Org-mode by the TAB key. Its main purpose
5565 is outline visibility cycling, but it also invokes other actions
5566 in special contexts.
5568 - When this function is called with a prefix argument, rotate the entire
5569 buffer through 3 states (global cycling)
5570 1. OVERVIEW: Show only top-level headlines.
5571 2. CONTENTS: Show all headlines of all levels, but no body text.
5572 3. SHOW ALL: Show everything.
5573 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5574 determined by the variable `org-startup-folded', and by any VISIBILITY
5575 properties in the buffer.
5576 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5577 including any drawers.
5579 - When inside a table, re-align the table and move to the next field.
5581 - When point is at the beginning of a headline, rotate the subtree started
5582 by this line through 3 different states (local cycling)
5583 1. FOLDED: Only the main headline is shown.
5584 2. CHILDREN: The main headline and the direct children are shown.
5585 From this state, you can move to one of the children
5586 and zoom in further.
5587 3. SUBTREE: Show the entire subtree, including body text.
5588 If there is no subtree, switch directly from CHILDREN to FOLDED.
5590 - When point is at the beginning of an empty headline and the variable
5591 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5592 of the headline by demoting and promoting it to likely levels. This
5593 speeds up creation document structure by presing TAB once or several
5594 times right after creating a new headline.
5596 - When there is a numeric prefix, go up to a heading with level ARG, do
5597 a `show-subtree' and return to the previous cursor position. If ARG
5598 is negative, go up that many levels.
5600 - When point is not at the beginning of a headline, execute the global
5601 binding for TAB, which is re-indenting the line. See the option
5602 `org-cycle-emulate-tab' for details.
5604 - Special case: if point is at the beginning of the buffer and there is
5605 no headline in line 1, this function will act as if called with prefix arg.
5606 But only if also the variable `org-cycle-global-at-bob' is t."
5607 (interactive "P")
5608 (org-load-modules-maybe)
5609 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5610 (and org-cycle-level-after-item/entry-creation
5611 (or (org-cycle-level)
5612 (org-cycle-item-indentation))))
5613 (let* ((limit-level
5614 (or org-cycle-max-level
5615 (and (boundp 'org-inlinetask-min-level)
5616 org-inlinetask-min-level
5617 (1- org-inlinetask-min-level))))
5618 (nstars (and limit-level
5619 (if org-odd-levels-only
5620 (and limit-level (1- (* limit-level 2)))
5621 limit-level)))
5622 (outline-regexp
5623 (cond
5624 ((not (org-mode-p)) outline-regexp)
5625 ((or (eq org-cycle-include-plain-lists 'integrate)
5626 (and org-cycle-include-plain-lists (org-at-item-p)))
5627 (concat "\\(?:\\*"
5628 (if nstars (format "\\{1,%d\\}" nstars) "+")
5629 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5630 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5631 (bob-special (and org-cycle-global-at-bob (bobp)
5632 (not (looking-at outline-regexp))))
5633 (org-cycle-hook
5634 (if bob-special
5635 (delq 'org-optimize-window-after-visibility-change
5636 (copy-sequence org-cycle-hook))
5637 org-cycle-hook))
5638 (pos (point)))
5640 (if (or bob-special (equal arg '(4)))
5641 ;; special case: use global cycling
5642 (setq arg t))
5644 (cond
5646 ((equal arg '(16))
5647 (org-set-startup-visibility)
5648 (message "Startup visibility, plus VISIBILITY properties"))
5650 ((equal arg '(64))
5651 (show-all)
5652 (message "Entire buffer visible, including drawers"))
5654 ((org-at-table-p 'any)
5655 ;; Enter the table or move to the next field in the table
5656 (if (org-at-table.el-p)
5657 (message "Use C-c ' to edit table.el tables")
5658 (if arg (org-table-edit-field t)
5659 (org-table-justify-field-maybe)
5660 (call-interactively 'org-table-next-field))))
5662 ((run-hook-with-args-until-success
5663 'org-tab-after-check-for-table-hook))
5665 ((eq arg t) ;; Global cycling
5666 (org-cycle-internal-global))
5668 ((and org-drawers org-drawer-regexp
5669 (save-excursion
5670 (beginning-of-line 1)
5671 (looking-at org-drawer-regexp)))
5672 ;; Toggle block visibility
5673 (org-flag-drawer
5674 (not (get-char-property (match-end 0) 'invisible))))
5676 ((integerp arg)
5677 ;; Show-subtree, ARG levels up from here.
5678 (save-excursion
5679 (org-back-to-heading)
5680 (outline-up-heading (if (< arg 0) (- arg)
5681 (- (funcall outline-level) arg)))
5682 (org-show-subtree)))
5684 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5685 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5687 (org-cycle-internal-local))
5689 ;; TAB emulation and template completion
5690 (buffer-read-only (org-back-to-heading))
5692 ((run-hook-with-args-until-success
5693 'org-tab-after-check-for-cycling-hook))
5695 ((org-try-structure-completion))
5697 ((org-try-cdlatex-tab))
5699 ((run-hook-with-args-until-success
5700 'org-tab-before-tab-emulation-hook))
5702 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5703 (or (not (bolp))
5704 (not (looking-at outline-regexp))))
5705 (call-interactively (global-key-binding "\t")))
5707 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5708 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5709 (or (and (eq org-cycle-emulate-tab 'white)
5710 (= (match-end 0) (point-at-eol)))
5711 (and (eq org-cycle-emulate-tab 'whitestart)
5712 (>= (match-end 0) pos))))
5714 (eq org-cycle-emulate-tab t))
5715 (call-interactively (global-key-binding "\t")))
5717 (t (save-excursion
5718 (org-back-to-heading)
5719 (org-cycle)))))))
5721 (defun org-cycle-internal-global ()
5722 "Do the global cycling action."
5723 (cond
5724 ((and (eq last-command this-command)
5725 (eq org-cycle-global-status 'overview))
5726 ;; We just created the overview - now do table of contents
5727 ;; This can be slow in very large buffers, so indicate action
5728 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5729 (message "CONTENTS...")
5730 (org-content)
5731 (message "CONTENTS...done")
5732 (setq org-cycle-global-status 'contents)
5733 (run-hook-with-args 'org-cycle-hook 'contents))
5735 ((and (eq last-command this-command)
5736 (eq org-cycle-global-status 'contents))
5737 ;; We just showed the table of contents - now show everything
5738 (run-hook-with-args 'org-pre-cycle-hook 'all)
5739 (show-all)
5740 (message "SHOW ALL")
5741 (setq org-cycle-global-status 'all)
5742 (run-hook-with-args 'org-cycle-hook 'all))
5745 ;; Default action: go to overview
5746 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5747 (org-overview)
5748 (message "OVERVIEW")
5749 (setq org-cycle-global-status 'overview)
5750 (run-hook-with-args 'org-cycle-hook 'overview))))
5752 (defun org-cycle-internal-local ()
5753 "Do the local cycling action."
5754 (org-back-to-heading)
5755 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5756 ;; First, some boundaries
5757 (save-excursion
5758 (org-back-to-heading)
5759 (setq level (funcall outline-level))
5760 (save-excursion
5761 (beginning-of-line 2)
5762 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5763 ; XEmacs does not have `next-single-char-property-change'
5764 ; I'm not sure about Emacs 21.
5765 (while (and (not (eobp)) ;; this is like `next-line'
5766 (get-char-property (1- (point)) 'invisible))
5767 (beginning-of-line 2))
5768 (while (and (not (eobp)) ;; this is like `next-line'
5769 (get-char-property (1- (point)) 'invisible))
5770 (goto-char (next-single-char-property-change (point) 'invisible))
5771 (and (eolp) (beginning-of-line 2))))
5772 (setq eol (point)))
5773 (outline-end-of-heading) (setq eoh (point))
5774 (save-excursion
5775 (outline-next-heading)
5776 (setq has-children (and (org-at-heading-p t)
5777 (> (funcall outline-level) level))))
5778 (org-end-of-subtree t)
5779 (unless (eobp)
5780 (skip-chars-forward " \t\n")
5781 (beginning-of-line 1) ; in case this is an item
5783 (setq eos (if (eobp) (point) (1- (point)))))
5784 ;; Find out what to do next and set `this-command'
5785 (cond
5786 ((= eos eoh)
5787 ;; Nothing is hidden behind this heading
5788 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5789 (message "EMPTY ENTRY")
5790 (setq org-cycle-subtree-status nil)
5791 (save-excursion
5792 (goto-char eos)
5793 (outline-next-heading)
5794 (if (org-invisible-p) (org-flag-heading nil))))
5795 ((and (or (>= eol eos)
5796 (not (string-match "\\S-" (buffer-substring eol eos))))
5797 (or has-children
5798 (not (setq children-skipped
5799 org-cycle-skip-children-state-if-no-children))))
5800 ;; Entire subtree is hidden in one line: children view
5801 (run-hook-with-args 'org-pre-cycle-hook 'children)
5802 (org-show-entry)
5803 (show-children)
5804 (message "CHILDREN")
5805 (save-excursion
5806 (goto-char eos)
5807 (outline-next-heading)
5808 (if (org-invisible-p) (org-flag-heading nil)))
5809 (setq org-cycle-subtree-status 'children)
5810 (run-hook-with-args 'org-cycle-hook 'children))
5811 ((or children-skipped
5812 (and (eq last-command this-command)
5813 (eq org-cycle-subtree-status 'children)))
5814 ;; We just showed the children, or no children are there,
5815 ;; now show everything.
5816 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5817 (org-show-subtree)
5818 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5819 (setq org-cycle-subtree-status 'subtree)
5820 (run-hook-with-args 'org-cycle-hook 'subtree))
5822 ;; Default action: hide the subtree.
5823 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5824 (hide-subtree)
5825 (message "FOLDED")
5826 (setq org-cycle-subtree-status 'folded)
5827 (run-hook-with-args 'org-cycle-hook 'folded)))))
5829 ;;;###autoload
5830 (defun org-global-cycle (&optional arg)
5831 "Cycle the global visibility. For details see `org-cycle'.
5832 With C-u prefix arg, switch to startup visibility.
5833 With a numeric prefix, show all headlines up to that level."
5834 (interactive "P")
5835 (let ((org-cycle-include-plain-lists
5836 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5837 (cond
5838 ((integerp arg)
5839 (show-all)
5840 (hide-sublevels arg)
5841 (setq org-cycle-global-status 'contents))
5842 ((equal arg '(4))
5843 (org-set-startup-visibility)
5844 (message "Startup visibility, plus VISIBILITY properties."))
5846 (org-cycle '(4))))))
5848 (defun org-set-startup-visibility ()
5849 "Set the visibility required by startup options and properties."
5850 (cond
5851 ((eq org-startup-folded t)
5852 (org-cycle '(4)))
5853 ((eq org-startup-folded 'content)
5854 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5855 (org-cycle '(4)) (org-cycle '(4)))))
5856 (unless (eq org-startup-folded 'showeverything)
5857 (if org-hide-block-startup (org-hide-block-all))
5858 (org-set-visibility-according-to-property 'no-cleanup)
5859 (org-cycle-hide-archived-subtrees 'all)
5860 (org-cycle-hide-drawers 'all)
5861 (org-cycle-show-empty-lines t)))
5863 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5864 "Switch subtree visibilities according to :VISIBILITY: property."
5865 (interactive)
5866 (let (org-show-entry-below state)
5867 (save-excursion
5868 (goto-char (point-min))
5869 (while (re-search-forward
5870 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5871 nil t)
5872 (setq state (match-string 1))
5873 (save-excursion
5874 (org-back-to-heading t)
5875 (hide-subtree)
5876 (org-reveal)
5877 (cond
5878 ((equal state '("fold" "folded"))
5879 (hide-subtree))
5880 ((equal state "children")
5881 (org-show-hidden-entry)
5882 (show-children))
5883 ((equal state "content")
5884 (save-excursion
5885 (save-restriction
5886 (org-narrow-to-subtree)
5887 (org-content))))
5888 ((member state '("all" "showall"))
5889 (show-subtree)))))
5890 (unless no-cleanup
5891 (org-cycle-hide-archived-subtrees 'all)
5892 (org-cycle-hide-drawers 'all)
5893 (org-cycle-show-empty-lines 'all)))))
5895 (defun org-overview ()
5896 "Switch to overview mode, showing only top-level headlines.
5897 Really, this shows all headlines with level equal or greater than the level
5898 of the first headline in the buffer. This is important, because if the
5899 first headline is not level one, then (hide-sublevels 1) gives confusing
5900 results."
5901 (interactive)
5902 (let ((level (save-excursion
5903 (goto-char (point-min))
5904 (if (re-search-forward (concat "^" outline-regexp) nil t)
5905 (progn
5906 (goto-char (match-beginning 0))
5907 (funcall outline-level))))))
5908 (and level (hide-sublevels level))))
5910 (defun org-content (&optional arg)
5911 "Show all headlines in the buffer, like a table of contents.
5912 With numerical argument N, show content up to level N."
5913 (interactive "P")
5914 (save-excursion
5915 ;; Visit all headings and show their offspring
5916 (and (integerp arg) (org-overview))
5917 (goto-char (point-max))
5918 (catch 'exit
5919 (while (and (progn (condition-case nil
5920 (outline-previous-visible-heading 1)
5921 (error (goto-char (point-min))))
5923 (looking-at outline-regexp))
5924 (if (integerp arg)
5925 (show-children (1- arg))
5926 (show-branches))
5927 (if (bobp) (throw 'exit nil))))))
5930 (defun org-optimize-window-after-visibility-change (state)
5931 "Adjust the window after a change in outline visibility.
5932 This function is the default value of the hook `org-cycle-hook'."
5933 (when (get-buffer-window (current-buffer))
5934 (cond
5935 ((eq state 'content) nil)
5936 ((eq state 'all) nil)
5937 ((eq state 'folded) nil)
5938 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5939 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5941 (defun org-remove-empty-overlays-at (pos)
5942 "Remove outline overlays that do not contain non-white stuff."
5943 (mapc
5944 (lambda (o)
5945 (and (eq 'outline (overlay-get o 'invisible))
5946 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5947 (overlay-end o))))
5948 (delete-overlay o)))
5949 (overlays-at pos)))
5951 (defun org-clean-visibility-after-subtree-move ()
5952 "Fix visibility issues after moving a subtree."
5953 ;; First, find a reasonable region to look at:
5954 ;; Start two siblings above, end three below
5955 (let* ((beg (save-excursion
5956 (and (org-get-last-sibling)
5957 (org-get-last-sibling))
5958 (point)))
5959 (end (save-excursion
5960 (and (org-get-next-sibling)
5961 (org-get-next-sibling)
5962 (org-get-next-sibling))
5963 (if (org-at-heading-p)
5964 (point-at-eol)
5965 (point))))
5966 (level (looking-at "\\*+"))
5967 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5968 (save-excursion
5969 (save-restriction
5970 (narrow-to-region beg end)
5971 (when re
5972 ;; Properly fold already folded siblings
5973 (goto-char (point-min))
5974 (while (re-search-forward re nil t)
5975 (if (and (not (org-invisible-p))
5976 (save-excursion
5977 (goto-char (point-at-eol)) (org-invisible-p)))
5978 (hide-entry))))
5979 (org-cycle-show-empty-lines 'overview)
5980 (org-cycle-hide-drawers 'overview)))))
5982 (defun org-cycle-show-empty-lines (state)
5983 "Show empty lines above all visible headlines.
5984 The region to be covered depends on STATE when called through
5985 `org-cycle-hook'. Lisp program can use t for STATE to get the
5986 entire buffer covered. Note that an empty line is only shown if there
5987 are at least `org-cycle-separator-lines' empty lines before the headline."
5988 (when (not (= org-cycle-separator-lines 0))
5989 (save-excursion
5990 (let* ((n (abs org-cycle-separator-lines))
5991 (re (cond
5992 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5993 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5994 (t (let ((ns (number-to-string (- n 2))))
5995 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5996 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5997 beg end b e)
5998 (cond
5999 ((memq state '(overview contents t))
6000 (setq beg (point-min) end (point-max)))
6001 ((memq state '(children folded))
6002 (setq beg (point) end (progn (org-end-of-subtree t t)
6003 (beginning-of-line 2)
6004 (point)))))
6005 (when beg
6006 (goto-char beg)
6007 (while (re-search-forward re end t)
6008 (unless (get-char-property (match-end 1) 'invisible)
6009 (setq e (match-end 1))
6010 (if (< org-cycle-separator-lines 0)
6011 (setq b (save-excursion
6012 (goto-char (match-beginning 0))
6013 (org-back-over-empty-lines)
6014 (if (save-excursion
6015 (goto-char (max (point-min) (1- (point))))
6016 (org-on-heading-p))
6017 (1- (point))
6018 (point))))
6019 (setq b (match-beginning 1)))
6020 (outline-flag-region b e nil)))))))
6021 ;; Never hide empty lines at the end of the file.
6022 (save-excursion
6023 (goto-char (point-max))
6024 (outline-previous-heading)
6025 (outline-end-of-heading)
6026 (if (and (looking-at "[ \t\n]+")
6027 (= (match-end 0) (point-max)))
6028 (outline-flag-region (point) (match-end 0) nil))))
6030 (defun org-show-empty-lines-in-parent ()
6031 "Move to the parent and re-show empty lines before visible headlines."
6032 (save-excursion
6033 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6034 (org-cycle-show-empty-lines context))))
6036 (defun org-files-list ()
6037 "Return `org-agenda-files' list, plus all open org-mode files.
6038 This is useful for operations that need to scan all of a user's
6039 open and agenda-wise Org files."
6040 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6041 (dolist (buf (buffer-list))
6042 (with-current-buffer buf
6043 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6044 (let ((file (expand-file-name (buffer-file-name))))
6045 (unless (member file files)
6046 (push file files))))))
6047 files))
6049 (defsubst org-entry-beginning-position ()
6050 "Return the beginning position of the current entry."
6051 (save-excursion (outline-back-to-heading t) (point)))
6053 (defsubst org-entry-end-position ()
6054 "Return the end position of the current entry."
6055 (save-excursion (outline-next-heading) (point)))
6057 (defun org-cycle-hide-drawers (state)
6058 "Re-hide all drawers after a visibility state change."
6059 (when (and (org-mode-p)
6060 (not (memq state '(overview folded contents))))
6061 (save-excursion
6062 (let* ((globalp (memq state '(contents all)))
6063 (beg (if globalp (point-min) (point)))
6064 (end (if globalp (point-max)
6065 (if (eq state 'children)
6066 (save-excursion (outline-next-heading) (point))
6067 (org-end-of-subtree t)))))
6068 (goto-char beg)
6069 (while (re-search-forward org-drawer-regexp end t)
6070 (org-flag-drawer t))))))
6072 (defun org-flag-drawer (flag)
6073 (save-excursion
6074 (beginning-of-line 1)
6075 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6076 (let ((b (match-end 0))
6077 (outline-regexp org-outline-regexp))
6078 (if (re-search-forward
6079 "^[ \t]*:END:"
6080 (save-excursion (outline-next-heading) (point)) t)
6081 (outline-flag-region b (point-at-eol) flag)
6082 (error ":END: line missing at position %s" b))))))
6084 (defun org-subtree-end-visible-p ()
6085 "Is the end of the current subtree visible?"
6086 (pos-visible-in-window-p
6087 (save-excursion (org-end-of-subtree t) (point))))
6089 (defun org-first-headline-recenter (&optional N)
6090 "Move cursor to the first headline and recenter the headline.
6091 Optional argument N means put the headline into the Nth line of the window."
6092 (goto-char (point-min))
6093 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6094 (beginning-of-line)
6095 (recenter (prefix-numeric-value N))))
6097 ;;; Saving and restoring visibility
6099 (defun org-outline-overlay-data (&optional use-markers)
6100 "Return a list of the locations of all outline overlays.
6101 The are overlays with the `invisible' property value `outline'.
6102 The return valus is a list of cons cells, with start and stop
6103 positions for each overlay.
6104 If USE-MARKERS is set, return the positions as markers."
6105 (let (beg end)
6106 (save-excursion
6107 (save-restriction
6108 (widen)
6109 (delq nil
6110 (mapcar (lambda (o)
6111 (when (eq (overlay-get o 'invisible) 'outline)
6112 (setq beg (overlay-start o)
6113 end (overlay-end o))
6114 (and beg end (> end beg)
6115 (if use-markers
6116 (cons (move-marker (make-marker) beg)
6117 (move-marker (make-marker) end))
6118 (cons beg end)))))
6119 (overlays-in (point-min) (point-max))))))))
6121 (defun org-set-outline-overlay-data (data)
6122 "Create visibility overlays for all positions in DATA.
6123 DATA should have been made by `org-outline-overlay-data'."
6124 (let (o)
6125 (save-excursion
6126 (save-restriction
6127 (widen)
6128 (show-all)
6129 (mapc (lambda (c)
6130 (setq o (make-overlay (car c) (cdr c)))
6131 (overlay-put o 'invisible 'outline))
6132 data)))))
6134 (defmacro org-save-outline-visibility (use-markers &rest body)
6135 "Save and restore outline visibility around BODY.
6136 If USE-MARKERS is non-nil, use markers for the positions.
6137 This means that the buffer may change while running BODY,
6138 but it also means that the buffer should stay alive
6139 during the operation, because otherwise all these markers will
6140 point nowhere."
6141 (declare (indent 1))
6142 `(let ((data (org-outline-overlay-data ,use-markers)))
6143 (unwind-protect
6144 (progn
6145 ,@body
6146 (org-set-outline-overlay-data data))
6147 (when ,use-markers
6148 (mapc (lambda (c)
6149 (and (markerp (car c)) (move-marker (car c) nil))
6150 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
6151 data)))))
6154 ;;; Folding of blocks
6156 (defconst org-block-regexp
6158 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6159 "Regular expression for hiding blocks.")
6161 (defvar org-hide-block-overlays nil
6162 "Overlays hiding blocks.")
6163 (make-variable-buffer-local 'org-hide-block-overlays)
6165 (defun org-block-map (function &optional start end)
6166 "Call func at the head of all source blocks in the current
6167 buffer. Optional arguments START and END can be used to limit
6168 the range."
6169 (let ((start (or start (point-min)))
6170 (end (or end (point-max))))
6171 (save-excursion
6172 (goto-char start)
6173 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6174 (save-excursion
6175 (save-match-data
6176 (goto-char (match-beginning 0))
6177 (funcall function)))))))
6179 (defun org-hide-block-toggle-all ()
6180 "Toggle the visibility of all blocks in the current buffer."
6181 (org-block-map #'org-hide-block-toggle))
6183 (defun org-hide-block-all ()
6184 "Fold all blocks in the current buffer."
6185 (interactive)
6186 (org-show-block-all)
6187 (org-block-map #'org-hide-block-toggle-maybe))
6189 (defun org-show-block-all ()
6190 "Unfold all blocks in the current buffer."
6191 (interactive)
6192 (mapc 'delete-overlay org-hide-block-overlays)
6193 (setq org-hide-block-overlays nil))
6195 (defun org-hide-block-toggle-maybe ()
6196 "Toggle visibility of block at point."
6197 (interactive)
6198 (let ((case-fold-search t))
6199 (if (save-excursion
6200 (beginning-of-line 1)
6201 (looking-at org-block-regexp))
6202 (progn (org-hide-block-toggle)
6203 t) ;; to signal that we took action
6204 nil))) ;; to signal that we did not
6206 (defun org-hide-block-toggle (&optional force)
6207 "Toggle the visibility of the current block."
6208 (interactive)
6209 (save-excursion
6210 (beginning-of-line)
6211 (if (re-search-forward org-block-regexp nil t)
6212 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6213 (end (match-end 0)) ;; end of entire body
6215 (if (memq t (mapcar (lambda (overlay)
6216 (eq (overlay-get overlay 'invisible)
6217 'org-hide-block))
6218 (overlays-at start)))
6219 (if (or (not force) (eq force 'off))
6220 (mapc (lambda (ov)
6221 (when (member ov org-hide-block-overlays)
6222 (setq org-hide-block-overlays
6223 (delq ov org-hide-block-overlays)))
6224 (when (eq (overlay-get ov 'invisible)
6225 'org-hide-block)
6226 (delete-overlay ov)))
6227 (overlays-at start)))
6228 (setq ov (make-overlay start end))
6229 (overlay-put ov 'invisible 'org-hide-block)
6230 ;; make the block accessible to isearch
6231 (overlay-put
6232 ov 'isearch-open-invisible
6233 (lambda (ov)
6234 (when (member ov org-hide-block-overlays)
6235 (setq org-hide-block-overlays
6236 (delq ov org-hide-block-overlays)))
6237 (when (eq (overlay-get ov 'invisible)
6238 'org-hide-block)
6239 (delete-overlay ov))))
6240 (push ov org-hide-block-overlays)))
6241 (error "Not looking at a source block"))))
6243 ;; org-tab-after-check-for-cycling-hook
6244 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6245 ;; Remove overlays when changing major mode
6246 (add-hook 'org-mode-hook
6247 (lambda () (org-add-hook 'change-major-mode-hook
6248 'org-show-block-all 'append 'local)))
6250 ;;; Org-goto
6252 (defvar org-goto-window-configuration nil)
6253 (defvar org-goto-marker nil)
6254 (defvar org-goto-map
6255 (let ((map (make-sparse-keymap)))
6256 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6257 (while (setq cmd (pop cmds))
6258 (substitute-key-definition cmd cmd map global-map)))
6259 (suppress-keymap map)
6260 (org-defkey map "\C-m" 'org-goto-ret)
6261 (org-defkey map [(return)] 'org-goto-ret)
6262 (org-defkey map [(left)] 'org-goto-left)
6263 (org-defkey map [(right)] 'org-goto-right)
6264 (org-defkey map [(control ?g)] 'org-goto-quit)
6265 (org-defkey map "\C-i" 'org-cycle)
6266 (org-defkey map [(tab)] 'org-cycle)
6267 (org-defkey map [(down)] 'outline-next-visible-heading)
6268 (org-defkey map [(up)] 'outline-previous-visible-heading)
6269 (if org-goto-auto-isearch
6270 (if (fboundp 'define-key-after)
6271 (define-key-after map [t] 'org-goto-local-auto-isearch)
6272 nil)
6273 (org-defkey map "q" 'org-goto-quit)
6274 (org-defkey map "n" 'outline-next-visible-heading)
6275 (org-defkey map "p" 'outline-previous-visible-heading)
6276 (org-defkey map "f" 'outline-forward-same-level)
6277 (org-defkey map "b" 'outline-backward-same-level)
6278 (org-defkey map "u" 'outline-up-heading))
6279 (org-defkey map "/" 'org-occur)
6280 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6281 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6282 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6283 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6284 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6285 map))
6287 (defconst org-goto-help
6288 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6289 RET=jump to location [Q]uit and return to previous location
6290 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6292 (defvar org-goto-start-pos) ; dynamically scoped parameter
6294 ;; FIXME: Docstring does not mention both interfaces
6295 (defun org-goto (&optional alternative-interface)
6296 "Look up a different location in the current file, keeping current visibility.
6298 When you want look-up or go to a different location in a document, the
6299 fastest way is often to fold the entire buffer and then dive into the tree.
6300 This method has the disadvantage, that the previous location will be folded,
6301 which may not be what you want.
6303 This command works around this by showing a copy of the current buffer
6304 in an indirect buffer, in overview mode. You can dive into the tree in
6305 that copy, use org-occur and incremental search to find a location.
6306 When pressing RET or `Q', the command returns to the original buffer in
6307 which the visibility is still unchanged. After RET is will also jump to
6308 the location selected in the indirect buffer and expose the
6309 the headline hierarchy above."
6310 (interactive "P")
6311 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6312 (org-refile-use-outline-path t)
6313 (org-refile-target-verify-function nil)
6314 (interface
6315 (if (not alternative-interface)
6316 org-goto-interface
6317 (if (eq org-goto-interface 'outline)
6318 'outline-path-completion
6319 'outline)))
6320 (org-goto-start-pos (point))
6321 (selected-point
6322 (if (eq interface 'outline)
6323 (car (org-get-location (current-buffer) org-goto-help))
6324 (nth 3 (org-refile-get-location "Goto: ")))))
6325 (if selected-point
6326 (progn
6327 (org-mark-ring-push org-goto-start-pos)
6328 (goto-char selected-point)
6329 (if (or (org-invisible-p) (org-invisible-p2))
6330 (org-show-context 'org-goto)))
6331 (message "Quit"))))
6333 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6334 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6335 (defvar org-goto-local-auto-isearch-map) ; defined below
6337 (defun org-get-location (buf help)
6338 "Let the user select a location in the Org-mode buffer BUF.
6339 This function uses a recursive edit. It returns the selected position
6340 or nil."
6341 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6342 (isearch-hide-immediately nil)
6343 (isearch-search-fun-function
6344 (lambda () 'org-goto-local-search-headings))
6345 (org-goto-selected-point org-goto-exit-command)
6346 (pop-up-frames nil)
6347 (special-display-buffer-names nil)
6348 (special-display-regexps nil)
6349 (special-display-function nil))
6350 (save-excursion
6351 (save-window-excursion
6352 (delete-other-windows)
6353 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6354 (switch-to-buffer
6355 (condition-case nil
6356 (make-indirect-buffer (current-buffer) "*org-goto*")
6357 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6358 (with-output-to-temp-buffer "*Help*"
6359 (princ help))
6360 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6361 (setq buffer-read-only nil)
6362 (let ((org-startup-truncated t)
6363 (org-startup-folded nil)
6364 (org-startup-align-all-tables nil))
6365 (org-mode)
6366 (org-overview))
6367 (setq buffer-read-only t)
6368 (if (and (boundp 'org-goto-start-pos)
6369 (integer-or-marker-p org-goto-start-pos))
6370 (let ((org-show-hierarchy-above t)
6371 (org-show-siblings t)
6372 (org-show-following-heading t))
6373 (goto-char org-goto-start-pos)
6374 (and (org-invisible-p) (org-show-context)))
6375 (goto-char (point-min)))
6376 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6377 (message "Select location and press RET")
6378 (use-local-map org-goto-map)
6379 (recursive-edit)
6381 (kill-buffer "*org-goto*")
6382 (cons org-goto-selected-point org-goto-exit-command)))
6384 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6385 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6386 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6387 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6389 (defun org-goto-local-search-headings (string bound noerror)
6390 "Search and make sure that any matches are in headlines."
6391 (catch 'return
6392 (while (if isearch-forward
6393 (search-forward string bound noerror)
6394 (search-backward string bound noerror))
6395 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6396 (and (member :headline context)
6397 (not (member :tags context))))
6398 (throw 'return (point))))))
6400 (defun org-goto-local-auto-isearch ()
6401 "Start isearch."
6402 (interactive)
6403 (goto-char (point-min))
6404 (let ((keys (this-command-keys)))
6405 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6406 (isearch-mode t)
6407 (isearch-process-search-char (string-to-char keys)))))
6409 (defun org-goto-ret (&optional arg)
6410 "Finish `org-goto' by going to the new location."
6411 (interactive "P")
6412 (setq org-goto-selected-point (point)
6413 org-goto-exit-command 'return)
6414 (throw 'exit nil))
6416 (defun org-goto-left ()
6417 "Finish `org-goto' by going to the new location."
6418 (interactive)
6419 (if (org-on-heading-p)
6420 (progn
6421 (beginning-of-line 1)
6422 (setq org-goto-selected-point (point)
6423 org-goto-exit-command 'left)
6424 (throw 'exit nil))
6425 (error "Not on a heading")))
6427 (defun org-goto-right ()
6428 "Finish `org-goto' by going to the new location."
6429 (interactive)
6430 (if (org-on-heading-p)
6431 (progn
6432 (setq org-goto-selected-point (point)
6433 org-goto-exit-command 'right)
6434 (throw 'exit nil))
6435 (error "Not on a heading")))
6437 (defun org-goto-quit ()
6438 "Finish `org-goto' without cursor motion."
6439 (interactive)
6440 (setq org-goto-selected-point nil)
6441 (setq org-goto-exit-command 'quit)
6442 (throw 'exit nil))
6444 ;;; Indirect buffer display of subtrees
6446 (defvar org-indirect-dedicated-frame nil
6447 "This is the frame being used for indirect tree display.")
6448 (defvar org-last-indirect-buffer nil)
6450 (defun org-tree-to-indirect-buffer (&optional arg)
6451 "Create indirect buffer and narrow it to current subtree.
6452 With numerical prefix ARG, go up to this level and then take that tree.
6453 If ARG is negative, go up that many levels.
6454 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6455 indirect buffer previously made with this command, to avoid proliferation of
6456 indirect buffers. However, when you call the command with a `C-u' prefix, or
6457 when `org-indirect-buffer-display' is `new-frame', the last buffer
6458 is kept so that you can work with several indirect buffers at the same time.
6459 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6460 requests that a new frame be made for the new buffer, so that the dedicated
6461 frame is not changed."
6462 (interactive "P")
6463 (let ((cbuf (current-buffer))
6464 (cwin (selected-window))
6465 (pos (point))
6466 beg end level heading ibuf)
6467 (save-excursion
6468 (org-back-to-heading t)
6469 (when (numberp arg)
6470 (setq level (org-outline-level))
6471 (if (< arg 0) (setq arg (+ level arg)))
6472 (while (> (setq level (org-outline-level)) arg)
6473 (outline-up-heading 1 t)))
6474 (setq beg (point)
6475 heading (org-get-heading))
6476 (org-end-of-subtree t t)
6477 (if (org-on-heading-p) (backward-char 1))
6478 (setq end (point)))
6479 (if (and (buffer-live-p org-last-indirect-buffer)
6480 (not (eq org-indirect-buffer-display 'new-frame))
6481 (not arg))
6482 (kill-buffer org-last-indirect-buffer))
6483 (setq ibuf (org-get-indirect-buffer cbuf)
6484 org-last-indirect-buffer ibuf)
6485 (cond
6486 ((or (eq org-indirect-buffer-display 'new-frame)
6487 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6488 (select-frame (make-frame))
6489 (delete-other-windows)
6490 (switch-to-buffer ibuf)
6491 (org-set-frame-title heading))
6492 ((eq org-indirect-buffer-display 'dedicated-frame)
6493 (raise-frame
6494 (select-frame (or (and org-indirect-dedicated-frame
6495 (frame-live-p org-indirect-dedicated-frame)
6496 org-indirect-dedicated-frame)
6497 (setq org-indirect-dedicated-frame (make-frame)))))
6498 (delete-other-windows)
6499 (switch-to-buffer ibuf)
6500 (org-set-frame-title (concat "Indirect: " heading)))
6501 ((eq org-indirect-buffer-display 'current-window)
6502 (switch-to-buffer ibuf))
6503 ((eq org-indirect-buffer-display 'other-window)
6504 (pop-to-buffer ibuf))
6505 (t (error "Invalid value")))
6506 (if (featurep 'xemacs)
6507 (save-excursion (org-mode) (turn-on-font-lock)))
6508 (narrow-to-region beg end)
6509 (show-all)
6510 (goto-char pos)
6511 (and (window-live-p cwin) (select-window cwin))))
6513 (defun org-get-indirect-buffer (&optional buffer)
6514 (setq buffer (or buffer (current-buffer)))
6515 (let ((n 1) (base (buffer-name buffer)) bname)
6516 (while (buffer-live-p
6517 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6518 (setq n (1+ n)))
6519 (condition-case nil
6520 (make-indirect-buffer buffer bname 'clone)
6521 (error (make-indirect-buffer buffer bname)))))
6523 (defun org-set-frame-title (title)
6524 "Set the title of the current frame to the string TITLE."
6525 ;; FIXME: how to name a single frame in XEmacs???
6526 (unless (featurep 'xemacs)
6527 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6529 ;;;; Structure editing
6531 ;;; Inserting headlines
6533 (defun org-previous-line-empty-p ()
6534 (save-excursion
6535 (and (not (bobp))
6536 (or (beginning-of-line 0) t)
6537 (save-match-data
6538 (looking-at "[ \t]*$")))))
6540 (defun org-insert-heading (&optional force-heading invisible-ok)
6541 "Insert a new heading or item with same depth at point.
6542 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6543 If point is at the beginning of a headline, insert a sibling before the
6544 current headline. If point is not at the beginning, do not split the line,
6545 but create the new headline after the current line.
6546 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6547 This is important for non-interactive uses of the command."
6548 (interactive "P")
6549 (if (or (= (buffer-size) 0)
6550 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6551 (org-on-heading-p))))
6552 (not (org-in-item-p))))
6553 (insert "\n* ")
6554 (when (or force-heading (not (org-insert-item)))
6555 (let* ((empty-line-p nil)
6556 (head (save-excursion
6557 (condition-case nil
6558 (progn
6559 (org-back-to-heading invisible-ok)
6560 (setq empty-line-p (org-previous-line-empty-p))
6561 (match-string 0))
6562 (error "*"))))
6563 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6564 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6565 pos hide-previous previous-pos)
6566 (cond
6567 ((and (org-on-heading-p) (bolp)
6568 (or (bobp)
6569 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6570 ;; insert before the current line
6571 (open-line (if blank 2 1)))
6572 ((and (bolp)
6573 (not org-insert-heading-respect-content)
6574 (or (bobp)
6575 (save-excursion
6576 (backward-char 1) (not (org-invisible-p)))))
6577 ;; insert right here
6578 nil)
6580 ;; somewhere in the line
6581 (save-excursion
6582 (setq previous-pos (point-at-bol))
6583 (end-of-line)
6584 (setq hide-previous (org-invisible-p)))
6585 (and org-insert-heading-respect-content (org-show-subtree))
6586 (let ((split
6587 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6588 (save-excursion
6589 (let ((p (point)))
6590 (goto-char (point-at-bol))
6591 (and (looking-at org-complex-heading-regexp)
6592 (> p (match-beginning 4)))))))
6593 tags pos)
6594 (cond
6595 (org-insert-heading-respect-content
6596 (org-end-of-subtree nil t)
6597 (or (bolp) (newline))
6598 (or (org-previous-line-empty-p)
6599 (and blank (newline)))
6600 (open-line 1))
6601 ((org-on-heading-p)
6602 (when hide-previous
6603 (show-children)
6604 (org-show-entry))
6605 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6606 (setq tags (and (match-end 2) (match-string 2)))
6607 (and (match-end 1)
6608 (delete-region (match-beginning 1) (match-end 1)))
6609 (setq pos (point-at-bol))
6610 (or split (end-of-line 1))
6611 (delete-horizontal-space)
6612 (if (string-match "\\`\\*+\\'"
6613 (buffer-substring (point-at-bol) (point)))
6614 (insert " "))
6615 (newline (if blank 2 1))
6616 (when tags
6617 (save-excursion
6618 (goto-char pos)
6619 (end-of-line 1)
6620 (insert " " tags)
6621 (org-set-tags nil 'align))))
6623 (or split (end-of-line 1))
6624 (newline (if blank 2 1)))))))
6625 (insert head) (just-one-space)
6626 (setq pos (point))
6627 (end-of-line 1)
6628 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6629 (when (and org-insert-heading-respect-content hide-previous)
6630 (save-excursion
6631 (goto-char previous-pos)
6632 (hide-subtree)))
6633 (run-hooks 'org-insert-heading-hook)))))
6635 (defun org-get-heading (&optional no-tags)
6636 "Return the heading of the current entry, without the stars."
6637 (save-excursion
6638 (org-back-to-heading t)
6639 (if (looking-at
6640 (if no-tags
6641 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6642 "\\*+[ \t]+\\([^\r\n]*\\)"))
6643 (match-string 1) "")))
6645 (defun org-heading-components ()
6646 "Return the components of the current heading.
6647 This is a list with the following elements:
6648 - the level as an integer
6649 - the reduced level, different if `org-odd-levels-only' is set.
6650 - the TODO keyword, or nil
6651 - the priority character, like ?A, or nil if no priority is given
6652 - the headline text itself, or the tags string if no headline text
6653 - the tags string, or nil."
6654 (save-excursion
6655 (org-back-to-heading t)
6656 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6657 (list (length (match-string 1))
6658 (org-reduced-level (length (match-string 1)))
6659 (org-match-string-no-properties 2)
6660 (and (match-end 3) (aref (match-string 3) 2))
6661 (org-match-string-no-properties 4)
6662 (org-match-string-no-properties 5)))))
6664 (defun org-get-entry ()
6665 "Get the entry text, after heading, entire subtree."
6666 (save-excursion
6667 (org-back-to-heading t)
6668 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6670 (defun org-insert-heading-after-current ()
6671 "Insert a new heading with same level as current, after current subtree."
6672 (interactive)
6673 (org-back-to-heading)
6674 (org-insert-heading)
6675 (org-move-subtree-down)
6676 (end-of-line 1))
6678 (defun org-insert-heading-respect-content ()
6679 (interactive)
6680 (let ((org-insert-heading-respect-content t))
6681 (org-insert-heading t)))
6683 (defun org-insert-todo-heading-respect-content (&optional force-state)
6684 (interactive "P")
6685 (let ((org-insert-heading-respect-content t))
6686 (org-insert-todo-heading force-state t)))
6688 (defun org-insert-todo-heading (arg &optional force-heading)
6689 "Insert a new heading with the same level and TODO state as current heading.
6690 If the heading has no TODO state, or if the state is DONE, use the first
6691 state (TODO by default). Also with prefix arg, force first state."
6692 (interactive "P")
6693 (when (or force-heading (not (org-insert-item 'checkbox)))
6694 (org-insert-heading force-heading)
6695 (save-excursion
6696 (org-back-to-heading)
6697 (outline-previous-heading)
6698 (looking-at org-todo-line-regexp))
6699 (let*
6700 ((new-mark-x
6701 (if (or arg
6702 (not (match-beginning 2))
6703 (member (match-string 2) org-done-keywords))
6704 (car org-todo-keywords-1)
6705 (match-string 2)))
6706 (new-mark
6708 (run-hook-with-args-until-success
6709 'org-todo-get-default-hook new-mark-x nil)
6710 new-mark-x)))
6711 (beginning-of-line 1)
6712 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6713 (if org-treat-insert-todo-heading-as-state-change
6714 (org-todo new-mark)
6715 (insert new-mark " "))))
6716 (when org-provide-todo-statistics
6717 (org-update-parent-todo-statistics))))
6719 (defun org-insert-subheading (arg)
6720 "Insert a new subheading and demote it.
6721 Works for outline headings and for plain lists alike."
6722 (interactive "P")
6723 (org-insert-heading arg)
6724 (cond
6725 ((org-on-heading-p) (org-do-demote))
6726 ((org-at-item-p) (org-indent-item 1))))
6728 (defun org-insert-todo-subheading (arg)
6729 "Insert a new subheading with TODO keyword or checkbox and demote it.
6730 Works for outline headings and for plain lists alike."
6731 (interactive "P")
6732 (org-insert-todo-heading arg)
6733 (cond
6734 ((org-on-heading-p) (org-do-demote))
6735 ((org-at-item-p) (org-indent-item 1))))
6737 ;;; Promotion and Demotion
6739 (defvar org-after-demote-entry-hook nil
6740 "Hook run after an entry has been demoted.
6741 The cursor will be at the beginning of the entry.
6742 When a subtree is being demoted, the hook will be called for each node.")
6744 (defvar org-after-promote-entry-hook nil
6745 "Hook run after an entry has been promoted.
6746 The cursor will be at the beginning of the entry.
6747 When a subtree is being promoted, the hook will be called for each node.")
6749 (defun org-promote-subtree ()
6750 "Promote the entire subtree.
6751 See also `org-promote'."
6752 (interactive)
6753 (save-excursion
6754 (org-map-tree 'org-promote))
6755 (org-fix-position-after-promote))
6757 (defun org-demote-subtree ()
6758 "Demote the entire subtree. See `org-demote'.
6759 See also `org-promote'."
6760 (interactive)
6761 (save-excursion
6762 (org-map-tree 'org-demote))
6763 (org-fix-position-after-promote))
6766 (defun org-do-promote ()
6767 "Promote the current heading higher up the tree.
6768 If the region is active in `transient-mark-mode', promote all headings
6769 in the region."
6770 (interactive)
6771 (save-excursion
6772 (if (org-region-active-p)
6773 (org-map-region 'org-promote (region-beginning) (region-end))
6774 (org-promote)))
6775 (org-fix-position-after-promote))
6777 (defun org-do-demote ()
6778 "Demote the current heading lower down the tree.
6779 If the region is active in `transient-mark-mode', demote all headings
6780 in the region."
6781 (interactive)
6782 (save-excursion
6783 (if (org-region-active-p)
6784 (org-map-region 'org-demote (region-beginning) (region-end))
6785 (org-demote)))
6786 (org-fix-position-after-promote))
6788 (defun org-fix-position-after-promote ()
6789 "Make sure that after pro/demotion cursor position is right."
6790 (let ((pos (point)))
6791 (when (save-excursion
6792 (beginning-of-line 1)
6793 (looking-at org-todo-line-regexp)
6794 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6795 (cond ((eobp) (insert " "))
6796 ((eolp) (insert " "))
6797 ((equal (char-after) ?\ ) (forward-char 1))))))
6799 (defun org-current-level ()
6800 "Return the level of the current entry, or nil if before the first headline.
6801 The level is the number of stars at the beginning of the headline."
6802 (save-excursion
6803 (condition-case nil
6804 (progn
6805 (org-back-to-heading t)
6806 (funcall outline-level))
6807 (error nil))))
6809 (defun org-get-previous-line-level ()
6810 "Return the outline depth of the last headline before the current line.
6811 Returns 0 for the first headline in the buffer, and nil if before the
6812 first headline."
6813 (let ((current-level (org-current-level))
6814 (prev-level (when (> (line-number-at-pos) 1)
6815 (save-excursion
6816 (beginning-of-line 0)
6817 (org-current-level)))))
6818 (cond ((null current-level) nil) ; Before first headline
6819 ((null prev-level) 0) ; At first headline
6820 (prev-level))))
6822 (defun org-reduced-level (l)
6823 "Compute the effective level of a heading.
6824 This takes into account the setting of `org-odd-levels-only'."
6825 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6827 (defun org-level-increment ()
6828 "Return the number of stars that will be added or removed at a
6829 time to headlines when structure editing, based on the value of
6830 `org-odd-levels-only'."
6831 (if org-odd-levels-only 2 1))
6833 (defun org-get-valid-level (level &optional change)
6834 "Rectify a level change under the influence of `org-odd-levels-only'
6835 LEVEL is a current level, CHANGE is by how much the level should be
6836 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6837 even level numbers will become the next higher odd number."
6838 (if org-odd-levels-only
6839 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6840 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6841 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6842 (max 1 (+ level (or change 0)))))
6844 (if (boundp 'define-obsolete-function-alias)
6845 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6846 (define-obsolete-function-alias 'org-get-legal-level
6847 'org-get-valid-level)
6848 (define-obsolete-function-alias 'org-get-legal-level
6849 'org-get-valid-level "23.1")))
6851 (defun org-promote ()
6852 "Promote the current heading higher up the tree.
6853 If the region is active in `transient-mark-mode', promote all headings
6854 in the region."
6855 (org-back-to-heading t)
6856 (let* ((level (save-match-data (funcall outline-level)))
6857 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6858 (diff (abs (- level (length up-head) -1))))
6859 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6860 (replace-match up-head nil t)
6861 ;; Fixup tag positioning
6862 (and org-auto-align-tags (org-set-tags nil t))
6863 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6864 (run-hooks 'org-after-promote-entry-hook)))
6866 (defun org-demote ()
6867 "Demote the current heading lower down the tree.
6868 If the region is active in `transient-mark-mode', demote all headings
6869 in the region."
6870 (org-back-to-heading t)
6871 (let* ((level (save-match-data (funcall outline-level)))
6872 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6873 (diff (abs (- level (length down-head) -1))))
6874 (replace-match down-head nil t)
6875 ;; Fixup tag positioning
6876 (and org-auto-align-tags (org-set-tags nil t))
6877 (if org-adapt-indentation (org-fixup-indentation diff))
6878 (run-hooks 'org-after-demote-entry-hook)))
6880 (defun org-cycle-level ()
6881 "Cycle the level of an empty headline through possible states.
6882 This goes first to child, then to parent, level, then up the hierarchy.
6883 After top level, it switches back to sibling level."
6884 (interactive)
6885 (let ((org-adapt-indentation nil))
6886 (when (org-point-at-end-of-empty-headline)
6887 (setq this-command 'org-cycle-level) ; Only needed for caching
6888 (let ((cur-level (org-current-level))
6889 (prev-level (org-get-previous-line-level)))
6890 (cond
6891 ;; If first headline in file, promote to top-level.
6892 ((= prev-level 0)
6893 (loop repeat (/ (- cur-level 1) (org-level-increment))
6894 do (org-do-promote)))
6895 ;; If same level as prev, demote one.
6896 ((= prev-level cur-level)
6897 (org-do-demote))
6898 ;; If parent is top-level, promote to top level if not already.
6899 ((= prev-level 1)
6900 (loop repeat (/ (- cur-level 1) (org-level-increment))
6901 do (org-do-promote)))
6902 ;; If top-level, return to prev-level.
6903 ((= cur-level 1)
6904 (loop repeat (/ (- prev-level 1) (org-level-increment))
6905 do (org-do-demote)))
6906 ;; If less than prev-level, promote one.
6907 ((< cur-level prev-level)
6908 (org-do-promote))
6909 ;; If deeper than prev-level, promote until higher than
6910 ;; prev-level.
6911 ((> cur-level prev-level)
6912 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6913 do (org-do-promote))))
6914 t))))
6916 (defun org-map-tree (fun)
6917 "Call FUN for every heading underneath the current one."
6918 (org-back-to-heading)
6919 (let ((level (funcall outline-level)))
6920 (save-excursion
6921 (funcall fun)
6922 (while (and (progn
6923 (outline-next-heading)
6924 (> (funcall outline-level) level))
6925 (not (eobp)))
6926 (funcall fun)))))
6928 (defun org-map-region (fun beg end)
6929 "Call FUN for every heading between BEG and END."
6930 (let ((org-ignore-region t))
6931 (save-excursion
6932 (setq end (copy-marker end))
6933 (goto-char beg)
6934 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6935 (< (point) end))
6936 (funcall fun))
6937 (while (and (progn
6938 (outline-next-heading)
6939 (< (point) end))
6940 (not (eobp)))
6941 (funcall fun)))))
6943 (defun org-fixup-indentation (diff)
6944 "Change the indentation in the current entry by DIFF
6945 However, if any line in the current entry has no indentation, or if it
6946 would end up with no indentation after the change, nothing at all is done."
6947 (save-excursion
6948 (let ((end (save-excursion (outline-next-heading)
6949 (point-marker)))
6950 (prohibit (if (> diff 0)
6951 "^\\S-"
6952 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6953 col)
6954 (unless (save-excursion (end-of-line 1)
6955 (re-search-forward prohibit end t))
6956 (while (and (< (point) end)
6957 (re-search-forward "^[ \t]+" end t))
6958 (goto-char (match-end 0))
6959 (setq col (current-column))
6960 (if (< diff 0) (replace-match ""))
6961 (org-indent-to-column (+ diff col))))
6962 (move-marker end nil))))
6964 (defun org-convert-to-odd-levels ()
6965 "Convert an org-mode file with all levels allowed to one with odd levels.
6966 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6967 level 5 etc."
6968 (interactive)
6969 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6970 (let ((outline-regexp org-outline-regexp)
6971 (outline-level 'org-outline-level)
6972 (org-odd-levels-only nil) n)
6973 (save-excursion
6974 (goto-char (point-min))
6975 (while (re-search-forward "^\\*\\*+ " nil t)
6976 (setq n (- (length (match-string 0)) 2))
6977 (while (>= (setq n (1- n)) 0)
6978 (org-demote))
6979 (end-of-line 1))))))
6981 (defun org-convert-to-oddeven-levels ()
6982 "Convert an org-mode file with only odd levels to one with odd and even levels.
6983 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6984 section with an even level, conversion would destroy the structure of the file. An error
6985 is signaled in this case."
6986 (interactive)
6987 (goto-char (point-min))
6988 ;; First check if there are no even levels
6989 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6990 (org-show-context t)
6991 (error "Not all levels are odd in this file. Conversion not possible"))
6992 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6993 (let ((outline-regexp org-outline-regexp)
6994 (outline-level 'org-outline-level)
6995 (org-odd-levels-only nil) n)
6996 (save-excursion
6997 (goto-char (point-min))
6998 (while (re-search-forward "^\\*\\*+ " nil t)
6999 (setq n (/ (1- (length (match-string 0))) 2))
7000 (while (>= (setq n (1- n)) 0)
7001 (org-promote))
7002 (end-of-line 1))))))
7004 (defun org-tr-level (n)
7005 "Make N odd if required."
7006 (if org-odd-levels-only (1+ (/ n 2)) n))
7008 ;;; Vertical tree motion, cutting and pasting of subtrees
7010 (defun org-move-subtree-up (&optional arg)
7011 "Move the current subtree up past ARG headlines of the same level."
7012 (interactive "p")
7013 (org-move-subtree-down (- (prefix-numeric-value arg))))
7015 (defun org-move-subtree-down (&optional arg)
7016 "Move the current subtree down past ARG headlines of the same level."
7017 (interactive "p")
7018 (setq arg (prefix-numeric-value arg))
7019 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7020 'org-get-last-sibling))
7021 (ins-point (make-marker))
7022 (cnt (abs arg))
7023 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7024 ;; Select the tree
7025 (org-back-to-heading)
7026 (setq beg0 (point))
7027 (save-excursion
7028 (setq ne-beg (org-back-over-empty-lines))
7029 (setq beg (point)))
7030 (save-match-data
7031 (save-excursion (outline-end-of-heading)
7032 (setq folded (org-invisible-p)))
7033 (outline-end-of-subtree))
7034 (outline-next-heading)
7035 (setq ne-end (org-back-over-empty-lines))
7036 (setq end (point))
7037 (goto-char beg0)
7038 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7039 ;; include less whitespace
7040 (save-excursion
7041 (goto-char beg)
7042 (forward-line (- ne-beg ne-end))
7043 (setq beg (point))))
7044 ;; Find insertion point, with error handling
7045 (while (> cnt 0)
7046 (or (and (funcall movfunc) (looking-at outline-regexp))
7047 (progn (goto-char beg0)
7048 (error "Cannot move past superior level or buffer limit")))
7049 (setq cnt (1- cnt)))
7050 (if (> arg 0)
7051 ;; Moving forward - still need to move over subtree
7052 (progn (org-end-of-subtree t t)
7053 (save-excursion
7054 (org-back-over-empty-lines)
7055 (or (bolp) (newline)))))
7056 (setq ne-ins (org-back-over-empty-lines))
7057 (move-marker ins-point (point))
7058 (setq txt (buffer-substring beg end))
7059 (org-save-markers-in-region beg end)
7060 (delete-region beg end)
7061 (org-remove-empty-overlays-at beg)
7062 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7063 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7064 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7065 (let ((bbb (point)))
7066 (insert-before-markers txt)
7067 (org-reinstall-markers-in-region bbb)
7068 (move-marker ins-point bbb))
7069 (or (bolp) (insert "\n"))
7070 (setq ins-end (point))
7071 (goto-char ins-point)
7072 (org-skip-whitespace)
7073 (when (and (< arg 0)
7074 (org-first-sibling-p)
7075 (> ne-ins ne-beg))
7076 ;; Move whitespace back to beginning
7077 (save-excursion
7078 (goto-char ins-end)
7079 (let ((kill-whole-line t))
7080 (kill-line (- ne-ins ne-beg)) (point)))
7081 (insert (make-string (- ne-ins ne-beg) ?\n)))
7082 (move-marker ins-point nil)
7083 (if folded
7084 (hide-subtree)
7085 (org-show-entry)
7086 (show-children)
7087 (org-cycle-hide-drawers 'children))
7088 (org-clean-visibility-after-subtree-move)))
7090 (defvar org-subtree-clip ""
7091 "Clipboard for cut and paste of subtrees.
7092 This is actually only a copy of the kill, because we use the normal kill
7093 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7095 (defvar org-subtree-clip-folded nil
7096 "Was the last copied subtree folded?
7097 This is used to fold the tree back after pasting.")
7099 (defun org-cut-subtree (&optional n)
7100 "Cut the current subtree into the clipboard.
7101 With prefix arg N, cut this many sequential subtrees.
7102 This is a short-hand for marking the subtree and then cutting it."
7103 (interactive "p")
7104 (org-copy-subtree n 'cut))
7106 (defun org-copy-subtree (&optional n cut force-store-markers)
7107 "Cut the current subtree into the clipboard.
7108 With prefix arg N, cut this many sequential subtrees.
7109 This is a short-hand for marking the subtree and then copying it.
7110 If CUT is non-nil, actually cut the subtree.
7111 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7112 of some markers in the region, even if CUT is non-nil. This is
7113 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7114 (interactive "p")
7115 (let (beg end folded (beg0 (point)))
7116 (if (interactive-p)
7117 (org-back-to-heading nil) ; take what looks like a subtree
7118 (org-back-to-heading t)) ; take what is really there
7119 (org-back-over-empty-lines)
7120 (setq beg (point))
7121 (skip-chars-forward " \t\r\n")
7122 (save-match-data
7123 (save-excursion (outline-end-of-heading)
7124 (setq folded (org-invisible-p)))
7125 (condition-case nil
7126 (org-forward-same-level (1- n) t)
7127 (error nil))
7128 (org-end-of-subtree t t))
7129 (org-back-over-empty-lines)
7130 (setq end (point))
7131 (goto-char beg0)
7132 (when (> end beg)
7133 (setq org-subtree-clip-folded folded)
7134 (when (or cut force-store-markers)
7135 (org-save-markers-in-region beg end))
7136 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7137 (setq org-subtree-clip (current-kill 0))
7138 (message "%s: Subtree(s) with %d characters"
7139 (if cut "Cut" "Copied")
7140 (length org-subtree-clip)))))
7142 (defun org-paste-subtree (&optional level tree for-yank)
7143 "Paste the clipboard as a subtree, with modification of headline level.
7144 The entire subtree is promoted or demoted in order to match a new headline
7145 level.
7147 If the cursor is at the beginning of a headline, the same level as
7148 that headline is used to paste the tree
7150 If not, the new level is derived from the *visible* headings
7151 before and after the insertion point, and taken to be the inferior headline
7152 level of the two. So if the previous visible heading is level 3 and the
7153 next is level 4 (or vice versa), level 4 will be used for insertion.
7154 This makes sure that the subtree remains an independent subtree and does
7155 not swallow low level entries.
7157 You can also force a different level, either by using a numeric prefix
7158 argument, or by inserting the heading marker by hand. For example, if the
7159 cursor is after \"*****\", then the tree will be shifted to level 5.
7161 If optional TREE is given, use this text instead of the kill ring.
7163 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7164 move back over whitespace before inserting, and move point to the end of
7165 the inserted text when done."
7166 (interactive "P")
7167 (setq tree (or tree (and kill-ring (current-kill 0))))
7168 (unless (org-kill-is-subtree-p tree)
7169 (error "%s"
7170 (substitute-command-keys
7171 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7172 (let* ((visp (not (org-invisible-p)))
7173 (txt tree)
7174 (^re (concat "^\\(" outline-regexp "\\)"))
7175 (re (concat "\\(" outline-regexp "\\)"))
7176 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7178 (old-level (if (string-match ^re txt)
7179 (- (match-end 0) (match-beginning 0) 1)
7180 -1))
7181 (force-level (cond (level (prefix-numeric-value level))
7182 ((and (looking-at "[ \t]*$")
7183 (string-match
7184 ^re_ (buffer-substring
7185 (point-at-bol) (point))))
7186 (- (match-end 1) (match-beginning 1)))
7187 ((and (bolp)
7188 (looking-at org-outline-regexp))
7189 (- (match-end 0) (point) 1))
7190 (t nil)))
7191 (previous-level (save-excursion
7192 (condition-case nil
7193 (progn
7194 (outline-previous-visible-heading 1)
7195 (if (looking-at re)
7196 (- (match-end 0) (match-beginning 0) 1)
7198 (error 1))))
7199 (next-level (save-excursion
7200 (condition-case nil
7201 (progn
7202 (or (looking-at outline-regexp)
7203 (outline-next-visible-heading 1))
7204 (if (looking-at re)
7205 (- (match-end 0) (match-beginning 0) 1)
7207 (error 1))))
7208 (new-level (or force-level (max previous-level next-level)))
7209 (shift (if (or (= old-level -1)
7210 (= new-level -1)
7211 (= old-level new-level))
7213 (- new-level old-level)))
7214 (delta (if (> shift 0) -1 1))
7215 (func (if (> shift 0) 'org-demote 'org-promote))
7216 (org-odd-levels-only nil)
7217 beg end newend)
7218 ;; Remove the forced level indicator
7219 (if force-level
7220 (delete-region (point-at-bol) (point)))
7221 ;; Paste
7222 (beginning-of-line 1)
7223 (unless for-yank (org-back-over-empty-lines))
7224 (setq beg (point))
7225 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7226 (insert-before-markers txt)
7227 (unless (string-match "\n\\'" txt) (insert "\n"))
7228 (setq newend (point))
7229 (org-reinstall-markers-in-region beg)
7230 (setq end (point))
7231 (goto-char beg)
7232 (skip-chars-forward " \t\n\r")
7233 (setq beg (point))
7234 (if (and (org-invisible-p) visp)
7235 (save-excursion (outline-show-heading)))
7236 ;; Shift if necessary
7237 (unless (= shift 0)
7238 (save-restriction
7239 (narrow-to-region beg end)
7240 (while (not (= shift 0))
7241 (org-map-region func (point-min) (point-max))
7242 (setq shift (+ delta shift)))
7243 (goto-char (point-min))
7244 (setq newend (point-max))))
7245 (when (or (interactive-p) for-yank)
7246 (message "Clipboard pasted as level %d subtree" new-level))
7247 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7248 kill-ring
7249 (eq org-subtree-clip (current-kill 0))
7250 org-subtree-clip-folded)
7251 ;; The tree was folded before it was killed/copied
7252 (hide-subtree))
7253 (and for-yank (goto-char newend))))
7255 (defun org-kill-is-subtree-p (&optional txt)
7256 "Check if the current kill is an outline subtree, or a set of trees.
7257 Returns nil if kill does not start with a headline, or if the first
7258 headline level is not the largest headline level in the tree.
7259 So this will actually accept several entries of equal levels as well,
7260 which is OK for `org-paste-subtree'.
7261 If optional TXT is given, check this string instead of the current kill."
7262 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7263 (start-level (and kill
7264 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7265 org-outline-regexp "\\)")
7266 kill)
7267 (- (match-end 2) (match-beginning 2) 1)))
7268 (re (concat "^" org-outline-regexp))
7269 (start (1+ (or (match-beginning 2) -1))))
7270 (if (not start-level)
7271 (progn
7272 nil) ;; does not even start with a heading
7273 (catch 'exit
7274 (while (setq start (string-match re kill (1+ start)))
7275 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7276 (throw 'exit nil)))
7277 t))))
7279 (defvar org-markers-to-move nil
7280 "Markers that should be moved with a cut-and-paste operation.
7281 Those markers are stored together with their positions relative to
7282 the start of the region.")
7284 (defun org-save-markers-in-region (beg end)
7285 "Check markers in region.
7286 If these markers are between BEG and END, record their position relative
7287 to BEG, so that after moving the block of text, we can put the markers back
7288 into place.
7289 This function gets called just before an entry or tree gets cut from the
7290 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7291 called immediately, to move the markers with the entries."
7292 (setq org-markers-to-move nil)
7293 (when (featurep 'org-clock)
7294 (org-clock-save-markers-for-cut-and-paste beg end))
7295 (when (featurep 'org-agenda)
7296 (org-agenda-save-markers-for-cut-and-paste beg end)))
7298 (defun org-check-and-save-marker (marker beg end)
7299 "Check if MARKER is between BEG and END.
7300 If yes, remember the marker and the distance to BEG."
7301 (when (and (marker-buffer marker)
7302 (equal (marker-buffer marker) (current-buffer)))
7303 (if (and (>= marker beg) (< marker end))
7304 (push (cons marker (- marker beg)) org-markers-to-move))))
7306 (defun org-reinstall-markers-in-region (beg)
7307 "Move all remembered markers to their position relative to BEG."
7308 (mapc (lambda (x)
7309 (move-marker (car x) (+ beg (cdr x))))
7310 org-markers-to-move)
7311 (setq org-markers-to-move nil))
7313 (defun org-narrow-to-subtree ()
7314 "Narrow buffer to the current subtree."
7315 (interactive)
7316 (save-excursion
7317 (save-match-data
7318 (narrow-to-region
7319 (progn (org-back-to-heading t) (point))
7320 (progn (org-end-of-subtree t t)
7321 (if (org-on-heading-p) (backward-char 1))
7322 (point))))))
7324 (eval-when-compile
7325 (defvar org-property-drawer-re))
7327 (defun org-clone-subtree-with-time-shift (n &optional shift)
7328 "Clone the task (subtree) at point N times.
7329 The clones will be inserted as siblings.
7331 In interactive use, the user will be prompted for the number of
7332 clones to be produced, and for a time SHIFT, which may be a
7333 repeater as used in time stamps, for example `+3d'.
7335 When a valid repeater is given and the entry contains any time
7336 stamps, the clones will become a sequence in time, with time
7337 stamps in the subtree shifted for each clone produced. If SHIFT
7338 is nil or the empty string, time stamps will be left alone. The
7339 ID property of the original subtree is removed.
7341 If the original subtree did contain time stamps with a repeater,
7342 the following will happen:
7343 - the repeater will be removed in each clone
7344 - an additional clone will be produced, with the current, unshifted
7345 date(s) in the entry.
7346 - the original entry will be placed *after* all the clones, with
7347 repeater intact.
7348 - the start days in the repeater in the original entry will be shifted
7349 to past the last clone.
7350 I this way you can spell out a number of instances of a repeating task,
7351 and still retain the repeater to cover future instances of the task."
7352 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7353 (let (beg end template task idprop
7354 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7355 (if (not (and (integerp n) (> n 0)))
7356 (error "Invalid number of replications %s" n))
7357 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7358 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7359 shift)))
7360 (error "Invalid shift specification %s" shift))
7361 (when doshift
7362 (setq shift-n (string-to-number (match-string 1 shift))
7363 shift-what (cdr (assoc (match-string 2 shift)
7364 '(("d" . day) ("w" . week)
7365 ("m" . month) ("y" . year))))))
7366 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7367 (setq nmin 1 nmax n)
7368 (org-back-to-heading t)
7369 (setq beg (point))
7370 (setq idprop (org-entry-get nil "ID"))
7371 (org-end-of-subtree t t)
7372 (or (bolp) (insert "\n"))
7373 (setq end (point))
7374 (setq template (buffer-substring beg end))
7375 (when (and doshift
7376 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7377 (delete-region beg end)
7378 (setq end beg)
7379 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7380 (goto-char end)
7381 (loop for n from nmin to nmax do
7382 ;; prepare clone
7383 (with-temp-buffer
7384 (insert template)
7385 (org-mode)
7386 (goto-char (point-min))
7387 (and idprop (if org-clone-delete-id
7388 (org-entry-delete nil "ID")
7389 (org-id-get-create t)))
7390 (while (re-search-forward org-property-drawer-re nil t)
7391 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7392 (goto-char (point-min))
7393 (when doshift
7394 (while (re-search-forward org-ts-regexp-both nil t)
7395 (org-timestamp-change (* n shift-n) shift-what))
7396 (unless (= n n-no-remove)
7397 (goto-char (point-min))
7398 (while (re-search-forward org-ts-regexp nil t)
7399 (save-excursion
7400 (goto-char (match-beginning 0))
7401 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7402 (delete-region (match-beginning 1) (match-end 1)))))))
7403 (setq task (buffer-string)))
7404 (insert task))
7405 (goto-char beg)))
7407 ;;; Outline Sorting
7409 (defun org-sort (with-case)
7410 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7411 Optional argument WITH-CASE means sort case-sensitively.
7412 With a double prefix argument, also remove duplicate entries."
7413 (interactive "P")
7414 (if (org-at-table-p)
7415 (org-call-with-arg 'org-table-sort-lines with-case)
7416 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7418 (defun org-sort-remove-invisible (s)
7419 (remove-text-properties 0 (length s) org-rm-props s)
7420 (while (string-match org-bracket-link-regexp s)
7421 (setq s (replace-match (if (match-end 2)
7422 (match-string 3 s)
7423 (match-string 1 s)) t t s)))
7426 (defvar org-priority-regexp) ; defined later in the file
7428 (defvar org-after-sorting-entries-or-items-hook nil
7429 "Hook that is run after a bunch of entries or items have been sorted.
7430 When children are sorted, the cursor is in the parent line when this
7431 hook gets called. When a region or a plain list is sorted, the cursor
7432 will be in the first entry of the sorted region/list.")
7434 (defun org-sort-entries-or-items
7435 (&optional with-case sorting-type getkey-func compare-func property)
7436 "Sort entries on a certain level of an outline tree, or plain list items.
7437 If there is an active region, the entries in the region are sorted.
7438 Else, if the cursor is before the first entry, sort the top-level items.
7439 Else, the children of the entry at point are sorted.
7440 If the cursor is at the first item in a plain list, the list items will be
7441 sorted.
7443 Sorting can be alphabetically, numerically, by date/time as given by
7444 a time stamp, by a property or by priority.
7446 The command prompts for the sorting type unless it has been given to the
7447 function through the SORTING-TYPE argument, which needs to be a character,
7448 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7449 precise meaning of each character:
7451 n Numerically, by converting the beginning of the entry/item to a number.
7452 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7453 t By date/time, either the first active time stamp in the entry, or, if
7454 none exist, by the first inactive one.
7455 In items, only the first line will be checked.
7456 s By the scheduled date/time.
7457 d By deadline date/time.
7458 c By creation time, which is assumed to be the first inactive time stamp
7459 at the beginning of a line.
7460 p By priority according to the cookie.
7461 r By the value of a property.
7463 Capital letters will reverse the sort order.
7465 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7466 called with point at the beginning of the record. It must return either
7467 a string or a number that should serve as the sorting key for that record.
7469 Comparing entries ignores case by default. However, with an optional argument
7470 WITH-CASE, the sorting considers case as well."
7471 (interactive "P")
7472 (let ((case-func (if with-case 'identity 'downcase))
7473 start beg end stars re re2
7474 txt what tmp plain-list-p)
7475 ;; Find beginning and end of region to sort
7476 (cond
7477 ((org-region-active-p)
7478 ;; we will sort the region
7479 (setq end (region-end)
7480 what "region")
7481 (goto-char (region-beginning))
7482 (if (not (org-on-heading-p)) (outline-next-heading))
7483 (setq start (point)))
7484 ((org-at-item-p)
7485 ;; we will sort this plain list
7486 (org-beginning-of-item-list) (setq start (point))
7487 (org-end-of-item-list)
7488 (or (bolp) (insert "\n"))
7489 (setq end (point))
7490 (goto-char start)
7491 (setq plain-list-p t
7492 what "plain list"))
7493 ((or (org-on-heading-p)
7494 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7495 ;; we will sort the children of the current headline
7496 (org-back-to-heading)
7497 (setq start (point)
7498 end (progn (org-end-of-subtree t t)
7499 (or (bolp) (insert "\n"))
7500 (org-back-over-empty-lines)
7501 (point))
7502 what "children")
7503 (goto-char start)
7504 (show-subtree)
7505 (outline-next-heading))
7507 ;; we will sort the top-level entries in this file
7508 (goto-char (point-min))
7509 (or (org-on-heading-p) (outline-next-heading))
7510 (setq start (point))
7511 (goto-char (point-max))
7512 (beginning-of-line 1)
7513 (when (looking-at ".*?\\S-")
7514 ;; File ends in a non-white line
7515 (end-of-line 1)
7516 (insert "\n"))
7517 (setq end (point-max))
7518 (setq what "top-level")
7519 (goto-char start)
7520 (show-all)))
7522 (setq beg (point))
7523 (if (>= beg end) (error "Nothing to sort"))
7525 (unless plain-list-p
7526 (looking-at "\\(\\*+\\)")
7527 (setq stars (match-string 1)
7528 re (concat "^" (regexp-quote stars) " +")
7529 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7530 txt (buffer-substring beg end))
7531 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7532 (if (and (not (equal stars "*")) (string-match re2 txt))
7533 (error "Region to sort contains a level above the first entry")))
7535 (unless sorting-type
7536 (message
7537 (if plain-list-p
7538 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7539 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7540 [t]ime [s]cheduled [d]eadline [c]reated
7541 A/N/T/S/D/C/P/O/F means reversed:")
7542 what)
7543 (setq sorting-type (read-char-exclusive))
7545 (and (= (downcase sorting-type) ?f)
7546 (setq getkey-func
7547 (org-icompleting-read "Sort using function: "
7548 obarray 'fboundp t nil nil))
7549 (setq getkey-func (intern getkey-func)))
7551 (and (= (downcase sorting-type) ?r)
7552 (setq property
7553 (org-icompleting-read "Property: "
7554 (mapcar 'list (org-buffer-property-keys t))
7555 nil t))))
7557 (message "Sorting entries...")
7559 (save-restriction
7560 (narrow-to-region start end)
7562 (let ((dcst (downcase sorting-type))
7563 (case-fold-search nil)
7564 (now (current-time)))
7565 (sort-subr
7566 (/= dcst sorting-type)
7567 ;; This function moves to the beginning character of the "record" to
7568 ;; be sorted.
7569 (if plain-list-p
7570 (lambda nil
7571 (if (org-at-item-p) t (goto-char (point-max))))
7572 (lambda nil
7573 (if (re-search-forward re nil t)
7574 (goto-char (match-beginning 0))
7575 (goto-char (point-max)))))
7576 ;; This function moves to the last character of the "record" being
7577 ;; sorted.
7578 (if plain-list-p
7579 'org-end-of-item
7580 (lambda nil
7581 (save-match-data
7582 (condition-case nil
7583 (outline-forward-same-level 1)
7584 (error
7585 (goto-char (point-max)))))))
7587 ;; This function returns the value that gets sorted against.
7588 (if plain-list-p
7589 (lambda nil
7590 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7591 (cond
7592 ((= dcst ?n)
7593 (string-to-number (buffer-substring (match-end 0)
7594 (point-at-eol))))
7595 ((= dcst ?a)
7596 (buffer-substring (match-end 0) (point-at-eol)))
7597 ((= dcst ?t)
7598 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7599 (re-search-forward org-ts-regexp-both
7600 (point-at-eol) t))
7601 (org-time-string-to-seconds (match-string 0))
7602 (org-float-time now)))
7603 ((= dcst ?f)
7604 (if getkey-func
7605 (progn
7606 (setq tmp (funcall getkey-func))
7607 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7608 tmp)
7609 (error "Invalid key function `%s'" getkey-func)))
7610 (t (error "Invalid sorting type `%c'" sorting-type)))))
7611 (lambda nil
7612 (cond
7613 ((= dcst ?n)
7614 (if (looking-at org-complex-heading-regexp)
7615 (string-to-number (match-string 4))
7616 nil))
7617 ((= dcst ?a)
7618 (if (looking-at org-complex-heading-regexp)
7619 (funcall case-func (match-string 4))
7620 nil))
7621 ((= dcst ?t)
7622 (let ((end (save-excursion (outline-next-heading) (point))))
7623 (if (or (re-search-forward org-ts-regexp end t)
7624 (re-search-forward org-ts-regexp-both end t))
7625 (org-time-string-to-seconds (match-string 0))
7626 (org-float-time now))))
7627 ((= dcst ?c)
7628 (let ((end (save-excursion (outline-next-heading) (point))))
7629 (if (re-search-forward
7630 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7631 end t)
7632 (org-time-string-to-seconds (match-string 0))
7633 (org-float-time now))))
7634 ((= dcst ?s)
7635 (let ((end (save-excursion (outline-next-heading) (point))))
7636 (if (re-search-forward org-scheduled-time-regexp end t)
7637 (org-time-string-to-seconds (match-string 1))
7638 (org-float-time now))))
7639 ((= dcst ?d)
7640 (let ((end (save-excursion (outline-next-heading) (point))))
7641 (if (re-search-forward org-deadline-time-regexp end t)
7642 (org-time-string-to-seconds (match-string 1))
7643 (org-float-time now))))
7644 ((= dcst ?p)
7645 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7646 (string-to-char (match-string 2))
7647 org-default-priority))
7648 ((= dcst ?r)
7649 (or (org-entry-get nil property) ""))
7650 ((= dcst ?o)
7651 (if (looking-at org-complex-heading-regexp)
7652 (- 9999 (length (member (match-string 2)
7653 org-todo-keywords-1)))))
7654 ((= dcst ?f)
7655 (if getkey-func
7656 (progn
7657 (setq tmp (funcall getkey-func))
7658 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7659 tmp)
7660 (error "Invalid key function `%s'" getkey-func)))
7661 (t (error "Invalid sorting type `%c'" sorting-type)))))
7663 (cond
7664 ((= dcst ?a) 'string<)
7665 ((= dcst ?f) compare-func)
7666 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7667 (t nil)))))
7668 (run-hooks 'org-after-sorting-entries-or-items-hook)
7669 (message "Sorting entries...done")))
7671 (defun org-do-sort (table what &optional with-case sorting-type)
7672 "Sort TABLE of WHAT according to SORTING-TYPE.
7673 The user will be prompted for the SORTING-TYPE if the call to this
7674 function does not specify it. WHAT is only for the prompt, to indicate
7675 what is being sorted. The sorting key will be extracted from
7676 the car of the elements of the table.
7677 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7678 (unless sorting-type
7679 (message
7680 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7681 what)
7682 (setq sorting-type (read-char-exclusive)))
7683 (let ((dcst (downcase sorting-type))
7684 extractfun comparefun)
7685 ;; Define the appropriate functions
7686 (cond
7687 ((= dcst ?n)
7688 (setq extractfun 'string-to-number
7689 comparefun (if (= dcst sorting-type) '< '>)))
7690 ((= dcst ?a)
7691 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7692 (lambda(x) (downcase (org-sort-remove-invisible x))))
7693 comparefun (if (= dcst sorting-type)
7694 'string<
7695 (lambda (a b) (and (not (string< a b))
7696 (not (string= a b)))))))
7697 ((= dcst ?t)
7698 (setq extractfun
7699 (lambda (x)
7700 (if (or (string-match org-ts-regexp x)
7701 (string-match org-ts-regexp-both x))
7702 (org-float-time
7703 (org-time-string-to-time (match-string 0 x)))
7705 comparefun (if (= dcst sorting-type) '< '>)))
7706 (t (error "Invalid sorting type `%c'" sorting-type)))
7708 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7709 table)
7710 (lambda (a b) (funcall comparefun (car a) (car b))))))
7713 ;;; The orgstruct minor mode
7715 ;; Define a minor mode which can be used in other modes in order to
7716 ;; integrate the org-mode structure editing commands.
7718 ;; This is really a hack, because the org-mode structure commands use
7719 ;; keys which normally belong to the major mode. Here is how it
7720 ;; works: The minor mode defines all the keys necessary to operate the
7721 ;; structure commands, but wraps the commands into a function which
7722 ;; tests if the cursor is currently at a headline or a plain list
7723 ;; item. If that is the case, the structure command is used,
7724 ;; temporarily setting many Org-mode variables like regular
7725 ;; expressions for filling etc. However, when any of those keys is
7726 ;; used at a different location, function uses `key-binding' to look
7727 ;; up if the key has an associated command in another currently active
7728 ;; keymap (minor modes, major mode, global), and executes that
7729 ;; command. There might be problems if any of the keys is otherwise
7730 ;; used as a prefix key.
7732 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7733 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7734 ;; addresses this by checking explicitly for both bindings.
7736 (defvar orgstruct-mode-map (make-sparse-keymap)
7737 "Keymap for the minor `orgstruct-mode'.")
7739 (defvar org-local-vars nil
7740 "List of local variables, for use by `orgstruct-mode'")
7742 ;;;###autoload
7743 (define-minor-mode orgstruct-mode
7744 "Toggle the minor mode `orgstruct-mode'.
7745 This mode is for using Org-mode structure commands in other
7746 modes. The following keys behave as if Org-mode were active, if
7747 the cursor is on a headline, or on a plain list item (both as
7748 defined by Org-mode).
7750 M-up Move entry/item up
7751 M-down Move entry/item down
7752 M-left Promote
7753 M-right Demote
7754 M-S-up Move entry/item up
7755 M-S-down Move entry/item down
7756 M-S-left Promote subtree
7757 M-S-right Demote subtree
7758 M-q Fill paragraph and items like in Org-mode
7759 C-c ^ Sort entries
7760 C-c - Cycle list bullet
7761 TAB Cycle item visibility
7762 M-RET Insert new heading/item
7763 S-M-RET Insert new TODO heading / Checkbox item
7764 C-c C-c Set tags / toggle checkbox"
7765 nil " OrgStruct" nil
7766 (org-load-modules-maybe)
7767 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7769 ;;;###autoload
7770 (defun turn-on-orgstruct ()
7771 "Unconditionally turn on `orgstruct-mode'."
7772 (orgstruct-mode 1))
7774 (defun orgstruct++-mode (&optional arg)
7775 "Toggle `orgstruct-mode', the enhanced version of it.
7776 In addition to setting orgstruct-mode, this also exports all indentation
7777 and autofilling variables from org-mode into the buffer. It will also
7778 recognize item context in multiline items.
7779 Note that turning off orgstruct-mode will *not* remove the
7780 indentation/paragraph settings. This can only be done by refreshing the
7781 major mode, for example with \\[normal-mode]."
7782 (interactive "P")
7783 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7784 (if (< arg 1)
7785 (orgstruct-mode -1)
7786 (orgstruct-mode 1)
7787 (let (var val)
7788 (mapc
7789 (lambda (x)
7790 (when (string-match
7791 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7792 (symbol-name (car x)))
7793 (setq var (car x) val (nth 1 x))
7794 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7795 org-local-vars)
7796 (org-set-local 'orgstruct-is-++ t))))
7798 (defvar orgstruct-is-++ nil
7799 "Is orgstruct-mode in ++ version in the current-buffer?")
7800 (make-variable-buffer-local 'orgstruct-is-++)
7802 ;;;###autoload
7803 (defun turn-on-orgstruct++ ()
7804 "Unconditionally turn on `orgstruct++-mode'."
7805 (orgstruct++-mode 1))
7807 (defun orgstruct-error ()
7808 "Error when there is no default binding for a structure key."
7809 (interactive)
7810 (error "This key has no function outside structure elements"))
7812 (defun orgstruct-setup ()
7813 "Setup orgstruct keymaps."
7814 (let ((nfunc 0)
7815 (bindings
7816 (list
7817 '([(meta up)] org-metaup)
7818 '([(meta down)] org-metadown)
7819 '([(meta left)] org-metaleft)
7820 '([(meta right)] org-metaright)
7821 '([(meta shift up)] org-shiftmetaup)
7822 '([(meta shift down)] org-shiftmetadown)
7823 '([(meta shift left)] org-shiftmetaleft)
7824 '([(meta shift right)] org-shiftmetaright)
7825 '([?\e (up)] org-metaup)
7826 '([?\e (down)] org-metadown)
7827 '([?\e (left)] org-metaleft)
7828 '([?\e (right)] org-metaright)
7829 '([?\e (shift up)] org-shiftmetaup)
7830 '([?\e (shift down)] org-shiftmetadown)
7831 '([?\e (shift left)] org-shiftmetaleft)
7832 '([?\e (shift right)] org-shiftmetaright)
7833 '([(shift up)] org-shiftup)
7834 '([(shift down)] org-shiftdown)
7835 '([(shift left)] org-shiftleft)
7836 '([(shift right)] org-shiftright)
7837 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7838 '("\M-q" fill-paragraph)
7839 '("\C-c^" org-sort)
7840 '("\C-c-" org-cycle-list-bullet)))
7841 elt key fun cmd)
7842 (while (setq elt (pop bindings))
7843 (setq nfunc (1+ nfunc))
7844 (setq key (org-key (car elt))
7845 fun (nth 1 elt)
7846 cmd (orgstruct-make-binding fun nfunc key))
7847 (org-defkey orgstruct-mode-map key cmd))
7849 ;; Special treatment needed for TAB and RET
7850 (org-defkey orgstruct-mode-map [(tab)]
7851 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7852 (org-defkey orgstruct-mode-map "\C-i"
7853 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7855 (org-defkey orgstruct-mode-map "\M-\C-m"
7856 (orgstruct-make-binding 'org-insert-heading 105
7857 "\M-\C-m" [(meta return)]))
7858 (org-defkey orgstruct-mode-map [(meta return)]
7859 (orgstruct-make-binding 'org-insert-heading 106
7860 [(meta return)] "\M-\C-m"))
7862 (org-defkey orgstruct-mode-map [(shift meta return)]
7863 (orgstruct-make-binding 'org-insert-todo-heading 107
7864 [(meta return)] "\M-\C-m"))
7866 (org-defkey orgstruct-mode-map "\e\C-m"
7867 (orgstruct-make-binding 'org-insert-heading 108
7868 "\e\C-m" [?\e (return)]))
7869 (org-defkey orgstruct-mode-map [?\e (return)]
7870 (orgstruct-make-binding 'org-insert-heading 109
7871 [?\e (return)] "\e\C-m"))
7872 (org-defkey orgstruct-mode-map [?\e (shift return)]
7873 (orgstruct-make-binding 'org-insert-todo-heading 110
7874 [?\e (return)] "\e\C-m"))
7876 (unless org-local-vars
7877 (setq org-local-vars (org-get-local-variables)))
7881 (defun orgstruct-make-binding (fun n &rest keys)
7882 "Create a function for binding in the structure minor mode.
7883 FUN is the command to call inside a table. N is used to create a unique
7884 command name. KEYS are keys that should be checked in for a command
7885 to execute outside of tables."
7886 (eval
7887 (list 'defun
7888 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7889 '(arg)
7890 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7891 "Outside of structure, run the binding of `"
7892 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7893 "'.")
7894 '(interactive "p")
7895 (list 'if
7896 `(org-context-p 'headline 'item
7897 (and orgstruct-is-++
7898 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7899 'item-body))
7900 (list 'org-run-like-in-org-mode (list 'quote fun))
7901 (list 'let '(orgstruct-mode)
7902 (list 'call-interactively
7903 (append '(or)
7904 (mapcar (lambda (k)
7905 (list 'key-binding k))
7906 keys)
7907 '('orgstruct-error))))))))
7909 (defun org-context-p (&rest contexts)
7910 "Check if local context is any of CONTEXTS.
7911 Possible values in the list of contexts are `table', `headline', and `item'."
7912 (let ((pos (point)))
7913 (goto-char (point-at-bol))
7914 (prog1 (or (and (memq 'table contexts)
7915 (looking-at "[ \t]*|"))
7916 (and (memq 'headline contexts)
7917 ;;????????? (looking-at "\\*+"))
7918 (looking-at outline-regexp))
7919 (and (memq 'item contexts)
7920 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7921 (and (memq 'item-body contexts)
7922 (org-in-item-p)))
7923 (goto-char pos))))
7925 (defun org-get-local-variables ()
7926 "Return a list of all local variables in an org-mode buffer."
7927 (let (varlist)
7928 (with-current-buffer (get-buffer-create "*Org tmp*")
7929 (erase-buffer)
7930 (org-mode)
7931 (setq varlist (buffer-local-variables)))
7932 (kill-buffer "*Org tmp*")
7933 (delq nil
7934 (mapcar
7935 (lambda (x)
7936 (setq x
7937 (if (symbolp x)
7938 (list x)
7939 (list (car x) (list 'quote (cdr x)))))
7940 (if (string-match
7941 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7942 (symbol-name (car x)))
7943 x nil))
7944 varlist))))
7946 ;;;###autoload
7947 (defun org-run-like-in-org-mode (cmd)
7948 "Run a command, pretending that the current buffer is in Org-mode.
7949 This will temporarily bind local variables that are typically bound in
7950 Org-mode to the values they have in Org-mode, and then interactively
7951 call CMD."
7952 (org-load-modules-maybe)
7953 (unless org-local-vars
7954 (setq org-local-vars (org-get-local-variables)))
7955 (eval (list 'let org-local-vars
7956 (list 'call-interactively (list 'quote cmd)))))
7958 ;;;; Archiving
7960 (defun org-get-category (&optional pos)
7961 "Get the category applying to position POS."
7962 (get-text-property (or pos (point)) 'org-category))
7964 (defun org-refresh-category-properties ()
7965 "Refresh category text properties in the buffer."
7966 (let ((def-cat (cond
7967 ((null org-category)
7968 (if buffer-file-name
7969 (file-name-sans-extension
7970 (file-name-nondirectory buffer-file-name))
7971 "???"))
7972 ((symbolp org-category) (symbol-name org-category))
7973 (t org-category)))
7974 beg end cat pos optionp)
7975 (org-unmodified
7976 (save-excursion
7977 (save-restriction
7978 (widen)
7979 (goto-char (point-min))
7980 (put-text-property (point) (point-max) 'org-category def-cat)
7981 (while (re-search-forward
7982 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7983 (setq pos (match-end 0)
7984 optionp (equal (char-after (match-beginning 0)) ?#)
7985 cat (org-trim (match-string 2)))
7986 (if optionp
7987 (setq beg (point-at-bol) end (point-max))
7988 (org-back-to-heading t)
7989 (setq beg (point) end (org-end-of-subtree t t)))
7990 (put-text-property beg end 'org-category cat)
7991 (goto-char pos)))))))
7994 ;;;; Link Stuff
7996 ;;; Link abbreviations
7998 (defun org-link-expand-abbrev (link)
7999 "Apply replacements as defined in `org-link-abbrev-alist."
8000 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
8001 (let* ((key (match-string 1 link))
8002 (as (or (assoc key org-link-abbrev-alist-local)
8003 (assoc key org-link-abbrev-alist)))
8004 (tag (and (match-end 2) (match-string 3 link)))
8005 rpl)
8006 (if (not as)
8007 link
8008 (setq rpl (cdr as))
8009 (cond
8010 ((symbolp rpl) (funcall rpl tag))
8011 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8012 ((string-match "%h" rpl)
8013 (replace-match (url-hexify-string (or tag "")) t t rpl))
8014 (t (concat rpl tag)))))
8015 link))
8017 ;;; Storing and inserting links
8019 (defvar org-insert-link-history nil
8020 "Minibuffer history for links inserted with `org-insert-link'.")
8022 (defvar org-stored-links nil
8023 "Contains the links stored with `org-store-link'.")
8025 (defvar org-store-link-plist nil
8026 "Plist with info about the most recently link created with `org-store-link'.")
8028 (defvar org-link-protocols nil
8029 "Link protocols added to Org-mode using `org-add-link-type'.")
8031 (defvar org-store-link-functions nil
8032 "List of functions that are called to create and store a link.
8033 Each function will be called in turn until one returns a non-nil
8034 value. Each function should check if it is responsible for creating
8035 this link (for example by looking at the major mode).
8036 If not, it must exit and return nil.
8037 If yes, it should return a non-nil value after a calling
8038 `org-store-link-props' with a list of properties and values.
8039 Special properties are:
8041 :type The link prefix. like \"http\". This must be given.
8042 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8043 This is obligatory as well.
8044 :description Optional default description for the second pair
8045 of brackets in an Org-mode link. The user can still change
8046 this when inserting this link into an Org-mode buffer.
8048 In addition to these, any additional properties can be specified
8049 and then used in remember templates.")
8051 (defun org-add-link-type (type &optional follow export)
8052 "Add TYPE to the list of `org-link-types'.
8053 Re-compute all regular expressions depending on `org-link-types'
8055 FOLLOW and EXPORT are two functions.
8057 FOLLOW should take the link path as the single argument and do whatever
8058 is necessary to follow the link, for example find a file or display
8059 a mail message.
8061 EXPORT should format the link path for export to one of the export formats.
8062 It should be a function accepting three arguments:
8064 path the path of the link, the text after the prefix (like \"http:\")
8065 desc the description of the link, if any, nil if there was no description
8066 format the export format, a symbol like `html' or `latex'.
8068 The function may use the FORMAT information to return different values
8069 depending on the format. The return value will be put literally into
8070 the exported file.
8071 Org-mode has a built-in default for exporting links. If you are happy with
8072 this default, there is no need to define an export function for the link
8073 type. For a simple example of an export function, see `org-bbdb.el'."
8074 (add-to-list 'org-link-types type t)
8075 (org-make-link-regexps)
8076 (if (assoc type org-link-protocols)
8077 (setcdr (assoc type org-link-protocols) (list follow export))
8078 (push (list type follow export) org-link-protocols)))
8080 (defvar org-agenda-buffer-name)
8082 ;;;###autoload
8083 (defun org-store-link (arg)
8084 "\\<org-mode-map>Store an org-link to the current location.
8085 This link is added to `org-stored-links' and can later be inserted
8086 into an org-buffer with \\[org-insert-link].
8088 For some link types, a prefix arg is interpreted:
8089 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8090 For file links, arg negates `org-context-in-file-links'."
8091 (interactive "P")
8092 (org-load-modules-maybe)
8093 (setq org-store-link-plist nil) ; reset
8094 (let ((outline-regexp (org-get-limited-outline-regexp))
8095 link cpltxt desc description search txt custom-id)
8096 (cond
8098 ((run-hook-with-args-until-success 'org-store-link-functions)
8099 (setq link (plist-get org-store-link-plist :link)
8100 desc (or (plist-get org-store-link-plist :description) link)))
8102 ((equal (buffer-name) "*Org Edit Src Example*")
8103 (let (label gc)
8104 (while (or (not label)
8105 (save-excursion
8106 (save-restriction
8107 (widen)
8108 (goto-char (point-min))
8109 (re-search-forward
8110 (regexp-quote (format org-coderef-label-format label))
8111 nil t))))
8112 (when label (message "Label exists already") (sit-for 2))
8113 (setq label (read-string "Code line label: " label)))
8114 (end-of-line 1)
8115 (setq link (format org-coderef-label-format label))
8116 (setq gc (- 79 (length link)))
8117 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8118 (insert link)
8119 (setq link (concat "(" label ")") desc nil)))
8121 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8122 ;; We are in the agenda, link to referenced location
8123 (let ((m (or (get-text-property (point) 'org-hd-marker)
8124 (get-text-property (point) 'org-marker))))
8125 (when m
8126 (org-with-point-at m
8127 (if (interactive-p)
8128 (call-interactively 'org-store-link)
8129 (org-store-link nil))))))
8131 ((eq major-mode 'calendar-mode)
8132 (let ((cd (calendar-cursor-to-date)))
8133 (setq link
8134 (format-time-string
8135 (car org-time-stamp-formats)
8136 (apply 'encode-time
8137 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8138 nil nil nil))))
8139 (org-store-link-props :type "calendar" :date cd)))
8141 ((eq major-mode 'w3-mode)
8142 (setq cpltxt (if (and (buffer-name)
8143 (not (string-match "Untitled" (buffer-name))))
8144 (buffer-name)
8145 (url-view-url t))
8146 link (org-make-link (url-view-url t)))
8147 (org-store-link-props :type "w3" :url (url-view-url t)))
8149 ((eq major-mode 'w3m-mode)
8150 (setq cpltxt (or w3m-current-title w3m-current-url)
8151 link (org-make-link w3m-current-url))
8152 (org-store-link-props :type "w3m" :url (url-view-url t)))
8154 ((setq search (run-hook-with-args-until-success
8155 'org-create-file-search-functions))
8156 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8157 "::" search))
8158 (setq cpltxt (or description link)))
8160 ((eq major-mode 'image-mode)
8161 (setq cpltxt (concat "file:"
8162 (abbreviate-file-name buffer-file-name))
8163 link (org-make-link cpltxt))
8164 (org-store-link-props :type "image" :file buffer-file-name))
8166 ((eq major-mode 'dired-mode)
8167 ;; link to the file in the current line
8168 (let ((file (dired-get-filename nil t)))
8169 (setq file (if file
8170 (abbreviate-file-name
8171 (expand-file-name (dired-get-filename nil t)))
8172 ;; otherwise, no file so use current directory.
8173 default-directory))
8174 (setq cpltxt (concat "file:" file)
8175 link (org-make-link cpltxt))))
8177 ((and buffer-file-name (org-mode-p))
8178 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8179 (cond
8180 ((org-in-regexp "<<\\(.*?\\)>>")
8181 (setq cpltxt
8182 (concat "file:"
8183 (abbreviate-file-name buffer-file-name)
8184 "::" (match-string 1))
8185 link (org-make-link cpltxt)))
8186 ((and (featurep 'org-id)
8187 (or (eq org-link-to-org-use-id t)
8188 (and (eq org-link-to-org-use-id 'create-if-interactive)
8189 (interactive-p))
8190 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8191 (interactive-p)
8192 (not custom-id))
8193 (and org-link-to-org-use-id
8194 (condition-case nil
8195 (org-entry-get nil "ID")
8196 (error nil)))))
8197 ;; We can make a link using the ID.
8198 (setq link (condition-case nil
8199 (prog1 (org-id-store-link)
8200 (setq desc (plist-get org-store-link-plist
8201 :description)))
8202 (error
8203 ;; probably before first headline, link to file only
8204 (concat "file:"
8205 (abbreviate-file-name buffer-file-name))))))
8207 ;; Just link to current headline
8208 (setq cpltxt (concat "file:"
8209 (abbreviate-file-name buffer-file-name)))
8210 ;; Add a context search string
8211 (when (org-xor org-context-in-file-links arg)
8212 (setq txt (cond
8213 ((org-on-heading-p) nil)
8214 ((org-region-active-p)
8215 (buffer-substring (region-beginning) (region-end)))
8216 (t nil)))
8217 (when (or (null txt) (string-match "\\S-" txt))
8218 (setq cpltxt
8219 (concat cpltxt "::"
8220 (condition-case nil
8221 (org-make-org-heading-search-string txt)
8222 (error "")))
8223 desc (or (nth 4 (ignore-errors
8224 (org-heading-components))) "NONE"))))
8225 (if (string-match "::\\'" cpltxt)
8226 (setq cpltxt (substring cpltxt 0 -2)))
8227 (setq link (org-make-link cpltxt)))))
8229 ((buffer-file-name (buffer-base-buffer))
8230 ;; Just link to this file here.
8231 (setq cpltxt (concat "file:"
8232 (abbreviate-file-name
8233 (buffer-file-name (buffer-base-buffer)))))
8234 ;; Add a context string
8235 (when (org-xor org-context-in-file-links arg)
8236 (setq txt (if (org-region-active-p)
8237 (buffer-substring (region-beginning) (region-end))
8238 (buffer-substring (point-at-bol) (point-at-eol))))
8239 ;; Only use search option if there is some text.
8240 (when (string-match "\\S-" txt)
8241 (setq cpltxt
8242 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8243 desc "NONE")))
8244 (setq link (org-make-link cpltxt)))
8246 ((interactive-p)
8247 (error "Cannot link to a buffer which is not visiting a file"))
8249 (t (setq link nil)))
8251 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8252 (setq link (or link cpltxt)
8253 desc (or desc cpltxt))
8254 (if (equal desc "NONE") (setq desc nil))
8256 (if (and (or (interactive-p) executing-kbd-macro) link)
8257 (progn
8258 (setq org-stored-links
8259 (cons (list link desc) org-stored-links))
8260 (message "Stored: %s" (or desc link))
8261 (when custom-id
8262 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8263 "::#" custom-id))
8264 (setq org-stored-links
8265 (cons (list link desc) org-stored-links))))
8266 (and link (org-make-link-string link desc)))))
8268 (defun org-store-link-props (&rest plist)
8269 "Store link properties, extract names and addresses."
8270 (let (x adr)
8271 (when (setq x (plist-get plist :from))
8272 (setq adr (mail-extract-address-components x))
8273 (setq plist (plist-put plist :fromname (car adr)))
8274 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8275 (when (setq x (plist-get plist :to))
8276 (setq adr (mail-extract-address-components x))
8277 (setq plist (plist-put plist :toname (car adr)))
8278 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8279 (let ((from (plist-get plist :from))
8280 (to (plist-get plist :to)))
8281 (when (and from to org-from-is-user-regexp)
8282 (setq plist
8283 (plist-put plist :fromto
8284 (if (string-match org-from-is-user-regexp from)
8285 (concat "to %t")
8286 (concat "from %f"))))))
8287 (setq org-store-link-plist plist))
8289 (defun org-add-link-props (&rest plist)
8290 "Add these properties to the link property list."
8291 (let (key value)
8292 (while plist
8293 (setq key (pop plist) value (pop plist))
8294 (setq org-store-link-plist
8295 (plist-put org-store-link-plist key value)))))
8297 (defun org-email-link-description (&optional fmt)
8298 "Return the description part of an email link.
8299 This takes information from `org-store-link-plist' and formats it
8300 according to FMT (default from `org-email-link-description-format')."
8301 (setq fmt (or fmt org-email-link-description-format))
8302 (let* ((p org-store-link-plist)
8303 (to (plist-get p :toaddress))
8304 (from (plist-get p :fromaddress))
8305 (table
8306 (list
8307 (cons "%c" (plist-get p :fromto))
8308 (cons "%F" (plist-get p :from))
8309 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8310 (cons "%T" (plist-get p :to))
8311 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8312 (cons "%s" (plist-get p :subject))
8313 (cons "%m" (plist-get p :message-id)))))
8314 (when (string-match "%c" fmt)
8315 ;; Check if the user wrote this message
8316 (if (and org-from-is-user-regexp from to
8317 (save-match-data (string-match org-from-is-user-regexp from)))
8318 (setq fmt (replace-match "to %t" t t fmt))
8319 (setq fmt (replace-match "from %f" t t fmt))))
8320 (org-replace-escapes fmt table)))
8322 (defun org-make-org-heading-search-string (&optional string heading)
8323 "Make search string for STRING or current headline."
8324 (interactive)
8325 (let ((s (or string (org-get-heading))))
8326 (unless (and string (not heading))
8327 ;; We are using a headline, clean up garbage in there.
8328 (if (string-match org-todo-regexp s)
8329 (setq s (replace-match "" t t s)))
8330 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8331 (setq s (replace-match "" t t s)))
8332 (setq s (org-trim s))
8333 (if (string-match (concat "^\\(" org-quote-string "\\|"
8334 org-comment-string "\\)") s)
8335 (setq s (replace-match "" t t s)))
8336 (while (string-match org-ts-regexp s)
8337 (setq s (replace-match "" t t s))))
8338 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8339 (setq s (replace-match " " t t s)))
8340 (or string (setq s (concat "*" s))) ; Add * for headlines
8341 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8343 (defun org-make-link (&rest strings)
8344 "Concatenate STRINGS."
8345 (apply 'concat strings))
8347 (defun org-make-link-string (link &optional description)
8348 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8349 (unless (string-match "\\S-" link)
8350 (error "Empty link"))
8351 (when (and description
8352 (stringp description)
8353 (not (string-match "\\S-" description)))
8354 (setq description nil))
8355 (when (stringp description)
8356 ;; Remove brackets from the description, they are fatal.
8357 (while (string-match "\\[" description)
8358 (setq description (replace-match "{" t t description)))
8359 (while (string-match "\\]" description)
8360 (setq description (replace-match "}" t t description))))
8361 (when (equal (org-link-escape link) description)
8362 ;; No description needed, it is identical
8363 (setq description nil))
8364 (when (and (not description)
8365 (not (equal link (org-link-escape link))))
8366 (setq description (org-extract-attributes link)))
8367 (concat "[[" (org-link-escape link) "]"
8368 (if description (concat "[" description "]") "")
8369 "]"))
8371 (defconst org-link-escape-chars
8372 '((?\ . "%20")
8373 (?\[ . "%5B")
8374 (?\] . "%5D")
8375 (?\340 . "%E0") ; `a
8376 (?\342 . "%E2") ; ^a
8377 (?\347 . "%E7") ; ,c
8378 (?\350 . "%E8") ; `e
8379 (?\351 . "%E9") ; 'e
8380 (?\352 . "%EA") ; ^e
8381 (?\356 . "%EE") ; ^i
8382 (?\364 . "%F4") ; ^o
8383 (?\371 . "%F9") ; `u
8384 (?\373 . "%FB") ; ^u
8385 (?\; . "%3B")
8386 ;; (?? . "%3F")
8387 (?= . "%3D")
8388 (?+ . "%2B")
8390 "Association list of escapes for some characters problematic in links.
8391 This is the list that is used for internal purposes.")
8393 (defvar org-url-encoding-use-url-hexify nil)
8395 (defconst org-link-escape-chars-browser
8396 '((?\ . "%20")) ; 32 for the SPC char
8397 "Association list of escapes for some characters problematic in links.
8398 This is the list that is used before handing over to the browser.")
8400 (defun org-link-escape (text &optional table)
8401 "Escape characters in TEXT that are problematic for links."
8402 (if (and org-url-encoding-use-url-hexify (not table))
8403 (url-hexify-string text)
8404 (setq table (or table org-link-escape-chars))
8405 (when text
8406 (let ((re (mapconcat (lambda (x) (regexp-quote
8407 (char-to-string (car x))))
8408 table "\\|")))
8409 (while (string-match re text)
8410 (setq text
8411 (replace-match
8412 (cdr (assoc (string-to-char (match-string 0 text))
8413 table))
8414 t t text)))
8415 text))))
8417 (defun org-link-unescape (text &optional table)
8418 "Reverse the action of `org-link-escape'."
8419 (if (and org-url-encoding-use-url-hexify (not table))
8420 (url-unhex-string text)
8421 (setq table (or table org-link-escape-chars))
8422 (when text
8423 (let ((case-fold-search t)
8424 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8425 table "\\|")))
8426 (while (string-match re text)
8427 (setq text
8428 (replace-match
8429 (char-to-string (car (rassoc (upcase (match-string 0 text))
8430 table)))
8431 t t text)))
8432 text))))
8434 (defun org-xor (a b)
8435 "Exclusive or."
8436 (if a (not b) b))
8438 (defun org-fixup-message-id-for-http (s)
8439 "Replace special characters in a message id, so it can be used in an http query."
8440 (when (string-match "%" s)
8441 (setq s (mapconcat (lambda (c)
8442 (if (eq c ?%)
8443 "%25"
8444 (char-to-string c)))
8445 s "")))
8446 (while (string-match "<" s)
8447 (setq s (replace-match "%3C" t t s)))
8448 (while (string-match ">" s)
8449 (setq s (replace-match "%3E" t t s)))
8450 (while (string-match "@" s)
8451 (setq s (replace-match "%40" t t s)))
8454 ;;;###autoload
8455 (defun org-insert-link-global ()
8456 "Insert a link like Org-mode does.
8457 This command can be called in any mode to insert a link in Org-mode syntax."
8458 (interactive)
8459 (org-load-modules-maybe)
8460 (org-run-like-in-org-mode 'org-insert-link))
8462 (defun org-insert-link (&optional complete-file link-location)
8463 "Insert a link. At the prompt, enter the link.
8465 Completion can be used to insert any of the link protocol prefixes like
8466 http or ftp in use.
8468 The history can be used to select a link previously stored with
8469 `org-store-link'. When the empty string is entered (i.e. if you just
8470 press RET at the prompt), the link defaults to the most recently
8471 stored link. As SPC triggers completion in the minibuffer, you need to
8472 use M-SPC or C-q SPC to force the insertion of a space character.
8474 You will also be prompted for a description, and if one is given, it will
8475 be displayed in the buffer instead of the link.
8477 If there is already a link at point, this command will allow you to edit link
8478 and description parts.
8480 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8481 be selected using completion. The path to the file will be relative to the
8482 current directory if the file is in the current directory or a subdirectory.
8483 Otherwise, the link will be the absolute path as completed in the minibuffer
8484 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8485 option `org-link-file-path-type'.
8487 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8488 the current directory or below.
8490 With three \\[universal-argument] prefixes, negate the meaning of
8491 `org-keep-stored-link-after-insertion'.
8493 If `org-make-link-description-function' is non-nil, this function will be
8494 called with the link target, and the result will be the default
8495 link description.
8497 If the LINK-LOCATION parameter is non-nil, this value will be
8498 used as the link location instead of reading one interactively."
8499 (interactive "P")
8500 (let* ((wcf (current-window-configuration))
8501 (region (if (org-region-active-p)
8502 (buffer-substring (region-beginning) (region-end))))
8503 (remove (and region (list (region-beginning) (region-end))))
8504 (desc region)
8505 tmphist ; byte-compile incorrectly complains about this
8506 (link link-location)
8507 entry file all-prefixes)
8508 (cond
8509 (link-location) ; specified by arg, just use it.
8510 ((org-in-regexp org-bracket-link-regexp 1)
8511 ;; We do have a link at point, and we are going to edit it.
8512 (setq remove (list (match-beginning 0) (match-end 0)))
8513 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8514 (setq link (read-string "Link: "
8515 (org-link-unescape
8516 (org-match-string-no-properties 1)))))
8517 ((or (org-in-regexp org-angle-link-re)
8518 (org-in-regexp org-plain-link-re))
8519 ;; Convert to bracket link
8520 (setq remove (list (match-beginning 0) (match-end 0))
8521 link (read-string "Link: "
8522 (org-remove-angle-brackets (match-string 0)))))
8523 ((member complete-file '((4) (16)))
8524 ;; Completing read for file names.
8525 (setq link (org-file-complete-link complete-file)))
8527 ;; Read link, with completion for stored links.
8528 (with-output-to-temp-buffer "*Org Links*"
8529 (princ "Insert a link.
8530 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8531 (when org-stored-links
8532 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8533 (princ (mapconcat
8534 (lambda (x)
8535 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8536 (reverse org-stored-links) "\n"))))
8537 (let ((cw (selected-window)))
8538 (select-window (get-buffer-window "*Org Links*" 'visible))
8539 (setq truncate-lines t)
8540 (unless (pos-visible-in-window-p (point-max))
8541 (org-fit-window-to-buffer))
8542 (and (window-live-p cw) (select-window cw)))
8543 ;; Fake a link history, containing the stored links.
8544 (setq tmphist (append (mapcar 'car org-stored-links)
8545 org-insert-link-history))
8546 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8547 (mapcar 'car org-link-abbrev-alist)
8548 org-link-types))
8549 (unwind-protect
8550 (progn
8551 (setq link
8552 (let ((org-completion-use-ido nil)
8553 (org-completion-use-iswitchb nil))
8554 (org-completing-read
8555 "Link: "
8556 (append
8557 (mapcar (lambda (x) (list (concat x ":")))
8558 all-prefixes)
8559 (mapcar 'car org-stored-links))
8560 nil nil nil
8561 'tmphist
8562 (car (car org-stored-links)))))
8563 (if (not (string-match "\\S-" link))
8564 (error "No link selected"))
8565 (if (or (member link all-prefixes)
8566 (and (equal ":" (substring link -1))
8567 (member (substring link 0 -1) all-prefixes)
8568 (setq link (substring link 0 -1))))
8569 (setq link (org-link-try-special-completion link))))
8570 (set-window-configuration wcf)
8571 (kill-buffer "*Org Links*"))
8572 (setq entry (assoc link org-stored-links))
8573 (or entry (push link org-insert-link-history))
8574 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8575 (not org-keep-stored-link-after-insertion))
8576 (setq org-stored-links (delq (assoc link org-stored-links)
8577 org-stored-links)))
8578 (setq desc (or desc (nth 1 entry)))))
8580 (if (string-match org-plain-link-re link)
8581 ;; URL-like link, normalize the use of angular brackets.
8582 (setq link (org-make-link (org-remove-angle-brackets link))))
8584 ;; Check if we are linking to the current file with a search option
8585 ;; If yes, simplify the link by using only the search option.
8586 (when (and buffer-file-name
8587 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8588 (let* ((path (match-string 1 link))
8589 (case-fold-search nil)
8590 (search (match-string 2 link)))
8591 (save-match-data
8592 (if (equal (file-truename buffer-file-name) (file-truename path))
8593 ;; We are linking to this same file, with a search option
8594 (setq link search)))))
8596 ;; Check if we can/should use a relative path. If yes, simplify the link
8597 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8598 (let* ((type (match-string 1 link))
8599 (path (match-string 2 link))
8600 (origpath path)
8601 (case-fold-search nil))
8602 (cond
8603 ((or (eq org-link-file-path-type 'absolute)
8604 (equal complete-file '(16)))
8605 (setq path (abbreviate-file-name (expand-file-name path))))
8606 ((eq org-link-file-path-type 'noabbrev)
8607 (setq path (expand-file-name path)))
8608 ((eq org-link-file-path-type 'relative)
8609 (setq path (file-relative-name path)))
8611 (save-match-data
8612 (if (string-match (concat "^" (regexp-quote
8613 (file-name-as-directory
8614 (expand-file-name "."))))
8615 (expand-file-name path))
8616 ;; We are linking a file with relative path name.
8617 (setq path (substring (expand-file-name path)
8618 (match-end 0)))
8619 (setq path (abbreviate-file-name (expand-file-name path)))))))
8620 (setq link (concat type path))
8621 (if (equal desc origpath)
8622 (setq desc path))))
8624 (if org-make-link-description-function
8625 (setq desc (funcall org-make-link-description-function link desc)))
8627 (setq desc (read-string "Description: " desc))
8628 (unless (string-match "\\S-" desc) (setq desc nil))
8629 (if remove (apply 'delete-region remove))
8630 (insert (org-make-link-string link desc))))
8632 (defun org-link-try-special-completion (type)
8633 "If there is completion support for link type TYPE, offer it."
8634 (let ((fun (intern (concat "org-" type "-complete-link"))))
8635 (if (functionp fun)
8636 (funcall fun)
8637 (read-string "Link (no completion support): " (concat type ":")))))
8639 (defun org-file-complete-link (&optional arg)
8640 "Create a file link using completion."
8641 (let (file link)
8642 (setq file (read-file-name "File: "))
8643 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8644 (pwd1 (file-name-as-directory (abbreviate-file-name
8645 (expand-file-name ".")))))
8646 (cond
8647 ((equal arg '(16))
8648 (setq link (org-make-link
8649 "file:"
8650 (abbreviate-file-name (expand-file-name file)))))
8651 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8652 (setq link (org-make-link "file:" (match-string 1 file))))
8653 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8654 (expand-file-name file))
8655 (setq link (org-make-link
8656 "file:" (match-string 1 (expand-file-name file)))))
8657 (t (setq link (org-make-link "file:" file)))))
8658 link))
8660 (defun org-completing-read (&rest args)
8661 "Completing-read with SPACE being a normal character."
8662 (let ((minibuffer-local-completion-map
8663 (copy-keymap minibuffer-local-completion-map)))
8664 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8665 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8666 (apply 'org-icompleting-read args)))
8668 (defun org-completing-read-no-i (&rest args)
8669 (let (org-completion-use-ido org-completion-use-iswitchb)
8670 (apply 'org-completing-read args)))
8672 (defun org-iswitchb-completing-read (prompt choices &rest args)
8673 "Use iswitch as a completing-read replacement to choose from choices.
8674 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8675 from."
8676 (let* ((iswitchb-use-virtual-buffers nil)
8677 (iswitchb-make-buflist-hook
8678 (lambda ()
8679 (setq iswitchb-temp-buflist choices))))
8680 (iswitchb-read-buffer prompt)))
8682 (defun org-icompleting-read (&rest args)
8683 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8684 (org-without-partial-completion
8685 (if (and org-completion-use-ido
8686 (fboundp 'ido-completing-read)
8687 (boundp 'ido-mode) ido-mode
8688 (listp (second args)))
8689 (let ((ido-enter-matching-directory nil))
8690 (apply 'ido-completing-read (concat (car args))
8691 (if (consp (car (nth 1 args)))
8692 (mapcar (lambda (x) (car x)) (nth 1 args))
8693 (nth 1 args))
8694 (cddr args)))
8695 (if (and org-completion-use-iswitchb
8696 (boundp 'iswitchb-mode) iswitchb-mode
8697 (listp (second args)))
8698 (apply 'org-iswitchb-completing-read (concat (car args))
8699 (if (consp (car (nth 1 args)))
8700 (mapcar (lambda (x) (car x)) (nth 1 args))
8701 (nth 1 args))
8702 (cddr args))
8703 (apply 'completing-read args)))))
8705 (defun org-extract-attributes (s)
8706 "Extract the attributes cookie from a string and set as text property."
8707 (let (a attr (start 0) key value)
8708 (save-match-data
8709 (when (string-match "{{\\([^}]+\\)}}$" s)
8710 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8711 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8712 (setq key (match-string 1 a) value (match-string 2 a)
8713 start (match-end 0)
8714 attr (plist-put attr (intern key) value))))
8715 (org-add-props s nil 'org-attr attr))
8718 (defun org-extract-attributes-from-string (tag)
8719 (let (key value attr)
8720 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8721 (setq key (match-string 1 tag) value (match-string 2 tag)
8722 tag (replace-match "" t t tag)
8723 attr (plist-put attr (intern key) value)))
8724 (cons tag attr)))
8726 (defun org-attributes-to-string (plist)
8727 "Format a property list into an HTML attribute list."
8728 (let ((s "") key value)
8729 (while plist
8730 (setq key (pop plist) value (pop plist))
8731 (and value
8732 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8735 ;;; Opening/following a link
8737 (defvar org-link-search-failed nil)
8739 (defvar org-open-link-functions nil
8740 "Hook for functions finding a plain text link.
8741 These functions must take a single argument, the link content.
8742 They will be called for links that look like [[link text][description]]
8743 when LINK TEXT does not have a protocol like \"http:\" and does not look
8744 like a filename (e.g. \"./blue.png\").
8746 These functions will be called *before* Org attempts to resolve the
8747 link by doing text searches in the current buffer - so if you want a
8748 link \"[[target]]\" to still find \"<<target>>\", your function should
8749 handle this as a special case.
8751 When the function does handle the link, it must return a non-nil value.
8752 If it decides that it is not responsible for this link, it must return
8753 nil to indicate that that Org-mode can continue with other options
8754 like exact and fuzzy text search.")
8756 (defun org-next-link ()
8757 "Move forward to the next link.
8758 If the link is in hidden text, expose it."
8759 (interactive)
8760 (when (and org-link-search-failed (eq this-command last-command))
8761 (goto-char (point-min))
8762 (message "Link search wrapped back to beginning of buffer"))
8763 (setq org-link-search-failed nil)
8764 (let* ((pos (point))
8765 (ct (org-context))
8766 (a (assoc :link ct)))
8767 (if a (goto-char (nth 2 a)))
8768 (if (re-search-forward org-any-link-re nil t)
8769 (progn
8770 (goto-char (match-beginning 0))
8771 (if (org-invisible-p) (org-show-context)))
8772 (goto-char pos)
8773 (setq org-link-search-failed t)
8774 (error "No further link found"))))
8776 (defun org-previous-link ()
8777 "Move backward to the previous link.
8778 If the link is in hidden text, expose it."
8779 (interactive)
8780 (when (and org-link-search-failed (eq this-command last-command))
8781 (goto-char (point-max))
8782 (message "Link search wrapped back to end of buffer"))
8783 (setq org-link-search-failed nil)
8784 (let* ((pos (point))
8785 (ct (org-context))
8786 (a (assoc :link ct)))
8787 (if a (goto-char (nth 1 a)))
8788 (if (re-search-backward org-any-link-re nil t)
8789 (progn
8790 (goto-char (match-beginning 0))
8791 (if (org-invisible-p) (org-show-context)))
8792 (goto-char pos)
8793 (setq org-link-search-failed t)
8794 (error "No further link found"))))
8796 (defun org-translate-link (s)
8797 "Translate a link string if a translation function has been defined."
8798 (if (and org-link-translation-function
8799 (fboundp org-link-translation-function)
8800 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8801 (progn
8802 (setq s (funcall org-link-translation-function
8803 (match-string 1) (match-string 2)))
8804 (concat (car s) ":" (cdr s)))
8807 (defun org-translate-link-from-planner (type path)
8808 "Translate a link from Emacs Planner syntax so that Org can follow it.
8809 This is still an experimental function, your mileage may vary."
8810 (cond
8811 ((member type '("http" "https" "news" "ftp"))
8812 ;; standard Internet links are the same.
8813 nil)
8814 ((and (equal type "irc") (string-match "^//" path))
8815 ;; Planner has two / at the beginning of an irc link, we have 1.
8816 ;; We should have zero, actually....
8817 (setq path (substring path 1)))
8818 ((and (equal type "lisp") (string-match "^/" path))
8819 ;; Planner has a slash, we do not.
8820 (setq type "elisp" path (substring path 1)))
8821 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8822 ;; A typical message link. Planner has the id after the final slash,
8823 ;; we separate it with a hash mark
8824 (setq path (concat (match-string 1 path) "#"
8825 (org-remove-angle-brackets (match-string 2 path)))))
8827 (cons type path))
8829 (defun org-find-file-at-mouse (ev)
8830 "Open file link or URL at mouse."
8831 (interactive "e")
8832 (mouse-set-point ev)
8833 (org-open-at-point 'in-emacs))
8835 (defun org-open-at-mouse (ev)
8836 "Open file link or URL at mouse."
8837 (interactive "e")
8838 (mouse-set-point ev)
8839 (if (eq major-mode 'org-agenda-mode)
8840 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8841 (org-open-at-point))
8843 (defvar org-window-config-before-follow-link nil
8844 "The window configuration before following a link.
8845 This is saved in case the need arises to restore it.")
8847 (defvar org-open-link-marker (make-marker)
8848 "Marker pointing to the location where `org-open-at-point; was called.")
8850 ;;;###autoload
8851 (defun org-open-at-point-global ()
8852 "Follow a link like Org-mode does.
8853 This command can be called in any mode to follow a link that has
8854 Org-mode syntax."
8855 (interactive)
8856 (org-run-like-in-org-mode 'org-open-at-point))
8858 ;;;###autoload
8859 (defun org-open-link-from-string (s &optional arg reference-buffer)
8860 "Open a link in the string S, as if it was in Org-mode."
8861 (interactive "sLink: \nP")
8862 (let ((reference-buffer (or reference-buffer (current-buffer))))
8863 (with-temp-buffer
8864 (let ((org-inhibit-startup t))
8865 (org-mode)
8866 (insert s)
8867 (goto-char (point-min))
8868 (when reference-buffer
8869 (setq org-link-abbrev-alist-local
8870 (with-current-buffer reference-buffer
8871 org-link-abbrev-alist-local)))
8872 (org-open-at-point arg reference-buffer)))))
8874 (defun org-open-at-point (&optional in-emacs reference-buffer)
8875 "Open link at or after point.
8876 If there is no link at point, this function will search forward up to
8877 the end of the current line.
8878 Normally, files will be opened by an appropriate application. If the
8879 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8880 With a double prefix argument, try to open outside of Emacs, in the
8881 application the system uses for this file type."
8882 (interactive "P")
8883 (org-load-modules-maybe)
8884 (move-marker org-open-link-marker (point))
8885 (setq org-window-config-before-follow-link (current-window-configuration))
8886 (org-remove-occur-highlights nil nil t)
8887 (cond
8888 ((and (org-on-heading-p)
8889 (not (org-in-regexp
8890 (concat org-plain-link-re "\\|"
8891 org-bracket-link-regexp "\\|"
8892 org-angle-link-re "\\|"
8893 "[ \t]:[^ \t\n]+:[ \t]*$")))
8894 (not (get-text-property (point) 'org-linked-text)))
8895 (or (org-offer-links-in-entry in-emacs)
8896 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8897 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8898 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8899 (org-footnote-action))
8901 (let (type path link line search (pos (point)))
8902 (catch 'match
8903 (save-excursion
8904 (skip-chars-forward "^]\n\r")
8905 (when (org-in-regexp org-bracket-link-regexp 1)
8906 (setq link (org-extract-attributes
8907 (org-link-unescape (org-match-string-no-properties 1))))
8908 (while (string-match " *\n *" link)
8909 (setq link (replace-match " " t t link)))
8910 (setq link (org-link-expand-abbrev link))
8911 (cond
8912 ((or (file-name-absolute-p link)
8913 (string-match "^\\.\\.?/" link))
8914 (setq type "file" path link))
8915 ((string-match org-link-re-with-space3 link)
8916 (setq type (match-string 1 link) path (match-string 2 link)))
8917 (t (setq type "thisfile" path link)))
8918 (throw 'match t)))
8920 (when (get-text-property (point) 'org-linked-text)
8921 (setq type "thisfile"
8922 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8923 (1+ (point)) (point))
8924 path (buffer-substring
8925 (previous-single-property-change pos 'org-linked-text)
8926 (next-single-property-change pos 'org-linked-text)))
8927 (throw 'match t))
8929 (save-excursion
8930 (when (or (org-in-regexp org-angle-link-re)
8931 (org-in-regexp org-plain-link-re))
8932 (setq type (match-string 1) path (match-string 2))
8933 (throw 'match t)))
8934 (save-excursion
8935 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8936 (setq type "tags"
8937 path (match-string 1))
8938 (while (string-match ":" path)
8939 (setq path (replace-match "+" t t path)))
8940 (throw 'match t)))
8941 (when (org-in-regexp "<\\([^><\n]+\\)>")
8942 (setq type "tree-match"
8943 path (match-string 1))
8944 (throw 'match t)))
8945 (unless path
8946 (error "No link found"))
8948 ;; switch back to reference buffer
8949 ;; needed when if called in a temporary buffer through
8950 ;; org-open-link-from-string
8951 (with-current-buffer (or reference-buffer (current-buffer))
8953 ;; Remove any trailing spaces in path
8954 (if (string-match " +\\'" path)
8955 (setq path (replace-match "" t t path)))
8956 (if (and org-link-translation-function
8957 (fboundp org-link-translation-function))
8958 ;; Check if we need to translate the link
8959 (let ((tmp (funcall org-link-translation-function type path)))
8960 (setq type (car tmp) path (cdr tmp))))
8962 (cond
8964 ((assoc type org-link-protocols)
8965 (funcall (nth 1 (assoc type org-link-protocols)) path))
8967 ((equal type "mailto")
8968 (let ((cmd (car org-link-mailto-program))
8969 (args (cdr org-link-mailto-program)) args1
8970 (address path) (subject "") a)
8971 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8972 (setq address (match-string 1 path)
8973 subject (org-link-escape (match-string 2 path))))
8974 (while args
8975 (cond
8976 ((not (stringp (car args))) (push (pop args) args1))
8977 (t (setq a (pop args))
8978 (if (string-match "%a" a)
8979 (setq a (replace-match address t t a)))
8980 (if (string-match "%s" a)
8981 (setq a (replace-match subject t t a)))
8982 (push a args1))))
8983 (apply cmd (nreverse args1))))
8985 ((member type '("http" "https" "ftp" "news"))
8986 (browse-url (concat type ":" (org-link-escape
8987 path org-link-escape-chars-browser))))
8989 ((string= type "doi")
8990 (browse-url (concat "http://dx.doi.org/"
8991 (org-link-escape
8992 path org-link-escape-chars-browser))))
8994 ((member type '("message"))
8995 (browse-url (concat type ":" path)))
8997 ((string= type "tags")
8998 (org-tags-view in-emacs path))
9000 ((string= type "tree-match")
9001 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9003 ((string= type "file")
9004 (if (string-match "::\\([0-9]+\\)\\'" path)
9005 (setq line (string-to-number (match-string 1 path))
9006 path (substring path 0 (match-beginning 0)))
9007 (if (string-match "::\\(.+\\)\\'" path)
9008 (setq search (match-string 1 path)
9009 path (substring path 0 (match-beginning 0)))))
9010 (if (string-match "[*?{]" (file-name-nondirectory path))
9011 (dired path)
9012 (org-open-file path in-emacs line search)))
9014 ((string= type "news")
9015 (require 'org-gnus)
9016 (org-gnus-follow-link path))
9018 ((string= type "shell")
9019 (let ((cmd path))
9020 (if (or (not org-confirm-shell-link-function)
9021 (funcall org-confirm-shell-link-function
9022 (format "Execute \"%s\" in shell? "
9023 (org-add-props cmd nil
9024 'face 'org-warning))))
9025 (progn
9026 (message "Executing %s" cmd)
9027 (shell-command cmd))
9028 (error "Abort"))))
9030 ((string= type "elisp")
9031 (let ((cmd path))
9032 (if (or (not org-confirm-elisp-link-function)
9033 (funcall org-confirm-elisp-link-function
9034 (format "Execute \"%s\" as elisp? "
9035 (org-add-props cmd nil
9036 'face 'org-warning))))
9037 (message "%s => %s" cmd
9038 (if (equal (string-to-char cmd) ?\()
9039 (eval (read cmd))
9040 (call-interactively (read cmd))))
9041 (error "Abort"))))
9043 ((and (string= type "thisfile")
9044 (run-hook-with-args-until-success
9045 'org-open-link-functions path)))
9047 ((string= type "thisfile")
9048 (if in-emacs
9049 (switch-to-buffer-other-window
9050 (org-get-buffer-for-internal-link (current-buffer)))
9051 (org-mark-ring-push))
9052 (let ((cmd `(org-link-search
9053 ,path
9054 ,(cond ((equal in-emacs '(4)) 'occur)
9055 ((equal in-emacs '(16)) 'org-occur)
9056 (t nil))
9057 ,pos)))
9058 (condition-case nil (eval cmd)
9059 (error (progn (widen) (eval cmd))))))
9062 (browse-url-at-point)))))))
9063 (move-marker org-open-link-marker nil)
9064 (run-hook-with-args 'org-follow-link-hook))
9066 (defun org-offer-links-in-entry (&optional nth zero)
9067 "Offer links in the current entry and follow the selected link.
9068 If there is only one link, follow it immediately as well.
9069 If NTH is an integer, immediately pick the NTH link found.
9070 If ZERO is a string, check also this string for a link, and if
9071 there is one, offer it as link number zero."
9072 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9073 "\\(" org-angle-link-re "\\)\\|"
9074 "\\(" org-plain-link-re "\\)"))
9075 (cnt ?0)
9076 (in-emacs (if (integerp nth) nil nth))
9077 have-zero end links link c)
9078 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9079 (push (match-string 0 zero) links)
9080 (setq cnt (1- cnt) have-zero t))
9081 (save-excursion
9082 (org-back-to-heading t)
9083 (setq end (save-excursion (outline-next-heading) (point)))
9084 (while (re-search-forward re end t)
9085 (push (match-string 0) links))
9086 (setq links (org-uniquify (reverse links))))
9088 (cond
9089 ((null links)
9090 (message "No links"))
9091 ((equal (length links) 1)
9092 (setq link (list (car links))))
9093 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9094 (setq link (nth (if have-zero nth (1- nth)) links)))
9095 (t ; we have to select a link
9096 (save-excursion
9097 (save-window-excursion
9098 (delete-other-windows)
9099 (with-output-to-temp-buffer "*Select Link*"
9100 (mapc (lambda (l)
9101 (if (not (string-match org-bracket-link-regexp l))
9102 (princ (format "[%c] %s\n" (incf cnt)
9103 (org-remove-angle-brackets l)))
9104 (if (match-end 3)
9105 (princ (format "[%c] %s (%s)\n" (incf cnt)
9106 (match-string 3 l) (match-string 1 l)))
9107 (princ (format "[%c] %s\n" (incf cnt)
9108 (match-string 1 l))))))
9109 links))
9110 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9111 (message "Select link to open, RET to open all:")
9112 (setq c (read-char-exclusive))
9113 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9114 (when (equal c ?q) (error "Abort"))
9115 (if (equal c ?\C-m)
9116 (setq link links)
9117 (setq nth (- c ?0))
9118 (if have-zero (setq nth (1+ nth)))
9119 (unless (and (integerp nth) (>= (length links) nth))
9120 (error "Invalid link selection"))
9121 (setq link (list (nth (1- nth) links))))))
9122 (if link
9123 (let ((buf (current-buffer)))
9124 (dolist (l link)
9125 (org-open-link-from-string l in-emacs buf))
9127 nil)))
9129 ;; Add special file links that specify the way of opening
9131 (org-add-link-type "file+sys" 'org-open-file-with-system)
9132 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9133 (defun org-open-file-with-system (path)
9134 "Open file at PATH using the system way of opeing it."
9135 (org-open-file path 'system))
9136 (defun org-open-file-with-emacs (path)
9137 "Open file at PATH in emacs."
9138 (org-open-file path 'emacs))
9139 (defun org-remove-file-link-modifiers ()
9140 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9141 (goto-char (point-min))
9142 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9143 (org-if-unprotected
9144 (replace-match "file:" t t))))
9145 (eval-after-load "org-exp"
9146 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9147 'org-remove-file-link-modifiers))
9149 ;;;; Time estimates
9151 (defun org-get-effort (&optional pom)
9152 "Get the effort estimate for the current entry."
9153 (org-entry-get pom org-effort-property))
9155 ;;; File search
9157 (defvar org-create-file-search-functions nil
9158 "List of functions to construct the right search string for a file link.
9159 These functions are called in turn with point at the location to
9160 which the link should point.
9162 A function in the hook should first test if it would like to
9163 handle this file type, for example by checking the major-mode or
9164 the file extension. If it decides not to handle this file, it
9165 should just return nil to give other functions a chance. If it
9166 does handle the file, it must return the search string to be used
9167 when following the link. The search string will be part of the
9168 file link, given after a double colon, and `org-open-at-point'
9169 will automatically search for it. If special measures must be
9170 taken to make the search successful, another function should be
9171 added to the companion hook `org-execute-file-search-functions',
9172 which see.
9174 A function in this hook may also use `setq' to set the variable
9175 `description' to provide a suggestion for the descriptive text to
9176 be used for this link when it gets inserted into an Org-mode
9177 buffer with \\[org-insert-link].")
9179 (defvar org-execute-file-search-functions nil
9180 "List of functions to execute a file search triggered by a link.
9182 Functions added to this hook must accept a single argument, the
9183 search string that was part of the file link, the part after the
9184 double colon. The function must first check if it would like to
9185 handle this search, for example by checking the major-mode or the
9186 file extension. If it decides not to handle this search, it
9187 should just return nil to give other functions a chance. If it
9188 does handle the search, it must return a non-nil value to keep
9189 other functions from trying.
9191 Each function can access the current prefix argument through the
9192 variable `current-prefix-argument'. Note that a single prefix is
9193 used to force opening a link in Emacs, so it may be good to only
9194 use a numeric or double prefix to guide the search function.
9196 In case this is needed, a function in this hook can also restore
9197 the window configuration before `org-open-at-point' was called using:
9199 (set-window-configuration org-window-config-before-follow-link)")
9201 (defun org-link-search (s &optional type avoid-pos)
9202 "Search for a link search option.
9203 If S is surrounded by forward slashes, it is interpreted as a
9204 regular expression. In org-mode files, this will create an `org-occur'
9205 sparse tree. In ordinary files, `occur' will be used to list matches.
9206 If the current buffer is in `dired-mode', grep will be used to search
9207 in all files. If AVOID-POS is given, ignore matches near that position."
9208 (let ((case-fold-search t)
9209 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9210 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9211 (append '(("") (" ") ("\t") ("\n"))
9212 org-emphasis-alist)
9213 "\\|") "\\)"))
9214 (pos (point))
9215 (pre nil) (post nil)
9216 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9217 (cond
9218 ;; First check if there are any special
9219 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9220 ;; Now try the builtin stuff
9221 ((and (equal (string-to-char s0) ?#)
9222 (> (length s0) 1)
9223 (save-excursion
9224 (goto-char (point-min))
9225 (and
9226 (re-search-forward
9227 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9228 (setq type 'dedicated
9229 pos (match-beginning 0))))
9230 ;; There is an exact target for this
9231 (goto-char pos)
9232 (org-back-to-heading t)))
9233 ((save-excursion
9234 (goto-char (point-min))
9235 (and
9236 (re-search-forward
9237 (concat "<<" (regexp-quote s0) ">>") nil t)
9238 (setq type 'dedicated
9239 pos (match-beginning 0))))
9240 ;; There is an exact target for this
9241 (goto-char pos))
9242 ((and (string-match "^(\\(.*\\))$" s0)
9243 (save-excursion
9244 (goto-char (point-min))
9245 (and
9246 (re-search-forward
9247 (concat "[^[]" (regexp-quote
9248 (format org-coderef-label-format
9249 (match-string 1 s0))))
9250 nil t)
9251 (setq type 'dedicated
9252 pos (1+ (match-beginning 0))))))
9253 ;; There is a coderef target for this
9254 (goto-char pos))
9255 ((string-match "^/\\(.*\\)/$" s)
9256 ;; A regular expression
9257 (cond
9258 ((org-mode-p)
9259 (org-occur (match-string 1 s)))
9260 ;;((eq major-mode 'dired-mode)
9261 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9262 (t (org-do-occur (match-string 1 s)))))
9264 ;; A normal search strings
9265 (when (equal (string-to-char s) ?*)
9266 ;; Anchor on headlines, post may include tags.
9267 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9268 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9269 s (substring s 1)))
9270 (remove-text-properties
9271 0 (length s)
9272 '(face nil mouse-face nil keymap nil fontified nil) s)
9273 ;; Make a series of regular expressions to find a match
9274 (setq words (org-split-string s "[ \n\r\t]+")
9276 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9277 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9278 "\\)" markers)
9279 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9280 re2a (concat "[ \t\r\n]" re2a_)
9281 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9282 re4 (concat "[^a-zA-Z_]" re4_)
9284 re1 (concat pre re2 post)
9285 re3 (concat pre (if pre re4_ re4) post)
9286 re5 (concat pre ".*" re4)
9287 re2 (concat pre re2)
9288 re2a (concat pre (if pre re2a_ re2a))
9289 re4 (concat pre (if pre re4_ re4))
9290 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9291 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9292 re5 "\\)"
9294 (cond
9295 ((eq type 'org-occur) (org-occur reall))
9296 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9297 (t (goto-char (point-min))
9298 (setq type 'fuzzy)
9299 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9300 (org-search-not-self 1 re1 nil t)
9301 (org-search-not-self 1 re2 nil t)
9302 (org-search-not-self 1 re2a nil t)
9303 (org-search-not-self 1 re3 nil t)
9304 (org-search-not-self 1 re4 nil t)
9305 (org-search-not-self 1 re5 nil t)
9307 (goto-char (match-beginning 1))
9308 (goto-char pos)
9309 (error "No match")))))
9311 ;; Normal string-search
9312 (goto-char (point-min))
9313 (if (search-forward s nil t)
9314 (goto-char (match-beginning 0))
9315 (error "No match"))))
9316 (and (org-mode-p) (org-show-context 'link-search))
9317 type))
9319 (defun org-search-not-self (group &rest args)
9320 "Execute `re-search-forward', but only accept matches that do not
9321 enclose the position of `org-open-link-marker'."
9322 (let ((m org-open-link-marker))
9323 (catch 'exit
9324 (while (apply 're-search-forward args)
9325 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9326 (goto-char (match-end group))
9327 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9328 (> (match-beginning 0) (marker-position m))
9329 (< (match-end 0) (marker-position m)))
9330 (save-match-data
9331 (or (not (org-in-regexp
9332 org-bracket-link-analytic-regexp 1))
9333 (not (match-end 4)) ; no description
9334 (and (<= (match-beginning 4) (point))
9335 (>= (match-end 4) (point))))))
9336 (throw 'exit (point))))))))
9338 (defun org-get-buffer-for-internal-link (buffer)
9339 "Return a buffer to be used for displaying the link target of internal links."
9340 (cond
9341 ((not org-display-internal-link-with-indirect-buffer)
9342 buffer)
9343 ((string-match "(Clone)$" (buffer-name buffer))
9344 (message "Buffer is already a clone, not making another one")
9345 ;; we also do not modify visibility in this case
9346 buffer)
9347 (t ; make a new indirect buffer for displaying the link
9348 (let* ((bn (buffer-name buffer))
9349 (ibn (concat bn "(Clone)"))
9350 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9351 (with-current-buffer ib (org-overview))
9352 ib))))
9354 (defun org-do-occur (regexp &optional cleanup)
9355 "Call the Emacs command `occur'.
9356 If CLEANUP is non-nil, remove the printout of the regular expression
9357 in the *Occur* buffer. This is useful if the regex is long and not useful
9358 to read."
9359 (occur regexp)
9360 (when cleanup
9361 (let ((cwin (selected-window)) win beg end)
9362 (when (setq win (get-buffer-window "*Occur*"))
9363 (select-window win))
9364 (goto-char (point-min))
9365 (when (re-search-forward "match[a-z]+" nil t)
9366 (setq beg (match-end 0))
9367 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9368 (setq end (1- (match-beginning 0)))))
9369 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9370 (goto-char (point-min))
9371 (select-window cwin))))
9373 ;;; The mark ring for links jumps
9375 (defvar org-mark-ring nil
9376 "Mark ring for positions before jumps in Org-mode.")
9377 (defvar org-mark-ring-last-goto nil
9378 "Last position in the mark ring used to go back.")
9379 ;; Fill and close the ring
9380 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9381 (loop for i from 1 to org-mark-ring-length do
9382 (push (make-marker) org-mark-ring))
9383 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9384 org-mark-ring)
9386 (defun org-mark-ring-push (&optional pos buffer)
9387 "Put the current position or POS into the mark ring and rotate it."
9388 (interactive)
9389 (setq pos (or pos (point)))
9390 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9391 (move-marker (car org-mark-ring)
9392 (or pos (point))
9393 (or buffer (current-buffer)))
9394 (message "%s"
9395 (substitute-command-keys
9396 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9398 (defun org-mark-ring-goto (&optional n)
9399 "Jump to the previous position in the mark ring.
9400 With prefix arg N, jump back that many stored positions. When
9401 called several times in succession, walk through the entire ring.
9402 Org-mode commands jumping to a different position in the current file,
9403 or to another Org-mode file, automatically push the old position
9404 onto the ring."
9405 (interactive "p")
9406 (let (p m)
9407 (if (eq last-command this-command)
9408 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9409 (setq p org-mark-ring))
9410 (setq org-mark-ring-last-goto p)
9411 (setq m (car p))
9412 (switch-to-buffer (marker-buffer m))
9413 (goto-char m)
9414 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9416 (defun org-remove-angle-brackets (s)
9417 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9418 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9420 (defun org-add-angle-brackets (s)
9421 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9422 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9424 (defun org-remove-double-quotes (s)
9425 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9426 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9429 ;;; Following specific links
9431 (defun org-follow-timestamp-link ()
9432 (cond
9433 ((org-at-date-range-p t)
9434 (let ((org-agenda-start-on-weekday)
9435 (t1 (match-string 1))
9436 (t2 (match-string 2)))
9437 (setq t1 (time-to-days (org-time-string-to-time t1))
9438 t2 (time-to-days (org-time-string-to-time t2)))
9439 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9440 ((org-at-timestamp-p t)
9441 (org-agenda-list nil (time-to-days (org-time-string-to-time
9442 (substring (match-string 1) 0 10)))
9444 (t (error "This should not happen"))))
9447 ;;; Following file links
9448 (defvar org-wait nil)
9449 (defun org-open-file (path &optional in-emacs line search)
9450 "Open the file at PATH.
9451 First, this expands any special file name abbreviations. Then the
9452 configuration variable `org-file-apps' is checked if it contains an
9453 entry for this file type, and if yes, the corresponding command is launched.
9455 If no application is found, Emacs simply visits the file.
9457 With optional prefix argument IN-EMACS, Emacs will visit the file.
9458 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9459 and to use an external application to visit the file.
9461 Optional LINE specifies a line to go to, optional SEARCH a string
9462 to search for. If LINE or SEARCH is given, the file will be
9463 opened in Emacs, unless an entry from org-file-apps that makes
9464 use of groups in a regexp matches.
9465 If the file does not exist, an error is thrown."
9466 (let* ((file (if (equal path "")
9467 buffer-file-name
9468 (substitute-in-file-name (expand-file-name path))))
9469 (file-apps (append org-file-apps (org-default-apps)))
9470 (apps (org-remove-if
9471 'org-file-apps-entry-match-against-dlink-p file-apps))
9472 (apps-dlink (org-remove-if-not
9473 'org-file-apps-entry-match-against-dlink-p file-apps))
9474 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9475 (dirp (if remp nil (file-directory-p file)))
9476 (file (if (and dirp org-open-directory-means-index-dot-org)
9477 (concat (file-name-as-directory file) "index.org")
9478 file))
9479 (a-m-a-p (assq 'auto-mode apps))
9480 (dfile (downcase file))
9481 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9482 (link (cond ((and (eq line nil)
9483 (eq search nil))
9484 file)
9485 (line
9486 (concat file "::" (number-to-string line)))
9487 (search
9488 (concat file "::" search))))
9489 (dlink (downcase link))
9490 (old-buffer (current-buffer))
9491 (old-pos (point))
9492 (old-mode major-mode)
9493 ext cmd link-match-data)
9494 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9495 (setq ext (match-string 1 dfile))
9496 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9497 (setq ext (match-string 1 dfile))))
9498 (cond
9499 ((member in-emacs '((16) system))
9500 (setq cmd (cdr (assoc 'system apps))))
9501 (in-emacs (setq cmd 'emacs))
9503 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9504 (and dirp (cdr (assoc 'directory apps)))
9505 ; first, try matching against apps-dlink
9506 ; if we get a match here, store the match data for later
9507 (let ((match (assoc-default dlink apps-dlink
9508 'string-match)))
9509 (if match
9510 (progn (setq link-match-data (match-data))
9511 match)
9512 (progn (setq in-emacs (or in-emacs line search))
9513 nil))) ; if we have no match in apps-dlink,
9514 ; always open the file in emacs if line or search
9515 ; is given (for backwards compatibility)
9516 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9517 'string-match)
9518 (cdr (assoc ext apps))
9519 (cdr (assoc t apps))))))
9520 (when (eq cmd 'system)
9521 (setq cmd (cdr (assoc 'system apps))))
9522 (when (eq cmd 'default)
9523 (setq cmd (cdr (assoc t apps))))
9524 (when (eq cmd 'mailcap)
9525 (require 'mailcap)
9526 (mailcap-parse-mailcaps)
9527 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9528 (command (mailcap-mime-info mime-type)))
9529 (if (stringp command)
9530 (setq cmd command)
9531 (setq cmd 'emacs))))
9532 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9533 (not (file-exists-p file))
9534 (not org-open-non-existing-files))
9535 (error "No such file: %s" file))
9536 (cond
9537 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9538 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9539 (while (string-match "['\"]%s['\"]" cmd)
9540 (setq cmd (replace-match "%s" t t cmd)))
9541 (while (string-match "%s" cmd)
9542 (setq cmd (replace-match
9543 (save-match-data
9544 (shell-quote-argument
9545 (convert-standard-filename file)))
9546 t t cmd)))
9548 ;; Replace "%1", "%2" etc. in command with group matches from regex
9549 (save-match-data
9550 (let ((match-index 1)
9551 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9552 (set-match-data link-match-data)
9553 (while (<= match-index number-of-groups)
9554 (let ((regex (concat "%" (number-to-string match-index)))
9555 (replace-with (match-string match-index dlink)))
9556 (while (string-match regex cmd)
9557 (setq cmd (replace-match replace-with t t cmd))))
9558 (setq match-index (+ match-index 1)))))
9560 (save-window-excursion
9561 (start-process-shell-command cmd nil cmd)
9562 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9564 ((or (stringp cmd)
9565 (eq cmd 'emacs))
9566 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9567 (widen)
9568 (if line (org-goto-line line)
9569 (if search (org-link-search search))))
9570 ((consp cmd)
9571 (let ((file (convert-standard-filename file)))
9572 (save-match-data
9573 (set-match-data link-match-data)
9574 (eval cmd))))
9575 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9576 (and (org-mode-p) (eq old-mode 'org-mode)
9577 (or (not (equal old-buffer (current-buffer)))
9578 (not (equal old-pos (point))))
9579 (org-mark-ring-push old-pos old-buffer))))
9581 (defun org-file-apps-entry-match-against-dlink-p (entry)
9582 "This function returns non-nil if `entry' uses a regular
9583 expression which should be matched against the whole link by
9584 org-open-file.
9586 It assumes that is the case when the entry uses a regular
9587 expression which has at least one grouping construct and the
9588 action is either a lisp form or a command string containing
9589 '%1', i.e. using at least one subexpression match as a
9590 parameter."
9591 (let ((selector (car entry))
9592 (action (cdr entry)))
9593 (if (stringp selector)
9594 (and (> (regexp-opt-depth selector) 0)
9595 (or (and (stringp action)
9596 (string-match "%[0-9]" action))
9597 (consp action)))
9598 nil)))
9600 (defun org-default-apps ()
9601 "Return the default applications for this operating system."
9602 (cond
9603 ((eq system-type 'darwin)
9604 org-file-apps-defaults-macosx)
9605 ((eq system-type 'windows-nt)
9606 org-file-apps-defaults-windowsnt)
9607 (t org-file-apps-defaults-gnu)))
9609 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9610 "Convert extensions to regular expressions in the cars of LIST.
9611 Also, weed out any non-string entries, because the return value is used
9612 only for regexp matching.
9613 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9614 point to the symbol `emacs', indicating that the file should
9615 be opened in Emacs."
9616 (append
9617 (delq nil
9618 (mapcar (lambda (x)
9619 (if (not (stringp (car x)))
9621 (if (string-match "\\W" (car x))
9623 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9624 list))
9625 (if add-auto-mode
9626 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9628 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9629 (defun org-file-remote-p (file)
9630 "Test whether FILE specifies a location on a remote system.
9631 Return non-nil if the location is indeed remote.
9633 For example, the filename \"/user@host:/foo\" specifies a location
9634 on the system \"/user@host:\"."
9635 (cond ((fboundp 'file-remote-p)
9636 (file-remote-p file))
9637 ((fboundp 'tramp-handle-file-remote-p)
9638 (tramp-handle-file-remote-p file))
9639 ((and (boundp 'ange-ftp-name-format)
9640 (string-match (car ange-ftp-name-format) file))
9642 (t nil)))
9645 ;;;; Refiling
9647 (defun org-get-org-file ()
9648 "Read a filename, with default directory `org-directory'."
9649 (let ((default (or org-default-notes-file remember-data-file)))
9650 (read-file-name (format "File name [%s]: " default)
9651 (file-name-as-directory org-directory)
9652 default)))
9654 (defun org-notes-order-reversed-p ()
9655 "Check if the current file should receive notes in reversed order."
9656 (cond
9657 ((not org-reverse-note-order) nil)
9658 ((eq t org-reverse-note-order) t)
9659 ((not (listp org-reverse-note-order)) nil)
9660 (t (catch 'exit
9661 (let ((all org-reverse-note-order)
9662 entry)
9663 (while (setq entry (pop all))
9664 (if (string-match (car entry) buffer-file-name)
9665 (throw 'exit (cdr entry))))
9666 nil)))))
9668 (defvar org-refile-target-table nil
9669 "The list of refile targets, created by `org-refile'.")
9671 (defvar org-agenda-new-buffers nil
9672 "Buffers created to visit agenda files.")
9674 (defvar org-refile-cache nil
9675 "Cache for refile targets.")
9678 (defvar org-refile-markers nil
9679 "All the markers used for caching refile locations.")
9681 (defun org-refile-marker (pos)
9682 "Get a new refile marker, but only if caching is in use."
9683 (if (not org-refile-use-cache)
9685 (let ((m (make-marker)))
9686 (move-marker m pos)
9687 (push m org-refile-markers)
9688 m)))
9690 (defun org-refile-cache-clear ()
9691 "Clear the refile cache and disable all the markers."
9692 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9693 (setq org-refile-markers nil)
9694 (setq org-refile-cache nil)
9695 (message "Refile cache has been cleared"))
9697 (defun org-refile-cache-check-set (set)
9698 "Check if all the markers in the cache still have live buffers."
9699 (let (marker)
9700 (catch 'exit
9701 (while (and set (setq marker (nth 3 (pop set))))
9702 ;; if org-refile-use-outline-path is 'file, marker may be nil
9703 (when (and marker (null (marker-buffer marker)))
9704 (message "not found") (sit-for 3)
9705 (throw 'exit nil)))
9706 t)))
9708 (defun org-refile-cache-put (set &rest identifiers)
9709 "Push the refile targets SET into the cache, under IDENTIFIERS."
9710 (let* ((key (sha1 (prin1-to-string identifiers)))
9711 (entry (assoc key org-refile-cache)))
9712 (if entry
9713 (setcdr entry set)
9714 (push (cons key set) org-refile-cache))))
9716 (defun org-refile-cache-get (&rest identifiers)
9717 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9718 (cond
9719 ((not org-refile-cache) nil)
9720 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9722 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9723 org-refile-cache))))
9724 (and set (org-refile-cache-check-set set) set)))))
9726 (defun org-get-refile-targets (&optional default-buffer)
9727 "Produce a table with refile targets."
9728 (let ((case-fold-search nil)
9729 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9730 (entries (or org-refile-targets '((nil . (:level . 1)))))
9731 targets tgs txt re files f desc descre fast-path-p level pos0)
9732 (message "Getting targets...")
9733 (with-current-buffer (or default-buffer (current-buffer))
9734 (while (setq entry (pop entries))
9735 (setq files (car entry) desc (cdr entry))
9736 (setq fast-path-p nil)
9737 (cond
9738 ((null files) (setq files (list (current-buffer))))
9739 ((eq files 'org-agenda-files)
9740 (setq files (org-agenda-files 'unrestricted)))
9741 ((and (symbolp files) (fboundp files))
9742 (setq files (funcall files)))
9743 ((and (symbolp files) (boundp files))
9744 (setq files (symbol-value files))))
9745 (if (stringp files) (setq files (list files)))
9746 (cond
9747 ((eq (car desc) :tag)
9748 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9749 ((eq (car desc) :todo)
9750 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9751 ((eq (car desc) :regexp)
9752 (setq descre (cdr desc)))
9753 ((eq (car desc) :level)
9754 (setq descre (concat "^\\*\\{" (number-to-string
9755 (if org-odd-levels-only
9756 (1- (* 2 (cdr desc)))
9757 (cdr desc)))
9758 "\\}[ \t]")))
9759 ((eq (car desc) :maxlevel)
9760 (setq fast-path-p t)
9761 (setq descre (concat "^\\*\\{1," (number-to-string
9762 (if org-odd-levels-only
9763 (1- (* 2 (cdr desc)))
9764 (cdr desc)))
9765 "\\}[ \t]")))
9766 (t (error "Bad refiling target description %s" desc)))
9767 (while (setq f (pop files))
9768 (with-current-buffer
9769 (if (bufferp f) f (org-get-agenda-file-buffer f))
9771 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9772 (progn
9773 (if (bufferp f) (setq f (buffer-file-name
9774 (buffer-base-buffer f))))
9775 (setq f (and f (expand-file-name f)))
9776 (if (eq org-refile-use-outline-path 'file)
9777 (push (list (file-name-nondirectory f) f nil nil) tgs))
9778 (save-excursion
9779 (save-restriction
9780 (widen)
9781 (goto-char (point-min))
9782 (while (re-search-forward descre nil t)
9783 (goto-char (setq pos0 (point-at-bol)))
9784 (catch 'next
9785 (when org-refile-target-verify-function
9786 (save-match-data
9787 (or (funcall org-refile-target-verify-function)
9788 (throw 'next t))))
9789 (when (looking-at org-complex-heading-regexp)
9790 (setq level (org-reduced-level
9791 (- (match-end 1) (match-beginning 1)))
9792 txt (org-link-display-format (match-string 4))
9793 re (concat "^" (regexp-quote
9794 (buffer-substring
9795 (match-beginning 1)
9796 (match-end 4)))))
9797 (if (match-end 5) (setq re (concat
9798 re "[ \t]+"
9799 (regexp-quote
9800 (match-string 5)))))
9801 (setq re (concat re "[ \t]*$"))
9802 (when org-refile-use-outline-path
9803 (setq txt (mapconcat
9804 'org-protect-slash
9805 (append
9806 (if (eq org-refile-use-outline-path
9807 'file)
9808 (list (file-name-nondirectory
9809 (buffer-file-name
9810 (buffer-base-buffer))))
9811 (if (eq org-refile-use-outline-path
9812 'full-file-path)
9813 (list (buffer-file-name
9814 (buffer-base-buffer)))))
9815 (org-get-outline-path fast-path-p
9816 level txt)
9817 (list txt))
9818 "/")))
9819 (push (list txt f re (org-refile-marker (point)))
9820 tgs)))
9821 (when (= (point) pos0)
9822 ;; verification function has not moved point
9823 (goto-char (point-at-eol))))))))
9824 (when org-refile-use-cache
9825 (org-refile-cache-put tgs (buffer-file-name) descre))
9826 (setq targets (append tgs targets))
9827 ))))
9828 (message "Getting targets...done")
9829 (nreverse targets)))
9831 (defun org-protect-slash (s)
9832 (while (string-match "/" s)
9833 (setq s (replace-match "\\" t t s)))
9836 (defvar org-olpa (make-vector 20 nil))
9838 (defun org-get-outline-path (&optional fastp level heading)
9839 "Return the outline path to the current entry, as a list.
9841 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9842 routine which makes outline path derivations for an entire file,
9843 avoiding backtracing. Refile target collection makes use of that."
9844 (if fastp
9845 (progn
9846 (if (> level 19)
9847 (error "Outline path failure, more than 19 levels."))
9848 (loop for i from level upto 19 do
9849 (aset org-olpa i nil))
9850 (prog1
9851 (delq nil (append org-olpa nil))
9852 (aset org-olpa level heading)))
9853 (let (rtn case-fold-search)
9854 (save-excursion
9855 (save-restriction
9856 (widen)
9857 (while (org-up-heading-safe)
9858 (when (looking-at org-complex-heading-regexp)
9859 (push (org-match-string-no-properties 4) rtn)))
9860 rtn)))))
9862 (defun org-format-outline-path (path &optional width prefix)
9863 "Format the outlie path PATH for display.
9864 Width is the maximum number of characters that is available.
9865 Prefix is a prefix to be included in the returned string,
9866 such as the file name."
9867 (setq width (or width 79))
9868 (if prefix (setq width (- width (length prefix))))
9869 (if (not path)
9870 (or prefix "")
9871 (let* ((nsteps (length path))
9872 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9873 (maxwidth (if (<= total-width width)
9874 10000 ;; everything fits
9875 ;; we need to shorten the level headings
9876 (/ (- width nsteps) nsteps)))
9877 (org-odd-levels-only nil)
9878 (n 0)
9879 (total (1+ (length prefix))))
9880 (setq maxwidth (max maxwidth 10))
9881 (concat prefix
9882 (mapconcat
9883 (lambda (h)
9884 (setq n (1+ n))
9885 (if (and (= n nsteps) (< maxwidth 10000))
9886 (setq maxwidth (- total-width total)))
9887 (if (< (length h) maxwidth)
9888 (progn (setq total (+ total (length h) 1)) h)
9889 (setq h (substring h 0 (- maxwidth 2))
9890 total (+ total maxwidth 1))
9891 (if (string-match "[ \t]+\\'" h)
9892 (setq h (substring h 0 (match-beginning 0))))
9893 (setq h (concat h "..")))
9894 (org-add-props h nil 'face
9895 (nth (% (1- n) org-n-level-faces)
9896 org-level-faces))
9898 path "/")))))
9900 (defun org-display-outline-path (&optional file current)
9901 "Display the current outline path in the echo area."
9902 (interactive "P")
9903 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9904 (case-fold-search nil)
9905 (path (and (org-mode-p) (org-get-outline-path))))
9906 (if current (setq path (append path
9907 (save-excursion
9908 (org-back-to-heading t)
9909 (if (looking-at org-complex-heading-regexp)
9910 (list (match-string 4)))))))
9911 (message "%s"
9912 (org-format-outline-path
9913 path
9914 (1- (frame-width))
9915 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9917 (defvar org-refile-history nil
9918 "History for refiling operations.")
9920 (defvar org-after-refile-insert-hook nil
9921 "Hook run after `org-refile' has inserted its stuff at the new location.
9922 Note that this is still *before* the stuff will be removed from
9923 the *old* location.")
9925 (defun org-refile (&optional goto default-buffer rfloc)
9926 "Move the entry at point to another heading.
9927 The list of target headings is compiled using the information in
9928 `org-refile-targets', which see. This list is created before each use
9929 and will therefore always be up-to-date.
9931 At the target location, the entry is filed as a subitem of the target heading.
9932 Depending on `org-reverse-note-order', the new subitem will either be the
9933 first or the last subitem.
9935 If there is an active region, all entries in that region will be moved.
9936 However, the region must fulfil the requirement that the first heading
9937 is the first one sets the top-level of the moved text - at most siblings
9938 below it are allowed.
9940 With prefix arg GOTO, the command will only visit the target location,
9941 not actually move anything.
9942 With a double prefix `C-u C-u', go to the location where the last refiling
9943 operation has put the subtree.
9944 With a prefix argument of `2', refile to the running clock.
9946 RFLOC can be a refile location obtained in a different way.
9948 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
9950 If you are using target caching (see `org-refile-use-cache'),
9951 You have to clear the target cache in order to find new targets.
9952 This can be done with a 0 prefix: `C-0 C-c C-w'"
9953 (interactive "P")
9954 (if (member goto '(0 (64)))
9955 (org-refile-cache-clear)
9956 (let* ((cbuf (current-buffer))
9957 (regionp (org-region-active-p))
9958 (region-start (and regionp (region-beginning)))
9959 (region-end (and regionp (region-end)))
9960 (region-length (and regionp (- region-end region-start)))
9961 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9962 pos it nbuf file re level reversed)
9963 (setq last-command nil)
9964 (when regionp
9965 (goto-char region-start)
9966 (or (bolp) (goto-char (point-at-bol)))
9967 (setq region-start (point))
9968 (unless (org-kill-is-subtree-p
9969 (buffer-substring region-start region-end))
9970 (error "The region is not a (sequence of) subtree(s)")))
9971 (if (equal goto '(16))
9972 (org-refile-goto-last-stored)
9973 (when (or
9974 (and (equal goto 2)
9975 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9976 (prog1
9977 (setq it (list (or org-clock-heading "running clock")
9978 (buffer-file-name
9979 (marker-buffer org-clock-hd-marker))
9981 (marker-position org-clock-hd-marker)))
9982 (setq goto nil)))
9983 (setq it (or rfloc
9984 (save-excursion
9985 (org-refile-get-location
9986 (if goto "Goto: " "Refile to: ") default-buffer
9987 org-refile-allow-creating-parent-nodes)))))
9988 (setq file (nth 1 it)
9989 re (nth 2 it)
9990 pos (nth 3 it))
9991 (if (and (not goto)
9993 (equal (buffer-file-name) file)
9994 (if regionp
9995 (and (>= pos region-start)
9996 (<= pos region-end))
9997 (and (>= pos (point))
9998 (< pos (save-excursion
9999 (org-end-of-subtree t t))))))
10000 (error "Cannot refile to position inside the tree or region"))
10002 (setq nbuf (or (find-buffer-visiting file)
10003 (find-file-noselect file)))
10004 (if goto
10005 (progn
10006 (switch-to-buffer nbuf)
10007 (goto-char pos)
10008 (org-show-context 'org-goto))
10009 (if regionp
10010 (progn
10011 (org-kill-new (buffer-substring region-start region-end))
10012 (org-save-markers-in-region region-start region-end))
10013 (org-copy-subtree 1 nil t))
10014 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10015 (find-file-noselect file)))
10016 (setq reversed (org-notes-order-reversed-p))
10017 (save-excursion
10018 (save-restriction
10019 (widen)
10020 (if pos
10021 (progn
10022 (goto-char pos)
10023 (looking-at outline-regexp)
10024 (setq level (org-get-valid-level (funcall outline-level) 1))
10025 (goto-char
10026 (if reversed
10027 (or (outline-next-heading) (point-max))
10028 (or (save-excursion (org-get-next-sibling))
10029 (org-end-of-subtree t t)
10030 (point-max)))))
10031 (setq level 1)
10032 (if (not reversed)
10033 (goto-char (point-max))
10034 (goto-char (point-min))
10035 (or (outline-next-heading) (goto-char (point-max)))))
10036 (if (not (bolp)) (newline))
10037 (org-paste-subtree level)
10038 (when org-log-refile
10039 (org-add-log-setup 'refile nil nil 'findpos
10040 org-log-refile)
10041 (unless (eq org-log-refile 'note)
10042 (save-excursion (org-add-log-note))))
10043 (and org-auto-align-tags (org-set-tags nil t))
10044 (bookmark-set "org-refile-last-stored")
10045 (if (fboundp 'deactivate-mark) (deactivate-mark))
10046 (run-hooks 'org-after-refile-insert-hook))))
10047 (if regionp
10048 (delete-region (point) (+ (point) region-length))
10049 (org-cut-subtree))
10050 (when (featurep 'org-inlinetask)
10051 (org-inlinetask-remove-END-maybe))
10052 (setq org-markers-to-move nil)
10053 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10055 (defun org-refile-goto-last-stored ()
10056 "Go to the location where the last refile was stored."
10057 (interactive)
10058 (bookmark-jump "org-refile-last-stored")
10059 (message "This is the location of the last refile"))
10061 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10062 "Prompt the user for a refile location, using PROMPT."
10063 (let ((org-refile-targets org-refile-targets)
10064 (org-refile-use-outline-path org-refile-use-outline-path))
10065 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10066 (unless org-refile-target-table
10067 (error "No refile targets"))
10068 (let* ((cbuf (current-buffer))
10069 (partial-completion-mode nil)
10070 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10071 (cfunc (if (and org-refile-use-outline-path
10072 org-outline-path-complete-in-steps)
10073 'org-olpath-completing-read
10074 'org-icompleting-read))
10075 (extra (if org-refile-use-outline-path "/" ""))
10076 (filename (and cfn (expand-file-name cfn)))
10077 (tbl (mapcar
10078 (lambda (x)
10079 (if (and (not (member org-refile-use-outline-path
10080 '(file full-file-path)))
10081 (not (equal filename (nth 1 x))))
10082 (cons (concat (car x) extra " ("
10083 (file-name-nondirectory (nth 1 x)) ")")
10084 (cdr x))
10085 (cons (concat (car x) extra) (cdr x))))
10086 org-refile-target-table))
10087 (completion-ignore-case t)
10088 pa answ parent-target child parent old-hist)
10089 (setq old-hist org-refile-history)
10090 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10091 nil 'org-refile-history))
10092 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10093 (if pa
10094 (progn
10095 (when (or (not org-refile-history)
10096 (not (eq old-hist org-refile-history))
10097 (not (equal (car pa) (car org-refile-history))))
10098 (setq org-refile-history
10099 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10100 org-refile-history
10101 (cdr org-refile-history))))
10102 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10103 (pop org-refile-history)))
10105 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10106 (progn
10107 (setq parent (match-string 1 answ)
10108 child (match-string 2 answ))
10109 (setq parent-target (or (assoc parent tbl)
10110 (assoc (concat parent "/") tbl)))
10111 (when (and parent-target
10112 (or (eq new-nodes t)
10113 (and (eq new-nodes 'confirm)
10114 (y-or-n-p (format "Create new node \"%s\"? "
10115 child)))))
10116 (org-refile-new-child parent-target child)))
10117 (error "Invalid target location")))))
10119 (defun org-refile-new-child (parent-target child)
10120 "Use refile target PARENT-TARGET to add new CHILD below it."
10121 (unless parent-target
10122 (error "Cannot find parent for new node"))
10123 (let ((file (nth 1 parent-target))
10124 (pos (nth 3 parent-target))
10125 level)
10126 (with-current-buffer (or (find-buffer-visiting file)
10127 (find-file-noselect file))
10128 (save-excursion
10129 (save-restriction
10130 (widen)
10131 (if pos
10132 (goto-char pos)
10133 (goto-char (point-max))
10134 (if (not (bolp)) (newline)))
10135 (when (looking-at outline-regexp)
10136 (setq level (funcall outline-level))
10137 (org-end-of-subtree t t))
10138 (org-back-over-empty-lines)
10139 (insert "\n" (make-string
10140 (if pos (org-get-valid-level level 1) 1) ?*)
10141 " " child "\n")
10142 (beginning-of-line 0)
10143 (list (concat (car parent-target) "/" child) file "" (point)))))))
10145 (defun org-olpath-completing-read (prompt collection &rest args)
10146 "Read an outline path like a file name."
10147 (let ((thetable collection)
10148 (org-completion-use-ido nil) ; does not work with ido.
10149 (org-completion-use-iswitchb nil)) ; or iswitchb
10150 (apply
10151 'org-icompleting-read prompt
10152 (lambda (string predicate &optional flag)
10153 (let (rtn r f (l (length string)))
10154 (cond
10155 ((eq flag nil)
10156 ;; try completion
10157 (try-completion string thetable))
10158 ((eq flag t)
10159 ;; all-completions
10160 (setq rtn (all-completions string thetable predicate))
10161 (mapcar
10162 (lambda (x)
10163 (setq r (substring x l))
10164 (if (string-match " ([^)]*)$" x)
10165 (setq f (match-string 0 x))
10166 (setq f ""))
10167 (if (string-match "/" r)
10168 (concat string (substring r 0 (match-end 0)) f)
10170 rtn))
10171 ((eq flag 'lambda)
10172 ;; exact match?
10173 (assoc string thetable)))
10175 args)))
10177 ;;;; Dynamic blocks
10179 (defun org-find-dblock (name)
10180 "Find the first dynamic block with name NAME in the buffer.
10181 If not found, stay at current position and return nil."
10182 (let (pos)
10183 (save-excursion
10184 (goto-char (point-min))
10185 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10186 nil t)
10187 (match-beginning 0))))
10188 (if pos (goto-char pos))
10189 pos))
10191 (defconst org-dblock-start-re
10192 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10193 "Matches the start line of a dynamic block, with parameters.")
10195 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10196 "Matches the end of a dynamic block.")
10198 (defun org-create-dblock (plist)
10199 "Create a dynamic block section, with parameters taken from PLIST.
10200 PLIST must contain a :name entry which is used as name of the block."
10201 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10202 (end-of-line 1)
10203 (newline))
10204 (let ((col (current-column))
10205 (name (plist-get plist :name)))
10206 (insert "#+BEGIN: " name)
10207 (while plist
10208 (if (eq (car plist) :name)
10209 (setq plist (cddr plist))
10210 (insert " " (prin1-to-string (pop plist)))))
10211 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10212 (beginning-of-line -2)))
10214 (defun org-prepare-dblock ()
10215 "Prepare dynamic block for refresh.
10216 This empties the block, puts the cursor at the insert position and returns
10217 the property list including an extra property :name with the block name."
10218 (unless (looking-at org-dblock-start-re)
10219 (error "Not at a dynamic block"))
10220 (let* ((begdel (1+ (match-end 0)))
10221 (name (org-no-properties (match-string 1)))
10222 (params (append (list :name name)
10223 (read (concat "(" (match-string 3) ")")))))
10224 (save-excursion
10225 (beginning-of-line 1)
10226 (skip-chars-forward " \t")
10227 (setq params (plist-put params :indentation-column (current-column))))
10228 (unless (re-search-forward org-dblock-end-re nil t)
10229 (error "Dynamic block not terminated"))
10230 (setq params
10231 (append params
10232 (list :content (buffer-substring
10233 begdel (match-beginning 0)))))
10234 (delete-region begdel (match-beginning 0))
10235 (goto-char begdel)
10236 (open-line 1)
10237 params))
10239 (defun org-map-dblocks (&optional command)
10240 "Apply COMMAND to all dynamic blocks in the current buffer.
10241 If COMMAND is not given, use `org-update-dblock'."
10242 (let ((cmd (or command 'org-update-dblock)))
10243 (save-excursion
10244 (goto-char (point-min))
10245 (while (re-search-forward org-dblock-start-re nil t)
10246 (goto-char (match-beginning 0))
10247 (save-excursion
10248 (condition-case nil
10249 (funcall cmd)
10250 (error (message "Error during update of dynamic block"))))
10251 (unless (re-search-forward org-dblock-end-re nil t)
10252 (error "Dynamic block not terminated"))))))
10254 (defun org-dblock-update (&optional arg)
10255 "User command for updating dynamic blocks.
10256 Update the dynamic block at point. With prefix ARG, update all dynamic
10257 blocks in the buffer."
10258 (interactive "P")
10259 (if arg
10260 (org-update-all-dblocks)
10261 (or (looking-at org-dblock-start-re)
10262 (org-beginning-of-dblock))
10263 (org-update-dblock)))
10265 (defun org-update-dblock ()
10266 "Update the dynamic block at point
10267 This means to empty the block, parse for parameters and then call
10268 the correct writing function."
10269 (save-window-excursion
10270 (let* ((pos (point))
10271 (line (org-current-line))
10272 (params (org-prepare-dblock))
10273 (name (plist-get params :name))
10274 (indent (plist-get params :indentation-column))
10275 (cmd (intern (concat "org-dblock-write:" name))))
10276 (message "Updating dynamic block `%s' at line %d..." name line)
10277 (funcall cmd params)
10278 (message "Updating dynamic block `%s' at line %d...done" name line)
10279 (goto-char pos)
10280 (when (and indent (> indent 0))
10281 (setq indent (make-string indent ?\ ))
10282 (save-excursion
10283 (org-beginning-of-dblock)
10284 (forward-line 1)
10285 (while (not (looking-at org-dblock-end-re))
10286 (insert indent)
10287 (beginning-of-line 2))
10288 (when (looking-at org-dblock-end-re)
10289 (and (looking-at "[ \t]+")
10290 (replace-match ""))
10291 (insert indent)))))))
10293 (defun org-beginning-of-dblock ()
10294 "Find the beginning of the dynamic block at point.
10295 Error if there is no such block at point."
10296 (let ((pos (point))
10297 beg)
10298 (end-of-line 1)
10299 (if (and (re-search-backward org-dblock-start-re nil t)
10300 (setq beg (match-beginning 0))
10301 (re-search-forward org-dblock-end-re nil t)
10302 (> (match-end 0) pos))
10303 (goto-char beg)
10304 (goto-char pos)
10305 (error "Not in a dynamic block"))))
10307 (defun org-update-all-dblocks ()
10308 "Update all dynamic blocks in the buffer.
10309 This function can be used in a hook."
10310 (when (org-mode-p)
10311 (org-map-dblocks 'org-update-dblock)))
10314 ;;;; Completion
10316 (defconst org-additional-option-like-keywords
10317 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10318 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10319 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10320 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10321 "BEGIN:" "END:"
10322 "ORGTBL" "TBLFM:" "TBLNAME:"
10323 "BEGIN_EXAMPLE" "END_EXAMPLE"
10324 "BEGIN_QUOTE" "END_QUOTE"
10325 "BEGIN_VERSE" "END_VERSE"
10326 "BEGIN_CENTER" "END_CENTER"
10327 "BEGIN_SRC" "END_SRC"
10328 "CATEGORY" "COLUMNS"
10329 "CAPTION" "LABEL"
10330 "SETUPFILE"
10331 "BIND"
10332 "MACRO"))
10334 (defcustom org-structure-template-alist
10336 ("s" "#+begin_src ?\n\n#+end_src"
10337 "<src lang=\"?\">\n\n</src>")
10338 ("e" "#+begin_example\n?\n#+end_example"
10339 "<example>\n?\n</example>")
10340 ("q" "#+begin_quote\n?\n#+end_quote"
10341 "<quote>\n?\n</quote>")
10342 ("v" "#+begin_verse\n?\n#+end_verse"
10343 "<verse>\n?\n/verse>")
10344 ("c" "#+begin_center\n?\n#+end_center"
10345 "<center>\n?\n/center>")
10346 ("l" "#+begin_latex\n?\n#+end_latex"
10347 "<literal style=\"latex\">\n?\n</literal>")
10348 ("L" "#+latex: "
10349 "<literal style=\"latex\">?</literal>")
10350 ("h" "#+begin_html\n?\n#+end_html"
10351 "<literal style=\"html\">\n?\n</literal>")
10352 ("H" "#+html: "
10353 "<literal style=\"html\">?</literal>")
10354 ("a" "#+begin_ascii\n?\n#+end_ascii")
10355 ("A" "#+ascii: ")
10356 ("i" "#+include %file ?"
10357 "<include file=%file markup=\"?\">")
10359 "Structure completion elements.
10360 This is a list of abbreviation keys and values. The value gets inserted
10361 if you type `<' followed by the key and then press the completion key,
10362 usually `M-TAB'. %file will be replaced by a file name after prompting
10363 for the file using completion.
10364 There are two templates for each key, the first uses the original Org syntax,
10365 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10366 the default when the /org-mtags.el/ module has been loaded. See also the
10367 variable `org-mtags-prefer-muse-templates'.
10368 This is an experimental feature, it is undecided if it is going to stay in."
10369 :group 'org-completion
10370 :type '(repeat
10371 (string :tag "Key")
10372 (string :tag "Template")
10373 (string :tag "Muse Template")))
10375 (defun org-try-structure-completion ()
10376 "Try to complete a structure template before point.
10377 This looks for strings like \"<e\" on an otherwise empty line and
10378 expands them."
10379 (let ((l (buffer-substring (point-at-bol) (point)))
10381 (when (and (looking-at "[ \t]*$")
10382 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10383 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10384 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10385 (match-beginning 1)) a)
10386 t)))
10388 (defun org-complete-expand-structure-template (start cell)
10389 "Expand a structure template."
10390 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10391 (rpl (nth (if musep 2 1) cell))
10392 (ind ""))
10393 (delete-region start (point))
10394 (when (string-match "\\`#\\+" rpl)
10395 (cond
10396 ((bolp))
10397 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10398 (setq ind (buffer-substring (point-at-bol) (point))))
10399 (t (newline))))
10400 (setq start (point))
10401 (if (string-match "%file" rpl)
10402 (setq rpl (replace-match
10403 (concat
10404 "\""
10405 (save-match-data
10406 (abbreviate-file-name (read-file-name "Include file: ")))
10407 "\"")
10408 t t rpl)))
10409 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10410 (concat "\n" ind)))
10411 (insert rpl)
10412 (if (re-search-backward "\\?" start t) (delete-char 1))))
10415 (defun org-complete (&optional arg)
10416 "Perform completion on word at point.
10417 At the beginning of a headline, this completes TODO keywords as given in
10418 `org-todo-keywords'.
10419 If the current word is preceded by a backslash, completes the TeX symbols
10420 that are supported for HTML support.
10421 If the current word is preceded by \"#+\", completes special words for
10422 setting file options.
10423 In the line after \"#+STARTUP:, complete valid keywords.\"
10424 At all other locations, this simply calls the value of
10425 `org-completion-fallback-command'."
10426 (interactive "P")
10427 (org-without-partial-completion
10428 (catch 'exit
10429 (let* ((a nil)
10430 (end (point))
10431 (beg1 (save-excursion
10432 (skip-chars-backward (org-re "[:alnum:]_@"))
10433 (point)))
10434 (beg (save-excursion
10435 (skip-chars-backward "a-zA-Z0-9_:$")
10436 (point)))
10437 (confirm (lambda (x) (stringp (car x))))
10438 (searchhead (equal (char-before beg) ?*))
10439 (struct
10440 (when (and (member (char-before beg1) '(?. ?<))
10441 (setq a (assoc (buffer-substring beg1 (point))
10442 org-structure-template-alist)))
10443 (org-complete-expand-structure-template (1- beg1) a)
10444 (throw 'exit t)))
10445 (tag (and (equal (char-before beg1) ?:)
10446 (equal (char-after (point-at-bol)) ?*)))
10447 (prop (and (equal (char-before beg1) ?:)
10448 (not (equal (char-after (point-at-bol)) ?*))))
10449 (texp (equal (char-before beg) ?\\))
10450 (link (equal (char-before beg) ?\[))
10451 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10452 beg)
10453 "#+"))
10454 (startup (string-match "^#\\+STARTUP:.*"
10455 (buffer-substring (point-at-bol) (point))))
10456 (completion-ignore-case opt)
10457 (type nil)
10458 (tbl nil)
10459 (table (cond
10460 (opt
10461 (setq type :opt)
10462 (require 'org-exp)
10463 (append
10464 (delq nil
10465 (mapcar
10466 (lambda (x)
10467 (if (string-match
10468 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10469 (cons (match-string 2 x)
10470 (match-string 1 x))))
10471 (org-split-string (org-get-current-options) "\n")))
10472 (mapcar 'list org-additional-option-like-keywords)))
10473 (startup
10474 (setq type :startup)
10475 org-startup-options)
10476 (link (append org-link-abbrev-alist-local
10477 org-link-abbrev-alist))
10478 (texp
10479 (setq type :tex)
10480 (append org-entities-user org-entities))
10481 ((string-match "\\`\\*+[ \t]+\\'"
10482 (buffer-substring (point-at-bol) beg))
10483 (setq type :todo)
10484 (mapcar 'list org-todo-keywords-1))
10485 (searchhead
10486 (setq type :searchhead)
10487 (save-excursion
10488 (goto-char (point-min))
10489 (while (re-search-forward org-todo-line-regexp nil t)
10490 (push (list
10491 (org-make-org-heading-search-string
10492 (match-string 3) t))
10493 tbl)))
10494 tbl)
10495 (tag (setq type :tag beg beg1)
10496 (or org-tag-alist (org-get-buffer-tags)))
10497 (prop (setq type :prop beg beg1)
10498 (mapcar 'list (org-buffer-property-keys nil t t)))
10499 (t (progn
10500 (call-interactively org-completion-fallback-command)
10501 (throw 'exit nil)))))
10502 (pattern (buffer-substring-no-properties beg end))
10503 (completion (try-completion pattern table confirm)))
10504 (cond ((eq completion t)
10505 (if (not (assoc (upcase pattern) table))
10506 (message "Already complete")
10507 (if (and (equal type :opt)
10508 (not (member (car (assoc (upcase pattern) table))
10509 org-additional-option-like-keywords)))
10510 (insert (substring (cdr (assoc (upcase pattern) table))
10511 (length pattern)))
10512 (if (memq type '(:tag :prop)) (insert ":")))))
10513 ((null completion)
10514 (message "Can't find completion for \"%s\"" pattern)
10515 (ding))
10516 ((not (string= pattern completion))
10517 (delete-region beg end)
10518 (if (string-match " +$" completion)
10519 (setq completion (replace-match "" t t completion)))
10520 (insert completion)
10521 (if (get-buffer-window "*Completions*")
10522 (delete-window (get-buffer-window "*Completions*")))
10523 (if (assoc completion table)
10524 (if (eq type :todo) (insert " ")
10525 (if (memq type '(:tag :prop)) (insert ":"))))
10526 (if (and (equal type :opt) (assoc completion table))
10527 (message "%s" (substitute-command-keys
10528 "Press \\[org-complete] again to insert example settings"))))
10530 (message "Making completion list...")
10531 (let ((list (sort (all-completions pattern table confirm)
10532 'string<)))
10533 (with-output-to-temp-buffer "*Completions*"
10534 (condition-case nil
10535 ;; Protection needed for XEmacs and emacs 21
10536 (display-completion-list list pattern)
10537 (error (display-completion-list list)))))
10538 (message "Making completion list...%s" "done")))))))
10540 ;;;; TODO, DEADLINE, Comments
10542 (defun org-toggle-comment ()
10543 "Change the COMMENT state of an entry."
10544 (interactive)
10545 (save-excursion
10546 (org-back-to-heading)
10547 (let (case-fold-search)
10548 (if (looking-at (concat outline-regexp
10549 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10550 (replace-match "" t t nil 1)
10551 (if (looking-at outline-regexp)
10552 (progn
10553 (goto-char (match-end 0))
10554 (insert org-comment-string " ")))))))
10556 (defvar org-last-todo-state-is-todo nil
10557 "This is non-nil when the last TODO state change led to a TODO state.
10558 If the last change removed the TODO tag or switched to DONE, then
10559 this is nil.")
10561 (defvar org-setting-tags nil) ; dynamically skipped
10563 (defun org-parse-local-options (string var)
10564 "Parse STRING for startup setting relevant for variable VAR."
10565 (let ((rtn (symbol-value var))
10566 e opts)
10567 (save-match-data
10568 (if (or (not string) (not (string-match "\\S-" string)))
10570 (setq opts (delq nil (mapcar (lambda (x)
10571 (setq e (assoc x org-startup-options))
10572 (if (eq (nth 1 e) var) e nil))
10573 (org-split-string string "[ \t]+"))))
10574 (if (not opts)
10576 (setq rtn nil)
10577 (while (setq e (pop opts))
10578 (if (not (nth 3 e))
10579 (setq rtn (nth 2 e))
10580 (if (not (listp rtn)) (setq rtn nil))
10581 (push (nth 2 e) rtn)))
10582 rtn)))))
10584 (defvar org-todo-setup-filter-hook nil
10585 "Hook for functions that pre-filter todo specs.
10587 Each function takes a todo spec and returns either `nil' or the spec
10588 transformed into canonical form." )
10590 (defvar org-todo-get-default-hook nil
10591 "Hook for functions that get a default item for todo.
10593 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10594 `nil' or a string to be used for the todo mark." )
10596 (defvar org-agenda-headline-snapshot-before-repeat)
10598 (defun org-todo (&optional arg)
10599 "Change the TODO state of an item.
10600 The state of an item is given by a keyword at the start of the heading,
10601 like
10602 *** TODO Write paper
10603 *** DONE Call mom
10605 The different keywords are specified in the variable `org-todo-keywords'.
10606 By default the available states are \"TODO\" and \"DONE\".
10607 So for this example: when the item starts with TODO, it is changed to DONE.
10608 When it starts with DONE, the DONE is removed. And when neither TODO nor
10609 DONE are present, add TODO at the beginning of the heading.
10611 With C-u prefix arg, use completion to determine the new state.
10612 With numeric prefix arg, switch to that state.
10613 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10614 With a triple C-u prefix, circumvent any state blocking.
10616 For calling through lisp, arg is also interpreted in the following way:
10617 'none -> empty state
10618 \"\"(empty string) -> switch to empty state
10619 'done -> switch to DONE
10620 'nextset -> switch to the next set of keywords
10621 'previousset -> switch to the previous set of keywords
10622 \"WAITING\" -> switch to the specified keyword, but only if it
10623 really is a member of `org-todo-keywords'."
10624 (interactive "P")
10625 (if (equal arg '(16)) (setq arg 'nextset))
10626 (let ((org-blocker-hook org-blocker-hook)
10627 (case-fold-search nil))
10628 (when (equal arg '(64))
10629 (setq arg nil org-blocker-hook nil))
10630 (when (and org-blocker-hook
10631 (or org-inhibit-blocking
10632 (org-entry-get nil "NOBLOCKING")))
10633 (setq org-blocker-hook nil))
10634 (save-excursion
10635 (catch 'exit
10636 (org-back-to-heading t)
10637 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10638 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10639 (looking-at " *"))
10640 (let* ((match-data (match-data))
10641 (startpos (point-at-bol))
10642 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10643 (org-log-done org-log-done)
10644 (org-log-repeat org-log-repeat)
10645 (org-todo-log-states org-todo-log-states)
10646 (this (match-string 1))
10647 (hl-pos (match-beginning 0))
10648 (head (org-get-todo-sequence-head this))
10649 (ass (assoc head org-todo-kwd-alist))
10650 (interpret (nth 1 ass))
10651 (done-word (nth 3 ass))
10652 (final-done-word (nth 4 ass))
10653 (last-state (or this ""))
10654 (completion-ignore-case t)
10655 (member (member this org-todo-keywords-1))
10656 (tail (cdr member))
10657 (state (cond
10658 ((and org-todo-key-trigger
10659 (or (and (equal arg '(4))
10660 (eq org-use-fast-todo-selection 'prefix))
10661 (and (not arg) org-use-fast-todo-selection
10662 (not (eq org-use-fast-todo-selection
10663 'prefix)))))
10664 ;; Use fast selection
10665 (org-fast-todo-selection))
10666 ((and (equal arg '(4))
10667 (or (not org-use-fast-todo-selection)
10668 (not org-todo-key-trigger)))
10669 ;; Read a state with completion
10670 (org-icompleting-read
10671 "State: " (mapcar (lambda(x) (list x))
10672 org-todo-keywords-1)
10673 nil t))
10674 ((eq arg 'right)
10675 (if this
10676 (if tail (car tail) nil)
10677 (car org-todo-keywords-1)))
10678 ((eq arg 'left)
10679 (if (equal member org-todo-keywords-1)
10681 (if this
10682 (nth (- (length org-todo-keywords-1)
10683 (length tail) 2)
10684 org-todo-keywords-1)
10685 (org-last org-todo-keywords-1))))
10686 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10687 (setq arg nil))) ; hack to fall back to cycling
10688 (arg
10689 ;; user or caller requests a specific state
10690 (cond
10691 ((equal arg "") nil)
10692 ((eq arg 'none) nil)
10693 ((eq arg 'done) (or done-word (car org-done-keywords)))
10694 ((eq arg 'nextset)
10695 (or (car (cdr (member head org-todo-heads)))
10696 (car org-todo-heads)))
10697 ((eq arg 'previousset)
10698 (let ((org-todo-heads (reverse org-todo-heads)))
10699 (or (car (cdr (member head org-todo-heads)))
10700 (car org-todo-heads))))
10701 ((car (member arg org-todo-keywords-1)))
10702 ((stringp arg)
10703 (error "State `%s' not valid in this file" arg))
10704 ((nth (1- (prefix-numeric-value arg))
10705 org-todo-keywords-1))))
10706 ((null member) (or head (car org-todo-keywords-1)))
10707 ((equal this final-done-word) nil) ;; -> make empty
10708 ((null tail) nil) ;; -> first entry
10709 ((memq interpret '(type priority))
10710 (if (eq this-command last-command)
10711 (car tail)
10712 (if (> (length tail) 0)
10713 (or done-word (car org-done-keywords))
10714 nil)))
10716 (car tail))))
10717 (state (or
10718 (run-hook-with-args-until-success
10719 'org-todo-get-default-hook state last-state)
10720 state))
10721 (next (if state (concat " " state " ") " "))
10722 (change-plist (list :type 'todo-state-change :from this :to state
10723 :position startpos))
10724 dolog now-done-p)
10725 (when org-blocker-hook
10726 (setq org-last-todo-state-is-todo
10727 (not (member this org-done-keywords)))
10728 (unless (save-excursion
10729 (save-match-data
10730 (run-hook-with-args-until-failure
10731 'org-blocker-hook change-plist)))
10732 (if (interactive-p)
10733 (error "TODO state change from %s to %s blocked" this state)
10734 ;; fail silently
10735 (message "TODO state change from %s to %s blocked" this state)
10736 (throw 'exit nil))))
10737 (store-match-data match-data)
10738 (replace-match next t t)
10739 (unless (pos-visible-in-window-p hl-pos)
10740 (message "TODO state changed to %s" (org-trim next)))
10741 (unless head
10742 (setq head (org-get-todo-sequence-head state)
10743 ass (assoc head org-todo-kwd-alist)
10744 interpret (nth 1 ass)
10745 done-word (nth 3 ass)
10746 final-done-word (nth 4 ass)))
10747 (when (memq arg '(nextset previousset))
10748 (message "Keyword-Set %d/%d: %s"
10749 (- (length org-todo-sets) -1
10750 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10751 (length org-todo-sets)
10752 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10753 (setq org-last-todo-state-is-todo
10754 (not (member state org-done-keywords)))
10755 (setq now-done-p (and (member state org-done-keywords)
10756 (not (member this org-done-keywords))))
10757 (and logging (org-local-logging logging))
10758 (when (and (or org-todo-log-states org-log-done)
10759 (not (eq org-inhibit-logging t))
10760 (not (memq arg '(nextset previousset))))
10761 ;; we need to look at recording a time and note
10762 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10763 (nth 2 (assoc this org-todo-log-states))))
10764 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10765 (setq dolog 'time))
10766 (when (and state
10767 (member state org-not-done-keywords)
10768 (not (member this org-not-done-keywords)))
10769 ;; This is now a todo state and was not one before
10770 ;; If there was a CLOSED time stamp, get rid of it.
10771 (org-add-planning-info nil nil 'closed))
10772 (when (and now-done-p org-log-done)
10773 ;; It is now done, and it was not done before
10774 (org-add-planning-info 'closed (org-current-time))
10775 (if (and (not dolog) (eq 'note org-log-done))
10776 (org-add-log-setup 'done state this 'findpos 'note)))
10777 (when (and state dolog)
10778 ;; This is a non-nil state, and we need to log it
10779 (org-add-log-setup 'state state this 'findpos dolog)))
10780 ;; Fixup tag positioning
10781 (org-todo-trigger-tag-changes state)
10782 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10783 (when org-provide-todo-statistics
10784 (org-update-parent-todo-statistics))
10785 (run-hooks 'org-after-todo-state-change-hook)
10786 (if (and arg (not (member state org-done-keywords)))
10787 (setq head (org-get-todo-sequence-head state)))
10788 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10789 ;; Do we need to trigger a repeat?
10790 (when now-done-p
10791 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10792 ;; This is for the agenda, take a snapshot of the headline.
10793 (save-match-data
10794 (setq org-agenda-headline-snapshot-before-repeat
10795 (org-get-heading))))
10796 (org-auto-repeat-maybe state))
10797 ;; Fixup cursor location if close to the keyword
10798 (if (and (outline-on-heading-p)
10799 (not (bolp))
10800 (save-excursion (beginning-of-line 1)
10801 (looking-at org-todo-line-regexp))
10802 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10803 (progn
10804 (goto-char (or (match-end 2) (match-end 1)))
10805 (and (looking-at " ") (just-one-space))))
10806 (when org-trigger-hook
10807 (save-excursion
10808 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10810 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10811 "Block turning an entry into a TODO, using the hierarchy.
10812 This checks whether the current task should be blocked from state
10813 changes. Such blocking occurs when:
10815 1. The task has children which are not all in a completed state.
10817 2. A task has a parent with the property :ORDERED:, and there
10818 are siblings prior to the current task with incomplete
10819 status.
10821 3. The parent of the task is blocked because it has siblings that should
10822 be done first, or is child of a block grandparent TODO entry."
10824 (if (not org-enforce-todo-dependencies)
10825 t ; if locally turned off don't block
10826 (catch 'dont-block
10827 ;; If this is not a todo state change, or if this entry is already DONE,
10828 ;; do not block
10829 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10830 (member (plist-get change-plist :from)
10831 (cons 'done org-done-keywords))
10832 (member (plist-get change-plist :to)
10833 (cons 'todo org-not-done-keywords))
10834 (not (plist-get change-plist :to)))
10835 (throw 'dont-block t))
10836 ;; If this task has children, and any are undone, it's blocked
10837 (save-excursion
10838 (org-back-to-heading t)
10839 (let ((this-level (funcall outline-level)))
10840 (outline-next-heading)
10841 (let ((child-level (funcall outline-level)))
10842 (while (and (not (eobp))
10843 (> child-level this-level))
10844 ;; this todo has children, check whether they are all
10845 ;; completed
10846 (if (and (not (org-entry-is-done-p))
10847 (org-entry-is-todo-p))
10848 (throw 'dont-block nil))
10849 (outline-next-heading)
10850 (setq child-level (funcall outline-level))))))
10851 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10852 ;; any previous siblings are undone, it's blocked
10853 (save-excursion
10854 (org-back-to-heading t)
10855 (let* ((pos (point))
10856 (parent-pos (and (org-up-heading-safe) (point))))
10857 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10858 (when (and (org-entry-get (point) "ORDERED")
10859 (forward-line 1)
10860 (re-search-forward org-not-done-heading-regexp pos t))
10861 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10862 ;; Search further up the hierarchy, to see if an anchestor is blocked
10863 (while t
10864 (goto-char parent-pos)
10865 (if (not (looking-at org-not-done-heading-regexp))
10866 (throw 'dont-block t)) ; do not block, parent is not a TODO
10867 (setq pos (point))
10868 (setq parent-pos (and (org-up-heading-safe) (point)))
10869 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10870 (when (and (org-entry-get (point) "ORDERED")
10871 (forward-line 1)
10872 (re-search-forward org-not-done-heading-regexp pos t))
10873 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10875 (defcustom org-track-ordered-property-with-tag nil
10876 "Should the ORDERED property also be shown as a tag?
10877 The ORDERED property decides if an entry should require subtasks to be
10878 completed in sequence. Since a property is not very visible, setting
10879 this option means that toggling the ORDERED property with the command
10880 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10881 not relevant for the behavior, but it makes things more visible.
10883 Note that toggling the tag with tags commands will not change the property
10884 and therefore not influence behavior!
10886 This can be t, meaning the tag ORDERED should be used, It can also be a
10887 string to select a different tag for this task."
10888 :group 'org-todo
10889 :type '(choice
10890 (const :tag "No tracking" nil)
10891 (const :tag "Track with ORDERED tag" t)
10892 (string :tag "Use other tag")))
10894 (defun org-toggle-ordered-property ()
10895 "Toggle the ORDERED property of the current entry.
10896 For better visibility, you can track the value of this property with a tag.
10897 See variable `org-track-ordered-property-with-tag'."
10898 (interactive)
10899 (let* ((t1 org-track-ordered-property-with-tag)
10900 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10901 (save-excursion
10902 (org-back-to-heading)
10903 (if (org-entry-get nil "ORDERED")
10904 (progn
10905 (org-delete-property "ORDERED")
10906 (and tag (org-toggle-tag tag 'off))
10907 (message "Subtasks can be completed in arbitrary order"))
10908 (org-entry-put nil "ORDERED" "t")
10909 (and tag (org-toggle-tag tag 'on))
10910 (message "Subtasks must be completed in sequence")))))
10912 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10913 (defun org-block-todo-from-checkboxes (change-plist)
10914 "Block turning an entry into a TODO, using checkboxes.
10915 This checks whether the current task should be blocked from state
10916 changes because there are unchecked boxes in this entry."
10917 (if (not org-enforce-todo-checkbox-dependencies)
10918 t ; if locally turned off don't block
10919 (catch 'dont-block
10920 ;; If this is not a todo state change, or if this entry is already DONE,
10921 ;; do not block
10922 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10923 (member (plist-get change-plist :from)
10924 (cons 'done org-done-keywords))
10925 (member (plist-get change-plist :to)
10926 (cons 'todo org-not-done-keywords))
10927 (not (plist-get change-plist :to)))
10928 (throw 'dont-block t))
10929 ;; If this task has checkboxes that are not checked, it's blocked
10930 (save-excursion
10931 (org-back-to-heading t)
10932 (let ((beg (point)) end)
10933 (outline-next-heading)
10934 (setq end (point))
10935 (goto-char beg)
10936 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10937 end t)
10938 (progn
10939 (if (boundp 'org-blocked-by-checkboxes)
10940 (setq org-blocked-by-checkboxes t))
10941 (throw 'dont-block nil)))))
10942 t))) ; do not block
10944 (defun org-entry-blocked-p ()
10945 "Is the current entry blocked?"
10946 (if (org-entry-get nil "NOBLOCKING")
10947 nil ;; Never block this entry
10948 (not
10949 (run-hook-with-args-until-failure
10950 'org-blocker-hook
10951 (list :type 'todo-state-change
10952 :position (point)
10953 :from 'todo
10954 :to 'done)))))
10956 (defun org-update-statistics-cookies (all)
10957 "Update the statistics cookie, either from TODO or from checkboxes.
10958 This should be called with the cursor in a line with a statistics cookie."
10959 (interactive "P")
10960 (if all
10961 (progn
10962 (org-update-checkbox-count 'all)
10963 (org-map-entries 'org-update-parent-todo-statistics))
10964 (if (not (org-on-heading-p))
10965 (org-update-checkbox-count)
10966 (let ((pos (move-marker (make-marker) (point)))
10967 end l1 l2)
10968 (ignore-errors (org-back-to-heading t))
10969 (if (not (org-on-heading-p))
10970 (org-update-checkbox-count)
10971 (setq l1 (org-outline-level))
10972 (setq end (save-excursion
10973 (outline-next-heading)
10974 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10975 (point)))
10976 (if (and (save-excursion
10977 (re-search-forward
10978 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10979 (not (save-excursion (re-search-forward
10980 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10981 (org-update-checkbox-count)
10982 (if (and l2 (> l2 l1))
10983 (progn
10984 (goto-char end)
10985 (org-update-parent-todo-statistics))
10986 (goto-char pos)
10987 (beginning-of-line 1)
10988 (while (re-search-forward
10989 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10990 (point-at-eol) t)
10991 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10992 (goto-char pos)
10993 (move-marker pos nil)))))
10995 (defvar org-entry-property-inherited-from) ;; defined below
10996 (defun org-update-parent-todo-statistics ()
10997 "Update any statistics cookie in the parent of the current headline.
10998 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10999 the entire subtree and this will travel up the hierarchy and update
11000 statistics everywhere."
11001 (interactive)
11002 (let* ((lim 0) prop
11003 (recursive (or (not org-hierarchical-todo-statistics)
11004 (string-match
11005 "\\<recursive\\>"
11006 (or (setq prop (org-entry-get
11007 nil "COOKIE_DATA" 'inherit)) ""))))
11008 (lim (or (and prop (marker-position
11009 org-entry-property-inherited-from))
11010 lim))
11011 (first t)
11012 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11013 level ltoggle l1 new ndel
11014 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11015 (catch 'exit
11016 (save-excursion
11017 (beginning-of-line 1)
11018 (if (org-at-heading-p)
11019 (setq ltoggle (funcall outline-level))
11020 (error "This should not happen"))
11021 (while (and (setq level (org-up-heading-safe))
11022 (or recursive first)
11023 (>= (point) lim))
11024 (setq first nil cookie-present nil)
11025 (unless (and level
11026 (not (string-match
11027 "\\<checkbox\\>"
11028 (downcase
11029 (or (org-entry-get
11030 nil "COOKIE_DATA")
11031 "")))))
11032 (throw 'exit nil))
11033 (while (re-search-forward box-re (point-at-eol) t)
11034 (setq cnt-all 0 cnt-done 0 cookie-present t)
11035 (setq is-percent (match-end 2))
11036 (save-match-data
11037 (unless (outline-next-heading) (throw 'exit nil))
11038 (while (and (looking-at org-complex-heading-regexp)
11039 (> (setq l1 (length (match-string 1))) level))
11040 (setq kwd (and (or recursive (= l1 ltoggle))
11041 (match-string 2)))
11042 (if (or (eq org-provide-todo-statistics 'all-headlines)
11043 (and (listp org-provide-todo-statistics)
11044 (or (member kwd org-provide-todo-statistics)
11045 (member kwd org-done-keywords))))
11046 (setq cnt-all (1+ cnt-all))
11047 (if (eq org-provide-todo-statistics t)
11048 (and kwd (setq cnt-all (1+ cnt-all)))))
11049 (and (member kwd org-done-keywords)
11050 (setq cnt-done (1+ cnt-done)))
11051 (outline-next-heading)))
11052 (setq new
11053 (if is-percent
11054 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11055 (format "[%d/%d]" cnt-done cnt-all))
11056 ndel (- (match-end 0) (match-beginning 0)))
11057 (goto-char (match-beginning 0))
11058 (insert new)
11059 (delete-region (point) (+ (point) ndel)))
11060 (when cookie-present
11061 (run-hook-with-args 'org-after-todo-statistics-hook
11062 cnt-done (- cnt-all cnt-done))))))
11063 (run-hooks 'org-todo-statistics-hook)))
11065 (defvar org-after-todo-statistics-hook nil
11066 "Hook that is called after a TODO statistics cookie has been updated.
11067 Each function is called with two arguments: the number of not-done entries
11068 and the number of done entries.
11070 For example, the following function, when added to this hook, will switch
11071 an entry to DONE when all children are done, and back to TODO when new
11072 entries are set to a TODO status. Note that this hook is only called
11073 when there is a statistics cookie in the headline!
11075 (defun org-summary-todo (n-done n-not-done)
11076 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11077 (let (org-log-done org-log-states) ; turn off logging
11078 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11081 (defvar org-todo-statistics-hook nil
11082 "Hook that is run whenever Org thinks TODO statistics should be updated.
11083 This hook runs even if there is no statistics cookie present, in which case
11084 `org-after-todo-statistics-hook' would not run.")
11086 (defun org-todo-trigger-tag-changes (state)
11087 "Apply the changes defined in `org-todo-state-tags-triggers'."
11088 (let ((l org-todo-state-tags-triggers)
11089 changes)
11090 (when (or (not state) (equal state ""))
11091 (setq changes (append changes (cdr (assoc "" l)))))
11092 (when (and (stringp state) (> (length state) 0))
11093 (setq changes (append changes (cdr (assoc state l)))))
11094 (when (member state org-not-done-keywords)
11095 (setq changes (append changes (cdr (assoc 'todo l)))))
11096 (when (member state org-done-keywords)
11097 (setq changes (append changes (cdr (assoc 'done l)))))
11098 (dolist (c changes)
11099 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11101 (defun org-local-logging (value)
11102 "Get logging settings from a property VALUE."
11103 (let* (words w a)
11104 ;; directly set the variables, they are already local.
11105 (setq org-log-done nil
11106 org-log-repeat nil
11107 org-todo-log-states nil)
11108 (setq words (org-split-string value))
11109 (while (setq w (pop words))
11110 (cond
11111 ((setq a (assoc w org-startup-options))
11112 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11113 (set (nth 1 a) (nth 2 a))))
11114 ((setq a (org-extract-log-state-settings w))
11115 (and (member (car a) org-todo-keywords-1)
11116 (push a org-todo-log-states)))))))
11118 (defun org-get-todo-sequence-head (kwd)
11119 "Return the head of the TODO sequence to which KWD belongs.
11120 If KWD is not set, check if there is a text property remembering the
11121 right sequence."
11122 (let (p)
11123 (cond
11124 ((not kwd)
11125 (or (get-text-property (point-at-bol) 'org-todo-head)
11126 (progn
11127 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11128 nil (point-at-eol)))
11129 (get-text-property p 'org-todo-head))))
11130 ((not (member kwd org-todo-keywords-1))
11131 (car org-todo-keywords-1))
11132 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11134 (defun org-fast-todo-selection ()
11135 "Fast TODO keyword selection with single keys.
11136 Returns the new TODO keyword, or nil if no state change should occur."
11137 (let* ((fulltable org-todo-key-alist)
11138 (done-keywords org-done-keywords) ;; needed for the faces.
11139 (maxlen (apply 'max (mapcar
11140 (lambda (x)
11141 (if (stringp (car x)) (string-width (car x)) 0))
11142 fulltable)))
11143 (expert nil)
11144 (fwidth (+ maxlen 3 1 3))
11145 (ncol (/ (- (window-width) 4) fwidth))
11146 tg cnt e c tbl
11147 groups ingroup)
11148 (save-excursion
11149 (save-window-excursion
11150 (if expert
11151 (set-buffer (get-buffer-create " *Org todo*"))
11152 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11153 (erase-buffer)
11154 (org-set-local 'org-done-keywords done-keywords)
11155 (setq tbl fulltable cnt 0)
11156 (while (setq e (pop tbl))
11157 (cond
11158 ((equal e '(:startgroup))
11159 (push '() groups) (setq ingroup t)
11160 (when (not (= cnt 0))
11161 (setq cnt 0)
11162 (insert "\n"))
11163 (insert "{ "))
11164 ((equal e '(:endgroup))
11165 (setq ingroup nil cnt 0)
11166 (insert "}\n"))
11167 ((equal e '(:newline))
11168 (when (not (= cnt 0))
11169 (setq cnt 0)
11170 (insert "\n")
11171 (setq e (car tbl))
11172 (while (equal (car tbl) '(:newline))
11173 (insert "\n")
11174 (setq tbl (cdr tbl)))))
11176 (setq tg (car e) c (cdr e))
11177 (if ingroup (push tg (car groups)))
11178 (setq tg (org-add-props tg nil 'face
11179 (org-get-todo-face tg)))
11180 (if (and (= cnt 0) (not ingroup)) (insert " "))
11181 (insert "[" c "] " tg (make-string
11182 (- fwidth 4 (length tg)) ?\ ))
11183 (when (= (setq cnt (1+ cnt)) ncol)
11184 (insert "\n")
11185 (if ingroup (insert " "))
11186 (setq cnt 0)))))
11187 (insert "\n")
11188 (goto-char (point-min))
11189 (if (not expert) (org-fit-window-to-buffer))
11190 (message "[a-z..]:Set [SPC]:clear")
11191 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11192 (cond
11193 ((or (= c ?\C-g)
11194 (and (= c ?q) (not (rassoc c fulltable))))
11195 (setq quit-flag t))
11196 ((= c ?\ ) nil)
11197 ((setq e (rassoc c fulltable) tg (car e))
11199 (t (setq quit-flag t)))))))
11201 (defun org-entry-is-todo-p ()
11202 (member (org-get-todo-state) org-not-done-keywords))
11204 (defun org-entry-is-done-p ()
11205 (member (org-get-todo-state) org-done-keywords))
11207 (defun org-get-todo-state ()
11208 (save-excursion
11209 (org-back-to-heading t)
11210 (and (looking-at org-todo-line-regexp)
11211 (match-end 2)
11212 (match-string 2))))
11214 (defun org-at-date-range-p (&optional inactive-ok)
11215 "Is the cursor inside a date range?"
11216 (interactive)
11217 (save-excursion
11218 (catch 'exit
11219 (let ((pos (point)))
11220 (skip-chars-backward "^[<\r\n")
11221 (skip-chars-backward "<[")
11222 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11223 (>= (match-end 0) pos)
11224 (throw 'exit t))
11225 (skip-chars-backward "^<[\r\n")
11226 (skip-chars-backward "<[")
11227 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11228 (>= (match-end 0) pos)
11229 (throw 'exit t)))
11230 nil)))
11232 (defun org-get-repeat (&optional tagline)
11233 "Check if there is a deadline/schedule with repeater in this entry."
11234 (save-match-data
11235 (save-excursion
11236 (org-back-to-heading t)
11237 (and (re-search-forward (if tagline
11238 (concat tagline "\\s-*" org-repeat-re)
11239 org-repeat-re)
11240 (org-entry-end-position) t)
11241 (match-string-no-properties 1)))))
11243 (defvar org-last-changed-timestamp)
11244 (defvar org-last-inserted-timestamp)
11245 (defvar org-log-post-message)
11246 (defvar org-log-note-purpose)
11247 (defvar org-log-note-how)
11248 (defvar org-log-note-extra)
11249 (defun org-auto-repeat-maybe (done-word)
11250 "Check if the current headline contains a repeated deadline/schedule.
11251 If yes, set TODO state back to what it was and change the base date
11252 of repeating deadline/scheduled time stamps to new date.
11253 This function is run automatically after each state change to a DONE state."
11254 ;; last-state is dynamically scoped into this function
11255 (let* ((repeat (org-get-repeat))
11256 (aa (assoc last-state org-todo-kwd-alist))
11257 (interpret (nth 1 aa))
11258 (head (nth 2 aa))
11259 (whata '(("d" . day) ("m" . month) ("y" . year)))
11260 (msg "Entry repeats: ")
11261 (org-log-done nil)
11262 (org-todo-log-states nil)
11263 (nshiftmax 10) (nshift 0)
11264 re type n what ts time to-state)
11265 (when repeat
11266 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11267 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11268 org-todo-repeat-to-state))
11269 (unless (and to-state (member to-state org-todo-keywords-1))
11270 (setq to-state (if (eq interpret 'type) last-state head)))
11271 (org-todo to-state)
11272 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11273 (org-entry-put nil "LAST_REPEAT" (format-time-string
11274 (org-time-stamp-format t t))))
11275 (when org-log-repeat
11276 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11277 (memq 'org-add-log-note post-command-hook))
11278 ;; OK, we are already setup for some record
11279 (if (eq org-log-repeat 'note)
11280 ;; make sure we take a note, not only a time stamp
11281 (setq org-log-note-how 'note))
11282 ;; Set up for taking a record
11283 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11284 last-state
11285 'findpos org-log-repeat)))
11286 (org-back-to-heading t)
11287 (org-add-planning-info nil nil 'closed)
11288 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11289 org-deadline-time-regexp "\\)\\|\\("
11290 org-ts-regexp "\\)"))
11291 (while (re-search-forward
11292 re (save-excursion (outline-next-heading) (point)) t)
11293 (setq type (if (match-end 1) org-scheduled-string
11294 (if (match-end 3) org-deadline-string "Plain:"))
11295 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11296 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11297 (setq n (string-to-number (match-string 2 ts))
11298 what (match-string 3 ts))
11299 (if (equal what "w") (setq n (* n 7) what "d"))
11300 ;; Preparation, see if we need to modify the start date for the change
11301 (when (match-end 1)
11302 (setq time (save-match-data (org-time-string-to-time ts)))
11303 (cond
11304 ((equal (match-string 1 ts) ".")
11305 ;; Shift starting date to today
11306 (org-timestamp-change
11307 (- (time-to-days (current-time)) (time-to-days time))
11308 'day))
11309 ((equal (match-string 1 ts) "+")
11310 (while (or (= nshift 0)
11311 (<= (time-to-days time) (time-to-days (current-time))))
11312 (when (= (incf nshift) nshiftmax)
11313 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11314 (error "Abort")))
11315 (org-timestamp-change n (cdr (assoc what whata)))
11316 (org-at-timestamp-p t)
11317 (setq ts (match-string 1))
11318 (setq time (save-match-data (org-time-string-to-time ts))))
11319 (org-timestamp-change (- n) (cdr (assoc what whata)))
11320 ;; rematch, so that we have everything in place for the real shift
11321 (org-at-timestamp-p t)
11322 (setq ts (match-string 1))
11323 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11324 (org-timestamp-change n (cdr (assoc what whata)))
11325 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11326 (setq org-log-post-message msg)
11327 (message "%s" msg))))
11329 (defun org-show-todo-tree (arg)
11330 "Make a compact tree which shows all headlines marked with TODO.
11331 The tree will show the lines where the regexp matches, and all higher
11332 headlines above the match.
11333 With a \\[universal-argument] prefix, prompt for a regexp to match.
11334 With a numeric prefix N, construct a sparse tree for the Nth element
11335 of `org-todo-keywords-1'."
11336 (interactive "P")
11337 (let ((case-fold-search nil)
11338 (kwd-re
11339 (cond ((null arg) org-not-done-regexp)
11340 ((equal arg '(4))
11341 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11342 (mapcar 'list org-todo-keywords-1))))
11343 (concat "\\("
11344 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11345 "\\)\\>")))
11346 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11347 (regexp-quote (nth (1- (prefix-numeric-value arg))
11348 org-todo-keywords-1)))
11349 (t (error "Invalid prefix argument: %s" arg)))))
11350 (message "%d TODO entries found"
11351 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11353 (defun org-deadline (&optional remove time)
11354 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11355 With argument REMOVE, remove any deadline from the item.
11356 When TIME is set, it should be an internal time specification, and the
11357 scheduling will use the corresponding date."
11358 (interactive "P")
11359 (let* ((old-date (org-entry-get nil "DEADLINE"))
11360 (repeater (and old-date
11361 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11362 (match-string 1 old-date))))
11363 (if remove
11364 (progn
11365 (when (and old-date org-log-redeadline)
11366 (org-add-log-setup 'deldeadline nil old-date 'findpos
11367 org-log-redeadline))
11368 (org-remove-timestamp-with-keyword org-deadline-string)
11369 (message "Item no longer has a deadline."))
11370 (org-add-planning-info 'deadline time 'closed)
11371 (when (and old-date org-log-redeadline
11372 (not (equal old-date
11373 (substring org-last-inserted-timestamp 1 -1))))
11374 (org-add-log-setup 'redeadline nil old-date 'findpos
11375 org-log-redeadline))
11376 (when repeater
11377 (save-excursion
11378 (org-back-to-heading t)
11379 (when (re-search-forward (concat org-deadline-string " "
11380 org-last-inserted-timestamp)
11381 (save-excursion
11382 (outline-next-heading) (point)) t)
11383 (goto-char (1- (match-end 0)))
11384 (insert " " repeater)
11385 (setq org-last-inserted-timestamp
11386 (concat (substring org-last-inserted-timestamp 0 -1)
11387 " " repeater
11388 (substring org-last-inserted-timestamp -1))))))
11389 (message "Deadline on %s" org-last-inserted-timestamp))))
11391 (defun org-schedule (&optional remove time)
11392 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11393 With argument REMOVE, remove any scheduling date from the item.
11394 When TIME is set, it should be an internal time specification, and the
11395 scheduling will use the corresponding date."
11396 (interactive "P")
11397 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11398 (repeater (and old-date
11399 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11400 (match-string 1 old-date))))
11401 (if remove
11402 (progn
11403 (when (and old-date org-log-reschedule)
11404 (org-add-log-setup 'delschedule nil old-date 'findpos
11405 org-log-reschedule))
11406 (org-remove-timestamp-with-keyword org-scheduled-string)
11407 (message "Item is no longer scheduled."))
11408 (org-add-planning-info 'scheduled time 'closed)
11409 (when (and old-date org-log-reschedule
11410 (not (equal old-date
11411 (substring org-last-inserted-timestamp 1 -1))))
11412 (org-add-log-setup 'reschedule nil old-date 'findpos
11413 org-log-reschedule))
11414 (when repeater
11415 (save-excursion
11416 (org-back-to-heading t)
11417 (when (re-search-forward (concat org-scheduled-string " "
11418 org-last-inserted-timestamp)
11419 (save-excursion
11420 (outline-next-heading) (point)) t)
11421 (goto-char (1- (match-end 0)))
11422 (insert " " repeater)
11423 (setq org-last-inserted-timestamp
11424 (concat (substring org-last-inserted-timestamp 0 -1)
11425 " " repeater
11426 (substring org-last-inserted-timestamp -1))))))
11427 (message "Scheduled to %s" org-last-inserted-timestamp))))
11429 (defun org-get-scheduled-time (pom &optional inherit)
11430 "Get the scheduled time as a time tuple, of a format suitable
11431 for calling org-schedule with, or if there is no scheduling,
11432 returns nil."
11433 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11434 (when time
11435 (apply 'encode-time (org-parse-time-string time)))))
11437 (defun org-get-deadline-time (pom &optional inherit)
11438 "Get the deadine as a time tuple, of a format suitable for
11439 calling org-deadline with, or if there is no scheduling, returns
11440 nil."
11441 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11442 (when time
11443 (apply 'encode-time (org-parse-time-string time)))))
11445 (defun org-remove-timestamp-with-keyword (keyword)
11446 "Remove all time stamps with KEYWORD in the current entry."
11447 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11448 beg)
11449 (save-excursion
11450 (org-back-to-heading t)
11451 (setq beg (point))
11452 (outline-next-heading)
11453 (while (re-search-backward re beg t)
11454 (replace-match "")
11455 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11456 (equal (char-before) ?\ ))
11457 (backward-delete-char 1)
11458 (if (string-match "^[ \t]*$" (buffer-substring
11459 (point-at-bol) (point-at-eol)))
11460 (delete-region (point-at-bol)
11461 (min (point-max) (1+ (point-at-eol))))))))))
11463 (defun org-add-planning-info (what &optional time &rest remove)
11464 "Insert new timestamp with keyword in the line directly after the headline.
11465 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11466 If non is given, the user is prompted for a date.
11467 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11468 be removed."
11469 (interactive)
11470 (let (org-time-was-given org-end-time-was-given ts
11471 end default-time default-input)
11473 (catch 'exit
11474 (when (and (not time) (memq what '(scheduled deadline)))
11475 ;; Try to get a default date/time from existing timestamp
11476 (save-excursion
11477 (org-back-to-heading t)
11478 (setq end (save-excursion (outline-next-heading) (point)))
11479 (when (re-search-forward (if (eq what 'scheduled)
11480 org-scheduled-time-regexp
11481 org-deadline-time-regexp)
11482 end t)
11483 (setq ts (match-string 1)
11484 default-time
11485 (apply 'encode-time (org-parse-time-string ts))
11486 default-input (and ts (org-get-compact-tod ts))))))
11487 (when what
11488 ;; If necessary, get the time from the user
11489 (setq time (or time (org-read-date nil 'to-time nil nil
11490 default-time default-input))))
11492 (when (and org-insert-labeled-timestamps-at-point
11493 (member what '(scheduled deadline)))
11494 (insert
11495 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11496 (org-insert-time-stamp time org-time-was-given
11497 nil nil nil (list org-end-time-was-given))
11498 (setq what nil))
11499 (save-excursion
11500 (save-restriction
11501 (let (col list elt ts buffer-invisibility-spec)
11502 (org-back-to-heading t)
11503 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11504 (goto-char (match-end 1))
11505 (setq col (current-column))
11506 (goto-char (match-end 0))
11507 (if (eobp) (insert "\n") (forward-char 1))
11508 (when (and (not what)
11509 (not (looking-at
11510 (concat "[ \t]*"
11511 org-keyword-time-not-clock-regexp))))
11512 ;; Nothing to add, nothing to remove...... :-)
11513 (throw 'exit nil))
11514 (if (and (not (looking-at outline-regexp))
11515 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11516 "[^\r\n]*"))
11517 (not (equal (match-string 1) org-clock-string)))
11518 (narrow-to-region (match-beginning 0) (match-end 0))
11519 (insert-before-markers "\n")
11520 (backward-char 1)
11521 (narrow-to-region (point) (point))
11522 (and org-adapt-indentation (org-indent-to-column col)))
11523 ;; Check if we have to remove something.
11524 (setq list (cons what remove))
11525 (while list
11526 (setq elt (pop list))
11527 (goto-char (point-min))
11528 (when (or (and (eq elt 'scheduled)
11529 (re-search-forward org-scheduled-time-regexp nil t))
11530 (and (eq elt 'deadline)
11531 (re-search-forward org-deadline-time-regexp nil t))
11532 (and (eq elt 'closed)
11533 (re-search-forward org-closed-time-regexp nil t)))
11534 (replace-match "")
11535 (if (looking-at "--+<[^>]+>") (replace-match ""))
11536 (skip-chars-backward " ")
11537 (if (looking-at " +") (replace-match ""))))
11538 (goto-char (point-max))
11539 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11540 (when what
11541 (insert
11542 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11543 (cond ((eq what 'scheduled) org-scheduled-string)
11544 ((eq what 'deadline) org-deadline-string)
11545 ((eq what 'closed) org-closed-string))
11546 " ")
11547 (setq ts (org-insert-time-stamp
11548 time
11549 (or org-time-was-given
11550 (and (eq what 'closed) org-log-done-with-time))
11551 (eq what 'closed)
11552 nil nil (list org-end-time-was-given)))
11553 (end-of-line 1))
11554 (goto-char (point-min))
11555 (widen)
11556 (if (and (looking-at "[ \t]*\n")
11557 (equal (char-before) ?\n))
11558 (delete-region (1- (point)) (point-at-eol)))
11559 ts))))))
11561 (defvar org-log-note-marker (make-marker))
11562 (defvar org-log-note-purpose nil)
11563 (defvar org-log-note-state nil)
11564 (defvar org-log-note-previous-state nil)
11565 (defvar org-log-note-how nil)
11566 (defvar org-log-note-extra nil)
11567 (defvar org-log-note-window-configuration nil)
11568 (defvar org-log-note-return-to (make-marker))
11569 (defvar org-log-post-message nil
11570 "Message to be displayed after a log note has been stored.
11571 The auto-repeater uses this.")
11573 (defun org-add-note ()
11574 "Add a note to the current entry.
11575 This is done in the same way as adding a state change note."
11576 (interactive)
11577 (org-add-log-setup 'note nil nil 'findpos nil))
11579 (defvar org-property-end-re)
11580 (defun org-add-log-setup (&optional purpose state prev-state
11581 findpos how &optional extra)
11582 "Set up the post command hook to take a note.
11583 If this is about to TODO state change, the new state is expected in STATE.
11584 When FINDPOS is non-nil, find the correct position for the note in
11585 the current entry. If not, assume that it can be inserted at point.
11586 HOW is an indicator what kind of note should be created.
11587 EXTRA is additional text that will be inserted into the notes buffer."
11588 (let* ((org-log-into-drawer (org-log-into-drawer))
11589 (drawer (cond ((stringp org-log-into-drawer)
11590 org-log-into-drawer)
11591 (org-log-into-drawer "LOGBOOK")
11592 (t nil))))
11593 (save-restriction
11594 (save-excursion
11595 (when findpos
11596 (org-back-to-heading t)
11597 (narrow-to-region (point) (save-excursion
11598 (outline-next-heading) (point)))
11599 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11600 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11601 "[^\r\n]*\\)?"))
11602 (goto-char (match-end 0))
11603 (cond
11604 (drawer
11605 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11606 nil t)
11607 (progn
11608 (goto-char (match-end 0))
11609 (or org-log-states-order-reversed
11610 (and (re-search-forward org-property-end-re nil t)
11611 (goto-char (1- (match-beginning 0))))))
11612 (insert "\n:" drawer ":\n:END:")
11613 (beginning-of-line 0)
11614 (org-indent-line-function)
11615 (beginning-of-line 2)
11616 (org-indent-line-function)
11617 (end-of-line 0)))
11618 ((and org-log-state-notes-insert-after-drawers
11619 (save-excursion
11620 (forward-line) (looking-at org-drawer-regexp)))
11621 (forward-line)
11622 (while (looking-at org-drawer-regexp)
11623 (goto-char (match-end 0))
11624 (re-search-forward org-property-end-re (point-max) t)
11625 (forward-line))
11626 (forward-line -1)))
11627 (unless org-log-states-order-reversed
11628 (and (= (char-after) ?\n) (forward-char 1))
11629 (org-skip-over-state-notes)
11630 (skip-chars-backward " \t\n\r")))
11631 (move-marker org-log-note-marker (point))
11632 (setq org-log-note-purpose purpose
11633 org-log-note-state state
11634 org-log-note-previous-state prev-state
11635 org-log-note-how how
11636 org-log-note-extra extra)
11637 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11639 (defun org-skip-over-state-notes ()
11640 "Skip past the list of State notes in an entry."
11641 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11642 (while (looking-at "[ \t]*- State")
11643 (condition-case nil
11644 (org-next-item)
11645 (error (org-end-of-item)))))
11647 (defun org-add-log-note (&optional purpose)
11648 "Pop up a window for taking a note, and add this note later at point."
11649 (remove-hook 'post-command-hook 'org-add-log-note)
11650 (setq org-log-note-window-configuration (current-window-configuration))
11651 (delete-other-windows)
11652 (move-marker org-log-note-return-to (point))
11653 (switch-to-buffer (marker-buffer org-log-note-marker))
11654 (goto-char org-log-note-marker)
11655 (org-switch-to-buffer-other-window "*Org Note*")
11656 (erase-buffer)
11657 (if (memq org-log-note-how '(time state))
11658 (let (current-prefix-arg) (org-store-log-note))
11659 (let ((org-inhibit-startup t)) (org-mode))
11660 (insert (format "# Insert note for %s.
11661 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11662 (cond
11663 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11664 ((eq org-log-note-purpose 'done) "closed todo item")
11665 ((eq org-log-note-purpose 'state)
11666 (format "state change from \"%s\" to \"%s\""
11667 (or org-log-note-previous-state "")
11668 (or org-log-note-state "")))
11669 ((eq org-log-note-purpose 'reschedule)
11670 "rescheduling")
11671 ((eq org-log-note-purpose 'delschedule)
11672 "no longer scheduled")
11673 ((eq org-log-note-purpose 'redeadline)
11674 "changing deadline")
11675 ((eq org-log-note-purpose 'deldeadline)
11676 "removing deadline")
11677 ((eq org-log-note-purpose 'refile)
11678 "refiling")
11679 ((eq org-log-note-purpose 'note)
11680 "this entry")
11681 (t (error "This should not happen")))))
11682 (if org-log-note-extra (insert org-log-note-extra))
11683 (org-set-local 'org-finish-function 'org-store-log-note)))
11685 (defvar org-note-abort nil) ; dynamically scoped
11686 (defun org-store-log-note ()
11687 "Finish taking a log note, and insert it to where it belongs."
11688 (let ((txt (buffer-string))
11689 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11690 lines ind)
11691 (kill-buffer (current-buffer))
11692 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11693 (setq txt (replace-match "" t t txt)))
11694 (if (string-match "\\s-+\\'" txt)
11695 (setq txt (replace-match "" t t txt)))
11696 (setq lines (org-split-string txt "\n"))
11697 (when (and note (string-match "\\S-" note))
11698 (setq note
11699 (org-replace-escapes
11700 note
11701 (list (cons "%u" (user-login-name))
11702 (cons "%U" user-full-name)
11703 (cons "%t" (format-time-string
11704 (org-time-stamp-format 'long 'inactive)
11705 (current-time)))
11706 (cons "%T" (format-time-string
11707 (org-time-stamp-format 'long nil)
11708 (current-time)))
11709 (cons "%s" (if org-log-note-state
11710 (concat "\"" org-log-note-state "\"")
11711 ""))
11712 (cons "%S" (if org-log-note-previous-state
11713 (concat "\"" org-log-note-previous-state "\"")
11714 "\"\"")))))
11715 (if lines (setq note (concat note " \\\\")))
11716 (push note lines))
11717 (when (or current-prefix-arg org-note-abort)
11718 (when org-log-into-drawer
11719 (org-remove-empty-drawer-at
11720 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11721 org-log-note-marker))
11722 (setq lines nil))
11723 (when lines
11724 (with-current-buffer (marker-buffer org-log-note-marker)
11725 (save-excursion
11726 (goto-char org-log-note-marker)
11727 (move-marker org-log-note-marker nil)
11728 (end-of-line 1)
11729 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11730 (insert "- " (pop lines))
11731 (org-indent-line-function)
11732 (beginning-of-line 1)
11733 (looking-at "[ \t]*")
11734 (setq ind (concat (match-string 0) " "))
11735 (end-of-line 1)
11736 (while lines (insert "\n" ind (pop lines)))
11737 (message "Note stored")
11738 (org-back-to-heading t)
11739 (org-cycle-hide-drawers 'children)))))
11740 (set-window-configuration org-log-note-window-configuration)
11741 (with-current-buffer (marker-buffer org-log-note-return-to)
11742 (goto-char org-log-note-return-to))
11743 (move-marker org-log-note-return-to nil)
11744 (and org-log-post-message (message "%s" org-log-post-message)))
11746 (defun org-remove-empty-drawer-at (drawer pos)
11747 "Remove an empty drawer DRAWER at position POS.
11748 POS may also be a marker."
11749 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11750 (save-excursion
11751 (save-restriction
11752 (widen)
11753 (goto-char pos)
11754 (if (org-in-regexp
11755 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11756 (replace-match ""))))))
11758 (defun org-sparse-tree (&optional arg)
11759 "Create a sparse tree, prompt for the details.
11760 This command can create sparse trees. You first need to select the type
11761 of match used to create the tree:
11763 t Show all TODO entries.
11764 T Show entries with a specific TODO keyword.
11765 m Show entries selected by a tags/property match.
11766 p Enter a property name and its value (both with completion on existing
11767 names/values) and show entries with that property.
11768 / Show entries matching a regular expression (`r' can be used as well)
11769 d Show deadlines due within `org-deadline-warning-days'.
11770 b Show deadlines and scheduled items before a date.
11771 a Show deadlines and scheduled items after a date."
11772 (interactive "P")
11773 (let (ans kwd value)
11774 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11775 (setq ans (read-char-exclusive))
11776 (cond
11777 ((equal ans ?d)
11778 (call-interactively 'org-check-deadlines))
11779 ((equal ans ?b)
11780 (call-interactively 'org-check-before-date))
11781 ((equal ans ?a)
11782 (call-interactively 'org-check-after-date))
11783 ((equal ans ?t)
11784 (org-show-todo-tree nil))
11785 ((equal ans ?T)
11786 (org-show-todo-tree '(4)))
11787 ((member ans '(?T ?m))
11788 (call-interactively 'org-match-sparse-tree))
11789 ((member ans '(?p ?P))
11790 (setq kwd (org-icompleting-read "Property: "
11791 (mapcar 'list (org-buffer-property-keys))))
11792 (setq value (org-icompleting-read "Value: "
11793 (mapcar 'list (org-property-values kwd))))
11794 (unless (string-match "\\`{.*}\\'" value)
11795 (setq value (concat "\"" value "\"")))
11796 (org-match-sparse-tree arg (concat kwd "=" value)))
11797 ((member ans '(?r ?R ?/))
11798 (call-interactively 'org-occur))
11799 (t (error "No such sparse tree command \"%c\"" ans)))))
11801 (defvar org-occur-highlights nil
11802 "List of overlays used for occur matches.")
11803 (make-variable-buffer-local 'org-occur-highlights)
11804 (defvar org-occur-parameters nil
11805 "Parameters of the active org-occur calls.
11806 This is a list, each call to org-occur pushes as cons cell,
11807 containing the regular expression and the callback, onto the list.
11808 The list can contain several entries if `org-occur' has been called
11809 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11810 will only contain one set of parameters. When the highlights are
11811 removed (for example with `C-c C-c', or with the next edit (depending
11812 on `org-remove-highlights-with-change'), this variable is emptied
11813 as well.")
11814 (make-variable-buffer-local 'org-occur-parameters)
11816 (defun org-occur (regexp &optional keep-previous callback)
11817 "Make a compact tree which shows all matches of REGEXP.
11818 The tree will show the lines where the regexp matches, and all higher
11819 headlines above the match. It will also show the heading after the match,
11820 to make sure editing the matching entry is easy.
11821 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11822 call to `org-occur' will be kept, to allow stacking of calls to this
11823 command.
11824 If CALLBACK is non-nil, it is a function which is called to confirm
11825 that the match should indeed be shown."
11826 (interactive "sRegexp: \nP")
11827 (when (equal regexp "")
11828 (error "Regexp cannot be empty"))
11829 (unless keep-previous
11830 (org-remove-occur-highlights nil nil t))
11831 (push (cons regexp callback) org-occur-parameters)
11832 (let ((cnt 0))
11833 (save-excursion
11834 (goto-char (point-min))
11835 (if (or (not keep-previous) ; do not want to keep
11836 (not org-occur-highlights)) ; no previous matches
11837 ;; hide everything
11838 (org-overview))
11839 (while (re-search-forward regexp nil t)
11840 (when (or (not callback)
11841 (save-match-data (funcall callback)))
11842 (setq cnt (1+ cnt))
11843 (when org-highlight-sparse-tree-matches
11844 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11845 (org-show-context 'occur-tree))))
11846 (when org-remove-highlights-with-change
11847 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11848 nil 'local))
11849 (unless org-sparse-tree-open-archived-trees
11850 (org-hide-archived-subtrees (point-min) (point-max)))
11851 (run-hooks 'org-occur-hook)
11852 (if (interactive-p)
11853 (message "%d match(es) for regexp %s" cnt regexp))
11854 cnt))
11856 (defun org-show-context (&optional key)
11857 "Make sure point and context are visible.
11858 How much context is shown depends upon the variables
11859 `org-show-hierarchy-above', `org-show-following-heading'. and
11860 `org-show-siblings'."
11861 (let ((heading-p (org-on-heading-p t))
11862 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11863 (following-p (org-get-alist-option org-show-following-heading key))
11864 (entry-p (org-get-alist-option org-show-entry-below key))
11865 (siblings-p (org-get-alist-option org-show-siblings key)))
11866 (catch 'exit
11867 ;; Show heading or entry text
11868 (if (and heading-p (not entry-p))
11869 (org-flag-heading nil) ; only show the heading
11870 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11871 (org-show-hidden-entry))) ; show entire entry
11872 (when following-p
11873 ;; Show next sibling, or heading below text
11874 (save-excursion
11875 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11876 (org-flag-heading nil))))
11877 (when siblings-p (org-show-siblings))
11878 (when hierarchy-p
11879 ;; show all higher headings, possibly with siblings
11880 (save-excursion
11881 (while (and (condition-case nil
11882 (progn (org-up-heading-all 1) t)
11883 (error nil))
11884 (not (bobp)))
11885 (org-flag-heading nil)
11886 (when siblings-p (org-show-siblings))))))))
11888 (defvar org-reveal-start-hook nil
11889 "Hook run before revealing a location.")
11891 (defun org-reveal (&optional siblings)
11892 "Show current entry, hierarchy above it, and the following headline.
11893 This can be used to show a consistent set of context around locations
11894 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11895 not t for the search context.
11897 With optional argument SIBLINGS, on each level of the hierarchy all
11898 siblings are shown. This repairs the tree structure to what it would
11899 look like when opened with hierarchical calls to `org-cycle'.
11900 With double optional argument `C-u C-u', go to the parent and show the
11901 entire tree."
11902 (interactive "P")
11903 (run-hooks 'org-reveal-start-hook)
11904 (let ((org-show-hierarchy-above t)
11905 (org-show-following-heading t)
11906 (org-show-siblings (if siblings t org-show-siblings)))
11907 (org-show-context nil))
11908 (when (equal siblings '(16))
11909 (save-excursion
11910 (when (org-up-heading-safe)
11911 (org-show-subtree)
11912 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11914 (defun org-highlight-new-match (beg end)
11915 "Highlight from BEG to END and mark the highlight is an occur headline."
11916 (let ((ov (make-overlay beg end)))
11917 (overlay-put ov 'face 'secondary-selection)
11918 (push ov org-occur-highlights)))
11920 (defun org-remove-occur-highlights (&optional beg end noremove)
11921 "Remove the occur highlights from the buffer.
11922 BEG and END are ignored. If NOREMOVE is nil, remove this function
11923 from the `before-change-functions' in the current buffer."
11924 (interactive)
11925 (unless org-inhibit-highlight-removal
11926 (mapc 'delete-overlay org-occur-highlights)
11927 (setq org-occur-highlights nil)
11928 (setq org-occur-parameters nil)
11929 (unless noremove
11930 (remove-hook 'before-change-functions
11931 'org-remove-occur-highlights 'local))))
11933 ;;;; Priorities
11935 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11936 "Regular expression matching the priority indicator.")
11938 (defvar org-remove-priority-next-time nil)
11940 (defun org-priority-up ()
11941 "Increase the priority of the current item."
11942 (interactive)
11943 (org-priority 'up))
11945 (defun org-priority-down ()
11946 "Decrease the priority of the current item."
11947 (interactive)
11948 (org-priority 'down))
11950 (defun org-priority (&optional action)
11951 "Change the priority of an item by ARG.
11952 ACTION can be `set', `up', `down', or a character."
11953 (interactive)
11954 (unless org-enable-priority-commands
11955 (error "Priority commands are disabled"))
11956 (setq action (or action 'set))
11957 (let (current new news have remove)
11958 (save-excursion
11959 (org-back-to-heading t)
11960 (if (looking-at org-priority-regexp)
11961 (setq current (string-to-char (match-string 2))
11962 have t)
11963 (setq current org-default-priority))
11964 (cond
11965 ((eq action 'remove)
11966 (setq remove t new ?\ ))
11967 ((or (eq action 'set)
11968 (if (featurep 'xemacs) (characterp action) (integerp action)))
11969 (if (not (eq action 'set))
11970 (setq new action)
11971 (message "Priority %c-%c, SPC to remove: "
11972 org-highest-priority org-lowest-priority)
11973 (setq new (read-char-exclusive)))
11974 (if (and (= (upcase org-highest-priority) org-highest-priority)
11975 (= (upcase org-lowest-priority) org-lowest-priority))
11976 (setq new (upcase new)))
11977 (cond ((equal new ?\ ) (setq remove t))
11978 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11979 (error "Priority must be between `%c' and `%c'"
11980 org-highest-priority org-lowest-priority))))
11981 ((eq action 'up)
11982 (if (and (not have) (eq last-command this-command))
11983 (setq new org-lowest-priority)
11984 (setq new (if (and org-priority-start-cycle-with-default (not have))
11985 org-default-priority (1- current)))))
11986 ((eq action 'down)
11987 (if (and (not have) (eq last-command this-command))
11988 (setq new org-highest-priority)
11989 (setq new (if (and org-priority-start-cycle-with-default (not have))
11990 org-default-priority (1+ current)))))
11991 (t (error "Invalid action")))
11992 (if (or (< (upcase new) org-highest-priority)
11993 (> (upcase new) org-lowest-priority))
11994 (setq remove t))
11995 (setq news (format "%c" new))
11996 (if have
11997 (if remove
11998 (replace-match "" t t nil 1)
11999 (replace-match news t t nil 2))
12000 (if remove
12001 (error "No priority cookie found in line")
12002 (let ((case-fold-search nil))
12003 (looking-at org-todo-line-regexp))
12004 (if (match-end 2)
12005 (progn
12006 (goto-char (match-end 2))
12007 (insert " [#" news "]"))
12008 (goto-char (match-beginning 3))
12009 (insert "[#" news "] "))))
12010 (org-preserve-lc (org-set-tags nil 'align)))
12011 (if remove
12012 (message "Priority removed")
12013 (message "Priority of current item set to %s" news))))
12015 (defun org-get-priority (s)
12016 "Find priority cookie and return priority."
12017 (save-match-data
12018 (if (not (string-match org-priority-regexp s))
12019 (* 1000 (- org-lowest-priority org-default-priority))
12020 (* 1000 (- org-lowest-priority
12021 (string-to-char (match-string 2 s)))))))
12023 ;;;; Tags
12025 (defvar org-agenda-archives-mode)
12026 (defvar org-map-continue-from nil
12027 "Position from where mapping should continue.
12028 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12030 (defvar org-scanner-tags nil
12031 "The current tag list while the tags scanner is running.")
12032 (defvar org-trust-scanner-tags nil
12033 "Should `org-get-tags-at' use the tags fro the scanner.
12034 This is for internal dynamical scoping only.
12035 When this is non-nil, the function `org-get-tags-at' will return the value
12036 of `org-scanner-tags' instead of building the list by itself. This
12037 can lead to large speed-ups when the tags scanner is used in a file with
12038 many entries, and when the list of tags is retrieved, for example to
12039 obtain a list of properties. Building the tags list for each entry in such
12040 a file becomes an N^2 operation - but with this variable set, it scales
12041 as N.")
12043 (defun org-scan-tags (action matcher &optional todo-only)
12044 "Scan headline tags with inheritance and produce output ACTION.
12046 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12047 or `agenda' to produce an entry list for an agenda view. It can also be
12048 a Lisp form or a function that should be called at each matched headline, in
12049 this case the return value is a list of all return values from these calls.
12051 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12052 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12053 only lines with a TODO keyword are included in the output."
12054 (require 'org-agenda)
12055 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12056 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12057 (org-re
12058 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12059 (props (list 'face 'default
12060 'done-face 'org-agenda-done
12061 'undone-face 'default
12062 'mouse-face 'highlight
12063 'org-not-done-regexp org-not-done-regexp
12064 'org-todo-regexp org-todo-regexp
12065 'help-echo
12066 (format "mouse-2 or RET jump to org file %s"
12067 (abbreviate-file-name
12068 (or (buffer-file-name (buffer-base-buffer))
12069 (buffer-name (buffer-base-buffer)))))))
12070 (case-fold-search nil)
12071 (org-map-continue-from nil)
12072 lspos tags tags-list
12073 (tags-alist (list (cons 0 org-file-tags)))
12074 (llast 0) rtn rtn1 level category i txt
12075 todo marker entry priority)
12076 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12077 (setq action (list 'lambda nil action)))
12078 (save-excursion
12079 (goto-char (point-min))
12080 (when (eq action 'sparse-tree)
12081 (org-overview)
12082 (org-remove-occur-highlights))
12083 (while (re-search-forward re nil t)
12084 (catch :skip
12085 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12086 tags (if (match-end 4) (org-match-string-no-properties 4)))
12087 (goto-char (setq lspos (match-beginning 0)))
12088 (setq level (org-reduced-level (funcall outline-level))
12089 category (org-get-category))
12090 (setq i llast llast level)
12091 ;; remove tag lists from same and sublevels
12092 (while (>= i level)
12093 (when (setq entry (assoc i tags-alist))
12094 (setq tags-alist (delete entry tags-alist)))
12095 (setq i (1- i)))
12096 ;; add the next tags
12097 (when tags
12098 (setq tags (org-split-string tags ":")
12099 tags-alist
12100 (cons (cons level tags) tags-alist)))
12101 ;; compile tags for current headline
12102 (setq tags-list
12103 (if org-use-tag-inheritance
12104 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12105 tags)
12106 org-scanner-tags tags-list)
12107 (when org-use-tag-inheritance
12108 (setcdr (car tags-alist)
12109 (mapcar (lambda (x)
12110 (setq x (copy-sequence x))
12111 (org-add-prop-inherited x))
12112 (cdar tags-alist))))
12113 (when (and tags org-use-tag-inheritance
12114 (or (not (eq t org-use-tag-inheritance))
12115 org-tags-exclude-from-inheritance))
12116 ;; selective inheritance, remove uninherited ones
12117 (setcdr (car tags-alist)
12118 (org-remove-uniherited-tags (cdar tags-alist))))
12119 (when (and (or (not todo-only)
12120 (and (member todo org-not-done-keywords)
12121 (or (not org-agenda-tags-todo-honor-ignore-options)
12122 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12123 (let ((case-fold-search t)) (eval matcher))
12125 (not (member org-archive-tag tags-list))
12126 ;; we have an archive tag, should we use this anyway?
12127 (or (not org-agenda-skip-archived-trees)
12128 (and (eq action 'agenda) org-agenda-archives-mode))))
12129 (unless (eq action 'sparse-tree) (org-agenda-skip))
12131 ;; select this headline
12133 (cond
12134 ((eq action 'sparse-tree)
12135 (and org-highlight-sparse-tree-matches
12136 (org-get-heading) (match-end 0)
12137 (org-highlight-new-match
12138 (match-beginning 0) (match-beginning 1)))
12139 (org-show-context 'tags-tree))
12140 ((eq action 'agenda)
12141 (setq txt (org-format-agenda-item
12143 (concat
12144 (if (eq org-tags-match-list-sublevels 'indented)
12145 (make-string (1- level) ?.) "")
12146 (org-get-heading))
12147 category
12148 tags-list
12150 priority (org-get-priority txt))
12151 (goto-char lspos)
12152 (setq marker (org-agenda-new-marker))
12153 (org-add-props txt props
12154 'org-marker marker 'org-hd-marker marker 'org-category category
12155 'todo-state todo
12156 'priority priority 'type "tagsmatch")
12157 (push txt rtn))
12158 ((functionp action)
12159 (setq org-map-continue-from nil)
12160 (save-excursion
12161 (setq rtn1 (funcall action))
12162 (push rtn1 rtn)))
12163 (t (error "Invalid action")))
12165 ;; if we are to skip sublevels, jump to end of subtree
12166 (unless org-tags-match-list-sublevels
12167 (org-end-of-subtree t)
12168 (backward-char 1))))
12169 ;; Get the correct position from where to continue
12170 (if org-map-continue-from
12171 (goto-char org-map-continue-from)
12172 (and (= (point) lspos) (end-of-line 1)))))
12173 (when (and (eq action 'sparse-tree)
12174 (not org-sparse-tree-open-archived-trees))
12175 (org-hide-archived-subtrees (point-min) (point-max)))
12176 (nreverse rtn)))
12178 (defun org-remove-uniherited-tags (tags)
12179 "Remove all tags that are not inherited from the list TAGS."
12180 (cond
12181 ((eq org-use-tag-inheritance t)
12182 (if org-tags-exclude-from-inheritance
12183 (org-delete-all org-tags-exclude-from-inheritance tags)
12184 tags))
12185 ((not org-use-tag-inheritance) nil)
12186 ((stringp org-use-tag-inheritance)
12187 (delq nil (mapcar
12188 (lambda (x)
12189 (if (and (string-match org-use-tag-inheritance x)
12190 (not (member x org-tags-exclude-from-inheritance)))
12191 x nil))
12192 tags)))
12193 ((listp org-use-tag-inheritance)
12194 (delq nil (mapcar
12195 (lambda (x)
12196 (if (member x org-use-tag-inheritance) x nil))
12197 tags)))))
12199 (defvar todo-only) ;; dynamically scoped
12201 (defun org-match-sparse-tree (&optional todo-only match)
12202 "Create a sparse tree according to tags string MATCH.
12203 MATCH can contain positive and negative selection of tags, like
12204 \"+WORK+URGENT-WITHBOSS\".
12205 If optional argument TODO-ONLY is non-nil, only select lines that are
12206 also TODO lines."
12207 (interactive "P")
12208 (org-prepare-agenda-buffers (list (current-buffer)))
12209 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12211 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12213 (defvar org-cached-props nil)
12214 (defun org-cached-entry-get (pom property)
12215 (if (or (eq t org-use-property-inheritance)
12216 (and (stringp org-use-property-inheritance)
12217 (string-match org-use-property-inheritance property))
12218 (and (listp org-use-property-inheritance)
12219 (member property org-use-property-inheritance)))
12220 ;; Caching is not possible, check it directly
12221 (org-entry-get pom property 'inherit)
12222 ;; Get all properties, so that we can do complicated checks easily
12223 (cdr (assoc property (or org-cached-props
12224 (setq org-cached-props
12225 (org-entry-properties pom)))))))
12227 (defun org-global-tags-completion-table (&optional files)
12228 "Return the list of all tags in all agenda buffer/files."
12229 (save-excursion
12230 (org-uniquify
12231 (delq nil
12232 (apply 'append
12233 (mapcar
12234 (lambda (file)
12235 (set-buffer (find-file-noselect file))
12236 (append (org-get-buffer-tags)
12237 (mapcar (lambda (x) (if (stringp (car-safe x))
12238 (list (car-safe x)) nil))
12239 org-tag-alist)))
12240 (if (and files (car files))
12241 files
12242 (org-agenda-files))))))))
12244 (defun org-make-tags-matcher (match)
12245 "Create the TAGS//TODO matcher form for the selection string MATCH."
12246 ;; todo-only is scoped dynamically into this function, and the function
12247 ;; may change it if the matcher asks for it.
12248 (unless match
12249 ;; Get a new match request, with completion
12250 (let ((org-last-tags-completion-table
12251 (org-global-tags-completion-table)))
12252 (setq match (org-completing-read-no-i
12253 "Match: " 'org-tags-completion-function nil nil nil
12254 'org-tags-history))))
12256 ;; Parse the string and create a lisp form
12257 (let ((match0 match)
12258 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12259 minus tag mm
12260 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12261 orterms term orlist re-p str-p level-p level-op time-p
12262 prop-p pn pv po cat-p gv rest)
12263 (if (string-match "/+" match)
12264 ;; match contains also a todo-matching request
12265 (progn
12266 (setq tagsmatch (substring match 0 (match-beginning 0))
12267 todomatch (substring match (match-end 0)))
12268 (if (string-match "^!" todomatch)
12269 (setq todo-only t todomatch (substring todomatch 1)))
12270 (if (string-match "^\\s-*$" todomatch)
12271 (setq todomatch nil)))
12272 ;; only matching tags
12273 (setq tagsmatch match todomatch nil))
12275 ;; Make the tags matcher
12276 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12277 (setq tagsmatcher t)
12278 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12279 (while (setq term (pop orterms))
12280 (while (and (equal (substring term -1) "\\") orterms)
12281 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12282 (while (string-match re term)
12283 (setq rest (substring term (match-end 0))
12284 minus (and (match-end 1)
12285 (equal (match-string 1 term) "-"))
12286 tag (match-string 2 term)
12287 re-p (equal (string-to-char tag) ?{)
12288 level-p (match-end 4)
12289 prop-p (match-end 5)
12290 mm (cond
12291 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12292 (level-p
12293 (setq level-op (org-op-to-function (match-string 3 term)))
12294 `(,level-op level ,(string-to-number
12295 (match-string 4 term))))
12296 (prop-p
12297 (setq pn (match-string 5 term)
12298 po (match-string 6 term)
12299 pv (match-string 7 term)
12300 cat-p (equal pn "CATEGORY")
12301 re-p (equal (string-to-char pv) ?{)
12302 str-p (equal (string-to-char pv) ?\")
12303 time-p (save-match-data
12304 (string-match "^\"[[<].*[]>]\"$" pv))
12305 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12306 (if time-p (setq pv (org-matcher-time pv)))
12307 (setq po (org-op-to-function po (if time-p 'time str-p)))
12308 (cond
12309 ((equal pn "CATEGORY")
12310 (setq gv '(get-text-property (point) 'org-category)))
12311 ((equal pn "TODO")
12312 (setq gv 'todo))
12314 (setq gv `(org-cached-entry-get nil ,pn))))
12315 (if re-p
12316 (if (eq po 'org<>)
12317 `(not (string-match ,pv (or ,gv "")))
12318 `(string-match ,pv (or ,gv "")))
12319 (if str-p
12320 `(,po (or ,gv "") ,pv)
12321 `(,po (string-to-number (or ,gv ""))
12322 ,(string-to-number pv) ))))
12323 (t `(member ,tag tags-list)))
12324 mm (if minus (list 'not mm) mm)
12325 term rest)
12326 (push mm tagsmatcher))
12327 (push (if (> (length tagsmatcher) 1)
12328 (cons 'and tagsmatcher)
12329 (car tagsmatcher))
12330 orlist)
12331 (setq tagsmatcher nil))
12332 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12333 (setq tagsmatcher
12334 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12335 ;; Make the todo matcher
12336 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12337 (setq todomatcher t)
12338 (setq orterms (org-split-string todomatch "|") orlist nil)
12339 (while (setq term (pop orterms))
12340 (while (string-match re term)
12341 (setq minus (and (match-end 1)
12342 (equal (match-string 1 term) "-"))
12343 kwd (match-string 2 term)
12344 re-p (equal (string-to-char kwd) ?{)
12345 term (substring term (match-end 0))
12346 mm (if re-p
12347 `(string-match ,(substring kwd 1 -1) todo)
12348 (list 'equal 'todo kwd))
12349 mm (if minus (list 'not mm) mm))
12350 (push mm todomatcher))
12351 (push (if (> (length todomatcher) 1)
12352 (cons 'and todomatcher)
12353 (car todomatcher))
12354 orlist)
12355 (setq todomatcher nil))
12356 (setq todomatcher (if (> (length orlist) 1)
12357 (cons 'or orlist) (car orlist))))
12359 ;; Return the string and lisp forms of the matcher
12360 (setq matcher (if todomatcher
12361 (list 'and tagsmatcher todomatcher)
12362 tagsmatcher))
12363 (cons match0 matcher)))
12365 (defun org-op-to-function (op &optional stringp)
12366 "Turn an operator into the appropriate function."
12367 (setq op
12368 (cond
12369 ((equal op "<" ) '(< string< org-time<))
12370 ((equal op ">" ) '(> org-string> org-time>))
12371 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12372 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12373 ((member op '("=" "==")) '(= string= org-time=))
12374 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12375 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12377 (defun org<> (a b) (not (= a b)))
12378 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12379 (defun org-string>= (a b) (not (string< a b)))
12380 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12381 (defun org-string<> (a b) (not (string= a b)))
12382 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12383 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12384 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12385 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12386 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12387 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12388 (defun org-2ft (s)
12389 "Convert S to a floating point time.
12390 If S is already a number, just return it. If it is a string, parse
12391 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12392 (cond
12393 ((numberp s) s)
12394 ((stringp s)
12395 (condition-case nil
12396 (float-time (apply 'encode-time (org-parse-time-string s)))
12397 (error 0.)))
12398 (t 0.)))
12400 (defun org-time-today ()
12401 "Time in seconds today at 0:00.
12402 Returns the float number of seconds since the beginning of the
12403 epoch to the beginning of today (00:00)."
12404 (float-time (apply 'encode-time
12405 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12407 (defun org-matcher-time (s)
12408 "Interpret a time comparison value."
12409 (save-match-data
12410 (cond
12411 ((string= s "<now>") (float-time))
12412 ((string= s "<today>") (org-time-today))
12413 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12414 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12415 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12416 (+ (org-time-today)
12417 (* (string-to-number (match-string 1 s))
12418 (cdr (assoc (match-string 2 s)
12419 '(("d" . 86400.0) ("w" . 604800.0)
12420 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12421 (t (org-2ft s)))))
12423 (defun org-match-any-p (re list)
12424 "Does re match any element of list?"
12425 (setq list (mapcar (lambda (x) (string-match re x)) list))
12426 (delq nil list))
12428 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12429 (defvar org-tags-overlay (make-overlay 1 1))
12430 (org-detach-overlay org-tags-overlay)
12432 (defun org-get-local-tags-at (&optional pos)
12433 "Get a list of tags defined in the current headline."
12434 (org-get-tags-at pos 'local))
12436 (defun org-get-local-tags ()
12437 "Get a list of tags defined in the current headline."
12438 (org-get-tags-at nil 'local))
12440 (defun org-get-tags-at (&optional pos local)
12441 "Get a list of all headline tags applicable at POS.
12442 POS defaults to point. If tags are inherited, the list contains
12443 the targets in the same sequence as the headlines appear, i.e.
12444 the tags of the current headline come last.
12445 When LOCAL is non-nil, only return tags from the current headline,
12446 ignore inherited ones."
12447 (interactive)
12448 (if (and org-trust-scanner-tags
12449 (or (not pos) (equal pos (point)))
12450 (not local))
12451 org-scanner-tags
12452 (let (tags ltags lastpos parent)
12453 (save-excursion
12454 (save-restriction
12455 (widen)
12456 (goto-char (or pos (point)))
12457 (save-match-data
12458 (catch 'done
12459 (condition-case nil
12460 (progn
12461 (org-back-to-heading t)
12462 (while (not (equal lastpos (point)))
12463 (setq lastpos (point))
12464 (when (looking-at
12465 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12466 (setq ltags (org-split-string
12467 (org-match-string-no-properties 1) ":"))
12468 (when parent
12469 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12470 (setq tags (append
12471 (if parent
12472 (org-remove-uniherited-tags ltags)
12473 ltags)
12474 tags)))
12475 (or org-use-tag-inheritance (throw 'done t))
12476 (if local (throw 'done t))
12477 (or (org-up-heading-safe) (error nil))
12478 (setq parent t)))
12479 (error nil)))))
12480 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12482 (defun org-add-prop-inherited (s)
12483 (add-text-properties 0 (length s) '(inherited t) s)
12486 (defun org-toggle-tag (tag &optional onoff)
12487 "Toggle the tag TAG for the current line.
12488 If ONOFF is `on' or `off', don't toggle but set to this state."
12489 (let (res current)
12490 (save-excursion
12491 (org-back-to-heading t)
12492 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12493 (point-at-eol) t)
12494 (progn
12495 (setq current (match-string 1))
12496 (replace-match ""))
12497 (setq current ""))
12498 (setq current (nreverse (org-split-string current ":")))
12499 (cond
12500 ((eq onoff 'on)
12501 (setq res t)
12502 (or (member tag current) (push tag current)))
12503 ((eq onoff 'off)
12504 (or (not (member tag current)) (setq current (delete tag current))))
12505 (t (if (member tag current)
12506 (setq current (delete tag current))
12507 (setq res t)
12508 (push tag current))))
12509 (end-of-line 1)
12510 (if current
12511 (progn
12512 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12513 (org-set-tags nil t))
12514 (delete-horizontal-space))
12515 (run-hooks 'org-after-tags-change-hook))
12516 res))
12518 (defun org-align-tags-here (to-col)
12519 ;; Assumes that this is a headline
12520 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12521 (beginning-of-line 1)
12522 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12523 (< pos (match-beginning 2)))
12524 (progn
12525 (setq tags-l (- (match-end 2) (match-beginning 2)))
12526 (goto-char (match-beginning 1))
12527 (insert " ")
12528 (delete-region (point) (1+ (match-beginning 2)))
12529 (setq ncol (max (1+ (current-column))
12530 (1+ col)
12531 (if (> to-col 0)
12532 to-col
12533 (- (abs to-col) tags-l))))
12534 (setq p (point))
12535 (insert (make-string (- ncol (current-column)) ?\ ))
12536 (setq ncol (current-column))
12537 (when indent-tabs-mode (tabify p (point-at-eol)))
12538 (org-move-to-column (min ncol col) t))
12539 (goto-char pos))))
12541 (defun org-set-tags-command (&optional arg just-align)
12542 "Call the set-tags command for the current entry."
12543 (interactive "P")
12544 (if (org-on-heading-p)
12545 (org-set-tags arg just-align)
12546 (save-excursion
12547 (org-back-to-heading t)
12548 (org-set-tags arg just-align))))
12550 (defun org-set-tags-to (data)
12551 "Set the tags of the current entry to DATA, replacing the current tags.
12552 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12553 If DATA is nil or the empty string, any tags will be removed."
12554 (interactive "sTags: ")
12555 (setq data
12556 (cond
12557 ((eq data nil) "")
12558 ((equal data "") "")
12559 ((stringp data)
12560 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12561 ":"))
12562 ((listp data)
12563 (concat ":" (mapconcat 'identity data ":") ":"))
12564 (t nil)))
12565 (when data
12566 (save-excursion
12567 (org-back-to-heading t)
12568 (when (looking-at org-complex-heading-regexp)
12569 (if (match-end 5)
12570 (progn
12571 (goto-char (match-beginning 5))
12572 (insert data)
12573 (delete-region (point) (point-at-eol))
12574 (org-set-tags nil 'align))
12575 (goto-char (point-at-eol))
12576 (insert " " data)
12577 (org-set-tags nil 'align)))
12578 (beginning-of-line 1)
12579 (if (looking-at ".*?\\([ \t]+\\)$")
12580 (delete-region (match-beginning 1) (match-end 1))))))
12582 (defun org-align-all-tags ()
12583 "Align the tags i all headings."
12584 (interactive)
12585 (save-excursion
12586 (or (ignore-errors (org-back-to-heading t))
12587 (outline-next-heading))
12588 (if (org-on-heading-p)
12589 (org-set-tags t)
12590 (message "No headings"))))
12592 (defun org-set-tags (&optional arg just-align)
12593 "Set the tags for the current headline.
12594 With prefix ARG, realign all tags in headings in the current buffer."
12595 (interactive "P")
12596 (let* ((re (concat "^" outline-regexp))
12597 (current (org-get-tags-string))
12598 (col (current-column))
12599 (org-setting-tags t)
12600 table current-tags inherited-tags ; computed below when needed
12601 tags p0 c0 c1 rpl)
12602 (if arg
12603 (save-excursion
12604 (goto-char (point-min))
12605 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12606 (while (re-search-forward re nil t)
12607 (org-set-tags nil t)
12608 (end-of-line 1)))
12609 (message "All tags realigned to column %d" org-tags-column))
12610 (if just-align
12611 (setq tags current)
12612 ;; Get a new set of tags from the user
12613 (save-excursion
12614 (setq table (append org-tag-persistent-alist
12615 (or org-tag-alist (org-get-buffer-tags))
12616 (and org-complete-tags-always-offer-all-agenda-tags
12617 (org-global-tags-completion-table (org-agenda-files))))
12618 org-last-tags-completion-table table
12619 current-tags (org-split-string current ":")
12620 inherited-tags (nreverse
12621 (nthcdr (length current-tags)
12622 (nreverse (org-get-tags-at))))
12623 tags
12624 (if (or (eq t org-use-fast-tag-selection)
12625 (and org-use-fast-tag-selection
12626 (delq nil (mapcar 'cdr table))))
12627 (org-fast-tag-selection
12628 current-tags inherited-tags table
12629 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12630 (let ((org-add-colon-after-tag-completion t))
12631 (org-trim
12632 (org-without-partial-completion
12633 (org-icompleting-read "Tags: " 'org-tags-completion-function
12634 nil nil current 'org-tags-history)))))))
12635 (while (string-match "[-+&]+" tags)
12636 ;; No boolean logic, just a list
12637 (setq tags (replace-match ":" t t tags))))
12639 (if org-tags-sort-function
12640 (setq tags (mapconcat 'identity
12641 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12642 org-tags-sort-function) ":")))
12644 (if (string-match "\\`[\t ]*\\'" tags)
12645 (setq tags "")
12646 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12647 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12649 ;; Insert new tags at the correct column
12650 (beginning-of-line 1)
12651 (cond
12652 ((and (equal current "") (equal tags "")))
12653 ((re-search-forward
12654 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12655 (point-at-eol) t)
12656 (if (equal tags "")
12657 (setq rpl "")
12658 (goto-char (match-beginning 0))
12659 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12660 (1+ (point)) (point))
12661 c1 (max (1+ c0) (if (> org-tags-column 0)
12662 org-tags-column
12663 (- (- org-tags-column) (length tags))))
12664 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12665 (replace-match rpl t t)
12666 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12667 tags)
12668 (t (error "Tags alignment failed")))
12669 (org-move-to-column col)
12670 (unless just-align
12671 (run-hooks 'org-after-tags-change-hook)))))
12673 (defun org-change-tag-in-region (beg end tag off)
12674 "Add or remove TAG for each entry in the region.
12675 This works in the agenda, and also in an org-mode buffer."
12676 (interactive
12677 (list (region-beginning) (region-end)
12678 (let ((org-last-tags-completion-table
12679 (if (org-mode-p)
12680 (org-get-buffer-tags)
12681 (org-global-tags-completion-table))))
12682 (org-icompleting-read
12683 "Tag: " 'org-tags-completion-function nil nil nil
12684 'org-tags-history))
12685 (progn
12686 (message "[s]et or [r]emove? ")
12687 (equal (read-char-exclusive) ?r))))
12688 (if (fboundp 'deactivate-mark) (deactivate-mark))
12689 (let ((agendap (equal major-mode 'org-agenda-mode))
12690 l1 l2 m buf pos newhead (cnt 0))
12691 (goto-char end)
12692 (setq l2 (1- (org-current-line)))
12693 (goto-char beg)
12694 (setq l1 (org-current-line))
12695 (loop for l from l1 to l2 do
12696 (org-goto-line l)
12697 (setq m (get-text-property (point) 'org-hd-marker))
12698 (when (or (and (org-mode-p) (org-on-heading-p))
12699 (and agendap m))
12700 (setq buf (if agendap (marker-buffer m) (current-buffer))
12701 pos (if agendap m (point)))
12702 (with-current-buffer buf
12703 (save-excursion
12704 (save-restriction
12705 (goto-char pos)
12706 (setq cnt (1+ cnt))
12707 (org-toggle-tag tag (if off 'off 'on))
12708 (setq newhead (org-get-heading)))))
12709 (and agendap (org-agenda-change-all-lines newhead m))))
12710 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12712 (defun org-tags-completion-function (string predicate &optional flag)
12713 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12714 (confirm (lambda (x) (stringp (car x)))))
12715 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12716 (setq s1 (match-string 1 string)
12717 s2 (match-string 2 string))
12718 (setq s1 "" s2 string))
12719 (cond
12720 ((eq flag nil)
12721 ;; try completion
12722 (setq rtn (try-completion s2 ctable confirm))
12723 (if (stringp rtn)
12724 (setq rtn
12725 (concat s1 s2 (substring rtn (length s2))
12726 (if (and org-add-colon-after-tag-completion
12727 (assoc rtn ctable))
12728 ":" ""))))
12729 rtn)
12730 ((eq flag t)
12731 ;; all-completions
12732 (all-completions s2 ctable confirm)
12734 ((eq flag 'lambda)
12735 ;; exact match?
12736 (assoc s2 ctable)))
12739 (defun org-fast-tag-insert (kwd tags face &optional end)
12740 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12741 (insert (format "%-12s" (concat kwd ":"))
12742 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12743 (or end "")))
12745 (defun org-fast-tag-show-exit (flag)
12746 (save-excursion
12747 (org-goto-line 3)
12748 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12749 (replace-match ""))
12750 (when flag
12751 (end-of-line 1)
12752 (org-move-to-column (- (window-width) 19) t)
12753 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12755 (defun org-set-current-tags-overlay (current prefix)
12756 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12757 (if (featurep 'xemacs)
12758 (org-overlay-display org-tags-overlay (concat prefix s)
12759 'secondary-selection)
12760 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12761 (org-overlay-display org-tags-overlay (concat prefix s)))))
12763 (defvar org-last-tag-selection-key nil)
12764 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12765 "Fast tag selection with single keys.
12766 CURRENT is the current list of tags in the headline, INHERITED is the
12767 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12768 possibly with grouping information. TODO-TABLE is a similar table with
12769 TODO keywords, should these have keys assigned to them.
12770 If the keys are nil, a-z are automatically assigned.
12771 Returns the new tags string, or nil to not change the current settings."
12772 (let* ((fulltable (append table todo-table))
12773 (maxlen (apply 'max (mapcar
12774 (lambda (x)
12775 (if (stringp (car x)) (string-width (car x)) 0))
12776 fulltable)))
12777 (buf (current-buffer))
12778 (expert (eq org-fast-tag-selection-single-key 'expert))
12779 (buffer-tags nil)
12780 (fwidth (+ maxlen 3 1 3))
12781 (ncol (/ (- (window-width) 4) fwidth))
12782 (i-face 'org-done)
12783 (c-face 'org-todo)
12784 tg cnt e c char c1 c2 ntable tbl rtn
12785 ov-start ov-end ov-prefix
12786 (exit-after-next org-fast-tag-selection-single-key)
12787 (done-keywords org-done-keywords)
12788 groups ingroup)
12789 (save-excursion
12790 (beginning-of-line 1)
12791 (if (looking-at
12792 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12793 (setq ov-start (match-beginning 1)
12794 ov-end (match-end 1)
12795 ov-prefix "")
12796 (setq ov-start (1- (point-at-eol))
12797 ov-end (1+ ov-start))
12798 (skip-chars-forward "^\n\r")
12799 (setq ov-prefix
12800 (concat
12801 (buffer-substring (1- (point)) (point))
12802 (if (> (current-column) org-tags-column)
12804 (make-string (- org-tags-column (current-column)) ?\ ))))))
12805 (move-overlay org-tags-overlay ov-start ov-end)
12806 (save-window-excursion
12807 (if expert
12808 (set-buffer (get-buffer-create " *Org tags*"))
12809 (delete-other-windows)
12810 (split-window-vertically)
12811 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12812 (erase-buffer)
12813 (org-set-local 'org-done-keywords done-keywords)
12814 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12815 (org-fast-tag-insert "Current" current c-face "\n\n")
12816 (org-fast-tag-show-exit exit-after-next)
12817 (org-set-current-tags-overlay current ov-prefix)
12818 (setq tbl fulltable char ?a cnt 0)
12819 (while (setq e (pop tbl))
12820 (cond
12821 ((equal (car e) :startgroup)
12822 (push '() groups) (setq ingroup t)
12823 (when (not (= cnt 0))
12824 (setq cnt 0)
12825 (insert "\n"))
12826 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12827 ((equal (car e) :endgroup)
12828 (setq ingroup nil cnt 0)
12829 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12830 ((equal e '(:newline))
12831 (when (not (= cnt 0))
12832 (setq cnt 0)
12833 (insert "\n")
12834 (setq e (car tbl))
12835 (while (equal (car tbl) '(:newline))
12836 (insert "\n")
12837 (setq tbl (cdr tbl)))))
12839 (setq tg (copy-sequence (car e)) c2 nil)
12840 (if (cdr e)
12841 (setq c (cdr e))
12842 ;; automatically assign a character.
12843 (setq c1 (string-to-char
12844 (downcase (substring
12845 tg (if (= (string-to-char tg) ?@) 1 0)))))
12846 (if (or (rassoc c1 ntable) (rassoc c1 table))
12847 (while (or (rassoc char ntable) (rassoc char table))
12848 (setq char (1+ char)))
12849 (setq c2 c1))
12850 (setq c (or c2 char)))
12851 (if ingroup (push tg (car groups)))
12852 (setq tg (org-add-props tg nil 'face
12853 (cond
12854 ((not (assoc tg table))
12855 (org-get-todo-face tg))
12856 ((member tg current) c-face)
12857 ((member tg inherited) i-face)
12858 (t nil))))
12859 (if (and (= cnt 0) (not ingroup)) (insert " "))
12860 (insert "[" c "] " tg (make-string
12861 (- fwidth 4 (length tg)) ?\ ))
12862 (push (cons tg c) ntable)
12863 (when (= (setq cnt (1+ cnt)) ncol)
12864 (insert "\n")
12865 (if ingroup (insert " "))
12866 (setq cnt 0)))))
12867 (setq ntable (nreverse ntable))
12868 (insert "\n")
12869 (goto-char (point-min))
12870 (if (not expert) (org-fit-window-to-buffer))
12871 (setq rtn
12872 (catch 'exit
12873 (while t
12874 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12875 (if (not groups) "no " "")
12876 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12877 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12878 (setq org-last-tag-selection-key c)
12879 (cond
12880 ((= c ?\r) (throw 'exit t))
12881 ((= c ?!)
12882 (setq groups (not groups))
12883 (goto-char (point-min))
12884 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12885 ((= c ?\C-c)
12886 (if (not expert)
12887 (org-fast-tag-show-exit
12888 (setq exit-after-next (not exit-after-next)))
12889 (setq expert nil)
12890 (delete-other-windows)
12891 (split-window-vertically)
12892 (org-switch-to-buffer-other-window " *Org tags*")
12893 (org-fit-window-to-buffer)))
12894 ((or (= c ?\C-g)
12895 (and (= c ?q) (not (rassoc c ntable))))
12896 (org-detach-overlay org-tags-overlay)
12897 (setq quit-flag t))
12898 ((= c ?\ )
12899 (setq current nil)
12900 (if exit-after-next (setq exit-after-next 'now)))
12901 ((= c ?\t)
12902 (condition-case nil
12903 (setq tg (org-icompleting-read
12904 "Tag: "
12905 (or buffer-tags
12906 (with-current-buffer buf
12907 (org-get-buffer-tags)))))
12908 (quit (setq tg "")))
12909 (when (string-match "\\S-" tg)
12910 (add-to-list 'buffer-tags (list tg))
12911 (if (member tg current)
12912 (setq current (delete tg current))
12913 (push tg current)))
12914 (if exit-after-next (setq exit-after-next 'now)))
12915 ((setq e (rassoc c todo-table) tg (car e))
12916 (with-current-buffer buf
12917 (save-excursion (org-todo tg)))
12918 (if exit-after-next (setq exit-after-next 'now)))
12919 ((setq e (rassoc c ntable) tg (car e))
12920 (if (member tg current)
12921 (setq current (delete tg current))
12922 (loop for g in groups do
12923 (if (member tg g)
12924 (mapc (lambda (x)
12925 (setq current (delete x current)))
12926 g)))
12927 (push tg current))
12928 (if exit-after-next (setq exit-after-next 'now))))
12930 ;; Create a sorted list
12931 (setq current
12932 (sort current
12933 (lambda (a b)
12934 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12935 (if (eq exit-after-next 'now) (throw 'exit t))
12936 (goto-char (point-min))
12937 (beginning-of-line 2)
12938 (delete-region (point) (point-at-eol))
12939 (org-fast-tag-insert "Current" current c-face)
12940 (org-set-current-tags-overlay current ov-prefix)
12941 (while (re-search-forward
12942 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12943 (setq tg (match-string 1))
12944 (add-text-properties
12945 (match-beginning 1) (match-end 1)
12946 (list 'face
12947 (cond
12948 ((member tg current) c-face)
12949 ((member tg inherited) i-face)
12950 (t (get-text-property (match-beginning 1) 'face))))))
12951 (goto-char (point-min)))))
12952 (org-detach-overlay org-tags-overlay)
12953 (if rtn
12954 (mapconcat 'identity current ":")
12955 nil))))
12957 (defun org-get-tags-string ()
12958 "Get the TAGS string in the current headline."
12959 (unless (org-on-heading-p t)
12960 (error "Not on a heading"))
12961 (save-excursion
12962 (beginning-of-line 1)
12963 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12964 (org-match-string-no-properties 1)
12965 "")))
12967 (defun org-get-tags ()
12968 "Get the list of tags specified in the current headline."
12969 (org-split-string (org-get-tags-string) ":"))
12971 (defun org-get-buffer-tags ()
12972 "Get a table of all tags used in the buffer, for completion."
12973 (let (tags)
12974 (save-excursion
12975 (goto-char (point-min))
12976 (while (re-search-forward
12977 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12978 (when (equal (char-after (point-at-bol 0)) ?*)
12979 (mapc (lambda (x) (add-to-list 'tags x))
12980 (org-split-string (org-match-string-no-properties 1) ":")))))
12981 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12982 (mapcar 'list tags)))
12984 ;;;; The mapping API
12986 ;;;###autoload
12987 (defun org-map-entries (func &optional match scope &rest skip)
12988 "Call FUNC at each headline selected by MATCH in SCOPE.
12990 FUNC is a function or a lisp form. The function will be called without
12991 arguments, with the cursor positioned at the beginning of the headline.
12992 The return values of all calls to the function will be collected and
12993 returned as a list.
12995 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12996 does not need to preserve point. After evaluation, the cursor will be
12997 moved to the end of the line (presumably of the headline of the
12998 processed entry) and search continues from there. Under some
12999 circumstances, this may not produce the wanted results. For example,
13000 if you have removed (e.g. archived) the current (sub)tree it could
13001 mean that the next entry will be skipped entirely. In such cases, you
13002 can specify the position from where search should continue by making
13003 FUNC set the variable `org-map-continue-from' to the desired buffer
13004 position.
13006 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13007 Only headlines that are matched by this query will be considered during
13008 the iteration. When MATCH is nil or t, all headlines will be
13009 visited by the iteration.
13011 SCOPE determines the scope of this command. It can be any of:
13013 nil The current buffer, respecting the restriction if any
13014 tree The subtree started with the entry at point
13015 file The current buffer, without restriction
13016 file-with-archives
13017 The current buffer, and any archives associated with it
13018 agenda All agenda files
13019 agenda-with-archives
13020 All agenda files with any archive files associated with them
13021 \(file1 file2 ...)
13022 If this is a list, all files in the list will be scanned
13024 The remaining args are treated as settings for the skipping facilities of
13025 the scanner. The following items can be given here:
13027 archive skip trees with the archive tag.
13028 comment skip trees with the COMMENT keyword
13029 function or Emacs Lisp form:
13030 will be used as value for `org-agenda-skip-function', so whenever
13031 the function returns t, FUNC will not be called for that
13032 entry and search will continue from the point where the
13033 function leaves it.
13035 If your function needs to retrieve the tags including inherited tags
13036 at the *current* entry, you can use the value of the variable
13037 `org-scanner-tags' which will be much faster than getting the value
13038 with `org-get-tags-at'. If your function gets properties with
13039 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13040 to t around the call to `org-entry-properties' to get the same speedup.
13041 Note that if your function moves around to retrieve tags and properties at
13042 a *different* entry, you cannot use these techniques."
13043 (let* ((org-agenda-archives-mode nil) ; just to make sure
13044 (org-agenda-skip-archived-trees (memq 'archive skip))
13045 (org-agenda-skip-comment-trees (memq 'comment skip))
13046 (org-agenda-skip-function
13047 (car (org-delete-all '(comment archive) skip)))
13048 (org-tags-match-list-sublevels t)
13049 matcher file res
13050 org-todo-keywords-for-agenda
13051 org-done-keywords-for-agenda
13052 org-todo-keyword-alist-for-agenda
13053 org-drawers-for-agenda
13054 org-tag-alist-for-agenda)
13056 (cond
13057 ((eq match t) (setq matcher t))
13058 ((eq match nil) (setq matcher t))
13059 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13061 (save-excursion
13062 (save-restriction
13063 (when (eq scope 'tree)
13064 (org-back-to-heading t)
13065 (org-narrow-to-subtree)
13066 (setq scope nil))
13068 (if (not scope)
13069 (progn
13070 (org-prepare-agenda-buffers
13071 (list (buffer-file-name (current-buffer))))
13072 (setq res (org-scan-tags func matcher)))
13073 ;; Get the right scope
13074 (cond
13075 ((and scope (listp scope) (symbolp (car scope)))
13076 (setq scope (eval scope)))
13077 ((eq scope 'agenda)
13078 (setq scope (org-agenda-files t)))
13079 ((eq scope 'agenda-with-archives)
13080 (setq scope (org-agenda-files t))
13081 (setq scope (org-add-archive-files scope)))
13082 ((eq scope 'file)
13083 (setq scope (list (buffer-file-name))))
13084 ((eq scope 'file-with-archives)
13085 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13086 (org-prepare-agenda-buffers scope)
13087 (while (setq file (pop scope))
13088 (with-current-buffer (org-find-base-buffer-visiting file)
13089 (save-excursion
13090 (save-restriction
13091 (widen)
13092 (goto-char (point-min))
13093 (setq res (append res (org-scan-tags func matcher))))))))))
13094 res))
13096 ;;;; Properties
13098 ;;; Setting and retrieving properties
13100 (defconst org-special-properties
13101 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13102 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13103 "The special properties valid in Org-mode.
13105 These are properties that are not defined in the property drawer,
13106 but in some other way.")
13108 (defconst org-default-properties
13109 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13110 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13111 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13112 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13113 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13114 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13115 "Some properties that are used by Org-mode for various purposes.
13116 Being in this list makes sure that they are offered for completion.")
13118 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13119 "Regular expression matching the first line of a property drawer.")
13121 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13122 "Regular expression matching the last line of a property drawer.")
13124 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13125 "Regular expression matching the first line of a property drawer.")
13127 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13128 "Regular expression matching the first line of a property drawer.")
13130 (defconst org-property-drawer-re
13131 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13132 org-property-end-re "\\)\n?")
13133 "Matches an entire property drawer.")
13135 (defconst org-clock-drawer-re
13136 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13137 org-property-end-re "\\)\n?")
13138 "Matches an entire clock drawer.")
13140 (defun org-property-action ()
13141 "Do an action on properties."
13142 (interactive)
13143 (let (c)
13144 (org-at-property-p)
13145 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13146 (setq c (read-char-exclusive))
13147 (cond
13148 ((equal c ?s)
13149 (call-interactively 'org-set-property))
13150 ((equal c ?d)
13151 (call-interactively 'org-delete-property))
13152 ((equal c ?D)
13153 (call-interactively 'org-delete-property-globally))
13154 ((equal c ?c)
13155 (call-interactively 'org-compute-property-at-point))
13156 (t (error "No such property action %c" c)))))
13158 (defun org-set-effort (&optional value)
13159 "Set the effort property of the current entry.
13160 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13161 allowed value."
13162 (interactive "P")
13163 (if (equal value 0) (setq value 10))
13164 (let* ((completion-ignore-case t)
13165 (prop org-effort-property)
13166 (cur (org-entry-get nil prop))
13167 (allowed (org-property-get-allowed-values nil prop 'table))
13168 (existing (mapcar 'list (org-property-values prop)))
13170 (val (cond
13171 ((stringp value) value)
13172 ((and allowed (integerp value))
13173 (or (car (nth (1- value) allowed))
13174 (car (org-last allowed))))
13175 (allowed
13176 (message "Select 1-9,0, [RET%s]: %s"
13177 (if cur (concat "=" cur) "")
13178 (mapconcat 'car allowed " "))
13179 (setq rpl (read-char-exclusive))
13180 (if (equal rpl ?\r)
13182 (setq rpl (- rpl ?0))
13183 (if (equal rpl 0) (setq rpl 10))
13184 (if (and (> rpl 0) (<= rpl (length allowed)))
13185 (car (nth (1- rpl) allowed))
13186 (org-completing-read "Effort: " allowed nil))))
13188 (let (org-completion-use-ido org-completion-use-iswitchb)
13189 (org-completing-read
13190 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13191 (concat "[" cur "]") "")
13192 ": ")
13193 existing nil nil "" nil cur))))))
13194 (unless (equal (org-entry-get nil prop) val)
13195 (org-entry-put nil prop val))
13196 (message "%s is now %s" prop val)))
13198 (defun org-at-property-p ()
13199 "Is cursor inside a property drawer?"
13200 (save-excursion
13201 (beginning-of-line 1)
13202 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13203 (save-match-data ;; Used by calling procedures
13204 (let ((p (point))
13205 (range (unless (org-before-first-heading-p)
13206 (org-get-property-block))))
13207 (and range (<= (car range) p) (< p (cdr range))))))))
13209 (defun org-get-property-block (&optional beg end force)
13210 "Return the (beg . end) range of the body of the property drawer.
13211 BEG and END can be beginning and end of subtree, if not given
13212 they will be found.
13213 If the drawer does not exist and FORCE is non-nil, create the drawer."
13214 (catch 'exit
13215 (save-excursion
13216 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13217 (end (or end (progn (outline-next-heading) (point)))))
13218 (goto-char beg)
13219 (if (re-search-forward org-property-start-re end t)
13220 (setq beg (1+ (match-end 0)))
13221 (if force
13222 (save-excursion
13223 (org-insert-property-drawer)
13224 (setq end (progn (outline-next-heading) (point))))
13225 (throw 'exit nil))
13226 (goto-char beg)
13227 (if (re-search-forward org-property-start-re end t)
13228 (setq beg (1+ (match-end 0)))))
13229 (if (re-search-forward org-property-end-re end t)
13230 (setq end (match-beginning 0))
13231 (or force (throw 'exit nil))
13232 (goto-char beg)
13233 (setq end beg)
13234 (org-indent-line-function)
13235 (insert ":END:\n"))
13236 (cons beg end)))))
13238 (defun org-entry-properties (&optional pom which specific)
13239 "Get all properties of the entry at point-or-marker POM.
13240 This includes the TODO keyword, the tags, time strings for deadline,
13241 scheduled, and clocking, and any additional properties defined in the
13242 entry. The return value is an alist, keys may occur multiple times
13243 if the property key was used several times.
13244 POM may also be nil, in which case the current entry is used.
13245 If WHICH is nil or `all', get all properties. If WHICH is
13246 `special' or `standard', only get that subclass. If WHICH
13247 is a string only get exactly this property. Specific can be a string, the
13248 specific property we are interested in. Specifying it can speed
13249 things up because then unnecessary parsing is avoided."
13250 (setq which (or which 'all))
13251 (org-with-point-at pom
13252 (let ((clockstr (substring org-clock-string 0 -1))
13253 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13254 (case-fold-search nil)
13255 beg end range props sum-props key value string clocksum)
13256 (save-excursion
13257 (when (condition-case nil
13258 (and (org-mode-p) (org-back-to-heading t))
13259 (error nil))
13260 (setq beg (point))
13261 (setq sum-props (get-text-property (point) 'org-summaries))
13262 (setq clocksum (get-text-property (point) :org-clock-minutes))
13263 (outline-next-heading)
13264 (setq end (point))
13265 (when (memq which '(all special))
13266 ;; Get the special properties, like TODO and tags
13267 (goto-char beg)
13268 (when (and (or (not specific) (string= specific "TODO"))
13269 (looking-at org-todo-line-regexp) (match-end 2))
13270 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13271 (when (and (or (not specific) (string= specific "PRIORITY"))
13272 (looking-at org-priority-regexp))
13273 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13274 (when (and (or (not specific) (string= specific "TAGS"))
13275 (setq value (org-get-tags-string))
13276 (string-match "\\S-" value))
13277 (push (cons "TAGS" value) props))
13278 (when (and (or (not specific) (string= specific "ALLTAGS"))
13279 (setq value (org-get-tags-at)))
13280 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13281 ":"))
13282 props))
13283 (when (or (not specific) (string= specific "BLOCKED"))
13284 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13285 (when (or (not specific)
13286 (member specific org-all-time-keywords)
13287 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
13288 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13289 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
13290 string (if (equal key clockstr)
13291 (org-no-properties
13292 (org-trim
13293 (buffer-substring
13294 (match-beginning 3) (goto-char (point-at-eol)))))
13295 (substring (org-match-string-no-properties 3) 1 -1)))
13296 (unless key
13297 (if (= (char-after (match-beginning 3)) ?\[)
13298 (setq key "TIMESTAMP_IA")
13299 (setq key "TIMESTAMP")))
13300 (when (or (equal key clockstr) (not (assoc key props)))
13301 (push (cons key string) props))))
13305 (when (memq which '(all standard))
13306 ;; Get the standard properties, like :PROP: ...
13307 (setq range (org-get-property-block beg end))
13308 (when range
13309 (goto-char (car range))
13310 (while (re-search-forward
13311 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13312 (cdr range) t)
13313 (setq key (org-match-string-no-properties 1)
13314 value (org-trim (or (org-match-string-no-properties 2) "")))
13315 (unless (member key excluded)
13316 (push (cons key (or value "")) props)))))
13317 (if clocksum
13318 (push (cons "CLOCKSUM"
13319 (org-columns-number-to-string (/ (float clocksum) 60.)
13320 'add_times))
13321 props))
13322 (unless (assoc "CATEGORY" props)
13323 (setq value (or (org-get-category)
13324 (progn (org-refresh-category-properties)
13325 (org-get-category))))
13326 (push (cons "CATEGORY" value) props))
13327 (append sum-props (nreverse props)))))))
13329 (defun org-entry-get (pom property &optional inherit)
13330 "Get value of PROPERTY for entry at point-or-marker POM.
13331 If INHERIT is non-nil and the entry does not have the property,
13332 then also check higher levels of the hierarchy.
13333 If INHERIT is the symbol `selective', use inheritance only if the setting
13334 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13335 If the property is present but empty, the return value is the empty string.
13336 If the property is not present at all, nil is returned."
13337 (org-with-point-at pom
13338 (if (and inherit (if (eq inherit 'selective)
13339 (org-property-inherit-p property)
13341 (org-entry-get-with-inheritance property)
13342 (if (member property org-special-properties)
13343 ;; We need a special property. Use `org-entry-properties' to
13344 ;; retrieve it, but specify the wanted property
13345 (cdr (assoc property (org-entry-properties nil 'special property)))
13346 (let ((range (org-get-property-block)))
13347 (if (and range
13348 (goto-char (car range))
13349 (re-search-forward
13350 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13351 (cdr range) t))
13352 ;; Found the property, return it.
13353 (if (match-end 1)
13354 (org-match-string-no-properties 1)
13355 "")))))))
13357 (defun org-property-or-variable-value (var &optional inherit)
13358 "Check if there is a property fixing the value of VAR.
13359 If yes, return this value. If not, return the current value of the variable."
13360 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13361 (if (and prop (stringp prop) (string-match "\\S-" prop))
13362 (read prop)
13363 (symbol-value var))))
13365 (defun org-entry-delete (pom property)
13366 "Delete the property PROPERTY from entry at point-or-marker POM."
13367 (org-with-point-at pom
13368 (if (member property org-special-properties)
13369 nil ; cannot delete these properties.
13370 (let ((range (org-get-property-block)))
13371 (if (and range
13372 (goto-char (car range))
13373 (re-search-forward
13374 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13375 (cdr range) t))
13376 (progn
13377 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13379 nil)))))
13381 ;; Multi-values properties are properties that contain multiple values
13382 ;; These values are assumed to be single words, separated by whitespace.
13383 (defun org-entry-add-to-multivalued-property (pom property value)
13384 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13385 (let* ((old (org-entry-get pom property))
13386 (values (and old (org-split-string old "[ \t]"))))
13387 (setq value (org-entry-protect-space value))
13388 (unless (member value values)
13389 (setq values (cons value values))
13390 (org-entry-put pom property
13391 (mapconcat 'identity values " ")))))
13393 (defun org-entry-remove-from-multivalued-property (pom property value)
13394 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13395 (let* ((old (org-entry-get pom property))
13396 (values (and old (org-split-string old "[ \t]"))))
13397 (setq value (org-entry-protect-space value))
13398 (when (member value values)
13399 (setq values (delete value values))
13400 (org-entry-put pom property
13401 (mapconcat 'identity values " ")))))
13403 (defun org-entry-member-in-multivalued-property (pom property value)
13404 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13405 (let* ((old (org-entry-get pom property))
13406 (values (and old (org-split-string old "[ \t]"))))
13407 (setq value (org-entry-protect-space value))
13408 (member value values)))
13410 (defun org-entry-get-multivalued-property (pom property)
13411 "Return a list of values in a multivalued property."
13412 (let* ((value (org-entry-get pom property))
13413 (values (and value (org-split-string value "[ \t]"))))
13414 (mapcar 'org-entry-restore-space values)))
13416 (defun org-entry-put-multivalued-property (pom property &rest values)
13417 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13418 VALUES should be a list of strings. Spaces will be protected."
13419 (org-entry-put pom property
13420 (mapconcat 'org-entry-protect-space values " "))
13421 (let* ((value (org-entry-get pom property))
13422 (values (and value (org-split-string value "[ \t]"))))
13423 (mapcar 'org-entry-restore-space values)))
13425 (defun org-entry-protect-space (s)
13426 "Protect spaces and newline in string S."
13427 (while (string-match " " s)
13428 (setq s (replace-match "%20" t t s)))
13429 (while (string-match "\n" s)
13430 (setq s (replace-match "%0A" t t s)))
13433 (defun org-entry-restore-space (s)
13434 "Restore spaces and newline in string S."
13435 (while (string-match "%20" s)
13436 (setq s (replace-match " " t t s)))
13437 (while (string-match "%0A" s)
13438 (setq s (replace-match "\n" t t s)))
13441 (defvar org-entry-property-inherited-from (make-marker)
13442 "Marker pointing to the entry from where a property was inherited.
13443 Each call to `org-entry-get-with-inheritance' will set this marker to the
13444 location of the entry where the inheritance search matched. If there was
13445 no match, the marker will point nowhere.
13446 Note that also `org-entry-get' calls this function, if the INHERIT flag
13447 is set.")
13449 (defun org-entry-get-with-inheritance (property)
13450 "Get entry property, and search higher levels if not present."
13451 (move-marker org-entry-property-inherited-from nil)
13452 (let (tmp)
13453 (save-excursion
13454 (save-restriction
13455 (widen)
13456 (catch 'ex
13457 (while t
13458 (when (setq tmp (org-entry-get nil property))
13459 (org-back-to-heading t)
13460 (move-marker org-entry-property-inherited-from (point))
13461 (throw 'ex tmp))
13462 (or (org-up-heading-safe) (throw 'ex nil)))))
13463 (or tmp
13464 (cdr (assoc property org-file-properties))
13465 (cdr (assoc property org-global-properties))
13466 (cdr (assoc property org-global-properties-fixed))))))
13468 (defvar org-property-changed-functions nil
13469 "Hook called when the value of a property has changed.
13470 Each hook function should accept two arguments, the name of the property
13471 and the new value.")
13473 (defun org-entry-put (pom property value)
13474 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13475 (org-with-point-at pom
13476 (org-back-to-heading t)
13477 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13478 range)
13479 (cond
13480 ((equal property "TODO")
13481 (when (and (stringp value) (string-match "\\S-" value)
13482 (not (member value org-todo-keywords-1)))
13483 (error "\"%s\" is not a valid TODO state" value))
13484 (if (or (not value)
13485 (not (string-match "\\S-" value)))
13486 (setq value 'none))
13487 (org-todo value)
13488 (org-set-tags nil 'align))
13489 ((equal property "PRIORITY")
13490 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13491 (string-to-char value) ?\ ))
13492 (org-set-tags nil 'align))
13493 ((equal property "SCHEDULED")
13494 (if (re-search-forward org-scheduled-time-regexp end t)
13495 (cond
13496 ((eq value 'earlier) (org-timestamp-change -1 'day))
13497 ((eq value 'later) (org-timestamp-change 1 'day))
13498 (t (call-interactively 'org-schedule)))
13499 (call-interactively 'org-schedule)))
13500 ((equal property "DEADLINE")
13501 (if (re-search-forward org-deadline-time-regexp end t)
13502 (cond
13503 ((eq value 'earlier) (org-timestamp-change -1 'day))
13504 ((eq value 'later) (org-timestamp-change 1 'day))
13505 (t (call-interactively 'org-deadline)))
13506 (call-interactively 'org-deadline)))
13507 ((member property org-special-properties)
13508 (error "The %s property can not yet be set with `org-entry-put'"
13509 property))
13510 (t ; a non-special property
13511 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13512 (setq range (org-get-property-block beg end 'force))
13513 (goto-char (car range))
13514 (if (re-search-forward
13515 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13516 (progn
13517 (delete-region (match-beginning 1) (match-end 1))
13518 (goto-char (match-beginning 1)))
13519 (goto-char (cdr range))
13520 (insert "\n")
13521 (backward-char 1)
13522 (org-indent-line-function)
13523 (insert ":" property ":"))
13524 (and value (insert " " value))
13525 (org-indent-line-function)))))
13526 (run-hook-with-args 'org-property-changed-functions property value)))
13528 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13529 "Get all property keys in the current buffer.
13530 With INCLUDE-SPECIALS, also list the special properties that reflect things
13531 like tags and TODO state.
13532 With INCLUDE-DEFAULTS, also include properties that has special meaning
13533 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13534 With INCLUDE-COLUMNS, also include property names given in COLUMN
13535 formats in the current buffer."
13536 (let (rtn range cfmt s p)
13537 (save-excursion
13538 (save-restriction
13539 (widen)
13540 (goto-char (point-min))
13541 (while (re-search-forward org-property-start-re nil t)
13542 (setq range (org-get-property-block))
13543 (goto-char (car range))
13544 (while (re-search-forward
13545 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13546 (cdr range) t)
13547 (add-to-list 'rtn (org-match-string-no-properties 1)))
13548 (outline-next-heading))))
13550 (when include-specials
13551 (setq rtn (append org-special-properties rtn)))
13553 (when include-defaults
13554 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13555 (add-to-list 'rtn org-effort-property))
13557 (when include-columns
13558 (save-excursion
13559 (save-restriction
13560 (widen)
13561 (goto-char (point-min))
13562 (while (re-search-forward
13563 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13564 nil t)
13565 (setq cfmt (match-string 2) s 0)
13566 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13567 cfmt s)
13568 (setq s (match-end 0)
13569 p (match-string 1 cfmt))
13570 (unless (or (equal p "ITEM")
13571 (member p org-special-properties))
13572 (add-to-list 'rtn (match-string 1 cfmt))))))))
13574 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13576 (defun org-property-values (key)
13577 "Return a list of all values of property KEY."
13578 (save-excursion
13579 (save-restriction
13580 (widen)
13581 (goto-char (point-min))
13582 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13583 values)
13584 (while (re-search-forward re nil t)
13585 (add-to-list 'values (org-trim (match-string 1))))
13586 (delete "" values)))))
13588 (defun org-insert-property-drawer ()
13589 "Insert a property drawer into the current entry."
13590 (interactive)
13591 (org-back-to-heading t)
13592 (looking-at outline-regexp)
13593 (let ((indent (if org-adapt-indentation
13594 (- (match-end 0)(match-beginning 0))
13596 (beg (point))
13597 (re (concat "^[ \t]*" org-keyword-time-regexp))
13598 end hiddenp)
13599 (outline-next-heading)
13600 (setq end (point))
13601 (goto-char beg)
13602 (while (re-search-forward re end t))
13603 (setq hiddenp (org-invisible-p))
13604 (end-of-line 1)
13605 (and (equal (char-after) ?\n) (forward-char 1))
13606 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13607 (if (member (match-string 1) '("CLOCK:" ":END:"))
13608 ;; just skip this line
13609 (beginning-of-line 2)
13610 ;; Drawer start, find the end
13611 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13612 (beginning-of-line 1)))
13613 (org-skip-over-state-notes)
13614 (skip-chars-backward " \t\n\r")
13615 (if (eq (char-before) ?*) (forward-char 1))
13616 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13617 (beginning-of-line 0)
13618 (org-indent-to-column indent)
13619 (beginning-of-line 2)
13620 (org-indent-to-column indent)
13621 (beginning-of-line 0)
13622 (if hiddenp
13623 (save-excursion
13624 (org-back-to-heading t)
13625 (hide-entry))
13626 (org-flag-drawer t))))
13628 (defun org-set-property (property value)
13629 "In the current entry, set PROPERTY to VALUE.
13630 When called interactively, this will prompt for a property name, offering
13631 completion on existing and default properties. And then it will prompt
13632 for a value, offering completion either on allowed values (via an inherited
13633 xxx_ALL property) or on existing values in other instances of this property
13634 in the current file."
13635 (interactive
13636 (let* ((completion-ignore-case t)
13637 (keys (org-buffer-property-keys nil t t))
13638 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13639 (prop (if (member prop0 keys)
13640 prop0
13641 (or (cdr (assoc (downcase prop0)
13642 (mapcar (lambda (x) (cons (downcase x) x))
13643 keys)))
13644 prop0)))
13645 (cur (org-entry-get nil prop))
13646 (prompt (concat prop " value"
13647 (if (and cur (string-match "\\S-" cur))
13648 (concat " [" cur "]") "") ": "))
13649 (allowed (org-property-get-allowed-values nil prop 'table))
13650 (existing (mapcar 'list (org-property-values prop)))
13651 (val (if allowed
13652 (org-completing-read prompt allowed nil
13653 (not (get-text-property 0 'org-unrestricted
13654 (caar allowed))))
13655 (let (org-completion-use-ido org-completion-use-iswitchb)
13656 (org-completing-read prompt existing nil nil "" nil cur)))))
13657 (list prop (if (equal val "") cur val))))
13658 (unless (equal (org-entry-get nil property) value)
13659 (org-entry-put nil property value)))
13661 (defun org-delete-property (property)
13662 "In the current entry, delete PROPERTY."
13663 (interactive
13664 (let* ((completion-ignore-case t)
13665 (prop (org-icompleting-read "Property: "
13666 (org-entry-properties nil 'standard))))
13667 (list prop)))
13668 (message "Property %s %s" property
13669 (if (org-entry-delete nil property)
13670 "deleted"
13671 "was not present in the entry")))
13673 (defun org-delete-property-globally (property)
13674 "Remove PROPERTY globally, from all entries."
13675 (interactive
13676 (let* ((completion-ignore-case t)
13677 (prop (org-icompleting-read
13678 "Globally remove property: "
13679 (mapcar 'list (org-buffer-property-keys)))))
13680 (list prop)))
13681 (save-excursion
13682 (save-restriction
13683 (widen)
13684 (goto-char (point-min))
13685 (let ((cnt 0))
13686 (while (re-search-forward
13687 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13688 nil t)
13689 (setq cnt (1+ cnt))
13690 (replace-match ""))
13691 (message "Property \"%s\" removed from %d entries" property cnt)))))
13693 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13695 (defun org-compute-property-at-point ()
13696 "Compute the property at point.
13697 This looks for an enclosing column format, extracts the operator and
13698 then applies it to the property in the column format's scope."
13699 (interactive)
13700 (unless (org-at-property-p)
13701 (error "Not at a property"))
13702 (let ((prop (org-match-string-no-properties 2)))
13703 (org-columns-get-format-and-top-level)
13704 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13705 (error "No operator defined for property %s" prop))
13706 (org-columns-compute prop)))
13708 (defvar org-property-allowed-value-functions nil
13709 "Hook for functions supplying allowed values for a specific property.
13710 The functions must take a single argument, the name of the property, and
13711 return a flat list of allowed values. If \":ETC\" is one of
13712 the values, this means that these values are intended as defaults for
13713 completion, but that other values should be allowed too.
13714 The functions must return nil if they are not responsible for this
13715 property.")
13717 (defun org-property-get-allowed-values (pom property &optional table)
13718 "Get allowed values for the property PROPERTY.
13719 When TABLE is non-nil, return an alist that can directly be used for
13720 completion."
13721 (let (vals)
13722 (cond
13723 ((equal property "TODO")
13724 (setq vals (org-with-point-at pom
13725 (append org-todo-keywords-1 '("")))))
13726 ((equal property "PRIORITY")
13727 (let ((n org-lowest-priority))
13728 (while (>= n org-highest-priority)
13729 (push (char-to-string n) vals)
13730 (setq n (1- n)))))
13731 ((member property org-special-properties))
13732 ((setq vals (run-hook-with-args-until-success
13733 'org-property-allowed-value-functions property)))
13735 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13736 (when (and vals (string-match "\\S-" vals))
13737 (setq vals (car (read-from-string (concat "(" vals ")"))))
13738 (setq vals (mapcar (lambda (x)
13739 (cond ((stringp x) x)
13740 ((numberp x) (number-to-string x))
13741 ((symbolp x) (symbol-name x))
13742 (t "???")))
13743 vals)))))
13744 (when (member ":ETC" vals)
13745 (setq vals (remove ":ETC" vals))
13746 (org-add-props (car vals) '(org-unrestricted t)))
13747 (if table (mapcar 'list vals) vals)))
13749 (defun org-property-previous-allowed-value (&optional previous)
13750 "Switch to the next allowed value for this property."
13751 (interactive)
13752 (org-property-next-allowed-value t))
13754 (defun org-property-next-allowed-value (&optional previous)
13755 "Switch to the next allowed value for this property."
13756 (interactive)
13757 (unless (org-at-property-p)
13758 (error "Not at a property"))
13759 (let* ((key (match-string 2))
13760 (value (match-string 3))
13761 (allowed (or (org-property-get-allowed-values (point) key)
13762 (and (member value '("[ ]" "[-]" "[X]"))
13763 '("[ ]" "[X]"))))
13764 nval)
13765 (unless allowed
13766 (error "Allowed values for this property have not been defined"))
13767 (if previous (setq allowed (reverse allowed)))
13768 (if (member value allowed)
13769 (setq nval (car (cdr (member value allowed)))))
13770 (setq nval (or nval (car allowed)))
13771 (if (equal nval value)
13772 (error "Only one allowed value for this property"))
13773 (org-at-property-p)
13774 (replace-match (concat " :" key ": " nval) t t)
13775 (org-indent-line-function)
13776 (beginning-of-line 1)
13777 (skip-chars-forward " \t")
13778 (run-hook-with-args 'org-property-changed-functions key nval)))
13780 (defun org-find-olp (path)
13781 "Return a marker pointing to the entry at outline path OLP.
13782 If anything goes wrong, throw an error.
13783 You can wrap this call to cathc the error like this:
13785 (condition-case msg
13786 (org-mobile-locate-entry (match-string 4))
13787 (error (nth 1 msg)))
13789 The return value will then be either a string with the error message,
13790 or a marker if everyhing is OK."
13791 (let* ((file (pop path))
13792 (buffer (find-file-noselect file))
13793 (level 1)
13794 (lmin 1)
13795 (lmax 1)
13796 limit re end found pos heading cnt)
13797 (unless buffer (error "File not found :%s" file))
13798 (with-current-buffer buffer
13799 (save-excursion
13800 (save-restriction
13801 (widen)
13802 (setq limit (point-max))
13803 (goto-char (point-min))
13804 (while (setq heading (pop path))
13805 (setq re (format org-complex-heading-regexp-format
13806 (regexp-quote heading)))
13807 (setq cnt 0 pos (point))
13808 (while (re-search-forward re end t)
13809 (setq level (- (match-end 1) (match-beginning 1)))
13810 (if (and (>= level lmin) (<= level lmax))
13811 (setq found (match-beginning 0) cnt (1+ cnt))))
13812 (when (= cnt 0) (error "Heading not found on level %d: %s"
13813 lmax heading))
13814 (when (> cnt 1) (error "Heading not unique on level %d: %s"
13815 lmax heading))
13816 (goto-char found)
13817 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
13818 (setq end (save-excursion (org-end-of-subtree t t))))
13819 (when (org-on-heading-p)
13820 (move-marker (make-marker) (point))))))))
13822 (defun org-find-entry-with-id (ident)
13823 "Locate the entry that contains the ID property with exact value IDENT.
13824 IDENT can be a string, a symbol or a number, this function will search for
13825 the string representation of it.
13826 Return the position where this entry starts, or nil if there is no such entry."
13827 (interactive "sID: ")
13828 (let ((id (cond
13829 ((stringp ident) ident)
13830 ((symbol-name ident) (symbol-name ident))
13831 ((numberp ident) (number-to-string ident))
13832 (t (error "IDENT %s must be a string, symbol or number" ident))))
13833 (case-fold-search nil))
13834 (save-excursion
13835 (save-restriction
13836 (widen)
13837 (goto-char (point-min))
13838 (when (re-search-forward
13839 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13840 nil t)
13841 (org-back-to-heading t)
13842 (point))))))
13844 ;;;; Timestamps
13846 (defvar org-last-changed-timestamp nil)
13847 (defvar org-last-inserted-timestamp nil
13848 "The last time stamp inserted with `org-insert-time-stamp'.")
13849 (defvar org-time-was-given) ; dynamically scoped parameter
13850 (defvar org-end-time-was-given) ; dynamically scoped parameter
13851 (defvar org-ts-what) ; dynamically scoped parameter
13853 (defun org-time-stamp (arg &optional inactive)
13854 "Prompt for a date/time and insert a time stamp.
13855 If the user specifies a time like HH:MM, or if this command is called
13856 with a prefix argument, the time stamp will contain date and time.
13857 Otherwise, only the date will be included. All parts of a date not
13858 specified by the user will be filled in from the current date/time.
13859 So if you press just return without typing anything, the time stamp
13860 will represent the current date/time. If there is already a timestamp
13861 at the cursor, it will be modified."
13862 (interactive "P")
13863 (let* ((ts nil)
13864 (default-time
13865 ;; Default time is either today, or, when entering a range,
13866 ;; the range start.
13867 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13868 (save-excursion
13869 (re-search-backward
13870 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13871 (- (point) 20) t)))
13872 (apply 'encode-time (org-parse-time-string (match-string 1)))
13873 (current-time)))
13874 (default-input (and ts (org-get-compact-tod ts)))
13875 org-time-was-given org-end-time-was-given time)
13876 (cond
13877 ((and (org-at-timestamp-p t)
13878 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13879 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13880 (insert "--")
13881 (setq time (let ((this-command this-command))
13882 (org-read-date arg 'totime nil nil
13883 default-time default-input)))
13884 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13885 ((org-at-timestamp-p t)
13886 (setq time (let ((this-command this-command))
13887 (org-read-date arg 'totime nil nil default-time default-input)))
13888 (when (org-at-timestamp-p t) ; just to get the match data
13889 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13890 (replace-match "")
13891 (setq org-last-changed-timestamp
13892 (org-insert-time-stamp
13893 time (or org-time-was-given arg)
13894 inactive nil nil (list org-end-time-was-given))))
13895 (message "Timestamp updated"))
13897 (setq time (let ((this-command this-command))
13898 (org-read-date arg 'totime nil nil default-time default-input)))
13899 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13900 nil nil (list org-end-time-was-given))))))
13902 ;; FIXME: can we use this for something else, like computing time differences?
13903 (defun org-get-compact-tod (s)
13904 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13905 (let* ((t1 (match-string 1 s))
13906 (h1 (string-to-number (match-string 2 s)))
13907 (m1 (string-to-number (match-string 3 s)))
13908 (t2 (and (match-end 4) (match-string 5 s)))
13909 (h2 (and t2 (string-to-number (match-string 6 s))))
13910 (m2 (and t2 (string-to-number (match-string 7 s))))
13911 dh dm)
13912 (if (not t2)
13914 (setq dh (- h2 h1) dm (- m2 m1))
13915 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13916 (concat t1 "+" (number-to-string dh)
13917 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13919 (defun org-time-stamp-inactive (&optional arg)
13920 "Insert an inactive time stamp.
13921 An inactive time stamp is enclosed in square brackets instead of angle
13922 brackets. It is inactive in the sense that it does not trigger agenda entries,
13923 does not link to the calendar and cannot be changed with the S-cursor keys.
13924 So these are more for recording a certain time/date."
13925 (interactive "P")
13926 (org-time-stamp arg 'inactive))
13928 (defvar org-date-ovl (make-overlay 1 1))
13929 (overlay-put org-date-ovl 'face 'org-warning)
13930 (org-detach-overlay org-date-ovl)
13932 (defvar org-ans1) ; dynamically scoped parameter
13933 (defvar org-ans2) ; dynamically scoped parameter
13935 (defvar org-plain-time-of-day-regexp) ; defined below
13937 (defvar org-overriding-default-time nil) ; dynamically scoped
13938 (defvar org-read-date-overlay nil)
13939 (defvar org-dcst nil) ; dynamically scoped
13940 (defvar org-read-date-history nil)
13941 (defvar org-read-date-final-answer nil)
13943 (defun org-read-date (&optional with-time to-time from-string prompt
13944 default-time default-input)
13945 "Read a date, possibly a time, and make things smooth for the user.
13946 The prompt will suggest to enter an ISO date, but you can also enter anything
13947 which will at least partially be understood by `parse-time-string'.
13948 Unrecognized parts of the date will default to the current day, month, year,
13949 hour and minute. If this command is called to replace a timestamp at point,
13950 of to enter the second timestamp of a range, the default time is taken
13951 from the existing stamp. Furthermore, the command prefers the future,
13952 so if you are giving a date where the year is not given, and the day-month
13953 combination is already past in the current year, it will assume you
13954 mean next year. For details, see the manual. A few examples:
13956 3-2-5 --> 2003-02-05
13957 feb 15 --> currentyear-02-15
13958 2/15 --> currentyear-02-15
13959 sep 12 9 --> 2009-09-12
13960 12:45 --> today 12:45
13961 22 sept 0:34 --> currentyear-09-22 0:34
13962 12 --> currentyear-currentmonth-12
13963 Fri --> nearest Friday (today or later)
13964 etc.
13966 Furthermore you can specify a relative date by giving, as the *first* thing
13967 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13968 change in days weeks, months, years.
13969 With a single plus or minus, the date is relative to today. With a double
13970 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13971 +4d --> four days from today
13972 +4 --> same as above
13973 +2w --> two weeks from today
13974 ++5 --> five days from default date
13976 The function understands only English month and weekday abbreviations,
13977 but this can be configured with the variables `parse-time-months' and
13978 `parse-time-weekdays'.
13980 While prompting, a calendar is popped up - you can also select the
13981 date with the mouse (button 1). The calendar shows a period of three
13982 months. To scroll it to other months, use the keys `>' and `<'.
13983 If you don't like the calendar, turn it off with
13984 \(setq org-read-date-popup-calendar nil)
13986 With optional argument TO-TIME, the date will immediately be converted
13987 to an internal time.
13988 With an optional argument WITH-TIME, the prompt will suggest to also
13989 insert a time. Note that when WITH-TIME is not set, you can still
13990 enter a time, and this function will inform the calling routine about
13991 this change. The calling routine may then choose to change the format
13992 used to insert the time stamp into the buffer to include the time.
13993 With optional argument FROM-STRING, read from this string instead from
13994 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13995 the time/date that is used for everything that is not specified by the
13996 user."
13997 (require 'parse-time)
13998 (let* ((org-time-stamp-rounding-minutes
13999 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14000 (org-dcst org-display-custom-times)
14001 (ct (org-current-time))
14002 (def (or org-overriding-default-time default-time ct))
14003 (defdecode (decode-time def))
14004 (dummy (progn
14005 (when (< (nth 2 defdecode) org-extend-today-until)
14006 (setcar (nthcdr 2 defdecode) -1)
14007 (setcar (nthcdr 1 defdecode) 59)
14008 (setq def (apply 'encode-time defdecode)
14009 defdecode (decode-time def)))))
14010 (calendar-frame-setup nil)
14011 (calendar-setup nil)
14012 (calendar-move-hook nil)
14013 (calendar-view-diary-initially-flag nil)
14014 (calendar-view-holidays-initially-flag nil)
14015 (timestr (format-time-string
14016 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14017 (prompt (concat (if prompt (concat prompt " ") "")
14018 (format "Date+time [%s]: " timestr)))
14019 ans (org-ans0 "") org-ans1 org-ans2 final)
14021 (cond
14022 (from-string (setq ans from-string))
14023 (org-read-date-popup-calendar
14024 (save-excursion
14025 (save-window-excursion
14026 (calendar)
14027 (calendar-forward-day (- (time-to-days def)
14028 (calendar-absolute-from-gregorian
14029 (calendar-current-date))))
14030 (org-eval-in-calendar nil t)
14031 (let* ((old-map (current-local-map))
14032 (map (copy-keymap calendar-mode-map))
14033 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14034 (org-defkey map (kbd "RET") 'org-calendar-select)
14035 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14036 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14037 (org-defkey minibuffer-local-map [(meta shift left)]
14038 (lambda () (interactive)
14039 (org-eval-in-calendar '(calendar-backward-month 1))))
14040 (org-defkey minibuffer-local-map [(meta shift right)]
14041 (lambda () (interactive)
14042 (org-eval-in-calendar '(calendar-forward-month 1))))
14043 (org-defkey minibuffer-local-map [(meta shift up)]
14044 (lambda () (interactive)
14045 (org-eval-in-calendar '(calendar-backward-year 1))))
14046 (org-defkey minibuffer-local-map [(meta shift down)]
14047 (lambda () (interactive)
14048 (org-eval-in-calendar '(calendar-forward-year 1))))
14049 (org-defkey minibuffer-local-map [?\e (shift left)]
14050 (lambda () (interactive)
14051 (org-eval-in-calendar '(calendar-backward-month 1))))
14052 (org-defkey minibuffer-local-map [?\e (shift right)]
14053 (lambda () (interactive)
14054 (org-eval-in-calendar '(calendar-forward-month 1))))
14055 (org-defkey minibuffer-local-map [?\e (shift up)]
14056 (lambda () (interactive)
14057 (org-eval-in-calendar '(calendar-backward-year 1))))
14058 (org-defkey minibuffer-local-map [?\e (shift down)]
14059 (lambda () (interactive)
14060 (org-eval-in-calendar '(calendar-forward-year 1))))
14061 (org-defkey minibuffer-local-map [(shift up)]
14062 (lambda () (interactive)
14063 (org-eval-in-calendar '(calendar-backward-week 1))))
14064 (org-defkey minibuffer-local-map [(shift down)]
14065 (lambda () (interactive)
14066 (org-eval-in-calendar '(calendar-forward-week 1))))
14067 (org-defkey minibuffer-local-map [(shift left)]
14068 (lambda () (interactive)
14069 (org-eval-in-calendar '(calendar-backward-day 1))))
14070 (org-defkey minibuffer-local-map [(shift right)]
14071 (lambda () (interactive)
14072 (org-eval-in-calendar '(calendar-forward-day 1))))
14073 (org-defkey minibuffer-local-map ">"
14074 (lambda () (interactive)
14075 (org-eval-in-calendar '(scroll-calendar-left 1))))
14076 (org-defkey minibuffer-local-map "<"
14077 (lambda () (interactive)
14078 (org-eval-in-calendar '(scroll-calendar-right 1))))
14079 (org-defkey minibuffer-local-map "\C-v"
14080 (lambda () (interactive)
14081 (org-eval-in-calendar
14082 '(calendar-scroll-left-three-months 1))))
14083 (org-defkey minibuffer-local-map "\M-v"
14084 (lambda () (interactive)
14085 (org-eval-in-calendar
14086 '(calendar-scroll-right-three-months 1))))
14087 (run-hooks 'org-read-date-minibuffer-setup-hook)
14088 (unwind-protect
14089 (progn
14090 (use-local-map map)
14091 (add-hook 'post-command-hook 'org-read-date-display)
14092 (setq org-ans0 (read-string prompt default-input
14093 'org-read-date-history nil))
14094 ;; org-ans0: from prompt
14095 ;; org-ans1: from mouse click
14096 ;; org-ans2: from calendar motion
14097 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14098 (remove-hook 'post-command-hook 'org-read-date-display)
14099 (use-local-map old-map)
14100 (when org-read-date-overlay
14101 (delete-overlay org-read-date-overlay)
14102 (setq org-read-date-overlay nil)))))))
14104 (t ; Naked prompt only
14105 (unwind-protect
14106 (setq ans (read-string prompt default-input
14107 'org-read-date-history timestr))
14108 (when org-read-date-overlay
14109 (delete-overlay org-read-date-overlay)
14110 (setq org-read-date-overlay nil)))))
14112 (setq final (org-read-date-analyze ans def defdecode))
14113 (setq org-read-date-final-answer ans)
14115 (if to-time
14116 (apply 'encode-time final)
14117 (if (and (boundp 'org-time-was-given) org-time-was-given)
14118 (format "%04d-%02d-%02d %02d:%02d"
14119 (nth 5 final) (nth 4 final) (nth 3 final)
14120 (nth 2 final) (nth 1 final))
14121 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14123 (defvar def)
14124 (defvar defdecode)
14125 (defvar with-time)
14126 (defvar org-read-date-analyze-futurep nil)
14127 (defun org-read-date-display ()
14128 "Display the current date prompt interpretation in the minibuffer."
14129 (when org-read-date-display-live
14130 (when org-read-date-overlay
14131 (delete-overlay org-read-date-overlay))
14132 (let ((p (point)))
14133 (end-of-line 1)
14134 (while (not (equal (buffer-substring
14135 (max (point-min) (- (point) 4)) (point))
14136 " "))
14137 (insert " "))
14138 (goto-char p))
14139 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14140 " " (or org-ans1 org-ans2)))
14141 (org-end-time-was-given nil)
14142 (f (org-read-date-analyze ans def defdecode))
14143 (fmts (if org-dcst
14144 org-time-stamp-custom-formats
14145 org-time-stamp-formats))
14146 (fmt (if (or with-time
14147 (and (boundp 'org-time-was-given) org-time-was-given))
14148 (cdr fmts)
14149 (car fmts)))
14150 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14151 (when (and org-end-time-was-given
14152 (string-match org-plain-time-of-day-regexp txt))
14153 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14154 org-end-time-was-given
14155 (substring txt (match-end 0)))))
14156 (when org-read-date-analyze-futurep
14157 (setq txt (concat txt " (=>F)")))
14158 (setq org-read-date-overlay
14159 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14160 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14162 (defun org-read-date-analyze (ans def defdecode)
14163 "Analyse the combined answer of the date prompt."
14164 ;; FIXME: cleanup and comment
14165 (let ((nowdecode (decode-time (current-time)))
14166 delta deltan deltaw deltadef year month day
14167 hour minute second wday pm h2 m2 tl wday1
14168 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14169 (setq org-read-date-analyze-futurep nil)
14170 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14171 (setq ans "+0"))
14173 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14174 (setq ans (replace-match "" t t ans)
14175 deltan (car delta)
14176 deltaw (nth 1 delta)
14177 deltadef (nth 2 delta)))
14179 ;; Check if there is an iso week date in there
14180 ;; If yes, store the info and postpone interpreting it until the rest
14181 ;; of the parsing is done
14182 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14183 (setq iso-year (if (match-end 1)
14184 (org-small-year-to-year
14185 (string-to-number (match-string 1 ans))))
14186 iso-weekday (if (match-end 3)
14187 (string-to-number (match-string 3 ans)))
14188 iso-week (string-to-number (match-string 2 ans)))
14189 (setq ans (replace-match "" t t ans)))
14191 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14192 (when (string-match
14193 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14194 (setq year (if (match-end 2)
14195 (string-to-number (match-string 2 ans))
14196 (progn (setq kill-year t)
14197 (string-to-number (format-time-string "%Y"))))
14198 month (string-to-number (match-string 3 ans))
14199 day (string-to-number (match-string 4 ans)))
14200 (if (< year 100) (setq year (+ 2000 year)))
14201 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14202 t nil ans)))
14203 ;; Help matching american dates, like 5/30 or 5/30/7
14204 (when (string-match
14205 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14206 (setq year (if (match-end 4)
14207 (string-to-number (match-string 4 ans))
14208 (progn (setq kill-year t)
14209 (string-to-number (format-time-string "%Y"))))
14210 month (string-to-number (match-string 1 ans))
14211 day (string-to-number (match-string 2 ans)))
14212 (if (< year 100) (setq year (+ 2000 year)))
14213 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14214 t nil ans)))
14215 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14216 ;; If there is a time with am/pm, and *no* time without it, we convert
14217 ;; so that matching will be successful.
14218 (loop for i from 1 to 2 do ; twice, for end time as well
14219 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14220 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14221 (setq hour (string-to-number (match-string 1 ans))
14222 minute (if (match-end 3)
14223 (string-to-number (match-string 3 ans))
14225 pm (equal ?p
14226 (string-to-char (downcase (match-string 4 ans)))))
14227 (if (and (= hour 12) (not pm))
14228 (setq hour 0)
14229 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14230 (setq ans (replace-match (format "%02d:%02d" hour minute)
14231 t t ans))))
14233 ;; Check if a time range is given as a duration
14234 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14235 (setq hour (string-to-number (match-string 1 ans))
14236 h2 (+ hour (string-to-number (match-string 3 ans)))
14237 minute (string-to-number (match-string 2 ans))
14238 m2 (+ minute (if (match-end 5) (string-to-number
14239 (match-string 5 ans))0)))
14240 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14241 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14242 t t ans)))
14244 ;; Check if there is a time range
14245 (when (boundp 'org-end-time-was-given)
14246 (setq org-time-was-given nil)
14247 (when (and (string-match org-plain-time-of-day-regexp ans)
14248 (match-end 8))
14249 (setq org-end-time-was-given (match-string 8 ans))
14250 (setq ans (concat (substring ans 0 (match-beginning 7))
14251 (substring ans (match-end 7))))))
14253 (setq tl (parse-time-string ans)
14254 day (or (nth 3 tl) (nth 3 defdecode))
14255 month (or (nth 4 tl)
14256 (if (and org-read-date-prefer-future
14257 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14258 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14259 (nth 4 defdecode)))
14260 year (or (and (not kill-year) (nth 5 tl))
14261 (if (and org-read-date-prefer-future
14262 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14263 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14264 (nth 5 defdecode)))
14265 hour (or (nth 2 tl) (nth 2 defdecode))
14266 minute (or (nth 1 tl) (nth 1 defdecode))
14267 second (or (nth 0 tl) 0)
14268 wday (nth 6 tl))
14270 (when (and (eq org-read-date-prefer-future 'time)
14271 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14272 (equal day (nth 3 nowdecode))
14273 (equal month (nth 4 nowdecode))
14274 (equal year (nth 5 nowdecode))
14275 (nth 2 tl)
14276 (or (< (nth 2 tl) (nth 2 nowdecode))
14277 (and (= (nth 2 tl) (nth 2 nowdecode))
14278 (nth 1 tl)
14279 (< (nth 1 tl) (nth 1 nowdecode)))))
14280 (setq day (1+ day)
14281 futurep t))
14283 ;; Special date definitions below
14284 (cond
14285 (iso-week
14286 ;; There was an iso week
14287 (require 'cal-iso)
14288 (setq futurep nil)
14289 (setq year (or iso-year year)
14290 day (or iso-weekday wday 1)
14291 wday nil ; to make sure that the trigger below does not match
14292 iso-date (calendar-gregorian-from-absolute
14293 (calendar-absolute-from-iso
14294 (list iso-week day year))))
14295 ; FIXME: Should we also push ISO weeks into the future?
14296 ; (when (and org-read-date-prefer-future
14297 ; (not iso-year)
14298 ; (< (calendar-absolute-from-gregorian iso-date)
14299 ; (time-to-days (current-time))))
14300 ; (setq year (1+ year)
14301 ; iso-date (calendar-gregorian-from-absolute
14302 ; (calendar-absolute-from-iso
14303 ; (list iso-week day year)))))
14304 (setq month (car iso-date)
14305 year (nth 2 iso-date)
14306 day (nth 1 iso-date)))
14307 (deltan
14308 (setq futurep nil)
14309 (unless deltadef
14310 (let ((now (decode-time (current-time))))
14311 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14312 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14313 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14314 ((equal deltaw "m") (setq month (+ month deltan)))
14315 ((equal deltaw "y") (setq year (+ year deltan)))))
14316 ((and wday (not (nth 3 tl)))
14317 (setq futurep nil)
14318 ;; Weekday was given, but no day, so pick that day in the week
14319 ;; on or after the derived date.
14320 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14321 (unless (equal wday wday1)
14322 (setq day (+ day (% (- wday wday1 -7) 7))))))
14323 (if (and (boundp 'org-time-was-given)
14324 (nth 2 tl))
14325 (setq org-time-was-given t))
14326 (if (< year 100) (setq year (+ 2000 year)))
14327 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14328 (setq org-read-date-analyze-futurep futurep)
14329 (list second minute hour day month year)))
14331 (defvar parse-time-weekdays)
14333 (defun org-read-date-get-relative (s today default)
14334 "Check string S for special relative date string.
14335 TODAY and DEFAULT are internal times, for today and for a default.
14336 Return shift list (N what def-flag)
14337 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14338 N is the number of WHATs to shift.
14339 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14340 the DEFAULT date rather than TODAY."
14341 (when (and
14342 (string-match
14343 (concat
14344 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14345 "\\([0-9]+\\)?"
14346 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14347 "\\([ \t]\\|$\\)") s)
14348 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14349 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14350 (string-to-char (substring (match-string 1 s) -1))
14351 ?+))
14352 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14353 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14354 (what (if (match-end 3) (match-string 3 s) "d"))
14355 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14356 (date (if rel default today))
14357 (wday (nth 6 (decode-time date)))
14358 delta)
14359 (if wday1
14360 (progn
14361 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14362 (if (= dir ?-) (setq delta (- delta 7)))
14363 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14364 (list delta "d" rel))
14365 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14367 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14368 "Turn a user-specified date into the internal representation.
14369 The internal representation needed by the calendar is (month day year).
14370 This is a wrapper to handle the brain-dead convention in calendar that
14371 user function argument order change dependent on argument order."
14372 (if (boundp 'calendar-date-style)
14373 (cond
14374 ((eq calendar-date-style 'american)
14375 (list arg1 arg2 arg3))
14376 ((eq calendar-date-style 'european)
14377 (list arg2 arg1 arg3))
14378 ((eq calendar-date-style 'iso)
14379 (list arg2 arg3 arg1)))
14380 (if (org-bound-and-true-p european-calendar-style)
14381 (list arg2 arg1 arg3)
14382 (list arg1 arg2 arg3))))
14384 (defun org-eval-in-calendar (form &optional keepdate)
14385 "Eval FORM in the calendar window and return to current window.
14386 Also, store the cursor date in variable org-ans2."
14387 (let ((sf (selected-frame))
14388 (sw (selected-window)))
14389 (select-window (get-buffer-window "*Calendar*" t))
14390 (eval form)
14391 (when (and (not keepdate) (calendar-cursor-to-date))
14392 (let* ((date (calendar-cursor-to-date))
14393 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14394 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14395 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14396 (select-window sw)
14397 (org-select-frame-set-input-focus sf)))
14399 (defun org-calendar-select ()
14400 "Return to `org-read-date' with the date currently selected.
14401 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14402 (interactive)
14403 (when (calendar-cursor-to-date)
14404 (let* ((date (calendar-cursor-to-date))
14405 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14406 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14407 (if (active-minibuffer-window) (exit-minibuffer))))
14409 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14410 "Insert a date stamp for the date given by the internal TIME.
14411 WITH-HM means use the stamp format that includes the time of the day.
14412 INACTIVE means use square brackets instead of angular ones, so that the
14413 stamp will not contribute to the agenda.
14414 PRE and POST are optional strings to be inserted before and after the
14415 stamp.
14416 The command returns the inserted time stamp."
14417 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14418 stamp)
14419 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14420 (insert-before-markers (or pre ""))
14421 (insert-before-markers (setq stamp (format-time-string fmt time)))
14422 (when (listp extra)
14423 (setq extra (car extra))
14424 (if (and (stringp extra)
14425 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14426 (setq extra (format "-%02d:%02d"
14427 (string-to-number (match-string 1 extra))
14428 (string-to-number (match-string 2 extra))))
14429 (setq extra nil)))
14430 (when extra
14431 (backward-char 1)
14432 (insert-before-markers extra)
14433 (forward-char 1))
14434 (insert-before-markers (or post ""))
14435 (setq org-last-inserted-timestamp stamp)))
14437 (defun org-toggle-time-stamp-overlays ()
14438 "Toggle the use of custom time stamp formats."
14439 (interactive)
14440 (setq org-display-custom-times (not org-display-custom-times))
14441 (unless org-display-custom-times
14442 (let ((p (point-min)) (bmp (buffer-modified-p)))
14443 (while (setq p (next-single-property-change p 'display))
14444 (if (and (get-text-property p 'display)
14445 (eq (get-text-property p 'face) 'org-date))
14446 (remove-text-properties
14447 p (setq p (next-single-property-change p 'display))
14448 '(display t))))
14449 (set-buffer-modified-p bmp)))
14450 (if (featurep 'xemacs)
14451 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14452 (org-restart-font-lock)
14453 (setq org-table-may-need-update t)
14454 (if org-display-custom-times
14455 (message "Time stamps are overlayed with custom format")
14456 (message "Time stamp overlays removed")))
14458 (defun org-display-custom-time (beg end)
14459 "Overlay modified time stamp format over timestamp between BEG and END."
14460 (let* ((ts (buffer-substring beg end))
14461 t1 w1 with-hm tf time str w2 (off 0))
14462 (save-match-data
14463 (setq t1 (org-parse-time-string ts t))
14464 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14465 (setq off (- (match-end 0) (match-beginning 0)))))
14466 (setq end (- end off))
14467 (setq w1 (- end beg)
14468 with-hm (and (nth 1 t1) (nth 2 t1))
14469 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14470 time (org-fix-decoded-time t1)
14471 str (org-add-props
14472 (format-time-string
14473 (substring tf 1 -1) (apply 'encode-time time))
14474 nil 'mouse-face 'highlight)
14475 w2 (length str))
14476 (if (not (= w2 w1))
14477 (add-text-properties (1+ beg) (+ 2 beg)
14478 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14479 (if (featurep 'xemacs)
14480 (progn
14481 (put-text-property beg end 'invisible t)
14482 (put-text-property beg end 'end-glyph (make-glyph str)))
14483 (put-text-property beg end 'display str))))
14485 (defun org-translate-time (string)
14486 "Translate all timestamps in STRING to custom format.
14487 But do this only if the variable `org-display-custom-times' is set."
14488 (when org-display-custom-times
14489 (save-match-data
14490 (let* ((start 0)
14491 (re org-ts-regexp-both)
14492 t1 with-hm inactive tf time str beg end)
14493 (while (setq start (string-match re string start))
14494 (setq beg (match-beginning 0)
14495 end (match-end 0)
14496 t1 (save-match-data
14497 (org-parse-time-string (substring string beg end) t))
14498 with-hm (and (nth 1 t1) (nth 2 t1))
14499 inactive (equal (substring string beg (1+ beg)) "[")
14500 tf (funcall (if with-hm 'cdr 'car)
14501 org-time-stamp-custom-formats)
14502 time (org-fix-decoded-time t1)
14503 str (format-time-string
14504 (concat
14505 (if inactive "[" "<") (substring tf 1 -1)
14506 (if inactive "]" ">"))
14507 (apply 'encode-time time))
14508 string (replace-match str t t string)
14509 start (+ start (length str)))))))
14510 string)
14512 (defun org-fix-decoded-time (time)
14513 "Set 0 instead of nil for the first 6 elements of time.
14514 Don't touch the rest."
14515 (let ((n 0))
14516 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14518 (defun org-days-to-time (timestamp-string)
14519 "Difference between TIMESTAMP-STRING and now in days."
14520 (- (time-to-days (org-time-string-to-time timestamp-string))
14521 (time-to-days (current-time))))
14523 (defun org-deadline-close (timestamp-string &optional ndays)
14524 "Is the time in TIMESTAMP-STRING close to the current date?"
14525 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14526 (and (< (org-days-to-time timestamp-string) ndays)
14527 (not (org-entry-is-done-p))))
14529 (defun org-get-wdays (ts)
14530 "Get the deadline lead time appropriate for timestring TS."
14531 (cond
14532 ((<= org-deadline-warning-days 0)
14533 ;; 0 or negative, enforce this value no matter what
14534 (- org-deadline-warning-days))
14535 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14536 ;; lead time is specified.
14537 (floor (* (string-to-number (match-string 1 ts))
14538 (cdr (assoc (match-string 2 ts)
14539 '(("d" . 1) ("w" . 7)
14540 ("m" . 30.4) ("y" . 365.25)))))))
14541 ;; go for the default.
14542 (t org-deadline-warning-days)))
14544 (defun org-calendar-select-mouse (ev)
14545 "Return to `org-read-date' with the date currently selected.
14546 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14547 (interactive "e")
14548 (mouse-set-point ev)
14549 (when (calendar-cursor-to-date)
14550 (let* ((date (calendar-cursor-to-date))
14551 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14552 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14553 (if (active-minibuffer-window) (exit-minibuffer))))
14555 (defun org-check-deadlines (ndays)
14556 "Check if there are any deadlines due or past due.
14557 A deadline is considered due if it happens within `org-deadline-warning-days'
14558 days from today's date. If the deadline appears in an entry marked DONE,
14559 it is not shown. The prefix arg NDAYS can be used to test that many
14560 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14561 (interactive "P")
14562 (let* ((org-warn-days
14563 (cond
14564 ((equal ndays '(4)) 100000)
14565 (ndays (prefix-numeric-value ndays))
14566 (t (abs org-deadline-warning-days))))
14567 (case-fold-search nil)
14568 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14569 (callback
14570 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14572 (message "%d deadlines past-due or due within %d days"
14573 (org-occur regexp nil callback)
14574 org-warn-days)))
14576 (defun org-check-before-date (date)
14577 "Check if there are deadlines or scheduled entries before DATE."
14578 (interactive (list (org-read-date)))
14579 (let ((case-fold-search nil)
14580 (regexp (concat "\\<\\(" org-deadline-string
14581 "\\|" org-scheduled-string
14582 "\\) *<\\([^>]+\\)>"))
14583 (callback
14584 (lambda () (time-less-p
14585 (org-time-string-to-time (match-string 2))
14586 (org-time-string-to-time date)))))
14587 (message "%d entries before %s"
14588 (org-occur regexp nil callback) date)))
14590 (defun org-check-after-date (date)
14591 "Check if there are deadlines or scheduled entries after DATE."
14592 (interactive (list (org-read-date)))
14593 (let ((case-fold-search nil)
14594 (regexp (concat "\\<\\(" org-deadline-string
14595 "\\|" org-scheduled-string
14596 "\\) *<\\([^>]+\\)>"))
14597 (callback
14598 (lambda () (not
14599 (time-less-p
14600 (org-time-string-to-time (match-string 2))
14601 (org-time-string-to-time date))))))
14602 (message "%d entries after %s"
14603 (org-occur regexp nil callback) date)))
14605 (defun org-evaluate-time-range (&optional to-buffer)
14606 "Evaluate a time range by computing the difference between start and end.
14607 Normally the result is just printed in the echo area, but with prefix arg
14608 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14609 If the time range is actually in a table, the result is inserted into the
14610 next column.
14611 For time difference computation, a year is assumed to be exactly 365
14612 days in order to avoid rounding problems."
14613 (interactive "P")
14615 (org-clock-update-time-maybe)
14616 (save-excursion
14617 (unless (org-at-date-range-p t)
14618 (goto-char (point-at-bol))
14619 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14620 (if (not (org-at-date-range-p t))
14621 (error "Not at a time-stamp range, and none found in current line")))
14622 (let* ((ts1 (match-string 1))
14623 (ts2 (match-string 2))
14624 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14625 (match-end (match-end 0))
14626 (time1 (org-time-string-to-time ts1))
14627 (time2 (org-time-string-to-time ts2))
14628 (t1 (org-float-time time1))
14629 (t2 (org-float-time time2))
14630 (diff (abs (- t2 t1)))
14631 (negative (< (- t2 t1) 0))
14632 ;; (ys (floor (* 365 24 60 60)))
14633 (ds (* 24 60 60))
14634 (hs (* 60 60))
14635 (fy "%dy %dd %02d:%02d")
14636 (fy1 "%dy %dd")
14637 (fd "%dd %02d:%02d")
14638 (fd1 "%dd")
14639 (fh "%02d:%02d")
14640 y d h m align)
14641 (if havetime
14642 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14644 d (floor (/ diff ds)) diff (mod diff ds)
14645 h (floor (/ diff hs)) diff (mod diff hs)
14646 m (floor (/ diff 60)))
14647 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14649 d (floor (+ (/ diff ds) 0.5))
14650 h 0 m 0))
14651 (if (not to-buffer)
14652 (message "%s" (org-make-tdiff-string y d h m))
14653 (if (org-at-table-p)
14654 (progn
14655 (goto-char match-end)
14656 (setq align t)
14657 (and (looking-at " *|") (goto-char (match-end 0))))
14658 (goto-char match-end))
14659 (if (looking-at
14660 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14661 (replace-match ""))
14662 (if negative (insert " -"))
14663 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14664 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14665 (insert " " (format fh h m))))
14666 (if align (org-table-align))
14667 (message "Time difference inserted")))))
14669 (defun org-make-tdiff-string (y d h m)
14670 (let ((fmt "")
14671 (l nil))
14672 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14673 l (push y l)))
14674 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14675 l (push d l)))
14676 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14677 l (push h l)))
14678 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14679 l (push m l)))
14680 (apply 'format fmt (nreverse l))))
14682 (defun org-time-string-to-time (s)
14683 (apply 'encode-time (org-parse-time-string s)))
14684 (defun org-time-string-to-seconds (s)
14685 (org-float-time (org-time-string-to-time s)))
14687 (defun org-time-string-to-absolute (s &optional daynr prefer show-all ignore-cyclic)
14688 "Convert a time stamp to an absolute day number.
14689 If there is a specifier for a cyclic time stamp, get the closest date to
14690 DAYNR.
14691 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14692 the variable date is bound by the calendar when this is called.
14693 IGNORE-CYCLIC ignores cyclic repeaters so the returned absolute date
14694 is based on the original date."
14695 (cond
14696 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14697 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14698 daynr
14699 (+ daynr 1000)))
14700 ((and (not ignore-cyclic) daynr (string-match "\\+[0-9]+[dwmy]" s))
14701 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14702 (time-to-days (current-time))) (match-string 0 s)
14703 prefer show-all))
14704 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14706 (defun org-days-to-iso-week (days)
14707 "Return the iso week number."
14708 (require 'cal-iso)
14709 (car (calendar-iso-from-absolute days)))
14711 (defun org-small-year-to-year (year)
14712 "Convert 2-digit years into 4-digit years.
14713 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14714 The year 2000 cannot be abbreviated. Any year larger than 99
14715 is returned unchanged."
14716 (if (< year 38)
14717 (setq year (+ 2000 year))
14718 (if (< year 100)
14719 (setq year (+ 1900 year))))
14720 year)
14722 (defun org-time-from-absolute (d)
14723 "Return the time corresponding to date D.
14724 D may be an absolute day number, or a calendar-type list (month day year)."
14725 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14726 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14728 (defun org-calendar-holiday ()
14729 "List of holidays, for Diary display in Org-mode."
14730 (require 'holidays)
14731 (let ((hl (funcall
14732 (if (fboundp 'calendar-check-holidays)
14733 'calendar-check-holidays 'check-calendar-holidays) date)))
14734 (if hl (mapconcat 'identity hl "; "))))
14736 (defun org-diary-sexp-entry (sexp entry date)
14737 "Process a SEXP diary ENTRY for DATE."
14738 (require 'diary-lib)
14739 (let ((result (if calendar-debug-sexp
14740 (let ((stack-trace-on-error t))
14741 (eval (car (read-from-string sexp))))
14742 (condition-case nil
14743 (eval (car (read-from-string sexp)))
14744 (error
14745 (beep)
14746 (message "Bad sexp at line %d in %s: %s"
14747 (org-current-line)
14748 (buffer-file-name) sexp)
14749 (sleep-for 2))))))
14750 (cond ((stringp result) result)
14751 ((and (consp result)
14752 (stringp (cdr result))) (cdr result))
14753 (result entry)
14754 (t nil))))
14756 (defun org-diary-to-ical-string (frombuf)
14757 "Get iCalendar entries from diary entries in buffer FROMBUF.
14758 This uses the icalendar.el library."
14759 (let* ((tmpdir (if (featurep 'xemacs)
14760 (temp-directory)
14761 temporary-file-directory))
14762 (tmpfile (make-temp-name
14763 (expand-file-name "orgics" tmpdir)))
14764 buf rtn b e)
14765 (with-current-buffer frombuf
14766 (icalendar-export-region (point-min) (point-max) tmpfile)
14767 (setq buf (find-buffer-visiting tmpfile))
14768 (set-buffer buf)
14769 (goto-char (point-min))
14770 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14771 (setq b (match-beginning 0)))
14772 (goto-char (point-max))
14773 (if (re-search-backward "^END:VEVENT" nil t)
14774 (setq e (match-end 0)))
14775 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14776 (kill-buffer buf)
14777 (delete-file tmpfile)
14778 rtn))
14780 (defun org-closest-date (start current change prefer show-all)
14781 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14782 When PREFER is `past' return a date that is either CURRENT or past.
14783 When PREFER is `future', return a date that is either CURRENT or future.
14784 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14785 ;; Make the proper lists from the dates
14786 (catch 'exit
14787 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14788 dn dw sday cday n1 n2 n0
14789 d m y y1 y2 date1 date2 nmonths nm ny m2)
14791 (setq start (org-date-to-gregorian start)
14792 current (org-date-to-gregorian
14793 (if show-all
14794 current
14795 (time-to-days (current-time))))
14796 sday (calendar-absolute-from-gregorian start)
14797 cday (calendar-absolute-from-gregorian current))
14799 (if (<= cday sday) (throw 'exit sday))
14801 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14802 (setq dn (string-to-number (match-string 1 change))
14803 dw (cdr (assoc (match-string 2 change) a1)))
14804 (error "Invalid change specifyer: %s" change))
14805 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14806 (cond
14807 ((eq dw 'day)
14808 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14809 n2 (+ n1 dn)))
14810 ((eq dw 'year)
14811 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14812 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14813 (setq date1 (list m d y1)
14814 n1 (calendar-absolute-from-gregorian date1)
14815 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14816 n2 (calendar-absolute-from-gregorian date2)))
14817 ((eq dw 'month)
14818 ;; approx number of month between the two dates
14819 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14820 ;; How often does dn fit in there?
14821 (setq d (nth 1 start) m (car start) y (nth 2 start)
14822 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14823 m (+ m nm)
14824 ny (floor (/ m 12))
14825 y (+ y ny)
14826 m (- m (* ny 12)))
14827 (while (> m 12) (setq m (- m 12) y (1+ y)))
14828 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14829 (setq m2 (+ m dn) y2 y)
14830 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14831 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14832 (while (<= n2 cday)
14833 (setq n1 n2 m m2 y y2)
14834 (setq m2 (+ m dn) y2 y)
14835 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14836 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14837 ;; Make sure n1 is the earlier date
14838 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14839 (if show-all
14840 (cond
14841 ((eq prefer 'past) (if (= cday n2) n2 n1))
14842 ((eq prefer 'future) (if (= cday n1) n1 n2))
14843 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14844 (cond
14845 ((eq prefer 'past) (if (= cday n2) n2 n1))
14846 ((eq prefer 'future) (if (= cday n1) n1 n2))
14847 (t (if (= cday n1) n1 n2)))))))
14849 (defun org-date-to-gregorian (date)
14850 "Turn any specification of DATE into a gregorian date for the calendar."
14851 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14852 ((and (listp date) (= (length date) 3)) date)
14853 ((stringp date)
14854 (setq date (org-parse-time-string date))
14855 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14856 ((listp date)
14857 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14859 (defun org-parse-time-string (s &optional nodefault)
14860 "Parse the standard Org-mode time string.
14861 This should be a lot faster than the normal `parse-time-string'.
14862 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14863 hour and minute fields will be nil if not given."
14864 (if (string-match org-ts-regexp0 s)
14865 (list 0
14866 (if (or (match-beginning 8) (not nodefault))
14867 (string-to-number (or (match-string 8 s) "0")))
14868 (if (or (match-beginning 7) (not nodefault))
14869 (string-to-number (or (match-string 7 s) "0")))
14870 (string-to-number (match-string 4 s))
14871 (string-to-number (match-string 3 s))
14872 (string-to-number (match-string 2 s))
14873 nil nil nil)
14874 (error "Not a standard Org-mode time string: %s" s)))
14876 (defun org-timestamp-up (&optional arg)
14877 "Increase the date item at the cursor by one.
14878 If the cursor is on the year, change the year. If it is on the month or
14879 the day, change that.
14880 With prefix ARG, change by that many units."
14881 (interactive "p")
14882 (org-timestamp-change (prefix-numeric-value arg)))
14884 (defun org-timestamp-down (&optional arg)
14885 "Decrease the date item at the cursor by one.
14886 If the cursor is on the year, change the year. If it is on the month or
14887 the day, change that.
14888 With prefix ARG, change by that many units."
14889 (interactive "p")
14890 (org-timestamp-change (- (prefix-numeric-value arg))))
14892 (defun org-timestamp-up-day (&optional arg)
14893 "Increase the date in the time stamp by one day.
14894 With prefix ARG, change that many days."
14895 (interactive "p")
14896 (if (and (not (org-at-timestamp-p t))
14897 (org-on-heading-p))
14898 (org-todo 'up)
14899 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14901 (defun org-timestamp-down-day (&optional arg)
14902 "Decrease the date in the time stamp by one day.
14903 With prefix ARG, change that many days."
14904 (interactive "p")
14905 (if (and (not (org-at-timestamp-p t))
14906 (org-on-heading-p))
14907 (org-todo 'down)
14908 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14910 (defun org-at-timestamp-p (&optional inactive-ok)
14911 "Determine if the cursor is in or at a timestamp."
14912 (interactive)
14913 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14914 (pos (point))
14915 (ans (or (looking-at tsr)
14916 (save-excursion
14917 (skip-chars-backward "^[<\n\r\t")
14918 (if (> (point) (point-min)) (backward-char 1))
14919 (and (looking-at tsr)
14920 (> (- (match-end 0) pos) -1))))))
14921 (and ans
14922 (boundp 'org-ts-what)
14923 (setq org-ts-what
14924 (cond
14925 ((= pos (match-beginning 0)) 'bracket)
14926 ((= pos (1- (match-end 0))) 'bracket)
14927 ((org-pos-in-match-range pos 2) 'year)
14928 ((org-pos-in-match-range pos 3) 'month)
14929 ((org-pos-in-match-range pos 7) 'hour)
14930 ((org-pos-in-match-range pos 8) 'minute)
14931 ((or (org-pos-in-match-range pos 4)
14932 (org-pos-in-match-range pos 5)) 'day)
14933 ((and (> pos (or (match-end 8) (match-end 5)))
14934 (< pos (match-end 0)))
14935 (- pos (or (match-end 8) (match-end 5))))
14936 (t 'day))))
14937 ans))
14939 (defun org-toggle-timestamp-type ()
14940 "Toggle the type (<active> or [inactive]) of a time stamp."
14941 (interactive)
14942 (when (org-at-timestamp-p t)
14943 (let ((beg (match-beginning 0)) (end (match-end 0))
14944 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14945 (save-excursion
14946 (goto-char beg)
14947 (while (re-search-forward "[][<>]" end t)
14948 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14949 t t)))
14950 (message "Timestamp is now %sactive"
14951 (if (equal (char-after beg) ?<) "" "in")))))
14953 (defun org-timestamp-change (n &optional what)
14954 "Change the date in the time stamp at point.
14955 The date will be changed by N times WHAT. WHAT can be `day', `month',
14956 `year', `minute', `second'. If WHAT is not given, the cursor position
14957 in the timestamp determines what will be changed."
14958 (let ((pos (point))
14959 with-hm inactive
14960 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14961 org-ts-what
14962 extra rem
14963 ts time time0)
14964 (if (not (org-at-timestamp-p t))
14965 (error "Not at a timestamp"))
14966 (if (and (not what) (eq org-ts-what 'bracket))
14967 (org-toggle-timestamp-type)
14968 (if (and (not what) (not (eq org-ts-what 'day))
14969 org-display-custom-times
14970 (get-text-property (point) 'display)
14971 (not (get-text-property (1- (point)) 'display)))
14972 (setq org-ts-what 'day))
14973 (setq org-ts-what (or what org-ts-what)
14974 inactive (= (char-after (match-beginning 0)) ?\[)
14975 ts (match-string 0))
14976 (replace-match "")
14977 (if (string-match
14978 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14980 (setq extra (match-string 1 ts)))
14981 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14982 (setq with-hm t))
14983 (setq time0 (org-parse-time-string ts))
14984 (when (and (eq org-ts-what 'minute)
14985 (eq current-prefix-arg nil))
14986 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14987 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14988 (setcar (cdr time0) (+ (nth 1 time0)
14989 (if (> n 0) (- rem) (- dm rem))))))
14990 (setq time
14991 (encode-time (or (car time0) 0)
14992 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14993 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14994 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14995 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14996 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14997 (nthcdr 6 time0)))
14998 (when (and (member org-ts-what '(hour minute))
14999 extra
15000 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15001 (setq extra (org-modify-ts-extra
15002 extra
15003 (if (eq org-ts-what 'hour) 2 5)
15004 n dm)))
15005 (when (integerp org-ts-what)
15006 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15007 (if (eq what 'calendar)
15008 (let ((cal-date (org-get-date-from-calendar)))
15009 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15010 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15011 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15012 (setcar time0 (or (car time0) 0))
15013 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15014 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15015 (setq time (apply 'encode-time time0))))
15016 (setq org-last-changed-timestamp
15017 (org-insert-time-stamp time with-hm inactive nil nil extra))
15018 (org-clock-update-time-maybe)
15019 (goto-char pos)
15020 ;; Try to recenter the calendar window, if any
15021 (if (and org-calendar-follow-timestamp-change
15022 (get-buffer-window "*Calendar*" t)
15023 (memq org-ts-what '(day month year)))
15024 (org-recenter-calendar (time-to-days time))))))
15026 (defun org-modify-ts-extra (s pos n dm)
15027 "Change the different parts of the lead-time and repeat fields in timestamp."
15028 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15029 ng h m new rem)
15030 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15031 (cond
15032 ((or (org-pos-in-match-range pos 2)
15033 (org-pos-in-match-range pos 3))
15034 (setq m (string-to-number (match-string 3 s))
15035 h (string-to-number (match-string 2 s)))
15036 (if (org-pos-in-match-range pos 2)
15037 (setq h (+ h n))
15038 (setq n (* dm (org-no-warnings (signum n))))
15039 (when (not (= 0 (setq rem (% m dm))))
15040 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15041 (setq m (+ m n)))
15042 (if (< m 0) (setq m (+ m 60) h (1- h)))
15043 (if (> m 59) (setq m (- m 60) h (1+ h)))
15044 (setq h (min 24 (max 0 h)))
15045 (setq ng 1 new (format "-%02d:%02d" h m)))
15046 ((org-pos-in-match-range pos 6)
15047 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15048 ((org-pos-in-match-range pos 5)
15049 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15051 ((org-pos-in-match-range pos 9)
15052 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15053 ((org-pos-in-match-range pos 8)
15054 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15056 (when ng
15057 (setq s (concat
15058 (substring s 0 (match-beginning ng))
15060 (substring s (match-end ng))))))
15063 (defun org-recenter-calendar (date)
15064 "If the calendar is visible, recenter it to DATE."
15065 (let* ((win (selected-window))
15066 (cwin (get-buffer-window "*Calendar*" t))
15067 (calendar-move-hook nil))
15068 (when cwin
15069 (select-window cwin)
15070 (calendar-goto-date (if (listp date) date
15071 (calendar-gregorian-from-absolute date)))
15072 (select-window win))))
15074 (defun org-goto-calendar (&optional arg)
15075 "Go to the Emacs calendar at the current date.
15076 If there is a time stamp in the current line, go to that date.
15077 A prefix ARG can be used to force the current date."
15078 (interactive "P")
15079 (let ((tsr org-ts-regexp) diff
15080 (calendar-move-hook nil)
15081 (calendar-view-holidays-initially-flag nil)
15082 (calendar-view-diary-initially-flag nil))
15083 (if (or (org-at-timestamp-p)
15084 (save-excursion
15085 (beginning-of-line 1)
15086 (looking-at (concat ".*" tsr))))
15087 (let ((d1 (time-to-days (current-time)))
15088 (d2 (time-to-days
15089 (org-time-string-to-time (match-string 1)))))
15090 (setq diff (- d2 d1))))
15091 (calendar)
15092 (calendar-goto-today)
15093 (if (and diff (not arg)) (calendar-forward-day diff))))
15095 (defun org-get-date-from-calendar ()
15096 "Return a list (month day year) of date at point in calendar."
15097 (with-current-buffer "*Calendar*"
15098 (save-match-data
15099 (calendar-cursor-to-date))))
15101 (defun org-date-from-calendar ()
15102 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15103 If there is already a time stamp at the cursor position, update it."
15104 (interactive)
15105 (if (org-at-timestamp-p t)
15106 (org-timestamp-change 0 'calendar)
15107 (let ((cal-date (org-get-date-from-calendar)))
15108 (org-insert-time-stamp
15109 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15111 (defun org-minutes-to-hh:mm-string (m)
15112 "Compute H:MM from a number of minutes."
15113 (let ((h (/ m 60)))
15114 (setq m (- m (* 60 h)))
15115 (format org-time-clocksum-format h m)))
15117 (defun org-hh:mm-string-to-minutes (s)
15118 "Convert a string H:MM to a number of minutes.
15119 If the string is just a number, interpret it as minutes.
15120 In fact, the first hh:mm or number in the string will be taken,
15121 there can be extra stuff in the string.
15122 If no number is found, the return value is 0."
15123 (cond
15124 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15125 (+ (* (string-to-number (match-string 1 s)) 60)
15126 (string-to-number (match-string 2 s))))
15127 ((string-match "\\([0-9]+\\)" s)
15128 (string-to-number (match-string 1 s)))
15129 (t 0)))
15131 ;;;; Files
15133 (defun org-save-all-org-buffers ()
15134 "Save all Org-mode buffers without user confirmation."
15135 (interactive)
15136 (message "Saving all Org-mode buffers...")
15137 (save-some-buffers t 'org-mode-p)
15138 (when (featurep 'org-id) (org-id-locations-save))
15139 (message "Saving all Org-mode buffers... done"))
15141 (defun org-revert-all-org-buffers ()
15142 "Revert all Org-mode buffers.
15143 Prompt for confirmation when there are unsaved changes.
15144 Be sure you know what you are doing before letting this function
15145 overwrite your changes.
15147 This function is useful in a setup where one tracks org files
15148 with a version control system, to revert on one machine after pulling
15149 changes from another. I believe the procedure must be like this:
15151 1. M-x org-save-all-org-buffers
15152 2. Pull changes from the other machine, resolve conflicts
15153 3. M-x org-revert-all-org-buffers"
15154 (interactive)
15155 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15156 (error "Abort"))
15157 (save-excursion
15158 (save-window-excursion
15159 (mapc
15160 (lambda (b)
15161 (when (and (with-current-buffer b (org-mode-p))
15162 (with-current-buffer b buffer-file-name))
15163 (switch-to-buffer b)
15164 (revert-buffer t 'no-confirm)))
15165 (buffer-list))
15166 (when (and (featurep 'org-id) org-id-track-globally)
15167 (org-id-locations-load)))))
15169 ;;;; Agenda files
15171 ;;;###autoload
15172 (defun org-iswitchb (&optional arg)
15173 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
15174 With a prefix argument, restrict available to files.
15175 With two prefix arguments, restrict available buffers to agenda files."
15176 (interactive "P")
15177 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15178 ((equal arg '(16)) (org-buffer-list 'agenda))
15179 (t (org-buffer-list)))))
15180 (switch-to-buffer
15181 (org-icompleting-read "Org buffer: "
15182 (mapcar 'list (mapcar 'buffer-name blist))
15183 nil t))))
15185 ;;;###autoload
15186 (defalias 'org-ido-switchb 'org-iswitchb)
15188 (defun org-buffer-list (&optional predicate exclude-tmp)
15189 "Return a list of Org buffers.
15190 PREDICATE can be `export', `files' or `agenda'.
15192 export restrict the list to Export buffers.
15193 files restrict the list to buffers visiting Org files.
15194 agenda restrict the list to buffers visiting agenda files.
15196 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15197 (let* ((bfn nil)
15198 (agenda-files (and (eq predicate 'agenda)
15199 (mapcar 'file-truename (org-agenda-files t))))
15200 (filter
15201 (cond
15202 ((eq predicate 'files)
15203 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15204 ((eq predicate 'export)
15205 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15206 ((eq predicate 'agenda)
15207 (lambda (b)
15208 (with-current-buffer b
15209 (and (eq major-mode 'org-mode)
15210 (setq bfn (buffer-file-name b))
15211 (member (file-truename bfn) agenda-files)))))
15212 (t (lambda (b) (with-current-buffer b
15213 (or (eq major-mode 'org-mode)
15214 (string-match "\*Org .*Export"
15215 (buffer-name b)))))))))
15216 (delq nil
15217 (mapcar
15218 (lambda(b)
15219 (if (and (funcall filter b)
15220 (or (not exclude-tmp)
15221 (not (string-match "tmp" (buffer-name b)))))
15223 nil))
15224 (buffer-list)))))
15226 (defun org-agenda-files (&optional unrestricted archives)
15227 "Get the list of agenda files.
15228 Optional UNRESTRICTED means return the full list even if a restriction
15229 is currently in place.
15230 When ARCHIVES is t, include all archive files that are really being
15231 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15232 `org-agenda-archives-mode' is t."
15233 (let ((files
15234 (cond
15235 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15236 ((stringp org-agenda-files) (org-read-agenda-file-list))
15237 ((listp org-agenda-files) org-agenda-files)
15238 (t (error "Invalid value of `org-agenda-files'")))))
15239 (setq files (apply 'append
15240 (mapcar (lambda (f)
15241 (if (file-directory-p f)
15242 (directory-files
15243 f t org-agenda-file-regexp)
15244 (list f)))
15245 files)))
15246 (when org-agenda-skip-unavailable-files
15247 (setq files (delq nil
15248 (mapcar (function
15249 (lambda (file)
15250 (and (file-readable-p file) file)))
15251 files))))
15252 (when (or (eq archives t)
15253 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15254 (setq files (org-add-archive-files files)))
15255 files))
15257 (defun org-agenda-file-p (&optional file)
15258 "Return non-nil, if FILE is an agenda file.
15259 If FILE is omitted, use the file associated with the current
15260 buffer."
15261 (member (or file (buffer-file-name))
15262 (org-agenda-files t)))
15264 (defun org-edit-agenda-file-list ()
15265 "Edit the list of agenda files.
15266 Depending on setup, this either uses customize to edit the variable
15267 `org-agenda-files', or it visits the file that is holding the list. In the
15268 latter case, the buffer is set up in a way that saving it automatically kills
15269 the buffer and restores the previous window configuration."
15270 (interactive)
15271 (if (stringp org-agenda-files)
15272 (let ((cw (current-window-configuration)))
15273 (find-file org-agenda-files)
15274 (org-set-local 'org-window-configuration cw)
15275 (org-add-hook 'after-save-hook
15276 (lambda ()
15277 (set-window-configuration
15278 (prog1 org-window-configuration
15279 (kill-buffer (current-buffer))))
15280 (org-install-agenda-files-menu)
15281 (message "New agenda file list installed"))
15282 nil 'local)
15283 (message "%s" (substitute-command-keys
15284 "Edit list and finish with \\[save-buffer]")))
15285 (customize-variable 'org-agenda-files)))
15287 (defun org-store-new-agenda-file-list (list)
15288 "Set new value for the agenda file list and save it correctly."
15289 (if (stringp org-agenda-files)
15290 (let ((fe (org-read-agenda-file-list t)) b u)
15291 (while (setq b (find-buffer-visiting org-agenda-files))
15292 (kill-buffer b))
15293 (with-temp-file org-agenda-files
15294 (insert
15295 (mapconcat
15296 (lambda (f) ;; Keep un-expanded entries.
15297 (if (setq u (assoc f fe))
15298 (cdr u)
15300 list "\n")
15301 "\n")))
15302 (let ((org-mode-hook nil) (org-inhibit-startup t)
15303 (org-insert-mode-line-in-empty-file nil))
15304 (setq org-agenda-files list)
15305 (customize-save-variable 'org-agenda-files org-agenda-files))))
15307 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15308 "Read the list of agenda files from a file.
15309 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15310 filenames, used by `org-store-new-agenda-file-list' to write back
15311 un-expanded file names."
15312 (when (file-directory-p org-agenda-files)
15313 (error "`org-agenda-files' cannot be a single directory"))
15314 (when (stringp org-agenda-files)
15315 (with-temp-buffer
15316 (insert-file-contents org-agenda-files)
15317 (mapcar
15318 (lambda (f)
15319 (let ((e (expand-file-name (substitute-in-file-name f)
15320 org-directory)))
15321 (if pair-with-expansion
15322 (cons e f)
15323 e)))
15324 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15326 ;;;###autoload
15327 (defun org-cycle-agenda-files ()
15328 "Cycle through the files in `org-agenda-files'.
15329 If the current buffer visits an agenda file, find the next one in the list.
15330 If the current buffer does not, find the first agenda file."
15331 (interactive)
15332 (let* ((fs (org-agenda-files t))
15333 (files (append fs (list (car fs))))
15334 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15335 file)
15336 (unless files (error "No agenda files"))
15337 (catch 'exit
15338 (while (setq file (pop files))
15339 (if (equal (file-truename file) tcf)
15340 (when (car files)
15341 (find-file (car files))
15342 (throw 'exit t))))
15343 (find-file (car fs)))
15344 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15346 (defun org-agenda-file-to-front (&optional to-end)
15347 "Move/add the current file to the top of the agenda file list.
15348 If the file is not present in the list, it is added to the front. If it is
15349 present, it is moved there. With optional argument TO-END, add/move to the
15350 end of the list."
15351 (interactive "P")
15352 (let ((org-agenda-skip-unavailable-files nil)
15353 (file-alist (mapcar (lambda (x)
15354 (cons (file-truename x) x))
15355 (org-agenda-files t)))
15356 (ctf (file-truename buffer-file-name))
15357 x had)
15358 (setq x (assoc ctf file-alist) had x)
15360 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15361 (if to-end
15362 (setq file-alist (append (delq x file-alist) (list x)))
15363 (setq file-alist (cons x (delq x file-alist))))
15364 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15365 (org-install-agenda-files-menu)
15366 (message "File %s to %s of agenda file list"
15367 (if had "moved" "added") (if to-end "end" "front"))))
15369 (defun org-remove-file (&optional file)
15370 "Remove current file from the list of files in variable `org-agenda-files'.
15371 These are the files which are being checked for agenda entries.
15372 Optional argument FILE means use this file instead of the current."
15373 (interactive)
15374 (let* ((org-agenda-skip-unavailable-files nil)
15375 (file (or file buffer-file-name))
15376 (true-file (file-truename file))
15377 (afile (abbreviate-file-name file))
15378 (files (delq nil (mapcar
15379 (lambda (x)
15380 (if (equal true-file
15381 (file-truename x))
15382 nil x))
15383 (org-agenda-files t)))))
15384 (if (not (= (length files) (length (org-agenda-files t))))
15385 (progn
15386 (org-store-new-agenda-file-list files)
15387 (org-install-agenda-files-menu)
15388 (message "Removed file: %s" afile))
15389 (message "File was not in list: %s (not removed)" afile))))
15391 (defun org-file-menu-entry (file)
15392 (vector file (list 'find-file file) t))
15394 (defun org-check-agenda-file (file)
15395 "Make sure FILE exists. If not, ask user what to do."
15396 (when (not (file-exists-p file))
15397 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15398 (abbreviate-file-name file))
15399 (let ((r (downcase (read-char-exclusive))))
15400 (cond
15401 ((equal r ?r)
15402 (org-remove-file file)
15403 (throw 'nextfile t))
15404 (t (error "Abort"))))))
15406 (defun org-get-agenda-file-buffer (file)
15407 "Get a buffer visiting FILE. If the buffer needs to be created, add
15408 it to the list of buffers which might be released later."
15409 (let ((buf (org-find-base-buffer-visiting file)))
15410 (if buf
15411 buf ; just return it
15412 ;; Make a new buffer and remember it
15413 (setq buf (find-file-noselect file))
15414 (if buf (push buf org-agenda-new-buffers))
15415 buf)))
15417 (defun org-release-buffers (blist)
15418 "Release all buffers in list, asking the user for confirmation when needed.
15419 When a buffer is unmodified, it is just killed. When modified, it is saved
15420 \(if the user agrees) and then killed."
15421 (let (buf file)
15422 (while (setq buf (pop blist))
15423 (setq file (buffer-file-name buf))
15424 (when (and (buffer-modified-p buf)
15425 file
15426 (y-or-n-p (format "Save file %s? " file)))
15427 (with-current-buffer buf (save-buffer)))
15428 (kill-buffer buf))))
15430 (defun org-prepare-agenda-buffers (files)
15431 "Create buffers for all agenda files, protect archived trees and comments."
15432 (interactive)
15433 (let ((pa '(:org-archived t))
15434 (pc '(:org-comment t))
15435 (pall '(:org-archived t :org-comment t))
15436 (inhibit-read-only t)
15437 (rea (concat ":" org-archive-tag ":"))
15438 bmp file re)
15439 (save-excursion
15440 (save-restriction
15441 (while (setq file (pop files))
15442 (catch 'nextfile
15443 (if (bufferp file)
15444 (set-buffer file)
15445 (org-check-agenda-file file)
15446 (set-buffer (org-get-agenda-file-buffer file)))
15447 (widen)
15448 (setq bmp (buffer-modified-p))
15449 (org-refresh-category-properties)
15450 (setq org-todo-keywords-for-agenda
15451 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15452 (setq org-done-keywords-for-agenda
15453 (append org-done-keywords-for-agenda org-done-keywords))
15454 (setq org-todo-keyword-alist-for-agenda
15455 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15456 (setq org-drawers-for-agenda
15457 (append org-drawers-for-agenda org-drawers))
15458 (setq org-tag-alist-for-agenda
15459 (append org-tag-alist-for-agenda org-tag-alist))
15461 (save-excursion
15462 (remove-text-properties (point-min) (point-max) pall)
15463 (when org-agenda-skip-archived-trees
15464 (goto-char (point-min))
15465 (while (re-search-forward rea nil t)
15466 (if (org-on-heading-p t)
15467 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15468 (goto-char (point-min))
15469 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15470 (while (re-search-forward re nil t)
15471 (add-text-properties
15472 (match-beginning 0) (org-end-of-subtree t) pc)))
15473 (set-buffer-modified-p bmp)))))
15474 (setq org-todo-keywords-for-agenda
15475 (org-uniquify org-todo-keywords-for-agenda))
15476 (setq org-todo-keyword-alist-for-agenda
15477 (org-uniquify org-todo-keyword-alist-for-agenda)
15478 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15480 ;;;; Embedded LaTeX
15482 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15483 "Keymap for the minor `org-cdlatex-mode'.")
15485 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15486 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15487 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15488 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15489 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15491 (defvar org-cdlatex-texmathp-advice-is-done nil
15492 "Flag remembering if we have applied the advice to texmathp already.")
15494 (define-minor-mode org-cdlatex-mode
15495 "Toggle the minor `org-cdlatex-mode'.
15496 This mode supports entering LaTeX environment and math in LaTeX fragments
15497 in Org-mode.
15498 \\{org-cdlatex-mode-map}"
15499 nil " OCDL" nil
15500 (when org-cdlatex-mode (require 'cdlatex))
15501 (unless org-cdlatex-texmathp-advice-is-done
15502 (setq org-cdlatex-texmathp-advice-is-done t)
15503 (defadvice texmathp (around org-math-always-on activate)
15504 "Always return t in org-mode buffers.
15505 This is because we want to insert math symbols without dollars even outside
15506 the LaTeX math segments. If Orgmode thinks that point is actually inside
15507 an embedded LaTeX fragment, let texmathp do its job.
15508 \\[org-cdlatex-mode-map]"
15509 (interactive)
15510 (let (p)
15511 (cond
15512 ((not (org-mode-p)) ad-do-it)
15513 ((eq this-command 'cdlatex-math-symbol)
15514 (setq ad-return-value t
15515 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15517 (let ((p (org-inside-LaTeX-fragment-p)))
15518 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15519 (setq ad-return-value t
15520 texmathp-why '("Org-mode embedded math" . 0))
15521 (if p ad-do-it)))))))))
15523 (defun turn-on-org-cdlatex ()
15524 "Unconditionally turn on `org-cdlatex-mode'."
15525 (org-cdlatex-mode 1))
15527 (defun org-inside-LaTeX-fragment-p ()
15528 "Test if point is inside a LaTeX fragment.
15529 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15530 sequence appearing also before point.
15531 Even though the matchers for math are configurable, this function assumes
15532 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15533 delimiters are skipped when they have been removed by customization.
15534 The return value is nil, or a cons cell with the delimiter and
15535 and the position of this delimiter.
15537 This function does a reasonably good job, but can locally be fooled by
15538 for example currency specifications. For example it will assume being in
15539 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15540 fragments that are properly closed, but during editing, we have to live
15541 with the uncertainty caused by missing closing delimiters. This function
15542 looks only before point, not after."
15543 (catch 'exit
15544 (let ((pos (point))
15545 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15546 (lim (progn
15547 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15548 (point)))
15549 dd-on str (start 0) m re)
15550 (goto-char pos)
15551 (when dodollar
15552 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15553 re (nth 1 (assoc "$" org-latex-regexps)))
15554 (while (string-match re str start)
15555 (cond
15556 ((= (match-end 0) (length str))
15557 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15558 ((= (match-end 0) (- (length str) 5))
15559 (throw 'exit nil))
15560 (t (setq start (match-end 0))))))
15561 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15562 (goto-char pos)
15563 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15564 (and (match-beginning 2) (throw 'exit nil))
15565 ;; count $$
15566 (while (re-search-backward "\\$\\$" lim t)
15567 (setq dd-on (not dd-on)))
15568 (goto-char pos)
15569 (if dd-on (cons "$$" m))))))
15571 (defun org-inside-latex-macro-p ()
15572 "Is point inside a LaTeX macro or its arguments?"
15573 (save-match-data
15574 (org-in-regexp
15575 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15577 (defun org-try-cdlatex-tab ()
15578 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15579 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15580 - inside a LaTeX fragment, or
15581 - after the first word in a line, where an abbreviation expansion could
15582 insert a LaTeX environment."
15583 (when org-cdlatex-mode
15584 (cond
15585 ((save-excursion
15586 (skip-chars-backward "a-zA-Z0-9*")
15587 (skip-chars-backward " \t")
15588 (bolp))
15589 (cdlatex-tab) t)
15590 ((org-inside-LaTeX-fragment-p)
15591 (cdlatex-tab) t)
15592 (t nil))))
15594 (defun org-cdlatex-underscore-caret (&optional arg)
15595 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15596 Revert to the normal definition outside of these fragments."
15597 (interactive "P")
15598 (if (org-inside-LaTeX-fragment-p)
15599 (call-interactively 'cdlatex-sub-superscript)
15600 (let (org-cdlatex-mode)
15601 (call-interactively (key-binding (vector last-input-event))))))
15603 (defun org-cdlatex-math-modify (&optional arg)
15604 "Execute `cdlatex-math-modify' in LaTeX fragments.
15605 Revert to the normal definition outside of these fragments."
15606 (interactive "P")
15607 (if (org-inside-LaTeX-fragment-p)
15608 (call-interactively 'cdlatex-math-modify)
15609 (let (org-cdlatex-mode)
15610 (call-interactively (key-binding (vector last-input-event))))))
15612 (defvar org-latex-fragment-image-overlays nil
15613 "List of overlays carrying the images of latex fragments.")
15614 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15616 (defun org-remove-latex-fragment-image-overlays ()
15617 "Remove all overlays with LaTeX fragment images in current buffer."
15618 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15619 (setq org-latex-fragment-image-overlays nil))
15621 (defun org-preview-latex-fragment (&optional subtree)
15622 "Preview the LaTeX fragment at point, or all locally or globally.
15623 If the cursor is in a LaTeX fragment, create the image and overlay
15624 it over the source code. If there is no fragment at point, display
15625 all fragments in the current text, from one headline to the next. With
15626 prefix SUBTREE, display all fragments in the current subtree. With a
15627 double prefix `C-u C-u', or when the cursor is before the first headline,
15628 display all fragments in the buffer.
15629 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15630 (interactive "P")
15631 (org-remove-latex-fragment-image-overlays)
15632 (save-excursion
15633 (save-restriction
15634 (let (beg end at msg)
15635 (cond
15636 ((or (equal subtree '(16))
15637 (not (save-excursion
15638 (re-search-backward (concat "^" outline-regexp) nil t))))
15639 (setq beg (point-min) end (point-max)
15640 msg "Creating images for buffer...%s"))
15641 ((equal subtree '(4))
15642 (org-back-to-heading)
15643 (setq beg (point) end (org-end-of-subtree t)
15644 msg "Creating images for subtree...%s"))
15646 (if (setq at (org-inside-LaTeX-fragment-p))
15647 (goto-char (max (point-min) (- (cdr at) 2)))
15648 (org-back-to-heading))
15649 (setq beg (point) end (progn (outline-next-heading) (point))
15650 msg (if at "Creating image...%s"
15651 "Creating images for entry...%s"))))
15652 (message msg "")
15653 (narrow-to-region beg end)
15654 (goto-char beg)
15655 (org-format-latex
15656 (concat "ltxpng/" (file-name-sans-extension
15657 (file-name-nondirectory
15658 buffer-file-name)))
15659 default-directory 'overlays msg at 'forbuffer)
15660 (message msg "done. Use `C-c C-c' to remove images.")))))
15662 (defvar org-latex-regexps
15663 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15664 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15665 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15666 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15667 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15668 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15669 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15670 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15671 "Regular expressions for matching embedded LaTeX.")
15673 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15674 "Replace LaTeX fragments with links to an image, and produce images.
15675 Some of the options can be changed using the variable
15676 `org-format-latex-options'."
15677 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15678 (let* ((prefixnodir (file-name-nondirectory prefix))
15679 (absprefix (expand-file-name prefix dir))
15680 (todir (file-name-directory absprefix))
15681 (opt org-format-latex-options)
15682 (matchers (plist-get opt :matchers))
15683 (re-list org-latex-regexps)
15684 (org-format-latex-header-extra
15685 (plist-get (org-infile-export-plist) :latex-header-extra))
15686 (cnt 0) txt hash link beg end re e checkdir
15687 executables-checked
15688 m n block linkfile movefile ov)
15689 ;; Check the different regular expressions
15690 (while (setq e (pop re-list))
15691 (setq m (car e) re (nth 1 e) n (nth 2 e)
15692 block (if (nth 3 e) "\n\n" ""))
15693 (when (member m matchers)
15694 (goto-char (point-min))
15695 (while (re-search-forward re nil t)
15696 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15697 (not (get-text-property (match-beginning n)
15698 'org-protected))
15699 (or (not overlays)
15700 (not (eq (get-char-property (match-beginning n)
15701 'org-overlay-type)
15702 'org-latex-overlay))))
15703 (setq txt (match-string n)
15704 beg (match-beginning n) end (match-end n)
15705 cnt (1+ cnt))
15706 (let (print-length print-level) ; make sure full list is printed
15707 (setq hash (sha1 (prin1-to-string
15708 (list org-format-latex-header
15709 org-format-latex-header-extra
15710 org-export-latex-default-packages-alist
15711 org-export-latex-packages-alist
15712 org-format-latex-options
15713 forbuffer txt)))
15714 linkfile (format "%s_%s.png" prefix hash)
15715 movefile (format "%s_%s.png" absprefix hash)))
15716 (setq link (concat block "[[file:" linkfile "]]" block))
15717 (if msg (message msg cnt))
15718 (goto-char beg)
15719 (unless checkdir ; make sure the directory exists
15720 (setq checkdir t)
15721 (or (file-directory-p todir) (make-directory todir)))
15723 (unless executables-checked
15724 (org-check-external-command
15725 "latex" "needed to convert LaTeX fragments to images")
15726 (org-check-external-command
15727 "dvipng" "needed to convert LaTeX fragments to images")
15728 (setq executables-checked t))
15730 (unless (file-exists-p movefile)
15731 (org-create-formula-image
15732 txt movefile opt forbuffer))
15733 (if overlays
15734 (progn
15735 (mapc (lambda (o)
15736 (if (eq (overlay-get o 'org-overlay-type)
15737 'org-latex-overlay)
15738 (delete-overlay o)))
15739 (overlays-in beg end))
15740 (setq ov (make-overlay beg end))
15741 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15742 (if (featurep 'xemacs)
15743 (progn
15744 (overlay-put ov 'invisible t)
15745 (overlay-put
15746 ov 'end-glyph
15747 (make-glyph (vector 'png :file movefile))))
15748 (overlay-put
15749 ov 'display
15750 (list 'image :type 'png :file movefile :ascent 'center)))
15751 (push ov org-latex-fragment-image-overlays)
15752 (goto-char end))
15753 (delete-region beg end)
15754 (insert (org-add-props link
15755 (list 'org-latex-src
15756 (replace-regexp-in-string "\"" "" txt)))))))))))
15758 ;; This function borrows from Ganesh Swami's latex2png.el
15759 (defun org-create-formula-image (string tofile options buffer)
15760 "This calls dvipng."
15761 (require 'org-latex)
15762 (let* ((tmpdir (if (featurep 'xemacs)
15763 (temp-directory)
15764 temporary-file-directory))
15765 (texfilebase (make-temp-name
15766 (expand-file-name "orgtex" tmpdir)))
15767 (texfile (concat texfilebase ".tex"))
15768 (dvifile (concat texfilebase ".dvi"))
15769 (pngfile (concat texfilebase ".png"))
15770 (fnh (if (featurep 'xemacs)
15771 (font-height (get-face-font 'default))
15772 (face-attribute 'default :height nil)))
15773 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15774 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15775 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15776 "Black"))
15777 (bg (or (plist-get options (if buffer :background :html-background))
15778 "Transparent")))
15779 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15780 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15781 (with-temp-file texfile
15782 (insert (org-splice-latex-header
15783 org-format-latex-header
15784 org-export-latex-default-packages-alist
15785 org-export-latex-packages-alist t
15786 org-format-latex-header-extra))
15787 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15788 (require 'org-latex)
15789 (org-export-latex-fix-inputenc))
15790 (let ((dir default-directory))
15791 (condition-case nil
15792 (progn
15793 (cd tmpdir)
15794 (call-process "latex" nil nil nil texfile))
15795 (error nil))
15796 (cd dir))
15797 (if (not (file-exists-p dvifile))
15798 (progn (message "Failed to create dvi file from %s" texfile) nil)
15799 (condition-case nil
15800 (call-process "dvipng" nil nil nil
15801 "-fg" fg "-bg" bg
15802 "-D" dpi
15803 ;;"-x" scale "-y" scale
15804 "-T" "tight"
15805 "-o" pngfile
15806 dvifile)
15807 (error nil))
15808 (if (not (file-exists-p pngfile))
15809 (if org-format-latex-signal-error
15810 (error "Failed to create png file from %s" texfile)
15811 (message "Failed to create png file from %s" texfile)
15812 nil)
15813 ;; Use the requested file name and clean up
15814 (copy-file pngfile tofile 'replace)
15815 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15816 (delete-file (concat texfilebase e)))
15817 pngfile))))
15819 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15820 "Fill a LaTeX header template TPL.
15821 In the template, the following place holders will be recognized:
15823 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15824 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15825 [PACKAGES] \\usepackage statements for PKG
15826 [NO-PACKAGES] do not include PKG
15827 [EXTRA] the string EXTRA
15828 [NO-EXTRA] do not include EXTRA
15830 For backward compatibility, if both the positive and the negative place
15831 holder is missing, the positive one (without the \"NO-\") will be
15832 assumed to be present at the end of the template.
15833 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15834 EXTRA is a string.
15835 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15836 (let (rpl (end ""))
15837 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15838 (setq rpl (if (or (match-end 1) (not def-pkg))
15839 "" (org-latex-packages-to-string def-pkg snippets-p t))
15840 tpl (replace-match rpl t t tpl))
15841 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15843 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15844 (setq rpl (if (or (match-end 1) (not pkg))
15845 "" (org-latex-packages-to-string pkg snippets-p t))
15846 tpl (replace-match rpl t t tpl))
15847 (if pkg (setq end
15848 (concat end "\n"
15849 (org-latex-packages-to-string pkg snippets-p)))))
15851 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15852 (setq rpl (if (or (match-end 1) (not extra))
15853 "" (concat extra "\n"))
15854 tpl (replace-match rpl t t tpl))
15855 (if (and extra (string-match "\\S-" extra))
15856 (setq end (concat end "\n" extra))))
15858 (if (string-match "\\S-" end)
15859 (concat tpl "\n" end)
15860 tpl)))
15862 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
15863 "Turn an alist of packages into a string with the \\usepackage macros."
15864 (setq pkg (mapconcat (lambda(p)
15865 (cond
15866 ((stringp p) p)
15867 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
15868 (format "%% Package %s omitted" (cadr p)))
15869 ((equal "" (car p))
15870 (format "\\usepackage{%s}" (cadr p)))
15872 (format "\\usepackage[%s]{%s}"
15873 (car p) (cadr p)))))
15875 "\n"))
15876 (if newline (concat pkg "\n") pkg))
15878 (defun org-dvipng-color (attr)
15879 "Return an rgb color specification for dvipng."
15880 (apply 'format "rgb %s %s %s"
15881 (mapcar 'org-normalize-color
15882 (color-values (face-attribute 'default attr nil)))))
15884 (defun org-normalize-color (value)
15885 "Return string to be used as color value for an RGB component."
15886 (format "%g" (/ value 65535.0)))
15888 ;; Image display
15891 (defvar org-inline-image-overlays nil)
15892 (make-variable-buffer-local 'org-inline-image-overlays)
15894 (defun org-toggle-inline-images (&optional include-linked)
15895 "Toggle the display of inline images.
15896 INCLUDE-LINKED is passed to `org-display-inline-images'."
15897 (interactive "P")
15898 (if org-inline-image-overlays
15899 (progn
15900 (org-remove-inline-images)
15901 (message "Inline image display turned off"))
15902 (org-display-inline-images include-linked)
15903 (if org-inline-image-overlays
15904 (message "%d images displayed inline"
15905 (length org-inline-image-overlays))
15906 (message "No images to display inline"))))
15908 (defun org-display-inline-images (&optional include-linked refresh beg end)
15909 "Display inline images.
15910 Normally only links without a description part are inlined, because this
15911 is how it will work for export. When INCLUDE-LINKED is set, also links
15912 with a description part will be inlined. This can be nice for a quick
15913 look at those images, but it does not reflect whatexported files will look
15914 like.
15915 When REFRESH is set, refresh existing images between BEG and END.
15916 This will create new image displays only if necessary.
15917 BEG and END default to the buffer boundaries."
15918 (interactive "P")
15919 (unless refresh
15920 (org-remove-inline-images)
15921 (clear-image-cache))
15922 (save-excursion
15923 (save-restriction
15924 (widen)
15925 (setq beg (or beg (point-min)) end (or end (point-max)))
15926 (goto-char (point-min))
15927 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~.:/\\_0-9a-zA-Z ]+"
15928 (substring (org-image-file-name-regexp) 0 -2)
15929 "\\)\\]" (if include-linked "" "\\]")))
15930 old file ov img)
15931 (while (re-search-forward re end t)
15932 (setq old (get-char-property-and-overlay (match-beginning 1)
15933 'org-image-overlay))
15934 (setq file (expand-file-name
15935 (concat (or (match-string 3) "") (match-string 4))))
15936 (when (file-exists-p file)
15937 (if (and (car-safe old) refresh)
15938 (image-refresh (overlay-get (cdr old) 'display))
15939 (setq img (create-image file))
15940 (when img
15941 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
15942 (overlay-put ov 'display img)
15943 (overlay-put ov 'face 'default)
15944 (overlay-put ov 'org-image-overlay t)
15945 (overlay-put ov 'modification-hooks
15946 (list 'org-display-inline-modification-hook))
15947 (push ov org-inline-image-overlays)))))))))
15949 (defun org-display-inline-modification-hook (ov after beg end &optional len)
15950 "Remove inline-display overlay if a corresponding region is modified."
15951 (let ((inhibit-modification-hooks t))
15952 (when (and ov after)
15953 (delete ov org-inline-image-overlays)
15954 (delete-overlay ov))))
15956 (defun org-remove-inline-images ()
15957 "Remove inline display of images."
15958 (interactive)
15959 (mapc 'delete-overlay org-inline-image-overlays)
15960 (setq org-inline-image-overlays nil))
15962 ;;;; Key bindings
15964 ;; Make `C-c C-x' a prefix key
15965 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15967 ;; TAB key with modifiers
15968 (org-defkey org-mode-map "\C-i" 'org-cycle)
15969 (org-defkey org-mode-map [(tab)] 'org-cycle)
15970 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15971 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15972 (org-defkey org-mode-map "\M-\t" 'org-complete)
15973 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15974 ;; The following line is necessary under Suse GNU/Linux
15975 (unless (featurep 'xemacs)
15976 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15977 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15978 (define-key org-mode-map [backtab] 'org-shifttab)
15980 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15981 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15982 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15984 ;; Cursor keys with modifiers
15985 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15986 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15987 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15988 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15990 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15991 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15992 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15993 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15995 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15996 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15997 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15998 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16000 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16001 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16003 ;;; Extra keys for tty access.
16004 ;; We only set them when really needed because otherwise the
16005 ;; menus don't show the simple keys
16007 (when (or org-use-extra-keys
16008 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16009 (not window-system))
16010 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16011 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16012 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16013 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16014 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16015 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16016 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16017 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16018 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16019 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16020 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16021 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16022 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16023 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16024 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16025 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16026 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16027 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16028 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16029 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16030 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16031 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16032 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16033 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16034 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16035 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16036 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16037 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16039 ;; All the other keys
16041 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16042 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16043 (if (boundp 'narrow-map)
16044 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16045 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16046 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16047 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16048 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16049 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16050 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16051 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16052 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16053 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16054 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16055 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16056 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16057 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16058 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16059 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16060 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16061 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16062 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16063 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16064 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16065 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16066 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16067 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16068 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16069 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16070 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16071 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16072 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16073 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16074 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16075 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16076 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16077 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16078 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16079 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16080 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16081 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16082 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16083 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16084 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16085 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16086 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16087 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16088 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16089 (org-defkey org-mode-map "\C-c^" 'org-sort)
16090 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16091 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16092 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16093 (org-defkey org-mode-map "\C-m" 'org-return)
16094 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16095 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16096 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16097 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16098 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16099 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16100 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16101 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16102 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16103 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16104 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16105 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16106 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16107 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16108 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16109 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16110 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16111 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16112 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16113 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16114 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16116 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16117 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16118 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16119 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16121 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16122 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16123 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16124 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16125 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16126 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16127 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16128 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16129 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16130 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16131 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16132 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16133 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16134 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16135 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16136 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16137 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16139 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16140 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16141 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16142 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16144 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16146 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16148 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16149 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16151 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16154 (when (featurep 'xemacs)
16155 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16158 (defconst org-speed-commands-default
16160 ("Outline Navigation")
16161 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16162 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16163 ("f" . (org-speed-move-safe 'org-forward-same-level))
16164 ("b" . (org-speed-move-safe 'org-backward-same-level))
16165 ("u" . (org-speed-move-safe 'outline-up-heading))
16166 ("j" . org-goto)
16167 ("g" . (org-refile t))
16168 ("Outline Visibility")
16169 ("c" . org-cycle)
16170 ("C" . org-shifttab)
16171 (" " . org-display-outline-path)
16172 ("Outline Structure Editing")
16173 ("U" . org-shiftmetaup)
16174 ("D" . org-shiftmetadown)
16175 ("r" . org-metaright)
16176 ("l" . org-metaleft)
16177 ("R" . org-shiftmetaright)
16178 ("L" . org-shiftmetaleft)
16179 ("i" . (progn (forward-char 1) (call-interactively
16180 'org-insert-heading-respect-content)))
16181 ("^" . org-sort)
16182 ("w" . org-refile)
16183 ("a" . org-archive-subtree-default-with-confirmation)
16184 ("." . outline-mark-subtree)
16185 ("Clock Commands")
16186 ("I" . org-clock-in)
16187 ("O" . org-clock-out)
16188 ("Meta Data Editing")
16189 ("t" . org-todo)
16190 ("0" . (org-priority ?\ ))
16191 ("1" . (org-priority ?A))
16192 ("2" . (org-priority ?B))
16193 ("3" . (org-priority ?C))
16194 (";" . org-set-tags-command)
16195 ("e" . org-set-effort)
16196 ("Agenda Views etc")
16197 ("v" . org-agenda)
16198 ("/" . org-sparse-tree)
16199 ("Misc")
16200 ("o" . org-open-at-point)
16201 ("?" . org-speed-command-help)
16203 "The default speed commands.")
16205 (defun org-print-speed-command (e)
16206 (if (> (length (car e)) 1)
16207 (progn
16208 (princ "\n")
16209 (princ (car e))
16210 (princ "\n")
16211 (princ (make-string (length (car e)) ?-))
16212 (princ "\n"))
16213 (princ (car e))
16214 (princ " ")
16215 (if (symbolp (cdr e))
16216 (princ (symbol-name (cdr e)))
16217 (prin1 (cdr e)))
16218 (princ "\n")))
16220 (defun org-speed-command-help ()
16221 "Show the available speed commands."
16222 (interactive)
16223 (if (not org-use-speed-commands)
16224 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
16225 (with-output-to-temp-buffer "*Help*"
16226 (princ "User-defined Speed commands\n===========================\n")
16227 (mapc 'org-print-speed-command org-speed-commands-user)
16228 (princ "\n")
16229 (princ "Built-in Speed commands\n=======================\n")
16230 (mapc 'org-print-speed-command org-speed-commands-default))
16231 (with-current-buffer "*Help*"
16232 (setq truncate-lines t))))
16234 (defun org-speed-move-safe (cmd)
16235 "Execute CMD, but make sure that the cursor always ends up in a headline.
16236 If not, return to the original position and throw an error."
16237 (interactive)
16238 (let ((pos (point)))
16239 (call-interactively cmd)
16240 (unless (and (bolp) (org-on-heading-p))
16241 (goto-char pos)
16242 (error "Boundary reached while executing %s" cmd))))
16244 (defvar org-self-insert-command-undo-counter 0)
16246 (defvar org-table-auto-blank-field) ; defined in org-table.el
16247 (defvar org-speed-command nil)
16248 (defun org-self-insert-command (N)
16249 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16250 If the cursor is in a table looking at whitespace, the whitespace is
16251 overwritten, and the table is not marked as requiring realignment."
16252 (interactive "p")
16253 (cond
16254 ((and org-use-speed-commands
16255 (or (and (bolp) (looking-at outline-regexp))
16256 (and (functionp org-use-speed-commands)
16257 (funcall org-use-speed-commands)))
16258 (setq
16259 org-speed-command
16260 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16261 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16262 (cond
16263 ((commandp org-speed-command)
16264 (setq this-command org-speed-command)
16265 (call-interactively org-speed-command))
16266 ((functionp org-speed-command)
16267 (funcall org-speed-command))
16268 ((and org-speed-command (listp org-speed-command))
16269 (eval org-speed-command))
16270 (t (let (org-use-speed-commands)
16271 (call-interactively 'org-self-insert-command)))))
16272 ((and
16273 (org-table-p)
16274 (progn
16275 ;; check if we blank the field, and if that triggers align
16276 (and (featurep 'org-table) org-table-auto-blank-field
16277 (member last-command
16278 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16279 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16280 ;; got extra space, this field does not determine column width
16281 (let (org-table-may-need-update) (org-table-blank-field))
16282 ;; no extra space, this field may determine column width
16283 (org-table-blank-field)))
16285 (eq N 1)
16286 (looking-at "[^|\n]* |"))
16287 (let (org-table-may-need-update)
16288 (goto-char (1- (match-end 0)))
16289 (delete-backward-char 1)
16290 (goto-char (match-beginning 0))
16291 (self-insert-command N)))
16293 (setq org-table-may-need-update t)
16294 (self-insert-command N)
16295 (org-fix-tags-on-the-fly)
16296 (if org-self-insert-cluster-for-undo
16297 (if (not (eq last-command 'org-self-insert-command))
16298 (setq org-self-insert-command-undo-counter 1)
16299 (if (>= org-self-insert-command-undo-counter 20)
16300 (setq org-self-insert-command-undo-counter 1)
16301 (and (> org-self-insert-command-undo-counter 0)
16302 buffer-undo-list
16303 (not (cadr buffer-undo-list)) ; remove nil entry
16304 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16305 (setq org-self-insert-command-undo-counter
16306 (1+ org-self-insert-command-undo-counter))))))))
16308 (defun org-fix-tags-on-the-fly ()
16309 (when (and (equal (char-after (point-at-bol)) ?*)
16310 (org-on-heading-p))
16311 (org-align-tags-here org-tags-column)))
16313 (defun org-delete-backward-char (N)
16314 "Like `delete-backward-char', insert whitespace at field end in tables.
16315 When deleting backwards, in tables this function will insert whitespace in
16316 front of the next \"|\" separator, to keep the table aligned. The table will
16317 still be marked for re-alignment if the field did fill the entire column,
16318 because, in this case the deletion might narrow the column."
16319 (interactive "p")
16320 (if (and (org-table-p)
16321 (eq N 1)
16322 (string-match "|" (buffer-substring (point-at-bol) (point)))
16323 (looking-at ".*?|"))
16324 (let ((pos (point))
16325 (noalign (looking-at "[^|\n\r]* |"))
16326 (c org-table-may-need-update))
16327 (backward-delete-char N)
16328 (skip-chars-forward "^|")
16329 (insert " ")
16330 (goto-char (1- pos))
16331 ;; noalign: if there were two spaces at the end, this field
16332 ;; does not determine the width of the column.
16333 (if noalign (setq org-table-may-need-update c)))
16334 (backward-delete-char N)
16335 (org-fix-tags-on-the-fly)))
16337 (defun org-delete-char (N)
16338 "Like `delete-char', but insert whitespace at field end in tables.
16339 When deleting characters, in tables this function will insert whitespace in
16340 front of the next \"|\" separator, to keep the table aligned. The table will
16341 still be marked for re-alignment if the field did fill the entire column,
16342 because, in this case the deletion might narrow the column."
16343 (interactive "p")
16344 (if (and (org-table-p)
16345 (not (bolp))
16346 (not (= (char-after) ?|))
16347 (eq N 1))
16348 (if (looking-at ".*?|")
16349 (let ((pos (point))
16350 (noalign (looking-at "[^|\n\r]* |"))
16351 (c org-table-may-need-update))
16352 (replace-match (concat
16353 (substring (match-string 0) 1 -1)
16354 " |"))
16355 (goto-char pos)
16356 ;; noalign: if there were two spaces at the end, this field
16357 ;; does not determine the width of the column.
16358 (if noalign (setq org-table-may-need-update c)))
16359 (delete-char N))
16360 (delete-char N)
16361 (org-fix-tags-on-the-fly)))
16363 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16364 (put 'org-self-insert-command 'delete-selection t)
16365 (put 'orgtbl-self-insert-command 'delete-selection t)
16366 (put 'org-delete-char 'delete-selection 'supersede)
16367 (put 'org-delete-backward-char 'delete-selection 'supersede)
16368 (put 'org-yank 'delete-selection 'yank)
16370 ;; Make `flyspell-mode' delay after some commands
16371 (put 'org-self-insert-command 'flyspell-delayed t)
16372 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16373 (put 'org-delete-char 'flyspell-delayed t)
16374 (put 'org-delete-backward-char 'flyspell-delayed t)
16376 ;; Make pabbrev-mode expand after org-mode commands
16377 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16378 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16380 ;; How to do this: Measure non-white length of current string
16381 ;; If equal to column width, we should realign.
16383 (defun org-remap (map &rest commands)
16384 "In MAP, remap the functions given in COMMANDS.
16385 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16386 (let (new old)
16387 (while commands
16388 (setq old (pop commands) new (pop commands))
16389 (if (fboundp 'command-remapping)
16390 (org-defkey map (vector 'remap old) new)
16391 (substitute-key-definition old new map global-map)))))
16393 (when (eq org-enable-table-editor 'optimized)
16394 ;; If the user wants maximum table support, we need to hijack
16395 ;; some standard editing functions
16396 (org-remap org-mode-map
16397 'self-insert-command 'org-self-insert-command
16398 'delete-char 'org-delete-char
16399 'delete-backward-char 'org-delete-backward-char)
16400 (org-defkey org-mode-map "|" 'org-force-self-insert))
16402 (defvar org-ctrl-c-ctrl-c-hook nil
16403 "Hook for functions attaching themselves to `C-c C-c'.
16404 This can be used to add additional functionality to the C-c C-c key which
16405 executes context-dependent commands.
16406 Each function will be called with no arguments. The function must check
16407 if the context is appropriate for it to act. If yes, it should do its
16408 thing and then return a non-nil value. If the context is wrong,
16409 just do nothing and return nil.")
16411 (defvar org-tab-first-hook nil
16412 "Hook for functions to attach themselves to TAB.
16413 See `org-ctrl-c-ctrl-c-hook' for more information.
16414 This hook runs as the first action when TAB is pressed, even before
16415 `org-cycle' messes around with the `outline-regexp' to cater for
16416 inline tasks and plain list item folding.
16417 If any function in this hook returns t, any other actions that
16418 would have been caused by TAB (such as table field motion or visibility
16419 cycling) will not occur.")
16421 (defvar org-tab-after-check-for-table-hook nil
16422 "Hook for functions to attach themselves to TAB.
16423 See `org-ctrl-c-ctrl-c-hook' for more information.
16424 This hook runs after it has been established that the cursor is not in a
16425 table, but before checking if the cursor is in a headline or if global cycling
16426 should be done.
16427 If any function in this hook returns t, not other actions like visibility
16428 cycling will be done.")
16430 (defvar org-tab-after-check-for-cycling-hook nil
16431 "Hook for functions to attach themselves to TAB.
16432 See `org-ctrl-c-ctrl-c-hook' for more information.
16433 This hook runs after it has been established that not table field motion and
16434 not visibility should be done because of current context. This is probably
16435 the place where a package like yasnippets can hook in.")
16437 (defvar org-tab-before-tab-emulation-hook nil
16438 "Hook for functions to attach themselves to TAB.
16439 See `org-ctrl-c-ctrl-c-hook' for more information.
16440 This hook runs after every other options for TAB have been exhausted, but
16441 before indentation and \t insertion takes place.")
16443 (defvar org-metaleft-hook nil
16444 "Hook for functions attaching themselves to `M-left'.
16445 See `org-ctrl-c-ctrl-c-hook' for more information.")
16446 (defvar org-metaright-hook nil
16447 "Hook for functions attaching themselves to `M-right'.
16448 See `org-ctrl-c-ctrl-c-hook' for more information.")
16449 (defvar org-metaup-hook nil
16450 "Hook for functions attaching themselves to `M-up'.
16451 See `org-ctrl-c-ctrl-c-hook' for more information.")
16452 (defvar org-metadown-hook nil
16453 "Hook for functions attaching themselves to `M-down'.
16454 See `org-ctrl-c-ctrl-c-hook' for more information.")
16455 (defvar org-shiftmetaleft-hook nil
16456 "Hook for functions attaching themselves to `M-S-left'.
16457 See `org-ctrl-c-ctrl-c-hook' for more information.")
16458 (defvar org-shiftmetaright-hook nil
16459 "Hook for functions attaching themselves to `M-S-right'.
16460 See `org-ctrl-c-ctrl-c-hook' for more information.")
16461 (defvar org-shiftmetaup-hook nil
16462 "Hook for functions attaching themselves to `M-S-up'.
16463 See `org-ctrl-c-ctrl-c-hook' for more information.")
16464 (defvar org-shiftmetadown-hook nil
16465 "Hook for functions attaching themselves to `M-S-down'.
16466 See `org-ctrl-c-ctrl-c-hook' for more information.")
16467 (defvar org-metareturn-hook nil
16468 "Hook for functions attaching themselves to `M-RET'.
16469 See `org-ctrl-c-ctrl-c-hook' for more information.")
16470 (defvar org-shiftup-hook nil
16471 "Hook for functions attaching themselves to `S-up'.
16472 See `org-ctrl-c-ctrl-c-hook' for more information.")
16473 (defvar org-shiftup-final-hook nil
16474 "Hook for functions attaching themselves to `S-up'.
16475 This one runs after all other options except shift-select have been excluded.
16476 See `org-ctrl-c-ctrl-c-hook' for more information.")
16477 (defvar org-shiftdown-hook nil
16478 "Hook for functions attaching themselves to `S-down'.
16479 See `org-ctrl-c-ctrl-c-hook' for more information.")
16480 (defvar org-shiftdown-final-hook nil
16481 "Hook for functions attaching themselves to `S-down'.
16482 This one runs after all other options except shift-select have been excluded.
16483 See `org-ctrl-c-ctrl-c-hook' for more information.")
16484 (defvar org-shiftleft-hook nil
16485 "Hook for functions attaching themselves to `S-left'.
16486 See `org-ctrl-c-ctrl-c-hook' for more information.")
16487 (defvar org-shiftleft-final-hook nil
16488 "Hook for functions attaching themselves to `S-left'.
16489 This one runs after all other options except shift-select have been excluded.
16490 See `org-ctrl-c-ctrl-c-hook' for more information.")
16491 (defvar org-shiftright-hook nil
16492 "Hook for functions attaching themselves to `S-right'.
16493 See `org-ctrl-c-ctrl-c-hook' for more information.")
16494 (defvar org-shiftright-final-hook nil
16495 "Hook for functions attaching themselves to `S-right'.
16496 This one runs after all other options except shift-select have been excluded.
16497 See `org-ctrl-c-ctrl-c-hook' for more information.")
16499 (defun org-modifier-cursor-error ()
16500 "Throw an error, a modified cursor command was applied in wrong context."
16501 (error "This command is active in special context like tables, headlines or items"))
16503 (defun org-shiftselect-error ()
16504 "Throw an error because Shift-Cursor command was applied in wrong context."
16505 (if (and (boundp 'shift-select-mode) shift-select-mode)
16506 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16507 (error "This command works only in special context like headlines or timestamps")))
16509 (defun org-call-for-shift-select (cmd)
16510 (let ((this-command-keys-shift-translated t))
16511 (call-interactively cmd)))
16513 (defun org-shifttab (&optional arg)
16514 "Global visibility cycling or move to previous table field.
16515 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16516 on context.
16517 See the individual commands for more information."
16518 (interactive "P")
16519 (cond
16520 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16521 ((integerp arg)
16522 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16523 (message "Content view to level: %d" arg)
16524 (org-content (prefix-numeric-value arg2))
16525 (setq org-cycle-global-status 'overview)))
16526 (t (call-interactively 'org-global-cycle))))
16528 (defun org-shiftmetaleft ()
16529 "Promote subtree or delete table column.
16530 Calls `org-promote-subtree', `org-outdent-item',
16531 or `org-table-delete-column', depending on context.
16532 See the individual commands for more information."
16533 (interactive)
16534 (cond
16535 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16536 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16537 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16538 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16539 (t (org-modifier-cursor-error))))
16541 (defun org-shiftmetaright ()
16542 "Demote subtree or insert table column.
16543 Calls `org-demote-subtree', `org-indent-item',
16544 or `org-table-insert-column', depending on context.
16545 See the individual commands for more information."
16546 (interactive)
16547 (cond
16548 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16549 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16550 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16551 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16552 (t (org-modifier-cursor-error))))
16554 (defun org-shiftmetaup (&optional arg)
16555 "Move subtree up or kill table row.
16556 Calls `org-move-subtree-up' or `org-table-kill-row' or
16557 `org-move-item-up' depending on context. See the individual commands
16558 for more information."
16559 (interactive "P")
16560 (cond
16561 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16562 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16563 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16564 ((org-at-item-p) (call-interactively 'org-move-item-up))
16565 (t (org-modifier-cursor-error))))
16567 (defun org-shiftmetadown (&optional arg)
16568 "Move subtree down or insert table row.
16569 Calls `org-move-subtree-down' or `org-table-insert-row' or
16570 `org-move-item-down', depending on context. See the individual
16571 commands for more information."
16572 (interactive "P")
16573 (cond
16574 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16575 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16576 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16577 ((org-at-item-p) (call-interactively 'org-move-item-down))
16578 (t (org-modifier-cursor-error))))
16580 (defsubst org-hidden-tree-error ()
16581 (error
16582 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16584 (defun org-metaleft (&optional arg)
16585 "Promote heading or move table column to left.
16586 Calls `org-do-promote' or `org-table-move-column', depending on context.
16587 With no specific context, calls the Emacs default `backward-word'.
16588 See the individual commands for more information."
16589 (interactive "P")
16590 (cond
16591 ((run-hook-with-args-until-success 'org-metaleft-hook))
16592 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16593 ((or (org-on-heading-p)
16594 (and (org-region-active-p)
16595 (save-excursion
16596 (goto-char (region-beginning))
16597 (org-on-heading-p))))
16598 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16599 (call-interactively 'org-do-promote))
16600 ((or (org-at-item-p)
16601 (and (org-region-active-p)
16602 (save-excursion
16603 (goto-char (region-beginning))
16604 (org-at-item-p))))
16605 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16606 (call-interactively 'org-outdent-item))
16607 (t (call-interactively 'backward-word))))
16609 (defun org-metaright (&optional arg)
16610 "Demote subtree or move table column to right.
16611 Calls `org-do-demote' or `org-table-move-column', depending on context.
16612 With no specific context, calls the Emacs default `forward-word'.
16613 See the individual commands for more information."
16614 (interactive "P")
16615 (cond
16616 ((run-hook-with-args-until-success 'org-metaright-hook))
16617 ((org-at-table-p) (call-interactively 'org-table-move-column))
16618 ((or (org-on-heading-p)
16619 (and (org-region-active-p)
16620 (save-excursion
16621 (goto-char (region-beginning))
16622 (org-on-heading-p))))
16623 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16624 (call-interactively 'org-do-demote))
16625 ((or (org-at-item-p)
16626 (and (org-region-active-p)
16627 (save-excursion
16628 (goto-char (region-beginning))
16629 (org-at-item-p))))
16630 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16631 (call-interactively 'org-indent-item))
16632 (t (call-interactively 'forward-word))))
16634 (defun org-check-for-hidden (what)
16635 "Check if there are hidden headlines/items in the current visual line.
16636 WHAT can be either `headlines' or `items'. If the current line is
16637 an outline or item heading and it has a folded subtree below it,
16638 this fucntion returns t, nil otherwise."
16639 (let ((re (cond
16640 ((eq what 'headlines) (concat "^" org-outline-regexp))
16641 ((eq what 'items) (concat "^" (org-item-re t)))
16642 (t (error "This should not happen"))))
16643 beg end)
16644 (save-excursion
16645 (catch 'exit
16646 (unless (org-region-active-p)
16647 (setq beg (point-at-bol))
16648 (beginning-of-line 2)
16649 (while (and (not (eobp)) ;; this is like `next-line'
16650 (get-char-property (1- (point)) 'invisible))
16651 (beginning-of-line 2))
16652 (setq end (point))
16653 (goto-char beg)
16654 (goto-char (point-at-eol))
16655 (setq end (max end (point)))
16656 (while (re-search-forward re end t)
16657 (if (get-char-property (match-beginning 0) 'invisible)
16658 (throw 'exit t))))
16659 nil))))
16661 (defun org-metaup (&optional arg)
16662 "Move subtree up or move table row up.
16663 Calls `org-move-subtree-up' or `org-table-move-row' or
16664 `org-move-item-up', depending on context. See the individual commands
16665 for more information."
16666 (interactive "P")
16667 (cond
16668 ((run-hook-with-args-until-success 'org-metaup-hook))
16669 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16670 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16671 ((org-at-item-p) (call-interactively 'org-move-item-up))
16672 (t (transpose-lines 1) (beginning-of-line -1))))
16674 (defun org-metadown (&optional arg)
16675 "Move subtree down or move table row down.
16676 Calls `org-move-subtree-down' or `org-table-move-row' or
16677 `org-move-item-down', depending on context. See the individual
16678 commands for more information."
16679 (interactive "P")
16680 (cond
16681 ((run-hook-with-args-until-success 'org-metadown-hook))
16682 ((org-at-table-p) (call-interactively 'org-table-move-row))
16683 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16684 ((org-at-item-p) (call-interactively 'org-move-item-down))
16685 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16687 (defun org-shiftup (&optional arg)
16688 "Increase item in timestamp or increase priority of current headline.
16689 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16690 depending on context. See the individual commands for more information."
16691 (interactive "P")
16692 (cond
16693 ((run-hook-with-args-until-success 'org-shiftup-hook))
16694 ((and org-support-shift-select (org-region-active-p))
16695 (org-call-for-shift-select 'previous-line))
16696 ((org-at-timestamp-p t)
16697 (call-interactively (if org-edit-timestamp-down-means-later
16698 'org-timestamp-down 'org-timestamp-up)))
16699 ((and (not (eq org-support-shift-select 'always))
16700 org-enable-priority-commands
16701 (org-on-heading-p))
16702 (call-interactively 'org-priority-up))
16703 ((and (not org-support-shift-select) (org-at-item-p))
16704 (call-interactively 'org-previous-item))
16705 ((org-clocktable-try-shift 'up arg))
16706 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16707 (org-support-shift-select
16708 (org-call-for-shift-select 'previous-line))
16709 (t (org-shiftselect-error))))
16711 (defun org-shiftdown (&optional arg)
16712 "Decrease item in timestamp or decrease priority of current headline.
16713 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16714 depending on context. See the individual commands for more information."
16715 (interactive "P")
16716 (cond
16717 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16718 ((and org-support-shift-select (org-region-active-p))
16719 (org-call-for-shift-select 'next-line))
16720 ((org-at-timestamp-p t)
16721 (call-interactively (if org-edit-timestamp-down-means-later
16722 'org-timestamp-up 'org-timestamp-down)))
16723 ((and (not (eq org-support-shift-select 'always))
16724 org-enable-priority-commands
16725 (org-on-heading-p))
16726 (call-interactively 'org-priority-down))
16727 ((and (not org-support-shift-select) (org-at-item-p))
16728 (call-interactively 'org-next-item))
16729 ((org-clocktable-try-shift 'down arg))
16730 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16731 (org-support-shift-select
16732 (org-call-for-shift-select 'next-line))
16733 (t (org-shiftselect-error))))
16735 (defun org-shiftright (&optional arg)
16736 "Cycle the thing at point or in the current line, depending on context.
16737 Depending on context, this does one of the following:
16739 - switch a timestamp at point one day into the future
16740 - on a headline, switch to the next TODO keyword.
16741 - on an item, switch entire list to the next bullet type
16742 - on a property line, switch to the next allowed value
16743 - on a clocktable definition line, move time block into the future"
16744 (interactive "P")
16745 (cond
16746 ((run-hook-with-args-until-success 'org-shiftright-hook))
16747 ((and org-support-shift-select (org-region-active-p))
16748 (org-call-for-shift-select 'forward-char))
16749 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16750 ((and (not (eq org-support-shift-select 'always))
16751 (org-on-heading-p))
16752 (let ((org-inhibit-logging
16753 (not org-treat-S-cursor-todo-selection-as-state-change))
16754 (org-inhibit-blocking
16755 (not org-treat-S-cursor-todo-selection-as-state-change)))
16756 (org-call-with-arg 'org-todo 'right)))
16757 ((or (and org-support-shift-select
16758 (not (eq org-support-shift-select 'always))
16759 (org-at-item-bullet-p))
16760 (and (not org-support-shift-select) (org-at-item-p)))
16761 (org-call-with-arg 'org-cycle-list-bullet nil))
16762 ((and (not (eq org-support-shift-select 'always))
16763 (org-at-property-p))
16764 (call-interactively 'org-property-next-allowed-value))
16765 ((org-clocktable-try-shift 'right arg))
16766 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16767 (org-support-shift-select
16768 (org-call-for-shift-select 'forward-char))
16769 (t (org-shiftselect-error))))
16771 (defun org-shiftleft (&optional arg)
16772 "Cycle the thing at point or in the current line, depending on context.
16773 Depending on context, this does one of the following:
16775 - switch a timestamp at point one day into the past
16776 - on a headline, switch to the previous TODO keyword.
16777 - on an item, switch entire list to the previous bullet type
16778 - on a property line, switch to the previous allowed value
16779 - on a clocktable definition line, move time block into the past"
16780 (interactive "P")
16781 (cond
16782 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16783 ((and org-support-shift-select (org-region-active-p))
16784 (org-call-for-shift-select 'backward-char))
16785 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16786 ((and (not (eq org-support-shift-select 'always))
16787 (org-on-heading-p))
16788 (let ((org-inhibit-logging
16789 (not org-treat-S-cursor-todo-selection-as-state-change))
16790 (org-inhibit-blocking
16791 (not org-treat-S-cursor-todo-selection-as-state-change)))
16792 (org-call-with-arg 'org-todo 'left)))
16793 ((or (and org-support-shift-select
16794 (not (eq org-support-shift-select 'always))
16795 (org-at-item-bullet-p))
16796 (and (not org-support-shift-select) (org-at-item-p)))
16797 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16798 ((and (not (eq org-support-shift-select 'always))
16799 (org-at-property-p))
16800 (call-interactively 'org-property-previous-allowed-value))
16801 ((org-clocktable-try-shift 'left arg))
16802 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16803 (org-support-shift-select
16804 (org-call-for-shift-select 'backward-char))
16805 (t (org-shiftselect-error))))
16807 (defun org-shiftcontrolright ()
16808 "Switch to next TODO set."
16809 (interactive)
16810 (cond
16811 ((and org-support-shift-select (org-region-active-p))
16812 (org-call-for-shift-select 'forward-word))
16813 ((and (not (eq org-support-shift-select 'always))
16814 (org-on-heading-p))
16815 (org-call-with-arg 'org-todo 'nextset))
16816 (org-support-shift-select
16817 (org-call-for-shift-select 'forward-word))
16818 (t (org-shiftselect-error))))
16820 (defun org-shiftcontrolleft ()
16821 "Switch to previous TODO set."
16822 (interactive)
16823 (cond
16824 ((and org-support-shift-select (org-region-active-p))
16825 (org-call-for-shift-select 'backward-word))
16826 ((and (not (eq org-support-shift-select 'always))
16827 (org-on-heading-p))
16828 (org-call-with-arg 'org-todo 'previousset))
16829 (org-support-shift-select
16830 (org-call-for-shift-select 'backward-word))
16831 (t (org-shiftselect-error))))
16833 (defun org-ctrl-c-ret ()
16834 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16835 (interactive)
16836 (cond
16837 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16838 (t (call-interactively 'org-insert-heading))))
16840 (defun org-copy-special ()
16841 "Copy region in table or copy current subtree.
16842 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16843 See the individual commands for more information."
16844 (interactive)
16845 (call-interactively
16846 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16848 (defun org-cut-special ()
16849 "Cut region in table or cut current subtree.
16850 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16851 See the individual commands for more information."
16852 (interactive)
16853 (call-interactively
16854 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16856 (defun org-paste-special (arg)
16857 "Paste rectangular region into table, or past subtree relative to level.
16858 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16859 See the individual commands for more information."
16860 (interactive "P")
16861 (if (org-at-table-p)
16862 (org-table-paste-rectangle)
16863 (org-paste-subtree arg)))
16865 (defun org-edit-special ()
16866 "Call a special editor for the stuff at point.
16867 When at a table, call the formula editor with `org-table-edit-formulas'.
16868 When at the first line of an src example, call `org-edit-src-code'.
16869 When in an #+include line, visit the include file. Otherwise call
16870 `ffap' to visit the file at point."
16871 (interactive)
16872 (cond
16873 ((save-excursion
16874 (beginning-of-line 1)
16875 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16876 (find-file (org-trim (match-string 1))))
16877 ((org-edit-src-code))
16878 ((org-edit-fixed-width-region))
16879 ((org-at-table.el-p)
16880 (org-edit-src-code))
16881 ((org-at-table-p)
16882 (call-interactively 'org-table-edit-formulas))
16883 (t (call-interactively 'ffap))))
16886 (defun org-ctrl-c-ctrl-c (&optional arg)
16887 "Set tags in headline, or update according to changed information at point.
16889 This command does many different things, depending on context:
16891 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16892 this is what we do.
16894 - If the cursor is on a statistics cookie, update it.
16896 - If the cursor is in a headline, prompt for tags and insert them
16897 into the current line, aligned to `org-tags-column'. When called
16898 with prefix arg, realign all tags in the current buffer.
16900 - If the cursor is in one of the special #+KEYWORD lines, this
16901 triggers scanning the buffer for these lines and updating the
16902 information.
16904 - If the cursor is inside a table, realign the table. This command
16905 works even if the automatic table editor has been turned off.
16907 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16908 the entire table.
16910 - If the cursor is at a footnote reference or definition, jump to
16911 the corresponding definition or references, respectively.
16913 - If the cursor is a the beginning of a dynamic block, update it.
16915 - If the current buffer is a remember buffer, close note and file
16916 it. A prefix argument of 1 files to the default location
16917 without further interaction. A prefix argument of 2 files to
16918 the currently clocking task.
16920 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16921 links in this buffer.
16923 - If the cursor is on a numbered item in a plain list, renumber the
16924 ordered list.
16926 - If the cursor is on a checkbox, toggle it."
16927 (interactive "P")
16928 (let ((org-enable-table-editor t))
16929 (cond
16930 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16931 org-occur-highlights
16932 org-latex-fragment-image-overlays)
16933 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16934 (org-remove-occur-highlights)
16935 (org-remove-latex-fragment-image-overlays)
16936 (message "Temporary highlights/overlays removed from current buffer"))
16937 ((and (local-variable-p 'org-finish-function (current-buffer))
16938 (fboundp org-finish-function))
16939 (funcall org-finish-function))
16940 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16941 ((or (looking-at org-property-start-re)
16942 (org-at-property-p))
16943 (call-interactively 'org-property-action))
16944 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16945 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16946 (or (org-on-heading-p) (org-at-item-p)))
16947 (call-interactively 'org-update-statistics-cookies))
16948 ((org-on-heading-p) (call-interactively 'org-set-tags))
16949 ((org-at-table.el-p)
16950 (message "Use C-c ' to edit table.el tables"))
16951 ((org-at-table-p)
16952 (org-table-maybe-eval-formula)
16953 (if arg
16954 (call-interactively 'org-table-recalculate)
16955 (org-table-maybe-recalculate-line))
16956 (call-interactively 'org-table-align))
16957 ((or (org-footnote-at-reference-p)
16958 (org-footnote-at-definition-p))
16959 (call-interactively 'org-footnote-action))
16960 ((org-at-item-checkbox-p)
16961 (call-interactively 'org-toggle-checkbox))
16962 ((org-at-item-p)
16963 (if arg
16964 (call-interactively 'org-toggle-checkbox)
16965 (call-interactively 'org-maybe-renumber-ordered-list)))
16966 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16967 ;; Dynamic block
16968 (beginning-of-line 1)
16969 (save-excursion (org-update-dblock)))
16970 ((save-excursion
16971 (beginning-of-line 1)
16972 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16973 (cond
16974 ((equal (match-string 1) "TBLFM")
16975 ;; Recalculate the table before this line
16976 (save-excursion
16977 (beginning-of-line 1)
16978 (skip-chars-backward " \r\n\t")
16979 (if (org-at-table-p)
16980 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16982 (let ((org-inhibit-startup-visibility-stuff t)
16983 (org-startup-align-all-tables nil))
16984 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16985 (message "Local setup has been refreshed"))))
16986 ((org-clock-update-time-maybe))
16987 (t (error "C-c C-c can do nothing useful at this location")))))
16989 (defun org-mode-restart ()
16990 "Restart Org-mode, to scan again for special lines.
16991 Also updates the keyword regular expressions."
16992 (interactive)
16993 (org-mode)
16994 (message "Org-mode restarted"))
16996 (defun org-kill-note-or-show-branches ()
16997 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16998 (interactive)
16999 (if (not org-finish-function)
17000 (progn
17001 (hide-subtree)
17002 (call-interactively 'show-branches))
17003 (let ((org-note-abort t))
17004 (funcall org-finish-function))))
17006 (defun org-return (&optional indent)
17007 "Goto next table row or insert a newline.
17008 Calls `org-table-next-row' or `newline', depending on context.
17009 See the individual commands for more information."
17010 (interactive)
17011 (cond
17012 ((bobp) (if indent (newline-and-indent) (newline)))
17013 ((org-at-table-p)
17014 (org-table-justify-field-maybe)
17015 (call-interactively 'org-table-next-row))
17016 ((and org-return-follows-link
17017 (eq (get-text-property (point) 'face) 'org-link))
17018 (call-interactively 'org-open-at-point))
17019 ((and (org-at-heading-p)
17020 (looking-at
17021 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
17022 (org-show-entry)
17023 (end-of-line 1)
17024 (newline))
17025 (t (if indent (newline-and-indent) (newline)))))
17027 (defun org-return-indent ()
17028 "Goto next table row or insert a newline and indent.
17029 Calls `org-table-next-row' or `newline-and-indent', depending on
17030 context. See the individual commands for more information."
17031 (interactive)
17032 (org-return t))
17034 (defun org-ctrl-c-star ()
17035 "Compute table, or change heading status of lines.
17036 Calls `org-table-recalculate' or `org-toggle-heading',
17037 depending on context."
17038 (interactive)
17039 (cond
17040 ((org-at-table-p)
17041 (call-interactively 'org-table-recalculate))
17043 ;; Convert all lines in region to list items
17044 (call-interactively 'org-toggle-heading))))
17046 (defun org-ctrl-c-minus ()
17047 "Insert separator line in table or modify bullet status of line.
17048 Also turns a plain line or a region of lines into list items.
17049 Calls `org-table-insert-hline', `org-toggle-item', or
17050 `org-cycle-list-bullet', depending on context."
17051 (interactive)
17052 (cond
17053 ((org-at-table-p)
17054 (call-interactively 'org-table-insert-hline))
17055 ((org-region-active-p)
17056 (call-interactively 'org-toggle-item))
17057 ((org-in-item-p)
17058 (call-interactively 'org-cycle-list-bullet))
17060 (call-interactively 'org-toggle-item))))
17062 (defun org-toggle-item ()
17063 "Convert headings or normal lines to items, items to normal lines.
17064 If there is no active region, only the current line is considered.
17066 If the first line in the region is a headline, convert all headlines to items.
17068 If the first line in the region is an item, convert all items to normal lines.
17070 If the first line is normal text, add an item bullet to each line."
17071 (interactive)
17072 (let (l2 l beg end)
17073 (if (org-region-active-p)
17074 (setq beg (region-beginning) end (region-end))
17075 (setq beg (point-at-bol)
17076 end (min (1+ (point-at-eol)) (point-max))))
17077 (save-excursion
17078 (goto-char end)
17079 (setq l2 (org-current-line))
17080 (goto-char beg)
17081 (beginning-of-line 1)
17082 (setq l (1- (org-current-line)))
17083 (if (org-at-item-p)
17084 ;; We already have items, de-itemize
17085 (while (< (setq l (1+ l)) l2)
17086 (when (org-at-item-p)
17087 (goto-char (match-beginning 2))
17088 (delete-region (match-beginning 2) (match-end 2))
17089 (and (looking-at "[ \t]+") (replace-match "")))
17090 (beginning-of-line 2))
17091 (if (org-on-heading-p)
17092 ;; Headings, convert to items
17093 (while (< (setq l (1+ l)) l2)
17094 (if (looking-at org-outline-regexp)
17095 (replace-match "- " t t))
17096 (beginning-of-line 2))
17097 ;; normal lines, turn them into items
17098 (while (< (setq l (1+ l)) l2)
17099 (unless (org-at-item-p)
17100 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17101 (replace-match "\\1- \\2")))
17102 (beginning-of-line 2)))))))
17104 (defun org-toggle-heading (&optional nstars)
17105 "Convert headings to normal text, or items or text to headings.
17106 If there is no active region, only the current line is considered.
17108 If the first line is a heading, remove the stars from all headlines
17109 in the region.
17111 If the first line is a plain list item, turn all plain list items
17112 into headings.
17114 If the first line is a normal line, turn each and every line in the
17115 region into a heading.
17117 When converting a line into a heading, the number of stars is chosen
17118 such that the lines become children of the current entry. However,
17119 when a prefix argument is given, its value determines the number of
17120 stars to add."
17121 (interactive "P")
17122 (let (l2 l itemp beg end)
17123 (if (org-region-active-p)
17124 (setq beg (region-beginning) end (region-end))
17125 (setq beg (point-at-bol)
17126 end (min (1+ (point-at-eol)) (point-max))))
17127 (save-excursion
17128 (goto-char end)
17129 (setq l2 (org-current-line))
17130 (goto-char beg)
17131 (beginning-of-line 1)
17132 (setq l (1- (org-current-line)))
17133 (if (org-on-heading-p)
17134 ;; We already have headlines, de-star them
17135 (while (< (setq l (1+ l)) l2)
17136 (when (org-on-heading-p t)
17137 (and (looking-at outline-regexp) (replace-match "")))
17138 (beginning-of-line 2))
17139 (setq itemp (org-at-item-p))
17140 (let* ((stars
17141 (if nstars
17142 (make-string (prefix-numeric-value current-prefix-arg)
17144 (save-excursion
17145 (if (re-search-backward org-complex-heading-regexp nil t)
17146 (match-string 1) ""))))
17147 (add-stars (cond (nstars "")
17148 ((equal stars "") "*")
17149 (org-odd-levels-only "**")
17150 (t "*")))
17151 (rpl (concat stars add-stars " ")))
17152 (while (< (setq l (1+ l)) l2)
17153 (if itemp
17154 (and (org-at-item-p) (replace-match rpl t t))
17155 (unless (org-on-heading-p)
17156 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17157 (replace-match (concat rpl (match-string 2))))))
17158 (beginning-of-line 2)))))))
17160 (defun org-meta-return (&optional arg)
17161 "Insert a new heading or wrap a region in a table.
17162 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17163 See the individual commands for more information."
17164 (interactive "P")
17165 (cond
17166 ((run-hook-with-args-until-success 'org-metareturn-hook))
17167 ((org-at-table-p)
17168 (call-interactively 'org-table-wrap-region))
17169 (t (call-interactively 'org-insert-heading))))
17171 ;;; Menu entries
17173 ;; Define the Org-mode menus
17174 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17175 '("Tbl"
17176 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17177 ["Next Field" org-cycle (org-at-table-p)]
17178 ["Previous Field" org-shifttab (org-at-table-p)]
17179 ["Next Row" org-return (org-at-table-p)]
17180 "--"
17181 ["Blank Field" org-table-blank-field (org-at-table-p)]
17182 ["Edit Field" org-table-edit-field (org-at-table-p)]
17183 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17184 "--"
17185 ("Column"
17186 ["Move Column Left" org-metaleft (org-at-table-p)]
17187 ["Move Column Right" org-metaright (org-at-table-p)]
17188 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17189 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17190 ("Row"
17191 ["Move Row Up" org-metaup (org-at-table-p)]
17192 ["Move Row Down" org-metadown (org-at-table-p)]
17193 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17194 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17195 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17196 "--"
17197 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17198 ("Rectangle"
17199 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17200 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17201 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17202 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17203 "--"
17204 ("Calculate"
17205 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17206 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17207 ["Edit Formulas" org-edit-special (org-at-table-p)]
17208 "--"
17209 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17210 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17211 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17212 "--"
17213 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17214 "--"
17215 ["Sum Column/Rectangle" org-table-sum
17216 (or (org-at-table-p) (org-region-active-p))]
17217 ["Which Column?" org-table-current-column (org-at-table-p)])
17218 ["Debug Formulas"
17219 org-table-toggle-formula-debugger
17220 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17221 ["Show Col/Row Numbers"
17222 org-table-toggle-coordinate-overlays
17223 :style toggle
17224 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17225 "--"
17226 ["Create" org-table-create (and (not (org-at-table-p))
17227 org-enable-table-editor)]
17228 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17229 ["Import from File" org-table-import (not (org-at-table-p))]
17230 ["Export to File" org-table-export (org-at-table-p)]
17231 "--"
17232 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17234 (easy-menu-define org-org-menu org-mode-map "Org menu"
17235 '("Org"
17236 ("Show/Hide"
17237 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17238 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17239 ["Sparse Tree..." org-sparse-tree t]
17240 ["Reveal Context" org-reveal t]
17241 ["Show All" show-all t]
17242 "--"
17243 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17244 "--"
17245 ["New Heading" org-insert-heading t]
17246 ("Navigate Headings"
17247 ["Up" outline-up-heading t]
17248 ["Next" outline-next-visible-heading t]
17249 ["Previous" outline-previous-visible-heading t]
17250 ["Next Same Level" outline-forward-same-level t]
17251 ["Previous Same Level" outline-backward-same-level t]
17252 "--"
17253 ["Jump" org-goto t])
17254 ("Edit Structure"
17255 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17256 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17257 "--"
17258 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17259 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17260 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17261 "--"
17262 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17263 "--"
17264 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17265 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17266 ["Demote Heading" org-metaright (not (org-at-table-p))]
17267 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17268 "--"
17269 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17270 "--"
17271 ["Convert to odd levels" org-convert-to-odd-levels t]
17272 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17273 ("Editing"
17274 ["Emphasis..." org-emphasize t]
17275 ["Edit Source Example" org-edit-special t]
17276 "--"
17277 ["Footnote new/jump" org-footnote-action t]
17278 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17279 ("Archive"
17280 ["Archive (default method)" org-archive-subtree-default t]
17281 "--"
17282 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17283 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17284 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17286 "--"
17287 ("Hyperlinks"
17288 ["Store Link (Global)" org-store-link t]
17289 ["Find existing link to here" org-occur-link-in-agenda-files t]
17290 ["Insert Link" org-insert-link t]
17291 ["Follow Link" org-open-at-point t]
17292 "--"
17293 ["Next link" org-next-link t]
17294 ["Previous link" org-previous-link t]
17295 "--"
17296 ["Descriptive Links"
17297 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17298 :style radio
17299 :selected (member '(org-link) buffer-invisibility-spec)]
17300 ["Literal Links"
17301 (progn
17302 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17303 :style radio
17304 :selected (not (member '(org-link) buffer-invisibility-spec))])
17305 "--"
17306 ("TODO Lists"
17307 ["TODO/DONE/-" org-todo t]
17308 ("Select keyword"
17309 ["Next keyword" org-shiftright (org-on-heading-p)]
17310 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17311 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17312 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17313 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17314 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17315 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17316 "--"
17317 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17318 :selected org-enforce-todo-dependencies :style toggle :active t]
17319 "Settings for tree at point"
17320 ["Do Children sequentially" org-toggle-ordered-property :style radio
17321 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17322 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17323 ["Do Children parallel" org-toggle-ordered-property :style radio
17324 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17325 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17326 "--"
17327 ["Set Priority" org-priority t]
17328 ["Priority Up" org-shiftup t]
17329 ["Priority Down" org-shiftdown t]
17330 "--"
17331 ["Get news from all feeds" org-feed-update-all t]
17332 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17333 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17334 ("TAGS and Properties"
17335 ["Set Tags" org-set-tags-command t]
17336 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17337 "--"
17338 ["Set property" org-set-property t]
17339 ["Column view of properties" org-columns t]
17340 ["Insert Column View DBlock" org-insert-columns-dblock t])
17341 ("Dates and Scheduling"
17342 ["Timestamp" org-time-stamp t]
17343 ["Timestamp (inactive)" org-time-stamp-inactive t]
17344 ("Change Date"
17345 ["1 Day Later" org-shiftright t]
17346 ["1 Day Earlier" org-shiftleft t]
17347 ["1 ... Later" org-shiftup t]
17348 ["1 ... Earlier" org-shiftdown t])
17349 ["Compute Time Range" org-evaluate-time-range t]
17350 ["Schedule Item" org-schedule t]
17351 ["Deadline" org-deadline t]
17352 "--"
17353 ["Custom time format" org-toggle-time-stamp-overlays
17354 :style radio :selected org-display-custom-times]
17355 "--"
17356 ["Goto Calendar" org-goto-calendar t]
17357 ["Date from Calendar" org-date-from-calendar t]
17358 "--"
17359 ["Start/Restart Timer" org-timer-start t]
17360 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17361 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17362 ["Insert Timer String" org-timer t]
17363 ["Insert Timer Item" org-timer-item t])
17364 ("Logging work"
17365 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17366 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17367 ["Clock out" org-clock-out t]
17368 ["Clock cancel" org-clock-cancel t]
17369 "--"
17370 ["Mark as default task" org-clock-mark-default-task t]
17371 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17372 ["Goto running clock" org-clock-goto t]
17373 "--"
17374 ["Display times" org-clock-display t]
17375 ["Create clock table" org-clock-report t]
17376 "--"
17377 ["Record DONE time"
17378 (progn (setq org-log-done (not org-log-done))
17379 (message "Switching to %s will %s record a timestamp"
17380 (car org-done-keywords)
17381 (if org-log-done "automatically" "not")))
17382 :style toggle :selected org-log-done])
17383 "--"
17384 ["Agenda Command..." org-agenda t]
17385 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17386 ("File List for Agenda")
17387 ("Special views current file"
17388 ["TODO Tree" org-show-todo-tree t]
17389 ["Check Deadlines" org-check-deadlines t]
17390 ["Timeline" org-timeline t]
17391 ["Tags/Property tree" org-match-sparse-tree t])
17392 "--"
17393 ["Export/Publish..." org-export t]
17394 ("LaTeX"
17395 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17396 :selected org-cdlatex-mode]
17397 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17398 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17399 ["Modify math symbol" org-cdlatex-math-modify
17400 (org-inside-LaTeX-fragment-p)]
17401 ["Insert citation" org-reftex-citation t]
17402 "--"
17403 ["Export LaTeX fragments as images"
17404 (if (featurep 'org-exp)
17405 (setq org-export-with-LaTeX-fragments
17406 (not org-export-with-LaTeX-fragments))
17407 (require 'org-exp))
17408 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
17409 org-export-with-LaTeX-fragments)]
17410 "--"
17411 ["Template for BEAMER" org-insert-beamer-options-template t])
17412 "--"
17413 ("MobileOrg"
17414 ["Push Files and Views" org-mobile-push t]
17415 ["Get Captured and Flagged" org-mobile-pull t]
17416 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17417 "--"
17418 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17419 "--"
17420 ("Documentation"
17421 ["Show Version" org-version t]
17422 ["Info Documentation" org-info t])
17423 ("Customize"
17424 ["Browse Org Group" org-customize t]
17425 "--"
17426 ["Expand This Menu" org-create-customize-menu
17427 (fboundp 'customize-menu-create)])
17428 ["Send bug report" org-submit-bug-report t]
17429 "--"
17430 ("Refresh/Reload"
17431 ["Refresh setup current buffer" org-mode-restart t]
17432 ["Reload Org (after update)" org-reload t]
17433 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17436 (defun org-info (&optional node)
17437 "Read documentation for Org-mode in the info system.
17438 With optional NODE, go directly to that node."
17439 (interactive)
17440 (info (format "(org)%s" (or node ""))))
17442 ;;;###autoload
17443 (defun org-submit-bug-report ()
17444 "Submit a bug report on Org-mode via mail.
17446 Don't hesitate to report any problems or inaccurate documentation.
17448 If you don't have setup sending mail from (X)Emacs, please copy the
17449 output buffer into your mail program, as it gives us important
17450 information about your Org-mode version and configuration."
17451 (interactive)
17452 (require 'reporter)
17453 (org-load-modules-maybe)
17454 (org-require-autoloaded-modules)
17455 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17456 (reporter-submit-bug-report
17457 "emacs-orgmode@gnu.org"
17458 (org-version)
17459 (let (list)
17460 (save-window-excursion
17461 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17462 (delete-other-windows)
17463 (erase-buffer)
17464 (insert "You are about to submit a bug report to the Org-mode mailing list.
17466 We would like to add your full Org-mode and Outline configuration to the
17467 bug report. This greatly simplifies the work of the maintainer and
17468 other experts on the mailing list.
17470 HOWEVER, some variables you have customized may contain private
17471 information. The names of customers, colleagues, or friends, might
17472 appear in the form of file names, tags, todo states, or search strings.
17473 If you answer yes to the prompt, you might want to check and remove
17474 such private information before sending the email.")
17475 (add-text-properties (point-min) (point-max) '(face org-warning))
17476 (when (yes-or-no-p "Include your Org-mode configuration ")
17477 (mapatoms
17478 (lambda (v)
17479 (and (boundp v)
17480 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17481 (or (and (symbol-value v)
17482 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17483 (and
17484 (get v 'custom-type) (get v 'standard-value)
17485 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17486 (push v list)))))
17487 (kill-buffer (get-buffer "*Warn about privacy*"))
17488 list))
17489 nil nil
17490 "Remember to cover the basics, that is, what you expected to happen and
17491 what in fact did happen. You don't know how to make a good report? See
17493 http://orgmode.org/manual/Feedback.html#Feedback
17495 Your bug report will be posted to the Org-mode mailing list.
17496 ------------------------------------------------------------------------")
17497 (save-excursion
17498 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17499 (replace-match "\\1Bug: \\3 [\\2]")))))
17502 (defun org-install-agenda-files-menu ()
17503 (let ((bl (buffer-list)))
17504 (save-excursion
17505 (while bl
17506 (set-buffer (pop bl))
17507 (if (org-mode-p) (setq bl nil)))
17508 (when (org-mode-p)
17509 (easy-menu-change
17510 '("Org") "File List for Agenda"
17511 (append
17512 (list
17513 ["Edit File List" (org-edit-agenda-file-list) t]
17514 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17515 ["Remove Current File from List" org-remove-file t]
17516 ["Cycle through agenda files" org-cycle-agenda-files t]
17517 ["Occur in all agenda files" org-occur-in-agenda-files t]
17518 "--")
17519 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17521 ;;;; Documentation
17523 ;;;###autoload
17524 (defun org-require-autoloaded-modules ()
17525 (interactive)
17526 (mapc 'require
17527 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17528 org-docbook org-exp org-html org-icalendar
17529 org-id org-latex
17530 org-publish org-remember org-table
17531 org-timer org-xoxo)))
17533 ;;;###autoload
17534 (defun org-reload (&optional uncompiled)
17535 "Reload all org lisp files.
17536 With prefix arg UNCOMPILED, load the uncompiled versions."
17537 (interactive "P")
17538 (require 'find-func)
17539 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17540 (dir-org (file-name-directory (org-find-library-name "org")))
17541 (dir-org-contrib (ignore-errors
17542 (file-name-directory
17543 (org-find-library-name "org-contribdir"))))
17544 (files
17545 (append (directory-files dir-org t file-re)
17546 (and dir-org-contrib
17547 (directory-files dir-org-contrib t file-re))))
17548 (remove-re (concat (if (featurep 'xemacs)
17549 "org-colview" "org-colview-xemacs")
17550 "\\'")))
17551 (setq files (mapcar 'file-name-sans-extension files))
17552 (setq files (mapcar
17553 (lambda (x) (if (string-match remove-re x) nil x))
17554 files))
17555 (setq files (delq nil files))
17556 (mapc
17557 (lambda (f)
17558 (when (featurep (intern (file-name-nondirectory f)))
17559 (if (and (not uncompiled)
17560 (file-exists-p (concat f ".elc")))
17561 (load (concat f ".elc") nil nil t)
17562 (load (concat f ".el") nil nil t))))
17563 files))
17564 (org-version))
17566 ;;;###autoload
17567 (defun org-customize ()
17568 "Call the customize function with org as argument."
17569 (interactive)
17570 (org-load-modules-maybe)
17571 (org-require-autoloaded-modules)
17572 (customize-browse 'org))
17574 (defun org-create-customize-menu ()
17575 "Create a full customization menu for Org-mode, insert it into the menu."
17576 (interactive)
17577 (org-load-modules-maybe)
17578 (org-require-autoloaded-modules)
17579 (if (fboundp 'customize-menu-create)
17580 (progn
17581 (easy-menu-change
17582 '("Org") "Customize"
17583 `(["Browse Org group" org-customize t]
17584 "--"
17585 ,(customize-menu-create 'org)
17586 ["Set" Custom-set t]
17587 ["Save" Custom-save t]
17588 ["Reset to Current" Custom-reset-current t]
17589 ["Reset to Saved" Custom-reset-saved t]
17590 ["Reset to Standard Settings" Custom-reset-standard t]))
17591 (message "\"Org\"-menu now contains full customization menu"))
17592 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17594 ;;;; Miscellaneous stuff
17596 ;;; Generally useful functions
17598 (defun org-get-at-bol (property)
17599 "Get text property PROPERTY at beginning of line."
17600 (get-text-property (point-at-bol) property))
17602 (defun org-find-text-property-in-string (prop s)
17603 "Return the first non-nil value of property PROP in string S."
17604 (or (get-text-property 0 prop s)
17605 (get-text-property (or (next-single-property-change 0 prop s) 0)
17606 prop s)))
17608 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17609 "Display the given MESSAGE as a warning."
17610 (if (fboundp 'display-warning)
17611 (display-warning 'org message
17612 (if (featurep 'xemacs) 'warning :warning))
17613 (let ((buf (get-buffer-create "*Org warnings*")))
17614 (with-current-buffer buf
17615 (goto-char (point-max))
17616 (insert "Warning (Org): " message)
17617 (unless (bolp)
17618 (newline)))
17619 (display-buffer buf)
17620 (sit-for 0))))
17622 (defun org-in-commented-line ()
17623 "Is point in a line starting with `#'?"
17624 (equal (char-after (point-at-bol)) ?#))
17626 (defun org-in-indented-comment-line ()
17627 "Is point in a line starting with `#' after some white space?"
17628 (save-excursion
17629 (save-match-data
17630 (goto-char (point-at-bol))
17631 (looking-at "[ \t]*#"))))
17633 (defun org-in-verbatim-emphasis ()
17634 (save-match-data
17635 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17637 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17638 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17639 (if (and marker (marker-buffer marker)
17640 (buffer-live-p (marker-buffer marker)))
17641 (progn
17642 (switch-to-buffer (marker-buffer marker))
17643 (if (or (> marker (point-max)) (< marker (point-min)))
17644 (widen))
17645 (goto-char marker)
17646 (org-show-context 'org-goto))
17647 (if bookmark
17648 (bookmark-jump bookmark)
17649 (error "Cannot find location"))))
17651 (defun org-quote-csv-field (s)
17652 "Quote field for inclusion in CSV material."
17653 (if (string-match "[\",]" s)
17654 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17657 (defun org-plist-delete (plist property)
17658 "Delete PROPERTY from PLIST.
17659 This is in contrast to merely setting it to 0."
17660 (let (p)
17661 (while plist
17662 (if (not (eq property (car plist)))
17663 (setq p (plist-put p (car plist) (nth 1 plist))))
17664 (setq plist (cddr plist)))
17667 (defun org-force-self-insert (N)
17668 "Needed to enforce self-insert under remapping."
17669 (interactive "p")
17670 (self-insert-command N))
17672 (defun org-string-width (s)
17673 "Compute width of string, ignoring invisible characters.
17674 This ignores character with invisibility property `org-link', and also
17675 characters with property `org-cwidth', because these will become invisible
17676 upon the next fontification round."
17677 (let (b l)
17678 (when (or (eq t buffer-invisibility-spec)
17679 (assq 'org-link buffer-invisibility-spec))
17680 (while (setq b (text-property-any 0 (length s)
17681 'invisible 'org-link s))
17682 (setq s (concat (substring s 0 b)
17683 (substring s (or (next-single-property-change
17684 b 'invisible s) (length s)))))))
17685 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17686 (setq s (concat (substring s 0 b)
17687 (substring s (or (next-single-property-change
17688 b 'org-cwidth s) (length s))))))
17689 (setq l (string-width s) b -1)
17690 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17691 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17694 (defun org-get-indentation (&optional line)
17695 "Get the indentation of the current line, interpreting tabs.
17696 When LINE is given, assume it represents a line and compute its indentation."
17697 (if line
17698 (if (string-match "^ *" (org-remove-tabs line))
17699 (match-end 0))
17700 (save-excursion
17701 (beginning-of-line 1)
17702 (skip-chars-forward " \t")
17703 (current-column))))
17705 (defun org-remove-tabs (s &optional width)
17706 "Replace tabulators in S with spaces.
17707 Assumes that s is a single line, starting in column 0."
17708 (setq width (or width tab-width))
17709 (while (string-match "\t" s)
17710 (setq s (replace-match
17711 (make-string
17712 (- (* width (/ (+ (match-beginning 0) width) width))
17713 (match-beginning 0)) ?\ )
17714 t t s)))
17717 (defun org-fix-indentation (line ind)
17718 "Fix indentation in LINE.
17719 IND is a cons cell with target and minimum indentation.
17720 If the current indentation in LINE is smaller than the minimum,
17721 leave it alone. If it is larger than ind, set it to the target."
17722 (let* ((l (org-remove-tabs line))
17723 (i (org-get-indentation l))
17724 (i1 (car ind)) (i2 (cdr ind)))
17725 (if (>= i i2) (setq l (substring line i2)))
17726 (if (> i1 0)
17727 (concat (make-string i1 ?\ ) l)
17728 l)))
17730 (defun org-remove-indentation (code &optional n)
17731 "Remove the maximum common indentation from the lines in CODE.
17732 N may optionally be the number of spaces to remove."
17733 (with-temp-buffer
17734 (insert code)
17735 (org-do-remove-indentation n)
17736 (buffer-string)))
17738 (defun org-do-remove-indentation (&optional n)
17739 "Remove the maximum common indentation from the buffer."
17740 (untabify (point-min) (point-max))
17741 (let ((min 10000) re)
17742 (if n
17743 (setq min n)
17744 (goto-char (point-min))
17745 (while (re-search-forward "^ *[^ \n]" nil t)
17746 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17747 (unless (or (= min 0) (= min 10000))
17748 (setq re (format "^ \\{%d\\}" min))
17749 (goto-char (point-min))
17750 (while (re-search-forward re nil t)
17751 (replace-match "")
17752 (end-of-line 1))
17753 min)))
17755 (defun org-fill-template (template alist)
17756 "Find each %key of ALIST in TEMPLATE and replace it."
17757 (let ((case-fold-search nil)
17758 entry key value)
17759 (setq alist (sort (copy-sequence alist)
17760 (lambda (a b) (< (length (car a)) (length (car b))))))
17761 (while (setq entry (pop alist))
17762 (setq template
17763 (replace-regexp-in-string
17764 (concat "%" (regexp-quote (car entry)))
17765 (cdr entry) template t t)))
17766 template))
17768 (defun org-base-buffer (buffer)
17769 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17770 (if (not buffer)
17771 buffer
17772 (or (buffer-base-buffer buffer)
17773 buffer)))
17775 (defun org-trim (s)
17776 "Remove whitespace at beginning and end of string."
17777 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17778 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17781 (defun org-wrap (string &optional width lines)
17782 "Wrap string to either a number of lines, or a width in characters.
17783 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17784 that costs. If there is a word longer than WIDTH, the text is actually
17785 wrapped to the length of that word.
17786 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17787 many lines, whatever width that takes.
17788 The return value is a list of lines, without newlines at the end."
17789 (let* ((words (org-split-string string "[ \t\n]+"))
17790 (maxword (apply 'max (mapcar 'org-string-width words)))
17791 w ll)
17792 (cond (width
17793 (org-do-wrap words (max maxword width)))
17794 (lines
17795 (setq w maxword)
17796 (setq ll (org-do-wrap words maxword))
17797 (if (<= (length ll) lines)
17799 (setq ll words)
17800 (while (> (length ll) lines)
17801 (setq w (1+ w))
17802 (setq ll (org-do-wrap words w)))
17803 ll))
17804 (t (error "Cannot wrap this")))))
17806 (defun org-do-wrap (words width)
17807 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17808 (let (lines line)
17809 (while words
17810 (setq line (pop words))
17811 (while (and words (< (+ (length line) (length (car words))) width))
17812 (setq line (concat line " " (pop words))))
17813 (setq lines (push line lines)))
17814 (nreverse lines)))
17816 (defun org-split-string (string &optional separators)
17817 "Splits STRING into substrings at SEPARATORS.
17818 No empty strings are returned if there are matches at the beginning
17819 and end of string."
17820 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17821 (start 0)
17822 notfirst
17823 (list nil))
17824 (while (and (string-match rexp string
17825 (if (and notfirst
17826 (= start (match-beginning 0))
17827 (< start (length string)))
17828 (1+ start) start))
17829 (< (match-beginning 0) (length string)))
17830 (setq notfirst t)
17831 (or (eq (match-beginning 0) 0)
17832 (and (eq (match-beginning 0) (match-end 0))
17833 (eq (match-beginning 0) start))
17834 (setq list
17835 (cons (substring string start (match-beginning 0))
17836 list)))
17837 (setq start (match-end 0)))
17838 (or (eq start (length string))
17839 (setq list
17840 (cons (substring string start)
17841 list)))
17842 (nreverse list)))
17844 (defun org-quote-vert (s)
17845 "Replace \"|\" with \"\\vert\"."
17846 (while (string-match "|" s)
17847 (setq s (replace-match "\\vert" t t s)))
17850 (defun org-uuidgen-p (s)
17851 "Is S an ID created by UUIDGEN?"
17852 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17854 (defun org-context ()
17855 "Return a list of contexts of the current cursor position.
17856 If several contexts apply, all are returned.
17857 Each context entry is a list with a symbol naming the context, and
17858 two positions indicating start and end of the context. Possible
17859 contexts are:
17861 :headline anywhere in a headline
17862 :headline-stars on the leading stars in a headline
17863 :todo-keyword on a TODO keyword (including DONE) in a headline
17864 :tags on the TAGS in a headline
17865 :priority on the priority cookie in a headline
17866 :item on the first line of a plain list item
17867 :item-bullet on the bullet/number of a plain list item
17868 :checkbox on the checkbox in a plain list item
17869 :table in an org-mode table
17870 :table-special on a special filed in a table
17871 :table-table in a table.el table
17872 :link on a hyperlink
17873 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17874 :target on a <<target>>
17875 :radio-target on a <<<radio-target>>>
17876 :latex-fragment on a LaTeX fragment
17877 :latex-preview on a LaTeX fragment with overlayed preview image
17879 This function expects the position to be visible because it uses font-lock
17880 faces as a help to recognize the following contexts: :table-special, :link,
17881 and :keyword."
17882 (let* ((f (get-text-property (point) 'face))
17883 (faces (if (listp f) f (list f)))
17884 (p (point)) clist o)
17885 ;; First the large context
17886 (cond
17887 ((org-on-heading-p t)
17888 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17889 (when (progn
17890 (beginning-of-line 1)
17891 (looking-at org-todo-line-tags-regexp))
17892 (push (org-point-in-group p 1 :headline-stars) clist)
17893 (push (org-point-in-group p 2 :todo-keyword) clist)
17894 (push (org-point-in-group p 4 :tags) clist))
17895 (goto-char p)
17896 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17897 (if (looking-at "\\[#[A-Z0-9]\\]")
17898 (push (org-point-in-group p 0 :priority) clist)))
17900 ((org-at-item-p)
17901 (push (org-point-in-group p 2 :item-bullet) clist)
17902 (push (list :item (point-at-bol)
17903 (save-excursion (org-end-of-item) (point)))
17904 clist)
17905 (and (org-at-item-checkbox-p)
17906 (push (org-point-in-group p 0 :checkbox) clist)))
17908 ((org-at-table-p)
17909 (push (list :table (org-table-begin) (org-table-end)) clist)
17910 (if (memq 'org-formula faces)
17911 (push (list :table-special
17912 (previous-single-property-change p 'face)
17913 (next-single-property-change p 'face)) clist)))
17914 ((org-at-table-p 'any)
17915 (push (list :table-table) clist)))
17916 (goto-char p)
17918 ;; Now the small context
17919 (cond
17920 ((org-at-timestamp-p)
17921 (push (org-point-in-group p 0 :timestamp) clist))
17922 ((memq 'org-link faces)
17923 (push (list :link
17924 (previous-single-property-change p 'face)
17925 (next-single-property-change p 'face)) clist))
17926 ((memq 'org-special-keyword faces)
17927 (push (list :keyword
17928 (previous-single-property-change p 'face)
17929 (next-single-property-change p 'face)) clist))
17930 ((org-on-target-p)
17931 (push (org-point-in-group p 0 :target) clist)
17932 (goto-char (1- (match-beginning 0)))
17933 (if (looking-at org-radio-target-regexp)
17934 (push (org-point-in-group p 0 :radio-target) clist))
17935 (goto-char p))
17936 ((setq o (car (delq nil
17937 (mapcar
17938 (lambda (x)
17939 (if (memq x org-latex-fragment-image-overlays) x))
17940 (overlays-at (point))))))
17941 (push (list :latex-fragment
17942 (overlay-start o) (overlay-end o)) clist)
17943 (push (list :latex-preview
17944 (overlay-start o) (overlay-end o)) clist))
17945 ((org-inside-LaTeX-fragment-p)
17946 ;; FIXME: positions wrong.
17947 (push (list :latex-fragment (point) (point)) clist)))
17949 (setq clist (nreverse (delq nil clist)))
17950 clist))
17952 ;; FIXME: Compare with at-regexp-p Do we need both?
17953 (defun org-in-regexp (re &optional nlines visually)
17954 "Check if point is inside a match of regexp.
17955 Normally only the current line is checked, but you can include NLINES extra
17956 lines both before and after point into the search.
17957 If VISUALLY is set, require that the cursor is not after the match but
17958 really on, so that the block visually is on the match."
17959 (catch 'exit
17960 (let ((pos (point))
17961 (eol (point-at-eol (+ 1 (or nlines 0))))
17962 (inc (if visually 1 0)))
17963 (save-excursion
17964 (beginning-of-line (- 1 (or nlines 0)))
17965 (while (re-search-forward re eol t)
17966 (if (and (<= (match-beginning 0) pos)
17967 (>= (+ inc (match-end 0)) pos))
17968 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17970 (defun org-at-regexp-p (regexp)
17971 "Is point inside a match of REGEXP in the current line?"
17972 (catch 'exit
17973 (save-excursion
17974 (let ((pos (point)) (end (point-at-eol)))
17975 (beginning-of-line 1)
17976 (while (re-search-forward regexp end t)
17977 (if (and (<= (match-beginning 0) pos)
17978 (>= (match-end 0) pos))
17979 (throw 'exit t)))
17980 nil))))
17982 (defun org-in-regexps-block-p (start-re end-re)
17983 "Returns t if the current point is between matches of START-RE and END-RE.
17984 This will also return to if point is on one of the two matches."
17985 (interactive)
17986 (let ((p (point)))
17987 (save-excursion
17988 (and (or (org-at-regexp-p start-re)
17989 (re-search-backward start-re nil t))
17990 (re-search-forward end-re nil t)
17991 (>= (point) p)))))
17993 (defun org-occur-in-agenda-files (regexp &optional nlines)
17994 "Call `multi-occur' with buffers for all agenda files."
17995 (interactive "sOrg-files matching: \np")
17996 (let* ((files (org-agenda-files))
17997 (tnames (mapcar 'file-truename files))
17998 (extra org-agenda-text-search-extra-files)
18000 (when (eq (car extra) 'agenda-archives)
18001 (setq extra (cdr extra))
18002 (setq files (org-add-archive-files files)))
18003 (while (setq f (pop extra))
18004 (unless (member (file-truename f) tnames)
18005 (add-to-list 'files f 'append)
18006 (add-to-list 'tnames (file-truename f) 'append)))
18007 (multi-occur
18008 (mapcar (lambda (x)
18009 (with-current-buffer
18010 (or (get-file-buffer x) (find-file-noselect x))
18011 (widen)
18012 (current-buffer)))
18013 files)
18014 regexp)))
18016 (if (boundp 'occur-mode-find-occurrence-hook)
18017 ;; Emacs 23
18018 (add-hook 'occur-mode-find-occurrence-hook
18019 (lambda ()
18020 (when (org-mode-p)
18021 (org-reveal))))
18022 ;; Emacs 22
18023 (defadvice occur-mode-goto-occurrence
18024 (after org-occur-reveal activate)
18025 (and (org-mode-p) (org-reveal)))
18026 (defadvice occur-mode-goto-occurrence-other-window
18027 (after org-occur-reveal activate)
18028 (and (org-mode-p) (org-reveal)))
18029 (defadvice occur-mode-display-occurrence
18030 (after org-occur-reveal activate)
18031 (when (org-mode-p)
18032 (let ((pos (occur-mode-find-occurrence)))
18033 (with-current-buffer (marker-buffer pos)
18034 (save-excursion
18035 (goto-char pos)
18036 (org-reveal)))))))
18038 (defun org-occur-link-in-agenda-files ()
18039 "Create a link and search for it in the agendas.
18040 The link is not stored in `org-stored-links', it is just created
18041 for the search purpose."
18042 (interactive)
18043 (let ((link (condition-case nil
18044 (org-store-link nil)
18045 (error "Unable to create a link to here"))))
18046 (org-occur-in-agenda-files (regexp-quote link))))
18048 (defun org-uniquify (list)
18049 "Remove duplicate elements from LIST."
18050 (let (res)
18051 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18052 res))
18054 (defun org-delete-all (elts list)
18055 "Remove all elements in ELTS from LIST."
18056 (while elts
18057 (setq list (delete (pop elts) list)))
18058 list)
18060 (defun org-remove-if (predicate seq)
18061 "Remove everything from SEQ that fulfills PREDICATE."
18062 (let (res e)
18063 (while seq
18064 (setq e (pop seq))
18065 (if (not (funcall predicate e)) (push e res)))
18066 (nreverse res)))
18068 (defun org-remove-if-not (predicate seq)
18069 "Remove everything from SEQ that does not fulfill PREDICATE."
18070 (let (res e)
18071 (while seq
18072 (setq e (pop seq))
18073 (if (funcall predicate e) (push e res)))
18074 (nreverse res)))
18076 (defun org-back-over-empty-lines ()
18077 "Move backwards over whitespace, to the beginning of the first empty line.
18078 Returns the number of empty lines passed."
18079 (let ((pos (point)))
18080 (skip-chars-backward " \t\n\r")
18081 (beginning-of-line 2)
18082 (goto-char (min (point) pos))
18083 (count-lines (point) pos)))
18085 (defun org-skip-whitespace ()
18086 (skip-chars-forward " \t\n\r"))
18088 (defun org-point-in-group (point group &optional context)
18089 "Check if POINT is in match-group GROUP.
18090 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18091 match. If the match group does ot exist or point is not inside it,
18092 return nil."
18093 (and (match-beginning group)
18094 (>= point (match-beginning group))
18095 (<= point (match-end group))
18096 (if context
18097 (list context (match-beginning group) (match-end group))
18098 t)))
18100 (defun org-switch-to-buffer-other-window (&rest args)
18101 "Switch to buffer in a second window on the current frame.
18102 In particular, do not allow pop-up frames."
18103 (let (pop-up-frames special-display-buffer-names special-display-regexps
18104 special-display-function)
18105 (apply 'switch-to-buffer-other-window args)))
18107 (defun org-combine-plists (&rest plists)
18108 "Create a single property list from all plists in PLISTS.
18109 The process starts by copying the first list, and then setting properties
18110 from the other lists. Settings in the last list are the most significant
18111 ones and overrule settings in the other lists."
18112 (let ((rtn (copy-sequence (pop plists)))
18113 p v ls)
18114 (while plists
18115 (setq ls (pop plists))
18116 (while ls
18117 (setq p (pop ls) v (pop ls))
18118 (setq rtn (plist-put rtn p v))))
18119 rtn))
18121 (defun org-move-line-down (arg)
18122 "Move the current line down. With prefix argument, move it past ARG lines."
18123 (interactive "p")
18124 (let ((col (current-column))
18125 beg end pos)
18126 (beginning-of-line 1) (setq beg (point))
18127 (beginning-of-line 2) (setq end (point))
18128 (beginning-of-line (+ 1 arg))
18129 (setq pos (move-marker (make-marker) (point)))
18130 (insert (delete-and-extract-region beg end))
18131 (goto-char pos)
18132 (org-move-to-column col)))
18134 (defun org-move-line-up (arg)
18135 "Move the current line up. With prefix argument, move it past ARG lines."
18136 (interactive "p")
18137 (let ((col (current-column))
18138 beg end pos)
18139 (beginning-of-line 1) (setq beg (point))
18140 (beginning-of-line 2) (setq end (point))
18141 (beginning-of-line (- arg))
18142 (setq pos (move-marker (make-marker) (point)))
18143 (insert (delete-and-extract-region beg end))
18144 (goto-char pos)
18145 (org-move-to-column col)))
18147 (defun org-replace-escapes (string table)
18148 "Replace %-escapes in STRING with values in TABLE.
18149 TABLE is an association list with keys like \"%a\" and string values.
18150 The sequences in STRING may contain normal field width and padding information,
18151 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18152 so values can contain further %-escapes if they are define later in TABLE."
18153 (let ((tbl (copy-alist table))
18154 (case-fold-search nil)
18155 (pchg 0)
18156 e re rpl)
18157 (while (setq e (pop tbl))
18158 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18159 (when (and (cdr e) (string-match re (cdr e)))
18160 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18161 (safe "SREF"))
18162 (add-text-properties 0 3 (list 'sref sref) safe)
18163 (setcdr e (replace-match safe t t (cdr e)))))
18164 (while (string-match re string)
18165 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18166 (cdr e)))
18167 (setq string (replace-match rpl t t string))))
18168 (while (setq pchg (next-property-change pchg string))
18169 (let ((sref (get-text-property pchg 'sref string)))
18170 (when (and sref (string-match "SREF" string pchg))
18171 (setq string (replace-match sref t t string)))))
18172 string))
18174 (defun org-sublist (list start end)
18175 "Return a section of LIST, from START to END.
18176 Counting starts at 1."
18177 (let (rtn (c start))
18178 (setq list (nthcdr (1- start) list))
18179 (while (and list (<= c end))
18180 (push (pop list) rtn)
18181 (setq c (1+ c)))
18182 (nreverse rtn)))
18184 (defun org-find-base-buffer-visiting (file)
18185 "Like `find-buffer-visiting' but always return the base buffer and
18186 not an indirect buffer."
18187 (let ((buf (or (get-file-buffer file)
18188 (find-buffer-visiting file))))
18189 (if buf
18190 (or (buffer-base-buffer buf) buf)
18191 nil)))
18193 (defun org-image-file-name-regexp (&optional extensions)
18194 "Return regexp matching the file names of images.
18195 If EXTENSIONS is given, only match these."
18196 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18197 (image-file-name-regexp)
18198 (let ((image-file-name-extensions
18199 (or extensions
18200 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18201 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18202 (concat "\\."
18203 (regexp-opt (nconc (mapcar 'upcase
18204 image-file-name-extensions)
18205 image-file-name-extensions)
18207 "\\'"))))
18209 (defun org-file-image-p (file &optional extensions)
18210 "Return non-nil if FILE is an image."
18211 (save-match-data
18212 (string-match (org-image-file-name-regexp extensions) file)))
18214 (defun org-get-cursor-date ()
18215 "Return the date at cursor in as a time.
18216 This works in the calendar and in the agenda, anywhere else it just
18217 returns the current time."
18218 (let (date day defd)
18219 (cond
18220 ((eq major-mode 'calendar-mode)
18221 (setq date (calendar-cursor-to-date)
18222 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18223 ((eq major-mode 'org-agenda-mode)
18224 (setq day (get-text-property (point) 'day))
18225 (if day
18226 (setq date (calendar-gregorian-from-absolute day)
18227 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18228 (nth 2 date))))))
18229 (or defd (current-time))))
18231 (defvar org-agenda-action-marker (make-marker)
18232 "Marker pointing to the entry for the next agenda action.")
18234 (defun org-mark-entry-for-agenda-action ()
18235 "Mark the current entry as target of an agenda action.
18236 Agenda actions are actions executed from the agenda with the key `k',
18237 which make use of the date at the cursor."
18238 (interactive)
18239 (move-marker org-agenda-action-marker
18240 (save-excursion (org-back-to-heading t) (point))
18241 (current-buffer))
18242 (message
18243 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18245 ;;; Paragraph filling stuff.
18246 ;; We want this to be just right, so use the full arsenal.
18248 (defun org-indent-line-function ()
18249 "Indent line like previous, but further if previous was headline or item."
18250 (interactive)
18251 (let* ((pos (point))
18252 (itemp (org-at-item-p))
18253 (case-fold-search t)
18254 (org-drawer-regexp (or org-drawer-regexp "\000"))
18255 column bpos bcol tpos tcol bullet btype bullet-type)
18256 ;; Find the previous relevant line
18257 (beginning-of-line 1)
18258 (cond
18259 ((looking-at "#") (setq column 0))
18260 ((looking-at "\\*+ ") (setq column 0))
18261 ((and (looking-at "[ \t]*:END:")
18262 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18263 (save-excursion
18264 (goto-char (1- (match-beginning 1)))
18265 (setq column (current-column))))
18266 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18267 (save-excursion
18268 (re-search-backward
18269 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18270 (setq column (org-get-indentation (match-string 0))))
18272 (beginning-of-line 0)
18273 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18274 (not (looking-at "[ \t]*:END:"))
18275 (not (looking-at org-drawer-regexp)))
18276 (beginning-of-line 0))
18277 (cond
18278 ((looking-at "\\*+[ \t]+")
18279 (if (not org-adapt-indentation)
18280 (setq column 0)
18281 (goto-char (match-end 0))
18282 (setq column (current-column))))
18283 ((looking-at org-drawer-regexp)
18284 (goto-char (1- (match-beginning 1)))
18285 (setq column (current-column)))
18286 ((looking-at "\\([ \t]*\\):END:")
18287 (goto-char (match-end 1))
18288 (setq column (current-column)))
18289 ((org-in-item-p)
18290 (org-beginning-of-item)
18291 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18292 (setq bpos (match-beginning 1) tpos (match-end 0)
18293 bcol (progn (goto-char bpos) (current-column))
18294 tcol (progn (goto-char tpos) (current-column))
18295 bullet (match-string 1)
18296 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18297 (if (> tcol (+ bcol org-description-max-indent))
18298 (setq tcol (+ bcol 5)))
18299 (if (not itemp)
18300 (setq column tcol)
18301 (goto-char pos)
18302 (beginning-of-line 1)
18303 (if (looking-at "\\S-")
18304 (progn
18305 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18306 (setq bullet (match-string 1)
18307 btype (if (string-match "[0-9]" bullet) "n" bullet))
18308 (setq column (if (equal btype bullet-type) bcol tcol)))
18309 (setq column (org-get-indentation)))))
18310 (t (setq column (org-get-indentation))))))
18311 (goto-char pos)
18312 (if (<= (current-column) (current-indentation))
18313 (org-indent-line-to column)
18314 (save-excursion (org-indent-line-to column)))
18315 (setq column (current-column))
18316 (beginning-of-line 1)
18317 (if (looking-at
18318 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18319 (replace-match (concat (match-string 1)
18320 (format org-property-format
18321 (match-string 2) (match-string 3)))
18322 t t))
18323 (org-move-to-column column)))
18325 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18326 "Variable to store copy of `adaptive-fill-regexp'.
18327 Since `adaptive-fill-regexp' is set to never match, we need to
18328 store a backup of its value before entering `org-mode' so that
18329 the functionality can be provided as a fall-back.")
18331 (defun org-set-autofill-regexps ()
18332 (interactive)
18333 ;; In the paragraph separator we include headlines, because filling
18334 ;; text in a line directly attached to a headline would otherwise
18335 ;; fill the headline as well.
18336 (org-set-local 'comment-start-skip "^#+[ \t]*")
18337 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18338 ;; The paragraph starter includes hand-formatted lists.
18339 (org-set-local
18340 'paragraph-start
18341 (concat
18342 "\f" "\\|"
18343 "[ ]*$" "\\|"
18344 "\\*+ " "\\|"
18345 "[ \t]*#" "\\|"
18346 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18347 "[ \t]*[:|]" "\\|"
18348 "\\$\\$" "\\|"
18349 "\\\\\\(begin\\|end\\|[][]\\)"))
18350 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18351 ;; But only if the user has not turned off tables or fixed-width regions
18352 (org-set-local
18353 'auto-fill-inhibit-regexp
18354 (concat "\\*+ \\|#\\+"
18355 "\\|[ \t]*" org-keyword-time-regexp
18356 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18357 (concat
18358 "\\|[ \t]*["
18359 (if org-enable-table-editor "|" "")
18360 (if org-enable-fixed-width-editor ":" "")
18361 "]"))))
18362 ;; We use our own fill-paragraph function, to make sure that tables
18363 ;; and fixed-width regions are not wrapped. That function will pass
18364 ;; through to `fill-paragraph' when appropriate.
18365 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18366 ;; Adaptive filling: To get full control, first make sure that
18367 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18368 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18369 (org-set-local 'org-adaptive-fill-regexp-backup
18370 adaptive-fill-regexp))
18371 (org-set-local 'adaptive-fill-regexp "\000")
18372 (org-set-local 'adaptive-fill-function
18373 'org-adaptive-fill-function)
18374 (org-set-local
18375 'align-mode-rules-list
18376 '((org-in-buffer-settings
18377 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18378 (modes . '(org-mode))))))
18380 (defun org-fill-paragraph (&optional justify)
18381 "Re-align a table, pass through to fill-paragraph if no table."
18382 (let ((table-p (org-at-table-p))
18383 (table.el-p (org-at-table.el-p)))
18384 (cond ((and (equal (char-after (point-at-bol)) ?*)
18385 (save-excursion (goto-char (point-at-bol))
18386 (looking-at outline-regexp)))
18387 t) ; skip headlines
18388 (table.el-p t) ; skip table.el tables
18389 (table-p (org-table-align) t) ; align org-mode tables
18390 (t nil)))) ; call paragraph-fill
18392 ;; For reference, this is the default value of adaptive-fill-regexp
18393 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18395 (defun org-adaptive-fill-function ()
18396 "Return a fill prefix for org-mode files.
18397 In particular, this makes sure hanging paragraphs for hand-formatted lists
18398 work correctly."
18399 (cond
18400 ;; Comment line
18401 ((looking-at "#[ \t]+")
18402 (match-string-no-properties 0))
18403 ;; Description list
18404 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18405 (save-excursion
18406 (if (> (match-end 1) (+ (match-beginning 1)
18407 org-description-max-indent))
18408 (goto-char (+ (match-beginning 1) 5))
18409 (goto-char (match-end 0)))
18410 (make-string (current-column) ?\ )))
18411 ;; Ordered or unordered list
18412 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18413 (save-excursion
18414 (goto-char (match-end 0))
18415 (make-string (current-column) ?\ )))
18416 ;; Other text
18417 ((looking-at org-adaptive-fill-regexp-backup)
18418 (match-string-no-properties 0))))
18420 ;;; Other stuff.
18422 (defun org-toggle-fixed-width-section (arg)
18423 "Toggle the fixed-width export.
18424 If there is no active region, the QUOTE keyword at the current headline is
18425 inserted or removed. When present, it causes the text between this headline
18426 and the next to be exported as fixed-width text, and unmodified.
18427 If there is an active region, this command adds or removes a colon as the
18428 first character of this line. If the first character of a line is a colon,
18429 this line is also exported in fixed-width font."
18430 (interactive "P")
18431 (let* ((cc 0)
18432 (regionp (org-region-active-p))
18433 (beg (if regionp (region-beginning) (point)))
18434 (end (if regionp (region-end)))
18435 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18436 (case-fold-search nil)
18437 (re "[ \t]*\\(: \\)")
18438 off)
18439 (if regionp
18440 (save-excursion
18441 (goto-char beg)
18442 (setq cc (current-column))
18443 (beginning-of-line 1)
18444 (setq off (looking-at re))
18445 (while (> nlines 0)
18446 (setq nlines (1- nlines))
18447 (beginning-of-line 1)
18448 (cond
18449 (arg
18450 (org-move-to-column cc t)
18451 (insert ": \n")
18452 (forward-line -1))
18453 ((and off (looking-at re))
18454 (replace-match "" t t nil 1))
18455 ((not off) (org-move-to-column cc t) (insert ": ")))
18456 (forward-line 1)))
18457 (save-excursion
18458 (org-back-to-heading)
18459 (if (looking-at (concat outline-regexp
18460 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18461 (replace-match "" t t nil 1)
18462 (if (looking-at outline-regexp)
18463 (progn
18464 (goto-char (match-end 0))
18465 (insert org-quote-string " "))))))))
18467 (defun org-reftex-citation ()
18468 "Use reftex-citation to insert a citation into the buffer.
18469 This looks for a line like
18471 #+BIBLIOGRAPHY: foo plain option:-d
18473 and derives from it that foo.bib is the bibliography file relevant
18474 for this document. It then installs the necessary environment for RefTeX
18475 to work in this buffer and calls `reftex-citation' to insert a citation
18476 into the buffer.
18478 Export of such citations to both LaTeX and HTML is handled by the contributed
18479 package org-exp-bibtex by Taru Karttunen."
18480 (interactive)
18481 (let ((reftex-docstruct-symbol 'rds)
18482 (reftex-cite-format "\\cite{%l}")
18483 rds bib)
18484 (save-excursion
18485 (save-restriction
18486 (widen)
18487 (let ((case-fold-search t)
18488 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18489 (if (not (save-excursion
18490 (or (re-search-forward re nil t)
18491 (re-search-backward re nil t))))
18492 (error "No bibliography defined in file")
18493 (setq bib (concat (match-string 1) ".bib")
18494 rds (list (list 'bib bib)))))))
18495 (call-interactively 'reftex-citation)))
18497 ;;;; Functions extending outline functionality
18499 (defun org-beginning-of-line (&optional arg)
18500 "Go to the beginning of the current line. If that is invisible, continue
18501 to a visible line beginning. This makes the function of C-a more intuitive.
18502 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18503 first attempt, and only move to after the tags when the cursor is already
18504 beyond the end of the headline."
18505 (interactive "P")
18506 (let ((pos (point))
18507 (special (if (consp org-special-ctrl-a/e)
18508 (car org-special-ctrl-a/e)
18509 org-special-ctrl-a/e))
18510 refpos)
18511 (if (org-bound-and-true-p line-move-visual)
18512 (beginning-of-visual-line 1)
18513 (beginning-of-line 1))
18514 (if (and arg (fboundp 'move-beginning-of-line))
18515 (call-interactively 'move-beginning-of-line)
18516 (if (bobp)
18518 (backward-char 1)
18519 (if (org-invisible-p)
18520 (while (and (not (bobp)) (org-invisible-p))
18521 (backward-char 1)
18522 (beginning-of-line 1))
18523 (forward-char 1))))
18524 (when special
18525 (cond
18526 ((and (looking-at org-complex-heading-regexp)
18527 (= (char-after (match-end 1)) ?\ ))
18528 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18529 (point-at-eol)))
18530 (goto-char
18531 (if (eq special t)
18532 (cond ((> pos refpos) refpos)
18533 ((= pos (point)) refpos)
18534 (t (point)))
18535 (cond ((> pos (point)) (point))
18536 ((not (eq last-command this-command)) (point))
18537 (t refpos)))))
18538 ((org-at-item-p)
18539 (goto-char
18540 (if (eq special t)
18541 (cond ((> pos (match-end 4)) (match-end 4))
18542 ((= pos (point)) (match-end 4))
18543 (t (point)))
18544 (cond ((> pos (point)) (point))
18545 ((not (eq last-command this-command)) (point))
18546 (t (match-end 4))))))))
18547 (org-no-warnings
18548 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18550 (defun org-end-of-line (&optional arg)
18551 "Go to the end of the line.
18552 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18553 first attempt, and only move to after the tags when the cursor is already
18554 beyond the end of the headline."
18555 (interactive "P")
18556 (let ((special (if (consp org-special-ctrl-a/e)
18557 (cdr org-special-ctrl-a/e)
18558 org-special-ctrl-a/e)))
18559 (if (or (not special)
18560 (not (org-on-heading-p))
18561 arg)
18562 (call-interactively
18563 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18564 ((fboundp 'move-end-of-line) 'move-end-of-line)
18565 (t 'end-of-line)))
18566 (let ((pos (point)))
18567 (beginning-of-line 1)
18568 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18569 (if (eq special t)
18570 (if (or (< pos (match-beginning 1))
18571 (= pos (match-end 0)))
18572 (goto-char (match-beginning 1))
18573 (goto-char (match-end 0)))
18574 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18575 (goto-char (match-end 0))
18576 (goto-char (match-beginning 1))))
18577 (call-interactively (if (fboundp 'move-end-of-line)
18578 'move-end-of-line
18579 'end-of-line)))))
18580 (org-no-warnings
18581 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18583 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18584 (define-key org-mode-map "\C-e" 'org-end-of-line)
18585 (define-key org-mode-map [home] 'org-beginning-of-line)
18586 (define-key org-mode-map [end] 'org-end-of-line)
18588 (defun org-backward-sentence (&optional arg)
18589 "Go to beginning of sentence, or beginning of table field.
18590 This will call `backward-sentence' or `org-table-beginning-of-field',
18591 depending on context."
18592 (interactive "P")
18593 (cond
18594 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18595 (t (call-interactively 'backward-sentence))))
18597 (defun org-forward-sentence (&optional arg)
18598 "Go to end of sentence, or end of table field.
18599 This will call `forward-sentence' or `org-table-end-of-field',
18600 depending on context."
18601 (interactive "P")
18602 (cond
18603 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18604 (t (call-interactively 'forward-sentence))))
18606 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18607 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18609 (defun org-kill-line (&optional arg)
18610 "Kill line, to tags or end of line."
18611 (interactive "P")
18612 (cond
18613 ((or (not org-special-ctrl-k)
18614 (bolp)
18615 (not (org-on-heading-p)))
18616 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
18617 org-ctrl-k-protect-subtree)
18618 (if (or (eq org-ctrl-k-protect-subtree 'error)
18619 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
18620 (error "C-k aborted - would kill hidden subtree")))
18621 (call-interactively 'kill-line))
18622 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18623 (kill-region (point) (match-beginning 1))
18624 (org-set-tags nil t))
18625 (t (kill-region (point) (point-at-eol)))))
18627 (define-key org-mode-map "\C-k" 'org-kill-line)
18629 (defun org-yank (&optional arg)
18630 "Yank. If the kill is a subtree, treat it specially.
18631 This command will look at the current kill and check if is a single
18632 subtree, or a series of subtrees[1]. If it passes the test, and if the
18633 cursor is at the beginning of a line or after the stars of a currently
18634 empty headline, then the yank is handled specially. How exactly depends
18635 on the value of the following variables, both set by default.
18637 org-yank-folded-subtrees
18638 When set, the subtree(s) will be folded after insertion, but only
18639 if doing so would now swallow text after the yanked text.
18641 org-yank-adjusted-subtrees
18642 When set, the subtree will be promoted or demoted in order to
18643 fit into the local outline tree structure, which means that the level
18644 will be adjusted so that it becomes the smaller one of the two
18645 *visible* surrounding headings.
18647 Any prefix to this command will cause `yank' to be called directly with
18648 no special treatment. In particular, a simple `C-u' prefix will just
18649 plainly yank the text as it is.
18651 \[1] The test checks if the first non-white line is a heading
18652 and if there are no other headings with fewer stars."
18653 (interactive "P")
18654 (org-yank-generic 'yank arg))
18656 (defun org-yank-generic (command arg)
18657 "Perform some yank-like command.
18659 This function implements the behavior described in the `org-yank'
18660 documentation. However, it has been generalized to work for any
18661 interactive command with similar behavior."
18663 ;; pretend to be command COMMAND
18664 (setq this-command command)
18666 (if arg
18667 (call-interactively command)
18669 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18670 (and (org-kill-is-subtree-p)
18671 (or (bolp)
18672 (and (looking-at "[ \t]*$")
18673 (string-match
18674 "\\`\\*+\\'"
18675 (buffer-substring (point-at-bol) (point)))))))
18676 swallowp)
18677 (cond
18678 ((and subtreep org-yank-folded-subtrees)
18679 (let ((beg (point))
18680 end)
18681 (if (and subtreep org-yank-adjusted-subtrees)
18682 (org-paste-subtree nil nil 'for-yank)
18683 (call-interactively command))
18685 (setq end (point))
18686 (goto-char beg)
18687 (when (and (bolp) subtreep
18688 (not (setq swallowp
18689 (org-yank-folding-would-swallow-text beg end))))
18690 (or (looking-at outline-regexp)
18691 (re-search-forward (concat "^" outline-regexp) end t))
18692 (while (and (< (point) end) (looking-at outline-regexp))
18693 (hide-subtree)
18694 (org-cycle-show-empty-lines 'folded)
18695 (condition-case nil
18696 (outline-forward-same-level 1)
18697 (error (goto-char end)))))
18698 (when swallowp
18699 (message
18700 "Inserted text not folded because that would swallow text"))
18702 (goto-char end)
18703 (skip-chars-forward " \t\n\r")
18704 (beginning-of-line 1)
18705 (push-mark beg 'nomsg)))
18706 ((and subtreep org-yank-adjusted-subtrees)
18707 (let ((beg (point-at-bol)))
18708 (org-paste-subtree nil nil 'for-yank)
18709 (push-mark beg 'nomsg)))
18711 (call-interactively command))))))
18713 (defun org-yank-folding-would-swallow-text (beg end)
18714 "Would hide-subtree at BEG swallow any text after END?"
18715 (let (level)
18716 (save-excursion
18717 (goto-char beg)
18718 (when (or (looking-at outline-regexp)
18719 (re-search-forward (concat "^" outline-regexp) end t))
18720 (setq level (org-outline-level)))
18721 (goto-char end)
18722 (skip-chars-forward " \t\r\n\v\f")
18723 (if (or (eobp)
18724 (and (bolp) (looking-at org-outline-regexp)
18725 (<= (org-outline-level) level)))
18726 nil ; Nothing would be swallowed
18727 t)))) ; something would swallow
18729 (define-key org-mode-map "\C-y" 'org-yank)
18731 (defun org-invisible-p ()
18732 "Check if point is at a character currently not visible."
18733 ;; Early versions of noutline don't have `outline-invisible-p'.
18734 (if (fboundp 'outline-invisible-p)
18735 (outline-invisible-p)
18736 (get-char-property (point) 'invisible)))
18738 (defun org-invisible-p2 ()
18739 "Check if point is at a character currently not visible."
18740 (save-excursion
18741 (if (and (eolp) (not (bobp))) (backward-char 1))
18742 ;; Early versions of noutline don't have `outline-invisible-p'.
18743 (if (fboundp 'outline-invisible-p)
18744 (outline-invisible-p)
18745 (get-char-property (point) 'invisible))))
18747 (defun org-back-to-heading (&optional invisible-ok)
18748 "Call `outline-back-to-heading', but provide a better error message."
18749 (condition-case nil
18750 (outline-back-to-heading invisible-ok)
18751 (error (error "Before first headline at position %d in buffer %s"
18752 (point) (current-buffer)))))
18754 (defun org-beginning-of-defun ()
18755 "Go to the beginning of the subtree, i.e. back to the heading."
18756 (org-back-to-heading))
18757 (defun org-end-of-defun ()
18758 "Go to the end of the subtree."
18759 (org-end-of-subtree nil t))
18761 (defun org-before-first-heading-p ()
18762 "Before first heading?"
18763 (save-excursion
18764 (null (re-search-backward "^\\*+ " nil t))))
18766 (defun org-on-heading-p (&optional ignored)
18767 (outline-on-heading-p t))
18768 (defun org-at-heading-p (&optional ignored)
18769 (outline-on-heading-p t))
18771 (defun org-point-at-end-of-empty-headline ()
18772 "If point is at the end of an empty headline, return t, else nil.
18773 If the heading only contains a TODO keyword, it is still still considered
18774 empty."
18775 (and (looking-at "[ \t]*$")
18776 (save-excursion
18777 (beginning-of-line 1)
18778 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18779 "\\)?[ \t]*$")))))
18780 (defun org-at-heading-or-item-p ()
18781 (or (org-on-heading-p) (org-at-item-p)))
18783 (defun org-on-target-p ()
18784 (or (org-in-regexp org-radio-target-regexp)
18785 (org-in-regexp org-target-regexp)))
18787 (defun org-up-heading-all (arg)
18788 "Move to the heading line of which the present line is a subheading.
18789 This function considers both visible and invisible heading lines.
18790 With argument, move up ARG levels."
18791 (if (fboundp 'outline-up-heading-all)
18792 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18793 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18795 (defun org-up-heading-safe ()
18796 "Move to the heading line of which the present line is a subheading.
18797 This version will not throw an error. It will return the level of the
18798 headline found, or nil if no higher level is found.
18800 Also, this function will be a lot faster than `outline-up-heading',
18801 because it relies on stars being the outline starters. This can really
18802 make a significant difference in outlines with very many siblings."
18803 (let (start-level re)
18804 (org-back-to-heading t)
18805 (setq start-level (funcall outline-level))
18806 (if (equal start-level 1)
18808 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18809 (if (re-search-backward re nil t)
18810 (funcall outline-level)))))
18812 (defun org-first-sibling-p ()
18813 "Is this heading the first child of its parents?"
18814 (interactive)
18815 (let ((re (concat "^" outline-regexp))
18816 level l)
18817 (unless (org-at-heading-p t)
18818 (error "Not at a heading"))
18819 (setq level (funcall outline-level))
18820 (save-excursion
18821 (if (not (re-search-backward re nil t))
18823 (setq l (funcall outline-level))
18824 (< l level)))))
18826 (defun org-goto-sibling (&optional previous)
18827 "Goto the next sibling, even if it is invisible.
18828 When PREVIOUS is set, go to the previous sibling instead. Returns t
18829 when a sibling was found. When none is found, return nil and don't
18830 move point."
18831 (let ((fun (if previous 're-search-backward 're-search-forward))
18832 (pos (point))
18833 (re (concat "^" outline-regexp))
18834 level l)
18835 (when (condition-case nil (org-back-to-heading t) (error nil))
18836 (setq level (funcall outline-level))
18837 (catch 'exit
18838 (or previous (forward-char 1))
18839 (while (funcall fun re nil t)
18840 (setq l (funcall outline-level))
18841 (when (< l level) (goto-char pos) (throw 'exit nil))
18842 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18843 (goto-char pos)
18844 nil))))
18846 (defun org-show-siblings ()
18847 "Show all siblings of the current headline."
18848 (save-excursion
18849 (while (org-goto-sibling) (org-flag-heading nil)))
18850 (save-excursion
18851 (while (org-goto-sibling 'previous)
18852 (org-flag-heading nil))))
18854 (defun org-show-hidden-entry ()
18855 "Show an entry where even the heading is hidden."
18856 (save-excursion
18857 (org-show-entry)))
18859 (defun org-flag-heading (flag &optional entry)
18860 "Flag the current heading. FLAG non-nil means make invisible.
18861 When ENTRY is non-nil, show the entire entry."
18862 (save-excursion
18863 (org-back-to-heading t)
18864 ;; Check if we should show the entire entry
18865 (if entry
18866 (progn
18867 (org-show-entry)
18868 (save-excursion
18869 (and (outline-next-heading)
18870 (org-flag-heading nil))))
18871 (outline-flag-region (max (point-min) (1- (point)))
18872 (save-excursion (outline-end-of-heading) (point))
18873 flag))))
18875 (defun org-get-next-sibling ()
18876 "Move to next heading of the same level, and return point.
18877 If there is no such heading, return nil.
18878 This is like outline-next-sibling, but invisible headings are ok."
18879 (let ((level (funcall outline-level)))
18880 (outline-next-heading)
18881 (while (and (not (eobp)) (> (funcall outline-level) level))
18882 (outline-next-heading))
18883 (if (or (eobp) (< (funcall outline-level) level))
18885 (point))))
18887 (defun org-get-last-sibling ()
18888 "Move to previous heading of the same level, and return point.
18889 If there is no such heading, return nil."
18890 (let ((opoint (point))
18891 (level (funcall outline-level)))
18892 (outline-previous-heading)
18893 (when (and (/= (point) opoint) (outline-on-heading-p t))
18894 (while (and (> (funcall outline-level) level)
18895 (not (bobp)))
18896 (outline-previous-heading))
18897 (if (< (funcall outline-level) level)
18899 (point)))))
18901 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18902 ;; This contains an exact copy of the original function, but it uses
18903 ;; `org-back-to-heading', to make it work also in invisible
18904 ;; trees. And is uses an invisible-OK argument.
18905 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18906 ;; Furthermore, when used inside Org, finding the end of a large subtree
18907 ;; with many children and grandchildren etc, this can be much faster
18908 ;; than the outline version.
18909 (org-back-to-heading invisible-OK)
18910 (let ((first t)
18911 (level (funcall outline-level)))
18912 (if (and (org-mode-p) (< level 1000))
18913 ;; A true heading (not a plain list item), in Org-mode
18914 ;; This means we can easily find the end by looking
18915 ;; only for the right number of stars. Using a regexp to do
18916 ;; this is so much faster than using a Lisp loop.
18917 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18918 (forward-char 1)
18919 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18920 ;; something else, do it the slow way
18921 (while (and (not (eobp))
18922 (or first (> (funcall outline-level) level)))
18923 (setq first nil)
18924 (outline-next-heading)))
18925 (unless to-heading
18926 (if (memq (preceding-char) '(?\n ?\^M))
18927 (progn
18928 ;; Go to end of line before heading
18929 (forward-char -1)
18930 (if (memq (preceding-char) '(?\n ?\^M))
18931 ;; leave blank line before heading
18932 (forward-char -1))))))
18933 (point))
18935 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18936 "Use Org version in org-mode, for dramatic speed-up."
18937 (if (eq major-mode 'org-mode)
18938 (progn
18939 (org-end-of-subtree nil t)
18940 (unless (eobp) (backward-char 1)))
18941 ad-do-it))
18943 (defun org-forward-same-level (arg &optional invisible-ok)
18944 "Move forward to the arg'th subheading at same level as this one.
18945 Stop at the first and last subheadings of a superior heading."
18946 (interactive "p")
18947 (org-back-to-heading invisible-ok)
18948 (org-on-heading-p)
18949 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18950 (re (format "^\\*\\{1,%d\\} " level))
18952 (forward-char 1)
18953 (while (> arg 0)
18954 (while (and (re-search-forward re nil 'move)
18955 (setq l (- (match-end 0) (match-beginning 0) 1))
18956 (= l level)
18957 (not invisible-ok)
18958 (progn (backward-char 1) (org-invisible-p)))
18959 (if (< l level) (setq arg 1)))
18960 (setq arg (1- arg)))
18961 (beginning-of-line 1)))
18963 (defun org-backward-same-level (arg &optional invisible-ok)
18964 "Move backward to the arg'th subheading at same level as this one.
18965 Stop at the first and last subheadings of a superior heading."
18966 (interactive "p")
18967 (org-back-to-heading)
18968 (org-on-heading-p)
18969 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18970 (re (format "^\\*\\{1,%d\\} " level))
18972 (while (> arg 0)
18973 (while (and (re-search-backward re nil 'move)
18974 (setq l (- (match-end 0) (match-beginning 0) 1))
18975 (= l level)
18976 (not invisible-ok)
18977 (org-invisible-p))
18978 (if (< l level) (setq arg 1)))
18979 (setq arg (1- arg)))))
18981 (defun org-show-subtree ()
18982 "Show everything after this heading at deeper levels."
18983 (outline-flag-region
18984 (point)
18985 (save-excursion
18986 (org-end-of-subtree t t))
18987 nil))
18989 (defun org-show-entry ()
18990 "Show the body directly following this heading.
18991 Show the heading too, if it is currently invisible."
18992 (interactive)
18993 (save-excursion
18994 (condition-case nil
18995 (progn
18996 (org-back-to-heading t)
18997 (outline-flag-region
18998 (max (point-min) (1- (point)))
18999 (save-excursion
19000 (if (re-search-forward
19001 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19002 (match-beginning 1)
19003 (point-max)))
19004 nil)
19005 (org-cycle-hide-drawers 'children))
19006 (error nil))))
19008 (defun org-make-options-regexp (kwds &optional extra)
19009 "Make a regular expression for keyword lines."
19010 (concat
19012 "#?[ \t]*\\+\\("
19013 (mapconcat 'regexp-quote kwds "\\|")
19014 (if extra (concat "\\|" extra))
19015 "\\):[ \t]*"
19016 "\\(.*\\)"))
19018 ;; Make isearch reveal the necessary context
19019 (defun org-isearch-end ()
19020 "Reveal context after isearch exits."
19021 (when isearch-success ; only if search was successful
19022 (if (featurep 'xemacs)
19023 ;; Under XEmacs, the hook is run in the correct place,
19024 ;; we directly show the context.
19025 (org-show-context 'isearch)
19026 ;; In Emacs the hook runs *before* restoring the overlays.
19027 ;; So we have to use a one-time post-command-hook to do this.
19028 ;; (Emacs 22 has a special variable, see function `org-mode')
19029 (unless (and (boundp 'isearch-mode-end-hook-quit)
19030 isearch-mode-end-hook-quit)
19031 ;; Only when the isearch was not quitted.
19032 (org-add-hook 'post-command-hook 'org-isearch-post-command
19033 'append 'local)))))
19035 (defun org-isearch-post-command ()
19036 "Remove self from hook, and show context."
19037 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19038 (org-show-context 'isearch))
19041 ;;;; Integration with and fixes for other packages
19043 ;;; Imenu support
19045 (defvar org-imenu-markers nil
19046 "All markers currently used by Imenu.")
19047 (make-variable-buffer-local 'org-imenu-markers)
19049 (defun org-imenu-new-marker (&optional pos)
19050 "Return a new marker for use by Imenu, and remember the marker."
19051 (let ((m (make-marker)))
19052 (move-marker m (or pos (point)))
19053 (push m org-imenu-markers)
19056 (defun org-imenu-get-tree ()
19057 "Produce the index for Imenu."
19058 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19059 (setq org-imenu-markers nil)
19060 (let* ((n org-imenu-depth)
19061 (re (concat "^" outline-regexp))
19062 (subs (make-vector (1+ n) nil))
19063 (last-level 0)
19064 m level head)
19065 (save-excursion
19066 (save-restriction
19067 (widen)
19068 (goto-char (point-max))
19069 (while (re-search-backward re nil t)
19070 (setq level (org-reduced-level (funcall outline-level)))
19071 (when (<= level n)
19072 (looking-at org-complex-heading-regexp)
19073 (setq head (org-link-display-format
19074 (org-match-string-no-properties 4))
19075 m (org-imenu-new-marker))
19076 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19077 (if (>= level last-level)
19078 (push (cons head m) (aref subs level))
19079 (push (cons head (aref subs (1+ level))) (aref subs level))
19080 (loop for i from (1+ level) to n do (aset subs i nil)))
19081 (setq last-level level)))))
19082 (aref subs 1)))
19084 (eval-after-load "imenu"
19085 '(progn
19086 (add-hook 'imenu-after-jump-hook
19087 (lambda ()
19088 (if (eq major-mode 'org-mode)
19089 (org-show-context 'org-goto))))))
19091 (defun org-link-display-format (link)
19092 "Replace a link with either the description, or the link target
19093 if no description is present"
19094 (save-match-data
19095 (if (string-match org-bracket-link-analytic-regexp link)
19096 (replace-match (if (match-end 5)
19097 (match-string 5 link)
19098 (concat (match-string 1 link)
19099 (match-string 3 link)))
19100 nil t link)
19101 link)))
19103 ;; Speedbar support
19105 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19106 "Overlay marking the agenda restriction line in speedbar.")
19107 (overlay-put org-speedbar-restriction-lock-overlay
19108 'face 'org-agenda-restriction-lock)
19109 (overlay-put org-speedbar-restriction-lock-overlay
19110 'help-echo "Agendas are currently limited to this item.")
19111 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19113 (defun org-speedbar-set-agenda-restriction ()
19114 "Restrict future agenda commands to the location at point in speedbar.
19115 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19116 (interactive)
19117 (require 'org-agenda)
19118 (let (p m tp np dir txt)
19119 (cond
19120 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19121 'org-imenu t))
19122 (setq m (get-text-property p 'org-imenu-marker))
19123 (with-current-buffer (marker-buffer m)
19124 (goto-char m)
19125 (org-agenda-set-restriction-lock 'subtree)))
19126 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19127 'speedbar-function 'speedbar-find-file))
19128 (setq tp (previous-single-property-change
19129 (1+ p) 'speedbar-function)
19130 np (next-single-property-change
19131 tp 'speedbar-function)
19132 dir (speedbar-line-directory)
19133 txt (buffer-substring-no-properties (or tp (point-min))
19134 (or np (point-max))))
19135 (with-current-buffer (find-file-noselect
19136 (let ((default-directory dir))
19137 (expand-file-name txt)))
19138 (unless (org-mode-p)
19139 (error "Cannot restrict to non-Org-mode file"))
19140 (org-agenda-set-restriction-lock 'file)))
19141 (t (error "Don't know how to restrict Org-mode's agenda")))
19142 (move-overlay org-speedbar-restriction-lock-overlay
19143 (point-at-bol) (point-at-eol))
19144 (setq current-prefix-arg nil)
19145 (org-agenda-maybe-redo)))
19147 (eval-after-load "speedbar"
19148 '(progn
19149 (speedbar-add-supported-extension ".org")
19150 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19151 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19152 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19153 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19154 (add-hook 'speedbar-visiting-tag-hook
19155 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19157 ;;; Fixes and Hacks for problems with other packages
19159 ;; Make flyspell not check words in links, to not mess up our keymap
19160 (defun org-mode-flyspell-verify ()
19161 "Don't let flyspell put overlays at active buttons."
19162 (and (not (get-text-property (point) 'keymap))
19163 (not (get-text-property (point) 'org-no-flyspell))))
19165 (defun org-remove-flyspell-overlays-in (beg end)
19166 "Remove flyspell overlays in region."
19167 (and (org-bound-and-true-p flyspell-mode)
19168 (fboundp 'flyspell-delete-region-overlays)
19169 (flyspell-delete-region-overlays beg end))
19170 (add-text-properties beg end '(org-no-flyspell t)))
19172 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19173 (eval-after-load "bookmark"
19174 '(if (boundp 'bookmark-after-jump-hook)
19175 ;; We can use the hook
19176 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19177 ;; Hook not available, use advice
19178 (defadvice bookmark-jump (after org-make-visible activate)
19179 "Make the position visible."
19180 (org-bookmark-jump-unhide))))
19182 ;; Make sure saveplace shows the location if it was hidden
19183 (eval-after-load "saveplace"
19184 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19185 "Make the position visible."
19186 (org-bookmark-jump-unhide)))
19188 ;; Make sure ecb shows the location if it was hidden
19189 (eval-after-load "ecb"
19190 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19191 "Make hierarchy visible when jumping into location from ECB tree buffer."
19192 (if (eq major-mode 'org-mode)
19193 (org-show-context))))
19195 (defun org-bookmark-jump-unhide ()
19196 "Unhide the current position, to show the bookmark location."
19197 (and (org-mode-p)
19198 (or (org-invisible-p)
19199 (save-excursion (goto-char (max (point-min) (1- (point))))
19200 (org-invisible-p)))
19201 (org-show-context 'bookmark-jump)))
19203 ;; Make session.el ignore our circular variable
19204 (eval-after-load "session"
19205 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19207 ;;;; Experimental code
19209 (defun org-closed-in-range ()
19210 "Sparse tree of items closed in a certain time range.
19211 Still experimental, may disappear in the future."
19212 (interactive)
19213 ;; Get the time interval from the user.
19214 (let* ((time1 (org-float-time
19215 (org-read-date nil 'to-time nil "Starting date: ")))
19216 (time2 (org-float-time
19217 (org-read-date nil 'to-time nil "End date:")))
19218 ;; callback function
19219 (callback (lambda ()
19220 (let ((time
19221 (org-float-time
19222 (apply 'encode-time
19223 (org-parse-time-string
19224 (match-string 1))))))
19225 ;; check if time in interval
19226 (and (>= time time1) (<= time time2))))))
19227 ;; make tree, check each match with the callback
19228 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19230 ;;;; Finish up
19232 (provide 'org)
19234 (run-hooks 'org-load-hook)
19236 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19238 ;;; org.el ends here