Fix some issues in the entity and subscript code
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob64044b49dbb5a26f69ae310a4705153d8c4b4354
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 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
264 (defcustom org-support-shift-select nil
265 "Non-nil means make shift-cursor commands select text when possible.
267 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
268 selecting a region, or enlarge thusly regions started in this way.
269 In Org-mode, in special contexts, these same keys are used for other
270 purposes, important enough to compete with shift selection. Org tries
271 to balance these needs by supporting `shift-select-mode' outside these
272 special contexts, under control of this variable.
274 The default of this variable is nil, to avoid confusing behavior. Shifted
275 cursor keys will then execute Org commands in the following contexts:
276 - on a headline, changing TODO state (left/right) and priority (up/down)
277 - on a time stamp, changing the time
278 - in a plain list item, changing the bullet type
279 - in a property definition line, switching between allowed values
280 - in the BEGIN line of a clock table (changing the time block).
281 Outside these contexts, the commands will throw an error.
283 When this variable is t and the cursor is not in a special context,
284 Org-mode will support shift-selection for making and enlarging regions.
285 To make this more effective, the bullet cycling will no longer happen
286 anywhere in an item line, but only if the cursor is exactly on the bullet.
288 If you set this variable to the symbol `always', then the keys
289 will not be special in headlines, property lines, and item lines, to make
290 shift selection work there as well. If this is what you want, you can
291 use the following alternative commands: `C-c C-t' and `C-c ,' to
292 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
293 TODO sets, `C-c -' to cycle item bullet types, and properties can be
294 edited by hand or in column view.
296 However, when the cursor is on a timestamp, shift-cursor commands
297 will still edit the time stamp - this is just too good to give up.
299 XEmacs user should have this variable set to nil, because shift-select-mode
300 is Emacs 23 only."
301 :group 'org
302 :type '(choice
303 (const :tag "Never" nil)
304 (const :tag "When outside special context" t)
305 (const :tag "Everywhere except timestamps" always)))
307 (defgroup org-startup nil
308 "Options concerning startup of Org-mode."
309 :tag "Org Startup"
310 :group 'org)
312 (defcustom org-startup-folded t
313 "Non-nil means entering Org-mode will switch to OVERVIEW.
314 This can also be configured on a per-file basis by adding one of
315 the following lines anywhere in the buffer:
317 #+STARTUP: fold (or `overview', this is equivalent)
318 #+STARTUP: nofold (or `showall', this is equivalent)
319 #+STARTUP: content
320 #+STARTUP: showeverything"
321 :group 'org-startup
322 :type '(choice
323 (const :tag "nofold: show all" nil)
324 (const :tag "fold: overview" t)
325 (const :tag "content: all headlines" content)
326 (const :tag "show everything, even drawers" showeverything)))
328 (defcustom org-startup-truncated t
329 "Non-nil means entering Org-mode will set `truncate-lines'.
330 This is useful since some lines containing links can be very long and
331 uninteresting. Also tables look terrible when wrapped."
332 :group 'org-startup
333 :type 'boolean)
335 (defcustom org-startup-indented nil
336 "Non-nil means turn on `org-indent-mode' on startup.
337 This can also be configured on a per-file basis by adding one of
338 the following lines anywhere in the buffer:
340 #+STARTUP: indent
341 #+STARTUP: noindent"
342 :group 'org-structure
343 :type '(choice
344 (const :tag "Not" nil)
345 (const :tag "Globally (slow on startup in large files)" t)))
347 (defcustom org-use-sub-superscripts t
348 "Non-nil means interpret \"_\" and \"^\" for export.
349 When this option is turned on, you can use TeX-like syntax for sub- and
350 superscripts. Several characters after \"_\" or \"^\" will be
351 considered as a single item - so grouping with {} is normally not
352 needed. For example, the following things will be parsed as single
353 sub- or superscripts.
355 10^24 or 10^tau several digits will be considered 1 item.
356 10^-12 or 10^-tau a leading sign with digits or a word
357 x^2-y^3 will be read as x^2 - y^3, because items are
358 terminated by almost any nonword/nondigit char.
359 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
361 Still, ambiguity is possible - so when in doubt use {} to enclose the
362 sub/superscript. If you set this variable to the symbol `{}',
363 the braces are *required* in order to trigger interpretations as
364 sub/superscript. This can be helpful in documents that need \"_\"
365 frequently in plain text.
367 Not all export backends support this, but HTML does.
369 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
370 :group 'org-startup
371 :group 'org-export-translation
372 :type '(choice
373 (const :tag "Always interpret" t)
374 (const :tag "Only with braces" {})
375 (const :tag "Never interpret" nil)))
377 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts)
380 (defcustom org-startup-with-beamer-mode nil
381 "Non-nil means turn on `org-beamer-mode' on startup.
382 This can also be configured on a per-file basis by adding one of
383 the following lines anywhere in the buffer:
385 #+STARTUP: beamer"
386 :group 'org-startup
387 :type 'boolean)
389 (defcustom org-startup-align-all-tables nil
390 "Non-nil means align all tables when visiting a file.
391 This is useful when the column width in tables is forced with <N> cookies
392 in table fields. Such tables will look correct only after the first re-align.
393 This can also be configured on a per-file basis by adding one of
394 the following lines anywhere in the buffer:
395 #+STARTUP: align
396 #+STARTUP: noalign"
397 :group 'org-startup
398 :type 'boolean)
400 (defcustom org-insert-mode-line-in-empty-file nil
401 "Non-nil means insert the first line setting Org-mode in empty files.
402 When the function `org-mode' is called interactively in an empty file, this
403 normally means that the file name does not automatically trigger Org-mode.
404 To ensure that the file will always be in Org-mode in the future, a
405 line enforcing Org-mode will be inserted into the buffer, if this option
406 has been set."
407 :group 'org-startup
408 :type 'boolean)
410 (defcustom org-replace-disputed-keys nil
411 "Non-nil means use alternative key bindings for some keys.
412 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
413 These keys are also used by other packages like shift-selection-mode'
414 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
415 If you want to use Org-mode together with one of these other modes,
416 or more generally if you would like to move some Org-mode commands to
417 other keys, set this variable and configure the keys with the variable
418 `org-disputed-keys'.
420 This option is only relevant at load-time of Org-mode, and must be set
421 *before* org.el is loaded. Changing it requires a restart of Emacs to
422 become effective."
423 :group 'org-startup
424 :type 'boolean)
426 (defcustom org-use-extra-keys nil
427 "Non-nil means use extra key sequence definitions for certain
428 commands. This happens automatically if you run XEmacs or if
429 window-system is nil. This variable lets you do the same
430 manually. You must set it before loading org.
432 Example: on Carbon Emacs 22 running graphically, with an external
433 keyboard on a Powerbook, the default way of setting M-left might
434 not work for either Alt or ESC. Setting this variable will make
435 it work for ESC."
436 :group 'org-startup
437 :type 'boolean)
439 (if (fboundp 'defvaralias)
440 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
442 (defcustom org-disputed-keys
443 '(([(shift up)] . [(meta p)])
444 ([(shift down)] . [(meta n)])
445 ([(shift left)] . [(meta -)])
446 ([(shift right)] . [(meta +)])
447 ([(control shift right)] . [(meta shift +)])
448 ([(control shift left)] . [(meta shift -)]))
449 "Keys for which Org-mode and other modes compete.
450 This is an alist, cars are the default keys, second element specifies
451 the alternative to use when `org-replace-disputed-keys' is t.
453 Keys can be specified in any syntax supported by `define-key'.
454 The value of this option takes effect only at Org-mode's startup,
455 therefore you'll have to restart Emacs to apply it after changing."
456 :group 'org-startup
457 :type 'alist)
459 (defun org-key (key)
460 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
461 Or return the original if not disputed.
462 Also apply the trnaslations defined in `org-xemacs-key-equivalents'."
463 (when org-replace-disputed-keys
464 (let* ((nkey (key-description key))
465 (x (org-find-if (lambda (x)
466 (equal (key-description (car x)) nkey))
467 org-disputed-keys)))
468 (setq key (if x (cdr x) key))))
469 (when (featurep 'xemacs)
470 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
471 key)
473 (defun org-find-if (predicate seq)
474 (catch 'exit
475 (while seq
476 (if (funcall predicate (car seq))
477 (throw 'exit (car seq))
478 (pop seq)))))
480 (defun org-defkey (keymap key def)
481 "Define a key, possibly translated, as returned by `org-key'."
482 (define-key keymap (org-key key) def))
484 (defcustom org-ellipsis nil
485 "The ellipsis to use in the Org-mode outline.
486 When nil, just use the standard three dots. When a string, use that instead,
487 When a face, use the standard 3 dots, but with the specified face.
488 The change affects only Org-mode (which will then use its own display table).
489 Changing this requires executing `M-x org-mode' in a buffer to become
490 effective."
491 :group 'org-startup
492 :type '(choice (const :tag "Default" nil)
493 (face :tag "Face" :value org-warning)
494 (string :tag "String" :value "...#")))
496 (defvar org-display-table nil
497 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
499 (defgroup org-keywords nil
500 "Keywords in Org-mode."
501 :tag "Org Keywords"
502 :group 'org)
504 (defcustom org-deadline-string "DEADLINE:"
505 "String to mark deadline entries.
506 A deadline is this string, followed by a time stamp. Should be a word,
507 terminated by a colon. You can insert a schedule keyword and
508 a timestamp with \\[org-deadline].
509 Changes become only effective after restarting Emacs."
510 :group 'org-keywords
511 :type 'string)
513 (defcustom org-scheduled-string "SCHEDULED:"
514 "String to mark scheduled TODO entries.
515 A schedule is this string, followed by a time stamp. Should be a word,
516 terminated by a colon. You can insert a schedule keyword and
517 a timestamp with \\[org-schedule].
518 Changes become only effective after restarting Emacs."
519 :group 'org-keywords
520 :type 'string)
522 (defcustom org-closed-string "CLOSED:"
523 "String used as the prefix for timestamps logging closing a TODO entry."
524 :group 'org-keywords
525 :type 'string)
527 (defcustom org-clock-string "CLOCK:"
528 "String used as prefix for timestamps clocking work hours on an item."
529 :group 'org-keywords
530 :type 'string)
532 (defcustom org-comment-string "COMMENT"
533 "Entries starting with this keyword will never be exported.
534 An entry can be toggled between COMMENT and normal with
535 \\[org-toggle-comment].
536 Changes become only effective after restarting Emacs."
537 :group 'org-keywords
538 :type 'string)
540 (defcustom org-quote-string "QUOTE"
541 "Entries starting with this keyword will be exported in fixed-width font.
542 Quoting applies only to the text in the entry following the headline, and does
543 not extend beyond the next headline, even if that is lower level.
544 An entry can be toggled between QUOTE and normal with
545 \\[org-toggle-fixed-width-section]."
546 :group 'org-keywords
547 :type 'string)
549 (defconst org-repeat-re
550 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
551 "Regular expression for specifying repeated events.
552 After a match, group 1 contains the repeat expression.")
554 (defgroup org-structure nil
555 "Options concerning the general structure of Org-mode files."
556 :tag "Org Structure"
557 :group 'org)
559 (defgroup org-reveal-location nil
560 "Options about how to make context of a location visible."
561 :tag "Org Reveal Location"
562 :group 'org-structure)
564 (defconst org-context-choice
565 '(choice
566 (const :tag "Always" t)
567 (const :tag "Never" nil)
568 (repeat :greedy t :tag "Individual contexts"
569 (cons
570 (choice :tag "Context"
571 (const agenda)
572 (const org-goto)
573 (const occur-tree)
574 (const tags-tree)
575 (const link-search)
576 (const mark-goto)
577 (const bookmark-jump)
578 (const isearch)
579 (const default))
580 (boolean))))
581 "Contexts for the reveal options.")
583 (defcustom org-show-hierarchy-above '((default . t))
584 "Non-nil means show full hierarchy when revealing a location.
585 Org-mode often shows locations in an org-mode file which might have
586 been invisible before. When this is set, the hierarchy of headings
587 above the exposed location is shown.
588 Turning this off for example for sparse trees makes them very compact.
589 Instead of t, this can also be an alist specifying this option for different
590 contexts. Valid contexts are
591 agenda when exposing an entry from the agenda
592 org-goto when using the command `org-goto' on key C-c C-j
593 occur-tree when using the command `org-occur' on key C-c /
594 tags-tree when constructing a sparse tree based on tags matches
595 link-search when exposing search matches associated with a link
596 mark-goto when exposing the jump goal of a mark
597 bookmark-jump when exposing a bookmark location
598 isearch when exiting from an incremental search
599 default default for all contexts not set explicitly"
600 :group 'org-reveal-location
601 :type org-context-choice)
603 (defcustom org-show-following-heading '((default . nil))
604 "Non-nil means show following heading when revealing a location.
605 Org-mode often shows locations in an org-mode file which might have
606 been invisible before. When this is set, the heading following the
607 match is shown.
608 Turning this off for example for sparse trees makes them very compact,
609 but makes it harder to edit the location of the match. In such a case,
610 use the command \\[org-reveal] to show more context.
611 Instead of t, this can also be an alist specifying this option for different
612 contexts. See `org-show-hierarchy-above' for valid contexts."
613 :group 'org-reveal-location
614 :type org-context-choice)
616 (defcustom org-show-siblings '((default . nil) (isearch t))
617 "Non-nil means show all sibling heading when revealing a location.
618 Org-mode often shows locations in an org-mode file which might have
619 been invisible before. When this is set, the sibling of the current entry
620 heading are all made visible. If `org-show-hierarchy-above' is t,
621 the same happens on each level of the hierarchy above the current entry.
623 By default this is on for the isearch context, off for all other contexts.
624 Turning this off for example for sparse trees makes them very compact,
625 but makes it harder to edit the location of the match. In such a case,
626 use the command \\[org-reveal] to show more context.
627 Instead of t, this can also be an alist specifying this option for different
628 contexts. See `org-show-hierarchy-above' for valid contexts."
629 :group 'org-reveal-location
630 :type org-context-choice)
632 (defcustom org-show-entry-below '((default . nil))
633 "Non-nil means show the entry below a headline when revealing a location.
634 Org-mode often shows locations in an org-mode file which might have
635 been invisible before. When this is set, the text below the headline that is
636 exposed is also shown.
638 By default this is off for all contexts.
639 Instead of t, this can also be an alist specifying this option for different
640 contexts. See `org-show-hierarchy-above' for valid contexts."
641 :group 'org-reveal-location
642 :type org-context-choice)
644 (defcustom org-indirect-buffer-display 'other-window
645 "How should indirect tree buffers be displayed?
646 This applies to indirect buffers created with the commands
647 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
648 Valid values are:
649 current-window Display in the current window
650 other-window Just display in another window.
651 dedicated-frame Create one new frame, and re-use it each time.
652 new-frame Make a new frame each time. Note that in this case
653 previously-made indirect buffers are kept, and you need to
654 kill these buffers yourself."
655 :group 'org-structure
656 :group 'org-agenda-windows
657 :type '(choice
658 (const :tag "In current window" current-window)
659 (const :tag "In current frame, other window" other-window)
660 (const :tag "Each time a new frame" new-frame)
661 (const :tag "One dedicated frame" dedicated-frame)))
663 (defcustom org-use-speed-commands nil
664 "Non-nil means activate single letter commands at beginning of a headline.
665 This may also be a function to test for appropriate locations where speed
666 commands should be active."
667 :group 'org-structure
668 :type '(choice
669 (const :tag "Never" nil)
670 (const :tag "At beginning of headline stars" t)
671 (function)))
673 (defcustom org-speed-commands-user nil
674 "Alist of additional speed commands.
675 This list will be checked before `org-speed-commands-default'
676 when the variable `org-use-speed-commands' is non-nil
677 and when the cursor is at the beginning of a headline.
678 The car if each entry is a string with a single letter, which must
679 be assigned to `self-insert-command' in the global map.
680 The cdr is either a command to be called interactively, a function
681 to be called, or a form to be evaluated.
682 An entry that is just a list with a single string will be interpreted
683 as a descriptive headline that will be added when listing the speed
684 copmmands in the Help buffer using the `?' speed command."
685 :group 'org-structure
686 :type '(repeat :value ("k" . ignore)
687 (choice :value ("k" . ignore)
688 (list :tag "Descriptive Headline" (string :tag "Headline"))
689 (cons :tag "Letter and Command"
690 (string :tag "Command letter")
691 (choice
692 (function)
693 (sexp))))))
695 (defgroup org-cycle nil
696 "Options concerning visibility cycling in Org-mode."
697 :tag "Org Cycle"
698 :group 'org-structure)
700 (defcustom org-cycle-skip-children-state-if-no-children t
701 "Non-nil means skip CHILDREN state in entries that don't have any."
702 :group 'org-cycle
703 :type 'boolean)
705 (defcustom org-cycle-max-level nil
706 "Maximum level which should still be subject to visibility cycling.
707 Levels higher than this will, for cycling, be treated as text, not a headline.
708 When `org-odd-levels-only' is set, a value of N in this variable actually
709 means 2N-1 stars as the limiting headline.
710 When nil, cycle all levels.
711 Note that the limiting level of cycling is also influenced by
712 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
713 `org-inlinetask-min-level' is, cycling will be limited to levels one less
714 than its value."
715 :group 'org-cycle
716 :type '(choice
717 (const :tag "No limit" nil)
718 (integer :tag "Maximum level")))
720 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
721 "Names of drawers. Drawers are not opened by cycling on the headline above.
722 Drawers only open with a TAB on the drawer line itself. A drawer looks like
723 this:
724 :DRAWERNAME:
725 .....
726 :END:
727 The drawer \"PROPERTIES\" is special for capturing properties through
728 the property API.
730 Drawers can be defined on the per-file basis with a line like:
732 #+DRAWERS: HIDDEN STATE PROPERTIES"
733 :group 'org-structure
734 :group 'org-cycle
735 :type '(repeat (string :tag "Drawer Name")))
737 (defcustom org-hide-block-startup nil
738 "Non-nil means entering Org-mode will fold all blocks.
739 This can also be set in on a per-file basis with
741 #+STARTUP: hideblocks
742 #+STARTUP: showblocks"
743 :group 'org-startup
744 :group 'org-cycle
745 :type 'boolean)
747 (defcustom org-cycle-global-at-bob nil
748 "Cycle globally if cursor is at beginning of buffer and not at a headline.
749 This makes it possible to do global cycling without having to use S-TAB or
750 C-u TAB. For this special case to work, the first line of the buffer
751 must not be a headline - it may be empty or some other text. When used in
752 this way, `org-cycle-hook' is disables temporarily, to make sure the
753 cursor stays at the beginning of the buffer.
754 When this option is nil, don't do anything special at the beginning
755 of the buffer."
756 :group 'org-cycle
757 :type 'boolean)
759 (defcustom org-cycle-level-after-item/entry-creation t
760 "Non-nil means cycle entry level or item indentation in new empty entries.
762 When the cursor is at the end of an empty headline, i.e with only stars
763 and maybe a TODO keyword, TAB will then switch the entry to become a child,
764 and then all possible anchestor states, before returning to the original state.
765 This makes data entry extremely fast: M-RET to create a new headline,
766 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
768 When the cursor is at the end of an empty plain list item, one TAB will
769 make it a subitem, two or more tabs will back up to make this an item
770 higher up in the item hierarchy."
771 :group 'org-cycle
772 :type 'boolean)
774 (defcustom org-cycle-emulate-tab t
775 "Where should `org-cycle' emulate TAB.
776 nil Never
777 white Only in completely white lines
778 whitestart Only at the beginning of lines, before the first non-white char
779 t Everywhere except in headlines
780 exc-hl-bol Everywhere except at the start of a headline
781 If TAB is used in a place where it does not emulate TAB, the current subtree
782 visibility is cycled."
783 :group 'org-cycle
784 :type '(choice (const :tag "Never" nil)
785 (const :tag "Only in completely white lines" white)
786 (const :tag "Before first char in a line" whitestart)
787 (const :tag "Everywhere except in headlines" t)
788 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
791 (defcustom org-cycle-separator-lines 2
792 "Number of empty lines needed to keep an empty line between collapsed trees.
793 If you leave an empty line between the end of a subtree and the following
794 headline, this empty line is hidden when the subtree is folded.
795 Org-mode will leave (exactly) one empty line visible if the number of
796 empty lines is equal or larger to the number given in this variable.
797 So the default 2 means at least 2 empty lines after the end of a subtree
798 are needed to produce free space between a collapsed subtree and the
799 following headline.
801 If the number is negative, and the number of empty lines is at least -N,
802 all empty lines are shown.
804 Special case: when 0, never leave empty lines in collapsed view."
805 :group 'org-cycle
806 :type 'integer)
807 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
809 (defcustom org-pre-cycle-hook nil
810 "Hook that is run before visibility cycling is happening.
811 The function(s) in this hook must accept a single argument which indicates
812 the new state that will be set right after running this hook. The
813 argument is a symbol. Before a global state change, it can have the values
814 `overview', `content', or `all'. Before a local state change, it can have
815 the values `folded', `children', or `subtree'."
816 :group 'org-cycle
817 :type 'hook)
819 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
820 org-cycle-hide-drawers
821 org-cycle-show-empty-lines
822 org-optimize-window-after-visibility-change)
823 "Hook that is run after `org-cycle' has changed the buffer visibility.
824 The function(s) in this hook must accept a single argument which indicates
825 the new state that was set by the most recent `org-cycle' command. The
826 argument is a symbol. After a global state change, it can have the values
827 `overview', `content', or `all'. After a local state change, it can have
828 the values `folded', `children', or `subtree'."
829 :group 'org-cycle
830 :type 'hook)
832 (defgroup org-edit-structure nil
833 "Options concerning structure editing in Org-mode."
834 :tag "Org Edit Structure"
835 :group 'org-structure)
837 (defcustom org-odd-levels-only nil
838 "Non-nil means skip even levels and only use odd levels for the outline.
839 This has the effect that two stars are being added/taken away in
840 promotion/demotion commands. It also influences how levels are
841 handled by the exporters.
842 Changing it requires restart of `font-lock-mode' to become effective
843 for fontification also in regions already fontified.
844 You may also set this on a per-file basis by adding one of the following
845 lines to the buffer:
847 #+STARTUP: odd
848 #+STARTUP: oddeven"
849 :group 'org-edit-structure
850 :group 'org-appearance
851 :type 'boolean)
853 (defcustom org-adapt-indentation t
854 "Non-nil means adapt indentation to outline node level.
856 When this variable is set, Org assumes that you write outlines by
857 indenting text in each node to align with the headline (after the stars).
858 The following issues are influenced by this variable:
860 - When this is set and the *entire* text in an entry is indented, the
861 indentation is increased by one space in a demotion command, and
862 decreased by one in a promotion command. If any line in the entry
863 body starts with text at column 0, indentation is not changed at all.
865 - Property drawers and planning information is inserted indented when
866 this variable s set. When nil, they will not be indented.
868 - TAB indents a line relative to context. The lines below a headline
869 will be indented when this variable is set.
871 Note that this is all about true indentation, by adding and removing
872 space characters. See also `org-indent.el' which does level-dependent
873 indentation in a virtual way, i.e. at display time in Emacs."
874 :group 'org-edit-structure
875 :type 'boolean)
877 (defcustom org-special-ctrl-a/e nil
878 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
880 When t, `C-a' will bring back the cursor to the beginning of the
881 headline text, i.e. after the stars and after a possible TODO keyword.
882 In an item, this will be the position after the bullet.
883 When the cursor is already at that position, another `C-a' will bring
884 it to the beginning of the line.
886 `C-e' will jump to the end of the headline, ignoring the presence of tags
887 in the headline. A second `C-e' will then jump to the true end of the
888 line, after any tags. This also means that, when this variable is
889 non-nil, `C-e' also will never jump beyond the end of the heading of a
890 folded section, i.e. not after the ellipses.
892 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
893 going to the true line boundary first. Only a directly following, identical
894 keypress will bring the cursor to the special positions.
896 This may also be a cons cell where the behavior for `C-a' and `C-e' is
897 set separately."
898 :group 'org-edit-structure
899 :type '(choice
900 (const :tag "off" nil)
901 (const :tag "on: after stars/bullet and before tags first" t)
902 (const :tag "reversed: true line boundary first" reversed)
903 (cons :tag "Set C-a and C-e separately"
904 (choice :tag "Special C-a"
905 (const :tag "off" nil)
906 (const :tag "on: after stars/bullet first" t)
907 (const :tag "reversed: before stars/bullet first" reversed))
908 (choice :tag "Special C-e"
909 (const :tag "off" nil)
910 (const :tag "on: before tags first" t)
911 (const :tag "reversed: after tags first" reversed)))))
912 (if (fboundp 'defvaralias)
913 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
915 (defcustom org-special-ctrl-k nil
916 "Non-nil means `C-k' will behave specially in headlines.
917 When nil, `C-k' will call the default `kill-line' command.
918 When t, the following will happen while the cursor is in the headline:
920 - When the cursor is at the beginning of a headline, kill the entire
921 line and possible the folded subtree below the line.
922 - When in the middle of the headline text, kill the headline up to the tags.
923 - When after the headline text, kill the tags."
924 :group 'org-edit-structure
925 :type 'boolean)
927 (defcustom org-ctrl-k-protect-subtree nil
928 "Non-nil means, do not delete a hidden subtree with C-k.
929 When set to the symbol `error', simply throw an error when C-k is
930 used to kill (part-of) a headline that has hidden text behind it.
931 Any other non-nil value will result in a query to the user, if it is
932 OK to kill that hidden subtree. When nil, kill without remorse."
933 :group 'org-edit-structure
934 :type '(choice
935 (const :tag "Do not protect hidden subtrees" nil)
936 (const :tag "Protect hidden subtrees with a security query" t)
937 (const :tag "Never kill a hidden subtree with C-k" error)))
939 (defcustom org-yank-folded-subtrees t
940 "Non-nil means when yanking subtrees, fold them.
941 If the kill is a single subtree, or a sequence of subtrees, i.e. if
942 it starts with a heading and all other headings in it are either children
943 or siblings, then fold all the subtrees. However, do this only if no
944 text after the yank would be swallowed into a folded tree by this action."
945 :group 'org-edit-structure
946 :type 'boolean)
948 (defcustom org-yank-adjusted-subtrees nil
949 "Non-nil means when yanking subtrees, adjust the level.
950 With this setting, `org-paste-subtree' is used to insert the subtree, see
951 this function for details."
952 :group 'org-edit-structure
953 :type 'boolean)
955 (defcustom org-M-RET-may-split-line '((default . t))
956 "Non-nil means M-RET will split the line at the cursor position.
957 When nil, it will go to the end of the line before making a
958 new line.
959 You may also set this option in a different way for different
960 contexts. Valid contexts are:
962 headline when creating a new headline
963 item when creating a new item
964 table in a table field
965 default the value to be used for all contexts not explicitly
966 customized"
967 :group 'org-structure
968 :group 'org-table
969 :type '(choice
970 (const :tag "Always" t)
971 (const :tag "Never" nil)
972 (repeat :greedy t :tag "Individual contexts"
973 (cons
974 (choice :tag "Context"
975 (const headline)
976 (const item)
977 (const table)
978 (const default))
979 (boolean)))))
982 (defcustom org-insert-heading-respect-content nil
983 "Non-nil means insert new headings after the current subtree.
984 When nil, the new heading is created directly after the current line.
985 The commands \\[org-insert-heading-respect-content] and
986 \\[org-insert-todo-heading-respect-content] turn this variable on
987 for the duration of the command."
988 :group 'org-structure
989 :type 'boolean)
991 (defcustom org-blank-before-new-entry '((heading . auto)
992 (plain-list-item . auto))
993 "Should `org-insert-heading' leave a blank line before new heading/item?
994 The value is an alist, with `heading' and `plain-list-item' as car,
995 and a boolean flag as cdr. For plain lists, if the variable
996 `org-empty-line-terminates-plain-lists' is set, the setting here
997 is ignored and no empty line is inserted, to keep the list in tact."
998 :group 'org-edit-structure
999 :type '(list
1000 (cons (const heading)
1001 (choice (const :tag "Never" nil)
1002 (const :tag "Always" t)
1003 (const :tag "Auto" auto)))
1004 (cons (const plain-list-item)
1005 (choice (const :tag "Never" nil)
1006 (const :tag "Always" t)
1007 (const :tag "Auto" auto)))))
1009 (defcustom org-insert-heading-hook nil
1010 "Hook being run after inserting a new heading."
1011 :group 'org-edit-structure
1012 :type 'hook)
1014 (defcustom org-enable-fixed-width-editor t
1015 "Non-nil means lines starting with \":\" are treated as fixed-width.
1016 This currently only means they are never auto-wrapped.
1017 When nil, such lines will be treated like ordinary lines.
1018 See also the QUOTE keyword."
1019 :group 'org-edit-structure
1020 :type 'boolean)
1023 (defcustom org-goto-auto-isearch t
1024 "Non-nil means typing characters in org-goto starts incremental search."
1025 :group 'org-edit-structure
1026 :type 'boolean)
1028 (defgroup org-sparse-trees nil
1029 "Options concerning sparse trees in Org-mode."
1030 :tag "Org Sparse Trees"
1031 :group 'org-structure)
1033 (defcustom org-highlight-sparse-tree-matches t
1034 "Non-nil means highlight all matches that define a sparse tree.
1035 The highlights will automatically disappear the next time the buffer is
1036 changed by an edit command."
1037 :group 'org-sparse-trees
1038 :type 'boolean)
1040 (defcustom org-remove-highlights-with-change t
1041 "Non-nil means any change to the buffer will remove temporary highlights.
1042 Such highlights are created by `org-occur' and `org-clock-display'.
1043 When nil, `C-c C-c needs to be used to get rid of the highlights.
1044 The highlights created by `org-preview-latex-fragment' always need
1045 `C-c C-c' to be removed."
1046 :group 'org-sparse-trees
1047 :group 'org-time
1048 :type 'boolean)
1051 (defcustom org-occur-hook '(org-first-headline-recenter)
1052 "Hook that is run after `org-occur' has constructed a sparse tree.
1053 This can be used to recenter the window to show as much of the structure
1054 as possible."
1055 :group 'org-sparse-trees
1056 :type 'hook)
1058 (defgroup org-imenu-and-speedbar nil
1059 "Options concerning imenu and speedbar in Org-mode."
1060 :tag "Org Imenu and Speedbar"
1061 :group 'org-structure)
1063 (defcustom org-imenu-depth 2
1064 "The maximum level for Imenu access to Org-mode headlines.
1065 This also applied for speedbar access."
1066 :group 'org-imenu-and-speedbar
1067 :type 'integer)
1069 (defgroup org-table nil
1070 "Options concerning tables in Org-mode."
1071 :tag "Org Table"
1072 :group 'org)
1074 (defcustom org-enable-table-editor 'optimized
1075 "Non-nil means lines starting with \"|\" are handled by the table editor.
1076 When nil, such lines will be treated like ordinary lines.
1078 When equal to the symbol `optimized', the table editor will be optimized to
1079 do the following:
1080 - Automatic overwrite mode in front of whitespace in table fields.
1081 This makes the structure of the table stay in tact as long as the edited
1082 field does not exceed the column width.
1083 - Minimize the number of realigns. Normally, the table is aligned each time
1084 TAB or RET are pressed to move to another field. With optimization this
1085 happens only if changes to a field might have changed the column width.
1086 Optimization requires replacing the functions `self-insert-command',
1087 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1088 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1089 very good at guessing when a re-align will be necessary, but you can always
1090 force one with \\[org-ctrl-c-ctrl-c].
1092 If you would like to use the optimized version in Org-mode, but the
1093 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1095 This variable can be used to turn on and off the table editor during a session,
1096 but in order to toggle optimization, a restart is required.
1098 See also the variable `org-table-auto-blank-field'."
1099 :group 'org-table
1100 :type '(choice
1101 (const :tag "off" nil)
1102 (const :tag "on" t)
1103 (const :tag "on, optimized" optimized)))
1105 (defcustom org-self-insert-cluster-for-undo t
1106 "Non-nil means cluster self-insert commands for undo when possible.
1107 If this is set, then, like in the Emacs command loop, 20 consecutive
1108 characters will be undone together.
1109 This is configurable, because there is some impact on typing performance."
1110 :group 'org-table
1111 :type 'boolean)
1113 (defcustom org-table-tab-recognizes-table.el t
1114 "Non-nil means TAB will automatically notice a table.el table.
1115 When it sees such a table, it moves point into it and - if necessary -
1116 calls `table-recognize-table'."
1117 :group 'org-table-editing
1118 :type 'boolean)
1120 (defgroup org-link nil
1121 "Options concerning links in Org-mode."
1122 :tag "Org Link"
1123 :group 'org)
1125 (defvar org-link-abbrev-alist-local nil
1126 "Buffer-local version of `org-link-abbrev-alist', which see.
1127 The value of this is taken from the #+LINK lines.")
1128 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1130 (defcustom org-link-abbrev-alist nil
1131 "Alist of link abbreviations.
1132 The car of each element is a string, to be replaced at the start of a link.
1133 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1134 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1136 [[linkkey:tag][description]]
1138 The 'linkkey' must be a word word, starting with a letter, followed
1139 by letters, numbers, '-' or '_'.
1141 If REPLACE is a string, the tag will simply be appended to create the link.
1142 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1143 the placeholder \"%h\" will cause a url-encoded version of the tag to
1144 be inserted at that point (see the function `url-hexify-string').
1146 REPLACE may also be a function that will be called with the tag as the
1147 only argument to create the link, which should be returned as a string.
1149 See the manual for examples."
1150 :group 'org-link
1151 :type '(repeat
1152 (cons
1153 (string :tag "Protocol")
1154 (choice
1155 (string :tag "Format")
1156 (function)))))
1158 (defcustom org-descriptive-links t
1159 "Non-nil means hide link part and only show description of bracket links.
1160 Bracket links are like [[link][description]]. This variable sets the initial
1161 state in new org-mode buffers. The setting can then be toggled on a
1162 per-buffer basis from the Org->Hyperlinks menu."
1163 :group 'org-link
1164 :type 'boolean)
1166 (defcustom org-link-file-path-type 'adaptive
1167 "How the path name in file links should be stored.
1168 Valid values are:
1170 relative Relative to the current directory, i.e. the directory of the file
1171 into which the link is being inserted.
1172 absolute Absolute path, if possible with ~ for home directory.
1173 noabbrev Absolute path, no abbreviation of home directory.
1174 adaptive Use relative path for files in the current directory and sub-
1175 directories of it. For other files, use an absolute path."
1176 :group 'org-link
1177 :type '(choice
1178 (const relative)
1179 (const absolute)
1180 (const noabbrev)
1181 (const adaptive)))
1183 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1184 "Types of links that should be activated in Org-mode files.
1185 This is a list of symbols, each leading to the activation of a certain link
1186 type. In principle, it does not hurt to turn on most link types - there may
1187 be a small gain when turning off unused link types. The types are:
1189 bracket The recommended [[link][description]] or [[link]] links with hiding.
1190 angular Links in angular brackets that may contain whitespace like
1191 <bbdb:Carsten Dominik>.
1192 plain Plain links in normal text, no whitespace, like http://google.com.
1193 radio Text that is matched by a radio target, see manual for details.
1194 tag Tag settings in a headline (link to tag search).
1195 date Time stamps (link to calendar).
1196 footnote Footnote labels.
1198 Changing this variable requires a restart of Emacs to become effective."
1199 :group 'org-link
1200 :type '(set :greedy t
1201 (const :tag "Double bracket links (new style)" bracket)
1202 (const :tag "Angular bracket links (old style)" angular)
1203 (const :tag "Plain text links" plain)
1204 (const :tag "Radio target matches" radio)
1205 (const :tag "Tags" tag)
1206 (const :tag "Timestamps" date)
1207 (const :tag "Footnotes" footnote)))
1209 (defcustom org-make-link-description-function nil
1210 "Function to use to generate link descriptions from links. If
1211 nil the link location will be used. This function must take two
1212 parameters; the first is the link and the second the description
1213 org-insert-link has generated, and should return the description
1214 to use."
1215 :group 'org-link
1216 :type 'function)
1218 (defgroup org-link-store nil
1219 "Options concerning storing links in Org-mode."
1220 :tag "Org Store Link"
1221 :group 'org-link)
1223 (defcustom org-email-link-description-format "Email %c: %.30s"
1224 "Format of the description part of a link to an email or usenet message.
1225 The following %-escapes will be replaced by corresponding information:
1227 %F full \"From\" field
1228 %f name, taken from \"From\" field, address if no name
1229 %T full \"To\" field
1230 %t first name in \"To\" field, address if no name
1231 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1232 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1233 %s subject
1234 %m message-id.
1236 You may use normal field width specification between the % and the letter.
1237 This is for example useful to limit the length of the subject.
1239 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1240 :group 'org-link-store
1241 :type 'string)
1243 (defcustom org-from-is-user-regexp
1244 (let (r1 r2)
1245 (when (and user-mail-address (not (string= user-mail-address "")))
1246 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1247 (when (and user-full-name (not (string= user-full-name "")))
1248 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1249 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1250 "Regexp matched against the \"From:\" header of an email or usenet message.
1251 It should match if the message is from the user him/herself."
1252 :group 'org-link-store
1253 :type 'regexp)
1255 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1256 "Non-nil means storing a link to an Org file will use entry IDs.
1258 Note that before this variable is even considered, org-id must be loaded,
1259 so please customize `org-modules' and turn it on.
1261 The variable can have the following values:
1263 t Create an ID if needed to make a link to the current entry.
1265 create-if-interactive
1266 If `org-store-link' is called directly (interactively, as a user
1267 command), do create an ID to support the link. But when doing the
1268 job for remember, only use the ID if it already exists. The
1269 purpose of this setting is to avoid proliferation of unwanted
1270 IDs, just because you happen to be in an Org file when you
1271 call `org-remember' that automatically and preemptively
1272 creates a link. If you do want to get an ID link in a remember
1273 template to an entry not having an ID, create it first by
1274 explicitly creating a link to it, using `C-c C-l' first.
1276 create-if-interactive-and-no-custom-id
1277 Like create-if-interactive, but do not create an ID if there is
1278 a CUSTOM_ID property defined in the entry. This is the default.
1280 use-existing
1281 Use existing ID, do not create one.
1283 nil Never use an ID to make a link, instead link using a text search for
1284 the headline text."
1285 :group 'org-link-store
1286 :type '(choice
1287 (const :tag "Create ID to make link" t)
1288 (const :tag "Create if storing link interactively"
1289 create-if-interactive)
1290 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1291 create-if-interactive-and-no-custom-id)
1292 (const :tag "Only use existing" use-existing)
1293 (const :tag "Do not use ID to create link" nil)))
1295 (defcustom org-context-in-file-links t
1296 "Non-nil means file links from `org-store-link' contain context.
1297 A search string will be added to the file name with :: as separator and
1298 used to find the context when the link is activated by the command
1299 `org-open-at-point'.
1300 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1301 negates this setting for the duration of the command."
1302 :group 'org-link-store
1303 :type 'boolean)
1305 (defcustom org-keep-stored-link-after-insertion nil
1306 "Non-nil means keep link in list for entire session.
1308 The command `org-store-link' adds a link pointing to the current
1309 location to an internal list. These links accumulate during a session.
1310 The command `org-insert-link' can be used to insert links into any
1311 Org-mode file (offering completion for all stored links). When this
1312 option is nil, every link which has been inserted once using \\[org-insert-link]
1313 will be removed from the list, to make completing the unused links
1314 more efficient."
1315 :group 'org-link-store
1316 :type 'boolean)
1318 (defgroup org-link-follow nil
1319 "Options concerning following links in Org-mode."
1320 :tag "Org Follow Link"
1321 :group 'org-link)
1323 (defcustom org-link-translation-function nil
1324 "Function to translate links with different syntax to Org syntax.
1325 This can be used to translate links created for example by the Planner
1326 or emacs-wiki packages to Org syntax.
1327 The function must accept two parameters, a TYPE containing the link
1328 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1329 which is everything after the link protocol. It should return a cons
1330 with possibly modified values of type and path.
1331 Org contains a function for this, so if you set this variable to
1332 `org-translate-link-from-planner', you should be able follow many
1333 links created by planner."
1334 :group 'org-link-follow
1335 :type 'function)
1337 (defcustom org-follow-link-hook nil
1338 "Hook that is run after a link has been followed."
1339 :group 'org-link-follow
1340 :type 'hook)
1342 (defcustom org-tab-follows-link nil
1343 "Non-nil means on links TAB will follow the link.
1344 Needs to be set before org.el is loaded.
1345 This really should not be used, it does not make sense, and the
1346 implementation is bad."
1347 :group 'org-link-follow
1348 :type 'boolean)
1350 (defcustom org-return-follows-link nil
1351 "Non-nil means on links RET will follow the link."
1352 :group 'org-link-follow
1353 :type 'boolean)
1355 (defcustom org-mouse-1-follows-link
1356 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1357 "Non-nil means mouse-1 on a link will follow the link.
1358 A longer mouse click will still set point. Does not work on XEmacs.
1359 Needs to be set before org.el is loaded."
1360 :group 'org-link-follow
1361 :type 'boolean)
1363 (defcustom org-mark-ring-length 4
1364 "Number of different positions to be recorded in the ring
1365 Changing this requires a restart of Emacs to work correctly."
1366 :group 'org-link-follow
1367 :type 'integer)
1369 (defcustom org-link-frame-setup
1370 '((vm . vm-visit-folder-other-frame)
1371 (gnus . gnus-other-frame)
1372 (file . find-file-other-window))
1373 "Setup the frame configuration for following links.
1374 When following a link with Emacs, it may often be useful to display
1375 this link in another window or frame. This variable can be used to
1376 set this up for the different types of links.
1377 For VM, use any of
1378 `vm-visit-folder'
1379 `vm-visit-folder-other-frame'
1380 For Gnus, use any of
1381 `gnus'
1382 `gnus-other-frame'
1383 `org-gnus-no-new-news'
1384 For FILE, use any of
1385 `find-file'
1386 `find-file-other-window'
1387 `find-file-other-frame'
1388 For the calendar, use the variable `calendar-setup'.
1389 For BBDB, it is currently only possible to display the matches in
1390 another window."
1391 :group 'org-link-follow
1392 :type '(list
1393 (cons (const vm)
1394 (choice
1395 (const vm-visit-folder)
1396 (const vm-visit-folder-other-window)
1397 (const vm-visit-folder-other-frame)))
1398 (cons (const gnus)
1399 (choice
1400 (const gnus)
1401 (const gnus-other-frame)
1402 (const org-gnus-no-new-news)))
1403 (cons (const file)
1404 (choice
1405 (const find-file)
1406 (const find-file-other-window)
1407 (const find-file-other-frame)))))
1409 (defcustom org-display-internal-link-with-indirect-buffer nil
1410 "Non-nil means use indirect buffer to display infile links.
1411 Activating internal links (from one location in a file to another location
1412 in the same file) normally just jumps to the location. When the link is
1413 activated with a C-u prefix (or with mouse-3), the link is displayed in
1414 another window. When this option is set, the other window actually displays
1415 an indirect buffer clone of the current buffer, to avoid any visibility
1416 changes to the current buffer."
1417 :group 'org-link-follow
1418 :type 'boolean)
1420 (defcustom org-open-non-existing-files nil
1421 "Non-nil means `org-open-file' will open non-existing files.
1422 When nil, an error will be generated.
1423 This variable applies only to external applications because they
1424 might choke on non-existing files. If the link is to a file that
1425 will be opened in Emacs, the variable is ignored."
1426 :group 'org-link-follow
1427 :type 'boolean)
1429 (defcustom org-open-directory-means-index-dot-org nil
1430 "Non-nil means a link to a directory really means to index.org.
1431 When nil, following a directory link will run dired or open a finder/explorer
1432 window on that directory."
1433 :group 'org-link-follow
1434 :type 'boolean)
1436 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1437 "Function and arguments to call for following mailto links.
1438 This is a list with the first element being a lisp function, and the
1439 remaining elements being arguments to the function. In string arguments,
1440 %a will be replaced by the address, and %s will be replaced by the subject
1441 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1442 :group 'org-link-follow
1443 :type '(choice
1444 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1445 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1446 (const :tag "message-mail" (message-mail "%a" "%s"))
1447 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1449 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1450 "Non-nil means ask for confirmation before executing shell links.
1451 Shell links can be dangerous: just think about a link
1453 [[shell:rm -rf ~/*][Google Search]]
1455 This link would show up in your Org-mode document as \"Google Search\",
1456 but really it would remove your entire home directory.
1457 Therefore we advise against setting this variable to nil.
1458 Just change it to `y-or-n-p' if you want to confirm with a
1459 single keystroke rather than having to type \"yes\"."
1460 :group 'org-link-follow
1461 :type '(choice
1462 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1463 (const :tag "with y-or-n (faster)" y-or-n-p)
1464 (const :tag "no confirmation (dangerous)" nil)))
1466 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1467 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1468 Elisp links can be dangerous: just think about a link
1470 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1472 This link would show up in your Org-mode document as \"Google Search\",
1473 but really it would remove your entire home directory.
1474 Therefore we advise against setting this variable to nil.
1475 Just change it to `y-or-n-p' if you want to confirm with a
1476 single keystroke rather than having to type \"yes\"."
1477 :group 'org-link-follow
1478 :type '(choice
1479 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1480 (const :tag "with y-or-n (faster)" y-or-n-p)
1481 (const :tag "no confirmation (dangerous)" nil)))
1483 (defconst org-file-apps-defaults-gnu
1484 '((remote . emacs)
1485 (system . mailcap)
1486 (t . mailcap))
1487 "Default file applications on a UNIX or GNU/Linux system.
1488 See `org-file-apps'.")
1490 (defconst org-file-apps-defaults-macosx
1491 '((remote . emacs)
1492 (t . "open %s")
1493 (system . "open %s")
1494 ("ps.gz" . "gv %s")
1495 ("eps.gz" . "gv %s")
1496 ("dvi" . "xdvi %s")
1497 ("fig" . "xfig %s"))
1498 "Default file applications on a MacOS X system.
1499 The system \"open\" is known as a default, but we use X11 applications
1500 for some files for which the OS does not have a good default.
1501 See `org-file-apps'.")
1503 (defconst org-file-apps-defaults-windowsnt
1504 (list
1505 '(remote . emacs)
1506 (cons t
1507 (list (if (featurep 'xemacs)
1508 'mswindows-shell-execute
1509 'w32-shell-execute)
1510 "open" 'file))
1511 (cons 'system
1512 (list (if (featurep 'xemacs)
1513 'mswindows-shell-execute
1514 'w32-shell-execute)
1515 "open" 'file)))
1516 "Default file applications on a Windows NT system.
1517 The system \"open\" is used for most files.
1518 See `org-file-apps'.")
1520 (defcustom org-file-apps
1522 (auto-mode . emacs)
1523 ("\\.mm\\'" . default)
1524 ("\\.x?html?\\'" . default)
1525 ("\\.pdf\\'" . default)
1527 "External applications for opening `file:path' items in a document.
1528 Org-mode uses system defaults for different file types, but
1529 you can use this variable to set the application for a given file
1530 extension. The entries in this list are cons cells where the car identifies
1531 files and the cdr the corresponding command. Possible values for the
1532 file identifier are
1533 \"string\" A string as a file identifier can be interpreted in different
1534 ways, depending on its contents:
1536 - Alphanumeric characters only:
1537 Match links with this file extension.
1538 Example: (\"pdf\" . \"evince %s\")
1539 to open PDFs with evince.
1541 - Regular expression: Match links where the
1542 filename matches the regexp. If you want to
1543 use groups here, use shy groups.
1545 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1546 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1547 to open *.html and *.xhtml with firefox.
1549 - Regular expression which contains (non-shy) groups:
1550 Match links where the whole link, including \"::\", and
1551 anything after that, matches the regexp.
1552 In a custom command string, %1, %2, etc. are replaced with
1553 the parts of the link that were matched by the groups.
1554 For backwards compatibility, if a command string is given
1555 that does not use any of the group matches, this case is
1556 handled identically to the second one (i.e. match against
1557 file name only).
1559 In a custom lisp form, you can access the group matches with
1560 (match-string n link).
1562 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1563 to open [[file:document.pdf::5]] with evince at page 5.
1565 `directory' Matches a directory
1566 `remote' Matches a remote file, accessible through tramp or efs.
1567 Remote files most likely should be visited through Emacs
1568 because external applications cannot handle such paths.
1569 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1570 so all files Emacs knows how to handle. Using this with
1571 command `emacs' will open most files in Emacs. Beware that this
1572 will also open html files inside Emacs, unless you add
1573 (\"html\" . default) to the list as well.
1574 t Default for files not matched by any of the other options.
1575 `system' The system command to open files, like `open' on Windows
1576 and Mac OS X, and mailcap under GNU/Linux. This is the command
1577 that will be selected if you call `C-c C-o' with a double
1578 `C-u C-u' prefix.
1580 Possible values for the command are:
1581 `emacs' The file will be visited by the current Emacs process.
1582 `default' Use the default application for this file type, which is the
1583 association for t in the list, most likely in the system-specific
1584 part.
1585 This can be used to overrule an unwanted setting in the
1586 system-specific variable.
1587 `system' Use the system command for opening files, like \"open\".
1588 This command is specified by the entry whose car is `system'.
1589 Most likely, the system-specific version of this variable
1590 does define this command, but you can overrule/replace it
1591 here.
1592 string A command to be executed by a shell; %s will be replaced
1593 by the path to the file.
1594 sexp A Lisp form which will be evaluated. The file path will
1595 be available in the Lisp variable `file'.
1596 For more examples, see the system specific constants
1597 `org-file-apps-defaults-macosx'
1598 `org-file-apps-defaults-windowsnt'
1599 `org-file-apps-defaults-gnu'."
1600 :group 'org-link-follow
1601 :type '(repeat
1602 (cons (choice :value ""
1603 (string :tag "Extension")
1604 (const :tag "System command to open files" system)
1605 (const :tag "Default for unrecognized files" t)
1606 (const :tag "Remote file" remote)
1607 (const :tag "Links to a directory" directory)
1608 (const :tag "Any files that have Emacs modes"
1609 auto-mode))
1610 (choice :value ""
1611 (const :tag "Visit with Emacs" emacs)
1612 (const :tag "Use default" default)
1613 (const :tag "Use the system command" system)
1614 (string :tag "Command")
1615 (sexp :tag "Lisp form")))))
1619 (defgroup org-refile nil
1620 "Options concerning refiling entries in Org-mode."
1621 :tag "Org Refile"
1622 :group 'org)
1624 (defcustom org-directory "~/org"
1625 "Directory with org files.
1626 This is just a default location to look for Org files. There is no need
1627 at all to put your files into this directory. It is only used in the
1628 following situations:
1630 1. When a remember template specifies a target file that is not an
1631 absolute path. The path will then be interpreted relative to
1632 `org-directory'
1633 2. When a remember note is filed away in an interactive way (when exiting the
1634 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1635 with `org-directory' as the default path."
1636 :group 'org-refile
1637 :group 'org-remember
1638 :type 'directory)
1640 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1641 "Default target for storing notes.
1642 Used by the hooks for remember.el. This can be a string, or nil to mean
1643 the value of `remember-data-file'.
1644 You can set this on a per-template basis with the variable
1645 `org-remember-templates'."
1646 :group 'org-refile
1647 :group 'org-remember
1648 :type '(choice
1649 (const :tag "Default from remember-data-file" nil)
1650 file))
1652 (defcustom org-goto-interface 'outline
1653 "The default interface to be used for `org-goto'.
1654 Allowed values are:
1655 outline The interface shows an outline of the relevant file
1656 and the correct heading is found by moving through
1657 the outline or by searching with incremental search.
1658 outline-path-completion Headlines in the current buffer are offered via
1659 completion. This is the interface also used by
1660 the refile command."
1661 :group 'org-refile
1662 :type '(choice
1663 (const :tag "Outline" outline)
1664 (const :tag "Outline-path-completion" outline-path-completion)))
1666 (defcustom org-goto-max-level 5
1667 "Maximum level to be considered when running org-goto with refile interface."
1668 :group 'org-refile
1669 :type 'integer)
1671 (defcustom org-reverse-note-order nil
1672 "Non-nil means store new notes at the beginning of a file or entry.
1673 When nil, new notes will be filed to the end of a file or entry.
1674 This can also be a list with cons cells of regular expressions that
1675 are matched against file names, and values."
1676 :group 'org-remember
1677 :group 'org-refile
1678 :type '(choice
1679 (const :tag "Reverse always" t)
1680 (const :tag "Reverse never" nil)
1681 (repeat :tag "By file name regexp"
1682 (cons regexp boolean))))
1684 (defcustom org-log-refile nil
1685 "Information to record when a task is refiled.
1687 Possible values are:
1689 nil Don't add anything
1690 time Add a time stamp to the task
1691 note Prompt for a note and add it with template `org-log-note-headings'
1693 This option can also be set with on a per-file-basis with
1695 #+STARTUP: nologrefile
1696 #+STARTUP: logrefile
1697 #+STARTUP: lognoterefile
1699 You can have local logging settings for a subtree by setting the LOGGING
1700 property to one or more of these keywords.
1702 When bulk-refiling from the agenda, the value `note' is forbidden and
1703 will temporarily be changed to `time'."
1704 :group 'org-refile
1705 :group 'org-progress
1706 :type '(choice
1707 (const :tag "No logging" nil)
1708 (const :tag "Record timestamp" time)
1709 (const :tag "Record timestamp with note." note)))
1711 (defcustom org-refile-targets nil
1712 "Targets for refiling entries with \\[org-refile].
1713 This is list of cons cells. Each cell contains:
1714 - a specification of the files to be considered, either a list of files,
1715 or a symbol whose function or variable value will be used to retrieve
1716 a file name or a list of file names. If you use `org-agenda-files' for
1717 that, all agenda files will be scanned for targets. Nil means consider
1718 headings in the current buffer.
1719 - A specification of how to find candidate refile targets. This may be
1720 any of:
1721 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1722 This tag has to be present in all target headlines, inheritance will
1723 not be considered.
1724 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1725 todo keyword.
1726 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1727 headlines that are refiling targets.
1728 - a cons cell (:level . N). Any headline of level N is considered a target.
1729 Note that, when `org-odd-levels-only' is set, level corresponds to
1730 order in hierarchy, not to the number of stars.
1731 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1732 Note that, when `org-odd-levels-only' is set, level corresponds to
1733 order in hierarchy, not to the number of stars.
1735 You can set the variable `org-refile-target-verify-function' to a function
1736 to verify each headline found by the simple critery above.
1738 When this variable is nil, all top-level headlines in the current buffer
1739 are used, equivalent to the value `((nil . (:level . 1))'."
1740 :group 'org-refile
1741 :type '(repeat
1742 (cons
1743 (choice :value org-agenda-files
1744 (const :tag "All agenda files" org-agenda-files)
1745 (const :tag "Current buffer" nil)
1746 (function) (variable) (file))
1747 (choice :tag "Identify target headline by"
1748 (cons :tag "Specific tag" (const :value :tag) (string))
1749 (cons :tag "TODO keyword" (const :value :todo) (string))
1750 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1751 (cons :tag "Level number" (const :value :level) (integer))
1752 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1754 (defcustom org-refile-target-verify-function nil
1755 "Function to verify if the headline at point should be a refile target.
1756 The function will be called without arguments, with point at the
1757 beginning of the headline. It should return t and leave point
1758 where it is if the headline is a valid target for refiling.
1760 If the target should not be selected, the function must return nil.
1761 In addition to this, it may move point to a place from where the search
1762 should be continued. For example, the function may decide that the entire
1763 subtree of the current entry should be excluded and move point to the end
1764 of the subtree."
1765 :group 'org-refile
1766 :type 'function)
1768 (defcustom org-refile-use-cache nil
1769 "Non-nil means cache refile targets to speed up the process.
1770 The cache for a particular file will be updated automatically when
1771 the buffer has been killed, or when any of the marker used for flagging
1772 refile targets no longer points at a live buffer.
1773 If you have added new entries to a buffer that might themselves be targets,
1774 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1775 find that easier, `C-u C-u C-u C-c C-w'."
1776 :group 'org-refile
1777 :type 'boolean)
1779 (defcustom org-refile-use-outline-path nil
1780 "Non-nil means provide refile targets as paths.
1781 So a level 3 headline will be available as level1/level2/level3.
1783 When the value is `file', also include the file name (without directory)
1784 into the path. In this case, you can also stop the completion after
1785 the file name, to get entries inserted as top level in the file.
1787 When `full-file-path', include the full file path."
1788 :group 'org-refile
1789 :type '(choice
1790 (const :tag "Not" nil)
1791 (const :tag "Yes" t)
1792 (const :tag "Start with file name" file)
1793 (const :tag "Start with full file path" full-file-path)))
1795 (defcustom org-outline-path-complete-in-steps t
1796 "Non-nil means complete the outline path in hierarchical steps.
1797 When Org-mode uses the refile interface to select an outline path
1798 \(see variable `org-refile-use-outline-path'), the completion of
1799 the path can be done is a single go, or if can be done in steps down
1800 the headline hierarchy. Going in steps is probably the best if you
1801 do not use a special completion package like `ido' or `icicles'.
1802 However, when using these packages, going in one step can be very
1803 fast, while still showing the whole path to the entry."
1804 :group 'org-refile
1805 :type 'boolean)
1807 (defcustom org-refile-allow-creating-parent-nodes nil
1808 "Non-nil means allow to create new nodes as refile targets.
1809 New nodes are then created by adding \"/new node name\" to the completion
1810 of an existing node. When the value of this variable is `confirm',
1811 new node creation must be confirmed by the user (recommended)
1812 When nil, the completion must match an existing entry.
1814 Note that, if the new heading is not seen by the criteria
1815 listed in `org-refile-targets', multiple instances of the same
1816 heading would be created by trying again to file under the new
1817 heading."
1818 :group 'org-refile
1819 :type '(choice
1820 (const :tag "Never" nil)
1821 (const :tag "Always" t)
1822 (const :tag "Prompt for confirmation" confirm)))
1824 (defgroup org-todo nil
1825 "Options concerning TODO items in Org-mode."
1826 :tag "Org TODO"
1827 :group 'org)
1829 (defgroup org-progress nil
1830 "Options concerning Progress logging in Org-mode."
1831 :tag "Org Progress"
1832 :group 'org-time)
1834 (defvar org-todo-interpretation-widgets
1836 (:tag "Sequence (cycling hits every state)" sequence)
1837 (:tag "Type (cycling directly to DONE)" type))
1838 "The available interpretation symbols for customizing
1839 `org-todo-keywords'.
1840 Interested libraries should add to this list.")
1842 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1843 "List of TODO entry keyword sequences and their interpretation.
1844 \\<org-mode-map>This is a list of sequences.
1846 Each sequence starts with a symbol, either `sequence' or `type',
1847 indicating if the keywords should be interpreted as a sequence of
1848 action steps, or as different types of TODO items. The first
1849 keywords are states requiring action - these states will select a headline
1850 for inclusion into the global TODO list Org-mode produces. If one of
1851 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1852 signify that no further action is necessary. If \"|\" is not found,
1853 the last keyword is treated as the only DONE state of the sequence.
1855 The command \\[org-todo] cycles an entry through these states, and one
1856 additional state where no keyword is present. For details about this
1857 cycling, see the manual.
1859 TODO keywords and interpretation can also be set on a per-file basis with
1860 the special #+SEQ_TODO and #+TYP_TODO lines.
1862 Each keyword can optionally specify a character for fast state selection
1863 \(in combination with the variable `org-use-fast-todo-selection')
1864 and specifiers for state change logging, using the same syntax
1865 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1866 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1867 indicates to record a time stamp each time this state is selected.
1869 Each keyword may also specify if a timestamp or a note should be
1870 recorded when entering or leaving the state, by adding additional
1871 characters in the parenthesis after the keyword. This looks like this:
1872 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1873 record only the time of the state change. With X and Y being either
1874 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1875 Y when leaving the state if and only if the *target* state does not
1876 define X. You may omit any of the fast-selection key or X or /Y,
1877 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1879 For backward compatibility, this variable may also be just a list
1880 of keywords - in this case the interpretation (sequence or type) will be
1881 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1882 :group 'org-todo
1883 :group 'org-keywords
1884 :type '(choice
1885 (repeat :tag "Old syntax, just keywords"
1886 (string :tag "Keyword"))
1887 (repeat :tag "New syntax"
1888 (cons
1889 (choice
1890 :tag "Interpretation"
1891 ;;Quick and dirty way to see
1892 ;;`org-todo-interpretations'. This takes the
1893 ;;place of item arguments
1894 :convert-widget
1895 (lambda (widget)
1896 (widget-put widget
1897 :args (mapcar
1898 #'(lambda (x)
1899 (widget-convert
1900 (cons 'const x)))
1901 org-todo-interpretation-widgets))
1902 widget))
1903 (repeat
1904 (string :tag "Keyword"))))))
1906 (defvar org-todo-keywords-1 nil
1907 "All TODO and DONE keywords active in a buffer.")
1908 (make-variable-buffer-local 'org-todo-keywords-1)
1909 (defvar org-todo-keywords-for-agenda nil)
1910 (defvar org-done-keywords-for-agenda nil)
1911 (defvar org-drawers-for-agenda nil)
1912 (defvar org-todo-keyword-alist-for-agenda nil)
1913 (defvar org-tag-alist-for-agenda nil)
1914 (defvar org-agenda-contributing-files nil)
1915 (defvar org-not-done-keywords nil)
1916 (make-variable-buffer-local 'org-not-done-keywords)
1917 (defvar org-done-keywords nil)
1918 (make-variable-buffer-local 'org-done-keywords)
1919 (defvar org-todo-heads nil)
1920 (make-variable-buffer-local 'org-todo-heads)
1921 (defvar org-todo-sets nil)
1922 (make-variable-buffer-local 'org-todo-sets)
1923 (defvar org-todo-log-states nil)
1924 (make-variable-buffer-local 'org-todo-log-states)
1925 (defvar org-todo-kwd-alist nil)
1926 (make-variable-buffer-local 'org-todo-kwd-alist)
1927 (defvar org-todo-key-alist nil)
1928 (make-variable-buffer-local 'org-todo-key-alist)
1929 (defvar org-todo-key-trigger nil)
1930 (make-variable-buffer-local 'org-todo-key-trigger)
1932 (defcustom org-todo-interpretation 'sequence
1933 "Controls how TODO keywords are interpreted.
1934 This variable is in principle obsolete and is only used for
1935 backward compatibility, if the interpretation of todo keywords is
1936 not given already in `org-todo-keywords'. See that variable for
1937 more information."
1938 :group 'org-todo
1939 :group 'org-keywords
1940 :type '(choice (const sequence)
1941 (const type)))
1943 (defcustom org-use-fast-todo-selection t
1944 "Non-nil means use the fast todo selection scheme with C-c C-t.
1945 This variable describes if and under what circumstances the cycling
1946 mechanism for TODO keywords will be replaced by a single-key, direct
1947 selection scheme.
1949 When nil, fast selection is never used.
1951 When the symbol `prefix', it will be used when `org-todo' is called with
1952 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1953 in an agenda buffer.
1955 When t, fast selection is used by default. In this case, the prefix
1956 argument forces cycling instead.
1958 In all cases, the special interface is only used if access keys have actually
1959 been assigned by the user, i.e. if keywords in the configuration are followed
1960 by a letter in parenthesis, like TODO(t)."
1961 :group 'org-todo
1962 :type '(choice
1963 (const :tag "Never" nil)
1964 (const :tag "By default" t)
1965 (const :tag "Only with C-u C-c C-t" prefix)))
1967 (defcustom org-provide-todo-statistics t
1968 "Non-nil means update todo statistics after insert and toggle.
1969 ALL-HEADLINES means update todo statistics by including headlines
1970 with no TODO keyword as well, counting them as not done.
1971 A list of TODO keywords means the same, but skip keywords that are
1972 not in this list.
1974 When this is set, todo statistics is updated in the parent of the
1975 current entry each time a todo state is changed."
1976 :group 'org-todo
1977 :type '(choice
1978 (const :tag "Yes, only for TODO entries" t)
1979 (const :tag "Yes, including all entries" 'all-headlines)
1980 (repeat :tag "Yes, for TODOs in this list"
1981 (string :tag "TODO keyword"))
1982 (other :tag "No TODO statistics" nil)))
1984 (defcustom org-hierarchical-todo-statistics t
1985 "Non-nil means TODO statistics covers just direct children.
1986 When nil, all entries in the subtree are considered.
1987 This has only an effect if `org-provide-todo-statistics' is set.
1988 To set this to nil for only a single subtree, use a COOKIE_DATA
1989 property and include the word \"recursive\" into the value."
1990 :group 'org-todo
1991 :type 'boolean)
1993 (defcustom org-after-todo-state-change-hook nil
1994 "Hook which is run after the state of a TODO item was changed.
1995 The new state (a string with a TODO keyword, or nil) is available in the
1996 Lisp variable `state'."
1997 :group 'org-todo
1998 :type 'hook)
2000 (defvar org-blocker-hook nil
2001 "Hook for functions that are allowed to block a state change.
2003 Each function gets as its single argument a property list, see
2004 `org-trigger-hook' for more information about this list.
2006 If any of the functions in this hook returns nil, the state change
2007 is blocked.")
2009 (defvar org-trigger-hook nil
2010 "Hook for functions that are triggered by a state change.
2012 Each function gets as its single argument a property list with at least
2013 the following elements:
2015 (:type type-of-change :position pos-at-entry-start
2016 :from old-state :to new-state)
2018 Depending on the type, more properties may be present.
2020 This mechanism is currently implemented for:
2022 TODO state changes
2023 ------------------
2024 :type todo-state-change
2025 :from previous state (keyword as a string), or nil, or a symbol
2026 'todo' or 'done', to indicate the general type of state.
2027 :to new state, like in :from")
2029 (defcustom org-enforce-todo-dependencies nil
2030 "Non-nil means undone TODO entries will block switching the parent to DONE.
2031 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2032 be blocked if any prior sibling is not yet done.
2033 Finally, if the parent is blocked because of ordered siblings of its own,
2034 the child will also be blocked.
2035 This variable needs to be set before org.el is loaded, and you need to
2036 restart Emacs after a change to make the change effective. The only way
2037 to change is while Emacs is running is through the customize interface."
2038 :set (lambda (var val)
2039 (set var val)
2040 (if val
2041 (add-hook 'org-blocker-hook
2042 'org-block-todo-from-children-or-siblings-or-parent)
2043 (remove-hook 'org-blocker-hook
2044 'org-block-todo-from-children-or-siblings-or-parent)))
2045 :group 'org-todo
2046 :type 'boolean)
2048 (defcustom org-enforce-todo-checkbox-dependencies nil
2049 "Non-nil means unchecked boxes will block switching the parent to DONE.
2050 When this is nil, checkboxes have no influence on switching TODO states.
2051 When non-nil, you first need to check off all check boxes before the TODO
2052 entry can be switched to DONE.
2053 This variable needs to be set before org.el is loaded, and you need to
2054 restart Emacs after a change to make the change effective. The only way
2055 to change is while Emacs is running is through the customize interface."
2056 :set (lambda (var val)
2057 (set var val)
2058 (if val
2059 (add-hook 'org-blocker-hook
2060 'org-block-todo-from-checkboxes)
2061 (remove-hook 'org-blocker-hook
2062 'org-block-todo-from-checkboxes)))
2063 :group 'org-todo
2064 :type 'boolean)
2066 (defcustom org-treat-insert-todo-heading-as-state-change nil
2067 "Non-nil means inserting a TODO heading is treated as state change.
2068 So when the command \\[org-insert-todo-heading] is used, state change
2069 logging will apply if appropriate. When nil, the new TODO item will
2070 be inserted directly, and no logging will take place."
2071 :group 'org-todo
2072 :type 'boolean)
2074 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2075 "Non-nil means switching TODO states with S-cursor counts as state change.
2076 This is the default behavior. However, setting this to nil allows a
2077 convenient way to select a TODO state and bypass any logging associated
2078 with that."
2079 :group 'org-todo
2080 :type 'boolean)
2082 (defcustom org-todo-state-tags-triggers nil
2083 "Tag changes that should be triggered by TODO state changes.
2084 This is a list. Each entry is
2086 (state-change (tag . flag) .......)
2088 State-change can be a string with a state, and empty string to indicate the
2089 state that has no TODO keyword, or it can be one of the symbols `todo'
2090 or `done', meaning any not-done or done state, respectively."
2091 :group 'org-todo
2092 :group 'org-tags
2093 :type '(repeat
2094 (cons (choice :tag "When changing to"
2095 (const :tag "Not-done state" todo)
2096 (const :tag "Done state" done)
2097 (string :tag "State"))
2098 (repeat
2099 (cons :tag "Tag action"
2100 (string :tag "Tag")
2101 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2103 (defcustom org-log-done nil
2104 "Information to record when a task moves to the DONE state.
2106 Possible values are:
2108 nil Don't add anything, just change the keyword
2109 time Add a time stamp to the task
2110 note Prompt for a note and add it with template `org-log-note-headings'
2112 This option can also be set with on a per-file-basis with
2114 #+STARTUP: nologdone
2115 #+STARTUP: logdone
2116 #+STARTUP: lognotedone
2118 You can have local logging settings for a subtree by setting the LOGGING
2119 property to one or more of these keywords."
2120 :group 'org-todo
2121 :group 'org-progress
2122 :type '(choice
2123 (const :tag "No logging" nil)
2124 (const :tag "Record CLOSED timestamp" time)
2125 (const :tag "Record CLOSED timestamp with note." note)))
2127 ;; Normalize old uses of org-log-done.
2128 (cond
2129 ((eq org-log-done t) (setq org-log-done 'time))
2130 ((and (listp org-log-done) (memq 'done org-log-done))
2131 (setq org-log-done 'note)))
2133 (defcustom org-log-reschedule nil
2134 "Information to record when the scheduling date of a tasks is modified.
2136 Possible values are:
2138 nil Don't add anything, just change the date
2139 time Add a time stamp to the task
2140 note Prompt for a note and add it with template `org-log-note-headings'
2142 This option can also be set with on a per-file-basis with
2144 #+STARTUP: nologreschedule
2145 #+STARTUP: logreschedule
2146 #+STARTUP: lognotereschedule"
2147 :group 'org-todo
2148 :group 'org-progress
2149 :type '(choice
2150 (const :tag "No logging" nil)
2151 (const :tag "Record timestamp" time)
2152 (const :tag "Record timestamp with note." note)))
2154 (defcustom org-log-redeadline nil
2155 "Information to record when the deadline date of a tasks is modified.
2157 Possible values are:
2159 nil Don't add anything, just change the date
2160 time Add a time stamp to the task
2161 note Prompt for a note and add it with template `org-log-note-headings'
2163 This option can also be set with on a per-file-basis with
2165 #+STARTUP: nologredeadline
2166 #+STARTUP: logredeadline
2167 #+STARTUP: lognoteredeadline
2169 You can have local logging settings for a subtree by setting the LOGGING
2170 property to one or more of these keywords."
2171 :group 'org-todo
2172 :group 'org-progress
2173 :type '(choice
2174 (const :tag "No logging" nil)
2175 (const :tag "Record timestamp" time)
2176 (const :tag "Record timestamp with note." note)))
2178 (defcustom org-log-note-clock-out nil
2179 "Non-nil means record a note when clocking out of an item.
2180 This can also be configured on a per-file basis by adding one of
2181 the following lines anywhere in the buffer:
2183 #+STARTUP: lognoteclock-out
2184 #+STARTUP: nolognoteclock-out"
2185 :group 'org-todo
2186 :group 'org-progress
2187 :type 'boolean)
2189 (defcustom org-log-done-with-time t
2190 "Non-nil means the CLOSED time stamp will contain date and time.
2191 When nil, only the date will be recorded."
2192 :group 'org-progress
2193 :type 'boolean)
2195 (defcustom org-log-note-headings
2196 '((done . "CLOSING NOTE %t")
2197 (state . "State %-12s from %-12S %t")
2198 (note . "Note taken on %t")
2199 (reschedule . "Rescheduled from %S on %t")
2200 (delschedule . "Not scheduled, was %S on %t")
2201 (redeadline . "New deadline from %S on %t")
2202 (deldeadline . "Removed deadline, was %S on %t")
2203 (refile . "Refiled on %t")
2204 (clock-out . ""))
2205 "Headings for notes added to entries.
2206 The value is an alist, with the car being a symbol indicating the note
2207 context, and the cdr is the heading to be used. The heading may also be the
2208 empty string.
2209 %t in the heading will be replaced by a time stamp.
2210 %T will be an acive time stamp instead the default inacive one
2211 %s will be replaced by the new TODO state, in double quotes.
2212 %S will be replaced by the old TODO state, in double quotes.
2213 %u will be replaced by the user name.
2214 %U will be replaced by the full user name.
2216 In fact, it is not a good idea to change the `state' entry, because
2217 agenda log mode depends on the format of these entries."
2218 :group 'org-todo
2219 :group 'org-progress
2220 :type '(list :greedy t
2221 (cons (const :tag "Heading when closing an item" done) string)
2222 (cons (const :tag
2223 "Heading when changing todo state (todo sequence only)"
2224 state) string)
2225 (cons (const :tag "Heading when just taking a note" note) string)
2226 (cons (const :tag "Heading when clocking out" clock-out) string)
2227 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2228 (cons (const :tag "Heading when rescheduling" reschedule) string)
2229 (cons (const :tag "Heading when changing deadline" redeadline) string)
2230 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2231 (cons (const :tag "Heading when refiling" refile) string)))
2233 (unless (assq 'note org-log-note-headings)
2234 (push '(note . "%t") org-log-note-headings))
2236 (defcustom org-log-into-drawer nil
2237 "Non-nil means insert state change notes and time stamps into a drawer.
2238 When nil, state changes notes will be inserted after the headline and
2239 any scheduling and clock lines, but not inside a drawer.
2241 The value of this variable should be the name of the drawer to use.
2242 LOGBOOK is proposed at the default drawer for this purpose, you can
2243 also set this to a string to define the drawer of your choice.
2245 A value of t is also allowed, representing \"LOGBOOK\".
2247 If this variable is set, `org-log-state-notes-insert-after-drawers'
2248 will be ignored.
2250 You can set the property LOG_INTO_DRAWER to overrule this setting for
2251 a subtree."
2252 :group 'org-todo
2253 :group 'org-progress
2254 :type '(choice
2255 (const :tag "Not into a drawer" nil)
2256 (const :tag "LOGBOOK" t)
2257 (string :tag "Other")))
2259 (if (fboundp 'defvaralias)
2260 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2262 (defun org-log-into-drawer ()
2263 "Return the value of `org-log-into-drawer', but let properties overrule.
2264 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2265 used instead of the default value."
2266 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2267 (cond
2268 ((or (not p) (equal p "nil")) org-log-into-drawer)
2269 ((equal p "t") "LOGBOOK")
2270 (t p))))
2272 (defcustom org-log-state-notes-insert-after-drawers nil
2273 "Non-nil means insert state change notes after any drawers in entry.
2274 Only the drawers that *immediately* follow the headline and the
2275 deadline/scheduled line are skipped.
2276 When nil, insert notes right after the heading and perhaps the line
2277 with deadline/scheduling if present.
2279 This variable will have no effect if `org-log-into-drawer' is
2280 set."
2281 :group 'org-todo
2282 :group 'org-progress
2283 :type 'boolean)
2285 (defcustom org-log-states-order-reversed t
2286 "Non-nil means the latest state note will be directly after heading.
2287 When nil, the state change notes will be ordered according to time."
2288 :group 'org-todo
2289 :group 'org-progress
2290 :type 'boolean)
2292 (defcustom org-todo-repeat-to-state nil
2293 "The TODO state to which a repeater should return the repeating task.
2294 By default this is the first task in a TODO sequence, or the previous state
2295 in a TODO_TYP set. But you can specify another task here.
2296 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2297 :group 'org-todo
2298 :type '(choice (const :tag "Head of sequence" nil)
2299 (string :tag "Specific state")))
2301 (defcustom org-log-repeat 'time
2302 "Non-nil means record moving through the DONE state when triggering repeat.
2303 An auto-repeating task is immediately switched back to TODO when
2304 marked DONE. If you are not logging state changes (by adding \"@\"
2305 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2306 record a closing note, there will be no record of the task moving
2307 through DONE. This variable forces taking a note anyway.
2309 nil Don't force a record
2310 time Record a time stamp
2311 note Record a note
2313 This option can also be set with on a per-file-basis with
2315 #+STARTUP: logrepeat
2316 #+STARTUP: lognoterepeat
2317 #+STARTUP: nologrepeat
2319 You can have local logging settings for a subtree by setting the LOGGING
2320 property to one or more of these keywords."
2321 :group 'org-todo
2322 :group 'org-progress
2323 :type '(choice
2324 (const :tag "Don't force a record" nil)
2325 (const :tag "Force recording the DONE state" time)
2326 (const :tag "Force recording a note with the DONE state" note)))
2329 (defgroup org-priorities nil
2330 "Priorities in Org-mode."
2331 :tag "Org Priorities"
2332 :group 'org-todo)
2334 (defcustom org-enable-priority-commands t
2335 "Non-nil means priority commands are active.
2336 When nil, these commands will be disabled, so that you never accidentally
2337 set a priority."
2338 :group 'org-priorities
2339 :type 'boolean)
2341 (defcustom org-highest-priority ?A
2342 "The highest priority of TODO items. A character like ?A, ?B etc.
2343 Must have a smaller ASCII number than `org-lowest-priority'."
2344 :group 'org-priorities
2345 :type 'character)
2347 (defcustom org-lowest-priority ?C
2348 "The lowest priority of TODO items. A character like ?A, ?B etc.
2349 Must have a larger ASCII number than `org-highest-priority'."
2350 :group 'org-priorities
2351 :type 'character)
2353 (defcustom org-default-priority ?B
2354 "The default priority of TODO items.
2355 This is the priority an item get if no explicit priority is given."
2356 :group 'org-priorities
2357 :type 'character)
2359 (defcustom org-priority-start-cycle-with-default t
2360 "Non-nil means start with default priority when starting to cycle.
2361 When this is nil, the first step in the cycle will be (depending on the
2362 command used) one higher or lower that the default priority."
2363 :group 'org-priorities
2364 :type 'boolean)
2366 (defgroup org-time nil
2367 "Options concerning time stamps and deadlines in Org-mode."
2368 :tag "Org Time"
2369 :group 'org)
2371 (defcustom org-insert-labeled-timestamps-at-point nil
2372 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2373 When nil, these labeled time stamps are forces into the second line of an
2374 entry, just after the headline. When scheduling from the global TODO list,
2375 the time stamp will always be forced into the second line."
2376 :group 'org-time
2377 :type 'boolean)
2379 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2380 "Formats for `format-time-string' which are used for time stamps.
2381 It is not recommended to change this constant.")
2383 (defcustom org-time-stamp-rounding-minutes '(0 5)
2384 "Number of minutes to round time stamps to.
2385 These are two values, the first applies when first creating a time stamp.
2386 The second applies when changing it with the commands `S-up' and `S-down'.
2387 When changing the time stamp, this means that it will change in steps
2388 of N minutes, as given by the second value.
2390 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2391 numbers should be factors of 60, so for example 5, 10, 15.
2393 When this is larger than 1, you can still force an exact time-stamp by using
2394 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2395 and by using a prefix arg to `S-up/down' to specify the exact number
2396 of minutes to shift."
2397 :group 'org-time
2398 :get '(lambda (var) ; Make sure both elements are there
2399 (if (integerp (default-value var))
2400 (list (default-value var) 5)
2401 (default-value var)))
2402 :type '(list
2403 (integer :tag "when inserting times")
2404 (integer :tag "when modifying times")))
2406 ;; Normalize old customizations of this variable.
2407 (when (integerp org-time-stamp-rounding-minutes)
2408 (setq org-time-stamp-rounding-minutes
2409 (list org-time-stamp-rounding-minutes
2410 org-time-stamp-rounding-minutes)))
2412 (defcustom org-display-custom-times nil
2413 "Non-nil means overlay custom formats over all time stamps.
2414 The formats are defined through the variable `org-time-stamp-custom-formats'.
2415 To turn this on on a per-file basis, insert anywhere in the file:
2416 #+STARTUP: customtime"
2417 :group 'org-time
2418 :set 'set-default
2419 :type 'sexp)
2420 (make-variable-buffer-local 'org-display-custom-times)
2422 (defcustom org-time-stamp-custom-formats
2423 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2424 "Custom formats for time stamps. See `format-time-string' for the syntax.
2425 These are overlayed over the default ISO format if the variable
2426 `org-display-custom-times' is set. Time like %H:%M should be at the
2427 end of the second format. The custom formats are also honored by export
2428 commands, if custom time display is turned on at the time of export."
2429 :group 'org-time
2430 :type 'sexp)
2432 (defun org-time-stamp-format (&optional long inactive)
2433 "Get the right format for a time string."
2434 (let ((f (if long (cdr org-time-stamp-formats)
2435 (car org-time-stamp-formats))))
2436 (if inactive
2437 (concat "[" (substring f 1 -1) "]")
2438 f)))
2440 (defcustom org-time-clocksum-format "%d:%02d"
2441 "The format string used when creating CLOCKSUM lines, or when
2442 org-mode generates a time duration."
2443 :group 'org-time
2444 :type 'string)
2446 (defcustom org-time-clocksum-use-fractional nil
2447 "If non-nil, \\[org-clock-display] uses fractional times.
2448 org-mode generates a time duration."
2449 :group 'org-time
2450 :type 'boolean)
2452 (defcustom org-time-clocksum-fractional-format "%.2f"
2453 "The format string used when creating CLOCKSUM lines, or when
2454 org-mode generates a time duration."
2455 :group 'org-time
2456 :type 'string)
2458 (defcustom org-deadline-warning-days 14
2459 "No. of days before expiration during which a deadline becomes active.
2460 This variable governs the display in sparse trees and in the agenda.
2461 When 0 or negative, it means use this number (the absolute value of it)
2462 even if a deadline has a different individual lead time specified.
2464 Custom commands can set this variable in the options section."
2465 :group 'org-time
2466 :group 'org-agenda-daily/weekly
2467 :type 'integer)
2469 (defcustom org-read-date-prefer-future t
2470 "Non-nil means assume future for incomplete date input from user.
2471 This affects the following situations:
2472 1. The user gives a month but not a year.
2473 For example, if it is april and you enter \"feb 2\", this will be read
2474 as feb 2, *next* year. \"May 5\", however, will be this year.
2475 2. The user gives a day, but no month.
2476 For example, if today is the 15th, and you enter \"3\", Org-mode will
2477 read this as the third of *next* month. However, if you enter \"17\",
2478 it will be considered as *this* month.
2480 If you set this variable to the symbol `time', then also the following
2481 will work:
2483 3. If the user gives a time, but no day. If the time is before now,
2484 to will be interpreted as tomorrow.
2486 Currently none of this works for ISO week specifications.
2488 When this option is nil, the current day, month and year will always be
2489 used as defaults."
2490 :group 'org-time
2491 :type '(choice
2492 (const :tag "Never" nil)
2493 (const :tag "Check month and day" t)
2494 (const :tag "Check month, day, and time" time)))
2496 (defcustom org-read-date-display-live t
2497 "Non-nil means display current interpretation of date prompt live.
2498 This display will be in an overlay, in the minibuffer."
2499 :group 'org-time
2500 :type 'boolean)
2502 (defcustom org-read-date-popup-calendar t
2503 "Non-nil means pop up a calendar when prompting for a date.
2504 In the calendar, the date can be selected with mouse-1. However, the
2505 minibuffer will also be active, and you can simply enter the date as well.
2506 When nil, only the minibuffer will be available."
2507 :group 'org-time
2508 :type 'boolean)
2509 (if (fboundp 'defvaralias)
2510 (defvaralias 'org-popup-calendar-for-date-prompt
2511 'org-read-date-popup-calendar))
2513 (defcustom org-read-date-minibuffer-setup-hook nil
2514 "Hook to be used to set up keys for the date/time interface.
2515 Add key definitions to `minibuffer-local-map', which will be a temporary
2516 copy."
2517 :group 'org-time
2518 :type 'hook)
2520 (defcustom org-extend-today-until 0
2521 "The hour when your day really ends. Must be an integer.
2522 This has influence for the following applications:
2523 - When switching the agenda to \"today\". It it is still earlier than
2524 the time given here, the day recognized as TODAY is actually yesterday.
2525 - When a date is read from the user and it is still before the time given
2526 here, the current date and time will be assumed to be yesterday, 23:59.
2527 Also, timestamps inserted in remember templates follow this rule.
2529 IMPORTANT: This is a feature whose implementation is and likely will
2530 remain incomplete. Really, it is only here because past midnight seems to
2531 be the favorite working time of John Wiegley :-)"
2532 :group 'org-time
2533 :type 'integer)
2535 (defcustom org-edit-timestamp-down-means-later nil
2536 "Non-nil means S-down will increase the time in a time stamp.
2537 When nil, S-up will increase."
2538 :group 'org-time
2539 :type 'boolean)
2541 (defcustom org-calendar-follow-timestamp-change t
2542 "Non-nil means make the calendar window follow timestamp changes.
2543 When a timestamp is modified and the calendar window is visible, it will be
2544 moved to the new date."
2545 :group 'org-time
2546 :type 'boolean)
2548 (defgroup org-tags nil
2549 "Options concerning tags in Org-mode."
2550 :tag "Org Tags"
2551 :group 'org)
2553 (defcustom org-tag-alist nil
2554 "List of tags allowed in Org-mode files.
2555 When this list is nil, Org-mode will base TAG input on what is already in the
2556 buffer.
2557 The value of this variable is an alist, the car of each entry must be a
2558 keyword as a string, the cdr may be a character that is used to select
2559 that tag through the fast-tag-selection interface.
2560 See the manual for details."
2561 :group 'org-tags
2562 :type '(repeat
2563 (choice
2564 (cons (string :tag "Tag name")
2565 (character :tag "Access char"))
2566 (list :tag "Start radio group"
2567 (const :startgroup)
2568 (option (string :tag "Group description")))
2569 (list :tag "End radio group"
2570 (const :endgroup)
2571 (option (string :tag "Group description")))
2572 (const :tag "New line" (:newline)))))
2574 (defcustom org-tag-persistent-alist nil
2575 "List of tags that will always appear in all Org-mode files.
2576 This is in addition to any in buffer settings or customizations
2577 of `org-tag-alist'.
2578 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2579 The value of this variable is an alist, the car of each entry must be a
2580 keyword as a string, the cdr may be a character that is used to select
2581 that tag through the fast-tag-selection interface.
2582 See the manual for details.
2583 To disable these tags on a per-file basis, insert anywhere in the file:
2584 #+STARTUP: noptag"
2585 :group 'org-tags
2586 :type '(repeat
2587 (choice
2588 (cons (string :tag "Tag name")
2589 (character :tag "Access char"))
2590 (const :tag "Start radio group" (:startgroup))
2591 (const :tag "End radio group" (:endgroup))
2592 (const :tag "New line" (:newline)))))
2594 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2595 "If non-nil, always offer completion for all tags of all agenda files.
2596 Instead of customizing this variable directly, you might want to
2597 set it locally for remember buffers, because there no list of
2598 tags in that file can be created dynamically (there are none).
2600 (add-hook 'org-remember-mode-hook
2601 (lambda ()
2602 (set (make-local-variable
2603 'org-complete-tags-always-offer-all-agenda-tags)
2604 t)))"
2605 :group 'org-tags
2606 :type 'boolean)
2608 (defvar org-file-tags nil
2609 "List of tags that can be inherited by all entries in the file.
2610 The tags will be inherited if the variable `org-use-tag-inheritance'
2611 says they should be.
2612 This variable is populated from #+FILETAGS lines.")
2614 (defcustom org-use-fast-tag-selection 'auto
2615 "Non-nil means use fast tag selection scheme.
2616 This is a special interface to select and deselect tags with single keys.
2617 When nil, fast selection is never used.
2618 When the symbol `auto', fast selection is used if and only if selection
2619 characters for tags have been configured, either through the variable
2620 `org-tag-alist' or through a #+TAGS line in the buffer.
2621 When t, fast selection is always used and selection keys are assigned
2622 automatically if necessary."
2623 :group 'org-tags
2624 :type '(choice
2625 (const :tag "Always" t)
2626 (const :tag "Never" nil)
2627 (const :tag "When selection characters are configured" 'auto)))
2629 (defcustom org-fast-tag-selection-single-key nil
2630 "Non-nil means fast tag selection exits after first change.
2631 When nil, you have to press RET to exit it.
2632 During fast tag selection, you can toggle this flag with `C-c'.
2633 This variable can also have the value `expert'. In this case, the window
2634 displaying the tags menu is not even shown, until you press C-c again."
2635 :group 'org-tags
2636 :type '(choice
2637 (const :tag "No" nil)
2638 (const :tag "Yes" t)
2639 (const :tag "Expert" expert)))
2641 (defvar org-fast-tag-selection-include-todo nil
2642 "Non-nil means fast tags selection interface will also offer TODO states.
2643 This is an undocumented feature, you should not rely on it.")
2645 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2646 "The column to which tags should be indented in a headline.
2647 If this number is positive, it specifies the column. If it is negative,
2648 it means that the tags should be flushright to that column. For example,
2649 -80 works well for a normal 80 character screen."
2650 :group 'org-tags
2651 :type 'integer)
2653 (defcustom org-auto-align-tags t
2654 "Non-nil means realign tags after pro/demotion of TODO state change.
2655 These operations change the length of a headline and therefore shift
2656 the tags around. With this options turned on, after each such operation
2657 the tags are again aligned to `org-tags-column'."
2658 :group 'org-tags
2659 :type 'boolean)
2661 (defcustom org-use-tag-inheritance t
2662 "Non-nil means tags in levels apply also for sublevels.
2663 When nil, only the tags directly given in a specific line apply there.
2664 This may also be a list of tags that should be inherited, or a regexp that
2665 matches tags that should be inherited. Additional control is possible
2666 with the variable `org-tags-exclude-from-inheritance' which gives an
2667 explicit list of tags to be excluded from inheritance., even if the value of
2668 `org-use-tag-inheritance' would select it for inheritance.
2670 If this option is t, a match early-on in a tree can lead to a large
2671 number of matches in the subtree when constructing the agenda or creating
2672 a sparse tree. If you only want to see the first match in a tree during
2673 a search, check out the variable `org-tags-match-list-sublevels'."
2674 :group 'org-tags
2675 :type '(choice
2676 (const :tag "Not" nil)
2677 (const :tag "Always" t)
2678 (repeat :tag "Specific tags" (string :tag "Tag"))
2679 (regexp :tag "Tags matched by regexp")))
2681 (defcustom org-tags-exclude-from-inheritance nil
2682 "List of tags that should never be inherited.
2683 This is a way to exclude a few tags from inheritance. For way to do
2684 the opposite, to actively allow inheritance for selected tags,
2685 see the variable `org-use-tag-inheritance'."
2686 :group 'org-tags
2687 :type '(repeat (string :tag "Tag")))
2689 (defun org-tag-inherit-p (tag)
2690 "Check if TAG is one that should be inherited."
2691 (cond
2692 ((member tag org-tags-exclude-from-inheritance) nil)
2693 ((eq org-use-tag-inheritance t) t)
2694 ((not org-use-tag-inheritance) nil)
2695 ((stringp org-use-tag-inheritance)
2696 (string-match org-use-tag-inheritance tag))
2697 ((listp org-use-tag-inheritance)
2698 (member tag org-use-tag-inheritance))
2699 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2701 (defcustom org-tags-match-list-sublevels t
2702 "Non-nil means list also sublevels of headlines matching a search.
2703 This variable applies to tags/property searches, and also to stuck
2704 projects because this search is based on a tags match as well.
2706 When set to the symbol `indented', sublevels are indented with
2707 leading dots.
2709 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2710 the sublevels of a headline matching a tag search often also match
2711 the same search. Listing all of them can create very long lists.
2712 Setting this variable to nil causes subtrees of a match to be skipped.
2714 This variable is semi-obsolete and probably should always be true. It
2715 is better to limit inheritance to certain tags using the variables
2716 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2717 :group 'org-tags
2718 :type '(choice
2719 (const :tag "No, don't list them" nil)
2720 (const :tag "Yes, do list them" t)
2721 (const :tag "List them, indented with leading dots" indented)))
2723 (defcustom org-tags-sort-function nil
2724 "When set, tags are sorted using this function as a comparator"
2725 :group 'org-tags
2726 :type '(choice
2727 (const :tag "No sorting" nil)
2728 (const :tag "Alphabetical" string<)
2729 (const :tag "Reverse alphabetical" string>)
2730 (function :tag "Custom function" nil)))
2732 (defvar org-tags-history nil
2733 "History of minibuffer reads for tags.")
2734 (defvar org-last-tags-completion-table nil
2735 "The last used completion table for tags.")
2736 (defvar org-after-tags-change-hook nil
2737 "Hook that is run after the tags in a line have changed.")
2739 (defgroup org-properties nil
2740 "Options concerning properties in Org-mode."
2741 :tag "Org Properties"
2742 :group 'org)
2744 (defcustom org-property-format "%-10s %s"
2745 "How property key/value pairs should be formatted by `indent-line'.
2746 When `indent-line' hits a property definition, it will format the line
2747 according to this format, mainly to make sure that the values are
2748 lined-up with respect to each other."
2749 :group 'org-properties
2750 :type 'string)
2752 (defcustom org-use-property-inheritance nil
2753 "Non-nil means properties apply also for sublevels.
2755 This setting is chiefly used during property searches. Turning it on can
2756 cause significant overhead when doing a search, which is why it is not
2757 on by default.
2759 When nil, only the properties directly given in the current entry count.
2760 When t, every property is inherited. The value may also be a list of
2761 properties that should have inheritance, or a regular expression matching
2762 properties that should be inherited.
2764 However, note that some special properties use inheritance under special
2765 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2766 and the properties ending in \"_ALL\" when they are used as descriptor
2767 for valid values of a property.
2769 Note for programmers:
2770 When querying an entry with `org-entry-get', you can control if inheritance
2771 should be used. By default, `org-entry-get' looks only at the local
2772 properties. You can request inheritance by setting the inherit argument
2773 to t (to force inheritance) or to `selective' (to respect the setting
2774 in this variable)."
2775 :group 'org-properties
2776 :type '(choice
2777 (const :tag "Not" nil)
2778 (const :tag "Always" t)
2779 (repeat :tag "Specific properties" (string :tag "Property"))
2780 (regexp :tag "Properties matched by regexp")))
2782 (defun org-property-inherit-p (property)
2783 "Check if PROPERTY is one that should be inherited."
2784 (cond
2785 ((eq org-use-property-inheritance t) t)
2786 ((not org-use-property-inheritance) nil)
2787 ((stringp org-use-property-inheritance)
2788 (string-match org-use-property-inheritance property))
2789 ((listp org-use-property-inheritance)
2790 (member property org-use-property-inheritance))
2791 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2793 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2794 "The default column format, if no other format has been defined.
2795 This variable can be set on the per-file basis by inserting a line
2797 #+COLUMNS: %25ITEM ....."
2798 :group 'org-properties
2799 :type 'string)
2801 (defcustom org-columns-ellipses ".."
2802 "The ellipses to be used when a field in column view is truncated.
2803 When this is the empty string, as many characters as possible are shown,
2804 but then there will be no visual indication that the field has been truncated.
2805 When this is a string of length N, the last N characters of a truncated
2806 field are replaced by this string. If the column is narrower than the
2807 ellipses string, only part of the ellipses string will be shown."
2808 :group 'org-properties
2809 :type 'string)
2811 (defcustom org-columns-modify-value-for-display-function nil
2812 "Function that modifies values for display in column view.
2813 For example, it can be used to cut out a certain part from a time stamp.
2814 The function must take 2 arguments:
2816 column-title The title of the column (*not* the property name)
2817 value The value that should be modified.
2819 The function should return the value that should be displayed,
2820 or nil if the normal value should be used."
2821 :group 'org-properties
2822 :type 'function)
2824 (defcustom org-effort-property "Effort"
2825 "The property that is being used to keep track of effort estimates.
2826 Effort estimates given in this property need to have the format H:MM."
2827 :group 'org-properties
2828 :group 'org-progress
2829 :type '(string :tag "Property"))
2831 (defconst org-global-properties-fixed
2832 '(("VISIBILITY_ALL" . "folded children content all")
2833 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2834 "List of property/value pairs that can be inherited by any entry.
2836 These are fixed values, for the preset properties. The user variable
2837 that can be used to add to this list is `org-global-properties'.
2839 The entries in this list are cons cells where the car is a property
2840 name and cdr is a string with the value. If the value represents
2841 multiple items like an \"_ALL\" property, separate the items by
2842 spaces.")
2844 (defcustom org-global-properties nil
2845 "List of property/value pairs that can be inherited by any entry.
2847 This list will be combined with the constant `org-global-properties-fixed'.
2849 The entries in this list are cons cells where the car is a property
2850 name and cdr is a string with the value.
2852 You can set buffer-local values for the same purpose in the variable
2853 `org-file-properties' this by adding lines like
2855 #+PROPERTY: NAME VALUE"
2856 :group 'org-properties
2857 :type '(repeat
2858 (cons (string :tag "Property")
2859 (string :tag "Value"))))
2861 (defvar org-file-properties nil
2862 "List of property/value pairs that can be inherited by any entry.
2863 Valid for the current buffer.
2864 This variable is populated from #+PROPERTY lines.")
2865 (make-variable-buffer-local 'org-file-properties)
2867 (defgroup org-agenda nil
2868 "Options concerning agenda views in Org-mode."
2869 :tag "Org Agenda"
2870 :group 'org)
2872 (defvar org-category nil
2873 "Variable used by org files to set a category for agenda display.
2874 Such files should use a file variable to set it, for example
2876 # -*- mode: org; org-category: \"ELisp\"
2878 or contain a special line
2880 #+CATEGORY: ELisp
2882 If the file does not specify a category, then file's base name
2883 is used instead.")
2884 (make-variable-buffer-local 'org-category)
2885 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2887 (defcustom org-agenda-files nil
2888 "The files to be used for agenda display.
2889 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2890 \\[org-remove-file]. You can also use customize to edit the list.
2892 If an entry is a directory, all files in that directory that are matched by
2893 `org-agenda-file-regexp' will be part of the file list.
2895 If the value of the variable is not a list but a single file name, then
2896 the list of agenda files is actually stored and maintained in that file, one
2897 agenda file per line. In this file paths can be given relative to
2898 `org-directory'. Tilde expansion and environment variable substitution
2899 are also made."
2900 :group 'org-agenda
2901 :type '(choice
2902 (repeat :tag "List of files and directories" file)
2903 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2905 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2906 "Regular expression to match files for `org-agenda-files'.
2907 If any element in the list in that variable contains a directory instead
2908 of a normal file, all files in that directory that are matched by this
2909 regular expression will be included."
2910 :group 'org-agenda
2911 :type 'regexp)
2913 (defcustom org-agenda-text-search-extra-files nil
2914 "List of extra files to be searched by text search commands.
2915 These files will be search in addition to the agenda files by the
2916 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2917 Note that these files will only be searched for text search commands,
2918 not for the other agenda views like todo lists, tag searches or the weekly
2919 agenda. This variable is intended to list notes and possibly archive files
2920 that should also be searched by these two commands.
2921 In fact, if the first element in the list is the symbol `agenda-archives',
2922 than all archive files of all agenda files will be added to the search
2923 scope."
2924 :group 'org-agenda
2925 :type '(set :greedy t
2926 (const :tag "Agenda Archives" agenda-archives)
2927 (repeat :inline t (file))))
2929 (if (fboundp 'defvaralias)
2930 (defvaralias 'org-agenda-multi-occur-extra-files
2931 'org-agenda-text-search-extra-files))
2933 (defcustom org-agenda-skip-unavailable-files nil
2934 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2935 A nil value means to remove them, after a query, from the list."
2936 :group 'org-agenda
2937 :type 'boolean)
2939 (defcustom org-calendar-to-agenda-key [?c]
2940 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2941 The command `org-calendar-goto-agenda' will be bound to this key. The
2942 default is the character `c' because then `c' can be used to switch back and
2943 forth between agenda and calendar."
2944 :group 'org-agenda
2945 :type 'sexp)
2947 (defcustom org-calendar-agenda-action-key [?k]
2948 "The key to be installed in `calendar-mode-map' for agenda-action.
2949 The command `org-agenda-action' will be bound to this key. The
2950 default is the character `k' because we use the same key in the agenda."
2951 :group 'org-agenda
2952 :type 'sexp)
2954 (defcustom org-calendar-insert-diary-entry-key [?i]
2955 "The key to be installed in `calendar-mode-map' for adding diary entries.
2956 This option is irrelevant until `org-agenda-diary-file' has been configured
2957 to point to an Org-mode file. When that is the case, the command
2958 `org-agenda-diary-entry' will be bound to the key given here, by default
2959 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2960 if you want to continue doing this, you need to change this to a different
2961 key."
2962 :group 'org-agenda
2963 :type 'sexp)
2965 (defcustom org-agenda-diary-file 'diary-file
2966 "File to which to add new entries with the `i' key in agenda and calendar.
2967 When this is the symbol `diary-file', the functionality in the Emacs
2968 calendar will be used to add entries to the `diary-file'. But when this
2969 points to a file, `org-agenda-diary-entry' will be used instead."
2970 :group 'org-agenda
2971 :type '(choice
2972 (const :tag "The standard Emacs diary file" diary-file)
2973 (file :tag "Special Org file diary entries")))
2975 (eval-after-load "calendar"
2976 '(progn
2977 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2978 'org-calendar-goto-agenda)
2979 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2980 'org-agenda-action)
2981 (add-hook 'calendar-mode-hook
2982 (lambda ()
2983 (unless (eq org-agenda-diary-file 'diary-file)
2984 (define-key calendar-mode-map
2985 org-calendar-insert-diary-entry-key
2986 'org-agenda-diary-entry))))))
2988 (defgroup org-latex nil
2989 "Options for embedding LaTeX code into Org-mode."
2990 :tag "Org LaTeX"
2991 :group 'org)
2993 (defcustom org-format-latex-options
2994 '(:foreground default :background default :scale 1.0
2995 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2996 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2997 "Options for creating images from LaTeX fragments.
2998 This is a property list with the following properties:
2999 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3000 `default' means use the foreground of the default face.
3001 :background the background color, or \"Transparent\".
3002 `default' means use the background of the default face.
3003 :scale a scaling factor for the size of the images.
3004 :html-foreground, :html-background, :html-scale
3005 the same numbers for HTML export.
3006 :matchers a list indicating which matchers should be used to
3007 find LaTeX fragments. Valid members of this list are:
3008 \"begin\" find environments
3009 \"$1\" find single characters surrounded by $.$
3010 \"$\" find math expressions surrounded by $...$
3011 \"$$\" find math expressions surrounded by $$....$$
3012 \"\\(\" find math expressions surrounded by \\(...\\)
3013 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3014 :group 'org-latex
3015 :type 'plist)
3017 (defcustom org-format-latex-signal-error t
3018 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3019 When nil, just push out a message."
3020 :group 'org-latex
3021 :type 'boolean)
3023 (defcustom org-format-latex-header "\\documentclass{article}
3024 \\usepackage[usenames]{color}
3025 \\usepackage{amsmath}
3026 \\usepackage[mathscr]{eucal}
3027 \\pagestyle{empty} % do not remove
3028 \[PACKAGES]
3029 \[DEFAULT-PACKAGES]
3030 % The settings below are copied from fullpage.sty
3031 \\setlength{\\textwidth}{\\paperwidth}
3032 \\addtolength{\\textwidth}{-3cm}
3033 \\setlength{\\oddsidemargin}{1.5cm}
3034 \\addtolength{\\oddsidemargin}{-2.54cm}
3035 \\setlength{\\evensidemargin}{\\oddsidemargin}
3036 \\setlength{\\textheight}{\\paperheight}
3037 \\addtolength{\\textheight}{-\\headheight}
3038 \\addtolength{\\textheight}{-\\headsep}
3039 \\addtolength{\\textheight}{-\\footskip}
3040 \\addtolength{\\textheight}{-3cm}
3041 \\setlength{\\topmargin}{1.5cm}
3042 \\addtolength{\\topmargin}{-2.54cm}"
3043 "The document header used for processing LaTeX fragments.
3044 It is imperative that this header make sure that no page number
3045 appears on the page. The package defined in the variables
3046 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3047 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3048 will be appended."
3049 :group 'org-latex
3050 :type 'string)
3052 (defvar org-format-latex-header-extra nil)
3054 (defun org-set-packages-alist (var val)
3055 "Set the packages alist and make sure it has 3 elements per entry."
3056 (set var (mapcar (lambda (x)
3057 (if (and (consp x) (= (length x) 2))
3058 (list (car x) (nth 1 x) t)
3060 val)))
3062 (defun org-get-packages-alist (var)
3064 "Get the packages alist and make sure it has 3 elements per entry."
3065 (mapcar (lambda (x)
3066 (if (and (consp x) (= (length x) 2))
3067 (list (car x) (nth 1 x) t)
3069 (default-value var)))
3071 ;; The following variables are defined here because is it also used
3072 ;; when formatting latex fragments. Originally it was part of the
3073 ;; LaTeX exporter, which is why the name includes "export".
3074 (defcustom org-export-latex-default-packages-alist
3075 '(("AUTO" "inputenc" t)
3076 ("T1" "fontenc" t)
3077 ("" "fixltx2e" nil)
3078 ("" "graphicx" t)
3079 ("" "longtable" nil)
3080 ("" "float" nil)
3081 ("" "wrapfig" nil)
3082 ("" "soul" t)
3083 ("" "t1enc" t)
3084 ("" "textcomp" t)
3085 ("" "marvosym" t)
3086 ("" "wasysym" t)
3087 ("" "latexsym" t)
3088 ("" "amssymb" t)
3089 ("" "hyperref" nil)
3090 "\\tolerance=1000"
3092 "Alist of default packages to be inserted in the header.
3093 Change this only if one of the packages here causes an incompatibility
3094 with another package you are using.
3095 The packages in this list are needed by one part or another of Org-mode
3096 to function properly.
3098 - inputenc, fontenc, t1enc: for basic font and character selection
3099 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3100 for interpreting the entities in `org-entities'. You can skip some of these
3101 packages if you don't use any of the symbols in it.
3102 - graphicx: for including images
3103 - float, wrapfig: for figure placement
3104 - longtable: for long tables
3105 - hyperref: for cross references
3107 Therefore you should not modify this variable unless you know what you
3108 are doing. The one reason to change it anyway is that you might be loading
3109 some other package that conflicts with one of the default packages.
3110 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3111 If SNIPPET-FLAG is t, the package also needs to be included when
3112 compiling LaTeX snippets into images for inclusion into HTML."
3113 :group 'org-export-latex
3114 :set 'org-set-packages-alist
3115 :get 'org-get-packages-alist
3116 :type '(repeat
3117 (choice
3118 (list :tag "options/package pair"
3119 (string :tag "options")
3120 (string :tag "package")
3121 (boolean :tag "Snippet"))
3122 (string :tag "A line of LaTeX"))))
3124 (defcustom org-export-latex-packages-alist nil
3125 "Alist of packages to be inserted in every LaTeX header.
3126 These will be inserted after `org-export-latex-default-packages-alist'.
3127 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3128 SNIPPET-FLAG, when t, indicates that this package is also needed when
3129 turning LaTeX snippets into images for inclusion into HTML.
3130 Make sure that you only list packages here which:
3131 - you want in every file
3132 - do not conflict with the default packages in
3133 `org-export-latex-default-packages-alist'
3134 - do not conflict with the setup in `org-format-latex-header'."
3135 :group 'org-export-latex
3136 :set 'org-set-packages-alist
3137 :get 'org-get-packages-alist
3138 :type '(repeat
3139 (choice
3140 (list :tag "options/package pair"
3141 (string :tag "options")
3142 (string :tag "package")
3143 (boolean :tag "Snippet"))
3144 (string :tag "A line of LaTeX"))))
3147 (defgroup org-appearance nil
3148 "Settings for Org-mode appearance."
3149 :tag "Org Appearance"
3150 :group 'org)
3152 (defcustom org-level-color-stars-only nil
3153 "Non-nil means fontify only the stars in each headline.
3154 When nil, the entire headline is fontified.
3155 Changing it requires restart of `font-lock-mode' to become effective
3156 also in regions already fontified."
3157 :group 'org-appearance
3158 :type 'boolean)
3160 (defcustom org-hide-leading-stars nil
3161 "Non-nil means hide the first N-1 stars in a headline.
3162 This works by using the face `org-hide' for these stars. This
3163 face is white for a light background, and black for a dark
3164 background. You may have to customize the face `org-hide' to
3165 make this work.
3166 Changing it requires restart of `font-lock-mode' to become effective
3167 also in regions already fontified.
3168 You may also set this on a per-file basis by adding one of the following
3169 lines to the buffer:
3171 #+STARTUP: hidestars
3172 #+STARTUP: showstars"
3173 :group 'org-appearance
3174 :type 'boolean)
3176 (defcustom org-hidden-keywords nil
3177 "List of keywords that should be hidden when typed in the org buffer.
3178 For example, add #+TITLE to this list in order to make the
3179 document title appear in the buffer without the initial #+TITLE:
3180 keyword."
3181 :group 'org-appearance
3182 :type '(set (const :tag "#+AUTHOR" author)
3183 (const :tag "#+DATE" date)
3184 (const :tag "#+EMAIL" email)
3185 (const :tag "#+TITLE" title)))
3187 (defcustom org-fontify-done-headline nil
3188 "Non-nil means change the face of a headline if it is marked DONE.
3189 Normally, only the TODO/DONE keyword indicates the state of a headline.
3190 When this is non-nil, the headline after the keyword is set to the
3191 `org-headline-done' as an additional indication."
3192 :group 'org-appearance
3193 :type 'boolean)
3195 (defcustom org-fontify-emphasized-text t
3196 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3197 Changing this variable requires a restart of Emacs to take effect."
3198 :group 'org-appearance
3199 :type 'boolean)
3201 (defcustom org-fontify-whole-heading-line nil
3202 "Non-nil means fontify the whole line for headings.
3203 This is useful when setting a background color for the
3204 org-level-* faces."
3205 :group 'org-appearance
3206 :type 'boolean)
3208 (defcustom org-highlight-latex-fragments-and-specials nil
3209 "Non-nil means fontify what is treated specially by the exporters."
3210 :group 'org-appearance
3211 :type 'boolean)
3213 (defcustom org-hide-emphasis-markers nil
3214 "Non-nil mean font-lock should hide the emphasis marker characters."
3215 :group 'org-appearance
3216 :type 'boolean)
3218 (defcustom org-pretty-entities nil
3219 "Non-nil means show entities as UTF8 characters.
3220 When nil, the \\name form remains in the buffer."
3221 :group 'org-appearance
3222 :type 'boolean)
3224 (defcustom org-pretty-entities-include-sub-superscripts t
3225 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3226 :group 'org-appearance
3227 :type 'boolean)
3229 (defvar org-emph-re nil
3230 "Regular expression for matching emphasis.
3231 After a match, the match groups contain these elements:
3232 1 The character before the proper match, or empty at beginning of line
3233 2 The proper match, including the leading and trailing markers
3234 3 The leading marker like * or /, indicating the type of highlighting
3235 4 The text between the emphasis markers, not including the markers
3236 5 The character after the match, empty at the end of a line")
3237 (defvar org-verbatim-re nil
3238 "Regular expression for matching verbatim text.")
3239 (defvar org-emphasis-regexp-components) ; defined just below
3240 (defvar org-emphasis-alist) ; defined just below
3241 (defun org-set-emph-re (var val)
3242 "Set variable and compute the emphasis regular expression."
3243 (set var val)
3244 (when (and (boundp 'org-emphasis-alist)
3245 (boundp 'org-emphasis-regexp-components)
3246 org-emphasis-alist org-emphasis-regexp-components)
3247 (let* ((e org-emphasis-regexp-components)
3248 (pre (car e))
3249 (post (nth 1 e))
3250 (border (nth 2 e))
3251 (body (nth 3 e))
3252 (nl (nth 4 e))
3253 (body1 (concat body "*?"))
3254 (markers (mapconcat 'car org-emphasis-alist ""))
3255 (vmarkers (mapconcat
3256 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3257 org-emphasis-alist "")))
3258 ;; make sure special characters appear at the right position in the class
3259 (if (string-match "\\^" markers)
3260 (setq markers (concat (replace-match "" t t markers) "^")))
3261 (if (string-match "-" markers)
3262 (setq markers (concat (replace-match "" t t markers) "-")))
3263 (if (string-match "\\^" vmarkers)
3264 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3265 (if (string-match "-" vmarkers)
3266 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3267 (if (> nl 0)
3268 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3269 (int-to-string nl) "\\}")))
3270 ;; Make the regexp
3271 (setq org-emph-re
3272 (concat "\\([" pre "]\\|^\\)"
3273 "\\("
3274 "\\([" markers "]\\)"
3275 "\\("
3276 "[^" border "]\\|"
3277 "[^" border "]"
3278 body1
3279 "[^" border "]"
3280 "\\)"
3281 "\\3\\)"
3282 "\\([" post "]\\|$\\)"))
3283 (setq org-verbatim-re
3284 (concat "\\([" pre "]\\|^\\)"
3285 "\\("
3286 "\\([" vmarkers "]\\)"
3287 "\\("
3288 "[^" border "]\\|"
3289 "[^" border "]"
3290 body1
3291 "[^" border "]"
3292 "\\)"
3293 "\\3\\)"
3294 "\\([" post "]\\|$\\)")))))
3296 (defcustom org-emphasis-regexp-components
3297 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3298 "Components used to build the regular expression for emphasis.
3299 This is a list with 6 entries. Terminology: In an emphasis string
3300 like \" *strong word* \", we call the initial space PREMATCH, the final
3301 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3302 and \"trong wor\" is the body. The different components in this variable
3303 specify what is allowed/forbidden in each part:
3305 pre Chars allowed as prematch. Beginning of line will be allowed too.
3306 post Chars allowed as postmatch. End of line will be allowed too.
3307 border The chars *forbidden* as border characters.
3308 body-regexp A regexp like \".\" to match a body character. Don't use
3309 non-shy groups here, and don't allow newline here.
3310 newline The maximum number of newlines allowed in an emphasis exp.
3312 Use customize to modify this, or restart Emacs after changing it."
3313 :group 'org-appearance
3314 :set 'org-set-emph-re
3315 :type '(list
3316 (sexp :tag "Allowed chars in pre ")
3317 (sexp :tag "Allowed chars in post ")
3318 (sexp :tag "Forbidden chars in border ")
3319 (sexp :tag "Regexp for body ")
3320 (integer :tag "number of newlines allowed")
3321 (option (boolean :tag "Please ignore this button"))))
3323 (defcustom org-emphasis-alist
3324 `(("*" bold "<b>" "</b>")
3325 ("/" italic "<i>" "</i>")
3326 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3327 ("=" org-code "<code>" "</code>" verbatim)
3328 ("~" org-verbatim "<code>" "</code>" verbatim)
3329 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3330 "<del>" "</del>")
3332 "Special syntax for emphasized text.
3333 Text starting and ending with a special character will be emphasized, for
3334 example *bold*, _underlined_ and /italic/. This variable sets the marker
3335 characters, the face to be used by font-lock for highlighting in Org-mode
3336 Emacs buffers, and the HTML tags to be used for this.
3337 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3338 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3339 Use customize to modify this, or restart Emacs after changing it."
3340 :group 'org-appearance
3341 :set 'org-set-emph-re
3342 :type '(repeat
3343 (list
3344 (string :tag "Marker character")
3345 (choice
3346 (face :tag "Font-lock-face")
3347 (plist :tag "Face property list"))
3348 (string :tag "HTML start tag")
3349 (string :tag "HTML end tag")
3350 (option (const verbatim)))))
3352 (defvar org-protecting-blocks
3353 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3354 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3355 This is needed for font-lock setup.")
3357 ;;; Miscellaneous options
3359 (defgroup org-completion nil
3360 "Completion in Org-mode."
3361 :tag "Org Completion"
3362 :group 'org)
3364 (defcustom org-completion-use-ido nil
3365 "Non-nil means use ido completion wherever possible.
3366 Note that `ido-mode' must be active for this variable to be relevant.
3367 If you decide to turn this variable on, you might well want to turn off
3368 `org-outline-path-complete-in-steps'.
3369 See also `org-completion-use-iswitchb'."
3370 :group 'org-completion
3371 :type 'boolean)
3373 (defcustom org-completion-use-iswitchb nil
3374 "Non-nil means use iswitchb completion wherever possible.
3375 Note that `iswitchb-mode' must be active for this variable to be relevant.
3376 If you decide to turn this variable on, you might well want to turn off
3377 `org-outline-path-complete-in-steps'.
3378 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3379 :group 'org-completion
3380 :type 'boolean)
3382 (defcustom org-completion-fallback-command 'hippie-expand
3383 "The expansion command called by \\[org-complete] in normal context.
3384 Normal means no org-mode-specific context."
3385 :group 'org-completion
3386 :type 'function)
3388 ;;; Functions and variables from their packages
3389 ;; Declared here to avoid compiler warnings
3391 ;; XEmacs only
3392 (defvar outline-mode-menu-heading)
3393 (defvar outline-mode-menu-show)
3394 (defvar outline-mode-menu-hide)
3395 (defvar zmacs-regions) ; XEmacs regions
3397 ;; Emacs only
3398 (defvar mark-active)
3400 ;; Various packages
3401 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3402 (declare-function calendar-forward-day "cal-move" (arg))
3403 (declare-function calendar-goto-date "cal-move" (date))
3404 (declare-function calendar-goto-today "cal-move" ())
3405 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3406 (defvar calc-embedded-close-formula)
3407 (defvar calc-embedded-open-formula)
3408 (declare-function cdlatex-tab "ext:cdlatex" ())
3409 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3410 (defvar font-lock-unfontify-region-function)
3411 (declare-function iswitchb-read-buffer "iswitchb"
3412 (prompt &optional default require-match start matches-set))
3413 (defvar iswitchb-temp-buflist)
3414 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3415 (defvar org-agenda-tags-todo-honor-ignore-options)
3416 (declare-function org-agenda-skip "org-agenda" ())
3417 (declare-function
3418 org-format-agenda-item "org-agenda"
3419 (extra txt &optional category tags dotime noprefix remove-re habitp))
3420 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3421 (declare-function org-agenda-change-all-lines "org-agenda"
3422 (newhead hdmarker &optional fixface just-this))
3423 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3424 (declare-function org-agenda-maybe-redo "org-agenda" ())
3425 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3426 (beg end))
3427 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3428 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3429 "org-agenda" (&optional end))
3430 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3431 (declare-function org-indent-mode "org-indent" (&optional arg))
3432 (declare-function parse-time-string "parse-time" (string))
3433 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3434 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3435 (defvar remember-data-file)
3436 (defvar texmathp-why)
3437 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3438 (declare-function table--at-cell-p "table" (position &optional object at-column))
3440 (defvar w3m-current-url)
3441 (defvar w3m-current-title)
3443 (defvar org-latex-regexps)
3445 ;;; Autoload and prepare some org modules
3447 ;; Some table stuff that needs to be defined here, because it is used
3448 ;; by the functions setting up org-mode or checking for table context.
3450 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3451 "Detects an org-type or table-type table.")
3452 (defconst org-table-line-regexp "^[ \t]*|"
3453 "Detects an org-type table line.")
3454 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3455 "Detects an org-type table line.")
3456 (defconst org-table-hline-regexp "^[ \t]*|-"
3457 "Detects an org-type table hline.")
3458 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3459 "Detects a table-type table hline.")
3460 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3461 "Searching from within a table (any type) this finds the first line
3462 outside the table.")
3464 ;; Autoload the functions in org-table.el that are needed by functions here.
3466 (eval-and-compile
3467 (org-autoload "org-table"
3468 '(org-table-align org-table-begin org-table-blank-field
3469 org-table-convert org-table-convert-region org-table-copy-down
3470 org-table-copy-region org-table-create
3471 org-table-create-or-convert-from-region
3472 org-table-create-with-table.el org-table-current-dline
3473 org-table-cut-region org-table-delete-column org-table-edit-field
3474 org-table-edit-formulas org-table-end org-table-eval-formula
3475 org-table-export org-table-field-info
3476 org-table-get-stored-formulas org-table-goto-column
3477 org-table-hline-and-move org-table-import org-table-insert-column
3478 org-table-insert-hline org-table-insert-row org-table-iterate
3479 org-table-justify-field-maybe org-table-kill-row
3480 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3481 org-table-move-column org-table-move-column-left
3482 org-table-move-column-right org-table-move-row
3483 org-table-move-row-down org-table-move-row-up
3484 org-table-next-field org-table-next-row org-table-paste-rectangle
3485 org-table-previous-field org-table-recalculate
3486 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3487 org-table-toggle-coordinate-overlays
3488 org-table-toggle-formula-debugger org-table-wrap-region
3489 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3491 (defun org-at-table-p (&optional table-type)
3492 "Return t if the cursor is inside an org-type table.
3493 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3494 (if org-enable-table-editor
3495 (save-excursion
3496 (beginning-of-line 1)
3497 (looking-at (if table-type org-table-any-line-regexp
3498 org-table-line-regexp)))
3499 nil))
3500 (defsubst org-table-p () (org-at-table-p))
3502 (defun org-at-table.el-p ()
3503 "Return t if and only if we are at a table.el table."
3504 (and (org-at-table-p 'any)
3505 (save-excursion
3506 (goto-char (org-table-begin 'any))
3507 (looking-at org-table1-hline-regexp))))
3508 (defun org-table-recognize-table.el ()
3509 "If there is a table.el table nearby, recognize it and move into it."
3510 (if org-table-tab-recognizes-table.el
3511 (if (org-at-table.el-p)
3512 (progn
3513 (beginning-of-line 1)
3514 (if (looking-at org-table-dataline-regexp)
3516 (if (looking-at org-table1-hline-regexp)
3517 (progn
3518 (beginning-of-line 2)
3519 (if (looking-at org-table-any-border-regexp)
3520 (beginning-of-line -1)))))
3521 (if (re-search-forward "|" (org-table-end t) t)
3522 (progn
3523 (require 'table)
3524 (if (table--at-cell-p (point))
3526 (message "recognizing table.el table...")
3527 (table-recognize-table)
3528 (message "recognizing table.el table...done")))
3529 (error "This should not happen..."))
3531 nil)
3532 nil))
3534 (defun org-at-table-hline-p ()
3535 "Return t if the cursor is inside a hline in a table."
3536 (if org-enable-table-editor
3537 (save-excursion
3538 (beginning-of-line 1)
3539 (looking-at org-table-hline-regexp))
3540 nil))
3542 (defvar org-table-clean-did-remove-column nil)
3544 (defun org-table-map-tables (function &optional quietly)
3545 "Apply FUNCTION to the start of all tables in the buffer."
3546 (save-excursion
3547 (save-restriction
3548 (widen)
3549 (goto-char (point-min))
3550 (while (re-search-forward org-table-any-line-regexp nil t)
3551 (unless quietly
3552 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3553 (beginning-of-line 1)
3554 (when (looking-at org-table-line-regexp)
3555 (save-excursion (funcall function))
3556 (or (looking-at org-table-line-regexp)
3557 (forward-char 1)))
3558 (re-search-forward org-table-any-border-regexp nil 1))))
3559 (unless quietly (message "Mapping tables: done")))
3561 ;; Declare and autoload functions from org-exp.el & Co
3563 (declare-function org-default-export-plist "org-exp")
3564 (declare-function org-infile-export-plist "org-exp")
3565 (declare-function org-get-current-options "org-exp")
3566 (eval-and-compile
3567 (org-autoload "org-exp"
3568 '(org-export org-export-visible
3569 org-insert-export-options-template
3570 org-table-clean-before-export))
3571 (org-autoload "org-ascii"
3572 '(org-export-as-ascii org-export-ascii-preprocess
3573 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3574 org-export-region-as-ascii))
3575 (org-autoload "org-latex"
3576 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3577 org-replace-region-by-latex org-export-region-as-latex
3578 org-export-as-latex org-export-as-pdf
3579 org-export-as-pdf-and-open))
3580 (org-autoload "org-html"
3581 '(org-export-as-html-and-open
3582 org-export-as-html-batch org-export-as-html-to-buffer
3583 org-replace-region-by-html org-export-region-as-html
3584 org-export-as-html))
3585 (org-autoload "org-docbook"
3586 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3587 org-replace-region-by-docbook org-export-region-as-docbook
3588 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3589 org-export-as-docbook))
3590 (org-autoload "org-icalendar"
3591 '(org-export-icalendar-this-file
3592 org-export-icalendar-all-agenda-files
3593 org-export-icalendar-combine-agenda-files))
3594 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3595 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3597 ;; Declare and autoload functions from org-agenda.el
3599 (eval-and-compile
3600 (org-autoload "org-agenda"
3601 '(org-agenda org-agenda-list org-search-view
3602 org-todo-list org-tags-view org-agenda-list-stuck-projects
3603 org-diary org-agenda-to-appt
3604 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3606 ;; Autoload org-remember
3608 (eval-and-compile
3609 (org-autoload "org-remember"
3610 '(org-remember-insinuate org-remember-annotation
3611 org-remember-apply-template org-remember org-remember-handler)))
3613 ;; Autoload org-clock.el
3616 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3617 (beg end))
3618 (declare-function org-clock-update-mode-line "org-clock" ())
3619 (declare-function org-resolve-clocks "org-clock"
3620 (&optional also-non-dangling-p prompt last-valid))
3621 (defvar org-clock-start-time)
3622 (defvar org-clock-marker (make-marker)
3623 "Marker recording the last clock-in.")
3624 (defvar org-clock-hd-marker (make-marker)
3625 "Marker recording the last clock-in, but the headline position.")
3626 (defvar org-clock-heading ""
3627 "The heading of the current clock entry.")
3628 (defun org-clock-is-active ()
3629 "Return non-nil if clock is currently running.
3630 The return value is actually the clock marker."
3631 (marker-buffer org-clock-marker))
3633 (eval-and-compile
3634 (org-autoload
3635 "org-clock"
3636 '(org-clock-in org-clock-out org-clock-cancel
3637 org-clock-goto org-clock-sum org-clock-display
3638 org-clock-remove-overlays org-clock-report
3639 org-clocktable-shift org-dblock-write:clocktable
3640 org-get-clocktable org-resolve-clocks)))
3642 (defun org-clock-update-time-maybe ()
3643 "If this is a CLOCK line, update it and return t.
3644 Otherwise, return nil."
3645 (interactive)
3646 (save-excursion
3647 (beginning-of-line 1)
3648 (skip-chars-forward " \t")
3649 (when (looking-at org-clock-string)
3650 (let ((re (concat "[ \t]*" org-clock-string
3651 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3652 "\\([ \t]*=>.*\\)?\\)?"))
3653 ts te h m s neg)
3654 (cond
3655 ((not (looking-at re))
3656 nil)
3657 ((not (match-end 2))
3658 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3659 (> org-clock-marker (point))
3660 (<= org-clock-marker (point-at-eol)))
3661 ;; The clock is running here
3662 (setq org-clock-start-time
3663 (apply 'encode-time
3664 (org-parse-time-string (match-string 1))))
3665 (org-clock-update-mode-line)))
3667 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3668 (end-of-line 1)
3669 (setq ts (match-string 1)
3670 te (match-string 3))
3671 (setq s (- (org-float-time
3672 (apply 'encode-time (org-parse-time-string te)))
3673 (org-float-time
3674 (apply 'encode-time (org-parse-time-string ts))))
3675 neg (< s 0)
3676 s (abs s)
3677 h (floor (/ s 3600))
3678 s (- s (* 3600 h))
3679 m (floor (/ s 60))
3680 s (- s (* 60 s)))
3681 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3682 t))))))
3684 (defun org-check-running-clock ()
3685 "Check if the current buffer contains the running clock.
3686 If yes, offer to stop it and to save the buffer with the changes."
3687 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3688 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3689 (buffer-name))))
3690 (org-clock-out)
3691 (when (y-or-n-p "Save changed buffer?")
3692 (save-buffer))))
3694 (defun org-clocktable-try-shift (dir n)
3695 "Check if this line starts a clock table, if yes, shift the time block."
3696 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3697 (org-clocktable-shift dir n)))
3699 ;; Autoload org-timer.el
3701 (eval-and-compile
3702 (org-autoload
3703 "org-timer"
3704 '(org-timer-start org-timer org-timer-item
3705 org-timer-change-times-in-region
3706 org-timer-set-timer
3707 org-timer-reset-timers
3708 org-timer-show-remaining-time)))
3710 ;; Autoload org-feed.el
3712 (eval-and-compile
3713 (org-autoload
3714 "org-feed"
3715 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3718 ;; Autoload org-indent.el
3720 ;; Define the variable already here, to make sure we have it.
3721 (defvar org-indent-mode nil
3722 "Non-nil if Org-Indent mode is enabled.
3723 Use the command `org-indent-mode' to change this variable.")
3725 (eval-and-compile
3726 (org-autoload
3727 "org-indent"
3728 '(org-indent-mode)))
3730 ;; Autoload org-mobile.el
3732 (eval-and-compile
3733 (org-autoload
3734 "org-mobile"
3735 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3737 ;; Autoload archiving code
3738 ;; The stuff that is needed for cycling and tags has to be defined here.
3740 (defgroup org-archive nil
3741 "Options concerning archiving in Org-mode."
3742 :tag "Org Archive"
3743 :group 'org-structure)
3745 (defcustom org-archive-location "%s_archive::"
3746 "The location where subtrees should be archived.
3748 The value of this variable is a string, consisting of two parts,
3749 separated by a double-colon. The first part is a filename and
3750 the second part is a headline.
3752 When the filename is omitted, archiving happens in the same file.
3753 %s in the filename will be replaced by the current file
3754 name (without the directory part). Archiving to a different file
3755 is useful to keep archived entries from contributing to the
3756 Org-mode Agenda.
3758 The archived entries will be filed as subtrees of the specified
3759 headline. When the headline is omitted, the subtrees are simply
3760 filed away at the end of the file, as top-level entries. Also in
3761 the heading you can use %s to represent the file name, this can be
3762 useful when using the same archive for a number of different files.
3764 Here are a few examples:
3765 \"%s_archive::\"
3766 If the current file is Projects.org, archive in file
3767 Projects.org_archive, as top-level trees. This is the default.
3769 \"::* Archived Tasks\"
3770 Archive in the current file, under the top-level headline
3771 \"* Archived Tasks\".
3773 \"~/org/archive.org::\"
3774 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3776 \"~/org/archive.org::From %s\"
3777 Archive in file ~/org/archive.org (absolute path), under headlines
3778 \"From FILENAME\" where file name is the current file name.
3780 \"basement::** Finished Tasks\"
3781 Archive in file ./basement (relative path), as level 3 trees
3782 below the level 2 heading \"** Finished Tasks\".
3784 You may set this option on a per-file basis by adding to the buffer a
3785 line like
3787 #+ARCHIVE: basement::** Finished Tasks
3789 You may also define it locally for a subtree by setting an ARCHIVE property
3790 in the entry. If such a property is found in an entry, or anywhere up
3791 the hierarchy, it will be used."
3792 :group 'org-archive
3793 :type 'string)
3795 (defcustom org-archive-tag "ARCHIVE"
3796 "The tag that marks a subtree as archived.
3797 An archived subtree does not open during visibility cycling, and does
3798 not contribute to the agenda listings.
3799 After changing this, font-lock must be restarted in the relevant buffers to
3800 get the proper fontification."
3801 :group 'org-archive
3802 :group 'org-keywords
3803 :type 'string)
3805 (defcustom org-agenda-skip-archived-trees t
3806 "Non-nil means the agenda will skip any items located in archived trees.
3807 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3808 variable is no longer recommended, you should leave it at the value t.
3809 Instead, use the key `v' to cycle the archives-mode in the agenda."
3810 :group 'org-archive
3811 :group 'org-agenda-skip
3812 :type 'boolean)
3814 (defcustom org-columns-skip-archived-trees t
3815 "Non-nil means ignore archived trees when creating column view."
3816 :group 'org-archive
3817 :group 'org-properties
3818 :type 'boolean)
3820 (defcustom org-cycle-open-archived-trees nil
3821 "Non-nil means `org-cycle' will open archived trees.
3822 An archived tree is a tree marked with the tag ARCHIVE.
3823 When nil, archived trees will stay folded. You can still open them with
3824 normal outline commands like `show-all', but not with the cycling commands."
3825 :group 'org-archive
3826 :group 'org-cycle
3827 :type 'boolean)
3829 (defcustom org-sparse-tree-open-archived-trees nil
3830 "Non-nil means sparse tree construction shows matches in archived trees.
3831 When nil, matches in these trees are highlighted, but the trees are kept in
3832 collapsed state."
3833 :group 'org-archive
3834 :group 'org-sparse-trees
3835 :type 'boolean)
3837 (defun org-cycle-hide-archived-subtrees (state)
3838 "Re-hide all archived subtrees after a visibility state change."
3839 (when (and (not org-cycle-open-archived-trees)
3840 (not (memq state '(overview folded))))
3841 (save-excursion
3842 (let* ((globalp (memq state '(contents all)))
3843 (beg (if globalp (point-min) (point)))
3844 (end (if globalp (point-max) (org-end-of-subtree t))))
3845 (org-hide-archived-subtrees beg end)
3846 (goto-char beg)
3847 (if (looking-at (concat ".*:" org-archive-tag ":"))
3848 (message "%s" (substitute-command-keys
3849 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3851 (defun org-force-cycle-archived ()
3852 "Cycle subtree even if it is archived."
3853 (interactive)
3854 (setq this-command 'org-cycle)
3855 (let ((org-cycle-open-archived-trees t))
3856 (call-interactively 'org-cycle)))
3858 (defun org-hide-archived-subtrees (beg end)
3859 "Re-hide all archived subtrees after a visibility state change."
3860 (save-excursion
3861 (let* ((re (concat ":" org-archive-tag ":")))
3862 (goto-char beg)
3863 (while (re-search-forward re end t)
3864 (when (org-on-heading-p)
3865 (org-flag-subtree t)
3866 (org-end-of-subtree t))))))
3868 (defun org-flag-subtree (flag)
3869 (save-excursion
3870 (org-back-to-heading t)
3871 (outline-end-of-heading)
3872 (outline-flag-region (point)
3873 (progn (org-end-of-subtree t) (point))
3874 flag)))
3876 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3878 (eval-and-compile
3879 (org-autoload "org-archive"
3880 '(org-add-archive-files org-archive-subtree
3881 org-archive-to-archive-sibling org-toggle-archive-tag
3882 org-archive-subtree-default
3883 org-archive-subtree-default-with-confirmation)))
3885 ;; Autoload Column View Code
3887 (declare-function org-columns-number-to-string "org-colview")
3888 (declare-function org-columns-get-format-and-top-level "org-colview")
3889 (declare-function org-columns-compute "org-colview")
3891 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3892 '(org-columns-number-to-string org-columns-get-format-and-top-level
3893 org-columns-compute org-agenda-columns org-columns-remove-overlays
3894 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3896 ;; Autoload ID code
3898 (declare-function org-id-store-link "org-id")
3899 (declare-function org-id-locations-load "org-id")
3900 (declare-function org-id-locations-save "org-id")
3901 (defvar org-id-track-globally)
3902 (org-autoload "org-id"
3903 '(org-id-get-create org-id-new org-id-copy org-id-get
3904 org-id-get-with-outline-path-completion
3905 org-id-get-with-outline-drilling
3906 org-id-goto org-id-find org-id-store-link))
3908 ;; Autoload Plotting Code
3910 (org-autoload "org-plot"
3911 '(org-plot/gnuplot))
3913 ;;; Variables for pre-computed regular expressions, all buffer local
3915 (defvar org-drawer-regexp nil
3916 "Matches first line of a hidden block.")
3917 (make-variable-buffer-local 'org-drawer-regexp)
3918 (defvar org-todo-regexp nil
3919 "Matches any of the TODO state keywords.")
3920 (make-variable-buffer-local 'org-todo-regexp)
3921 (defvar org-not-done-regexp nil
3922 "Matches any of the TODO state keywords except the last one.")
3923 (make-variable-buffer-local 'org-not-done-regexp)
3924 (defvar org-not-done-heading-regexp nil
3925 "Matches a TODO headline that is not done.")
3926 (make-variable-buffer-local 'org-not-done-regexp)
3927 (defvar org-todo-line-regexp nil
3928 "Matches a headline and puts TODO state into group 2 if present.")
3929 (make-variable-buffer-local 'org-todo-line-regexp)
3930 (defvar org-complex-heading-regexp nil
3931 "Matches a headline and puts everything into groups:
3932 group 1: the stars
3933 group 2: The todo keyword, maybe
3934 group 3: Priority cookie
3935 group 4: True headline
3936 group 5: Tags")
3937 (make-variable-buffer-local 'org-complex-heading-regexp)
3938 (defvar org-complex-heading-regexp-format nil)
3939 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3940 (defvar org-todo-line-tags-regexp nil
3941 "Matches a headline and puts TODO state into group 2 if present.
3942 Also put tags into group 4 if tags are present.")
3943 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3944 (defvar org-nl-done-regexp nil
3945 "Matches newline followed by a headline with the DONE keyword.")
3946 (make-variable-buffer-local 'org-nl-done-regexp)
3947 (defvar org-looking-at-done-regexp nil
3948 "Matches the DONE keyword a point.")
3949 (make-variable-buffer-local 'org-looking-at-done-regexp)
3950 (defvar org-ds-keyword-length 12
3951 "Maximum length of the Deadline and SCHEDULED keywords.")
3952 (make-variable-buffer-local 'org-ds-keyword-length)
3953 (defvar org-deadline-regexp nil
3954 "Matches the DEADLINE keyword.")
3955 (make-variable-buffer-local 'org-deadline-regexp)
3956 (defvar org-deadline-time-regexp nil
3957 "Matches the DEADLINE keyword together with a time stamp.")
3958 (make-variable-buffer-local 'org-deadline-time-regexp)
3959 (defvar org-deadline-line-regexp nil
3960 "Matches the DEADLINE keyword and the rest of the line.")
3961 (make-variable-buffer-local 'org-deadline-line-regexp)
3962 (defvar org-scheduled-regexp nil
3963 "Matches the SCHEDULED keyword.")
3964 (make-variable-buffer-local 'org-scheduled-regexp)
3965 (defvar org-scheduled-time-regexp nil
3966 "Matches the SCHEDULED keyword together with a time stamp.")
3967 (make-variable-buffer-local 'org-scheduled-time-regexp)
3968 (defvar org-closed-time-regexp nil
3969 "Matches the CLOSED keyword together with a time stamp.")
3970 (make-variable-buffer-local 'org-closed-time-regexp)
3972 (defvar org-keyword-time-regexp nil
3973 "Matches any of the 4 keywords, together with the time stamp.")
3974 (make-variable-buffer-local 'org-keyword-time-regexp)
3975 (defvar org-keyword-time-not-clock-regexp nil
3976 "Matches any of the 3 keywords, together with the time stamp.")
3977 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3978 (defvar org-maybe-keyword-time-regexp nil
3979 "Matches a timestamp, possibly preceeded by a keyword.")
3980 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3981 (defvar org-planning-or-clock-line-re nil
3982 "Matches a line with planning or clock info.")
3983 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3984 (defvar org-all-time-keywords nil
3985 "List of time keywords.")
3986 (make-variable-buffer-local 'org-all-time-keywords)
3988 (defconst org-plain-time-of-day-regexp
3989 (concat
3990 "\\(\\<[012]?[0-9]"
3991 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3992 "\\(--?"
3993 "\\(\\<[012]?[0-9]"
3994 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3995 "\\)?")
3996 "Regular expression to match a plain time or time range.
3997 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3998 groups carry important information:
3999 0 the full match
4000 1 the first time, range or not
4001 8 the second time, if it is a range.")
4003 (defconst org-plain-time-extension-regexp
4004 (concat
4005 "\\(\\<[012]?[0-9]"
4006 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4007 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4008 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4009 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4010 groups carry important information:
4011 0 the full match
4012 7 hours of duration
4013 9 minutes of duration")
4015 (defconst org-stamp-time-of-day-regexp
4016 (concat
4017 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4018 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4019 "\\(--?"
4020 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4021 "Regular expression to match a timestamp time or time range.
4022 After a match, the following groups carry important information:
4023 0 the full match
4024 1 date plus weekday, for back referencing to make sure both times are on the same day
4025 2 the first time, range or not
4026 4 the second time, if it is a range.")
4028 (defconst org-startup-options
4029 '(("fold" org-startup-folded t)
4030 ("overview" org-startup-folded t)
4031 ("nofold" org-startup-folded nil)
4032 ("showall" org-startup-folded nil)
4033 ("showeverything" org-startup-folded showeverything)
4034 ("content" org-startup-folded content)
4035 ("indent" org-startup-indented t)
4036 ("noindent" org-startup-indented nil)
4037 ("hidestars" org-hide-leading-stars t)
4038 ("showstars" org-hide-leading-stars nil)
4039 ("odd" org-odd-levels-only t)
4040 ("oddeven" org-odd-levels-only nil)
4041 ("align" org-startup-align-all-tables t)
4042 ("noalign" org-startup-align-all-tables nil)
4043 ("customtime" org-display-custom-times t)
4044 ("logdone" org-log-done time)
4045 ("lognotedone" org-log-done note)
4046 ("nologdone" org-log-done nil)
4047 ("lognoteclock-out" org-log-note-clock-out t)
4048 ("nolognoteclock-out" org-log-note-clock-out nil)
4049 ("logrepeat" org-log-repeat state)
4050 ("lognoterepeat" org-log-repeat note)
4051 ("nologrepeat" org-log-repeat nil)
4052 ("logreschedule" org-log-reschedule time)
4053 ("lognotereschedule" org-log-reschedule note)
4054 ("nologreschedule" org-log-reschedule nil)
4055 ("logredeadline" org-log-redeadline time)
4056 ("lognoteredeadline" org-log-redeadline note)
4057 ("nologredeadline" org-log-redeadline nil)
4058 ("logrefile" org-log-refile time)
4059 ("lognoterefile" org-log-refile note)
4060 ("nologrefile" org-log-refile nil)
4061 ("fninline" org-footnote-define-inline t)
4062 ("nofninline" org-footnote-define-inline nil)
4063 ("fnlocal" org-footnote-section nil)
4064 ("fnauto" org-footnote-auto-label t)
4065 ("fnprompt" org-footnote-auto-label nil)
4066 ("fnconfirm" org-footnote-auto-label confirm)
4067 ("fnplain" org-footnote-auto-label plain)
4068 ("fnadjust" org-footnote-auto-adjust t)
4069 ("nofnadjust" org-footnote-auto-adjust nil)
4070 ("constcgs" constants-unit-system cgs)
4071 ("constSI" constants-unit-system SI)
4072 ("noptag" org-tag-persistent-alist nil)
4073 ("hideblocks" org-hide-block-startup t)
4074 ("nohideblocks" org-hide-block-startup nil)
4075 ("beamer" org-startup-with-beamer-mode t)
4076 ("entitiespretty" org-pretty-entities t)
4077 ("entitiesplain" org-pretty-entities nil))
4078 "Variable associated with STARTUP options for org-mode.
4079 Each element is a list of three items: The startup options as written
4080 in the #+STARTUP line, the corresponding variable, and the value to
4081 set this variable to if the option is found. An optional forth element PUSH
4082 means to push this value onto the list in the variable.")
4084 (defun org-set-regexps-and-options ()
4085 "Precompute regular expressions for current buffer."
4086 (when (org-mode-p)
4087 (org-set-local 'org-todo-kwd-alist nil)
4088 (org-set-local 'org-todo-key-alist nil)
4089 (org-set-local 'org-todo-key-trigger nil)
4090 (org-set-local 'org-todo-keywords-1 nil)
4091 (org-set-local 'org-done-keywords nil)
4092 (org-set-local 'org-todo-heads nil)
4093 (org-set-local 'org-todo-sets nil)
4094 (org-set-local 'org-todo-log-states nil)
4095 (org-set-local 'org-file-properties nil)
4096 (org-set-local 'org-file-tags nil)
4097 (let ((re (org-make-options-regexp
4098 '("CATEGORY" "TODO" "COLUMNS"
4099 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4100 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4101 "OPTIONS")
4102 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4103 (splitre "[ \t]+")
4104 (scripts org-use-sub-superscripts)
4105 kwds kws0 kwsa key log value cat arch tags const links hw dws
4106 tail sep kws1 prio props ftags drawers beamer-p
4107 ext-setup-or-nil setup-contents (start 0))
4108 (save-excursion
4109 (save-restriction
4110 (widen)
4111 (goto-char (point-min))
4112 (while (or (and ext-setup-or-nil
4113 (string-match re ext-setup-or-nil start)
4114 (setq start (match-end 0)))
4115 (and (setq ext-setup-or-nil nil start 0)
4116 (re-search-forward re nil t)))
4117 (setq key (upcase (match-string 1 ext-setup-or-nil))
4118 value (org-match-string-no-properties 2 ext-setup-or-nil))
4119 (if (stringp value) (setq value (org-trim value)))
4120 (cond
4121 ((equal key "CATEGORY")
4122 (setq cat value))
4123 ((member key '("SEQ_TODO" "TODO"))
4124 (push (cons 'sequence (org-split-string value splitre)) kwds))
4125 ((equal key "TYP_TODO")
4126 (push (cons 'type (org-split-string value splitre)) kwds))
4127 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4128 ;; general TODO-like setup
4129 (push (cons (intern (downcase (match-string 1 key)))
4130 (org-split-string value splitre)) kwds))
4131 ((equal key "TAGS")
4132 (setq tags (append tags (if tags '("\\n") nil)
4133 (org-split-string value splitre))))
4134 ((equal key "COLUMNS")
4135 (org-set-local 'org-columns-default-format value))
4136 ((equal key "LINK")
4137 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4138 (push (cons (match-string 1 value)
4139 (org-trim (match-string 2 value)))
4140 links)))
4141 ((equal key "PRIORITIES")
4142 (setq prio (org-split-string value " +")))
4143 ((equal key "PROPERTY")
4144 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4145 (push (cons (match-string 1 value) (match-string 2 value))
4146 props)))
4147 ((equal key "FILETAGS")
4148 (when (string-match "\\S-" value)
4149 (setq ftags
4150 (append
4151 ftags
4152 (apply 'append
4153 (mapcar (lambda (x) (org-split-string x ":"))
4154 (org-split-string value)))))))
4155 ((equal key "DRAWERS")
4156 (setq drawers (org-split-string value splitre)))
4157 ((equal key "CONSTANTS")
4158 (setq const (append const (org-split-string value splitre))))
4159 ((equal key "STARTUP")
4160 (let ((opts (org-split-string value splitre))
4161 l var val)
4162 (while (setq l (pop opts))
4163 (when (setq l (assoc l org-startup-options))
4164 (setq var (nth 1 l) val (nth 2 l))
4165 (if (not (nth 3 l))
4166 (set (make-local-variable var) val)
4167 (if (not (listp (symbol-value var)))
4168 (set (make-local-variable var) nil))
4169 (set (make-local-variable var) (symbol-value var))
4170 (add-to-list var val))))))
4171 ((equal key "ARCHIVE")
4172 (setq arch value)
4173 (remove-text-properties 0 (length arch)
4174 '(face t fontified t) arch))
4175 ((equal key "LATEX_CLASS")
4176 (setq beamer-p (equal value "beamer")))
4177 ((equal key "OPTIONS")
4178 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4179 (setq scripts (read (match-string 2 value)))))
4180 ((equal key "SETUPFILE")
4181 (setq setup-contents (org-file-contents
4182 (expand-file-name
4183 (org-remove-double-quotes value))
4184 'noerror))
4185 (if (not ext-setup-or-nil)
4186 (setq ext-setup-or-nil setup-contents start 0)
4187 (setq ext-setup-or-nil
4188 (concat (substring ext-setup-or-nil 0 start)
4189 "\n" setup-contents "\n"
4190 (substring ext-setup-or-nil start)))))
4191 ))))
4192 (org-set-local 'org-use-sub-superscripts scripts)
4193 (when cat
4194 (org-set-local 'org-category (intern cat))
4195 (push (cons "CATEGORY" cat) props))
4196 (when prio
4197 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4198 (setq prio (mapcar 'string-to-char prio))
4199 (org-set-local 'org-highest-priority (nth 0 prio))
4200 (org-set-local 'org-lowest-priority (nth 1 prio))
4201 (org-set-local 'org-default-priority (nth 2 prio)))
4202 (and props (org-set-local 'org-file-properties (nreverse props)))
4203 (and ftags (org-set-local 'org-file-tags
4204 (mapcar 'org-add-prop-inherited ftags)))
4205 (and drawers (org-set-local 'org-drawers drawers))
4206 (and arch (org-set-local 'org-archive-location arch))
4207 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4208 ;; Process the TODO keywords
4209 (unless kwds
4210 ;; Use the global values as if they had been given locally.
4211 (setq kwds (default-value 'org-todo-keywords))
4212 (if (stringp (car kwds))
4213 (setq kwds (list (cons org-todo-interpretation
4214 (default-value 'org-todo-keywords)))))
4215 (setq kwds (reverse kwds)))
4216 (setq kwds (nreverse kwds))
4217 (let (inter kws kw)
4218 (while (setq kws (pop kwds))
4219 (let ((kws (or
4220 (run-hook-with-args-until-success
4221 'org-todo-setup-filter-hook kws)
4222 kws)))
4223 (setq inter (pop kws) sep (member "|" kws)
4224 kws0 (delete "|" (copy-sequence kws))
4225 kwsa nil
4226 kws1 (mapcar
4227 (lambda (x)
4228 ;; 1 2
4229 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4230 (progn
4231 (setq kw (match-string 1 x)
4232 key (and (match-end 2) (match-string 2 x))
4233 log (org-extract-log-state-settings x))
4234 (push (cons kw (and key (string-to-char key))) kwsa)
4235 (and log (push log org-todo-log-states))
4237 (error "Invalid TODO keyword %s" x)))
4238 kws0)
4239 kwsa (if kwsa (append '((:startgroup))
4240 (nreverse kwsa)
4241 '((:endgroup))))
4242 hw (car kws1)
4243 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4244 tail (list inter hw (car dws) (org-last dws))))
4245 (add-to-list 'org-todo-heads hw 'append)
4246 (push kws1 org-todo-sets)
4247 (setq org-done-keywords (append org-done-keywords dws nil))
4248 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4249 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4250 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4251 (setq org-todo-sets (nreverse org-todo-sets)
4252 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4253 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4254 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4255 ;; Process the constants
4256 (when const
4257 (let (e cst)
4258 (while (setq e (pop const))
4259 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4260 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4261 (setq org-table-formula-constants-local cst)))
4263 ;; Process the tags.
4264 (when tags
4265 (let (e tgs)
4266 (while (setq e (pop tags))
4267 (cond
4268 ((equal e "{") (push '(:startgroup) tgs))
4269 ((equal e "}") (push '(:endgroup) tgs))
4270 ((equal e "\\n") (push '(:newline) tgs))
4271 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4272 (push (cons (match-string 1 e)
4273 (string-to-char (match-string 2 e)))
4274 tgs))
4275 (t (push (list e) tgs))))
4276 (org-set-local 'org-tag-alist nil)
4277 (while (setq e (pop tgs))
4278 (or (and (stringp (car e))
4279 (assoc (car e) org-tag-alist))
4280 (push e org-tag-alist)))))
4282 ;; Compute the regular expressions and other local variables
4283 (if (not org-done-keywords)
4284 (setq org-done-keywords (and org-todo-keywords-1
4285 (list (org-last org-todo-keywords-1)))))
4286 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4287 (length org-scheduled-string)
4288 (length org-clock-string)
4289 (length org-closed-string)))
4290 org-drawer-regexp
4291 (concat "^[ \t]*:\\("
4292 (mapconcat 'regexp-quote org-drawers "\\|")
4293 "\\):[ \t]*$")
4294 org-not-done-keywords
4295 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4296 org-todo-regexp
4297 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4298 "\\|") "\\)\\>")
4299 org-not-done-regexp
4300 (concat "\\<\\("
4301 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4302 "\\)\\>")
4303 org-not-done-heading-regexp
4304 (concat "^\\(\\*+\\)[ \t]+\\("
4305 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4306 "\\)\\>")
4307 org-todo-line-regexp
4308 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4309 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4310 "\\)\\>\\)?[ \t]*\\(.*\\)")
4311 org-complex-heading-regexp
4312 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4313 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4314 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4315 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4316 org-complex-heading-regexp-format
4317 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4318 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4319 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4320 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4321 org-nl-done-regexp
4322 (concat "\n\\*+[ \t]+"
4323 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4324 "\\)" "\\>")
4325 org-todo-line-tags-regexp
4326 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4327 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4328 (org-re
4329 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4330 org-looking-at-done-regexp
4331 (concat "^" "\\(?:"
4332 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4333 "\\>")
4334 org-deadline-regexp (concat "\\<" org-deadline-string)
4335 org-deadline-time-regexp
4336 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4337 org-deadline-line-regexp
4338 (concat "\\<\\(" org-deadline-string "\\).*")
4339 org-scheduled-regexp
4340 (concat "\\<" org-scheduled-string)
4341 org-scheduled-time-regexp
4342 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4343 org-closed-time-regexp
4344 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4345 org-keyword-time-regexp
4346 (concat "\\<\\(" org-scheduled-string
4347 "\\|" org-deadline-string
4348 "\\|" org-closed-string
4349 "\\|" org-clock-string "\\)"
4350 " *[[<]\\([^]>]+\\)[]>]")
4351 org-keyword-time-not-clock-regexp
4352 (concat "\\<\\(" org-scheduled-string
4353 "\\|" org-deadline-string
4354 "\\|" org-closed-string
4355 "\\)"
4356 " *[[<]\\([^]>]+\\)[]>]")
4357 org-maybe-keyword-time-regexp
4358 (concat "\\(\\<\\(" org-scheduled-string
4359 "\\|" org-deadline-string
4360 "\\|" org-closed-string
4361 "\\|" org-clock-string "\\)\\)?"
4362 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4363 org-planning-or-clock-line-re
4364 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4365 "\\|" org-deadline-string
4366 "\\|" org-closed-string "\\|" org-clock-string
4367 "\\)\\>\\)")
4368 org-all-time-keywords
4369 (mapcar (lambda (w) (substring w 0 -1))
4370 (list org-scheduled-string org-deadline-string
4371 org-clock-string org-closed-string))
4373 (org-compute-latex-and-specials-regexp)
4374 (org-set-font-lock-defaults))))
4376 (defun org-file-contents (file &optional noerror)
4377 "Return the contents of FILE, as a string."
4378 (if (or (not file)
4379 (not (file-readable-p file)))
4380 (if noerror
4381 (progn
4382 (message "Cannot read file \"%s\"" file)
4383 (ding) (sit-for 2)
4385 (error "Cannot read file \"%s\"" file))
4386 (with-temp-buffer
4387 (insert-file-contents file)
4388 (buffer-string))))
4390 (defun org-extract-log-state-settings (x)
4391 "Extract the log state setting from a TODO keyword string.
4392 This will extract info from a string like \"WAIT(w@/!)\"."
4393 (let (kw key log1 log2)
4394 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4395 (setq kw (match-string 1 x)
4396 key (and (match-end 2) (match-string 2 x))
4397 log1 (and (match-end 3) (match-string 3 x))
4398 log2 (and (match-end 4) (match-string 4 x)))
4399 (and (or log1 log2)
4400 (list kw
4401 (and log1 (if (equal log1 "!") 'time 'note))
4402 (and log2 (if (equal log2 "!") 'time 'note)))))))
4404 (defun org-remove-keyword-keys (list)
4405 "Remove a pair of parenthesis at the end of each string in LIST."
4406 (mapcar (lambda (x)
4407 (if (string-match "(.*)$" x)
4408 (substring x 0 (match-beginning 0))
4410 list))
4412 (defun org-assign-fast-keys (alist)
4413 "Assign fast keys to a keyword-key alist.
4414 Respect keys that are already there."
4415 (let (new e (alt ?0))
4416 (while (setq e (pop alist))
4417 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4418 (cdr e)) ;; Key already assigned.
4419 (push e new)
4420 (let ((clist (string-to-list (downcase (car e))))
4421 (used (append new alist)))
4422 (when (= (car clist) ?@)
4423 (pop clist))
4424 (while (and clist (rassoc (car clist) used))
4425 (pop clist))
4426 (unless clist
4427 (while (rassoc alt used)
4428 (incf alt)))
4429 (push (cons (car e) (or (car clist) alt)) new))))
4430 (nreverse new)))
4432 ;;; Some variables used in various places
4434 (defvar org-window-configuration nil
4435 "Used in various places to store a window configuration.")
4436 (defvar org-selected-window nil
4437 "Used in various places to store a window configuration.")
4438 (defvar org-finish-function nil
4439 "Function to be called when `C-c C-c' is used.
4440 This is for getting out of special buffers like remember.")
4443 ;; FIXME: Occasionally check by commenting these, to make sure
4444 ;; no other functions uses these, forgetting to let-bind them.
4445 (defvar entry)
4446 (defvar last-state)
4447 (defvar date)
4449 ;; Defined somewhere in this file, but used before definition.
4450 (defvar org-entities) ;; defined in org-entities.el
4451 (defvar org-struct-menu)
4452 (defvar org-org-menu)
4453 (defvar org-tbl-menu)
4455 ;;;; Define the Org-mode
4457 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4458 (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."))
4461 ;; We use a before-change function to check if a table might need
4462 ;; an update.
4463 (defvar org-table-may-need-update t
4464 "Indicates that a table might need an update.
4465 This variable is set by `org-before-change-function'.
4466 `org-table-align' sets it back to nil.")
4467 (defun org-before-change-function (beg end)
4468 "Every change indicates that a table might need an update."
4469 (setq org-table-may-need-update t))
4470 (defvar org-mode-map)
4471 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4472 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4473 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4474 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4475 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4476 (defvar org-table-buffer-is-an nil)
4477 (defconst org-outline-regexp "\\*+ ")
4479 ;;;###autoload
4480 (define-derived-mode org-mode outline-mode "Org"
4481 "Outline-based notes management and organizer, alias
4482 \"Carsten's outline-mode for keeping track of everything.\"
4484 Org-mode develops organizational tasks around a NOTES file which
4485 contains information about projects as plain text. Org-mode is
4486 implemented on top of outline-mode, which is ideal to keep the content
4487 of large files well structured. It supports ToDo items, deadlines and
4488 time stamps, which magically appear in the diary listing of the Emacs
4489 calendar. Tables are easily created with a built-in table editor.
4490 Plain text URL-like links connect to websites, emails (VM), Usenet
4491 messages (Gnus), BBDB entries, and any files related to the project.
4492 For printing and sharing of notes, an Org-mode file (or a part of it)
4493 can be exported as a structured ASCII or HTML file.
4495 The following commands are available:
4497 \\{org-mode-map}"
4499 ;; Get rid of Outline menus, they are not needed
4500 ;; Need to do this here because define-derived-mode sets up
4501 ;; the keymap so late. Still, it is a waste to call this each time
4502 ;; we switch another buffer into org-mode.
4503 (if (featurep 'xemacs)
4504 (when (boundp 'outline-mode-menu-heading)
4505 ;; Assume this is Greg's port, it uses easymenu
4506 (easy-menu-remove outline-mode-menu-heading)
4507 (easy-menu-remove outline-mode-menu-show)
4508 (easy-menu-remove outline-mode-menu-hide))
4509 (define-key org-mode-map [menu-bar headings] 'undefined)
4510 (define-key org-mode-map [menu-bar hide] 'undefined)
4511 (define-key org-mode-map [menu-bar show] 'undefined))
4513 (org-load-modules-maybe)
4514 (easy-menu-add org-org-menu)
4515 (easy-menu-add org-tbl-menu)
4516 (org-install-agenda-files-menu)
4517 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4518 (add-to-invisibility-spec '(org-cwidth))
4519 (add-to-invisibility-spec '(org-hide-block . t))
4520 (when (featurep 'xemacs)
4521 (org-set-local 'line-move-ignore-invisible t))
4522 (org-set-local 'outline-regexp org-outline-regexp)
4523 (org-set-local 'outline-level 'org-outline-level)
4524 (when (and org-ellipsis
4525 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4526 (fboundp 'make-glyph-code))
4527 (unless org-display-table
4528 (setq org-display-table (make-display-table)))
4529 (set-display-table-slot
4530 org-display-table 4
4531 (vconcat (mapcar
4532 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4533 org-ellipsis)))
4534 (if (stringp org-ellipsis) org-ellipsis "..."))))
4535 (setq buffer-display-table org-display-table))
4536 (org-set-regexps-and-options)
4537 (when (and org-tag-faces (not org-tags-special-faces-re))
4538 ;; tag faces set outside customize.... force initialization.
4539 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4540 ;; Calc embedded
4541 (org-set-local 'calc-embedded-open-mode "# ")
4542 (modify-syntax-entry ?@ "w")
4543 (if org-startup-truncated (setq truncate-lines t))
4544 (org-set-local 'font-lock-unfontify-region-function
4545 'org-unfontify-region)
4546 ;; Activate before-change-function
4547 (org-set-local 'org-table-may-need-update t)
4548 (org-add-hook 'before-change-functions 'org-before-change-function nil
4549 'local)
4550 ;; Check for running clock before killing a buffer
4551 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4552 ;; Paragraphs and auto-filling
4553 (org-set-autofill-regexps)
4554 (setq indent-line-function 'org-indent-line-function)
4555 (org-update-radio-target-regexp)
4556 ;; Beginning/end of defun
4557 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4558 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4559 ;; Make sure dependence stuff works reliably, even for users who set it
4560 ;; too late :-(
4561 (if org-enforce-todo-dependencies
4562 (add-hook 'org-blocker-hook
4563 'org-block-todo-from-children-or-siblings-or-parent)
4564 (remove-hook 'org-blocker-hook
4565 'org-block-todo-from-children-or-siblings-or-parent))
4566 (if org-enforce-todo-checkbox-dependencies
4567 (add-hook 'org-blocker-hook
4568 'org-block-todo-from-checkboxes)
4569 (remove-hook 'org-blocker-hook
4570 'org-block-todo-from-checkboxes))
4572 ;; Comment characters
4573 ;; (org-set-local 'comment-start "#")
4574 (org-set-local 'comment-padding " ")
4575 (modify-syntax-entry ?# "<")
4576 ;; (modify-syntax-entry ?\n ">")
4578 ;; Align options lines
4579 (org-set-local
4580 'align-mode-rules-list
4581 '((org-in-buffer-settings
4582 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4583 (modes . '(org-mode)))))
4585 ;; Imenu
4586 (org-set-local 'imenu-create-index-function
4587 'org-imenu-get-tree)
4589 ;; Make isearch reveal context
4590 (if (or (featurep 'xemacs)
4591 (not (boundp 'outline-isearch-open-invisible-function)))
4592 ;; Emacs 21 and XEmacs make use of the hook
4593 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4594 ;; Emacs 22 deals with this through a special variable
4595 (org-set-local 'outline-isearch-open-invisible-function
4596 (lambda (&rest ignore) (org-show-context 'isearch))))
4598 ;; Turn on org-beamer-mode?
4599 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4601 ;; If empty file that did not turn on org-mode automatically, make it to.
4602 (if (and org-insert-mode-line-in-empty-file
4603 (interactive-p)
4604 (= (point-min) (point-max)))
4605 (insert "# -*- mode: org -*-\n\n"))
4606 (unless org-inhibit-startup
4607 (when org-startup-align-all-tables
4608 (let ((bmp (buffer-modified-p)))
4609 (org-table-map-tables 'org-table-align 'quietly)
4610 (set-buffer-modified-p bmp)))
4611 (when org-startup-indented
4612 (require 'org-indent)
4613 (org-indent-mode 1))
4614 (unless org-inhibit-startup-visibility-stuff
4615 (org-set-startup-visibility))))
4617 (when (fboundp 'abbrev-table-put)
4618 (abbrev-table-put org-mode-abbrev-table
4619 :parents (list text-mode-abbrev-table)))
4621 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4623 (defun org-current-time ()
4624 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4625 (if (> (car org-time-stamp-rounding-minutes) 1)
4626 (let ((r (car org-time-stamp-rounding-minutes))
4627 (time (decode-time)))
4628 (apply 'encode-time
4629 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4630 (nthcdr 2 time))))
4631 (current-time)))
4633 ;;;; Font-Lock stuff, including the activators
4635 (defvar org-mouse-map (make-sparse-keymap))
4636 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4637 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4638 (when org-mouse-1-follows-link
4639 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4640 (when org-tab-follows-link
4641 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4642 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4644 (require 'font-lock)
4646 (defconst org-non-link-chars "]\t\n\r<>")
4647 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4648 "shell" "elisp" "doi"))
4649 (defvar org-link-types-re nil
4650 "Matches a link that has a url-like prefix like \"http:\"")
4651 (defvar org-link-re-with-space nil
4652 "Matches a link with spaces, optional angular brackets around it.")
4653 (defvar org-link-re-with-space2 nil
4654 "Matches a link with spaces, optional angular brackets around it.")
4655 (defvar org-link-re-with-space3 nil
4656 "Matches a link with spaces, only for internal part in bracket links.")
4657 (defvar org-angle-link-re nil
4658 "Matches link with angular brackets, spaces are allowed.")
4659 (defvar org-plain-link-re nil
4660 "Matches plain link, without spaces.")
4661 (defvar org-bracket-link-regexp nil
4662 "Matches a link in double brackets.")
4663 (defvar org-bracket-link-analytic-regexp nil
4664 "Regular expression used to analyze links.
4665 Here is what the match groups contain after a match:
4666 1: http:
4667 2: http
4668 3: path
4669 4: [desc]
4670 5: desc")
4671 (defvar org-bracket-link-analytic-regexp++ nil
4672 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4673 (defvar org-any-link-re nil
4674 "Regular expression matching any link.")
4676 (defcustom org-match-sexp-depth 3
4677 "Number of stacked braces for sub/superscript matching.
4678 This has to be set before loading org.el to be effective."
4679 :group 'org-export-translation ; ??????????????????????????/
4680 :type 'integer)
4682 (defun org-create-multibrace-regexp (left right n)
4683 "Create a regular expression which will match a balanced sexp.
4684 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4685 as single character strings.
4686 The regexp returned will match the entire expression including the
4687 delimiters. It will also define a single group which contains the
4688 match except for the outermost delimiters. The maximum depth of
4689 stacked delimiters is N. Escaping delimiters is not possible."
4690 (let* ((nothing (concat "[^" left right "]*?"))
4691 (or "\\|")
4692 (re nothing)
4693 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4694 (while (> n 1)
4695 (setq n (1- n)
4696 re (concat re or next)
4697 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4698 (concat left "\\(" re "\\)" right)))
4700 (defvar org-match-substring-regexp
4701 (concat
4702 "\\([^\\]\\)\\([_^]\\)\\("
4703 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4704 "\\|"
4705 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4706 "\\|"
4707 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4708 "The regular expression matching a sub- or superscript.")
4710 (defvar org-match-substring-with-braces-regexp
4711 (concat
4712 "\\([^\\]\\)\\([_^]\\)\\("
4713 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4714 "\\)")
4715 "The regular expression matching a sub- or superscript, forcing braces.")
4717 (defun org-make-link-regexps ()
4718 "Update the link regular expressions.
4719 This should be called after the variable `org-link-types' has changed."
4720 (setq org-link-types-re
4721 (concat
4722 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4723 org-link-re-with-space
4724 (concat
4725 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4726 "\\([^" org-non-link-chars " ]"
4727 "[^" org-non-link-chars "]*"
4728 "[^" org-non-link-chars " ]\\)>?")
4729 org-link-re-with-space2
4730 (concat
4731 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4732 "\\([^" org-non-link-chars " ]"
4733 "[^\t\n\r]*"
4734 "[^" org-non-link-chars " ]\\)>?")
4735 org-link-re-with-space3
4736 (concat
4737 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4738 "\\([^" org-non-link-chars " ]"
4739 "[^\t\n\r]*\\)")
4740 org-angle-link-re
4741 (concat
4742 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4743 "\\([^" org-non-link-chars " ]"
4744 "[^" org-non-link-chars "]*"
4745 "\\)>")
4746 org-plain-link-re
4747 (concat
4748 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4749 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4750 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4751 org-bracket-link-regexp
4752 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4753 org-bracket-link-analytic-regexp
4754 (concat
4755 "\\[\\["
4756 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4757 "\\([^]]+\\)"
4758 "\\]"
4759 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4760 "\\]")
4761 org-bracket-link-analytic-regexp++
4762 (concat
4763 "\\[\\["
4764 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4765 "\\([^]]+\\)"
4766 "\\]"
4767 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4768 "\\]")
4769 org-any-link-re
4770 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4771 org-angle-link-re "\\)\\|\\("
4772 org-plain-link-re "\\)")))
4774 (org-make-link-regexps)
4776 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4777 "Regular expression for fast time stamp matching.")
4778 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4779 "Regular expression for fast time stamp matching.")
4780 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4781 "Regular expression matching time strings for analysis.
4782 This one does not require the space after the date, so it can be used
4783 on a string that terminates immediately after the date.")
4784 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4785 "Regular expression matching time strings for analysis.")
4786 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4787 "Regular expression matching time stamps, with groups.")
4788 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4789 "Regular expression matching time stamps (also [..]), with groups.")
4790 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4791 "Regular expression matching a time stamp range.")
4792 (defconst org-tr-regexp-both
4793 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4794 "Regular expression matching a time stamp range.")
4795 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4796 org-ts-regexp "\\)?")
4797 "Regular expression matching a time stamp or time stamp range.")
4798 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4799 org-ts-regexp-both "\\)?")
4800 "Regular expression matching a time stamp or time stamp range.
4801 The time stamps may be either active or inactive.")
4803 (defvar org-emph-face nil)
4805 (defun org-do-emphasis-faces (limit)
4806 "Run through the buffer and add overlays to links."
4807 (let (rtn a)
4808 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4809 (if (not (= (char-after (match-beginning 3))
4810 (char-after (match-beginning 4))))
4811 (progn
4812 (setq rtn t)
4813 (setq a (assoc (match-string 3) org-emphasis-alist))
4814 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4815 'face
4816 (nth 1 a))
4817 (and (nth 4 a)
4818 (org-remove-flyspell-overlays-in
4819 (match-beginning 0) (match-end 0)))
4820 (add-text-properties (match-beginning 2) (match-end 2)
4821 '(font-lock-multiline t org-emphasis t))
4822 (when org-hide-emphasis-markers
4823 (add-text-properties (match-end 4) (match-beginning 5)
4824 '(invisible org-link))
4825 (add-text-properties (match-beginning 3) (match-end 3)
4826 '(invisible org-link)))))
4827 (backward-char 1))
4828 rtn))
4830 (defun org-emphasize (&optional char)
4831 "Insert or change an emphasis, i.e. a font like bold or italic.
4832 If there is an active region, change that region to a new emphasis.
4833 If there is no region, just insert the marker characters and position
4834 the cursor between them.
4835 CHAR should be either the marker character, or the first character of the
4836 HTML tag associated with that emphasis. If CHAR is a space, the means
4837 to remove the emphasis of the selected region.
4838 If char is not given (for example in an interactive call) it
4839 will be prompted for."
4840 (interactive)
4841 (let ((eal org-emphasis-alist) e det
4842 (erc org-emphasis-regexp-components)
4843 (prompt "")
4844 (string "") beg end move tag c s)
4845 (if (org-region-active-p)
4846 (setq beg (region-beginning) end (region-end)
4847 string (buffer-substring beg end))
4848 (setq move t))
4850 (while (setq e (pop eal))
4851 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4852 c (aref tag 0))
4853 (push (cons c (string-to-char (car e))) det)
4854 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4855 (substring tag 1)))))
4856 (setq det (nreverse det))
4857 (unless char
4858 (message "%s" (concat "Emphasis marker or tag:" prompt))
4859 (setq char (read-char-exclusive)))
4860 (setq char (or (cdr (assoc char det)) char))
4861 (if (equal char ?\ )
4862 (setq s "" move nil)
4863 (unless (assoc (char-to-string char) org-emphasis-alist)
4864 (error "No such emphasis marker: \"%c\"" char))
4865 (setq s (char-to-string char)))
4866 (while (and (> (length string) 1)
4867 (equal (substring string 0 1) (substring string -1))
4868 (assoc (substring string 0 1) org-emphasis-alist))
4869 (setq string (substring string 1 -1)))
4870 (setq string (concat s string s))
4871 (if beg (delete-region beg end))
4872 (unless (or (bolp)
4873 (string-match (concat "[" (nth 0 erc) "\n]")
4874 (char-to-string (char-before (point)))))
4875 (insert " "))
4876 (unless (or (eobp)
4877 (string-match (concat "[" (nth 1 erc) "\n]")
4878 (char-to-string (char-after (point)))))
4879 (insert " ") (backward-char 1))
4880 (insert string)
4881 (and move (backward-char 1))))
4883 (defconst org-nonsticky-props
4884 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4886 (defsubst org-rear-nonsticky-at (pos)
4887 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4889 (defun org-activate-plain-links (limit)
4890 "Run through the buffer and add overlays to links."
4891 (catch 'exit
4892 (let (f)
4893 (if (re-search-forward org-plain-link-re limit t)
4894 (progn
4895 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4896 (setq f (get-text-property (match-beginning 0) 'face))
4897 (if (or (eq f 'org-tag)
4898 (and (listp f) (memq 'org-tag f)))
4900 (add-text-properties (match-beginning 0) (match-end 0)
4901 (list 'mouse-face 'highlight
4902 'face 'org-link
4903 'keymap org-mouse-map))
4904 (org-rear-nonsticky-at (match-end 0)))
4905 t)))))
4907 (defun org-activate-code (limit)
4908 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4909 (progn
4910 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4911 (remove-text-properties (match-beginning 0) (match-end 0)
4912 '(display t invisible t intangible t))
4913 t)))
4915 (defun org-fontify-meta-lines-and-blocks (limit)
4916 "Fontify #+ lines and blocks, in the correct ways."
4917 (let ((case-fold-search t))
4918 (if (re-search-forward
4919 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4920 limit t)
4921 (let ((beg (match-beginning 0))
4922 (beg1 (line-beginning-position 2))
4923 (dc1 (downcase (match-string 2)))
4924 (dc3 (downcase (match-string 3)))
4925 end end1 quoting block-type)
4926 (cond
4927 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4928 ;; a single line of backend-specific content
4929 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4930 (remove-text-properties (match-beginning 0) (match-end 0)
4931 '(display t invisible t intangible t))
4932 (add-text-properties (match-beginning 1) (match-end 3)
4933 '(font-lock-fontified t face org-meta-line))
4934 (add-text-properties (match-beginning 6) (match-end 6)
4935 '(font-lock-fontified t face org-block))
4937 ((and (match-end 4) (equal dc3 "begin"))
4938 ;; Truly a block
4939 (setq block-type (downcase (match-string 5))
4940 quoting (member block-type org-protecting-blocks))
4941 (when (re-search-forward
4942 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4943 nil t) ;; on purpose, we look further than LIMIT
4944 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4945 (when quoting
4946 (remove-text-properties beg end
4947 '(display t invisible t intangible t)))
4948 (add-text-properties
4949 beg end
4950 '(font-lock-fontified t font-lock-multiline t))
4951 (add-text-properties beg beg1 '(face org-meta-line))
4952 (add-text-properties end1 end '(face org-meta-line))
4953 (cond
4954 (quoting
4955 (add-text-properties beg1 end1 '(face org-block)))
4956 ((not org-fontify-quote-and-verse-blocks))
4957 ((string= block-type "quote")
4958 (add-text-properties beg1 end1 '(face org-quote)))
4959 ((string= block-type "verse")
4960 (add-text-properties beg1 end1 '(face org-verse))))
4962 ((member dc1 '("title:" "author:" "email:" "date:"))
4963 (add-text-properties
4964 beg (match-end 3)
4965 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4966 '(font-lock-fontified t invisible t)
4967 '(font-lock-fontified t face org-document-info-keyword)))
4968 (add-text-properties
4969 (match-beginning 6) (match-end 6)
4970 (if (string-equal dc1 "title:")
4971 '(font-lock-fontified t face org-document-title)
4972 '(font-lock-fontified t face org-document-info))))
4973 ((not (member (char-after beg) '(?\ ?\t)))
4974 ;; just any other in-buffer setting, but not indented
4975 (add-text-properties
4976 beg (match-end 0)
4977 '(font-lock-fontified t face org-meta-line))
4979 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4980 "orgtbl:" "tblfm:" "tblname:"))
4981 (and (match-end 4) (equal dc3 "attr")))
4982 (add-text-properties
4983 beg (match-end 0)
4984 '(font-lock-fontified t face org-meta-line))
4986 ((member dc3 '(" " ""))
4987 (add-text-properties
4988 beg (match-end 0)
4989 '(font-lock-fontified t face font-lock-comment-face)))
4990 (t nil))))))
4992 (defun org-activate-angle-links (limit)
4993 "Run through the buffer and add overlays to links."
4994 (if (re-search-forward org-angle-link-re limit t)
4995 (progn
4996 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4997 (add-text-properties (match-beginning 0) (match-end 0)
4998 (list 'mouse-face 'highlight
4999 'keymap org-mouse-map))
5000 (org-rear-nonsticky-at (match-end 0))
5001 t)))
5003 (defun org-activate-footnote-links (limit)
5004 "Run through the buffer and add overlays to links."
5005 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5006 limit t)
5007 (progn
5008 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5009 (add-text-properties (match-beginning 2) (match-end 2)
5010 (list 'mouse-face 'highlight
5011 'keymap org-mouse-map
5012 'help-echo
5013 (if (= (point-at-bol) (match-beginning 2))
5014 "Footnote definition"
5015 "Footnote reference")
5017 (org-rear-nonsticky-at (match-end 2))
5018 t)))
5020 (defun org-activate-bracket-links (limit)
5021 "Run through the buffer and add overlays to bracketed links."
5022 (if (re-search-forward org-bracket-link-regexp limit t)
5023 (let* ((help (concat "LINK: "
5024 (org-match-string-no-properties 1)))
5025 ;; FIXME: above we should remove the escapes.
5026 ;; but that requires another match, protecting match data,
5027 ;; a lot of overhead for font-lock.
5028 (ip (org-maybe-intangible
5029 (list 'invisible 'org-link
5030 'keymap org-mouse-map 'mouse-face 'highlight
5031 'font-lock-multiline t 'help-echo help)))
5032 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5033 'font-lock-multiline t 'help-echo help)))
5034 ;; We need to remove the invisible property here. Table narrowing
5035 ;; may have made some of this invisible.
5036 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5037 (remove-text-properties (match-beginning 0) (match-end 0)
5038 '(invisible nil))
5039 (if (match-end 3)
5040 (progn
5041 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5042 (org-rear-nonsticky-at (match-beginning 3))
5043 (add-text-properties (match-beginning 3) (match-end 3) vp)
5044 (org-rear-nonsticky-at (match-end 3))
5045 (add-text-properties (match-end 3) (match-end 0) ip)
5046 (org-rear-nonsticky-at (match-end 0)))
5047 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5048 (org-rear-nonsticky-at (match-beginning 1))
5049 (add-text-properties (match-beginning 1) (match-end 1) vp)
5050 (org-rear-nonsticky-at (match-end 1))
5051 (add-text-properties (match-end 1) (match-end 0) ip)
5052 (org-rear-nonsticky-at (match-end 0)))
5053 t)))
5055 (defun org-activate-dates (limit)
5056 "Run through the buffer and add overlays to dates."
5057 (if (re-search-forward org-tsr-regexp-both limit t)
5058 (progn
5059 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5060 (add-text-properties (match-beginning 0) (match-end 0)
5061 (list 'mouse-face 'highlight
5062 'keymap org-mouse-map))
5063 (org-rear-nonsticky-at (match-end 0))
5064 (when org-display-custom-times
5065 (if (match-end 3)
5066 (org-display-custom-time (match-beginning 3) (match-end 3)))
5067 (org-display-custom-time (match-beginning 1) (match-end 1)))
5068 t)))
5070 (defvar org-target-link-regexp nil
5071 "Regular expression matching radio targets in plain text.")
5072 (make-variable-buffer-local 'org-target-link-regexp)
5073 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5074 "Regular expression matching a link target.")
5075 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5076 "Regular expression matching a radio target.")
5077 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5078 "Regular expression matching any target.")
5080 (defun org-activate-target-links (limit)
5081 "Run through the buffer and add overlays to target matches."
5082 (when org-target-link-regexp
5083 (let ((case-fold-search t))
5084 (if (re-search-forward org-target-link-regexp limit t)
5085 (progn
5086 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5087 (add-text-properties (match-beginning 0) (match-end 0)
5088 (list 'mouse-face 'highlight
5089 'keymap org-mouse-map
5090 'help-echo "Radio target link"
5091 'org-linked-text t))
5092 (org-rear-nonsticky-at (match-end 0))
5093 t)))))
5095 (defun org-update-radio-target-regexp ()
5096 "Find all radio targets in this file and update the regular expression."
5097 (interactive)
5098 (when (memq 'radio org-activate-links)
5099 (setq org-target-link-regexp
5100 (org-make-target-link-regexp (org-all-targets 'radio)))
5101 (org-restart-font-lock)))
5103 (defun org-hide-wide-columns (limit)
5104 (let (s e)
5105 (setq s (text-property-any (point) (or limit (point-max))
5106 'org-cwidth t))
5107 (when s
5108 (setq e (next-single-property-change s 'org-cwidth))
5109 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5110 (goto-char e)
5111 t)))
5113 (defvar org-latex-and-specials-regexp nil
5114 "Regular expression for highlighting export special stuff.")
5115 (defvar org-match-substring-regexp)
5116 (defvar org-match-substring-with-braces-regexp)
5118 ;; This should be with the exporter code, but we also use if for font-locking
5119 (defconst org-export-html-special-string-regexps
5120 '(("\\\\-" . "&shy;")
5121 ("---\\([^-]\\)" . "&mdash;\\1")
5122 ("--\\([^-]\\)" . "&ndash;\\1")
5123 ("\\.\\.\\." . "&hellip;"))
5124 "Regular expressions for special string conversion.")
5127 (defun org-compute-latex-and-specials-regexp ()
5128 "Compute regular expression for stuff treated specially by exporters."
5129 (if (not org-highlight-latex-fragments-and-specials)
5130 (org-set-local 'org-latex-and-specials-regexp nil)
5131 (require 'org-exp)
5132 (let*
5133 ((matchers (plist-get org-format-latex-options :matchers))
5134 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5135 org-latex-regexps)))
5136 (org-export-allow-BIND nil)
5137 (options (org-combine-plists (org-default-export-plist)
5138 (org-infile-export-plist)))
5139 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5140 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5141 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5142 (org-export-html-expand (plist-get options :expand-quoted-html))
5143 (org-export-with-special-strings (plist-get options :special-strings))
5144 (re-sub
5145 (cond
5146 ((equal org-export-with-sub-superscripts '{})
5147 (list org-match-substring-with-braces-regexp))
5148 (org-export-with-sub-superscripts
5149 (list org-match-substring-regexp))
5150 (t nil)))
5151 (re-latex
5152 (if org-export-with-LaTeX-fragments
5153 (mapcar (lambda (x) (nth 1 x)) latexs)))
5154 (re-macros
5155 (if org-export-with-TeX-macros
5156 (list (concat "\\\\"
5157 (regexp-opt
5158 (append (mapcar 'car (append org-entities-user
5159 org-entities))
5160 (if (boundp 'org-latex-entities)
5161 (mapcar (lambda (x)
5162 (or (car-safe x) x))
5163 org-latex-entities)
5164 nil))
5165 'words))) ; FIXME
5167 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5168 (re-special (if org-export-with-special-strings
5169 (mapcar (lambda (x) (car x))
5170 org-export-html-special-string-regexps)))
5171 (re-rest
5172 (delq nil
5173 (list
5174 (if org-export-html-expand "@<[^>\n]+>")
5175 ))))
5176 (org-set-local
5177 'org-latex-and-specials-regexp
5178 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5179 re-rest) "\\|")))))
5181 (defun org-do-latex-and-special-faces (limit)
5182 "Run through the buffer and add overlays to links."
5183 (when org-latex-and-specials-regexp
5184 (let (rtn d)
5185 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5186 limit t))
5187 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5188 'face))
5189 '(org-code org-verbatim underline)))
5190 (progn
5191 (setq rtn t
5192 d (cond ((member (char-after (1+ (match-beginning 0)))
5193 '(?_ ?^)) 1)
5194 (t 0)))
5195 (font-lock-prepend-text-property
5196 (+ d (match-beginning 0)) (match-end 0)
5197 'face 'org-latex-and-export-specials)
5198 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5199 '(font-lock-multiline t)))))
5200 rtn)))
5202 (defun org-restart-font-lock ()
5203 "Restart font-lock-mode, to force refontification."
5204 (when (and (boundp 'font-lock-mode) font-lock-mode)
5205 (font-lock-mode -1)
5206 (font-lock-mode 1)))
5208 (defun org-all-targets (&optional radio)
5209 "Return a list of all targets in this file.
5210 With optional argument RADIO, only find radio targets."
5211 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5212 rtn)
5213 (save-excursion
5214 (goto-char (point-min))
5215 (while (re-search-forward re nil t)
5216 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5217 rtn)))
5219 (defun org-make-target-link-regexp (targets)
5220 "Make regular expression matching all strings in TARGETS.
5221 The regular expression finds the targets also if there is a line break
5222 between words."
5223 (and targets
5224 (concat
5225 "\\<\\("
5226 (mapconcat
5227 (lambda (x)
5228 (while (string-match " +" x)
5229 (setq x (replace-match "\\s-+" t t x)))
5231 targets
5232 "\\|")
5233 "\\)\\>")))
5235 (defun org-activate-tags (limit)
5236 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5237 (progn
5238 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5239 (add-text-properties (match-beginning 1) (match-end 1)
5240 (list 'mouse-face 'highlight
5241 'keymap org-mouse-map))
5242 (org-rear-nonsticky-at (match-end 1))
5243 t)))
5245 (defun org-outline-level ()
5246 "Compute the outline level of the heading at point.
5247 This function assumes that the cursor is at the beginning of a line matched
5248 by outline-regexp. Otherwise it returns garbage.
5249 If this is called at a normal headline, the level is the number of stars.
5250 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5251 For plain list items, if they are matched by `outline-regexp', this returns
5252 1000 plus the line indentation."
5253 (save-excursion
5254 (looking-at outline-regexp)
5255 (if (match-beginning 1)
5256 (+ (org-get-string-indentation (match-string 1)) 1000)
5257 (1- (- (match-end 0) (match-beginning 0))))))
5259 (defvar org-font-lock-keywords nil)
5261 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5262 "Regular expression matching a property line.")
5264 (defvar org-font-lock-hook nil
5265 "Functions to be called for special font lock stuff.")
5267 (defun org-font-lock-hook (limit)
5268 (run-hook-with-args 'org-font-lock-hook limit))
5270 (defun org-set-font-lock-defaults ()
5271 (let* ((em org-fontify-emphasized-text)
5272 (lk org-activate-links)
5273 (org-font-lock-extra-keywords
5274 (list
5275 ;; Call the hook
5276 '(org-font-lock-hook)
5277 ;; Headlines
5278 `(,(if org-fontify-whole-heading-line
5279 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5280 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5281 (1 (org-get-level-face 1))
5282 (2 (org-get-level-face 2))
5283 (3 (org-get-level-face 3)))
5284 ;; Table lines
5285 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5286 (1 'org-table t))
5287 ;; Table internals
5288 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5289 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5290 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5291 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5292 ;; Drawers
5293 (list org-drawer-regexp '(0 'org-special-keyword t))
5294 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5295 ;; Properties
5296 (list org-property-re
5297 '(1 'org-special-keyword t)
5298 '(3 'org-property-value t))
5299 ;; Links
5300 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5301 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5302 (if (memq 'plain lk) '(org-activate-plain-links))
5303 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5304 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5305 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5306 (if (memq 'footnote lk) '(org-activate-footnote-links
5307 (2 'org-footnote t)))
5308 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5309 '(org-hide-wide-columns (0 nil append))
5310 ;; TODO lines
5311 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5312 '(1 (org-get-todo-face 1) t))
5313 ;; DONE
5314 (if org-fontify-done-headline
5315 (list (concat "^[*]+ +\\<\\("
5316 (mapconcat 'regexp-quote org-done-keywords "\\|")
5317 "\\)\\(.*\\)")
5318 '(2 'org-headline-done t))
5319 nil)
5320 ;; Priorities
5321 '(org-font-lock-add-priority-faces)
5322 ;; Tags
5323 '(org-font-lock-add-tag-faces)
5324 ;; Special keywords
5325 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5326 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5327 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5328 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5329 ;; Emphasis
5330 (if em
5331 (if (featurep 'xemacs)
5332 '(org-do-emphasis-faces (0 nil append))
5333 '(org-do-emphasis-faces)))
5334 ;; Checkboxes
5335 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5336 2 'org-checkbox prepend)
5337 (if org-provide-checkbox-statistics
5338 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5339 (0 (org-get-checkbox-statistics-face) t)))
5340 ;; Description list items
5341 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5342 2 'bold prepend)
5343 ;; ARCHIVEd headings
5344 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5345 '(1 'org-archived prepend))
5346 ;; Specials
5347 '(org-do-latex-and-special-faces)
5348 '(org-fontify-entities)
5349 '(org-raise-scripts)
5350 ;; Code
5351 '(org-activate-code (1 'org-code t))
5352 ;; COMMENT
5353 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5354 "\\|" org-quote-string "\\)\\>")
5355 '(1 'org-special-keyword t))
5356 '("^#.*" (0 'font-lock-comment-face t))
5357 ;; Blocks and meta lines
5358 '(org-fontify-meta-lines-and-blocks)
5360 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5361 ;; Now set the full font-lock-keywords
5362 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5363 (org-set-local 'font-lock-defaults
5364 '(org-font-lock-keywords t nil nil backward-paragraph))
5365 (kill-local-variable 'font-lock-keywords) nil))
5367 (defun org-toggle-pretty-entities ()
5368 "Toggle the compostion display of entities as UTF8 characters."
5369 (interactive)
5370 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5371 (org-restart-font-lock)
5372 (if org-pretty-entities
5373 (message "Entities are displayed as UTF8 characers")
5374 (save-restriction
5375 (widen)
5376 (decompose-region (point-min) (point-max))
5377 (message "Entities are displayed plain"))))
5379 (defun org-fontify-entities (limit)
5380 "Find an entity to fontify."
5381 (let (ee)
5382 (when org-pretty-entities
5383 (catch 'match
5384 (while (re-search-forward
5385 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5386 limit t)
5387 (if (and (not (org-in-indented-comment-line))
5388 (setq ee (org-entity-get (match-string 1)))
5389 (= (length (nth 6 ee)) 1))
5390 (progn
5391 (add-text-properties
5392 (match-beginning 0) (match-end 1)
5393 (list 'font-lock-fontified t))
5394 (compose-region (match-beginning 0) (match-end 1)
5395 (nth 6 ee) nil)
5396 (backward-char 1)
5397 (throw 'match t))))
5398 nil))))
5400 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5401 "Fontify string S like in Org-mode"
5402 (with-temp-buffer
5403 (insert s)
5404 (let ((org-odd-levels-only odd-levels))
5405 (org-mode)
5406 (font-lock-fontify-buffer)
5407 (buffer-string))))
5409 (defvar org-m nil)
5410 (defvar org-l nil)
5411 (defvar org-f nil)
5412 (defun org-get-level-face (n)
5413 "Get the right face for match N in font-lock matching of headlines."
5414 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5415 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5416 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5417 (cond
5418 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5419 ((eq n 2) org-f)
5420 (t (if org-level-color-stars-only nil org-f))))
5422 (defun org-get-todo-face (kwd)
5423 "Get the right face for a TODO keyword KWD.
5424 If KWD is a number, get the corresponding match group."
5425 (if (numberp kwd) (setq kwd (match-string kwd)))
5426 (or (org-face-from-face-or-color
5427 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5428 (and (member kwd org-done-keywords) 'org-done)
5429 'org-todo))
5431 (defun org-face-from-face-or-color (context inherit face-or-color)
5432 "Create a face list that inherits INHERIT, but sets the foreground color.
5433 When FACE-OR-COLOR is not a string, just return it."
5434 (if (stringp face-or-color)
5435 (list :inherit inherit
5436 (cdr (assoc context org-faces-easy-properties))
5437 face-or-color)
5438 face-or-color))
5440 (defun org-font-lock-add-tag-faces (limit)
5441 "Add the special tag faces."
5442 (when (and org-tag-faces org-tags-special-faces-re)
5443 (while (re-search-forward org-tags-special-faces-re limit t)
5444 (add-text-properties (match-beginning 1) (match-end 1)
5445 (list 'face (org-get-tag-face 1)
5446 'font-lock-fontified t))
5447 (backward-char 1))))
5449 (defun org-font-lock-add-priority-faces (limit)
5450 "Add the special priority faces."
5451 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5452 (add-text-properties
5453 (match-beginning 0) (match-end 0)
5454 (list 'face (or (org-face-from-face-or-color
5455 'priority 'org-special-keyword
5456 (cdr (assoc (char-after (match-beginning 1))
5457 org-priority-faces)))
5458 'org-special-keyword)
5459 'font-lock-fontified t))))
5461 (defun org-get-tag-face (kwd)
5462 "Get the right face for a TODO keyword KWD.
5463 If KWD is a number, get the corresponding match group."
5464 (if (numberp kwd) (setq kwd (match-string kwd)))
5465 (or (org-face-from-face-or-color
5466 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5467 'org-tag))
5469 (defun org-unfontify-region (beg end &optional maybe_loudly)
5470 "Remove fontification and activation overlays from links."
5471 (font-lock-default-unfontify-region beg end)
5472 (let* ((buffer-undo-list t)
5473 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5474 (inhibit-modification-hooks t)
5475 deactivate-mark buffer-file-name buffer-file-truename)
5476 (decompose-region beg end)
5477 (remove-text-properties
5478 beg end
5479 (if org-indent-mode
5480 ;; also remove line-prefix and wrap-prefix properties
5481 '(mouse-face t keymap t org-linked-text t
5482 invisible t intangible t
5483 line-prefix t wrap-prefix t
5484 org-no-flyspell t org-emphasis t)
5485 '(mouse-face t keymap t org-linked-text t
5486 invisible t intangible t
5487 org-no-flyspell t org-emphasis t)))
5488 (org-remove-font-lock-display-properties beg end)))
5490 (defconst org-script-display '(((raise -0.3) (height 0.7))
5491 ((raise 0.3) (height 0.7))
5492 ((raise -0.5))
5493 ((raise 0.5)))
5494 "Display properties for showing superscripts and subscripts.")
5496 (defun org-remove-font-lock-display-properties (beg end)
5497 "Remove specific display properties that have been added by font lock.
5498 The will remove the raise properties that are used to show superscripts
5499 and subscriipts."
5500 (let (next prop)
5501 (while (< beg end)
5502 (setq next (next-single-property-change beg 'display nil end)
5503 prop (get-text-property beg 'display))
5504 (if (member prop org-script-display)
5505 (put-text-property beg next 'display nil))
5506 (setq beg next))))
5508 (defun org-raise-scripts (limit)
5509 "Add raise properties to sub/superscripts."
5510 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5511 (if (re-search-forward
5512 (if (eq org-use-sub-superscripts t)
5513 org-match-substring-regexp
5514 org-match-substring-with-braces-regexp)
5515 limit t)
5516 (let* ((pos (point)) table-p comment-p emph-p)
5517 (setq emph-p (get-text-property (match-beginning 3) 'org-emphasis))
5518 (goto-char (point-at-bol))
5519 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5520 comment-p (org-looking-at-p "[ \t]*#"))
5521 (goto-char pos)
5522 (if (or comment-p emph-p)
5524 (put-text-property (match-beginning 3) (match-end 0)
5525 'display
5526 (if (equal (char-after (match-beginning 2)) ?^)
5527 (nth (if table-p 3 1) org-script-display)
5528 (nth (if table-p 2 0) org-script-display)))
5529 (add-text-properties (match-beginning 2) (match-end 2)
5530 (list 'invisible t
5531 'org-dwidth t 'org-dwidth-n 1))
5532 (if (and (eq (char-after (match-beginning 3)) ?{)
5533 (eq (char-before (match-end 3)) ?}))
5534 (progn
5535 (add-text-properties
5536 (match-beginning 3) (1+ (match-beginning 3))
5537 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5538 (add-text-properties
5539 (1- (match-end 3)) (match-end 3)
5540 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5541 t)))))
5543 ;;;; Visibility cycling, including org-goto and indirect buffer
5545 ;;; Cycling
5547 (defvar org-cycle-global-status nil)
5548 (make-variable-buffer-local 'org-cycle-global-status)
5549 (defvar org-cycle-subtree-status nil)
5550 (make-variable-buffer-local 'org-cycle-subtree-status)
5552 ;;;###autoload
5554 (defvar org-inlinetask-min-level)
5556 (defun org-cycle (&optional arg)
5557 "TAB-action and visibility cycling for Org-mode.
5559 This is the command invoked in Org-mode by the TAB key. Its main purpose
5560 is outline visibility cycling, but it also invokes other actions
5561 in special contexts.
5563 - When this function is called with a prefix argument, rotate the entire
5564 buffer through 3 states (global cycling)
5565 1. OVERVIEW: Show only top-level headlines.
5566 2. CONTENTS: Show all headlines of all levels, but no body text.
5567 3. SHOW ALL: Show everything.
5568 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5569 determined by the variable `org-startup-folded', and by any VISIBILITY
5570 properties in the buffer.
5571 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5572 including any drawers.
5574 - When inside a table, re-align the table and move to the next field.
5576 - When point is at the beginning of a headline, rotate the subtree started
5577 by this line through 3 different states (local cycling)
5578 1. FOLDED: Only the main headline is shown.
5579 2. CHILDREN: The main headline and the direct children are shown.
5580 From this state, you can move to one of the children
5581 and zoom in further.
5582 3. SUBTREE: Show the entire subtree, including body text.
5583 If there is no subtree, switch directly from CHILDREN to FOLDED.
5585 - When point is at the beginning of an empty headline and the variable
5586 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5587 of the headline by demoting and promoting it to likely levels. This
5588 speeds up creation document structure by presing TAB once or several
5589 times right after creating a new headline.
5591 - When there is a numeric prefix, go up to a heading with level ARG, do
5592 a `show-subtree' and return to the previous cursor position. If ARG
5593 is negative, go up that many levels.
5595 - When point is not at the beginning of a headline, execute the global
5596 binding for TAB, which is re-indenting the line. See the option
5597 `org-cycle-emulate-tab' for details.
5599 - Special case: if point is at the beginning of the buffer and there is
5600 no headline in line 1, this function will act as if called with prefix arg.
5601 But only if also the variable `org-cycle-global-at-bob' is t."
5602 (interactive "P")
5603 (org-load-modules-maybe)
5604 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5605 (and org-cycle-level-after-item/entry-creation
5606 (or (org-cycle-level)
5607 (org-cycle-item-indentation))))
5608 (let* ((limit-level
5609 (or org-cycle-max-level
5610 (and (boundp 'org-inlinetask-min-level)
5611 org-inlinetask-min-level
5612 (1- org-inlinetask-min-level))))
5613 (nstars (and limit-level
5614 (if org-odd-levels-only
5615 (and limit-level (1- (* limit-level 2)))
5616 limit-level)))
5617 (outline-regexp
5618 (cond
5619 ((not (org-mode-p)) outline-regexp)
5620 ((or (eq org-cycle-include-plain-lists 'integrate)
5621 (and org-cycle-include-plain-lists (org-at-item-p)))
5622 (concat "\\(?:\\*"
5623 (if nstars (format "\\{1,%d\\}" nstars) "+")
5624 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5625 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5626 (bob-special (and org-cycle-global-at-bob (bobp)
5627 (not (looking-at outline-regexp))))
5628 (org-cycle-hook
5629 (if bob-special
5630 (delq 'org-optimize-window-after-visibility-change
5631 (copy-sequence org-cycle-hook))
5632 org-cycle-hook))
5633 (pos (point)))
5635 (if (or bob-special (equal arg '(4)))
5636 ;; special case: use global cycling
5637 (setq arg t))
5639 (cond
5641 ((equal arg '(16))
5642 (org-set-startup-visibility)
5643 (message "Startup visibility, plus VISIBILITY properties"))
5645 ((equal arg '(64))
5646 (show-all)
5647 (message "Entire buffer visible, including drawers"))
5649 ((org-at-table-p 'any)
5650 ;; Enter the table or move to the next field in the table
5651 (if (org-at-table.el-p)
5652 (message "Use C-c ' to edit table.el tables")
5653 (if arg (org-table-edit-field t)
5654 (org-table-justify-field-maybe)
5655 (call-interactively 'org-table-next-field))))
5657 ((run-hook-with-args-until-success
5658 'org-tab-after-check-for-table-hook))
5660 ((eq arg t) ;; Global cycling
5661 (org-cycle-internal-global))
5663 ((and org-drawers org-drawer-regexp
5664 (save-excursion
5665 (beginning-of-line 1)
5666 (looking-at org-drawer-regexp)))
5667 ;; Toggle block visibility
5668 (org-flag-drawer
5669 (not (get-char-property (match-end 0) 'invisible))))
5671 ((integerp arg)
5672 ;; Show-subtree, ARG levels up from here.
5673 (save-excursion
5674 (org-back-to-heading)
5675 (outline-up-heading (if (< arg 0) (- arg)
5676 (- (funcall outline-level) arg)))
5677 (org-show-subtree)))
5679 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5680 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5682 (org-cycle-internal-local))
5684 ;; TAB emulation and template completion
5685 (buffer-read-only (org-back-to-heading))
5687 ((run-hook-with-args-until-success
5688 'org-tab-after-check-for-cycling-hook))
5690 ((org-try-structure-completion))
5692 ((org-try-cdlatex-tab))
5694 ((run-hook-with-args-until-success
5695 'org-tab-before-tab-emulation-hook))
5697 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5698 (or (not (bolp))
5699 (not (looking-at outline-regexp))))
5700 (call-interactively (global-key-binding "\t")))
5702 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5703 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5704 (or (and (eq org-cycle-emulate-tab 'white)
5705 (= (match-end 0) (point-at-eol)))
5706 (and (eq org-cycle-emulate-tab 'whitestart)
5707 (>= (match-end 0) pos))))
5709 (eq org-cycle-emulate-tab t))
5710 (call-interactively (global-key-binding "\t")))
5712 (t (save-excursion
5713 (org-back-to-heading)
5714 (org-cycle)))))))
5716 (defun org-cycle-internal-global ()
5717 "Do the global cycling action."
5718 (cond
5719 ((and (eq last-command this-command)
5720 (eq org-cycle-global-status 'overview))
5721 ;; We just created the overview - now do table of contents
5722 ;; This can be slow in very large buffers, so indicate action
5723 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5724 (message "CONTENTS...")
5725 (org-content)
5726 (message "CONTENTS...done")
5727 (setq org-cycle-global-status 'contents)
5728 (run-hook-with-args 'org-cycle-hook 'contents))
5730 ((and (eq last-command this-command)
5731 (eq org-cycle-global-status 'contents))
5732 ;; We just showed the table of contents - now show everything
5733 (run-hook-with-args 'org-pre-cycle-hook 'all)
5734 (show-all)
5735 (message "SHOW ALL")
5736 (setq org-cycle-global-status 'all)
5737 (run-hook-with-args 'org-cycle-hook 'all))
5740 ;; Default action: go to overview
5741 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5742 (org-overview)
5743 (message "OVERVIEW")
5744 (setq org-cycle-global-status 'overview)
5745 (run-hook-with-args 'org-cycle-hook 'overview))))
5747 (defun org-cycle-internal-local ()
5748 "Do the local cycling action."
5749 (org-back-to-heading)
5750 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5751 ;; First, some boundaries
5752 (save-excursion
5753 (org-back-to-heading)
5754 (setq level (funcall outline-level))
5755 (save-excursion
5756 (beginning-of-line 2)
5757 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5758 ; XEmacs does not have `next-single-char-property-change'
5759 ; I'm not sure about Emacs 21.
5760 (while (and (not (eobp)) ;; this is like `next-line'
5761 (get-char-property (1- (point)) 'invisible))
5762 (beginning-of-line 2))
5763 (while (and (not (eobp)) ;; this is like `next-line'
5764 (get-char-property (1- (point)) 'invisible))
5765 (goto-char (next-single-char-property-change (point) 'invisible))
5766 (and (eolp) (beginning-of-line 2))))
5767 (setq eol (point)))
5768 (outline-end-of-heading) (setq eoh (point))
5769 (save-excursion
5770 (outline-next-heading)
5771 (setq has-children (and (org-at-heading-p t)
5772 (> (funcall outline-level) level))))
5773 (org-end-of-subtree t)
5774 (unless (eobp)
5775 (skip-chars-forward " \t\n")
5776 (beginning-of-line 1) ; in case this is an item
5778 (setq eos (if (eobp) (point) (1- (point)))))
5779 ;; Find out what to do next and set `this-command'
5780 (cond
5781 ((= eos eoh)
5782 ;; Nothing is hidden behind this heading
5783 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5784 (message "EMPTY ENTRY")
5785 (setq org-cycle-subtree-status nil)
5786 (save-excursion
5787 (goto-char eos)
5788 (outline-next-heading)
5789 (if (org-invisible-p) (org-flag-heading nil))))
5790 ((and (or (>= eol eos)
5791 (not (string-match "\\S-" (buffer-substring eol eos))))
5792 (or has-children
5793 (not (setq children-skipped
5794 org-cycle-skip-children-state-if-no-children))))
5795 ;; Entire subtree is hidden in one line: children view
5796 (run-hook-with-args 'org-pre-cycle-hook 'children)
5797 (org-show-entry)
5798 (show-children)
5799 (message "CHILDREN")
5800 (save-excursion
5801 (goto-char eos)
5802 (outline-next-heading)
5803 (if (org-invisible-p) (org-flag-heading nil)))
5804 (setq org-cycle-subtree-status 'children)
5805 (run-hook-with-args 'org-cycle-hook 'children))
5806 ((or children-skipped
5807 (and (eq last-command this-command)
5808 (eq org-cycle-subtree-status 'children)))
5809 ;; We just showed the children, or no children are there,
5810 ;; now show everything.
5811 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5812 (org-show-subtree)
5813 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5814 (setq org-cycle-subtree-status 'subtree)
5815 (run-hook-with-args 'org-cycle-hook 'subtree))
5817 ;; Default action: hide the subtree.
5818 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5819 (hide-subtree)
5820 (message "FOLDED")
5821 (setq org-cycle-subtree-status 'folded)
5822 (run-hook-with-args 'org-cycle-hook 'folded)))))
5824 ;;;###autoload
5825 (defun org-global-cycle (&optional arg)
5826 "Cycle the global visibility. For details see `org-cycle'.
5827 With C-u prefix arg, switch to startup visibility.
5828 With a numeric prefix, show all headlines up to that level."
5829 (interactive "P")
5830 (let ((org-cycle-include-plain-lists
5831 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5832 (cond
5833 ((integerp arg)
5834 (show-all)
5835 (hide-sublevels arg)
5836 (setq org-cycle-global-status 'contents))
5837 ((equal arg '(4))
5838 (org-set-startup-visibility)
5839 (message "Startup visibility, plus VISIBILITY properties."))
5841 (org-cycle '(4))))))
5843 (defun org-set-startup-visibility ()
5844 "Set the visibility required by startup options and properties."
5845 (cond
5846 ((eq org-startup-folded t)
5847 (org-cycle '(4)))
5848 ((eq org-startup-folded 'content)
5849 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5850 (org-cycle '(4)) (org-cycle '(4)))))
5851 (unless (eq org-startup-folded 'showeverything)
5852 (if org-hide-block-startup (org-hide-block-all))
5853 (org-set-visibility-according-to-property 'no-cleanup)
5854 (org-cycle-hide-archived-subtrees 'all)
5855 (org-cycle-hide-drawers 'all)
5856 (org-cycle-show-empty-lines t)))
5858 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5859 "Switch subtree visibilities according to :VISIBILITY: property."
5860 (interactive)
5861 (let (org-show-entry-below state)
5862 (save-excursion
5863 (goto-char (point-min))
5864 (while (re-search-forward
5865 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5866 nil t)
5867 (setq state (match-string 1))
5868 (save-excursion
5869 (org-back-to-heading t)
5870 (hide-subtree)
5871 (org-reveal)
5872 (cond
5873 ((equal state '("fold" "folded"))
5874 (hide-subtree))
5875 ((equal state "children")
5876 (org-show-hidden-entry)
5877 (show-children))
5878 ((equal state "content")
5879 (save-excursion
5880 (save-restriction
5881 (org-narrow-to-subtree)
5882 (org-content))))
5883 ((member state '("all" "showall"))
5884 (show-subtree)))))
5885 (unless no-cleanup
5886 (org-cycle-hide-archived-subtrees 'all)
5887 (org-cycle-hide-drawers 'all)
5888 (org-cycle-show-empty-lines 'all)))))
5890 (defun org-overview ()
5891 "Switch to overview mode, showing only top-level headlines.
5892 Really, this shows all headlines with level equal or greater than the level
5893 of the first headline in the buffer. This is important, because if the
5894 first headline is not level one, then (hide-sublevels 1) gives confusing
5895 results."
5896 (interactive)
5897 (let ((level (save-excursion
5898 (goto-char (point-min))
5899 (if (re-search-forward (concat "^" outline-regexp) nil t)
5900 (progn
5901 (goto-char (match-beginning 0))
5902 (funcall outline-level))))))
5903 (and level (hide-sublevels level))))
5905 (defun org-content (&optional arg)
5906 "Show all headlines in the buffer, like a table of contents.
5907 With numerical argument N, show content up to level N."
5908 (interactive "P")
5909 (save-excursion
5910 ;; Visit all headings and show their offspring
5911 (and (integerp arg) (org-overview))
5912 (goto-char (point-max))
5913 (catch 'exit
5914 (while (and (progn (condition-case nil
5915 (outline-previous-visible-heading 1)
5916 (error (goto-char (point-min))))
5918 (looking-at outline-regexp))
5919 (if (integerp arg)
5920 (show-children (1- arg))
5921 (show-branches))
5922 (if (bobp) (throw 'exit nil))))))
5925 (defun org-optimize-window-after-visibility-change (state)
5926 "Adjust the window after a change in outline visibility.
5927 This function is the default value of the hook `org-cycle-hook'."
5928 (when (get-buffer-window (current-buffer))
5929 (cond
5930 ((eq state 'content) nil)
5931 ((eq state 'all) nil)
5932 ((eq state 'folded) nil)
5933 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5934 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5936 (defun org-remove-empty-overlays-at (pos)
5937 "Remove outline overlays that do not contain non-white stuff."
5938 (mapc
5939 (lambda (o)
5940 (and (eq 'outline (overlay-get o 'invisible))
5941 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5942 (overlay-end o))))
5943 (delete-overlay o)))
5944 (overlays-at pos)))
5946 (defun org-clean-visibility-after-subtree-move ()
5947 "Fix visibility issues after moving a subtree."
5948 ;; First, find a reasonable region to look at:
5949 ;; Start two siblings above, end three below
5950 (let* ((beg (save-excursion
5951 (and (org-get-last-sibling)
5952 (org-get-last-sibling))
5953 (point)))
5954 (end (save-excursion
5955 (and (org-get-next-sibling)
5956 (org-get-next-sibling)
5957 (org-get-next-sibling))
5958 (if (org-at-heading-p)
5959 (point-at-eol)
5960 (point))))
5961 (level (looking-at "\\*+"))
5962 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5963 (save-excursion
5964 (save-restriction
5965 (narrow-to-region beg end)
5966 (when re
5967 ;; Properly fold already folded siblings
5968 (goto-char (point-min))
5969 (while (re-search-forward re nil t)
5970 (if (and (not (org-invisible-p))
5971 (save-excursion
5972 (goto-char (point-at-eol)) (org-invisible-p)))
5973 (hide-entry))))
5974 (org-cycle-show-empty-lines 'overview)
5975 (org-cycle-hide-drawers 'overview)))))
5977 (defun org-cycle-show-empty-lines (state)
5978 "Show empty lines above all visible headlines.
5979 The region to be covered depends on STATE when called through
5980 `org-cycle-hook'. Lisp program can use t for STATE to get the
5981 entire buffer covered. Note that an empty line is only shown if there
5982 are at least `org-cycle-separator-lines' empty lines before the headline."
5983 (when (not (= org-cycle-separator-lines 0))
5984 (save-excursion
5985 (let* ((n (abs org-cycle-separator-lines))
5986 (re (cond
5987 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5988 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5989 (t (let ((ns (number-to-string (- n 2))))
5990 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5991 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5992 beg end b e)
5993 (cond
5994 ((memq state '(overview contents t))
5995 (setq beg (point-min) end (point-max)))
5996 ((memq state '(children folded))
5997 (setq beg (point) end (progn (org-end-of-subtree t t)
5998 (beginning-of-line 2)
5999 (point)))))
6000 (when beg
6001 (goto-char beg)
6002 (while (re-search-forward re end t)
6003 (unless (get-char-property (match-end 1) 'invisible)
6004 (setq e (match-end 1))
6005 (if (< org-cycle-separator-lines 0)
6006 (setq b (save-excursion
6007 (goto-char (match-beginning 0))
6008 (org-back-over-empty-lines)
6009 (if (save-excursion
6010 (goto-char (max (point-min) (1- (point))))
6011 (org-on-heading-p))
6012 (1- (point))
6013 (point))))
6014 (setq b (match-beginning 1)))
6015 (outline-flag-region b e nil)))))))
6016 ;; Never hide empty lines at the end of the file.
6017 (save-excursion
6018 (goto-char (point-max))
6019 (outline-previous-heading)
6020 (outline-end-of-heading)
6021 (if (and (looking-at "[ \t\n]+")
6022 (= (match-end 0) (point-max)))
6023 (outline-flag-region (point) (match-end 0) nil))))
6025 (defun org-show-empty-lines-in-parent ()
6026 "Move to the parent and re-show empty lines before visible headlines."
6027 (save-excursion
6028 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6029 (org-cycle-show-empty-lines context))))
6031 (defun org-files-list ()
6032 "Return `org-agenda-files' list, plus all open org-mode files.
6033 This is useful for operations that need to scan all of a user's
6034 open and agenda-wise Org files."
6035 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6036 (dolist (buf (buffer-list))
6037 (with-current-buffer buf
6038 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6039 (let ((file (expand-file-name (buffer-file-name))))
6040 (unless (member file files)
6041 (push file files))))))
6042 files))
6044 (defsubst org-entry-beginning-position ()
6045 "Return the beginning position of the current entry."
6046 (save-excursion (outline-back-to-heading t) (point)))
6048 (defsubst org-entry-end-position ()
6049 "Return the end position of the current entry."
6050 (save-excursion (outline-next-heading) (point)))
6052 (defun org-cycle-hide-drawers (state)
6053 "Re-hide all drawers after a visibility state change."
6054 (when (and (org-mode-p)
6055 (not (memq state '(overview folded contents))))
6056 (save-excursion
6057 (let* ((globalp (memq state '(contents all)))
6058 (beg (if globalp (point-min) (point)))
6059 (end (if globalp (point-max)
6060 (if (eq state 'children)
6061 (save-excursion (outline-next-heading) (point))
6062 (org-end-of-subtree t)))))
6063 (goto-char beg)
6064 (while (re-search-forward org-drawer-regexp end t)
6065 (org-flag-drawer t))))))
6067 (defun org-flag-drawer (flag)
6068 (save-excursion
6069 (beginning-of-line 1)
6070 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6071 (let ((b (match-end 0))
6072 (outline-regexp org-outline-regexp))
6073 (if (re-search-forward
6074 "^[ \t]*:END:"
6075 (save-excursion (outline-next-heading) (point)) t)
6076 (outline-flag-region b (point-at-eol) flag)
6077 (error ":END: line missing at position %s" b))))))
6079 (defun org-subtree-end-visible-p ()
6080 "Is the end of the current subtree visible?"
6081 (pos-visible-in-window-p
6082 (save-excursion (org-end-of-subtree t) (point))))
6084 (defun org-first-headline-recenter (&optional N)
6085 "Move cursor to the first headline and recenter the headline.
6086 Optional argument N means put the headline into the Nth line of the window."
6087 (goto-char (point-min))
6088 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6089 (beginning-of-line)
6090 (recenter (prefix-numeric-value N))))
6092 ;;; Saving and restoring visibility
6094 (defun org-outline-overlay-data (&optional use-markers)
6095 "Return a list of the locations of all outline overlays.
6096 The are overlays with the `invisible' property value `outline'.
6097 The return valus is a list of cons cells, with start and stop
6098 positions for each overlay.
6099 If USE-MARKERS is set, return the positions as markers."
6100 (let (beg end)
6101 (save-excursion
6102 (save-restriction
6103 (widen)
6104 (delq nil
6105 (mapcar (lambda (o)
6106 (when (eq (overlay-get o 'invisible) 'outline)
6107 (setq beg (overlay-start o)
6108 end (overlay-end o))
6109 (and beg end (> end beg)
6110 (if use-markers
6111 (cons (move-marker (make-marker) beg)
6112 (move-marker (make-marker) end))
6113 (cons beg end)))))
6114 (overlays-in (point-min) (point-max))))))))
6116 (defun org-set-outline-overlay-data (data)
6117 "Create visibility overlays for all positions in DATA.
6118 DATA should have been made by `org-outline-overlay-data'."
6119 (let (o)
6120 (save-excursion
6121 (save-restriction
6122 (widen)
6123 (show-all)
6124 (mapc (lambda (c)
6125 (setq o (make-overlay (car c) (cdr c)))
6126 (overlay-put o 'invisible 'outline))
6127 data)))))
6129 (defmacro org-save-outline-visibility (use-markers &rest body)
6130 "Save and restore outline visibility around BODY.
6131 If USE-MARKERS is non-nil, use markers for the positions.
6132 This means that the buffer may change while running BODY,
6133 but it also means that the buffer should stay alive
6134 during the operation, because otherwise all these markers will
6135 point nowhere."
6136 (declare (indent 1))
6137 `(let ((data (org-outline-overlay-data ,use-markers)))
6138 (unwind-protect
6139 (progn
6140 ,@body
6141 (org-set-outline-overlay-data data))
6142 (when ,use-markers
6143 (mapc (lambda (c)
6144 (and (markerp (car c)) (move-marker (car c) nil))
6145 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
6146 data)))))
6149 ;;; Folding of blocks
6151 (defconst org-block-regexp
6153 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6154 "Regular expression for hiding blocks.")
6156 (defvar org-hide-block-overlays nil
6157 "Overlays hiding blocks.")
6158 (make-variable-buffer-local 'org-hide-block-overlays)
6160 (defun org-block-map (function &optional start end)
6161 "Call func at the head of all source blocks in the current
6162 buffer. Optional arguments START and END can be used to limit
6163 the range."
6164 (let ((start (or start (point-min)))
6165 (end (or end (point-max))))
6166 (save-excursion
6167 (goto-char start)
6168 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6169 (save-excursion
6170 (save-match-data
6171 (goto-char (match-beginning 0))
6172 (funcall function)))))))
6174 (defun org-hide-block-toggle-all ()
6175 "Toggle the visibility of all blocks in the current buffer."
6176 (org-block-map #'org-hide-block-toggle))
6178 (defun org-hide-block-all ()
6179 "Fold all blocks in the current buffer."
6180 (interactive)
6181 (org-show-block-all)
6182 (org-block-map #'org-hide-block-toggle-maybe))
6184 (defun org-show-block-all ()
6185 "Unfold all blocks in the current buffer."
6186 (mapc 'delete-overlay org-hide-block-overlays)
6187 (setq org-hide-block-overlays nil))
6189 (defun org-hide-block-toggle-maybe ()
6190 "Toggle visibility of block at point."
6191 (interactive)
6192 (let ((case-fold-search t))
6193 (if (save-excursion
6194 (beginning-of-line 1)
6195 (looking-at org-block-regexp))
6196 (progn (org-hide-block-toggle)
6197 t) ;; to signal that we took action
6198 nil))) ;; to signal that we did not
6200 (defun org-hide-block-toggle (&optional force)
6201 "Toggle the visibility of the current block."
6202 (interactive)
6203 (save-excursion
6204 (beginning-of-line)
6205 (if (re-search-forward org-block-regexp nil t)
6206 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6207 (end (match-end 0)) ;; end of entire body
6209 (if (memq t (mapcar (lambda (overlay)
6210 (eq (overlay-get overlay 'invisible)
6211 'org-hide-block))
6212 (overlays-at start)))
6213 (if (or (not force) (eq force 'off))
6214 (mapc (lambda (ov)
6215 (when (member ov org-hide-block-overlays)
6216 (setq org-hide-block-overlays
6217 (delq ov org-hide-block-overlays)))
6218 (when (eq (overlay-get ov 'invisible)
6219 'org-hide-block)
6220 (delete-overlay ov)))
6221 (overlays-at start)))
6222 (setq ov (make-overlay start end))
6223 (overlay-put ov 'invisible 'org-hide-block)
6224 ;; make the block accessible to isearch
6225 (overlay-put
6226 ov 'isearch-open-invisible
6227 (lambda (ov)
6228 (when (member ov org-hide-block-overlays)
6229 (setq org-hide-block-overlays
6230 (delq ov org-hide-block-overlays)))
6231 (when (eq (overlay-get ov 'invisible)
6232 'org-hide-block)
6233 (delete-overlay ov))))
6234 (push ov org-hide-block-overlays)))
6235 (error "Not looking at a source block"))))
6237 ;; org-tab-after-check-for-cycling-hook
6238 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6239 ;; Remove overlays when changing major mode
6240 (add-hook 'org-mode-hook
6241 (lambda () (org-add-hook 'change-major-mode-hook
6242 'org-show-block-all 'append 'local)))
6244 ;;; Org-goto
6246 (defvar org-goto-window-configuration nil)
6247 (defvar org-goto-marker nil)
6248 (defvar org-goto-map
6249 (let ((map (make-sparse-keymap)))
6250 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6251 (while (setq cmd (pop cmds))
6252 (substitute-key-definition cmd cmd map global-map)))
6253 (suppress-keymap map)
6254 (org-defkey map "\C-m" 'org-goto-ret)
6255 (org-defkey map [(return)] 'org-goto-ret)
6256 (org-defkey map [(left)] 'org-goto-left)
6257 (org-defkey map [(right)] 'org-goto-right)
6258 (org-defkey map [(control ?g)] 'org-goto-quit)
6259 (org-defkey map "\C-i" 'org-cycle)
6260 (org-defkey map [(tab)] 'org-cycle)
6261 (org-defkey map [(down)] 'outline-next-visible-heading)
6262 (org-defkey map [(up)] 'outline-previous-visible-heading)
6263 (if org-goto-auto-isearch
6264 (if (fboundp 'define-key-after)
6265 (define-key-after map [t] 'org-goto-local-auto-isearch)
6266 nil)
6267 (org-defkey map "q" 'org-goto-quit)
6268 (org-defkey map "n" 'outline-next-visible-heading)
6269 (org-defkey map "p" 'outline-previous-visible-heading)
6270 (org-defkey map "f" 'outline-forward-same-level)
6271 (org-defkey map "b" 'outline-backward-same-level)
6272 (org-defkey map "u" 'outline-up-heading))
6273 (org-defkey map "/" 'org-occur)
6274 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6275 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6276 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6277 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6278 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6279 map))
6281 (defconst org-goto-help
6282 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6283 RET=jump to location [Q]uit and return to previous location
6284 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6286 (defvar org-goto-start-pos) ; dynamically scoped parameter
6288 ;; FIXME: Docstring does not mention both interfaces
6289 (defun org-goto (&optional alternative-interface)
6290 "Look up a different location in the current file, keeping current visibility.
6292 When you want look-up or go to a different location in a document, the
6293 fastest way is often to fold the entire buffer and then dive into the tree.
6294 This method has the disadvantage, that the previous location will be folded,
6295 which may not be what you want.
6297 This command works around this by showing a copy of the current buffer
6298 in an indirect buffer, in overview mode. You can dive into the tree in
6299 that copy, use org-occur and incremental search to find a location.
6300 When pressing RET or `Q', the command returns to the original buffer in
6301 which the visibility is still unchanged. After RET is will also jump to
6302 the location selected in the indirect buffer and expose the
6303 the headline hierarchy above."
6304 (interactive "P")
6305 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6306 (org-refile-use-outline-path t)
6307 (org-refile-target-verify-function nil)
6308 (interface
6309 (if (not alternative-interface)
6310 org-goto-interface
6311 (if (eq org-goto-interface 'outline)
6312 'outline-path-completion
6313 'outline)))
6314 (org-goto-start-pos (point))
6315 (selected-point
6316 (if (eq interface 'outline)
6317 (car (org-get-location (current-buffer) org-goto-help))
6318 (nth 3 (org-refile-get-location "Goto: ")))))
6319 (if selected-point
6320 (progn
6321 (org-mark-ring-push org-goto-start-pos)
6322 (goto-char selected-point)
6323 (if (or (org-invisible-p) (org-invisible-p2))
6324 (org-show-context 'org-goto)))
6325 (message "Quit"))))
6327 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6328 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6329 (defvar org-goto-local-auto-isearch-map) ; defined below
6331 (defun org-get-location (buf help)
6332 "Let the user select a location in the Org-mode buffer BUF.
6333 This function uses a recursive edit. It returns the selected position
6334 or nil."
6335 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6336 (isearch-hide-immediately nil)
6337 (isearch-search-fun-function
6338 (lambda () 'org-goto-local-search-headings))
6339 (org-goto-selected-point org-goto-exit-command)
6340 (pop-up-frames nil)
6341 (special-display-buffer-names nil)
6342 (special-display-regexps nil)
6343 (special-display-function nil))
6344 (save-excursion
6345 (save-window-excursion
6346 (delete-other-windows)
6347 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6348 (switch-to-buffer
6349 (condition-case nil
6350 (make-indirect-buffer (current-buffer) "*org-goto*")
6351 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6352 (with-output-to-temp-buffer "*Help*"
6353 (princ help))
6354 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6355 (setq buffer-read-only nil)
6356 (let ((org-startup-truncated t)
6357 (org-startup-folded nil)
6358 (org-startup-align-all-tables nil))
6359 (org-mode)
6360 (org-overview))
6361 (setq buffer-read-only t)
6362 (if (and (boundp 'org-goto-start-pos)
6363 (integer-or-marker-p org-goto-start-pos))
6364 (let ((org-show-hierarchy-above t)
6365 (org-show-siblings t)
6366 (org-show-following-heading t))
6367 (goto-char org-goto-start-pos)
6368 (and (org-invisible-p) (org-show-context)))
6369 (goto-char (point-min)))
6370 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6371 (message "Select location and press RET")
6372 (use-local-map org-goto-map)
6373 (recursive-edit)
6375 (kill-buffer "*org-goto*")
6376 (cons org-goto-selected-point org-goto-exit-command)))
6378 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6379 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6380 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6381 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6383 (defun org-goto-local-search-headings (string bound noerror)
6384 "Search and make sure that any matches are in headlines."
6385 (catch 'return
6386 (while (if isearch-forward
6387 (search-forward string bound noerror)
6388 (search-backward string bound noerror))
6389 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6390 (and (member :headline context)
6391 (not (member :tags context))))
6392 (throw 'return (point))))))
6394 (defun org-goto-local-auto-isearch ()
6395 "Start isearch."
6396 (interactive)
6397 (goto-char (point-min))
6398 (let ((keys (this-command-keys)))
6399 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6400 (isearch-mode t)
6401 (isearch-process-search-char (string-to-char keys)))))
6403 (defun org-goto-ret (&optional arg)
6404 "Finish `org-goto' by going to the new location."
6405 (interactive "P")
6406 (setq org-goto-selected-point (point)
6407 org-goto-exit-command 'return)
6408 (throw 'exit nil))
6410 (defun org-goto-left ()
6411 "Finish `org-goto' by going to the new location."
6412 (interactive)
6413 (if (org-on-heading-p)
6414 (progn
6415 (beginning-of-line 1)
6416 (setq org-goto-selected-point (point)
6417 org-goto-exit-command 'left)
6418 (throw 'exit nil))
6419 (error "Not on a heading")))
6421 (defun org-goto-right ()
6422 "Finish `org-goto' by going to the new location."
6423 (interactive)
6424 (if (org-on-heading-p)
6425 (progn
6426 (setq org-goto-selected-point (point)
6427 org-goto-exit-command 'right)
6428 (throw 'exit nil))
6429 (error "Not on a heading")))
6431 (defun org-goto-quit ()
6432 "Finish `org-goto' without cursor motion."
6433 (interactive)
6434 (setq org-goto-selected-point nil)
6435 (setq org-goto-exit-command 'quit)
6436 (throw 'exit nil))
6438 ;;; Indirect buffer display of subtrees
6440 (defvar org-indirect-dedicated-frame nil
6441 "This is the frame being used for indirect tree display.")
6442 (defvar org-last-indirect-buffer nil)
6444 (defun org-tree-to-indirect-buffer (&optional arg)
6445 "Create indirect buffer and narrow it to current subtree.
6446 With numerical prefix ARG, go up to this level and then take that tree.
6447 If ARG is negative, go up that many levels.
6448 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6449 indirect buffer previously made with this command, to avoid proliferation of
6450 indirect buffers. However, when you call the command with a `C-u' prefix, or
6451 when `org-indirect-buffer-display' is `new-frame', the last buffer
6452 is kept so that you can work with several indirect buffers at the same time.
6453 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6454 requests that a new frame be made for the new buffer, so that the dedicated
6455 frame is not changed."
6456 (interactive "P")
6457 (let ((cbuf (current-buffer))
6458 (cwin (selected-window))
6459 (pos (point))
6460 beg end level heading ibuf)
6461 (save-excursion
6462 (org-back-to-heading t)
6463 (when (numberp arg)
6464 (setq level (org-outline-level))
6465 (if (< arg 0) (setq arg (+ level arg)))
6466 (while (> (setq level (org-outline-level)) arg)
6467 (outline-up-heading 1 t)))
6468 (setq beg (point)
6469 heading (org-get-heading))
6470 (org-end-of-subtree t t)
6471 (if (org-on-heading-p) (backward-char 1))
6472 (setq end (point)))
6473 (if (and (buffer-live-p org-last-indirect-buffer)
6474 (not (eq org-indirect-buffer-display 'new-frame))
6475 (not arg))
6476 (kill-buffer org-last-indirect-buffer))
6477 (setq ibuf (org-get-indirect-buffer cbuf)
6478 org-last-indirect-buffer ibuf)
6479 (cond
6480 ((or (eq org-indirect-buffer-display 'new-frame)
6481 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6482 (select-frame (make-frame))
6483 (delete-other-windows)
6484 (switch-to-buffer ibuf)
6485 (org-set-frame-title heading))
6486 ((eq org-indirect-buffer-display 'dedicated-frame)
6487 (raise-frame
6488 (select-frame (or (and org-indirect-dedicated-frame
6489 (frame-live-p org-indirect-dedicated-frame)
6490 org-indirect-dedicated-frame)
6491 (setq org-indirect-dedicated-frame (make-frame)))))
6492 (delete-other-windows)
6493 (switch-to-buffer ibuf)
6494 (org-set-frame-title (concat "Indirect: " heading)))
6495 ((eq org-indirect-buffer-display 'current-window)
6496 (switch-to-buffer ibuf))
6497 ((eq org-indirect-buffer-display 'other-window)
6498 (pop-to-buffer ibuf))
6499 (t (error "Invalid value")))
6500 (if (featurep 'xemacs)
6501 (save-excursion (org-mode) (turn-on-font-lock)))
6502 (narrow-to-region beg end)
6503 (show-all)
6504 (goto-char pos)
6505 (and (window-live-p cwin) (select-window cwin))))
6507 (defun org-get-indirect-buffer (&optional buffer)
6508 (setq buffer (or buffer (current-buffer)))
6509 (let ((n 1) (base (buffer-name buffer)) bname)
6510 (while (buffer-live-p
6511 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6512 (setq n (1+ n)))
6513 (condition-case nil
6514 (make-indirect-buffer buffer bname 'clone)
6515 (error (make-indirect-buffer buffer bname)))))
6517 (defun org-set-frame-title (title)
6518 "Set the title of the current frame to the string TITLE."
6519 ;; FIXME: how to name a single frame in XEmacs???
6520 (unless (featurep 'xemacs)
6521 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6523 ;;;; Structure editing
6525 ;;; Inserting headlines
6527 (defun org-previous-line-empty-p ()
6528 (save-excursion
6529 (and (not (bobp))
6530 (or (beginning-of-line 0) t)
6531 (save-match-data
6532 (looking-at "[ \t]*$")))))
6534 (defun org-insert-heading (&optional force-heading invisible-ok)
6535 "Insert a new heading or item with same depth at point.
6536 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6537 If point is at the beginning of a headline, insert a sibling before the
6538 current headline. If point is not at the beginning, do not split the line,
6539 but create the new headline after the current line.
6540 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6541 This is important for non-interactive uses of the command."
6542 (interactive "P")
6543 (if (or (= (buffer-size) 0)
6544 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6545 (org-on-heading-p))))
6546 (not (org-in-item-p))))
6547 (insert "\n* ")
6548 (when (or force-heading (not (org-insert-item)))
6549 (let* ((empty-line-p nil)
6550 (head (save-excursion
6551 (condition-case nil
6552 (progn
6553 (org-back-to-heading invisible-ok)
6554 (setq empty-line-p (org-previous-line-empty-p))
6555 (match-string 0))
6556 (error "*"))))
6557 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6558 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6559 pos hide-previous previous-pos)
6560 (cond
6561 ((and (org-on-heading-p) (bolp)
6562 (or (bobp)
6563 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6564 ;; insert before the current line
6565 (open-line (if blank 2 1)))
6566 ((and (bolp)
6567 (not org-insert-heading-respect-content)
6568 (or (bobp)
6569 (save-excursion
6570 (backward-char 1) (not (org-invisible-p)))))
6571 ;; insert right here
6572 nil)
6574 ;; somewhere in the line
6575 (save-excursion
6576 (setq previous-pos (point-at-bol))
6577 (end-of-line)
6578 (setq hide-previous (org-invisible-p)))
6579 (and org-insert-heading-respect-content (org-show-subtree))
6580 (let ((split
6581 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6582 (save-excursion
6583 (let ((p (point)))
6584 (goto-char (point-at-bol))
6585 (and (looking-at org-complex-heading-regexp)
6586 (> p (match-beginning 4)))))))
6587 tags pos)
6588 (cond
6589 (org-insert-heading-respect-content
6590 (org-end-of-subtree nil t)
6591 (or (bolp) (newline))
6592 (or (org-previous-line-empty-p)
6593 (and blank (newline)))
6594 (open-line 1))
6595 ((org-on-heading-p)
6596 (when hide-previous
6597 (show-children)
6598 (org-show-entry))
6599 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6600 (setq tags (and (match-end 2) (match-string 2)))
6601 (and (match-end 1)
6602 (delete-region (match-beginning 1) (match-end 1)))
6603 (setq pos (point-at-bol))
6604 (or split (end-of-line 1))
6605 (delete-horizontal-space)
6606 (if (string-match "\\`\\*+\\'"
6607 (buffer-substring (point-at-bol) (point)))
6608 (insert " "))
6609 (newline (if blank 2 1))
6610 (when tags
6611 (save-excursion
6612 (goto-char pos)
6613 (end-of-line 1)
6614 (insert " " tags)
6615 (org-set-tags nil 'align))))
6617 (or split (end-of-line 1))
6618 (newline (if blank 2 1)))))))
6619 (insert head) (just-one-space)
6620 (setq pos (point))
6621 (end-of-line 1)
6622 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6623 (when (and org-insert-heading-respect-content hide-previous)
6624 (save-excursion
6625 (goto-char previous-pos)
6626 (hide-subtree)))
6627 (run-hooks 'org-insert-heading-hook)))))
6629 (defun org-get-heading (&optional no-tags)
6630 "Return the heading of the current entry, without the stars."
6631 (save-excursion
6632 (org-back-to-heading t)
6633 (if (looking-at
6634 (if no-tags
6635 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6636 "\\*+[ \t]+\\([^\r\n]*\\)"))
6637 (match-string 1) "")))
6639 (defun org-heading-components ()
6640 "Return the components of the current heading.
6641 This is a list with the following elements:
6642 - the level as an integer
6643 - the reduced level, different if `org-odd-levels-only' is set.
6644 - the TODO keyword, or nil
6645 - the priority character, like ?A, or nil if no priority is given
6646 - the headline text itself, or the tags string if no headline text
6647 - the tags string, or nil."
6648 (save-excursion
6649 (org-back-to-heading t)
6650 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6651 (list (length (match-string 1))
6652 (org-reduced-level (length (match-string 1)))
6653 (org-match-string-no-properties 2)
6654 (and (match-end 3) (aref (match-string 3) 2))
6655 (org-match-string-no-properties 4)
6656 (org-match-string-no-properties 5)))))
6658 (defun org-get-entry ()
6659 "Get the entry text, after heading, entire subtree."
6660 (save-excursion
6661 (org-back-to-heading t)
6662 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6664 (defun org-insert-heading-after-current ()
6665 "Insert a new heading with same level as current, after current subtree."
6666 (interactive)
6667 (org-back-to-heading)
6668 (org-insert-heading)
6669 (org-move-subtree-down)
6670 (end-of-line 1))
6672 (defun org-insert-heading-respect-content ()
6673 (interactive)
6674 (let ((org-insert-heading-respect-content t))
6675 (org-insert-heading t)))
6677 (defun org-insert-todo-heading-respect-content (&optional force-state)
6678 (interactive "P")
6679 (let ((org-insert-heading-respect-content t))
6680 (org-insert-todo-heading force-state t)))
6682 (defun org-insert-todo-heading (arg &optional force-heading)
6683 "Insert a new heading with the same level and TODO state as current heading.
6684 If the heading has no TODO state, or if the state is DONE, use the first
6685 state (TODO by default). Also with prefix arg, force first state."
6686 (interactive "P")
6687 (when (or force-heading (not (org-insert-item 'checkbox)))
6688 (org-insert-heading force-heading)
6689 (save-excursion
6690 (org-back-to-heading)
6691 (outline-previous-heading)
6692 (looking-at org-todo-line-regexp))
6693 (let*
6694 ((new-mark-x
6695 (if (or arg
6696 (not (match-beginning 2))
6697 (member (match-string 2) org-done-keywords))
6698 (car org-todo-keywords-1)
6699 (match-string 2)))
6700 (new-mark
6702 (run-hook-with-args-until-success
6703 'org-todo-get-default-hook new-mark-x nil)
6704 new-mark-x)))
6705 (beginning-of-line 1)
6706 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6707 (if org-treat-insert-todo-heading-as-state-change
6708 (org-todo new-mark)
6709 (insert new-mark " "))))
6710 (when org-provide-todo-statistics
6711 (org-update-parent-todo-statistics))))
6713 (defun org-insert-subheading (arg)
6714 "Insert a new subheading and demote it.
6715 Works for outline headings and for plain lists alike."
6716 (interactive "P")
6717 (org-insert-heading arg)
6718 (cond
6719 ((org-on-heading-p) (org-do-demote))
6720 ((org-at-item-p) (org-indent-item 1))))
6722 (defun org-insert-todo-subheading (arg)
6723 "Insert a new subheading with TODO keyword or checkbox and demote it.
6724 Works for outline headings and for plain lists alike."
6725 (interactive "P")
6726 (org-insert-todo-heading arg)
6727 (cond
6728 ((org-on-heading-p) (org-do-demote))
6729 ((org-at-item-p) (org-indent-item 1))))
6731 ;;; Promotion and Demotion
6733 (defvar org-after-demote-entry-hook nil
6734 "Hook run after an entry has been demoted.
6735 The cursor will be at the beginning of the entry.
6736 When a subtree is being demoted, the hook will be called for each node.")
6738 (defvar org-after-promote-entry-hook nil
6739 "Hook run after an entry has been promoted.
6740 The cursor will be at the beginning of the entry.
6741 When a subtree is being promoted, the hook will be called for each node.")
6743 (defun org-promote-subtree ()
6744 "Promote the entire subtree.
6745 See also `org-promote'."
6746 (interactive)
6747 (save-excursion
6748 (org-map-tree 'org-promote))
6749 (org-fix-position-after-promote))
6751 (defun org-demote-subtree ()
6752 "Demote the entire subtree. See `org-demote'.
6753 See also `org-promote'."
6754 (interactive)
6755 (save-excursion
6756 (org-map-tree 'org-demote))
6757 (org-fix-position-after-promote))
6760 (defun org-do-promote ()
6761 "Promote the current heading higher up the tree.
6762 If the region is active in `transient-mark-mode', promote all headings
6763 in the region."
6764 (interactive)
6765 (save-excursion
6766 (if (org-region-active-p)
6767 (org-map-region 'org-promote (region-beginning) (region-end))
6768 (org-promote)))
6769 (org-fix-position-after-promote))
6771 (defun org-do-demote ()
6772 "Demote the current heading lower down the tree.
6773 If the region is active in `transient-mark-mode', demote all headings
6774 in the region."
6775 (interactive)
6776 (save-excursion
6777 (if (org-region-active-p)
6778 (org-map-region 'org-demote (region-beginning) (region-end))
6779 (org-demote)))
6780 (org-fix-position-after-promote))
6782 (defun org-fix-position-after-promote ()
6783 "Make sure that after pro/demotion cursor position is right."
6784 (let ((pos (point)))
6785 (when (save-excursion
6786 (beginning-of-line 1)
6787 (looking-at org-todo-line-regexp)
6788 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6789 (cond ((eobp) (insert " "))
6790 ((eolp) (insert " "))
6791 ((equal (char-after) ?\ ) (forward-char 1))))))
6793 (defun org-current-level ()
6794 "Return the level of the current entry, or nil if before the first headline.
6795 The level is the number of stars at the beginning of the headline."
6796 (save-excursion
6797 (condition-case nil
6798 (progn
6799 (org-back-to-heading t)
6800 (funcall outline-level))
6801 (error nil))))
6803 (defun org-get-previous-line-level ()
6804 "Return the outline depth of the last headline before the current line.
6805 Returns 0 for the first headline in the buffer, and nil if before the
6806 first headline."
6807 (let ((current-level (org-current-level))
6808 (prev-level (when (> (line-number-at-pos) 1)
6809 (save-excursion
6810 (beginning-of-line 0)
6811 (org-current-level)))))
6812 (cond ((null current-level) nil) ; Before first headline
6813 ((null prev-level) 0) ; At first headline
6814 (prev-level))))
6816 (defun org-reduced-level (l)
6817 "Compute the effective level of a heading.
6818 This takes into account the setting of `org-odd-levels-only'."
6819 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6821 (defun org-level-increment ()
6822 "Return the number of stars that will be added or removed at a
6823 time to headlines when structure editing, based on the value of
6824 `org-odd-levels-only'."
6825 (if org-odd-levels-only 2 1))
6827 (defun org-get-valid-level (level &optional change)
6828 "Rectify a level change under the influence of `org-odd-levels-only'
6829 LEVEL is a current level, CHANGE is by how much the level should be
6830 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6831 even level numbers will become the next higher odd number."
6832 (if org-odd-levels-only
6833 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6834 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6835 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6836 (max 1 (+ level (or change 0)))))
6838 (if (boundp 'define-obsolete-function-alias)
6839 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6840 (define-obsolete-function-alias 'org-get-legal-level
6841 'org-get-valid-level)
6842 (define-obsolete-function-alias 'org-get-legal-level
6843 'org-get-valid-level "23.1")))
6845 (defun org-promote ()
6846 "Promote the current heading higher up the tree.
6847 If the region is active in `transient-mark-mode', promote all headings
6848 in the region."
6849 (org-back-to-heading t)
6850 (let* ((level (save-match-data (funcall outline-level)))
6851 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6852 (diff (abs (- level (length up-head) -1))))
6853 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6854 (replace-match up-head nil t)
6855 ;; Fixup tag positioning
6856 (and org-auto-align-tags (org-set-tags nil t))
6857 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6858 (run-hooks 'org-after-promote-entry-hook)))
6860 (defun org-demote ()
6861 "Demote the current heading lower down the tree.
6862 If the region is active in `transient-mark-mode', demote all headings
6863 in the region."
6864 (org-back-to-heading t)
6865 (let* ((level (save-match-data (funcall outline-level)))
6866 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6867 (diff (abs (- level (length down-head) -1))))
6868 (replace-match down-head nil t)
6869 ;; Fixup tag positioning
6870 (and org-auto-align-tags (org-set-tags nil t))
6871 (if org-adapt-indentation (org-fixup-indentation diff))
6872 (run-hooks 'org-after-demote-entry-hook)))
6874 (defun org-cycle-level ()
6875 "Cycle the level of an empty headline through possible states.
6876 This goes first to child, then to parent, level, then up the hierarchy.
6877 After top level, it switches back to sibling level."
6878 (interactive)
6879 (let ((org-adapt-indentation nil))
6880 (when (org-point-at-end-of-empty-headline)
6881 (setq this-command 'org-cycle-level) ; Only needed for caching
6882 (let ((cur-level (org-current-level))
6883 (prev-level (org-get-previous-line-level)))
6884 (cond
6885 ;; If first headline in file, promote to top-level.
6886 ((= prev-level 0)
6887 (loop repeat (/ (- cur-level 1) (org-level-increment))
6888 do (org-do-promote)))
6889 ;; If same level as prev, demote one.
6890 ((= prev-level cur-level)
6891 (org-do-demote))
6892 ;; If parent is top-level, promote to top level if not already.
6893 ((= prev-level 1)
6894 (loop repeat (/ (- cur-level 1) (org-level-increment))
6895 do (org-do-promote)))
6896 ;; If top-level, return to prev-level.
6897 ((= cur-level 1)
6898 (loop repeat (/ (- prev-level 1) (org-level-increment))
6899 do (org-do-demote)))
6900 ;; If less than prev-level, promote one.
6901 ((< cur-level prev-level)
6902 (org-do-promote))
6903 ;; If deeper than prev-level, promote until higher than
6904 ;; prev-level.
6905 ((> cur-level prev-level)
6906 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6907 do (org-do-promote))))
6908 t))))
6910 (defun org-map-tree (fun)
6911 "Call FUN for every heading underneath the current one."
6912 (org-back-to-heading)
6913 (let ((level (funcall outline-level)))
6914 (save-excursion
6915 (funcall fun)
6916 (while (and (progn
6917 (outline-next-heading)
6918 (> (funcall outline-level) level))
6919 (not (eobp)))
6920 (funcall fun)))))
6922 (defun org-map-region (fun beg end)
6923 "Call FUN for every heading between BEG and END."
6924 (let ((org-ignore-region t))
6925 (save-excursion
6926 (setq end (copy-marker end))
6927 (goto-char beg)
6928 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6929 (< (point) end))
6930 (funcall fun))
6931 (while (and (progn
6932 (outline-next-heading)
6933 (< (point) end))
6934 (not (eobp)))
6935 (funcall fun)))))
6937 (defun org-fixup-indentation (diff)
6938 "Change the indentation in the current entry by DIFF
6939 However, if any line in the current entry has no indentation, or if it
6940 would end up with no indentation after the change, nothing at all is done."
6941 (save-excursion
6942 (let ((end (save-excursion (outline-next-heading)
6943 (point-marker)))
6944 (prohibit (if (> diff 0)
6945 "^\\S-"
6946 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6947 col)
6948 (unless (save-excursion (end-of-line 1)
6949 (re-search-forward prohibit end t))
6950 (while (and (< (point) end)
6951 (re-search-forward "^[ \t]+" end t))
6952 (goto-char (match-end 0))
6953 (setq col (current-column))
6954 (if (< diff 0) (replace-match ""))
6955 (org-indent-to-column (+ diff col))))
6956 (move-marker end nil))))
6958 (defun org-convert-to-odd-levels ()
6959 "Convert an org-mode file with all levels allowed to one with odd levels.
6960 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6961 level 5 etc."
6962 (interactive)
6963 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6964 (let ((outline-regexp org-outline-regexp)
6965 (outline-level 'org-outline-level)
6966 (org-odd-levels-only nil) n)
6967 (save-excursion
6968 (goto-char (point-min))
6969 (while (re-search-forward "^\\*\\*+ " nil t)
6970 (setq n (- (length (match-string 0)) 2))
6971 (while (>= (setq n (1- n)) 0)
6972 (org-demote))
6973 (end-of-line 1))))))
6975 (defun org-convert-to-oddeven-levels ()
6976 "Convert an org-mode file with only odd levels to one with odd and even levels.
6977 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6978 section with an even level, conversion would destroy the structure of the file. An error
6979 is signaled in this case."
6980 (interactive)
6981 (goto-char (point-min))
6982 ;; First check if there are no even levels
6983 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6984 (org-show-context t)
6985 (error "Not all levels are odd in this file. Conversion not possible"))
6986 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6987 (let ((outline-regexp org-outline-regexp)
6988 (outline-level 'org-outline-level)
6989 (org-odd-levels-only nil) n)
6990 (save-excursion
6991 (goto-char (point-min))
6992 (while (re-search-forward "^\\*\\*+ " nil t)
6993 (setq n (/ (1- (length (match-string 0))) 2))
6994 (while (>= (setq n (1- n)) 0)
6995 (org-promote))
6996 (end-of-line 1))))))
6998 (defun org-tr-level (n)
6999 "Make N odd if required."
7000 (if org-odd-levels-only (1+ (/ n 2)) n))
7002 ;;; Vertical tree motion, cutting and pasting of subtrees
7004 (defun org-move-subtree-up (&optional arg)
7005 "Move the current subtree up past ARG headlines of the same level."
7006 (interactive "p")
7007 (org-move-subtree-down (- (prefix-numeric-value arg))))
7009 (defun org-move-subtree-down (&optional arg)
7010 "Move the current subtree down past ARG headlines of the same level."
7011 (interactive "p")
7012 (setq arg (prefix-numeric-value arg))
7013 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7014 'org-get-last-sibling))
7015 (ins-point (make-marker))
7016 (cnt (abs arg))
7017 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7018 ;; Select the tree
7019 (org-back-to-heading)
7020 (setq beg0 (point))
7021 (save-excursion
7022 (setq ne-beg (org-back-over-empty-lines))
7023 (setq beg (point)))
7024 (save-match-data
7025 (save-excursion (outline-end-of-heading)
7026 (setq folded (org-invisible-p)))
7027 (outline-end-of-subtree))
7028 (outline-next-heading)
7029 (setq ne-end (org-back-over-empty-lines))
7030 (setq end (point))
7031 (goto-char beg0)
7032 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7033 ;; include less whitespace
7034 (save-excursion
7035 (goto-char beg)
7036 (forward-line (- ne-beg ne-end))
7037 (setq beg (point))))
7038 ;; Find insertion point, with error handling
7039 (while (> cnt 0)
7040 (or (and (funcall movfunc) (looking-at outline-regexp))
7041 (progn (goto-char beg0)
7042 (error "Cannot move past superior level or buffer limit")))
7043 (setq cnt (1- cnt)))
7044 (if (> arg 0)
7045 ;; Moving forward - still need to move over subtree
7046 (progn (org-end-of-subtree t t)
7047 (save-excursion
7048 (org-back-over-empty-lines)
7049 (or (bolp) (newline)))))
7050 (setq ne-ins (org-back-over-empty-lines))
7051 (move-marker ins-point (point))
7052 (setq txt (buffer-substring beg end))
7053 (org-save-markers-in-region beg end)
7054 (delete-region beg end)
7055 (org-remove-empty-overlays-at beg)
7056 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7057 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7058 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7059 (let ((bbb (point)))
7060 (insert-before-markers txt)
7061 (org-reinstall-markers-in-region bbb)
7062 (move-marker ins-point bbb))
7063 (or (bolp) (insert "\n"))
7064 (setq ins-end (point))
7065 (goto-char ins-point)
7066 (org-skip-whitespace)
7067 (when (and (< arg 0)
7068 (org-first-sibling-p)
7069 (> ne-ins ne-beg))
7070 ;; Move whitespace back to beginning
7071 (save-excursion
7072 (goto-char ins-end)
7073 (let ((kill-whole-line t))
7074 (kill-line (- ne-ins ne-beg)) (point)))
7075 (insert (make-string (- ne-ins ne-beg) ?\n)))
7076 (move-marker ins-point nil)
7077 (if folded
7078 (hide-subtree)
7079 (org-show-entry)
7080 (show-children)
7081 (org-cycle-hide-drawers 'children))
7082 (org-clean-visibility-after-subtree-move)))
7084 (defvar org-subtree-clip ""
7085 "Clipboard for cut and paste of subtrees.
7086 This is actually only a copy of the kill, because we use the normal kill
7087 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7089 (defvar org-subtree-clip-folded nil
7090 "Was the last copied subtree folded?
7091 This is used to fold the tree back after pasting.")
7093 (defun org-cut-subtree (&optional n)
7094 "Cut the current subtree into the clipboard.
7095 With prefix arg N, cut this many sequential subtrees.
7096 This is a short-hand for marking the subtree and then cutting it."
7097 (interactive "p")
7098 (org-copy-subtree n 'cut))
7100 (defun org-copy-subtree (&optional n cut force-store-markers)
7101 "Cut the current subtree into the clipboard.
7102 With prefix arg N, cut this many sequential subtrees.
7103 This is a short-hand for marking the subtree and then copying it.
7104 If CUT is non-nil, actually cut the subtree.
7105 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7106 of some markers in the region, even if CUT is non-nil. This is
7107 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7108 (interactive "p")
7109 (let (beg end folded (beg0 (point)))
7110 (if (interactive-p)
7111 (org-back-to-heading nil) ; take what looks like a subtree
7112 (org-back-to-heading t)) ; take what is really there
7113 (org-back-over-empty-lines)
7114 (setq beg (point))
7115 (skip-chars-forward " \t\r\n")
7116 (save-match-data
7117 (save-excursion (outline-end-of-heading)
7118 (setq folded (org-invisible-p)))
7119 (condition-case nil
7120 (org-forward-same-level (1- n) t)
7121 (error nil))
7122 (org-end-of-subtree t t))
7123 (org-back-over-empty-lines)
7124 (setq end (point))
7125 (goto-char beg0)
7126 (when (> end beg)
7127 (setq org-subtree-clip-folded folded)
7128 (when (or cut force-store-markers)
7129 (org-save-markers-in-region beg end))
7130 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7131 (setq org-subtree-clip (current-kill 0))
7132 (message "%s: Subtree(s) with %d characters"
7133 (if cut "Cut" "Copied")
7134 (length org-subtree-clip)))))
7136 (defun org-paste-subtree (&optional level tree for-yank)
7137 "Paste the clipboard as a subtree, with modification of headline level.
7138 The entire subtree is promoted or demoted in order to match a new headline
7139 level.
7141 If the cursor is at the beginning of a headline, the same level as
7142 that headline is used to paste the tree
7144 If not, the new level is derived from the *visible* headings
7145 before and after the insertion point, and taken to be the inferior headline
7146 level of the two. So if the previous visible heading is level 3 and the
7147 next is level 4 (or vice versa), level 4 will be used for insertion.
7148 This makes sure that the subtree remains an independent subtree and does
7149 not swallow low level entries.
7151 You can also force a different level, either by using a numeric prefix
7152 argument, or by inserting the heading marker by hand. For example, if the
7153 cursor is after \"*****\", then the tree will be shifted to level 5.
7155 If optional TREE is given, use this text instead of the kill ring.
7157 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7158 move back over whitespace before inserting, and move point to the end of
7159 the inserted text when done."
7160 (interactive "P")
7161 (setq tree (or tree (and kill-ring (current-kill 0))))
7162 (unless (org-kill-is-subtree-p tree)
7163 (error "%s"
7164 (substitute-command-keys
7165 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7166 (let* ((visp (not (org-invisible-p)))
7167 (txt tree)
7168 (^re (concat "^\\(" outline-regexp "\\)"))
7169 (re (concat "\\(" outline-regexp "\\)"))
7170 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7172 (old-level (if (string-match ^re txt)
7173 (- (match-end 0) (match-beginning 0) 1)
7174 -1))
7175 (force-level (cond (level (prefix-numeric-value level))
7176 ((and (looking-at "[ \t]*$")
7177 (string-match
7178 ^re_ (buffer-substring
7179 (point-at-bol) (point))))
7180 (- (match-end 1) (match-beginning 1)))
7181 ((and (bolp)
7182 (looking-at org-outline-regexp))
7183 (- (match-end 0) (point) 1))
7184 (t nil)))
7185 (previous-level (save-excursion
7186 (condition-case nil
7187 (progn
7188 (outline-previous-visible-heading 1)
7189 (if (looking-at re)
7190 (- (match-end 0) (match-beginning 0) 1)
7192 (error 1))))
7193 (next-level (save-excursion
7194 (condition-case nil
7195 (progn
7196 (or (looking-at outline-regexp)
7197 (outline-next-visible-heading 1))
7198 (if (looking-at re)
7199 (- (match-end 0) (match-beginning 0) 1)
7201 (error 1))))
7202 (new-level (or force-level (max previous-level next-level)))
7203 (shift (if (or (= old-level -1)
7204 (= new-level -1)
7205 (= old-level new-level))
7207 (- new-level old-level)))
7208 (delta (if (> shift 0) -1 1))
7209 (func (if (> shift 0) 'org-demote 'org-promote))
7210 (org-odd-levels-only nil)
7211 beg end newend)
7212 ;; Remove the forced level indicator
7213 (if force-level
7214 (delete-region (point-at-bol) (point)))
7215 ;; Paste
7216 (beginning-of-line 1)
7217 (unless for-yank (org-back-over-empty-lines))
7218 (setq beg (point))
7219 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7220 (insert-before-markers txt)
7221 (unless (string-match "\n\\'" txt) (insert "\n"))
7222 (setq newend (point))
7223 (org-reinstall-markers-in-region beg)
7224 (setq end (point))
7225 (goto-char beg)
7226 (skip-chars-forward " \t\n\r")
7227 (setq beg (point))
7228 (if (and (org-invisible-p) visp)
7229 (save-excursion (outline-show-heading)))
7230 ;; Shift if necessary
7231 (unless (= shift 0)
7232 (save-restriction
7233 (narrow-to-region beg end)
7234 (while (not (= shift 0))
7235 (org-map-region func (point-min) (point-max))
7236 (setq shift (+ delta shift)))
7237 (goto-char (point-min))
7238 (setq newend (point-max))))
7239 (when (or (interactive-p) for-yank)
7240 (message "Clipboard pasted as level %d subtree" new-level))
7241 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7242 kill-ring
7243 (eq org-subtree-clip (current-kill 0))
7244 org-subtree-clip-folded)
7245 ;; The tree was folded before it was killed/copied
7246 (hide-subtree))
7247 (and for-yank (goto-char newend))))
7249 (defun org-kill-is-subtree-p (&optional txt)
7250 "Check if the current kill is an outline subtree, or a set of trees.
7251 Returns nil if kill does not start with a headline, or if the first
7252 headline level is not the largest headline level in the tree.
7253 So this will actually accept several entries of equal levels as well,
7254 which is OK for `org-paste-subtree'.
7255 If optional TXT is given, check this string instead of the current kill."
7256 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7257 (start-level (and kill
7258 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7259 org-outline-regexp "\\)")
7260 kill)
7261 (- (match-end 2) (match-beginning 2) 1)))
7262 (re (concat "^" org-outline-regexp))
7263 (start (1+ (or (match-beginning 2) -1))))
7264 (if (not start-level)
7265 (progn
7266 nil) ;; does not even start with a heading
7267 (catch 'exit
7268 (while (setq start (string-match re kill (1+ start)))
7269 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7270 (throw 'exit nil)))
7271 t))))
7273 (defvar org-markers-to-move nil
7274 "Markers that should be moved with a cut-and-paste operation.
7275 Those markers are stored together with their positions relative to
7276 the start of the region.")
7278 (defun org-save-markers-in-region (beg end)
7279 "Check markers in region.
7280 If these markers are between BEG and END, record their position relative
7281 to BEG, so that after moving the block of text, we can put the markers back
7282 into place.
7283 This function gets called just before an entry or tree gets cut from the
7284 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7285 called immediately, to move the markers with the entries."
7286 (setq org-markers-to-move nil)
7287 (when (featurep 'org-clock)
7288 (org-clock-save-markers-for-cut-and-paste beg end))
7289 (when (featurep 'org-agenda)
7290 (org-agenda-save-markers-for-cut-and-paste beg end)))
7292 (defun org-check-and-save-marker (marker beg end)
7293 "Check if MARKER is between BEG and END.
7294 If yes, remember the marker and the distance to BEG."
7295 (when (and (marker-buffer marker)
7296 (equal (marker-buffer marker) (current-buffer)))
7297 (if (and (>= marker beg) (< marker end))
7298 (push (cons marker (- marker beg)) org-markers-to-move))))
7300 (defun org-reinstall-markers-in-region (beg)
7301 "Move all remembered markers to their position relative to BEG."
7302 (mapc (lambda (x)
7303 (move-marker (car x) (+ beg (cdr x))))
7304 org-markers-to-move)
7305 (setq org-markers-to-move nil))
7307 (defun org-narrow-to-subtree ()
7308 "Narrow buffer to the current subtree."
7309 (interactive)
7310 (save-excursion
7311 (save-match-data
7312 (narrow-to-region
7313 (progn (org-back-to-heading t) (point))
7314 (progn (org-end-of-subtree t t)
7315 (if (org-on-heading-p) (backward-char 1))
7316 (point))))))
7318 (eval-when-compile
7319 (defvar org-property-drawer-re))
7321 (defun org-clone-subtree-with-time-shift (n &optional shift)
7322 "Clone the task (subtree) at point N times.
7323 The clones will be inserted as siblings.
7325 In interactive use, the user will be prompted for the number of
7326 clones to be produced, and for a time SHIFT, which may be a
7327 repeater as used in time stamps, for example `+3d'.
7329 When a valid repeater is given and the entry contains any time
7330 stamps, the clones will become a sequence in time, with time
7331 stamps in the subtree shifted for each clone produced. If SHIFT
7332 is nil or the empty string, time stamps will be left alone. The
7333 ID property of the original subtree is removed.
7335 If the original subtree did contain time stamps with a repeater,
7336 the following will happen:
7337 - the repeater will be removed in each clone
7338 - an additional clone will be produced, with the current, unshifted
7339 date(s) in the entry.
7340 - the original entry will be placed *after* all the clones, with
7341 repeater intact.
7342 - the start days in the repeater in the original entry will be shifted
7343 to past the last clone.
7344 I this way you can spell out a number of instances of a repeating task,
7345 and still retain the repeater to cover future instances of the task."
7346 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7347 (let (beg end template task idprop
7348 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7349 (if (not (and (integerp n) (> n 0)))
7350 (error "Invalid number of replications %s" n))
7351 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7352 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7353 shift)))
7354 (error "Invalid shift specification %s" shift))
7355 (when doshift
7356 (setq shift-n (string-to-number (match-string 1 shift))
7357 shift-what (cdr (assoc (match-string 2 shift)
7358 '(("d" . day) ("w" . week)
7359 ("m" . month) ("y" . year))))))
7360 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7361 (setq nmin 1 nmax n)
7362 (org-back-to-heading t)
7363 (setq beg (point))
7364 (setq idprop (org-entry-get nil "ID"))
7365 (org-end-of-subtree t t)
7366 (or (bolp) (insert "\n"))
7367 (setq end (point))
7368 (setq template (buffer-substring beg end))
7369 (when (and doshift
7370 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7371 (delete-region beg end)
7372 (setq end beg)
7373 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7374 (goto-char end)
7375 (loop for n from nmin to nmax do
7376 ;; prepare clone
7377 (with-temp-buffer
7378 (insert template)
7379 (org-mode)
7380 (goto-char (point-min))
7381 (and idprop (if org-clone-delete-id
7382 (org-entry-delete nil "ID")
7383 (org-id-get-create t)))
7384 (while (re-search-forward org-property-drawer-re nil t)
7385 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7386 (goto-char (point-min))
7387 (when doshift
7388 (while (re-search-forward org-ts-regexp-both nil t)
7389 (org-timestamp-change (* n shift-n) shift-what))
7390 (unless (= n n-no-remove)
7391 (goto-char (point-min))
7392 (while (re-search-forward org-ts-regexp nil t)
7393 (save-excursion
7394 (goto-char (match-beginning 0))
7395 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7396 (delete-region (match-beginning 1) (match-end 1)))))))
7397 (setq task (buffer-string)))
7398 (insert task))
7399 (goto-char beg)))
7401 ;;; Outline Sorting
7403 (defun org-sort (with-case)
7404 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7405 Optional argument WITH-CASE means sort case-sensitively.
7406 With a double prefix argument, also remove duplicate entries."
7407 (interactive "P")
7408 (if (org-at-table-p)
7409 (org-call-with-arg 'org-table-sort-lines with-case)
7410 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7412 (defun org-sort-remove-invisible (s)
7413 (remove-text-properties 0 (length s) org-rm-props s)
7414 (while (string-match org-bracket-link-regexp s)
7415 (setq s (replace-match (if (match-end 2)
7416 (match-string 3 s)
7417 (match-string 1 s)) t t s)))
7420 (defvar org-priority-regexp) ; defined later in the file
7422 (defvar org-after-sorting-entries-or-items-hook nil
7423 "Hook that is run after a bunch of entries or items have been sorted.
7424 When children are sorted, the cursor is in the parent line when this
7425 hook gets called. When a region or a plain list is sorted, the cursor
7426 will be in the first entry of the sorted region/list.")
7428 (defun org-sort-entries-or-items
7429 (&optional with-case sorting-type getkey-func compare-func property)
7430 "Sort entries on a certain level of an outline tree, or plain list items.
7431 If there is an active region, the entries in the region are sorted.
7432 Else, if the cursor is before the first entry, sort the top-level items.
7433 Else, the children of the entry at point are sorted.
7434 If the cursor is at the first item in a plain list, the list items will be
7435 sorted.
7437 Sorting can be alphabetically, numerically, by date/time as given by
7438 a time stamp, by a property or by priority.
7440 The command prompts for the sorting type unless it has been given to the
7441 function through the SORTING-TYPE argument, which needs to be a character,
7442 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7443 precise meaning of each character:
7445 n Numerically, by converting the beginning of the entry/item to a number.
7446 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7447 t By date/time, either the first active time stamp in the entry, or, if
7448 none exist, by the first inactive one.
7449 In items, only the first line will be checked.
7450 s By the scheduled date/time.
7451 d By deadline date/time.
7452 c By creation time, which is assumed to be the first inactive time stamp
7453 at the beginning of a line.
7454 p By priority according to the cookie.
7455 r By the value of a property.
7457 Capital letters will reverse the sort order.
7459 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7460 called with point at the beginning of the record. It must return either
7461 a string or a number that should serve as the sorting key for that record.
7463 Comparing entries ignores case by default. However, with an optional argument
7464 WITH-CASE, the sorting considers case as well."
7465 (interactive "P")
7466 (let ((case-func (if with-case 'identity 'downcase))
7467 start beg end stars re re2
7468 txt what tmp plain-list-p)
7469 ;; Find beginning and end of region to sort
7470 (cond
7471 ((org-region-active-p)
7472 ;; we will sort the region
7473 (setq end (region-end)
7474 what "region")
7475 (goto-char (region-beginning))
7476 (if (not (org-on-heading-p)) (outline-next-heading))
7477 (setq start (point)))
7478 ((org-at-item-p)
7479 ;; we will sort this plain list
7480 (org-beginning-of-item-list) (setq start (point))
7481 (org-end-of-item-list)
7482 (or (bolp) (insert "\n"))
7483 (setq end (point))
7484 (goto-char start)
7485 (setq plain-list-p t
7486 what "plain list"))
7487 ((or (org-on-heading-p)
7488 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7489 ;; we will sort the children of the current headline
7490 (org-back-to-heading)
7491 (setq start (point)
7492 end (progn (org-end-of-subtree t t)
7493 (or (bolp) (insert "\n"))
7494 (org-back-over-empty-lines)
7495 (point))
7496 what "children")
7497 (goto-char start)
7498 (show-subtree)
7499 (outline-next-heading))
7501 ;; we will sort the top-level entries in this file
7502 (goto-char (point-min))
7503 (or (org-on-heading-p) (outline-next-heading))
7504 (setq start (point))
7505 (goto-char (point-max))
7506 (beginning-of-line 1)
7507 (when (looking-at ".*?\\S-")
7508 ;; File ends in a non-white line
7509 (end-of-line 1)
7510 (insert "\n"))
7511 (setq end (point-max))
7512 (setq what "top-level")
7513 (goto-char start)
7514 (show-all)))
7516 (setq beg (point))
7517 (if (>= beg end) (error "Nothing to sort"))
7519 (unless plain-list-p
7520 (looking-at "\\(\\*+\\)")
7521 (setq stars (match-string 1)
7522 re (concat "^" (regexp-quote stars) " +")
7523 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7524 txt (buffer-substring beg end))
7525 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7526 (if (and (not (equal stars "*")) (string-match re2 txt))
7527 (error "Region to sort contains a level above the first entry")))
7529 (unless sorting-type
7530 (message
7531 (if plain-list-p
7532 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7533 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7534 [t]ime [s]cheduled [d]eadline [c]reated
7535 A/N/T/S/D/C/P/O/F means reversed:")
7536 what)
7537 (setq sorting-type (read-char-exclusive))
7539 (and (= (downcase sorting-type) ?f)
7540 (setq getkey-func
7541 (org-icompleting-read "Sort using function: "
7542 obarray 'fboundp t nil nil))
7543 (setq getkey-func (intern getkey-func)))
7545 (and (= (downcase sorting-type) ?r)
7546 (setq property
7547 (org-icompleting-read "Property: "
7548 (mapcar 'list (org-buffer-property-keys t))
7549 nil t))))
7551 (message "Sorting entries...")
7553 (save-restriction
7554 (narrow-to-region start end)
7556 (let ((dcst (downcase sorting-type))
7557 (case-fold-search nil)
7558 (now (current-time)))
7559 (sort-subr
7560 (/= dcst sorting-type)
7561 ;; This function moves to the beginning character of the "record" to
7562 ;; be sorted.
7563 (if plain-list-p
7564 (lambda nil
7565 (if (org-at-item-p) t (goto-char (point-max))))
7566 (lambda nil
7567 (if (re-search-forward re nil t)
7568 (goto-char (match-beginning 0))
7569 (goto-char (point-max)))))
7570 ;; This function moves to the last character of the "record" being
7571 ;; sorted.
7572 (if plain-list-p
7573 'org-end-of-item
7574 (lambda nil
7575 (save-match-data
7576 (condition-case nil
7577 (outline-forward-same-level 1)
7578 (error
7579 (goto-char (point-max)))))))
7581 ;; This function returns the value that gets sorted against.
7582 (if plain-list-p
7583 (lambda nil
7584 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7585 (cond
7586 ((= dcst ?n)
7587 (string-to-number (buffer-substring (match-end 0)
7588 (point-at-eol))))
7589 ((= dcst ?a)
7590 (buffer-substring (match-end 0) (point-at-eol)))
7591 ((= dcst ?t)
7592 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7593 (re-search-forward org-ts-regexp-both
7594 (point-at-eol) t))
7595 (org-time-string-to-seconds (match-string 0))
7596 (org-float-time now)))
7597 ((= dcst ?f)
7598 (if getkey-func
7599 (progn
7600 (setq tmp (funcall getkey-func))
7601 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7602 tmp)
7603 (error "Invalid key function `%s'" getkey-func)))
7604 (t (error "Invalid sorting type `%c'" sorting-type)))))
7605 (lambda nil
7606 (cond
7607 ((= dcst ?n)
7608 (if (looking-at org-complex-heading-regexp)
7609 (string-to-number (match-string 4))
7610 nil))
7611 ((= dcst ?a)
7612 (if (looking-at org-complex-heading-regexp)
7613 (funcall case-func (match-string 4))
7614 nil))
7615 ((= dcst ?t)
7616 (let ((end (save-excursion (outline-next-heading) (point))))
7617 (if (or (re-search-forward org-ts-regexp end t)
7618 (re-search-forward org-ts-regexp-both end t))
7619 (org-time-string-to-seconds (match-string 0))
7620 (org-float-time now))))
7621 ((= dcst ?c)
7622 (let ((end (save-excursion (outline-next-heading) (point))))
7623 (if (re-search-forward
7624 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7625 end t)
7626 (org-time-string-to-seconds (match-string 0))
7627 (org-float-time now))))
7628 ((= dcst ?s)
7629 (let ((end (save-excursion (outline-next-heading) (point))))
7630 (if (re-search-forward org-scheduled-time-regexp end t)
7631 (org-time-string-to-seconds (match-string 1))
7632 (org-float-time now))))
7633 ((= dcst ?d)
7634 (let ((end (save-excursion (outline-next-heading) (point))))
7635 (if (re-search-forward org-deadline-time-regexp end t)
7636 (org-time-string-to-seconds (match-string 1))
7637 (org-float-time now))))
7638 ((= dcst ?p)
7639 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7640 (string-to-char (match-string 2))
7641 org-default-priority))
7642 ((= dcst ?r)
7643 (or (org-entry-get nil property) ""))
7644 ((= dcst ?o)
7645 (if (looking-at org-complex-heading-regexp)
7646 (- 9999 (length (member (match-string 2)
7647 org-todo-keywords-1)))))
7648 ((= dcst ?f)
7649 (if getkey-func
7650 (progn
7651 (setq tmp (funcall getkey-func))
7652 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7653 tmp)
7654 (error "Invalid key function `%s'" getkey-func)))
7655 (t (error "Invalid sorting type `%c'" sorting-type)))))
7657 (cond
7658 ((= dcst ?a) 'string<)
7659 ((= dcst ?f) compare-func)
7660 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7661 (t nil)))))
7662 (run-hooks 'org-after-sorting-entries-or-items-hook)
7663 (message "Sorting entries...done")))
7665 (defun org-do-sort (table what &optional with-case sorting-type)
7666 "Sort TABLE of WHAT according to SORTING-TYPE.
7667 The user will be prompted for the SORTING-TYPE if the call to this
7668 function does not specify it. WHAT is only for the prompt, to indicate
7669 what is being sorted. The sorting key will be extracted from
7670 the car of the elements of the table.
7671 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7672 (unless sorting-type
7673 (message
7674 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7675 what)
7676 (setq sorting-type (read-char-exclusive)))
7677 (let ((dcst (downcase sorting-type))
7678 extractfun comparefun)
7679 ;; Define the appropriate functions
7680 (cond
7681 ((= dcst ?n)
7682 (setq extractfun 'string-to-number
7683 comparefun (if (= dcst sorting-type) '< '>)))
7684 ((= dcst ?a)
7685 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7686 (lambda(x) (downcase (org-sort-remove-invisible x))))
7687 comparefun (if (= dcst sorting-type)
7688 'string<
7689 (lambda (a b) (and (not (string< a b))
7690 (not (string= a b)))))))
7691 ((= dcst ?t)
7692 (setq extractfun
7693 (lambda (x)
7694 (if (or (string-match org-ts-regexp x)
7695 (string-match org-ts-regexp-both x))
7696 (org-float-time
7697 (org-time-string-to-time (match-string 0 x)))
7699 comparefun (if (= dcst sorting-type) '< '>)))
7700 (t (error "Invalid sorting type `%c'" sorting-type)))
7702 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7703 table)
7704 (lambda (a b) (funcall comparefun (car a) (car b))))))
7707 ;;; The orgstruct minor mode
7709 ;; Define a minor mode which can be used in other modes in order to
7710 ;; integrate the org-mode structure editing commands.
7712 ;; This is really a hack, because the org-mode structure commands use
7713 ;; keys which normally belong to the major mode. Here is how it
7714 ;; works: The minor mode defines all the keys necessary to operate the
7715 ;; structure commands, but wraps the commands into a function which
7716 ;; tests if the cursor is currently at a headline or a plain list
7717 ;; item. If that is the case, the structure command is used,
7718 ;; temporarily setting many Org-mode variables like regular
7719 ;; expressions for filling etc. However, when any of those keys is
7720 ;; used at a different location, function uses `key-binding' to look
7721 ;; up if the key has an associated command in another currently active
7722 ;; keymap (minor modes, major mode, global), and executes that
7723 ;; command. There might be problems if any of the keys is otherwise
7724 ;; used as a prefix key.
7726 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7727 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7728 ;; addresses this by checking explicitly for both bindings.
7730 (defvar orgstruct-mode-map (make-sparse-keymap)
7731 "Keymap for the minor `orgstruct-mode'.")
7733 (defvar org-local-vars nil
7734 "List of local variables, for use by `orgstruct-mode'")
7736 ;;;###autoload
7737 (define-minor-mode orgstruct-mode
7738 "Toggle the minor mode `orgstruct-mode'.
7739 This mode is for using Org-mode structure commands in other
7740 modes. The following keys behave as if Org-mode were active, if
7741 the cursor is on a headline, or on a plain list item (both as
7742 defined by Org-mode).
7744 M-up Move entry/item up
7745 M-down Move entry/item down
7746 M-left Promote
7747 M-right Demote
7748 M-S-up Move entry/item up
7749 M-S-down Move entry/item down
7750 M-S-left Promote subtree
7751 M-S-right Demote subtree
7752 M-q Fill paragraph and items like in Org-mode
7753 C-c ^ Sort entries
7754 C-c - Cycle list bullet
7755 TAB Cycle item visibility
7756 M-RET Insert new heading/item
7757 S-M-RET Insert new TODO heading / Checkbox item
7758 C-c C-c Set tags / toggle checkbox"
7759 nil " OrgStruct" nil
7760 (org-load-modules-maybe)
7761 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7763 ;;;###autoload
7764 (defun turn-on-orgstruct ()
7765 "Unconditionally turn on `orgstruct-mode'."
7766 (orgstruct-mode 1))
7768 (defun orgstruct++-mode (&optional arg)
7769 "Toggle `orgstruct-mode', the enhanced version of it.
7770 In addition to setting orgstruct-mode, this also exports all indentation
7771 and autofilling variables from org-mode into the buffer. It will also
7772 recognize item context in multiline items.
7773 Note that turning off orgstruct-mode will *not* remove the
7774 indentation/paragraph settings. This can only be done by refreshing the
7775 major mode, for example with \\[normal-mode]."
7776 (interactive "P")
7777 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7778 (if (< arg 1)
7779 (orgstruct-mode -1)
7780 (orgstruct-mode 1)
7781 (let (var val)
7782 (mapc
7783 (lambda (x)
7784 (when (string-match
7785 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7786 (symbol-name (car x)))
7787 (setq var (car x) val (nth 1 x))
7788 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7789 org-local-vars)
7790 (org-set-local 'orgstruct-is-++ t))))
7792 (defvar orgstruct-is-++ nil
7793 "Is orgstruct-mode in ++ version in the current-buffer?")
7794 (make-variable-buffer-local 'orgstruct-is-++)
7796 ;;;###autoload
7797 (defun turn-on-orgstruct++ ()
7798 "Unconditionally turn on `orgstruct++-mode'."
7799 (orgstruct++-mode 1))
7801 (defun orgstruct-error ()
7802 "Error when there is no default binding for a structure key."
7803 (interactive)
7804 (error "This key has no function outside structure elements"))
7806 (defun orgstruct-setup ()
7807 "Setup orgstruct keymaps."
7808 (let ((nfunc 0)
7809 (bindings
7810 (list
7811 '([(meta up)] org-metaup)
7812 '([(meta down)] org-metadown)
7813 '([(meta left)] org-metaleft)
7814 '([(meta right)] org-metaright)
7815 '([(meta shift up)] org-shiftmetaup)
7816 '([(meta shift down)] org-shiftmetadown)
7817 '([(meta shift left)] org-shiftmetaleft)
7818 '([(meta shift right)] org-shiftmetaright)
7819 '([?\e (up)] org-metaup)
7820 '([?\e (down)] org-metadown)
7821 '([?\e (left)] org-metaleft)
7822 '([?\e (right)] org-metaright)
7823 '([?\e (shift up)] org-shiftmetaup)
7824 '([?\e (shift down)] org-shiftmetadown)
7825 '([?\e (shift left)] org-shiftmetaleft)
7826 '([?\e (shift right)] org-shiftmetaright)
7827 '([(shift up)] org-shiftup)
7828 '([(shift down)] org-shiftdown)
7829 '([(shift left)] org-shiftleft)
7830 '([(shift right)] org-shiftright)
7831 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7832 '("\M-q" fill-paragraph)
7833 '("\C-c^" org-sort)
7834 '("\C-c-" org-cycle-list-bullet)))
7835 elt key fun cmd)
7836 (while (setq elt (pop bindings))
7837 (setq nfunc (1+ nfunc))
7838 (setq key (org-key (car elt))
7839 fun (nth 1 elt)
7840 cmd (orgstruct-make-binding fun nfunc key))
7841 (org-defkey orgstruct-mode-map key cmd))
7843 ;; Special treatment needed for TAB and RET
7844 (org-defkey orgstruct-mode-map [(tab)]
7845 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7846 (org-defkey orgstruct-mode-map "\C-i"
7847 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7849 (org-defkey orgstruct-mode-map "\M-\C-m"
7850 (orgstruct-make-binding 'org-insert-heading 105
7851 "\M-\C-m" [(meta return)]))
7852 (org-defkey orgstruct-mode-map [(meta return)]
7853 (orgstruct-make-binding 'org-insert-heading 106
7854 [(meta return)] "\M-\C-m"))
7856 (org-defkey orgstruct-mode-map [(shift meta return)]
7857 (orgstruct-make-binding 'org-insert-todo-heading 107
7858 [(meta return)] "\M-\C-m"))
7860 (org-defkey orgstruct-mode-map "\e\C-m"
7861 (orgstruct-make-binding 'org-insert-heading 108
7862 "\e\C-m" [?\e (return)]))
7863 (org-defkey orgstruct-mode-map [?\e (return)]
7864 (orgstruct-make-binding 'org-insert-heading 109
7865 [?\e (return)] "\e\C-m"))
7866 (org-defkey orgstruct-mode-map [?\e (shift return)]
7867 (orgstruct-make-binding 'org-insert-todo-heading 110
7868 [?\e (return)] "\e\C-m"))
7870 (unless org-local-vars
7871 (setq org-local-vars (org-get-local-variables)))
7875 (defun orgstruct-make-binding (fun n &rest keys)
7876 "Create a function for binding in the structure minor mode.
7877 FUN is the command to call inside a table. N is used to create a unique
7878 command name. KEYS are keys that should be checked in for a command
7879 to execute outside of tables."
7880 (eval
7881 (list 'defun
7882 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7883 '(arg)
7884 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7885 "Outside of structure, run the binding of `"
7886 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7887 "'.")
7888 '(interactive "p")
7889 (list 'if
7890 `(org-context-p 'headline 'item
7891 (and orgstruct-is-++
7892 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7893 'item-body))
7894 (list 'org-run-like-in-org-mode (list 'quote fun))
7895 (list 'let '(orgstruct-mode)
7896 (list 'call-interactively
7897 (append '(or)
7898 (mapcar (lambda (k)
7899 (list 'key-binding k))
7900 keys)
7901 '('orgstruct-error))))))))
7903 (defun org-context-p (&rest contexts)
7904 "Check if local context is any of CONTEXTS.
7905 Possible values in the list of contexts are `table', `headline', and `item'."
7906 (let ((pos (point)))
7907 (goto-char (point-at-bol))
7908 (prog1 (or (and (memq 'table contexts)
7909 (looking-at "[ \t]*|"))
7910 (and (memq 'headline contexts)
7911 ;;????????? (looking-at "\\*+"))
7912 (looking-at outline-regexp))
7913 (and (memq 'item contexts)
7914 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7915 (and (memq 'item-body contexts)
7916 (org-in-item-p)))
7917 (goto-char pos))))
7919 (defun org-get-local-variables ()
7920 "Return a list of all local variables in an org-mode buffer."
7921 (let (varlist)
7922 (with-current-buffer (get-buffer-create "*Org tmp*")
7923 (erase-buffer)
7924 (org-mode)
7925 (setq varlist (buffer-local-variables)))
7926 (kill-buffer "*Org tmp*")
7927 (delq nil
7928 (mapcar
7929 (lambda (x)
7930 (setq x
7931 (if (symbolp x)
7932 (list x)
7933 (list (car x) (list 'quote (cdr x)))))
7934 (if (string-match
7935 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7936 (symbol-name (car x)))
7937 x nil))
7938 varlist))))
7940 ;;;###autoload
7941 (defun org-run-like-in-org-mode (cmd)
7942 "Run a command, pretending that the current buffer is in Org-mode.
7943 This will temporarily bind local variables that are typically bound in
7944 Org-mode to the values they have in Org-mode, and then interactively
7945 call CMD."
7946 (org-load-modules-maybe)
7947 (unless org-local-vars
7948 (setq org-local-vars (org-get-local-variables)))
7949 (eval (list 'let org-local-vars
7950 (list 'call-interactively (list 'quote cmd)))))
7952 ;;;; Archiving
7954 (defun org-get-category (&optional pos)
7955 "Get the category applying to position POS."
7956 (get-text-property (or pos (point)) 'org-category))
7958 (defun org-refresh-category-properties ()
7959 "Refresh category text properties in the buffer."
7960 (let ((def-cat (cond
7961 ((null org-category)
7962 (if buffer-file-name
7963 (file-name-sans-extension
7964 (file-name-nondirectory buffer-file-name))
7965 "???"))
7966 ((symbolp org-category) (symbol-name org-category))
7967 (t org-category)))
7968 beg end cat pos optionp)
7969 (org-unmodified
7970 (save-excursion
7971 (save-restriction
7972 (widen)
7973 (goto-char (point-min))
7974 (put-text-property (point) (point-max) 'org-category def-cat)
7975 (while (re-search-forward
7976 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7977 (setq pos (match-end 0)
7978 optionp (equal (char-after (match-beginning 0)) ?#)
7979 cat (org-trim (match-string 2)))
7980 (if optionp
7981 (setq beg (point-at-bol) end (point-max))
7982 (org-back-to-heading t)
7983 (setq beg (point) end (org-end-of-subtree t t)))
7984 (put-text-property beg end 'org-category cat)
7985 (goto-char pos)))))))
7988 ;;;; Link Stuff
7990 ;;; Link abbreviations
7992 (defun org-link-expand-abbrev (link)
7993 "Apply replacements as defined in `org-link-abbrev-alist."
7994 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7995 (let* ((key (match-string 1 link))
7996 (as (or (assoc key org-link-abbrev-alist-local)
7997 (assoc key org-link-abbrev-alist)))
7998 (tag (and (match-end 2) (match-string 3 link)))
7999 rpl)
8000 (if (not as)
8001 link
8002 (setq rpl (cdr as))
8003 (cond
8004 ((symbolp rpl) (funcall rpl tag))
8005 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8006 ((string-match "%h" rpl)
8007 (replace-match (url-hexify-string (or tag "")) t t rpl))
8008 (t (concat rpl tag)))))
8009 link))
8011 ;;; Storing and inserting links
8013 (defvar org-insert-link-history nil
8014 "Minibuffer history for links inserted with `org-insert-link'.")
8016 (defvar org-stored-links nil
8017 "Contains the links stored with `org-store-link'.")
8019 (defvar org-store-link-plist nil
8020 "Plist with info about the most recently link created with `org-store-link'.")
8022 (defvar org-link-protocols nil
8023 "Link protocols added to Org-mode using `org-add-link-type'.")
8025 (defvar org-store-link-functions nil
8026 "List of functions that are called to create and store a link.
8027 Each function will be called in turn until one returns a non-nil
8028 value. Each function should check if it is responsible for creating
8029 this link (for example by looking at the major mode).
8030 If not, it must exit and return nil.
8031 If yes, it should return a non-nil value after a calling
8032 `org-store-link-props' with a list of properties and values.
8033 Special properties are:
8035 :type The link prefix. like \"http\". This must be given.
8036 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8037 This is obligatory as well.
8038 :description Optional default description for the second pair
8039 of brackets in an Org-mode link. The user can still change
8040 this when inserting this link into an Org-mode buffer.
8042 In addition to these, any additional properties can be specified
8043 and then used in remember templates.")
8045 (defun org-add-link-type (type &optional follow export)
8046 "Add TYPE to the list of `org-link-types'.
8047 Re-compute all regular expressions depending on `org-link-types'
8049 FOLLOW and EXPORT are two functions.
8051 FOLLOW should take the link path as the single argument and do whatever
8052 is necessary to follow the link, for example find a file or display
8053 a mail message.
8055 EXPORT should format the link path for export to one of the export formats.
8056 It should be a function accepting three arguments:
8058 path the path of the link, the text after the prefix (like \"http:\")
8059 desc the description of the link, if any, nil if there was no description
8060 format the export format, a symbol like `html' or `latex'.
8062 The function may use the FORMAT information to return different values
8063 depending on the format. The return value will be put literally into
8064 the exported file.
8065 Org-mode has a built-in default for exporting links. If you are happy with
8066 this default, there is no need to define an export function for the link
8067 type. For a simple example of an export function, see `org-bbdb.el'."
8068 (add-to-list 'org-link-types type t)
8069 (org-make-link-regexps)
8070 (if (assoc type org-link-protocols)
8071 (setcdr (assoc type org-link-protocols) (list follow export))
8072 (push (list type follow export) org-link-protocols)))
8074 (defvar org-agenda-buffer-name)
8076 ;;;###autoload
8077 (defun org-store-link (arg)
8078 "\\<org-mode-map>Store an org-link to the current location.
8079 This link is added to `org-stored-links' and can later be inserted
8080 into an org-buffer with \\[org-insert-link].
8082 For some link types, a prefix arg is interpreted:
8083 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8084 For file links, arg negates `org-context-in-file-links'."
8085 (interactive "P")
8086 (org-load-modules-maybe)
8087 (setq org-store-link-plist nil) ; reset
8088 (let ((outline-regexp (org-get-limited-outline-regexp))
8089 link cpltxt desc description search txt custom-id)
8090 (cond
8092 ((run-hook-with-args-until-success 'org-store-link-functions)
8093 (setq link (plist-get org-store-link-plist :link)
8094 desc (or (plist-get org-store-link-plist :description) link)))
8096 ((equal (buffer-name) "*Org Edit Src Example*")
8097 (let (label gc)
8098 (while (or (not label)
8099 (save-excursion
8100 (save-restriction
8101 (widen)
8102 (goto-char (point-min))
8103 (re-search-forward
8104 (regexp-quote (format org-coderef-label-format label))
8105 nil t))))
8106 (when label (message "Label exists already") (sit-for 2))
8107 (setq label (read-string "Code line label: " label)))
8108 (end-of-line 1)
8109 (setq link (format org-coderef-label-format label))
8110 (setq gc (- 79 (length link)))
8111 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8112 (insert link)
8113 (setq link (concat "(" label ")") desc nil)))
8115 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8116 ;; We are in the agenda, link to referenced location
8117 (let ((m (or (get-text-property (point) 'org-hd-marker)
8118 (get-text-property (point) 'org-marker))))
8119 (when m
8120 (org-with-point-at m
8121 (if (interactive-p)
8122 (call-interactively 'org-store-link)
8123 (org-store-link nil))))))
8125 ((eq major-mode 'calendar-mode)
8126 (let ((cd (calendar-cursor-to-date)))
8127 (setq link
8128 (format-time-string
8129 (car org-time-stamp-formats)
8130 (apply 'encode-time
8131 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8132 nil nil nil))))
8133 (org-store-link-props :type "calendar" :date cd)))
8135 ((eq major-mode 'w3-mode)
8136 (setq cpltxt (if (and (buffer-name)
8137 (not (string-match "Untitled" (buffer-name))))
8138 (buffer-name)
8139 (url-view-url t))
8140 link (org-make-link (url-view-url t)))
8141 (org-store-link-props :type "w3" :url (url-view-url t)))
8143 ((eq major-mode 'w3m-mode)
8144 (setq cpltxt (or w3m-current-title w3m-current-url)
8145 link (org-make-link w3m-current-url))
8146 (org-store-link-props :type "w3m" :url (url-view-url t)))
8148 ((setq search (run-hook-with-args-until-success
8149 'org-create-file-search-functions))
8150 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8151 "::" search))
8152 (setq cpltxt (or description link)))
8154 ((eq major-mode 'image-mode)
8155 (setq cpltxt (concat "file:"
8156 (abbreviate-file-name buffer-file-name))
8157 link (org-make-link cpltxt))
8158 (org-store-link-props :type "image" :file buffer-file-name))
8160 ((eq major-mode 'dired-mode)
8161 ;; link to the file in the current line
8162 (let ((file (dired-get-filename nil t)))
8163 (setq file (if file
8164 (abbreviate-file-name
8165 (expand-file-name (dired-get-filename nil t)))
8166 ;; otherwise, no file so use current directory.
8167 default-directory))
8168 (setq cpltxt (concat "file:" file)
8169 link (org-make-link cpltxt))))
8171 ((and buffer-file-name (org-mode-p))
8172 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8173 (cond
8174 ((org-in-regexp "<<\\(.*?\\)>>")
8175 (setq cpltxt
8176 (concat "file:"
8177 (abbreviate-file-name buffer-file-name)
8178 "::" (match-string 1))
8179 link (org-make-link cpltxt)))
8180 ((and (featurep 'org-id)
8181 (or (eq org-link-to-org-use-id t)
8182 (and (eq org-link-to-org-use-id 'create-if-interactive)
8183 (interactive-p))
8184 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8185 (interactive-p)
8186 (not custom-id))
8187 (and org-link-to-org-use-id
8188 (condition-case nil
8189 (org-entry-get nil "ID")
8190 (error nil)))))
8191 ;; We can make a link using the ID.
8192 (setq link (condition-case nil
8193 (prog1 (org-id-store-link)
8194 (setq desc (plist-get org-store-link-plist
8195 :description)))
8196 (error
8197 ;; probably before first headline, link to file only
8198 (concat "file:"
8199 (abbreviate-file-name buffer-file-name))))))
8201 ;; Just link to current headline
8202 (setq cpltxt (concat "file:"
8203 (abbreviate-file-name buffer-file-name)))
8204 ;; Add a context search string
8205 (when (org-xor org-context-in-file-links arg)
8206 (setq txt (cond
8207 ((org-on-heading-p) nil)
8208 ((org-region-active-p)
8209 (buffer-substring (region-beginning) (region-end)))
8210 (t nil)))
8211 (when (or (null txt) (string-match "\\S-" txt))
8212 (setq cpltxt
8213 (concat cpltxt "::"
8214 (condition-case nil
8215 (org-make-org-heading-search-string txt)
8216 (error "")))
8217 desc (or (nth 4 (ignore-errors
8218 (org-heading-components))) "NONE"))))
8219 (if (string-match "::\\'" cpltxt)
8220 (setq cpltxt (substring cpltxt 0 -2)))
8221 (setq link (org-make-link cpltxt)))))
8223 ((buffer-file-name (buffer-base-buffer))
8224 ;; Just link to this file here.
8225 (setq cpltxt (concat "file:"
8226 (abbreviate-file-name
8227 (buffer-file-name (buffer-base-buffer)))))
8228 ;; Add a context string
8229 (when (org-xor org-context-in-file-links arg)
8230 (setq txt (if (org-region-active-p)
8231 (buffer-substring (region-beginning) (region-end))
8232 (buffer-substring (point-at-bol) (point-at-eol))))
8233 ;; Only use search option if there is some text.
8234 (when (string-match "\\S-" txt)
8235 (setq cpltxt
8236 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8237 desc "NONE")))
8238 (setq link (org-make-link cpltxt)))
8240 ((interactive-p)
8241 (error "Cannot link to a buffer which is not visiting a file"))
8243 (t (setq link nil)))
8245 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8246 (setq link (or link cpltxt)
8247 desc (or desc cpltxt))
8248 (if (equal desc "NONE") (setq desc nil))
8250 (if (and (or (interactive-p) executing-kbd-macro) link)
8251 (progn
8252 (setq org-stored-links
8253 (cons (list link desc) org-stored-links))
8254 (message "Stored: %s" (or desc link))
8255 (when custom-id
8256 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8257 "::#" custom-id))
8258 (setq org-stored-links
8259 (cons (list link desc) org-stored-links))))
8260 (and link (org-make-link-string link desc)))))
8262 (defun org-store-link-props (&rest plist)
8263 "Store link properties, extract names and addresses."
8264 (let (x adr)
8265 (when (setq x (plist-get plist :from))
8266 (setq adr (mail-extract-address-components x))
8267 (setq plist (plist-put plist :fromname (car adr)))
8268 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8269 (when (setq x (plist-get plist :to))
8270 (setq adr (mail-extract-address-components x))
8271 (setq plist (plist-put plist :toname (car adr)))
8272 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8273 (let ((from (plist-get plist :from))
8274 (to (plist-get plist :to)))
8275 (when (and from to org-from-is-user-regexp)
8276 (setq plist
8277 (plist-put plist :fromto
8278 (if (string-match org-from-is-user-regexp from)
8279 (concat "to %t")
8280 (concat "from %f"))))))
8281 (setq org-store-link-plist plist))
8283 (defun org-add-link-props (&rest plist)
8284 "Add these properties to the link property list."
8285 (let (key value)
8286 (while plist
8287 (setq key (pop plist) value (pop plist))
8288 (setq org-store-link-plist
8289 (plist-put org-store-link-plist key value)))))
8291 (defun org-email-link-description (&optional fmt)
8292 "Return the description part of an email link.
8293 This takes information from `org-store-link-plist' and formats it
8294 according to FMT (default from `org-email-link-description-format')."
8295 (setq fmt (or fmt org-email-link-description-format))
8296 (let* ((p org-store-link-plist)
8297 (to (plist-get p :toaddress))
8298 (from (plist-get p :fromaddress))
8299 (table
8300 (list
8301 (cons "%c" (plist-get p :fromto))
8302 (cons "%F" (plist-get p :from))
8303 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8304 (cons "%T" (plist-get p :to))
8305 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8306 (cons "%s" (plist-get p :subject))
8307 (cons "%m" (plist-get p :message-id)))))
8308 (when (string-match "%c" fmt)
8309 ;; Check if the user wrote this message
8310 (if (and org-from-is-user-regexp from to
8311 (save-match-data (string-match org-from-is-user-regexp from)))
8312 (setq fmt (replace-match "to %t" t t fmt))
8313 (setq fmt (replace-match "from %f" t t fmt))))
8314 (org-replace-escapes fmt table)))
8316 (defun org-make-org-heading-search-string (&optional string heading)
8317 "Make search string for STRING or current headline."
8318 (interactive)
8319 (let ((s (or string (org-get-heading))))
8320 (unless (and string (not heading))
8321 ;; We are using a headline, clean up garbage in there.
8322 (if (string-match org-todo-regexp s)
8323 (setq s (replace-match "" t t s)))
8324 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8325 (setq s (replace-match "" t t s)))
8326 (setq s (org-trim s))
8327 (if (string-match (concat "^\\(" org-quote-string "\\|"
8328 org-comment-string "\\)") s)
8329 (setq s (replace-match "" t t s)))
8330 (while (string-match org-ts-regexp s)
8331 (setq s (replace-match "" t t s))))
8332 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8333 (setq s (replace-match " " t t s)))
8334 (or string (setq s (concat "*" s))) ; Add * for headlines
8335 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8337 (defun org-make-link (&rest strings)
8338 "Concatenate STRINGS."
8339 (apply 'concat strings))
8341 (defun org-make-link-string (link &optional description)
8342 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8343 (unless (string-match "\\S-" link)
8344 (error "Empty link"))
8345 (when (and description
8346 (stringp description)
8347 (not (string-match "\\S-" description)))
8348 (setq description nil))
8349 (when (stringp description)
8350 ;; Remove brackets from the description, they are fatal.
8351 (while (string-match "\\[" description)
8352 (setq description (replace-match "{" t t description)))
8353 (while (string-match "\\]" description)
8354 (setq description (replace-match "}" t t description))))
8355 (when (equal (org-link-escape link) description)
8356 ;; No description needed, it is identical
8357 (setq description nil))
8358 (when (and (not description)
8359 (not (equal link (org-link-escape link))))
8360 (setq description (org-extract-attributes link)))
8361 (concat "[[" (org-link-escape link) "]"
8362 (if description (concat "[" description "]") "")
8363 "]"))
8365 (defconst org-link-escape-chars
8366 '((?\ . "%20")
8367 (?\[ . "%5B")
8368 (?\] . "%5D")
8369 (?\340 . "%E0") ; `a
8370 (?\342 . "%E2") ; ^a
8371 (?\347 . "%E7") ; ,c
8372 (?\350 . "%E8") ; `e
8373 (?\351 . "%E9") ; 'e
8374 (?\352 . "%EA") ; ^e
8375 (?\356 . "%EE") ; ^i
8376 (?\364 . "%F4") ; ^o
8377 (?\371 . "%F9") ; `u
8378 (?\373 . "%FB") ; ^u
8379 (?\; . "%3B")
8380 ;; (?? . "%3F")
8381 (?= . "%3D")
8382 (?+ . "%2B")
8384 "Association list of escapes for some characters problematic in links.
8385 This is the list that is used for internal purposes.")
8387 (defvar org-url-encoding-use-url-hexify nil)
8389 (defconst org-link-escape-chars-browser
8390 '((?\ . "%20")) ; 32 for the SPC char
8391 "Association list of escapes for some characters problematic in links.
8392 This is the list that is used before handing over to the browser.")
8394 (defun org-link-escape (text &optional table)
8395 "Escape characters in TEXT that are problematic for links."
8396 (if (and org-url-encoding-use-url-hexify (not table))
8397 (url-hexify-string text)
8398 (setq table (or table org-link-escape-chars))
8399 (when text
8400 (let ((re (mapconcat (lambda (x) (regexp-quote
8401 (char-to-string (car x))))
8402 table "\\|")))
8403 (while (string-match re text)
8404 (setq text
8405 (replace-match
8406 (cdr (assoc (string-to-char (match-string 0 text))
8407 table))
8408 t t text)))
8409 text))))
8411 (defun org-link-unescape (text &optional table)
8412 "Reverse the action of `org-link-escape'."
8413 (if (and org-url-encoding-use-url-hexify (not table))
8414 (url-unhex-string text)
8415 (setq table (or table org-link-escape-chars))
8416 (when text
8417 (let ((case-fold-search t)
8418 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8419 table "\\|")))
8420 (while (string-match re text)
8421 (setq text
8422 (replace-match
8423 (char-to-string (car (rassoc (upcase (match-string 0 text))
8424 table)))
8425 t t text)))
8426 text))))
8428 (defun org-xor (a b)
8429 "Exclusive or."
8430 (if a (not b) b))
8432 (defun org-fixup-message-id-for-http (s)
8433 "Replace special characters in a message id, so it can be used in an http query."
8434 (when (string-match "%" s)
8435 (setq s (mapconcat (lambda (c)
8436 (if (eq c ?%)
8437 "%25"
8438 (char-to-string c)))
8439 s "")))
8440 (while (string-match "<" s)
8441 (setq s (replace-match "%3C" t t s)))
8442 (while (string-match ">" s)
8443 (setq s (replace-match "%3E" t t s)))
8444 (while (string-match "@" s)
8445 (setq s (replace-match "%40" t t s)))
8448 ;;;###autoload
8449 (defun org-insert-link-global ()
8450 "Insert a link like Org-mode does.
8451 This command can be called in any mode to insert a link in Org-mode syntax."
8452 (interactive)
8453 (org-load-modules-maybe)
8454 (org-run-like-in-org-mode 'org-insert-link))
8456 (defun org-insert-link (&optional complete-file link-location)
8457 "Insert a link. At the prompt, enter the link.
8459 Completion can be used to insert any of the link protocol prefixes like
8460 http or ftp in use.
8462 The history can be used to select a link previously stored with
8463 `org-store-link'. When the empty string is entered (i.e. if you just
8464 press RET at the prompt), the link defaults to the most recently
8465 stored link. As SPC triggers completion in the minibuffer, you need to
8466 use M-SPC or C-q SPC to force the insertion of a space character.
8468 You will also be prompted for a description, and if one is given, it will
8469 be displayed in the buffer instead of the link.
8471 If there is already a link at point, this command will allow you to edit link
8472 and description parts.
8474 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8475 be selected using completion. The path to the file will be relative to the
8476 current directory if the file is in the current directory or a subdirectory.
8477 Otherwise, the link will be the absolute path as completed in the minibuffer
8478 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8479 option `org-link-file-path-type'.
8481 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8482 the current directory or below.
8484 With three \\[universal-argument] prefixes, negate the meaning of
8485 `org-keep-stored-link-after-insertion'.
8487 If `org-make-link-description-function' is non-nil, this function will be
8488 called with the link target, and the result will be the default
8489 link description.
8491 If the LINK-LOCATION parameter is non-nil, this value will be
8492 used as the link location instead of reading one interactively."
8493 (interactive "P")
8494 (let* ((wcf (current-window-configuration))
8495 (region (if (org-region-active-p)
8496 (buffer-substring (region-beginning) (region-end))))
8497 (remove (and region (list (region-beginning) (region-end))))
8498 (desc region)
8499 tmphist ; byte-compile incorrectly complains about this
8500 (link link-location)
8501 entry file all-prefixes)
8502 (cond
8503 (link-location) ; specified by arg, just use it.
8504 ((org-in-regexp org-bracket-link-regexp 1)
8505 ;; We do have a link at point, and we are going to edit it.
8506 (setq remove (list (match-beginning 0) (match-end 0)))
8507 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8508 (setq link (read-string "Link: "
8509 (org-link-unescape
8510 (org-match-string-no-properties 1)))))
8511 ((or (org-in-regexp org-angle-link-re)
8512 (org-in-regexp org-plain-link-re))
8513 ;; Convert to bracket link
8514 (setq remove (list (match-beginning 0) (match-end 0))
8515 link (read-string "Link: "
8516 (org-remove-angle-brackets (match-string 0)))))
8517 ((member complete-file '((4) (16)))
8518 ;; Completing read for file names.
8519 (setq link (org-file-complete-link complete-file)))
8521 ;; Read link, with completion for stored links.
8522 (with-output-to-temp-buffer "*Org Links*"
8523 (princ "Insert a link.
8524 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8525 (when org-stored-links
8526 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8527 (princ (mapconcat
8528 (lambda (x)
8529 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8530 (reverse org-stored-links) "\n"))))
8531 (let ((cw (selected-window)))
8532 (select-window (get-buffer-window "*Org Links*" 'visible))
8533 (setq truncate-lines t)
8534 (unless (pos-visible-in-window-p (point-max))
8535 (org-fit-window-to-buffer))
8536 (and (window-live-p cw) (select-window cw)))
8537 ;; Fake a link history, containing the stored links.
8538 (setq tmphist (append (mapcar 'car org-stored-links)
8539 org-insert-link-history))
8540 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8541 (mapcar 'car org-link-abbrev-alist)
8542 org-link-types))
8543 (unwind-protect
8544 (progn
8545 (setq link
8546 (let ((org-completion-use-ido nil)
8547 (org-completion-use-iswitchb nil))
8548 (org-completing-read
8549 "Link: "
8550 (append
8551 (mapcar (lambda (x) (list (concat x ":")))
8552 all-prefixes)
8553 (mapcar 'car org-stored-links))
8554 nil nil nil
8555 'tmphist
8556 (car (car org-stored-links)))))
8557 (if (not (string-match "\\S-" link))
8558 (error "No link selected"))
8559 (if (or (member link all-prefixes)
8560 (and (equal ":" (substring link -1))
8561 (member (substring link 0 -1) all-prefixes)
8562 (setq link (substring link 0 -1))))
8563 (setq link (org-link-try-special-completion link))))
8564 (set-window-configuration wcf)
8565 (kill-buffer "*Org Links*"))
8566 (setq entry (assoc link org-stored-links))
8567 (or entry (push link org-insert-link-history))
8568 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8569 (not org-keep-stored-link-after-insertion))
8570 (setq org-stored-links (delq (assoc link org-stored-links)
8571 org-stored-links)))
8572 (setq desc (or desc (nth 1 entry)))))
8574 (if (string-match org-plain-link-re link)
8575 ;; URL-like link, normalize the use of angular brackets.
8576 (setq link (org-make-link (org-remove-angle-brackets link))))
8578 ;; Check if we are linking to the current file with a search option
8579 ;; If yes, simplify the link by using only the search option.
8580 (when (and buffer-file-name
8581 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8582 (let* ((path (match-string 1 link))
8583 (case-fold-search nil)
8584 (search (match-string 2 link)))
8585 (save-match-data
8586 (if (equal (file-truename buffer-file-name) (file-truename path))
8587 ;; We are linking to this same file, with a search option
8588 (setq link search)))))
8590 ;; Check if we can/should use a relative path. If yes, simplify the link
8591 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8592 (let* ((type (match-string 1 link))
8593 (path (match-string 2 link))
8594 (origpath path)
8595 (case-fold-search nil))
8596 (cond
8597 ((or (eq org-link-file-path-type 'absolute)
8598 (equal complete-file '(16)))
8599 (setq path (abbreviate-file-name (expand-file-name path))))
8600 ((eq org-link-file-path-type 'noabbrev)
8601 (setq path (expand-file-name path)))
8602 ((eq org-link-file-path-type 'relative)
8603 (setq path (file-relative-name path)))
8605 (save-match-data
8606 (if (string-match (concat "^" (regexp-quote
8607 (file-name-as-directory
8608 (expand-file-name "."))))
8609 (expand-file-name path))
8610 ;; We are linking a file with relative path name.
8611 (setq path (substring (expand-file-name path)
8612 (match-end 0)))
8613 (setq path (abbreviate-file-name (expand-file-name path)))))))
8614 (setq link (concat type path))
8615 (if (equal desc origpath)
8616 (setq desc path))))
8618 (if org-make-link-description-function
8619 (setq desc (funcall org-make-link-description-function link desc)))
8621 (setq desc (read-string "Description: " desc))
8622 (unless (string-match "\\S-" desc) (setq desc nil))
8623 (if remove (apply 'delete-region remove))
8624 (insert (org-make-link-string link desc))))
8626 (defun org-link-try-special-completion (type)
8627 "If there is completion support for link type TYPE, offer it."
8628 (let ((fun (intern (concat "org-" type "-complete-link"))))
8629 (if (functionp fun)
8630 (funcall fun)
8631 (read-string "Link (no completion support): " (concat type ":")))))
8633 (defun org-file-complete-link (&optional arg)
8634 "Create a file link using completion."
8635 (let (file link)
8636 (setq file (read-file-name "File: "))
8637 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8638 (pwd1 (file-name-as-directory (abbreviate-file-name
8639 (expand-file-name ".")))))
8640 (cond
8641 ((equal arg '(16))
8642 (setq link (org-make-link
8643 "file:"
8644 (abbreviate-file-name (expand-file-name file)))))
8645 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8646 (setq link (org-make-link "file:" (match-string 1 file))))
8647 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8648 (expand-file-name file))
8649 (setq link (org-make-link
8650 "file:" (match-string 1 (expand-file-name file)))))
8651 (t (setq link (org-make-link "file:" file)))))
8652 link))
8654 (defun org-completing-read (&rest args)
8655 "Completing-read with SPACE being a normal character."
8656 (let ((minibuffer-local-completion-map
8657 (copy-keymap minibuffer-local-completion-map)))
8658 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8659 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8660 (apply 'org-icompleting-read args)))
8662 (defun org-completing-read-no-i (&rest args)
8663 (let (org-completion-use-ido org-completion-use-iswitchb)
8664 (apply 'org-completing-read args)))
8666 (defun org-iswitchb-completing-read (prompt choices &rest args)
8667 "Use iswitch as a completing-read replacement to choose from choices.
8668 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8669 from."
8670 (let* ((iswitchb-use-virtual-buffers nil)
8671 (iswitchb-make-buflist-hook
8672 (lambda ()
8673 (setq iswitchb-temp-buflist choices))))
8674 (iswitchb-read-buffer prompt)))
8676 (defun org-icompleting-read (&rest args)
8677 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8678 (org-without-partial-completion
8679 (if (and org-completion-use-ido
8680 (fboundp 'ido-completing-read)
8681 (boundp 'ido-mode) ido-mode
8682 (listp (second args)))
8683 (let ((ido-enter-matching-directory nil))
8684 (apply 'ido-completing-read (concat (car args))
8685 (if (consp (car (nth 1 args)))
8686 (mapcar (lambda (x) (car x)) (nth 1 args))
8687 (nth 1 args))
8688 (cddr args)))
8689 (if (and org-completion-use-iswitchb
8690 (boundp 'iswitchb-mode) iswitchb-mode
8691 (listp (second args)))
8692 (apply 'org-iswitchb-completing-read (concat (car args))
8693 (if (consp (car (nth 1 args)))
8694 (mapcar (lambda (x) (car x)) (nth 1 args))
8695 (nth 1 args))
8696 (cddr args))
8697 (apply 'completing-read args)))))
8699 (defun org-extract-attributes (s)
8700 "Extract the attributes cookie from a string and set as text property."
8701 (let (a attr (start 0) key value)
8702 (save-match-data
8703 (when (string-match "{{\\([^}]+\\)}}$" s)
8704 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8705 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8706 (setq key (match-string 1 a) value (match-string 2 a)
8707 start (match-end 0)
8708 attr (plist-put attr (intern key) value))))
8709 (org-add-props s nil 'org-attr attr))
8712 (defun org-extract-attributes-from-string (tag)
8713 (let (key value attr)
8714 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8715 (setq key (match-string 1 tag) value (match-string 2 tag)
8716 tag (replace-match "" t t tag)
8717 attr (plist-put attr (intern key) value)))
8718 (cons tag attr)))
8720 (defun org-attributes-to-string (plist)
8721 "Format a property list into an HTML attribute list."
8722 (let ((s "") key value)
8723 (while plist
8724 (setq key (pop plist) value (pop plist))
8725 (and value
8726 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8729 ;;; Opening/following a link
8731 (defvar org-link-search-failed nil)
8733 (defvar org-open-link-functions nil
8734 "Hook for functions finding a plain text link.
8735 These functions must take a single argument, the link content.
8736 They will be called for links that look like [[link text][description]]
8737 when LINK TEXT does not have a protocol like \"http:\" and does not look
8738 like a filename (e.g. \"./blue.png\").
8740 These functions will be called *before* Org attempts to resolve the
8741 link by doing text searches in the current buffer - so if you want a
8742 link \"[[target]]\" to still find \"<<target>>\", your function should
8743 handle this as a special case.
8745 When the function does handle the link, it must return a non-nil value.
8746 If it decides that it is not responsible for this link, it must return
8747 nil to indicate that that Org-mode can continue with other options
8748 like exact and fuzzy text search.")
8750 (defun org-next-link ()
8751 "Move forward to the next link.
8752 If the link is in hidden text, expose it."
8753 (interactive)
8754 (when (and org-link-search-failed (eq this-command last-command))
8755 (goto-char (point-min))
8756 (message "Link search wrapped back to beginning of buffer"))
8757 (setq org-link-search-failed nil)
8758 (let* ((pos (point))
8759 (ct (org-context))
8760 (a (assoc :link ct)))
8761 (if a (goto-char (nth 2 a)))
8762 (if (re-search-forward org-any-link-re nil t)
8763 (progn
8764 (goto-char (match-beginning 0))
8765 (if (org-invisible-p) (org-show-context)))
8766 (goto-char pos)
8767 (setq org-link-search-failed t)
8768 (error "No further link found"))))
8770 (defun org-previous-link ()
8771 "Move backward to the previous link.
8772 If the link is in hidden text, expose it."
8773 (interactive)
8774 (when (and org-link-search-failed (eq this-command last-command))
8775 (goto-char (point-max))
8776 (message "Link search wrapped back to end of buffer"))
8777 (setq org-link-search-failed nil)
8778 (let* ((pos (point))
8779 (ct (org-context))
8780 (a (assoc :link ct)))
8781 (if a (goto-char (nth 1 a)))
8782 (if (re-search-backward org-any-link-re nil t)
8783 (progn
8784 (goto-char (match-beginning 0))
8785 (if (org-invisible-p) (org-show-context)))
8786 (goto-char pos)
8787 (setq org-link-search-failed t)
8788 (error "No further link found"))))
8790 (defun org-translate-link (s)
8791 "Translate a link string if a translation function has been defined."
8792 (if (and org-link-translation-function
8793 (fboundp org-link-translation-function)
8794 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8795 (progn
8796 (setq s (funcall org-link-translation-function
8797 (match-string 1) (match-string 2)))
8798 (concat (car s) ":" (cdr s)))
8801 (defun org-translate-link-from-planner (type path)
8802 "Translate a link from Emacs Planner syntax so that Org can follow it.
8803 This is still an experimental function, your mileage may vary."
8804 (cond
8805 ((member type '("http" "https" "news" "ftp"))
8806 ;; standard Internet links are the same.
8807 nil)
8808 ((and (equal type "irc") (string-match "^//" path))
8809 ;; Planner has two / at the beginning of an irc link, we have 1.
8810 ;; We should have zero, actually....
8811 (setq path (substring path 1)))
8812 ((and (equal type "lisp") (string-match "^/" path))
8813 ;; Planner has a slash, we do not.
8814 (setq type "elisp" path (substring path 1)))
8815 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8816 ;; A typical message link. Planner has the id after the final slash,
8817 ;; we separate it with a hash mark
8818 (setq path (concat (match-string 1 path) "#"
8819 (org-remove-angle-brackets (match-string 2 path)))))
8821 (cons type path))
8823 (defun org-find-file-at-mouse (ev)
8824 "Open file link or URL at mouse."
8825 (interactive "e")
8826 (mouse-set-point ev)
8827 (org-open-at-point 'in-emacs))
8829 (defun org-open-at-mouse (ev)
8830 "Open file link or URL at mouse."
8831 (interactive "e")
8832 (mouse-set-point ev)
8833 (if (eq major-mode 'org-agenda-mode)
8834 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8835 (org-open-at-point))
8837 (defvar org-window-config-before-follow-link nil
8838 "The window configuration before following a link.
8839 This is saved in case the need arises to restore it.")
8841 (defvar org-open-link-marker (make-marker)
8842 "Marker pointing to the location where `org-open-at-point; was called.")
8844 ;;;###autoload
8845 (defun org-open-at-point-global ()
8846 "Follow a link like Org-mode does.
8847 This command can be called in any mode to follow a link that has
8848 Org-mode syntax."
8849 (interactive)
8850 (org-run-like-in-org-mode 'org-open-at-point))
8852 ;;;###autoload
8853 (defun org-open-link-from-string (s &optional arg reference-buffer)
8854 "Open a link in the string S, as if it was in Org-mode."
8855 (interactive "sLink: \nP")
8856 (let ((reference-buffer (or reference-buffer (current-buffer))))
8857 (with-temp-buffer
8858 (let ((org-inhibit-startup t))
8859 (org-mode)
8860 (insert s)
8861 (goto-char (point-min))
8862 (when reference-buffer
8863 (setq org-link-abbrev-alist-local
8864 (with-current-buffer reference-buffer
8865 org-link-abbrev-alist-local)))
8866 (org-open-at-point arg reference-buffer)))))
8868 (defun org-open-at-point (&optional in-emacs reference-buffer)
8869 "Open link at or after point.
8870 If there is no link at point, this function will search forward up to
8871 the end of the current line.
8872 Normally, files will be opened by an appropriate application. If the
8873 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8874 With a double prefix argument, try to open outside of Emacs, in the
8875 application the system uses for this file type."
8876 (interactive "P")
8877 (org-load-modules-maybe)
8878 (move-marker org-open-link-marker (point))
8879 (setq org-window-config-before-follow-link (current-window-configuration))
8880 (org-remove-occur-highlights nil nil t)
8881 (cond
8882 ((and (org-on-heading-p)
8883 (not (org-in-regexp
8884 (concat org-plain-link-re "\\|"
8885 org-bracket-link-regexp "\\|"
8886 org-angle-link-re "\\|"
8887 "[ \t]:[^ \t\n]+:[ \t]*$")))
8888 (not (get-text-property (point) 'org-linked-text)))
8889 (or (org-offer-links-in-entry in-emacs)
8890 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8891 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8892 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8893 (org-footnote-action))
8895 (let (type path link line search (pos (point)))
8896 (catch 'match
8897 (save-excursion
8898 (skip-chars-forward "^]\n\r")
8899 (when (org-in-regexp org-bracket-link-regexp 1)
8900 (setq link (org-extract-attributes
8901 (org-link-unescape (org-match-string-no-properties 1))))
8902 (while (string-match " *\n *" link)
8903 (setq link (replace-match " " t t link)))
8904 (setq link (org-link-expand-abbrev link))
8905 (cond
8906 ((or (file-name-absolute-p link)
8907 (string-match "^\\.\\.?/" link))
8908 (setq type "file" path link))
8909 ((string-match org-link-re-with-space3 link)
8910 (setq type (match-string 1 link) path (match-string 2 link)))
8911 (t (setq type "thisfile" path link)))
8912 (throw 'match t)))
8914 (when (get-text-property (point) 'org-linked-text)
8915 (setq type "thisfile"
8916 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8917 (1+ (point)) (point))
8918 path (buffer-substring
8919 (previous-single-property-change pos 'org-linked-text)
8920 (next-single-property-change pos 'org-linked-text)))
8921 (throw 'match t))
8923 (save-excursion
8924 (when (or (org-in-regexp org-angle-link-re)
8925 (org-in-regexp org-plain-link-re))
8926 (setq type (match-string 1) path (match-string 2))
8927 (throw 'match t)))
8928 (save-excursion
8929 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8930 (setq type "tags"
8931 path (match-string 1))
8932 (while (string-match ":" path)
8933 (setq path (replace-match "+" t t path)))
8934 (throw 'match t)))
8935 (when (org-in-regexp "<\\([^><\n]+\\)>")
8936 (setq type "tree-match"
8937 path (match-string 1))
8938 (throw 'match t)))
8939 (unless path
8940 (error "No link found"))
8942 ;; switch back to reference buffer
8943 ;; needed when if called in a temporary buffer through
8944 ;; org-open-link-from-string
8945 (with-current-buffer (or reference-buffer (current-buffer))
8947 ;; Remove any trailing spaces in path
8948 (if (string-match " +\\'" path)
8949 (setq path (replace-match "" t t path)))
8950 (if (and org-link-translation-function
8951 (fboundp org-link-translation-function))
8952 ;; Check if we need to translate the link
8953 (let ((tmp (funcall org-link-translation-function type path)))
8954 (setq type (car tmp) path (cdr tmp))))
8956 (cond
8958 ((assoc type org-link-protocols)
8959 (funcall (nth 1 (assoc type org-link-protocols)) path))
8961 ((equal type "mailto")
8962 (let ((cmd (car org-link-mailto-program))
8963 (args (cdr org-link-mailto-program)) args1
8964 (address path) (subject "") a)
8965 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8966 (setq address (match-string 1 path)
8967 subject (org-link-escape (match-string 2 path))))
8968 (while args
8969 (cond
8970 ((not (stringp (car args))) (push (pop args) args1))
8971 (t (setq a (pop args))
8972 (if (string-match "%a" a)
8973 (setq a (replace-match address t t a)))
8974 (if (string-match "%s" a)
8975 (setq a (replace-match subject t t a)))
8976 (push a args1))))
8977 (apply cmd (nreverse args1))))
8979 ((member type '("http" "https" "ftp" "news"))
8980 (browse-url (concat type ":" (org-link-escape
8981 path org-link-escape-chars-browser))))
8983 ((string= type "doi")
8984 (browse-url (concat "http://dx.doi.org/"
8985 (org-link-escape
8986 path org-link-escape-chars-browser))))
8988 ((member type '("message"))
8989 (browse-url (concat type ":" path)))
8991 ((string= type "tags")
8992 (org-tags-view in-emacs path))
8994 ((string= type "tree-match")
8995 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8997 ((string= type "file")
8998 (if (string-match "::\\([0-9]+\\)\\'" path)
8999 (setq line (string-to-number (match-string 1 path))
9000 path (substring path 0 (match-beginning 0)))
9001 (if (string-match "::\\(.+\\)\\'" path)
9002 (setq search (match-string 1 path)
9003 path (substring path 0 (match-beginning 0)))))
9004 (if (string-match "[*?{]" (file-name-nondirectory path))
9005 (dired path)
9006 (org-open-file path in-emacs line search)))
9008 ((string= type "news")
9009 (require 'org-gnus)
9010 (org-gnus-follow-link path))
9012 ((string= type "shell")
9013 (let ((cmd path))
9014 (if (or (not org-confirm-shell-link-function)
9015 (funcall org-confirm-shell-link-function
9016 (format "Execute \"%s\" in shell? "
9017 (org-add-props cmd nil
9018 'face 'org-warning))))
9019 (progn
9020 (message "Executing %s" cmd)
9021 (shell-command cmd))
9022 (error "Abort"))))
9024 ((string= type "elisp")
9025 (let ((cmd path))
9026 (if (or (not org-confirm-elisp-link-function)
9027 (funcall org-confirm-elisp-link-function
9028 (format "Execute \"%s\" as elisp? "
9029 (org-add-props cmd nil
9030 'face 'org-warning))))
9031 (message "%s => %s" cmd
9032 (if (equal (string-to-char cmd) ?\()
9033 (eval (read cmd))
9034 (call-interactively (read cmd))))
9035 (error "Abort"))))
9037 ((and (string= type "thisfile")
9038 (run-hook-with-args-until-success
9039 'org-open-link-functions path)))
9041 ((string= type "thisfile")
9042 (if in-emacs
9043 (switch-to-buffer-other-window
9044 (org-get-buffer-for-internal-link (current-buffer)))
9045 (org-mark-ring-push))
9046 (let ((cmd `(org-link-search
9047 ,path
9048 ,(cond ((equal in-emacs '(4)) 'occur)
9049 ((equal in-emacs '(16)) 'org-occur)
9050 (t nil))
9051 ,pos)))
9052 (condition-case nil (eval cmd)
9053 (error (progn (widen) (eval cmd))))))
9056 (browse-url-at-point)))))))
9057 (move-marker org-open-link-marker nil)
9058 (run-hook-with-args 'org-follow-link-hook))
9060 (defun org-offer-links-in-entry (&optional nth zero)
9061 "Offer links in the current entry and follow the selected link.
9062 If there is only one link, follow it immediately as well.
9063 If NTH is an integer, immediately pick the NTH link found.
9064 If ZERO is a string, check also this string for a link, and if
9065 there is one, offer it as link number zero."
9066 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9067 "\\(" org-angle-link-re "\\)\\|"
9068 "\\(" org-plain-link-re "\\)"))
9069 (cnt ?0)
9070 (in-emacs (if (integerp nth) nil nth))
9071 have-zero end links link c)
9072 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9073 (push (match-string 0 zero) links)
9074 (setq cnt (1- cnt) have-zero t))
9075 (save-excursion
9076 (org-back-to-heading t)
9077 (setq end (save-excursion (outline-next-heading) (point)))
9078 (while (re-search-forward re end t)
9079 (push (match-string 0) links))
9080 (setq links (org-uniquify (reverse links))))
9082 (cond
9083 ((null links)
9084 (message "No links"))
9085 ((equal (length links) 1)
9086 (setq link (list (car links))))
9087 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9088 (setq link (nth (if have-zero nth (1- nth)) links)))
9089 (t ; we have to select a link
9090 (save-excursion
9091 (save-window-excursion
9092 (delete-other-windows)
9093 (with-output-to-temp-buffer "*Select Link*"
9094 (mapc (lambda (l)
9095 (if (not (string-match org-bracket-link-regexp l))
9096 (princ (format "[%c] %s\n" (incf cnt)
9097 (org-remove-angle-brackets l)))
9098 (if (match-end 3)
9099 (princ (format "[%c] %s (%s)\n" (incf cnt)
9100 (match-string 3 l) (match-string 1 l)))
9101 (princ (format "[%c] %s\n" (incf cnt)
9102 (match-string 1 l))))))
9103 links))
9104 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9105 (message "Select link to open, RET to open all:")
9106 (setq c (read-char-exclusive))
9107 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9108 (when (equal c ?q) (error "Abort"))
9109 (if (equal c ?\C-m)
9110 (setq link links)
9111 (setq nth (- c ?0))
9112 (if have-zero (setq nth (1+ nth)))
9113 (unless (and (integerp nth) (>= (length links) nth))
9114 (error "Invalid link selection"))
9115 (setq link (list (nth (1- nth) links))))))
9116 (if link
9117 (let ((buf (current-buffer)))
9118 (dolist (l link)
9119 (org-open-link-from-string l in-emacs buf))
9121 nil)))
9123 ;; Add special file links that specify the way of opening
9125 (org-add-link-type "file+sys" 'org-open-file-with-system)
9126 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9127 (defun org-open-file-with-system (path)
9128 "Open file at PATH using the system way of opeing it."
9129 (org-open-file path 'system))
9130 (defun org-open-file-with-emacs (path)
9131 "Open file at PATH in emacs."
9132 (org-open-file path 'emacs))
9133 (defun org-remove-file-link-modifiers ()
9134 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9135 (goto-char (point-min))
9136 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9137 (org-if-unprotected
9138 (replace-match "file:" t t))))
9139 (eval-after-load "org-exp"
9140 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9141 'org-remove-file-link-modifiers))
9143 ;;;; Time estimates
9145 (defun org-get-effort (&optional pom)
9146 "Get the effort estimate for the current entry."
9147 (org-entry-get pom org-effort-property))
9149 ;;; File search
9151 (defvar org-create-file-search-functions nil
9152 "List of functions to construct the right search string for a file link.
9153 These functions are called in turn with point at the location to
9154 which the link should point.
9156 A function in the hook should first test if it would like to
9157 handle this file type, for example by checking the major-mode or
9158 the file extension. If it decides not to handle this file, it
9159 should just return nil to give other functions a chance. If it
9160 does handle the file, it must return the search string to be used
9161 when following the link. The search string will be part of the
9162 file link, given after a double colon, and `org-open-at-point'
9163 will automatically search for it. If special measures must be
9164 taken to make the search successful, another function should be
9165 added to the companion hook `org-execute-file-search-functions',
9166 which see.
9168 A function in this hook may also use `setq' to set the variable
9169 `description' to provide a suggestion for the descriptive text to
9170 be used for this link when it gets inserted into an Org-mode
9171 buffer with \\[org-insert-link].")
9173 (defvar org-execute-file-search-functions nil
9174 "List of functions to execute a file search triggered by a link.
9176 Functions added to this hook must accept a single argument, the
9177 search string that was part of the file link, the part after the
9178 double colon. The function must first check if it would like to
9179 handle this search, for example by checking the major-mode or the
9180 file extension. If it decides not to handle this search, it
9181 should just return nil to give other functions a chance. If it
9182 does handle the search, it must return a non-nil value to keep
9183 other functions from trying.
9185 Each function can access the current prefix argument through the
9186 variable `current-prefix-argument'. Note that a single prefix is
9187 used to force opening a link in Emacs, so it may be good to only
9188 use a numeric or double prefix to guide the search function.
9190 In case this is needed, a function in this hook can also restore
9191 the window configuration before `org-open-at-point' was called using:
9193 (set-window-configuration org-window-config-before-follow-link)")
9195 (defun org-link-search (s &optional type avoid-pos)
9196 "Search for a link search option.
9197 If S is surrounded by forward slashes, it is interpreted as a
9198 regular expression. In org-mode files, this will create an `org-occur'
9199 sparse tree. In ordinary files, `occur' will be used to list matches.
9200 If the current buffer is in `dired-mode', grep will be used to search
9201 in all files. If AVOID-POS is given, ignore matches near that position."
9202 (let ((case-fold-search t)
9203 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9204 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9205 (append '(("") (" ") ("\t") ("\n"))
9206 org-emphasis-alist)
9207 "\\|") "\\)"))
9208 (pos (point))
9209 (pre nil) (post nil)
9210 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9211 (cond
9212 ;; First check if there are any special
9213 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9214 ;; Now try the builtin stuff
9215 ((and (equal (string-to-char s0) ?#)
9216 (> (length s0) 1)
9217 (save-excursion
9218 (goto-char (point-min))
9219 (and
9220 (re-search-forward
9221 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9222 (setq type 'dedicated
9223 pos (match-beginning 0))))
9224 ;; There is an exact target for this
9225 (goto-char pos)
9226 (org-back-to-heading t)))
9227 ((save-excursion
9228 (goto-char (point-min))
9229 (and
9230 (re-search-forward
9231 (concat "<<" (regexp-quote s0) ">>") nil t)
9232 (setq type 'dedicated
9233 pos (match-beginning 0))))
9234 ;; There is an exact target for this
9235 (goto-char pos))
9236 ((and (string-match "^(\\(.*\\))$" s0)
9237 (save-excursion
9238 (goto-char (point-min))
9239 (and
9240 (re-search-forward
9241 (concat "[^[]" (regexp-quote
9242 (format org-coderef-label-format
9243 (match-string 1 s0))))
9244 nil t)
9245 (setq type 'dedicated
9246 pos (1+ (match-beginning 0))))))
9247 ;; There is a coderef target for this
9248 (goto-char pos))
9249 ((string-match "^/\\(.*\\)/$" s)
9250 ;; A regular expression
9251 (cond
9252 ((org-mode-p)
9253 (org-occur (match-string 1 s)))
9254 ;;((eq major-mode 'dired-mode)
9255 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9256 (t (org-do-occur (match-string 1 s)))))
9258 ;; A normal search strings
9259 (when (equal (string-to-char s) ?*)
9260 ;; Anchor on headlines, post may include tags.
9261 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9262 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9263 s (substring s 1)))
9264 (remove-text-properties
9265 0 (length s)
9266 '(face nil mouse-face nil keymap nil fontified nil) s)
9267 ;; Make a series of regular expressions to find a match
9268 (setq words (org-split-string s "[ \n\r\t]+")
9270 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9271 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9272 "\\)" markers)
9273 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9274 re2a (concat "[ \t\r\n]" re2a_)
9275 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9276 re4 (concat "[^a-zA-Z_]" re4_)
9278 re1 (concat pre re2 post)
9279 re3 (concat pre (if pre re4_ re4) post)
9280 re5 (concat pre ".*" re4)
9281 re2 (concat pre re2)
9282 re2a (concat pre (if pre re2a_ re2a))
9283 re4 (concat pre (if pre re4_ re4))
9284 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9285 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9286 re5 "\\)"
9288 (cond
9289 ((eq type 'org-occur) (org-occur reall))
9290 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9291 (t (goto-char (point-min))
9292 (setq type 'fuzzy)
9293 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9294 (org-search-not-self 1 re1 nil t)
9295 (org-search-not-self 1 re2 nil t)
9296 (org-search-not-self 1 re2a nil t)
9297 (org-search-not-self 1 re3 nil t)
9298 (org-search-not-self 1 re4 nil t)
9299 (org-search-not-self 1 re5 nil t)
9301 (goto-char (match-beginning 1))
9302 (goto-char pos)
9303 (error "No match")))))
9305 ;; Normal string-search
9306 (goto-char (point-min))
9307 (if (search-forward s nil t)
9308 (goto-char (match-beginning 0))
9309 (error "No match"))))
9310 (and (org-mode-p) (org-show-context 'link-search))
9311 type))
9313 (defun org-search-not-self (group &rest args)
9314 "Execute `re-search-forward', but only accept matches that do not
9315 enclose the position of `org-open-link-marker'."
9316 (let ((m org-open-link-marker))
9317 (catch 'exit
9318 (while (apply 're-search-forward args)
9319 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9320 (goto-char (match-end group))
9321 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9322 (> (match-beginning 0) (marker-position m))
9323 (< (match-end 0) (marker-position m)))
9324 (save-match-data
9325 (or (not (org-in-regexp
9326 org-bracket-link-analytic-regexp 1))
9327 (not (match-end 4)) ; no description
9328 (and (<= (match-beginning 4) (point))
9329 (>= (match-end 4) (point))))))
9330 (throw 'exit (point))))))))
9332 (defun org-get-buffer-for-internal-link (buffer)
9333 "Return a buffer to be used for displaying the link target of internal links."
9334 (cond
9335 ((not org-display-internal-link-with-indirect-buffer)
9336 buffer)
9337 ((string-match "(Clone)$" (buffer-name buffer))
9338 (message "Buffer is already a clone, not making another one")
9339 ;; we also do not modify visibility in this case
9340 buffer)
9341 (t ; make a new indirect buffer for displaying the link
9342 (let* ((bn (buffer-name buffer))
9343 (ibn (concat bn "(Clone)"))
9344 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9345 (with-current-buffer ib (org-overview))
9346 ib))))
9348 (defun org-do-occur (regexp &optional cleanup)
9349 "Call the Emacs command `occur'.
9350 If CLEANUP is non-nil, remove the printout of the regular expression
9351 in the *Occur* buffer. This is useful if the regex is long and not useful
9352 to read."
9353 (occur regexp)
9354 (when cleanup
9355 (let ((cwin (selected-window)) win beg end)
9356 (when (setq win (get-buffer-window "*Occur*"))
9357 (select-window win))
9358 (goto-char (point-min))
9359 (when (re-search-forward "match[a-z]+" nil t)
9360 (setq beg (match-end 0))
9361 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9362 (setq end (1- (match-beginning 0)))))
9363 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9364 (goto-char (point-min))
9365 (select-window cwin))))
9367 ;;; The mark ring for links jumps
9369 (defvar org-mark-ring nil
9370 "Mark ring for positions before jumps in Org-mode.")
9371 (defvar org-mark-ring-last-goto nil
9372 "Last position in the mark ring used to go back.")
9373 ;; Fill and close the ring
9374 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9375 (loop for i from 1 to org-mark-ring-length do
9376 (push (make-marker) org-mark-ring))
9377 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9378 org-mark-ring)
9380 (defun org-mark-ring-push (&optional pos buffer)
9381 "Put the current position or POS into the mark ring and rotate it."
9382 (interactive)
9383 (setq pos (or pos (point)))
9384 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9385 (move-marker (car org-mark-ring)
9386 (or pos (point))
9387 (or buffer (current-buffer)))
9388 (message "%s"
9389 (substitute-command-keys
9390 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9392 (defun org-mark-ring-goto (&optional n)
9393 "Jump to the previous position in the mark ring.
9394 With prefix arg N, jump back that many stored positions. When
9395 called several times in succession, walk through the entire ring.
9396 Org-mode commands jumping to a different position in the current file,
9397 or to another Org-mode file, automatically push the old position
9398 onto the ring."
9399 (interactive "p")
9400 (let (p m)
9401 (if (eq last-command this-command)
9402 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9403 (setq p org-mark-ring))
9404 (setq org-mark-ring-last-goto p)
9405 (setq m (car p))
9406 (switch-to-buffer (marker-buffer m))
9407 (goto-char m)
9408 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9410 (defun org-remove-angle-brackets (s)
9411 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9412 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9414 (defun org-add-angle-brackets (s)
9415 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9416 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9418 (defun org-remove-double-quotes (s)
9419 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9420 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9423 ;;; Following specific links
9425 (defun org-follow-timestamp-link ()
9426 (cond
9427 ((org-at-date-range-p t)
9428 (let ((org-agenda-start-on-weekday)
9429 (t1 (match-string 1))
9430 (t2 (match-string 2)))
9431 (setq t1 (time-to-days (org-time-string-to-time t1))
9432 t2 (time-to-days (org-time-string-to-time t2)))
9433 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9434 ((org-at-timestamp-p t)
9435 (org-agenda-list nil (time-to-days (org-time-string-to-time
9436 (substring (match-string 1) 0 10)))
9438 (t (error "This should not happen"))))
9441 ;;; Following file links
9442 (defvar org-wait nil)
9443 (defun org-open-file (path &optional in-emacs line search)
9444 "Open the file at PATH.
9445 First, this expands any special file name abbreviations. Then the
9446 configuration variable `org-file-apps' is checked if it contains an
9447 entry for this file type, and if yes, the corresponding command is launched.
9449 If no application is found, Emacs simply visits the file.
9451 With optional prefix argument IN-EMACS, Emacs will visit the file.
9452 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9453 and to use an external application to visit the file.
9455 Optional LINE specifies a line to go to, optional SEARCH a string
9456 to search for. If LINE or SEARCH is given, the file will be
9457 opened in Emacs, unless an entry from org-file-apps that makes
9458 use of groups in a regexp matches.
9459 If the file does not exist, an error is thrown."
9460 (let* ((file (if (equal path "")
9461 buffer-file-name
9462 (substitute-in-file-name (expand-file-name path))))
9463 (file-apps (append org-file-apps (org-default-apps)))
9464 (apps (org-remove-if
9465 'org-file-apps-entry-match-against-dlink-p file-apps))
9466 (apps-dlink (org-remove-if-not
9467 'org-file-apps-entry-match-against-dlink-p file-apps))
9468 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9469 (dirp (if remp nil (file-directory-p file)))
9470 (file (if (and dirp org-open-directory-means-index-dot-org)
9471 (concat (file-name-as-directory file) "index.org")
9472 file))
9473 (a-m-a-p (assq 'auto-mode apps))
9474 (dfile (downcase file))
9475 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9476 (link (cond ((and (eq line nil)
9477 (eq search nil))
9478 file)
9479 (line
9480 (concat file "::" (number-to-string line)))
9481 (search
9482 (concat file "::" search))))
9483 (dlink (downcase link))
9484 (old-buffer (current-buffer))
9485 (old-pos (point))
9486 (old-mode major-mode)
9487 ext cmd link-match-data)
9488 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9489 (setq ext (match-string 1 dfile))
9490 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9491 (setq ext (match-string 1 dfile))))
9492 (cond
9493 ((member in-emacs '((16) system))
9494 (setq cmd (cdr (assoc 'system apps))))
9495 (in-emacs (setq cmd 'emacs))
9497 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9498 (and dirp (cdr (assoc 'directory apps)))
9499 ; first, try matching against apps-dlink
9500 ; if we get a match here, store the match data for later
9501 (let ((match (assoc-default dlink apps-dlink
9502 'string-match)))
9503 (if match
9504 (progn (setq link-match-data (match-data))
9505 match)
9506 (progn (setq in-emacs (or in-emacs line search))
9507 nil))) ; if we have no match in apps-dlink,
9508 ; always open the file in emacs if line or search
9509 ; is given (for backwards compatibility)
9510 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9511 'string-match)
9512 (cdr (assoc ext apps))
9513 (cdr (assoc t apps))))))
9514 (when (eq cmd 'system)
9515 (setq cmd (cdr (assoc 'system apps))))
9516 (when (eq cmd 'default)
9517 (setq cmd (cdr (assoc t apps))))
9518 (when (eq cmd 'mailcap)
9519 (require 'mailcap)
9520 (mailcap-parse-mailcaps)
9521 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9522 (command (mailcap-mime-info mime-type)))
9523 (if (stringp command)
9524 (setq cmd command)
9525 (setq cmd 'emacs))))
9526 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9527 (not (file-exists-p file))
9528 (not org-open-non-existing-files))
9529 (error "No such file: %s" file))
9530 (cond
9531 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9532 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9533 (while (string-match "['\"]%s['\"]" cmd)
9534 (setq cmd (replace-match "%s" t t cmd)))
9535 (while (string-match "%s" cmd)
9536 (setq cmd (replace-match
9537 (save-match-data
9538 (shell-quote-argument
9539 (convert-standard-filename file)))
9540 t t cmd)))
9542 ;; Replace "%1", "%2" etc. in command with group matches from regex
9543 (save-match-data
9544 (let ((match-index 1)
9545 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9546 (set-match-data link-match-data)
9547 (while (<= match-index number-of-groups)
9548 (let ((regex (concat "%" (number-to-string match-index)))
9549 (replace-with (match-string match-index dlink)))
9550 (while (string-match regex cmd)
9551 (setq cmd (replace-match replace-with t t cmd))))
9552 (setq match-index (+ match-index 1)))))
9554 (save-window-excursion
9555 (start-process-shell-command cmd nil cmd)
9556 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9558 ((or (stringp cmd)
9559 (eq cmd 'emacs))
9560 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9561 (widen)
9562 (if line (org-goto-line line)
9563 (if search (org-link-search search))))
9564 ((consp cmd)
9565 (let ((file (convert-standard-filename file)))
9566 (save-match-data
9567 (set-match-data link-match-data)
9568 (eval cmd))))
9569 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9570 (and (org-mode-p) (eq old-mode 'org-mode)
9571 (or (not (equal old-buffer (current-buffer)))
9572 (not (equal old-pos (point))))
9573 (org-mark-ring-push old-pos old-buffer))))
9575 (defun org-file-apps-entry-match-against-dlink-p (entry)
9576 "This function returns non-nil if `entry' uses a regular
9577 expression which should be matched against the whole link by
9578 org-open-file.
9580 It assumes that is the case when the entry uses a regular
9581 expression which has at least one grouping construct and the
9582 action is either a lisp form or a command string containing
9583 '%1', i.e. using at least one subexpression match as a
9584 parameter."
9585 (let ((selector (car entry))
9586 (action (cdr entry)))
9587 (if (stringp selector)
9588 (and (> (regexp-opt-depth selector) 0)
9589 (or (and (stringp action)
9590 (string-match "%[0-9]" action))
9591 (consp action)))
9592 nil)))
9594 (defun org-default-apps ()
9595 "Return the default applications for this operating system."
9596 (cond
9597 ((eq system-type 'darwin)
9598 org-file-apps-defaults-macosx)
9599 ((eq system-type 'windows-nt)
9600 org-file-apps-defaults-windowsnt)
9601 (t org-file-apps-defaults-gnu)))
9603 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9604 "Convert extensions to regular expressions in the cars of LIST.
9605 Also, weed out any non-string entries, because the return value is used
9606 only for regexp matching.
9607 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9608 point to the symbol `emacs', indicating that the file should
9609 be opened in Emacs."
9610 (append
9611 (delq nil
9612 (mapcar (lambda (x)
9613 (if (not (stringp (car x)))
9615 (if (string-match "\\W" (car x))
9617 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9618 list))
9619 (if add-auto-mode
9620 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9622 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9623 (defun org-file-remote-p (file)
9624 "Test whether FILE specifies a location on a remote system.
9625 Return non-nil if the location is indeed remote.
9627 For example, the filename \"/user@host:/foo\" specifies a location
9628 on the system \"/user@host:\"."
9629 (cond ((fboundp 'file-remote-p)
9630 (file-remote-p file))
9631 ((fboundp 'tramp-handle-file-remote-p)
9632 (tramp-handle-file-remote-p file))
9633 ((and (boundp 'ange-ftp-name-format)
9634 (string-match (car ange-ftp-name-format) file))
9636 (t nil)))
9639 ;;;; Refiling
9641 (defun org-get-org-file ()
9642 "Read a filename, with default directory `org-directory'."
9643 (let ((default (or org-default-notes-file remember-data-file)))
9644 (read-file-name (format "File name [%s]: " default)
9645 (file-name-as-directory org-directory)
9646 default)))
9648 (defun org-notes-order-reversed-p ()
9649 "Check if the current file should receive notes in reversed order."
9650 (cond
9651 ((not org-reverse-note-order) nil)
9652 ((eq t org-reverse-note-order) t)
9653 ((not (listp org-reverse-note-order)) nil)
9654 (t (catch 'exit
9655 (let ((all org-reverse-note-order)
9656 entry)
9657 (while (setq entry (pop all))
9658 (if (string-match (car entry) buffer-file-name)
9659 (throw 'exit (cdr entry))))
9660 nil)))))
9662 (defvar org-refile-target-table nil
9663 "The list of refile targets, created by `org-refile'.")
9665 (defvar org-agenda-new-buffers nil
9666 "Buffers created to visit agenda files.")
9668 (defvar org-refile-cache nil
9669 "Cache for refile targets.")
9672 (defvar org-refile-markers nil
9673 "All the markers used for caching refile locations.")
9675 (defun org-refile-marker (pos)
9676 "Get a new refile marker, but only if caching is in use."
9677 (if (not org-refile-use-cache)
9679 (let ((m (make-marker)))
9680 (move-marker m pos)
9681 (push m org-refile-markers)
9682 m)))
9684 (defun org-refile-cache-clear ()
9685 "Clear the refile cache and disable all the markers."
9686 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9687 (setq org-refile-markers nil)
9688 (setq org-refile-cache nil)
9689 (message "Refile cache has been cleared"))
9691 (defun org-refile-cache-check-set (set)
9692 "Check if all the markers in the cache still have live buffers."
9693 (let (marker)
9694 (catch 'exit
9695 (while (and set (setq marker (nth 3 (pop set))))
9696 ;; if org-refile-use-outline-path is 'file, marker may be nil
9697 (when (and marker (null (marker-buffer marker)))
9698 (message "not found") (sit-for 3)
9699 (throw 'exit nil)))
9700 t)))
9702 (defun org-refile-cache-put (set &rest identifiers)
9703 "Push the refile targets SET into the cache, under IDENTIFIERS."
9704 (let* ((key (sha1 (prin1-to-string identifiers)))
9705 (entry (assoc key org-refile-cache)))
9706 (if entry
9707 (setcdr entry set)
9708 (push (cons key set) org-refile-cache))))
9710 (defun org-refile-cache-get (&rest identifiers)
9711 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9712 (cond
9713 ((not org-refile-cache) nil)
9714 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9716 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9717 org-refile-cache))))
9718 (and set (org-refile-cache-check-set set) set)))))
9720 (defun org-get-refile-targets (&optional default-buffer)
9721 "Produce a table with refile targets."
9722 (let ((case-fold-search nil)
9723 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9724 (entries (or org-refile-targets '((nil . (:level . 1)))))
9725 targets tgs txt re files f desc descre fast-path-p level pos0)
9726 (message "Getting targets...")
9727 (with-current-buffer (or default-buffer (current-buffer))
9728 (while (setq entry (pop entries))
9729 (setq files (car entry) desc (cdr entry))
9730 (setq fast-path-p nil)
9731 (cond
9732 ((null files) (setq files (list (current-buffer))))
9733 ((eq files 'org-agenda-files)
9734 (setq files (org-agenda-files 'unrestricted)))
9735 ((and (symbolp files) (fboundp files))
9736 (setq files (funcall files)))
9737 ((and (symbolp files) (boundp files))
9738 (setq files (symbol-value files))))
9739 (if (stringp files) (setq files (list files)))
9740 (cond
9741 ((eq (car desc) :tag)
9742 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9743 ((eq (car desc) :todo)
9744 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9745 ((eq (car desc) :regexp)
9746 (setq descre (cdr desc)))
9747 ((eq (car desc) :level)
9748 (setq descre (concat "^\\*\\{" (number-to-string
9749 (if org-odd-levels-only
9750 (1- (* 2 (cdr desc)))
9751 (cdr desc)))
9752 "\\}[ \t]")))
9753 ((eq (car desc) :maxlevel)
9754 (setq fast-path-p t)
9755 (setq descre (concat "^\\*\\{1," (number-to-string
9756 (if org-odd-levels-only
9757 (1- (* 2 (cdr desc)))
9758 (cdr desc)))
9759 "\\}[ \t]")))
9760 (t (error "Bad refiling target description %s" desc)))
9761 (while (setq f (pop files))
9762 (with-current-buffer
9763 (if (bufferp f) f (org-get-agenda-file-buffer f))
9765 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9766 (progn
9767 (if (bufferp f) (setq f (buffer-file-name
9768 (buffer-base-buffer f))))
9769 (setq f (and f (expand-file-name f)))
9770 (if (eq org-refile-use-outline-path 'file)
9771 (push (list (file-name-nondirectory f) f nil nil) tgs))
9772 (save-excursion
9773 (save-restriction
9774 (widen)
9775 (goto-char (point-min))
9776 (while (re-search-forward descre nil t)
9777 (goto-char (setq pos0 (point-at-bol)))
9778 (catch 'next
9779 (when org-refile-target-verify-function
9780 (save-match-data
9781 (or (funcall org-refile-target-verify-function)
9782 (throw 'next t))))
9783 (when (looking-at org-complex-heading-regexp)
9784 (setq level (org-reduced-level
9785 (- (match-end 1) (match-beginning 1)))
9786 txt (org-link-display-format (match-string 4))
9787 re (concat "^" (regexp-quote
9788 (buffer-substring
9789 (match-beginning 1)
9790 (match-end 4)))))
9791 (if (match-end 5) (setq re (concat
9792 re "[ \t]+"
9793 (regexp-quote
9794 (match-string 5)))))
9795 (setq re (concat re "[ \t]*$"))
9796 (when org-refile-use-outline-path
9797 (setq txt (mapconcat
9798 'org-protect-slash
9799 (append
9800 (if (eq org-refile-use-outline-path
9801 'file)
9802 (list (file-name-nondirectory
9803 (buffer-file-name
9804 (buffer-base-buffer))))
9805 (if (eq org-refile-use-outline-path
9806 'full-file-path)
9807 (list (buffer-file-name
9808 (buffer-base-buffer)))))
9809 (org-get-outline-path fast-path-p
9810 level txt)
9811 (list txt))
9812 "/")))
9813 (push (list txt f re (org-refile-marker (point)))
9814 tgs)))
9815 (when (= (point) pos0)
9816 ;; verification function has not moved point
9817 (goto-char (point-at-eol))))))))
9818 (when org-refile-use-cache
9819 (org-refile-cache-put tgs (buffer-file-name) descre))
9820 (setq targets (append tgs targets))
9821 ))))
9822 (message "Getting targets...done")
9823 (nreverse targets)))
9825 (defun org-protect-slash (s)
9826 (while (string-match "/" s)
9827 (setq s (replace-match "\\" t t s)))
9830 (defvar org-olpa (make-vector 20 nil))
9832 (defun org-get-outline-path (&optional fastp level heading)
9833 "Return the outline path to the current entry, as a list.
9835 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9836 routine which makes outline path derivations for an entire file,
9837 avoiding backtracing. Refile target collection makes use of that."
9838 (if fastp
9839 (progn
9840 (if (> level 19)
9841 (error "Outline path failure, more than 19 levels."))
9842 (loop for i from level upto 19 do
9843 (aset org-olpa i nil))
9844 (prog1
9845 (delq nil (append org-olpa nil))
9846 (aset org-olpa level heading)))
9847 (let (rtn case-fold-search)
9848 (save-excursion
9849 (save-restriction
9850 (widen)
9851 (while (org-up-heading-safe)
9852 (when (looking-at org-complex-heading-regexp)
9853 (push (org-match-string-no-properties 4) rtn)))
9854 rtn)))))
9856 (defun org-format-outline-path (path &optional width prefix)
9857 "Format the outlie path PATH for display.
9858 Width is the maximum number of characters that is available.
9859 Prefix is a prefix to be included in the returned string,
9860 such as the file name."
9861 (setq width (or width 79))
9862 (if prefix (setq width (- width (length prefix))))
9863 (if (not path)
9864 (or prefix "")
9865 (let* ((nsteps (length path))
9866 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9867 (maxwidth (if (<= total-width width)
9868 10000 ;; everything fits
9869 ;; we need to shorten the level headings
9870 (/ (- width nsteps) nsteps)))
9871 (org-odd-levels-only nil)
9872 (n 0)
9873 (total (1+ (length prefix))))
9874 (setq maxwidth (max maxwidth 10))
9875 (concat prefix
9876 (mapconcat
9877 (lambda (h)
9878 (setq n (1+ n))
9879 (if (and (= n nsteps) (< maxwidth 10000))
9880 (setq maxwidth (- total-width total)))
9881 (if (< (length h) maxwidth)
9882 (progn (setq total (+ total (length h) 1)) h)
9883 (setq h (substring h 0 (- maxwidth 2))
9884 total (+ total maxwidth 1))
9885 (if (string-match "[ \t]+\\'" h)
9886 (setq h (substring h 0 (match-beginning 0))))
9887 (setq h (concat h "..")))
9888 (org-add-props h nil 'face
9889 (nth (% (1- n) org-n-level-faces)
9890 org-level-faces))
9892 path "/")))))
9894 (defun org-display-outline-path (&optional file current)
9895 "Display the current outline path in the echo area."
9896 (interactive "P")
9897 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9898 (case-fold-search nil)
9899 (path (and (org-mode-p) (org-get-outline-path))))
9900 (if current (setq path (append path
9901 (save-excursion
9902 (org-back-to-heading t)
9903 (if (looking-at org-complex-heading-regexp)
9904 (list (match-string 4)))))))
9905 (message "%s"
9906 (org-format-outline-path
9907 path
9908 (1- (frame-width))
9909 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9911 (defvar org-refile-history nil
9912 "History for refiling operations.")
9914 (defvar org-after-refile-insert-hook nil
9915 "Hook run after `org-refile' has inserted its stuff at the new location.
9916 Note that this is still *before* the stuff will be removed from
9917 the *old* location.")
9919 (defun org-refile (&optional goto default-buffer rfloc)
9920 "Move the entry at point to another heading.
9921 The list of target headings is compiled using the information in
9922 `org-refile-targets', which see. This list is created before each use
9923 and will therefore always be up-to-date.
9925 At the target location, the entry is filed as a subitem of the target heading.
9926 Depending on `org-reverse-note-order', the new subitem will either be the
9927 first or the last subitem.
9929 If there is an active region, all entries in that region will be moved.
9930 However, the region must fulfil the requirement that the first heading
9931 is the first one sets the top-level of the moved text - at most siblings
9932 below it are allowed.
9934 With prefix arg GOTO, the command will only visit the target location,
9935 not actually move anything.
9936 With a double prefix `C-u C-u', go to the location where the last refiling
9937 operation has put the subtree.
9938 With a prefix argument of `2', refile to the running clock.
9940 RFLOC can be a refile location obtained in a different way.
9942 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
9944 If you are using target caching (see `org-refile-use-cache'),
9945 You have to clear the target cache in order to find new targets.
9946 This can be done with a 0 prefix: `C-0 C-c C-w'"
9947 (interactive "P")
9948 (if (member goto '(0 (64)))
9949 (org-refile-cache-clear)
9950 (let* ((cbuf (current-buffer))
9951 (regionp (org-region-active-p))
9952 (region-start (and regionp (region-beginning)))
9953 (region-end (and regionp (region-end)))
9954 (region-length (and regionp (- region-end region-start)))
9955 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9956 pos it nbuf file re level reversed)
9957 (setq last-command nil)
9958 (when regionp
9959 (goto-char region-start)
9960 (or (bolp) (goto-char (point-at-bol)))
9961 (setq region-start (point))
9962 (unless (org-kill-is-subtree-p
9963 (buffer-substring region-start region-end))
9964 (error "The region is not a (sequence of) subtree(s)")))
9965 (if (equal goto '(16))
9966 (org-refile-goto-last-stored)
9967 (when (or
9968 (and (equal goto 2)
9969 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9970 (prog1
9971 (setq it (list (or org-clock-heading "running clock")
9972 (buffer-file-name
9973 (marker-buffer org-clock-hd-marker))
9975 (marker-position org-clock-hd-marker)))
9976 (setq goto nil)))
9977 (setq it (or rfloc
9978 (save-excursion
9979 (org-refile-get-location
9980 (if goto "Goto: " "Refile to: ") default-buffer
9981 org-refile-allow-creating-parent-nodes)))))
9982 (setq file (nth 1 it)
9983 re (nth 2 it)
9984 pos (nth 3 it))
9985 (if (and (not goto)
9987 (equal (buffer-file-name) file)
9988 (if regionp
9989 (and (>= pos region-start)
9990 (<= pos region-end))
9991 (and (>= pos (point))
9992 (< pos (save-excursion
9993 (org-end-of-subtree t t))))))
9994 (error "Cannot refile to position inside the tree or region"))
9996 (setq nbuf (or (find-buffer-visiting file)
9997 (find-file-noselect file)))
9998 (if goto
9999 (progn
10000 (switch-to-buffer nbuf)
10001 (goto-char pos)
10002 (org-show-context 'org-goto))
10003 (if regionp
10004 (progn
10005 (org-kill-new (buffer-substring region-start region-end))
10006 (org-save-markers-in-region region-start region-end))
10007 (org-copy-subtree 1 nil t))
10008 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10009 (find-file-noselect file)))
10010 (setq reversed (org-notes-order-reversed-p))
10011 (save-excursion
10012 (save-restriction
10013 (widen)
10014 (if pos
10015 (progn
10016 (goto-char pos)
10017 (looking-at outline-regexp)
10018 (setq level (org-get-valid-level (funcall outline-level) 1))
10019 (goto-char
10020 (if reversed
10021 (or (outline-next-heading) (point-max))
10022 (or (save-excursion (org-get-next-sibling))
10023 (org-end-of-subtree t t)
10024 (point-max)))))
10025 (setq level 1)
10026 (if (not reversed)
10027 (goto-char (point-max))
10028 (goto-char (point-min))
10029 (or (outline-next-heading) (goto-char (point-max)))))
10030 (if (not (bolp)) (newline))
10031 (org-paste-subtree level)
10032 (when org-log-refile
10033 (org-add-log-setup 'refile nil nil 'findpos
10034 org-log-refile)
10035 (unless (eq org-log-refile 'note)
10036 (save-excursion (org-add-log-note))))
10037 (and org-auto-align-tags (org-set-tags nil t))
10038 (bookmark-set "org-refile-last-stored")
10039 (if (fboundp 'deactivate-mark) (deactivate-mark))
10040 (run-hooks 'org-after-refile-insert-hook))))
10041 (if regionp
10042 (delete-region (point) (+ (point) region-length))
10043 (org-cut-subtree))
10044 (when (featurep 'org-inlinetask)
10045 (org-inlinetask-remove-END-maybe))
10046 (setq org-markers-to-move nil)
10047 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10049 (defun org-refile-goto-last-stored ()
10050 "Go to the location where the last refile was stored."
10051 (interactive)
10052 (bookmark-jump "org-refile-last-stored")
10053 (message "This is the location of the last refile"))
10055 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10056 "Prompt the user for a refile location, using PROMPT."
10057 (let ((org-refile-targets org-refile-targets)
10058 (org-refile-use-outline-path org-refile-use-outline-path))
10059 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10060 (unless org-refile-target-table
10061 (error "No refile targets"))
10062 (let* ((cbuf (current-buffer))
10063 (partial-completion-mode nil)
10064 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10065 (cfunc (if (and org-refile-use-outline-path
10066 org-outline-path-complete-in-steps)
10067 'org-olpath-completing-read
10068 'org-icompleting-read))
10069 (extra (if org-refile-use-outline-path "/" ""))
10070 (filename (and cfn (expand-file-name cfn)))
10071 (tbl (mapcar
10072 (lambda (x)
10073 (if (and (not (member org-refile-use-outline-path
10074 '(file full-file-path)))
10075 (not (equal filename (nth 1 x))))
10076 (cons (concat (car x) extra " ("
10077 (file-name-nondirectory (nth 1 x)) ")")
10078 (cdr x))
10079 (cons (concat (car x) extra) (cdr x))))
10080 org-refile-target-table))
10081 (completion-ignore-case t)
10082 pa answ parent-target child parent old-hist)
10083 (setq old-hist org-refile-history)
10084 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10085 nil 'org-refile-history))
10086 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10087 (if pa
10088 (progn
10089 (when (or (not org-refile-history)
10090 (not (eq old-hist org-refile-history))
10091 (not (equal (car pa) (car org-refile-history))))
10092 (setq org-refile-history
10093 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10094 org-refile-history
10095 (cdr org-refile-history))))
10096 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10097 (pop org-refile-history)))
10099 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10100 (progn
10101 (setq parent (match-string 1 answ)
10102 child (match-string 2 answ))
10103 (setq parent-target (or (assoc parent tbl)
10104 (assoc (concat parent "/") tbl)))
10105 (when (and parent-target
10106 (or (eq new-nodes t)
10107 (and (eq new-nodes 'confirm)
10108 (y-or-n-p (format "Create new node \"%s\"? "
10109 child)))))
10110 (org-refile-new-child parent-target child)))
10111 (error "Invalid target location")))))
10113 (defun org-refile-new-child (parent-target child)
10114 "Use refile target PARENT-TARGET to add new CHILD below it."
10115 (unless parent-target
10116 (error "Cannot find parent for new node"))
10117 (let ((file (nth 1 parent-target))
10118 (pos (nth 3 parent-target))
10119 level)
10120 (with-current-buffer (or (find-buffer-visiting file)
10121 (find-file-noselect file))
10122 (save-excursion
10123 (save-restriction
10124 (widen)
10125 (if pos
10126 (goto-char pos)
10127 (goto-char (point-max))
10128 (if (not (bolp)) (newline)))
10129 (when (looking-at outline-regexp)
10130 (setq level (funcall outline-level))
10131 (org-end-of-subtree t t))
10132 (org-back-over-empty-lines)
10133 (insert "\n" (make-string
10134 (if pos (org-get-valid-level level 1) 1) ?*)
10135 " " child "\n")
10136 (beginning-of-line 0)
10137 (list (concat (car parent-target) "/" child) file "" (point)))))))
10139 (defun org-olpath-completing-read (prompt collection &rest args)
10140 "Read an outline path like a file name."
10141 (let ((thetable collection)
10142 (org-completion-use-ido nil) ; does not work with ido.
10143 (org-completion-use-iswitchb nil)) ; or iswitchb
10144 (apply
10145 'org-icompleting-read prompt
10146 (lambda (string predicate &optional flag)
10147 (let (rtn r f (l (length string)))
10148 (cond
10149 ((eq flag nil)
10150 ;; try completion
10151 (try-completion string thetable))
10152 ((eq flag t)
10153 ;; all-completions
10154 (setq rtn (all-completions string thetable predicate))
10155 (mapcar
10156 (lambda (x)
10157 (setq r (substring x l))
10158 (if (string-match " ([^)]*)$" x)
10159 (setq f (match-string 0 x))
10160 (setq f ""))
10161 (if (string-match "/" r)
10162 (concat string (substring r 0 (match-end 0)) f)
10164 rtn))
10165 ((eq flag 'lambda)
10166 ;; exact match?
10167 (assoc string thetable)))
10169 args)))
10171 ;;;; Dynamic blocks
10173 (defun org-find-dblock (name)
10174 "Find the first dynamic block with name NAME in the buffer.
10175 If not found, stay at current position and return nil."
10176 (let (pos)
10177 (save-excursion
10178 (goto-char (point-min))
10179 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10180 nil t)
10181 (match-beginning 0))))
10182 (if pos (goto-char pos))
10183 pos))
10185 (defconst org-dblock-start-re
10186 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10187 "Matches the start line of a dynamic block, with parameters.")
10189 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10190 "Matches the end of a dynamic block.")
10192 (defun org-create-dblock (plist)
10193 "Create a dynamic block section, with parameters taken from PLIST.
10194 PLIST must contain a :name entry which is used as name of the block."
10195 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10196 (end-of-line 1)
10197 (newline))
10198 (let ((col (current-column))
10199 (name (plist-get plist :name)))
10200 (insert "#+BEGIN: " name)
10201 (while plist
10202 (if (eq (car plist) :name)
10203 (setq plist (cddr plist))
10204 (insert " " (prin1-to-string (pop plist)))))
10205 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10206 (beginning-of-line -2)))
10208 (defun org-prepare-dblock ()
10209 "Prepare dynamic block for refresh.
10210 This empties the block, puts the cursor at the insert position and returns
10211 the property list including an extra property :name with the block name."
10212 (unless (looking-at org-dblock-start-re)
10213 (error "Not at a dynamic block"))
10214 (let* ((begdel (1+ (match-end 0)))
10215 (name (org-no-properties (match-string 1)))
10216 (params (append (list :name name)
10217 (read (concat "(" (match-string 3) ")")))))
10218 (save-excursion
10219 (beginning-of-line 1)
10220 (skip-chars-forward " \t")
10221 (setq params (plist-put params :indentation-column (current-column))))
10222 (unless (re-search-forward org-dblock-end-re nil t)
10223 (error "Dynamic block not terminated"))
10224 (setq params
10225 (append params
10226 (list :content (buffer-substring
10227 begdel (match-beginning 0)))))
10228 (delete-region begdel (match-beginning 0))
10229 (goto-char begdel)
10230 (open-line 1)
10231 params))
10233 (defun org-map-dblocks (&optional command)
10234 "Apply COMMAND to all dynamic blocks in the current buffer.
10235 If COMMAND is not given, use `org-update-dblock'."
10236 (let ((cmd (or command 'org-update-dblock)))
10237 (save-excursion
10238 (goto-char (point-min))
10239 (while (re-search-forward org-dblock-start-re nil t)
10240 (goto-char (match-beginning 0))
10241 (save-excursion
10242 (condition-case nil
10243 (funcall cmd)
10244 (error (message "Error during update of dynamic block"))))
10245 (unless (re-search-forward org-dblock-end-re nil t)
10246 (error "Dynamic block not terminated"))))))
10248 (defun org-dblock-update (&optional arg)
10249 "User command for updating dynamic blocks.
10250 Update the dynamic block at point. With prefix ARG, update all dynamic
10251 blocks in the buffer."
10252 (interactive "P")
10253 (if arg
10254 (org-update-all-dblocks)
10255 (or (looking-at org-dblock-start-re)
10256 (org-beginning-of-dblock))
10257 (org-update-dblock)))
10259 (defun org-update-dblock ()
10260 "Update the dynamic block at point
10261 This means to empty the block, parse for parameters and then call
10262 the correct writing function."
10263 (save-window-excursion
10264 (let* ((pos (point))
10265 (line (org-current-line))
10266 (params (org-prepare-dblock))
10267 (name (plist-get params :name))
10268 (indent (plist-get params :indentation-column))
10269 (cmd (intern (concat "org-dblock-write:" name))))
10270 (message "Updating dynamic block `%s' at line %d..." name line)
10271 (funcall cmd params)
10272 (message "Updating dynamic block `%s' at line %d...done" name line)
10273 (goto-char pos)
10274 (when (and indent (> indent 0))
10275 (setq indent (make-string indent ?\ ))
10276 (save-excursion
10277 (org-beginning-of-dblock)
10278 (forward-line 1)
10279 (while (not (looking-at org-dblock-end-re))
10280 (insert indent)
10281 (beginning-of-line 2))
10282 (when (looking-at org-dblock-end-re)
10283 (and (looking-at "[ \t]+")
10284 (replace-match ""))
10285 (insert indent)))))))
10287 (defun org-beginning-of-dblock ()
10288 "Find the beginning of the dynamic block at point.
10289 Error if there is no such block at point."
10290 (let ((pos (point))
10291 beg)
10292 (end-of-line 1)
10293 (if (and (re-search-backward org-dblock-start-re nil t)
10294 (setq beg (match-beginning 0))
10295 (re-search-forward org-dblock-end-re nil t)
10296 (> (match-end 0) pos))
10297 (goto-char beg)
10298 (goto-char pos)
10299 (error "Not in a dynamic block"))))
10301 (defun org-update-all-dblocks ()
10302 "Update all dynamic blocks in the buffer.
10303 This function can be used in a hook."
10304 (when (org-mode-p)
10305 (org-map-dblocks 'org-update-dblock)))
10308 ;;;; Completion
10310 (defconst org-additional-option-like-keywords
10311 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10312 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10313 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10314 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10315 "BEGIN:" "END:"
10316 "ORGTBL" "TBLFM:" "TBLNAME:"
10317 "BEGIN_EXAMPLE" "END_EXAMPLE"
10318 "BEGIN_QUOTE" "END_QUOTE"
10319 "BEGIN_VERSE" "END_VERSE"
10320 "BEGIN_CENTER" "END_CENTER"
10321 "BEGIN_SRC" "END_SRC"
10322 "CATEGORY" "COLUMNS"
10323 "CAPTION" "LABEL"
10324 "SETUPFILE"
10325 "BIND"
10326 "MACRO"))
10328 (defcustom org-structure-template-alist
10330 ("s" "#+begin_src ?\n\n#+end_src"
10331 "<src lang=\"?\">\n\n</src>")
10332 ("e" "#+begin_example\n?\n#+end_example"
10333 "<example>\n?\n</example>")
10334 ("q" "#+begin_quote\n?\n#+end_quote"
10335 "<quote>\n?\n</quote>")
10336 ("v" "#+begin_verse\n?\n#+end_verse"
10337 "<verse>\n?\n/verse>")
10338 ("c" "#+begin_center\n?\n#+end_center"
10339 "<center>\n?\n/center>")
10340 ("l" "#+begin_latex\n?\n#+end_latex"
10341 "<literal style=\"latex\">\n?\n</literal>")
10342 ("L" "#+latex: "
10343 "<literal style=\"latex\">?</literal>")
10344 ("h" "#+begin_html\n?\n#+end_html"
10345 "<literal style=\"html\">\n?\n</literal>")
10346 ("H" "#+html: "
10347 "<literal style=\"html\">?</literal>")
10348 ("a" "#+begin_ascii\n?\n#+end_ascii")
10349 ("A" "#+ascii: ")
10350 ("i" "#+include %file ?"
10351 "<include file=%file markup=\"?\">")
10353 "Structure completion elements.
10354 This is a list of abbreviation keys and values. The value gets inserted
10355 if you type `<' followed by the key and then press the completion key,
10356 usually `M-TAB'. %file will be replaced by a file name after prompting
10357 for the file using completion.
10358 There are two templates for each key, the first uses the original Org syntax,
10359 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10360 the default when the /org-mtags.el/ module has been loaded. See also the
10361 variable `org-mtags-prefer-muse-templates'.
10362 This is an experimental feature, it is undecided if it is going to stay in."
10363 :group 'org-completion
10364 :type '(repeat
10365 (string :tag "Key")
10366 (string :tag "Template")
10367 (string :tag "Muse Template")))
10369 (defun org-try-structure-completion ()
10370 "Try to complete a structure template before point.
10371 This looks for strings like \"<e\" on an otherwise empty line and
10372 expands them."
10373 (let ((l (buffer-substring (point-at-bol) (point)))
10375 (when (and (looking-at "[ \t]*$")
10376 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10377 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10378 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10379 (match-beginning 1)) a)
10380 t)))
10382 (defun org-complete-expand-structure-template (start cell)
10383 "Expand a structure template."
10384 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10385 (rpl (nth (if musep 2 1) cell))
10386 (ind ""))
10387 (delete-region start (point))
10388 (when (string-match "\\`#\\+" rpl)
10389 (cond
10390 ((bolp))
10391 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10392 (setq ind (buffer-substring (point-at-bol) (point))))
10393 (t (newline))))
10394 (setq start (point))
10395 (if (string-match "%file" rpl)
10396 (setq rpl (replace-match
10397 (concat
10398 "\""
10399 (save-match-data
10400 (abbreviate-file-name (read-file-name "Include file: ")))
10401 "\"")
10402 t t rpl)))
10403 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10404 (concat "\n" ind)))
10405 (insert rpl)
10406 (if (re-search-backward "\\?" start t) (delete-char 1))))
10409 (defun org-complete (&optional arg)
10410 "Perform completion on word at point.
10411 At the beginning of a headline, this completes TODO keywords as given in
10412 `org-todo-keywords'.
10413 If the current word is preceded by a backslash, completes the TeX symbols
10414 that are supported for HTML support.
10415 If the current word is preceded by \"#+\", completes special words for
10416 setting file options.
10417 In the line after \"#+STARTUP:, complete valid keywords.\"
10418 At all other locations, this simply calls the value of
10419 `org-completion-fallback-command'."
10420 (interactive "P")
10421 (org-without-partial-completion
10422 (catch 'exit
10423 (let* ((a nil)
10424 (end (point))
10425 (beg1 (save-excursion
10426 (skip-chars-backward (org-re "[:alnum:]_@"))
10427 (point)))
10428 (beg (save-excursion
10429 (skip-chars-backward "a-zA-Z0-9_:$")
10430 (point)))
10431 (confirm (lambda (x) (stringp (car x))))
10432 (searchhead (equal (char-before beg) ?*))
10433 (struct
10434 (when (and (member (char-before beg1) '(?. ?<))
10435 (setq a (assoc (buffer-substring beg1 (point))
10436 org-structure-template-alist)))
10437 (org-complete-expand-structure-template (1- beg1) a)
10438 (throw 'exit t)))
10439 (tag (and (equal (char-before beg1) ?:)
10440 (equal (char-after (point-at-bol)) ?*)))
10441 (prop (and (equal (char-before beg1) ?:)
10442 (not (equal (char-after (point-at-bol)) ?*))))
10443 (texp (equal (char-before beg) ?\\))
10444 (link (equal (char-before beg) ?\[))
10445 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10446 beg)
10447 "#+"))
10448 (startup (string-match "^#\\+STARTUP:.*"
10449 (buffer-substring (point-at-bol) (point))))
10450 (completion-ignore-case opt)
10451 (type nil)
10452 (tbl nil)
10453 (table (cond
10454 (opt
10455 (setq type :opt)
10456 (require 'org-exp)
10457 (append
10458 (delq nil
10459 (mapcar
10460 (lambda (x)
10461 (if (string-match
10462 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10463 (cons (match-string 2 x)
10464 (match-string 1 x))))
10465 (org-split-string (org-get-current-options) "\n")))
10466 (mapcar 'list org-additional-option-like-keywords)))
10467 (startup
10468 (setq type :startup)
10469 org-startup-options)
10470 (link (append org-link-abbrev-alist-local
10471 org-link-abbrev-alist))
10472 (texp
10473 (setq type :tex)
10474 (append org-entities-user org-entities))
10475 ((string-match "\\`\\*+[ \t]+\\'"
10476 (buffer-substring (point-at-bol) beg))
10477 (setq type :todo)
10478 (mapcar 'list org-todo-keywords-1))
10479 (searchhead
10480 (setq type :searchhead)
10481 (save-excursion
10482 (goto-char (point-min))
10483 (while (re-search-forward org-todo-line-regexp nil t)
10484 (push (list
10485 (org-make-org-heading-search-string
10486 (match-string 3) t))
10487 tbl)))
10488 tbl)
10489 (tag (setq type :tag beg beg1)
10490 (or org-tag-alist (org-get-buffer-tags)))
10491 (prop (setq type :prop beg beg1)
10492 (mapcar 'list (org-buffer-property-keys nil t t)))
10493 (t (progn
10494 (call-interactively org-completion-fallback-command)
10495 (throw 'exit nil)))))
10496 (pattern (buffer-substring-no-properties beg end))
10497 (completion (try-completion pattern table confirm)))
10498 (cond ((eq completion t)
10499 (if (not (assoc (upcase pattern) table))
10500 (message "Already complete")
10501 (if (and (equal type :opt)
10502 (not (member (car (assoc (upcase pattern) table))
10503 org-additional-option-like-keywords)))
10504 (insert (substring (cdr (assoc (upcase pattern) table))
10505 (length pattern)))
10506 (if (memq type '(:tag :prop)) (insert ":")))))
10507 ((null completion)
10508 (message "Can't find completion for \"%s\"" pattern)
10509 (ding))
10510 ((not (string= pattern completion))
10511 (delete-region beg end)
10512 (if (string-match " +$" completion)
10513 (setq completion (replace-match "" t t completion)))
10514 (insert completion)
10515 (if (get-buffer-window "*Completions*")
10516 (delete-window (get-buffer-window "*Completions*")))
10517 (if (assoc completion table)
10518 (if (eq type :todo) (insert " ")
10519 (if (memq type '(:tag :prop)) (insert ":"))))
10520 (if (and (equal type :opt) (assoc completion table))
10521 (message "%s" (substitute-command-keys
10522 "Press \\[org-complete] again to insert example settings"))))
10524 (message "Making completion list...")
10525 (let ((list (sort (all-completions pattern table confirm)
10526 'string<)))
10527 (with-output-to-temp-buffer "*Completions*"
10528 (condition-case nil
10529 ;; Protection needed for XEmacs and emacs 21
10530 (display-completion-list list pattern)
10531 (error (display-completion-list list)))))
10532 (message "Making completion list...%s" "done")))))))
10534 ;;;; TODO, DEADLINE, Comments
10536 (defun org-toggle-comment ()
10537 "Change the COMMENT state of an entry."
10538 (interactive)
10539 (save-excursion
10540 (org-back-to-heading)
10541 (let (case-fold-search)
10542 (if (looking-at (concat outline-regexp
10543 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10544 (replace-match "" t t nil 1)
10545 (if (looking-at outline-regexp)
10546 (progn
10547 (goto-char (match-end 0))
10548 (insert org-comment-string " ")))))))
10550 (defvar org-last-todo-state-is-todo nil
10551 "This is non-nil when the last TODO state change led to a TODO state.
10552 If the last change removed the TODO tag or switched to DONE, then
10553 this is nil.")
10555 (defvar org-setting-tags nil) ; dynamically skipped
10557 (defun org-parse-local-options (string var)
10558 "Parse STRING for startup setting relevant for variable VAR."
10559 (let ((rtn (symbol-value var))
10560 e opts)
10561 (save-match-data
10562 (if (or (not string) (not (string-match "\\S-" string)))
10564 (setq opts (delq nil (mapcar (lambda (x)
10565 (setq e (assoc x org-startup-options))
10566 (if (eq (nth 1 e) var) e nil))
10567 (org-split-string string "[ \t]+"))))
10568 (if (not opts)
10570 (setq rtn nil)
10571 (while (setq e (pop opts))
10572 (if (not (nth 3 e))
10573 (setq rtn (nth 2 e))
10574 (if (not (listp rtn)) (setq rtn nil))
10575 (push (nth 2 e) rtn)))
10576 rtn)))))
10578 (defvar org-todo-setup-filter-hook nil
10579 "Hook for functions that pre-filter todo specs.
10581 Each function takes a todo spec and returns either `nil' or the spec
10582 transformed into canonical form." )
10584 (defvar org-todo-get-default-hook nil
10585 "Hook for functions that get a default item for todo.
10587 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10588 `nil' or a string to be used for the todo mark." )
10590 (defvar org-agenda-headline-snapshot-before-repeat)
10592 (defun org-todo (&optional arg)
10593 "Change the TODO state of an item.
10594 The state of an item is given by a keyword at the start of the heading,
10595 like
10596 *** TODO Write paper
10597 *** DONE Call mom
10599 The different keywords are specified in the variable `org-todo-keywords'.
10600 By default the available states are \"TODO\" and \"DONE\".
10601 So for this example: when the item starts with TODO, it is changed to DONE.
10602 When it starts with DONE, the DONE is removed. And when neither TODO nor
10603 DONE are present, add TODO at the beginning of the heading.
10605 With C-u prefix arg, use completion to determine the new state.
10606 With numeric prefix arg, switch to that state.
10607 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10608 With a triple C-u prefix, circumvent any state blocking.
10610 For calling through lisp, arg is also interpreted in the following way:
10611 'none -> empty state
10612 \"\"(empty string) -> switch to empty state
10613 'done -> switch to DONE
10614 'nextset -> switch to the next set of keywords
10615 'previousset -> switch to the previous set of keywords
10616 \"WAITING\" -> switch to the specified keyword, but only if it
10617 really is a member of `org-todo-keywords'."
10618 (interactive "P")
10619 (if (equal arg '(16)) (setq arg 'nextset))
10620 (let ((org-blocker-hook org-blocker-hook)
10621 (case-fold-search nil))
10622 (when (equal arg '(64))
10623 (setq arg nil org-blocker-hook nil))
10624 (when (and org-blocker-hook
10625 (or org-inhibit-blocking
10626 (org-entry-get nil "NOBLOCKING")))
10627 (setq org-blocker-hook nil))
10628 (save-excursion
10629 (catch 'exit
10630 (org-back-to-heading t)
10631 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10632 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10633 (looking-at " *"))
10634 (let* ((match-data (match-data))
10635 (startpos (point-at-bol))
10636 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10637 (org-log-done org-log-done)
10638 (org-log-repeat org-log-repeat)
10639 (org-todo-log-states org-todo-log-states)
10640 (this (match-string 1))
10641 (hl-pos (match-beginning 0))
10642 (head (org-get-todo-sequence-head this))
10643 (ass (assoc head org-todo-kwd-alist))
10644 (interpret (nth 1 ass))
10645 (done-word (nth 3 ass))
10646 (final-done-word (nth 4 ass))
10647 (last-state (or this ""))
10648 (completion-ignore-case t)
10649 (member (member this org-todo-keywords-1))
10650 (tail (cdr member))
10651 (state (cond
10652 ((and org-todo-key-trigger
10653 (or (and (equal arg '(4))
10654 (eq org-use-fast-todo-selection 'prefix))
10655 (and (not arg) org-use-fast-todo-selection
10656 (not (eq org-use-fast-todo-selection
10657 'prefix)))))
10658 ;; Use fast selection
10659 (org-fast-todo-selection))
10660 ((and (equal arg '(4))
10661 (or (not org-use-fast-todo-selection)
10662 (not org-todo-key-trigger)))
10663 ;; Read a state with completion
10664 (org-icompleting-read
10665 "State: " (mapcar (lambda(x) (list x))
10666 org-todo-keywords-1)
10667 nil t))
10668 ((eq arg 'right)
10669 (if this
10670 (if tail (car tail) nil)
10671 (car org-todo-keywords-1)))
10672 ((eq arg 'left)
10673 (if (equal member org-todo-keywords-1)
10675 (if this
10676 (nth (- (length org-todo-keywords-1)
10677 (length tail) 2)
10678 org-todo-keywords-1)
10679 (org-last org-todo-keywords-1))))
10680 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10681 (setq arg nil))) ; hack to fall back to cycling
10682 (arg
10683 ;; user or caller requests a specific state
10684 (cond
10685 ((equal arg "") nil)
10686 ((eq arg 'none) nil)
10687 ((eq arg 'done) (or done-word (car org-done-keywords)))
10688 ((eq arg 'nextset)
10689 (or (car (cdr (member head org-todo-heads)))
10690 (car org-todo-heads)))
10691 ((eq arg 'previousset)
10692 (let ((org-todo-heads (reverse org-todo-heads)))
10693 (or (car (cdr (member head org-todo-heads)))
10694 (car org-todo-heads))))
10695 ((car (member arg org-todo-keywords-1)))
10696 ((stringp arg)
10697 (error "State `%s' not valid in this file" arg))
10698 ((nth (1- (prefix-numeric-value arg))
10699 org-todo-keywords-1))))
10700 ((null member) (or head (car org-todo-keywords-1)))
10701 ((equal this final-done-word) nil) ;; -> make empty
10702 ((null tail) nil) ;; -> first entry
10703 ((memq interpret '(type priority))
10704 (if (eq this-command last-command)
10705 (car tail)
10706 (if (> (length tail) 0)
10707 (or done-word (car org-done-keywords))
10708 nil)))
10710 (car tail))))
10711 (state (or
10712 (run-hook-with-args-until-success
10713 'org-todo-get-default-hook state last-state)
10714 state))
10715 (next (if state (concat " " state " ") " "))
10716 (change-plist (list :type 'todo-state-change :from this :to state
10717 :position startpos))
10718 dolog now-done-p)
10719 (when org-blocker-hook
10720 (setq org-last-todo-state-is-todo
10721 (not (member this org-done-keywords)))
10722 (unless (save-excursion
10723 (save-match-data
10724 (run-hook-with-args-until-failure
10725 'org-blocker-hook change-plist)))
10726 (if (interactive-p)
10727 (error "TODO state change from %s to %s blocked" this state)
10728 ;; fail silently
10729 (message "TODO state change from %s to %s blocked" this state)
10730 (throw 'exit nil))))
10731 (store-match-data match-data)
10732 (replace-match next t t)
10733 (unless (pos-visible-in-window-p hl-pos)
10734 (message "TODO state changed to %s" (org-trim next)))
10735 (unless head
10736 (setq head (org-get-todo-sequence-head state)
10737 ass (assoc head org-todo-kwd-alist)
10738 interpret (nth 1 ass)
10739 done-word (nth 3 ass)
10740 final-done-word (nth 4 ass)))
10741 (when (memq arg '(nextset previousset))
10742 (message "Keyword-Set %d/%d: %s"
10743 (- (length org-todo-sets) -1
10744 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10745 (length org-todo-sets)
10746 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10747 (setq org-last-todo-state-is-todo
10748 (not (member state org-done-keywords)))
10749 (setq now-done-p (and (member state org-done-keywords)
10750 (not (member this org-done-keywords))))
10751 (and logging (org-local-logging logging))
10752 (when (and (or org-todo-log-states org-log-done)
10753 (not (eq org-inhibit-logging t))
10754 (not (memq arg '(nextset previousset))))
10755 ;; we need to look at recording a time and note
10756 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10757 (nth 2 (assoc this org-todo-log-states))))
10758 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10759 (setq dolog 'time))
10760 (when (and state
10761 (member state org-not-done-keywords)
10762 (not (member this org-not-done-keywords)))
10763 ;; This is now a todo state and was not one before
10764 ;; If there was a CLOSED time stamp, get rid of it.
10765 (org-add-planning-info nil nil 'closed))
10766 (when (and now-done-p org-log-done)
10767 ;; It is now done, and it was not done before
10768 (org-add-planning-info 'closed (org-current-time))
10769 (if (and (not dolog) (eq 'note org-log-done))
10770 (org-add-log-setup 'done state this 'findpos 'note)))
10771 (when (and state dolog)
10772 ;; This is a non-nil state, and we need to log it
10773 (org-add-log-setup 'state state this 'findpos dolog)))
10774 ;; Fixup tag positioning
10775 (org-todo-trigger-tag-changes state)
10776 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10777 (when org-provide-todo-statistics
10778 (org-update-parent-todo-statistics))
10779 (run-hooks 'org-after-todo-state-change-hook)
10780 (if (and arg (not (member state org-done-keywords)))
10781 (setq head (org-get-todo-sequence-head state)))
10782 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10783 ;; Do we need to trigger a repeat?
10784 (when now-done-p
10785 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10786 ;; This is for the agenda, take a snapshot of the headline.
10787 (save-match-data
10788 (setq org-agenda-headline-snapshot-before-repeat
10789 (org-get-heading))))
10790 (org-auto-repeat-maybe state))
10791 ;; Fixup cursor location if close to the keyword
10792 (if (and (outline-on-heading-p)
10793 (not (bolp))
10794 (save-excursion (beginning-of-line 1)
10795 (looking-at org-todo-line-regexp))
10796 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10797 (progn
10798 (goto-char (or (match-end 2) (match-end 1)))
10799 (and (looking-at " ") (just-one-space))))
10800 (when org-trigger-hook
10801 (save-excursion
10802 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10804 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10805 "Block turning an entry into a TODO, using the hierarchy.
10806 This checks whether the current task should be blocked from state
10807 changes. Such blocking occurs when:
10809 1. The task has children which are not all in a completed state.
10811 2. A task has a parent with the property :ORDERED:, and there
10812 are siblings prior to the current task with incomplete
10813 status.
10815 3. The parent of the task is blocked because it has siblings that should
10816 be done first, or is child of a block grandparent TODO entry."
10818 (if (not org-enforce-todo-dependencies)
10819 t ; if locally turned off don't block
10820 (catch 'dont-block
10821 ;; If this is not a todo state change, or if this entry is already DONE,
10822 ;; do not block
10823 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10824 (member (plist-get change-plist :from)
10825 (cons 'done org-done-keywords))
10826 (member (plist-get change-plist :to)
10827 (cons 'todo org-not-done-keywords))
10828 (not (plist-get change-plist :to)))
10829 (throw 'dont-block t))
10830 ;; If this task has children, and any are undone, it's blocked
10831 (save-excursion
10832 (org-back-to-heading t)
10833 (let ((this-level (funcall outline-level)))
10834 (outline-next-heading)
10835 (let ((child-level (funcall outline-level)))
10836 (while (and (not (eobp))
10837 (> child-level this-level))
10838 ;; this todo has children, check whether they are all
10839 ;; completed
10840 (if (and (not (org-entry-is-done-p))
10841 (org-entry-is-todo-p))
10842 (throw 'dont-block nil))
10843 (outline-next-heading)
10844 (setq child-level (funcall outline-level))))))
10845 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10846 ;; any previous siblings are undone, it's blocked
10847 (save-excursion
10848 (org-back-to-heading t)
10849 (let* ((pos (point))
10850 (parent-pos (and (org-up-heading-safe) (point))))
10851 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10852 (when (and (org-entry-get (point) "ORDERED")
10853 (forward-line 1)
10854 (re-search-forward org-not-done-heading-regexp pos t))
10855 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10856 ;; Search further up the hierarchy, to see if an anchestor is blocked
10857 (while t
10858 (goto-char parent-pos)
10859 (if (not (looking-at org-not-done-heading-regexp))
10860 (throw 'dont-block t)) ; do not block, parent is not a TODO
10861 (setq pos (point))
10862 (setq parent-pos (and (org-up-heading-safe) (point)))
10863 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10864 (when (and (org-entry-get (point) "ORDERED")
10865 (forward-line 1)
10866 (re-search-forward org-not-done-heading-regexp pos t))
10867 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10869 (defcustom org-track-ordered-property-with-tag nil
10870 "Should the ORDERED property also be shown as a tag?
10871 The ORDERED property decides if an entry should require subtasks to be
10872 completed in sequence. Since a property is not very visible, setting
10873 this option means that toggling the ORDERED property with the command
10874 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10875 not relevant for the behavior, but it makes things more visible.
10877 Note that toggling the tag with tags commands will not change the property
10878 and therefore not influence behavior!
10880 This can be t, meaning the tag ORDERED should be used, It can also be a
10881 string to select a different tag for this task."
10882 :group 'org-todo
10883 :type '(choice
10884 (const :tag "No tracking" nil)
10885 (const :tag "Track with ORDERED tag" t)
10886 (string :tag "Use other tag")))
10888 (defun org-toggle-ordered-property ()
10889 "Toggle the ORDERED property of the current entry.
10890 For better visibility, you can track the value of this property with a tag.
10891 See variable `org-track-ordered-property-with-tag'."
10892 (interactive)
10893 (let* ((t1 org-track-ordered-property-with-tag)
10894 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10895 (save-excursion
10896 (org-back-to-heading)
10897 (if (org-entry-get nil "ORDERED")
10898 (progn
10899 (org-delete-property "ORDERED")
10900 (and tag (org-toggle-tag tag 'off))
10901 (message "Subtasks can be completed in arbitrary order"))
10902 (org-entry-put nil "ORDERED" "t")
10903 (and tag (org-toggle-tag tag 'on))
10904 (message "Subtasks must be completed in sequence")))))
10906 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10907 (defun org-block-todo-from-checkboxes (change-plist)
10908 "Block turning an entry into a TODO, using checkboxes.
10909 This checks whether the current task should be blocked from state
10910 changes because there are unchecked boxes in this entry."
10911 (if (not org-enforce-todo-checkbox-dependencies)
10912 t ; if locally turned off don't block
10913 (catch 'dont-block
10914 ;; If this is not a todo state change, or if this entry is already DONE,
10915 ;; do not block
10916 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10917 (member (plist-get change-plist :from)
10918 (cons 'done org-done-keywords))
10919 (member (plist-get change-plist :to)
10920 (cons 'todo org-not-done-keywords))
10921 (not (plist-get change-plist :to)))
10922 (throw 'dont-block t))
10923 ;; If this task has checkboxes that are not checked, it's blocked
10924 (save-excursion
10925 (org-back-to-heading t)
10926 (let ((beg (point)) end)
10927 (outline-next-heading)
10928 (setq end (point))
10929 (goto-char beg)
10930 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10931 end t)
10932 (progn
10933 (if (boundp 'org-blocked-by-checkboxes)
10934 (setq org-blocked-by-checkboxes t))
10935 (throw 'dont-block nil)))))
10936 t))) ; do not block
10938 (defun org-entry-blocked-p ()
10939 "Is the current entry blocked?"
10940 (if (org-entry-get nil "NOBLOCKING")
10941 nil ;; Never block this entry
10942 (not
10943 (run-hook-with-args-until-failure
10944 'org-blocker-hook
10945 (list :type 'todo-state-change
10946 :position (point)
10947 :from 'todo
10948 :to 'done)))))
10950 (defun org-update-statistics-cookies (all)
10951 "Update the statistics cookie, either from TODO or from checkboxes.
10952 This should be called with the cursor in a line with a statistics cookie."
10953 (interactive "P")
10954 (if all
10955 (progn
10956 (org-update-checkbox-count 'all)
10957 (org-map-entries 'org-update-parent-todo-statistics))
10958 (if (not (org-on-heading-p))
10959 (org-update-checkbox-count)
10960 (let ((pos (move-marker (make-marker) (point)))
10961 end l1 l2)
10962 (ignore-errors (org-back-to-heading t))
10963 (if (not (org-on-heading-p))
10964 (org-update-checkbox-count)
10965 (setq l1 (org-outline-level))
10966 (setq end (save-excursion
10967 (outline-next-heading)
10968 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10969 (point)))
10970 (if (and (save-excursion
10971 (re-search-forward
10972 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10973 (not (save-excursion (re-search-forward
10974 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10975 (org-update-checkbox-count)
10976 (if (and l2 (> l2 l1))
10977 (progn
10978 (goto-char end)
10979 (org-update-parent-todo-statistics))
10980 (goto-char pos)
10981 (beginning-of-line 1)
10982 (while (re-search-forward
10983 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10984 (point-at-eol) t)
10985 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10986 (goto-char pos)
10987 (move-marker pos nil)))))
10989 (defvar org-entry-property-inherited-from) ;; defined below
10990 (defun org-update-parent-todo-statistics ()
10991 "Update any statistics cookie in the parent of the current headline.
10992 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10993 the entire subtree and this will travel up the hierarchy and update
10994 statistics everywhere."
10995 (interactive)
10996 (let* ((lim 0) prop
10997 (recursive (or (not org-hierarchical-todo-statistics)
10998 (string-match
10999 "\\<recursive\\>"
11000 (or (setq prop (org-entry-get
11001 nil "COOKIE_DATA" 'inherit)) ""))))
11002 (lim (or (and prop (marker-position
11003 org-entry-property-inherited-from))
11004 lim))
11005 (first t)
11006 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11007 level ltoggle l1 new ndel
11008 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11009 (catch 'exit
11010 (save-excursion
11011 (beginning-of-line 1)
11012 (if (org-at-heading-p)
11013 (setq ltoggle (funcall outline-level))
11014 (error "This should not happen"))
11015 (while (and (setq level (org-up-heading-safe))
11016 (or recursive first)
11017 (>= (point) lim))
11018 (setq first nil cookie-present nil)
11019 (unless (and level
11020 (not (string-match
11021 "\\<checkbox\\>"
11022 (downcase
11023 (or (org-entry-get
11024 nil "COOKIE_DATA")
11025 "")))))
11026 (throw 'exit nil))
11027 (while (re-search-forward box-re (point-at-eol) t)
11028 (setq cnt-all 0 cnt-done 0 cookie-present t)
11029 (setq is-percent (match-end 2))
11030 (save-match-data
11031 (unless (outline-next-heading) (throw 'exit nil))
11032 (while (and (looking-at org-complex-heading-regexp)
11033 (> (setq l1 (length (match-string 1))) level))
11034 (setq kwd (and (or recursive (= l1 ltoggle))
11035 (match-string 2)))
11036 (if (or (eq org-provide-todo-statistics 'all-headlines)
11037 (and (listp org-provide-todo-statistics)
11038 (or (member kwd org-provide-todo-statistics)
11039 (member kwd org-done-keywords))))
11040 (setq cnt-all (1+ cnt-all))
11041 (if (eq org-provide-todo-statistics t)
11042 (and kwd (setq cnt-all (1+ cnt-all)))))
11043 (and (member kwd org-done-keywords)
11044 (setq cnt-done (1+ cnt-done)))
11045 (outline-next-heading)))
11046 (setq new
11047 (if is-percent
11048 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11049 (format "[%d/%d]" cnt-done cnt-all))
11050 ndel (- (match-end 0) (match-beginning 0)))
11051 (goto-char (match-beginning 0))
11052 (insert new)
11053 (delete-region (point) (+ (point) ndel)))
11054 (when cookie-present
11055 (run-hook-with-args 'org-after-todo-statistics-hook
11056 cnt-done (- cnt-all cnt-done))))))
11057 (run-hooks 'org-todo-statistics-hook)))
11059 (defvar org-after-todo-statistics-hook nil
11060 "Hook that is called after a TODO statistics cookie has been updated.
11061 Each function is called with two arguments: the number of not-done entries
11062 and the number of done entries.
11064 For example, the following function, when added to this hook, will switch
11065 an entry to DONE when all children are done, and back to TODO when new
11066 entries are set to a TODO status. Note that this hook is only called
11067 when there is a statistics cookie in the headline!
11069 (defun org-summary-todo (n-done n-not-done)
11070 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11071 (let (org-log-done org-log-states) ; turn off logging
11072 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11075 (defvar org-todo-statistics-hook nil
11076 "Hook that is run whenever Org thinks TODO statistics should be updated.
11077 This hook runs even if there is no statistics cookie present, in which case
11078 `org-after-todo-statistics-hook' would not run.")
11080 (defun org-todo-trigger-tag-changes (state)
11081 "Apply the changes defined in `org-todo-state-tags-triggers'."
11082 (let ((l org-todo-state-tags-triggers)
11083 changes)
11084 (when (or (not state) (equal state ""))
11085 (setq changes (append changes (cdr (assoc "" l)))))
11086 (when (and (stringp state) (> (length state) 0))
11087 (setq changes (append changes (cdr (assoc state l)))))
11088 (when (member state org-not-done-keywords)
11089 (setq changes (append changes (cdr (assoc 'todo l)))))
11090 (when (member state org-done-keywords)
11091 (setq changes (append changes (cdr (assoc 'done l)))))
11092 (dolist (c changes)
11093 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11095 (defun org-local-logging (value)
11096 "Get logging settings from a property VALUE."
11097 (let* (words w a)
11098 ;; directly set the variables, they are already local.
11099 (setq org-log-done nil
11100 org-log-repeat nil
11101 org-todo-log-states nil)
11102 (setq words (org-split-string value))
11103 (while (setq w (pop words))
11104 (cond
11105 ((setq a (assoc w org-startup-options))
11106 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11107 (set (nth 1 a) (nth 2 a))))
11108 ((setq a (org-extract-log-state-settings w))
11109 (and (member (car a) org-todo-keywords-1)
11110 (push a org-todo-log-states)))))))
11112 (defun org-get-todo-sequence-head (kwd)
11113 "Return the head of the TODO sequence to which KWD belongs.
11114 If KWD is not set, check if there is a text property remembering the
11115 right sequence."
11116 (let (p)
11117 (cond
11118 ((not kwd)
11119 (or (get-text-property (point-at-bol) 'org-todo-head)
11120 (progn
11121 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11122 nil (point-at-eol)))
11123 (get-text-property p 'org-todo-head))))
11124 ((not (member kwd org-todo-keywords-1))
11125 (car org-todo-keywords-1))
11126 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11128 (defun org-fast-todo-selection ()
11129 "Fast TODO keyword selection with single keys.
11130 Returns the new TODO keyword, or nil if no state change should occur."
11131 (let* ((fulltable org-todo-key-alist)
11132 (done-keywords org-done-keywords) ;; needed for the faces.
11133 (maxlen (apply 'max (mapcar
11134 (lambda (x)
11135 (if (stringp (car x)) (string-width (car x)) 0))
11136 fulltable)))
11137 (expert nil)
11138 (fwidth (+ maxlen 3 1 3))
11139 (ncol (/ (- (window-width) 4) fwidth))
11140 tg cnt e c tbl
11141 groups ingroup)
11142 (save-excursion
11143 (save-window-excursion
11144 (if expert
11145 (set-buffer (get-buffer-create " *Org todo*"))
11146 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11147 (erase-buffer)
11148 (org-set-local 'org-done-keywords done-keywords)
11149 (setq tbl fulltable cnt 0)
11150 (while (setq e (pop tbl))
11151 (cond
11152 ((equal e '(:startgroup))
11153 (push '() groups) (setq ingroup t)
11154 (when (not (= cnt 0))
11155 (setq cnt 0)
11156 (insert "\n"))
11157 (insert "{ "))
11158 ((equal e '(:endgroup))
11159 (setq ingroup nil cnt 0)
11160 (insert "}\n"))
11161 ((equal e '(:newline))
11162 (when (not (= cnt 0))
11163 (setq cnt 0)
11164 (insert "\n")
11165 (setq e (car tbl))
11166 (while (equal (car tbl) '(:newline))
11167 (insert "\n")
11168 (setq tbl (cdr tbl)))))
11170 (setq tg (car e) c (cdr e))
11171 (if ingroup (push tg (car groups)))
11172 (setq tg (org-add-props tg nil 'face
11173 (org-get-todo-face tg)))
11174 (if (and (= cnt 0) (not ingroup)) (insert " "))
11175 (insert "[" c "] " tg (make-string
11176 (- fwidth 4 (length tg)) ?\ ))
11177 (when (= (setq cnt (1+ cnt)) ncol)
11178 (insert "\n")
11179 (if ingroup (insert " "))
11180 (setq cnt 0)))))
11181 (insert "\n")
11182 (goto-char (point-min))
11183 (if (not expert) (org-fit-window-to-buffer))
11184 (message "[a-z..]:Set [SPC]:clear")
11185 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11186 (cond
11187 ((or (= c ?\C-g)
11188 (and (= c ?q) (not (rassoc c fulltable))))
11189 (setq quit-flag t))
11190 ((= c ?\ ) nil)
11191 ((setq e (rassoc c fulltable) tg (car e))
11193 (t (setq quit-flag t)))))))
11195 (defun org-entry-is-todo-p ()
11196 (member (org-get-todo-state) org-not-done-keywords))
11198 (defun org-entry-is-done-p ()
11199 (member (org-get-todo-state) org-done-keywords))
11201 (defun org-get-todo-state ()
11202 (save-excursion
11203 (org-back-to-heading t)
11204 (and (looking-at org-todo-line-regexp)
11205 (match-end 2)
11206 (match-string 2))))
11208 (defun org-at-date-range-p (&optional inactive-ok)
11209 "Is the cursor inside a date range?"
11210 (interactive)
11211 (save-excursion
11212 (catch 'exit
11213 (let ((pos (point)))
11214 (skip-chars-backward "^[<\r\n")
11215 (skip-chars-backward "<[")
11216 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11217 (>= (match-end 0) pos)
11218 (throw 'exit t))
11219 (skip-chars-backward "^<[\r\n")
11220 (skip-chars-backward "<[")
11221 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11222 (>= (match-end 0) pos)
11223 (throw 'exit t)))
11224 nil)))
11226 (defun org-get-repeat (&optional tagline)
11227 "Check if there is a deadline/schedule with repeater in this entry."
11228 (save-match-data
11229 (save-excursion
11230 (org-back-to-heading t)
11231 (and (re-search-forward (if tagline
11232 (concat tagline "\\s-*" org-repeat-re)
11233 org-repeat-re)
11234 (org-entry-end-position) t)
11235 (match-string-no-properties 1)))))
11237 (defvar org-last-changed-timestamp)
11238 (defvar org-last-inserted-timestamp)
11239 (defvar org-log-post-message)
11240 (defvar org-log-note-purpose)
11241 (defvar org-log-note-how)
11242 (defvar org-log-note-extra)
11243 (defun org-auto-repeat-maybe (done-word)
11244 "Check if the current headline contains a repeated deadline/schedule.
11245 If yes, set TODO state back to what it was and change the base date
11246 of repeating deadline/scheduled time stamps to new date.
11247 This function is run automatically after each state change to a DONE state."
11248 ;; last-state is dynamically scoped into this function
11249 (let* ((repeat (org-get-repeat))
11250 (aa (assoc last-state org-todo-kwd-alist))
11251 (interpret (nth 1 aa))
11252 (head (nth 2 aa))
11253 (whata '(("d" . day) ("m" . month) ("y" . year)))
11254 (msg "Entry repeats: ")
11255 (org-log-done nil)
11256 (org-todo-log-states nil)
11257 (nshiftmax 10) (nshift 0)
11258 re type n what ts time to-state)
11259 (when repeat
11260 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11261 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11262 org-todo-repeat-to-state))
11263 (unless (and to-state (member to-state org-todo-keywords-1))
11264 (setq to-state (if (eq interpret 'type) last-state head)))
11265 (org-todo to-state)
11266 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11267 (org-entry-put nil "LAST_REPEAT" (format-time-string
11268 (org-time-stamp-format t t))))
11269 (when org-log-repeat
11270 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11271 (memq 'org-add-log-note post-command-hook))
11272 ;; OK, we are already setup for some record
11273 (if (eq org-log-repeat 'note)
11274 ;; make sure we take a note, not only a time stamp
11275 (setq org-log-note-how 'note))
11276 ;; Set up for taking a record
11277 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11278 last-state
11279 'findpos org-log-repeat)))
11280 (org-back-to-heading t)
11281 (org-add-planning-info nil nil 'closed)
11282 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11283 org-deadline-time-regexp "\\)\\|\\("
11284 org-ts-regexp "\\)"))
11285 (while (re-search-forward
11286 re (save-excursion (outline-next-heading) (point)) t)
11287 (setq type (if (match-end 1) org-scheduled-string
11288 (if (match-end 3) org-deadline-string "Plain:"))
11289 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11290 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11291 (setq n (string-to-number (match-string 2 ts))
11292 what (match-string 3 ts))
11293 (if (equal what "w") (setq n (* n 7) what "d"))
11294 ;; Preparation, see if we need to modify the start date for the change
11295 (when (match-end 1)
11296 (setq time (save-match-data (org-time-string-to-time ts)))
11297 (cond
11298 ((equal (match-string 1 ts) ".")
11299 ;; Shift starting date to today
11300 (org-timestamp-change
11301 (- (time-to-days (current-time)) (time-to-days time))
11302 'day))
11303 ((equal (match-string 1 ts) "+")
11304 (while (or (= nshift 0)
11305 (<= (time-to-days time) (time-to-days (current-time))))
11306 (when (= (incf nshift) nshiftmax)
11307 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11308 (error "Abort")))
11309 (org-timestamp-change n (cdr (assoc what whata)))
11310 (org-at-timestamp-p t)
11311 (setq ts (match-string 1))
11312 (setq time (save-match-data (org-time-string-to-time ts))))
11313 (org-timestamp-change (- n) (cdr (assoc what whata)))
11314 ;; rematch, so that we have everything in place for the real shift
11315 (org-at-timestamp-p t)
11316 (setq ts (match-string 1))
11317 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11318 (org-timestamp-change n (cdr (assoc what whata)))
11319 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11320 (setq org-log-post-message msg)
11321 (message "%s" msg))))
11323 (defun org-show-todo-tree (arg)
11324 "Make a compact tree which shows all headlines marked with TODO.
11325 The tree will show the lines where the regexp matches, and all higher
11326 headlines above the match.
11327 With a \\[universal-argument] prefix, prompt for a regexp to match.
11328 With a numeric prefix N, construct a sparse tree for the Nth element
11329 of `org-todo-keywords-1'."
11330 (interactive "P")
11331 (let ((case-fold-search nil)
11332 (kwd-re
11333 (cond ((null arg) org-not-done-regexp)
11334 ((equal arg '(4))
11335 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11336 (mapcar 'list org-todo-keywords-1))))
11337 (concat "\\("
11338 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11339 "\\)\\>")))
11340 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11341 (regexp-quote (nth (1- (prefix-numeric-value arg))
11342 org-todo-keywords-1)))
11343 (t (error "Invalid prefix argument: %s" arg)))))
11344 (message "%d TODO entries found"
11345 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11347 (defun org-deadline (&optional remove time)
11348 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11349 With argument REMOVE, remove any deadline from the item.
11350 When TIME is set, it should be an internal time specification, and the
11351 scheduling will use the corresponding date."
11352 (interactive "P")
11353 (let* ((old-date (org-entry-get nil "DEADLINE"))
11354 (repeater (and old-date
11355 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11356 (match-string 1 old-date))))
11357 (if remove
11358 (progn
11359 (when (and old-date org-log-redeadline)
11360 (org-add-log-setup 'deldeadline nil old-date 'findpos
11361 org-log-redeadline))
11362 (org-remove-timestamp-with-keyword org-deadline-string)
11363 (message "Item no longer has a deadline."))
11364 (org-add-planning-info 'deadline time 'closed)
11365 (when (and old-date org-log-redeadline
11366 (not (equal old-date
11367 (substring org-last-inserted-timestamp 1 -1))))
11368 (org-add-log-setup 'redeadline nil old-date 'findpos
11369 org-log-redeadline))
11370 (when repeater
11371 (save-excursion
11372 (org-back-to-heading t)
11373 (when (re-search-forward (concat org-deadline-string " "
11374 org-last-inserted-timestamp)
11375 (save-excursion
11376 (outline-next-heading) (point)) t)
11377 (goto-char (1- (match-end 0)))
11378 (insert " " repeater)
11379 (setq org-last-inserted-timestamp
11380 (concat (substring org-last-inserted-timestamp 0 -1)
11381 " " repeater
11382 (substring org-last-inserted-timestamp -1))))))
11383 (message "Deadline on %s" org-last-inserted-timestamp))))
11385 (defun org-schedule (&optional remove time)
11386 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11387 With argument REMOVE, remove any scheduling date from the item.
11388 When TIME is set, it should be an internal time specification, and the
11389 scheduling will use the corresponding date."
11390 (interactive "P")
11391 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11392 (repeater (and old-date
11393 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11394 (match-string 1 old-date))))
11395 (if remove
11396 (progn
11397 (when (and old-date org-log-reschedule)
11398 (org-add-log-setup 'delschedule nil old-date 'findpos
11399 org-log-reschedule))
11400 (org-remove-timestamp-with-keyword org-scheduled-string)
11401 (message "Item is no longer scheduled."))
11402 (org-add-planning-info 'scheduled time 'closed)
11403 (when (and old-date org-log-reschedule
11404 (not (equal old-date
11405 (substring org-last-inserted-timestamp 1 -1))))
11406 (org-add-log-setup 'reschedule nil old-date 'findpos
11407 org-log-reschedule))
11408 (when repeater
11409 (save-excursion
11410 (org-back-to-heading t)
11411 (when (re-search-forward (concat org-scheduled-string " "
11412 org-last-inserted-timestamp)
11413 (save-excursion
11414 (outline-next-heading) (point)) t)
11415 (goto-char (1- (match-end 0)))
11416 (insert " " repeater)
11417 (setq org-last-inserted-timestamp
11418 (concat (substring org-last-inserted-timestamp 0 -1)
11419 " " repeater
11420 (substring org-last-inserted-timestamp -1))))))
11421 (message "Scheduled to %s" org-last-inserted-timestamp))))
11423 (defun org-get-scheduled-time (pom &optional inherit)
11424 "Get the scheduled time as a time tuple, of a format suitable
11425 for calling org-schedule with, or if there is no scheduling,
11426 returns nil."
11427 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11428 (when time
11429 (apply 'encode-time (org-parse-time-string time)))))
11431 (defun org-get-deadline-time (pom &optional inherit)
11432 "Get the deadine as a time tuple, of a format suitable for
11433 calling org-deadline with, or if there is no scheduling, returns
11434 nil."
11435 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11436 (when time
11437 (apply 'encode-time (org-parse-time-string time)))))
11439 (defun org-remove-timestamp-with-keyword (keyword)
11440 "Remove all time stamps with KEYWORD in the current entry."
11441 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11442 beg)
11443 (save-excursion
11444 (org-back-to-heading t)
11445 (setq beg (point))
11446 (outline-next-heading)
11447 (while (re-search-backward re beg t)
11448 (replace-match "")
11449 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11450 (equal (char-before) ?\ ))
11451 (backward-delete-char 1)
11452 (if (string-match "^[ \t]*$" (buffer-substring
11453 (point-at-bol) (point-at-eol)))
11454 (delete-region (point-at-bol)
11455 (min (point-max) (1+ (point-at-eol))))))))))
11457 (defun org-add-planning-info (what &optional time &rest remove)
11458 "Insert new timestamp with keyword in the line directly after the headline.
11459 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11460 If non is given, the user is prompted for a date.
11461 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11462 be removed."
11463 (interactive)
11464 (let (org-time-was-given org-end-time-was-given ts
11465 end default-time default-input)
11467 (catch 'exit
11468 (when (and (not time) (memq what '(scheduled deadline)))
11469 ;; Try to get a default date/time from existing timestamp
11470 (save-excursion
11471 (org-back-to-heading t)
11472 (setq end (save-excursion (outline-next-heading) (point)))
11473 (when (re-search-forward (if (eq what 'scheduled)
11474 org-scheduled-time-regexp
11475 org-deadline-time-regexp)
11476 end t)
11477 (setq ts (match-string 1)
11478 default-time
11479 (apply 'encode-time (org-parse-time-string ts))
11480 default-input (and ts (org-get-compact-tod ts))))))
11481 (when what
11482 ;; If necessary, get the time from the user
11483 (setq time (or time (org-read-date nil 'to-time nil nil
11484 default-time default-input))))
11486 (when (and org-insert-labeled-timestamps-at-point
11487 (member what '(scheduled deadline)))
11488 (insert
11489 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11490 (org-insert-time-stamp time org-time-was-given
11491 nil nil nil (list org-end-time-was-given))
11492 (setq what nil))
11493 (save-excursion
11494 (save-restriction
11495 (let (col list elt ts buffer-invisibility-spec)
11496 (org-back-to-heading t)
11497 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11498 (goto-char (match-end 1))
11499 (setq col (current-column))
11500 (goto-char (match-end 0))
11501 (if (eobp) (insert "\n") (forward-char 1))
11502 (when (and (not what)
11503 (not (looking-at
11504 (concat "[ \t]*"
11505 org-keyword-time-not-clock-regexp))))
11506 ;; Nothing to add, nothing to remove...... :-)
11507 (throw 'exit nil))
11508 (if (and (not (looking-at outline-regexp))
11509 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11510 "[^\r\n]*"))
11511 (not (equal (match-string 1) org-clock-string)))
11512 (narrow-to-region (match-beginning 0) (match-end 0))
11513 (insert-before-markers "\n")
11514 (backward-char 1)
11515 (narrow-to-region (point) (point))
11516 (and org-adapt-indentation (org-indent-to-column col)))
11517 ;; Check if we have to remove something.
11518 (setq list (cons what remove))
11519 (while list
11520 (setq elt (pop list))
11521 (goto-char (point-min))
11522 (when (or (and (eq elt 'scheduled)
11523 (re-search-forward org-scheduled-time-regexp nil t))
11524 (and (eq elt 'deadline)
11525 (re-search-forward org-deadline-time-regexp nil t))
11526 (and (eq elt 'closed)
11527 (re-search-forward org-closed-time-regexp nil t)))
11528 (replace-match "")
11529 (if (looking-at "--+<[^>]+>") (replace-match ""))
11530 (skip-chars-backward " ")
11531 (if (looking-at " +") (replace-match ""))))
11532 (goto-char (point-max))
11533 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11534 (when what
11535 (insert
11536 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11537 (cond ((eq what 'scheduled) org-scheduled-string)
11538 ((eq what 'deadline) org-deadline-string)
11539 ((eq what 'closed) org-closed-string))
11540 " ")
11541 (setq ts (org-insert-time-stamp
11542 time
11543 (or org-time-was-given
11544 (and (eq what 'closed) org-log-done-with-time))
11545 (eq what 'closed)
11546 nil nil (list org-end-time-was-given)))
11547 (end-of-line 1))
11548 (goto-char (point-min))
11549 (widen)
11550 (if (and (looking-at "[ \t]*\n")
11551 (equal (char-before) ?\n))
11552 (delete-region (1- (point)) (point-at-eol)))
11553 ts))))))
11555 (defvar org-log-note-marker (make-marker))
11556 (defvar org-log-note-purpose nil)
11557 (defvar org-log-note-state nil)
11558 (defvar org-log-note-previous-state nil)
11559 (defvar org-log-note-how nil)
11560 (defvar org-log-note-extra nil)
11561 (defvar org-log-note-window-configuration nil)
11562 (defvar org-log-note-return-to (make-marker))
11563 (defvar org-log-post-message nil
11564 "Message to be displayed after a log note has been stored.
11565 The auto-repeater uses this.")
11567 (defun org-add-note ()
11568 "Add a note to the current entry.
11569 This is done in the same way as adding a state change note."
11570 (interactive)
11571 (org-add-log-setup 'note nil nil 'findpos nil))
11573 (defvar org-property-end-re)
11574 (defun org-add-log-setup (&optional purpose state prev-state
11575 findpos how &optional extra)
11576 "Set up the post command hook to take a note.
11577 If this is about to TODO state change, the new state is expected in STATE.
11578 When FINDPOS is non-nil, find the correct position for the note in
11579 the current entry. If not, assume that it can be inserted at point.
11580 HOW is an indicator what kind of note should be created.
11581 EXTRA is additional text that will be inserted into the notes buffer."
11582 (let* ((org-log-into-drawer (org-log-into-drawer))
11583 (drawer (cond ((stringp org-log-into-drawer)
11584 org-log-into-drawer)
11585 (org-log-into-drawer "LOGBOOK")
11586 (t nil))))
11587 (save-restriction
11588 (save-excursion
11589 (when findpos
11590 (org-back-to-heading t)
11591 (narrow-to-region (point) (save-excursion
11592 (outline-next-heading) (point)))
11593 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11594 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11595 "[^\r\n]*\\)?"))
11596 (goto-char (match-end 0))
11597 (cond
11598 (drawer
11599 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11600 nil t)
11601 (progn
11602 (goto-char (match-end 0))
11603 (or org-log-states-order-reversed
11604 (and (re-search-forward org-property-end-re nil t)
11605 (goto-char (1- (match-beginning 0))))))
11606 (insert "\n:" drawer ":\n:END:")
11607 (beginning-of-line 0)
11608 (org-indent-line-function)
11609 (beginning-of-line 2)
11610 (org-indent-line-function)
11611 (end-of-line 0)))
11612 ((and org-log-state-notes-insert-after-drawers
11613 (save-excursion
11614 (forward-line) (looking-at org-drawer-regexp)))
11615 (forward-line)
11616 (while (looking-at org-drawer-regexp)
11617 (goto-char (match-end 0))
11618 (re-search-forward org-property-end-re (point-max) t)
11619 (forward-line))
11620 (forward-line -1)))
11621 (unless org-log-states-order-reversed
11622 (and (= (char-after) ?\n) (forward-char 1))
11623 (org-skip-over-state-notes)
11624 (skip-chars-backward " \t\n\r")))
11625 (move-marker org-log-note-marker (point))
11626 (setq org-log-note-purpose purpose
11627 org-log-note-state state
11628 org-log-note-previous-state prev-state
11629 org-log-note-how how
11630 org-log-note-extra extra)
11631 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11633 (defun org-skip-over-state-notes ()
11634 "Skip past the list of State notes in an entry."
11635 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11636 (while (looking-at "[ \t]*- State")
11637 (condition-case nil
11638 (org-next-item)
11639 (error (org-end-of-item)))))
11641 (defun org-add-log-note (&optional purpose)
11642 "Pop up a window for taking a note, and add this note later at point."
11643 (remove-hook 'post-command-hook 'org-add-log-note)
11644 (setq org-log-note-window-configuration (current-window-configuration))
11645 (delete-other-windows)
11646 (move-marker org-log-note-return-to (point))
11647 (switch-to-buffer (marker-buffer org-log-note-marker))
11648 (goto-char org-log-note-marker)
11649 (org-switch-to-buffer-other-window "*Org Note*")
11650 (erase-buffer)
11651 (if (memq org-log-note-how '(time state))
11652 (let (current-prefix-arg) (org-store-log-note))
11653 (let ((org-inhibit-startup t)) (org-mode))
11654 (insert (format "# Insert note for %s.
11655 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11656 (cond
11657 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11658 ((eq org-log-note-purpose 'done) "closed todo item")
11659 ((eq org-log-note-purpose 'state)
11660 (format "state change from \"%s\" to \"%s\""
11661 (or org-log-note-previous-state "")
11662 (or org-log-note-state "")))
11663 ((eq org-log-note-purpose 'reschedule)
11664 "rescheduling")
11665 ((eq org-log-note-purpose 'delschedule)
11666 "no longer scheduled")
11667 ((eq org-log-note-purpose 'redeadline)
11668 "changing deadline")
11669 ((eq org-log-note-purpose 'deldeadline)
11670 "removing deadline")
11671 ((eq org-log-note-purpose 'refile)
11672 "refiling")
11673 ((eq org-log-note-purpose 'note)
11674 "this entry")
11675 (t (error "This should not happen")))))
11676 (if org-log-note-extra (insert org-log-note-extra))
11677 (org-set-local 'org-finish-function 'org-store-log-note)))
11679 (defvar org-note-abort nil) ; dynamically scoped
11680 (defun org-store-log-note ()
11681 "Finish taking a log note, and insert it to where it belongs."
11682 (let ((txt (buffer-string))
11683 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11684 lines ind)
11685 (kill-buffer (current-buffer))
11686 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11687 (setq txt (replace-match "" t t txt)))
11688 (if (string-match "\\s-+\\'" txt)
11689 (setq txt (replace-match "" t t txt)))
11690 (setq lines (org-split-string txt "\n"))
11691 (when (and note (string-match "\\S-" note))
11692 (setq note
11693 (org-replace-escapes
11694 note
11695 (list (cons "%u" (user-login-name))
11696 (cons "%U" user-full-name)
11697 (cons "%t" (format-time-string
11698 (org-time-stamp-format 'long 'inactive)
11699 (current-time)))
11700 (cons "%T" (format-time-string
11701 (org-time-stamp-format 'long nil)
11702 (current-time)))
11703 (cons "%s" (if org-log-note-state
11704 (concat "\"" org-log-note-state "\"")
11705 ""))
11706 (cons "%S" (if org-log-note-previous-state
11707 (concat "\"" org-log-note-previous-state "\"")
11708 "\"\"")))))
11709 (if lines (setq note (concat note " \\\\")))
11710 (push note lines))
11711 (when (or current-prefix-arg org-note-abort)
11712 (when org-log-into-drawer
11713 (org-remove-empty-drawer-at
11714 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11715 org-log-note-marker))
11716 (setq lines nil))
11717 (when lines
11718 (with-current-buffer (marker-buffer org-log-note-marker)
11719 (save-excursion
11720 (goto-char org-log-note-marker)
11721 (move-marker org-log-note-marker nil)
11722 (end-of-line 1)
11723 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11724 (insert "- " (pop lines))
11725 (org-indent-line-function)
11726 (beginning-of-line 1)
11727 (looking-at "[ \t]*")
11728 (setq ind (concat (match-string 0) " "))
11729 (end-of-line 1)
11730 (while lines (insert "\n" ind (pop lines)))
11731 (message "Note stored")
11732 (org-back-to-heading t)
11733 (org-cycle-hide-drawers 'children)))))
11734 (set-window-configuration org-log-note-window-configuration)
11735 (with-current-buffer (marker-buffer org-log-note-return-to)
11736 (goto-char org-log-note-return-to))
11737 (move-marker org-log-note-return-to nil)
11738 (and org-log-post-message (message "%s" org-log-post-message)))
11740 (defun org-remove-empty-drawer-at (drawer pos)
11741 "Remove an empty drawer DRAWER at position POS.
11742 POS may also be a marker."
11743 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11744 (save-excursion
11745 (save-restriction
11746 (widen)
11747 (goto-char pos)
11748 (if (org-in-regexp
11749 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11750 (replace-match ""))))))
11752 (defun org-sparse-tree (&optional arg)
11753 "Create a sparse tree, prompt for the details.
11754 This command can create sparse trees. You first need to select the type
11755 of match used to create the tree:
11757 t Show all TODO entries.
11758 T Show entries with a specific TODO keyword.
11759 m Show entries selected by a tags/property match.
11760 p Enter a property name and its value (both with completion on existing
11761 names/values) and show entries with that property.
11762 / Show entries matching a regular expression (`r' can be used as well)
11763 d Show deadlines due within `org-deadline-warning-days'.
11764 b Show deadlines and scheduled items before a date.
11765 a Show deadlines and scheduled items after a date."
11766 (interactive "P")
11767 (let (ans kwd value)
11768 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11769 (setq ans (read-char-exclusive))
11770 (cond
11771 ((equal ans ?d)
11772 (call-interactively 'org-check-deadlines))
11773 ((equal ans ?b)
11774 (call-interactively 'org-check-before-date))
11775 ((equal ans ?a)
11776 (call-interactively 'org-check-after-date))
11777 ((equal ans ?t)
11778 (org-show-todo-tree nil))
11779 ((equal ans ?T)
11780 (org-show-todo-tree '(4)))
11781 ((member ans '(?T ?m))
11782 (call-interactively 'org-match-sparse-tree))
11783 ((member ans '(?p ?P))
11784 (setq kwd (org-icompleting-read "Property: "
11785 (mapcar 'list (org-buffer-property-keys))))
11786 (setq value (org-icompleting-read "Value: "
11787 (mapcar 'list (org-property-values kwd))))
11788 (unless (string-match "\\`{.*}\\'" value)
11789 (setq value (concat "\"" value "\"")))
11790 (org-match-sparse-tree arg (concat kwd "=" value)))
11791 ((member ans '(?r ?R ?/))
11792 (call-interactively 'org-occur))
11793 (t (error "No such sparse tree command \"%c\"" ans)))))
11795 (defvar org-occur-highlights nil
11796 "List of overlays used for occur matches.")
11797 (make-variable-buffer-local 'org-occur-highlights)
11798 (defvar org-occur-parameters nil
11799 "Parameters of the active org-occur calls.
11800 This is a list, each call to org-occur pushes as cons cell,
11801 containing the regular expression and the callback, onto the list.
11802 The list can contain several entries if `org-occur' has been called
11803 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11804 will only contain one set of parameters. When the highlights are
11805 removed (for example with `C-c C-c', or with the next edit (depending
11806 on `org-remove-highlights-with-change'), this variable is emptied
11807 as well.")
11808 (make-variable-buffer-local 'org-occur-parameters)
11810 (defun org-occur (regexp &optional keep-previous callback)
11811 "Make a compact tree which shows all matches of REGEXP.
11812 The tree will show the lines where the regexp matches, and all higher
11813 headlines above the match. It will also show the heading after the match,
11814 to make sure editing the matching entry is easy.
11815 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11816 call to `org-occur' will be kept, to allow stacking of calls to this
11817 command.
11818 If CALLBACK is non-nil, it is a function which is called to confirm
11819 that the match should indeed be shown."
11820 (interactive "sRegexp: \nP")
11821 (when (equal regexp "")
11822 (error "Regexp cannot be empty"))
11823 (unless keep-previous
11824 (org-remove-occur-highlights nil nil t))
11825 (push (cons regexp callback) org-occur-parameters)
11826 (let ((cnt 0))
11827 (save-excursion
11828 (goto-char (point-min))
11829 (if (or (not keep-previous) ; do not want to keep
11830 (not org-occur-highlights)) ; no previous matches
11831 ;; hide everything
11832 (org-overview))
11833 (while (re-search-forward regexp nil t)
11834 (when (or (not callback)
11835 (save-match-data (funcall callback)))
11836 (setq cnt (1+ cnt))
11837 (when org-highlight-sparse-tree-matches
11838 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11839 (org-show-context 'occur-tree))))
11840 (when org-remove-highlights-with-change
11841 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11842 nil 'local))
11843 (unless org-sparse-tree-open-archived-trees
11844 (org-hide-archived-subtrees (point-min) (point-max)))
11845 (run-hooks 'org-occur-hook)
11846 (if (interactive-p)
11847 (message "%d match(es) for regexp %s" cnt regexp))
11848 cnt))
11850 (defun org-show-context (&optional key)
11851 "Make sure point and context are visible.
11852 How much context is shown depends upon the variables
11853 `org-show-hierarchy-above', `org-show-following-heading'. and
11854 `org-show-siblings'."
11855 (let ((heading-p (org-on-heading-p t))
11856 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11857 (following-p (org-get-alist-option org-show-following-heading key))
11858 (entry-p (org-get-alist-option org-show-entry-below key))
11859 (siblings-p (org-get-alist-option org-show-siblings key)))
11860 (catch 'exit
11861 ;; Show heading or entry text
11862 (if (and heading-p (not entry-p))
11863 (org-flag-heading nil) ; only show the heading
11864 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11865 (org-show-hidden-entry))) ; show entire entry
11866 (when following-p
11867 ;; Show next sibling, or heading below text
11868 (save-excursion
11869 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11870 (org-flag-heading nil))))
11871 (when siblings-p (org-show-siblings))
11872 (when hierarchy-p
11873 ;; show all higher headings, possibly with siblings
11874 (save-excursion
11875 (while (and (condition-case nil
11876 (progn (org-up-heading-all 1) t)
11877 (error nil))
11878 (not (bobp)))
11879 (org-flag-heading nil)
11880 (when siblings-p (org-show-siblings))))))))
11882 (defvar org-reveal-start-hook nil
11883 "Hook run before revealing a location.")
11885 (defun org-reveal (&optional siblings)
11886 "Show current entry, hierarchy above it, and the following headline.
11887 This can be used to show a consistent set of context around locations
11888 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11889 not t for the search context.
11891 With optional argument SIBLINGS, on each level of the hierarchy all
11892 siblings are shown. This repairs the tree structure to what it would
11893 look like when opened with hierarchical calls to `org-cycle'.
11894 With double optional argument `C-u C-u', go to the parent and show the
11895 entire tree."
11896 (interactive "P")
11897 (run-hooks 'org-reveal-start-hook)
11898 (let ((org-show-hierarchy-above t)
11899 (org-show-following-heading t)
11900 (org-show-siblings (if siblings t org-show-siblings)))
11901 (org-show-context nil))
11902 (when (equal siblings '(16))
11903 (save-excursion
11904 (when (org-up-heading-safe)
11905 (org-show-subtree)
11906 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11908 (defun org-highlight-new-match (beg end)
11909 "Highlight from BEG to END and mark the highlight is an occur headline."
11910 (let ((ov (make-overlay beg end)))
11911 (overlay-put ov 'face 'secondary-selection)
11912 (push ov org-occur-highlights)))
11914 (defun org-remove-occur-highlights (&optional beg end noremove)
11915 "Remove the occur highlights from the buffer.
11916 BEG and END are ignored. If NOREMOVE is nil, remove this function
11917 from the `before-change-functions' in the current buffer."
11918 (interactive)
11919 (unless org-inhibit-highlight-removal
11920 (mapc 'delete-overlay org-occur-highlights)
11921 (setq org-occur-highlights nil)
11922 (setq org-occur-parameters nil)
11923 (unless noremove
11924 (remove-hook 'before-change-functions
11925 'org-remove-occur-highlights 'local))))
11927 ;;;; Priorities
11929 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11930 "Regular expression matching the priority indicator.")
11932 (defvar org-remove-priority-next-time nil)
11934 (defun org-priority-up ()
11935 "Increase the priority of the current item."
11936 (interactive)
11937 (org-priority 'up))
11939 (defun org-priority-down ()
11940 "Decrease the priority of the current item."
11941 (interactive)
11942 (org-priority 'down))
11944 (defun org-priority (&optional action)
11945 "Change the priority of an item by ARG.
11946 ACTION can be `set', `up', `down', or a character."
11947 (interactive)
11948 (unless org-enable-priority-commands
11949 (error "Priority commands are disabled"))
11950 (setq action (or action 'set))
11951 (let (current new news have remove)
11952 (save-excursion
11953 (org-back-to-heading t)
11954 (if (looking-at org-priority-regexp)
11955 (setq current (string-to-char (match-string 2))
11956 have t)
11957 (setq current org-default-priority))
11958 (cond
11959 ((eq action 'remove)
11960 (setq remove t new ?\ ))
11961 ((or (eq action 'set)
11962 (if (featurep 'xemacs) (characterp action) (integerp action)))
11963 (if (not (eq action 'set))
11964 (setq new action)
11965 (message "Priority %c-%c, SPC to remove: "
11966 org-highest-priority org-lowest-priority)
11967 (setq new (read-char-exclusive)))
11968 (if (and (= (upcase org-highest-priority) org-highest-priority)
11969 (= (upcase org-lowest-priority) org-lowest-priority))
11970 (setq new (upcase new)))
11971 (cond ((equal new ?\ ) (setq remove t))
11972 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11973 (error "Priority must be between `%c' and `%c'"
11974 org-highest-priority org-lowest-priority))))
11975 ((eq action 'up)
11976 (if (and (not have) (eq last-command this-command))
11977 (setq new org-lowest-priority)
11978 (setq new (if (and org-priority-start-cycle-with-default (not have))
11979 org-default-priority (1- current)))))
11980 ((eq action 'down)
11981 (if (and (not have) (eq last-command this-command))
11982 (setq new org-highest-priority)
11983 (setq new (if (and org-priority-start-cycle-with-default (not have))
11984 org-default-priority (1+ current)))))
11985 (t (error "Invalid action")))
11986 (if (or (< (upcase new) org-highest-priority)
11987 (> (upcase new) org-lowest-priority))
11988 (setq remove t))
11989 (setq news (format "%c" new))
11990 (if have
11991 (if remove
11992 (replace-match "" t t nil 1)
11993 (replace-match news t t nil 2))
11994 (if remove
11995 (error "No priority cookie found in line")
11996 (let ((case-fold-search nil))
11997 (looking-at org-todo-line-regexp))
11998 (if (match-end 2)
11999 (progn
12000 (goto-char (match-end 2))
12001 (insert " [#" news "]"))
12002 (goto-char (match-beginning 3))
12003 (insert "[#" news "] "))))
12004 (org-preserve-lc (org-set-tags nil 'align)))
12005 (if remove
12006 (message "Priority removed")
12007 (message "Priority of current item set to %s" news))))
12009 (defun org-get-priority (s)
12010 "Find priority cookie and return priority."
12011 (save-match-data
12012 (if (not (string-match org-priority-regexp s))
12013 (* 1000 (- org-lowest-priority org-default-priority))
12014 (* 1000 (- org-lowest-priority
12015 (string-to-char (match-string 2 s)))))))
12017 ;;;; Tags
12019 (defvar org-agenda-archives-mode)
12020 (defvar org-map-continue-from nil
12021 "Position from where mapping should continue.
12022 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12024 (defvar org-scanner-tags nil
12025 "The current tag list while the tags scanner is running.")
12026 (defvar org-trust-scanner-tags nil
12027 "Should `org-get-tags-at' use the tags fro the scanner.
12028 This is for internal dynamical scoping only.
12029 When this is non-nil, the function `org-get-tags-at' will return the value
12030 of `org-scanner-tags' instead of building the list by itself. This
12031 can lead to large speed-ups when the tags scanner is used in a file with
12032 many entries, and when the list of tags is retrieved, for example to
12033 obtain a list of properties. Building the tags list for each entry in such
12034 a file becomes an N^2 operation - but with this variable set, it scales
12035 as N.")
12037 (defun org-scan-tags (action matcher &optional todo-only)
12038 "Scan headline tags with inheritance and produce output ACTION.
12040 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12041 or `agenda' to produce an entry list for an agenda view. It can also be
12042 a Lisp form or a function that should be called at each matched headline, in
12043 this case the return value is a list of all return values from these calls.
12045 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12046 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12047 only lines with a TODO keyword are included in the output."
12048 (require 'org-agenda)
12049 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12050 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12051 (org-re
12052 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12053 (props (list 'face 'default
12054 'done-face 'org-agenda-done
12055 'undone-face 'default
12056 'mouse-face 'highlight
12057 'org-not-done-regexp org-not-done-regexp
12058 'org-todo-regexp org-todo-regexp
12059 'help-echo
12060 (format "mouse-2 or RET jump to org file %s"
12061 (abbreviate-file-name
12062 (or (buffer-file-name (buffer-base-buffer))
12063 (buffer-name (buffer-base-buffer)))))))
12064 (case-fold-search nil)
12065 (org-map-continue-from nil)
12066 lspos tags tags-list
12067 (tags-alist (list (cons 0 org-file-tags)))
12068 (llast 0) rtn rtn1 level category i txt
12069 todo marker entry priority)
12070 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12071 (setq action (list 'lambda nil action)))
12072 (save-excursion
12073 (goto-char (point-min))
12074 (when (eq action 'sparse-tree)
12075 (org-overview)
12076 (org-remove-occur-highlights))
12077 (while (re-search-forward re nil t)
12078 (catch :skip
12079 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12080 tags (if (match-end 4) (org-match-string-no-properties 4)))
12081 (goto-char (setq lspos (match-beginning 0)))
12082 (setq level (org-reduced-level (funcall outline-level))
12083 category (org-get-category))
12084 (setq i llast llast level)
12085 ;; remove tag lists from same and sublevels
12086 (while (>= i level)
12087 (when (setq entry (assoc i tags-alist))
12088 (setq tags-alist (delete entry tags-alist)))
12089 (setq i (1- i)))
12090 ;; add the next tags
12091 (when tags
12092 (setq tags (org-split-string tags ":")
12093 tags-alist
12094 (cons (cons level tags) tags-alist)))
12095 ;; compile tags for current headline
12096 (setq tags-list
12097 (if org-use-tag-inheritance
12098 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12099 tags)
12100 org-scanner-tags tags-list)
12101 (when org-use-tag-inheritance
12102 (setcdr (car tags-alist)
12103 (mapcar (lambda (x)
12104 (setq x (copy-sequence x))
12105 (org-add-prop-inherited x))
12106 (cdar tags-alist))))
12107 (when (and tags org-use-tag-inheritance
12108 (or (not (eq t org-use-tag-inheritance))
12109 org-tags-exclude-from-inheritance))
12110 ;; selective inheritance, remove uninherited ones
12111 (setcdr (car tags-alist)
12112 (org-remove-uniherited-tags (cdar tags-alist))))
12113 (when (and (or (not todo-only)
12114 (and (member todo org-not-done-keywords)
12115 (or (not org-agenda-tags-todo-honor-ignore-options)
12116 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12117 (let ((case-fold-search t)) (eval matcher))
12119 (not (member org-archive-tag tags-list))
12120 ;; we have an archive tag, should we use this anyway?
12121 (or (not org-agenda-skip-archived-trees)
12122 (and (eq action 'agenda) org-agenda-archives-mode))))
12123 (unless (eq action 'sparse-tree) (org-agenda-skip))
12125 ;; select this headline
12127 (cond
12128 ((eq action 'sparse-tree)
12129 (and org-highlight-sparse-tree-matches
12130 (org-get-heading) (match-end 0)
12131 (org-highlight-new-match
12132 (match-beginning 0) (match-beginning 1)))
12133 (org-show-context 'tags-tree))
12134 ((eq action 'agenda)
12135 (setq txt (org-format-agenda-item
12137 (concat
12138 (if (eq org-tags-match-list-sublevels 'indented)
12139 (make-string (1- level) ?.) "")
12140 (org-get-heading))
12141 category
12142 tags-list
12144 priority (org-get-priority txt))
12145 (goto-char lspos)
12146 (setq marker (org-agenda-new-marker))
12147 (org-add-props txt props
12148 'org-marker marker 'org-hd-marker marker 'org-category category
12149 'todo-state todo
12150 'priority priority 'type "tagsmatch")
12151 (push txt rtn))
12152 ((functionp action)
12153 (setq org-map-continue-from nil)
12154 (save-excursion
12155 (setq rtn1 (funcall action))
12156 (push rtn1 rtn)))
12157 (t (error "Invalid action")))
12159 ;; if we are to skip sublevels, jump to end of subtree
12160 (unless org-tags-match-list-sublevels
12161 (org-end-of-subtree t)
12162 (backward-char 1))))
12163 ;; Get the correct position from where to continue
12164 (if org-map-continue-from
12165 (goto-char org-map-continue-from)
12166 (and (= (point) lspos) (end-of-line 1)))))
12167 (when (and (eq action 'sparse-tree)
12168 (not org-sparse-tree-open-archived-trees))
12169 (org-hide-archived-subtrees (point-min) (point-max)))
12170 (nreverse rtn)))
12172 (defun org-remove-uniherited-tags (tags)
12173 "Remove all tags that are not inherited from the list TAGS."
12174 (cond
12175 ((eq org-use-tag-inheritance t)
12176 (if org-tags-exclude-from-inheritance
12177 (org-delete-all org-tags-exclude-from-inheritance tags)
12178 tags))
12179 ((not org-use-tag-inheritance) nil)
12180 ((stringp org-use-tag-inheritance)
12181 (delq nil (mapcar
12182 (lambda (x)
12183 (if (and (string-match org-use-tag-inheritance x)
12184 (not (member x org-tags-exclude-from-inheritance)))
12185 x nil))
12186 tags)))
12187 ((listp org-use-tag-inheritance)
12188 (delq nil (mapcar
12189 (lambda (x)
12190 (if (member x org-use-tag-inheritance) x nil))
12191 tags)))))
12193 (defvar todo-only) ;; dynamically scoped
12195 (defun org-match-sparse-tree (&optional todo-only match)
12196 "Create a sparse tree according to tags string MATCH.
12197 MATCH can contain positive and negative selection of tags, like
12198 \"+WORK+URGENT-WITHBOSS\".
12199 If optional argument TODO-ONLY is non-nil, only select lines that are
12200 also TODO lines."
12201 (interactive "P")
12202 (org-prepare-agenda-buffers (list (current-buffer)))
12203 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12205 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12207 (defvar org-cached-props nil)
12208 (defun org-cached-entry-get (pom property)
12209 (if (or (eq t org-use-property-inheritance)
12210 (and (stringp org-use-property-inheritance)
12211 (string-match org-use-property-inheritance property))
12212 (and (listp org-use-property-inheritance)
12213 (member property org-use-property-inheritance)))
12214 ;; Caching is not possible, check it directly
12215 (org-entry-get pom property 'inherit)
12216 ;; Get all properties, so that we can do complicated checks easily
12217 (cdr (assoc property (or org-cached-props
12218 (setq org-cached-props
12219 (org-entry-properties pom)))))))
12221 (defun org-global-tags-completion-table (&optional files)
12222 "Return the list of all tags in all agenda buffer/files."
12223 (save-excursion
12224 (org-uniquify
12225 (delq nil
12226 (apply 'append
12227 (mapcar
12228 (lambda (file)
12229 (set-buffer (find-file-noselect file))
12230 (append (org-get-buffer-tags)
12231 (mapcar (lambda (x) (if (stringp (car-safe x))
12232 (list (car-safe x)) nil))
12233 org-tag-alist)))
12234 (if (and files (car files))
12235 files
12236 (org-agenda-files))))))))
12238 (defun org-make-tags-matcher (match)
12239 "Create the TAGS//TODO matcher form for the selection string MATCH."
12240 ;; todo-only is scoped dynamically into this function, and the function
12241 ;; may change it if the matcher asks for it.
12242 (unless match
12243 ;; Get a new match request, with completion
12244 (let ((org-last-tags-completion-table
12245 (org-global-tags-completion-table)))
12246 (setq match (org-completing-read-no-i
12247 "Match: " 'org-tags-completion-function nil nil nil
12248 'org-tags-history))))
12250 ;; Parse the string and create a lisp form
12251 (let ((match0 match)
12252 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12253 minus tag mm
12254 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12255 orterms term orlist re-p str-p level-p level-op time-p
12256 prop-p pn pv po cat-p gv rest)
12257 (if (string-match "/+" match)
12258 ;; match contains also a todo-matching request
12259 (progn
12260 (setq tagsmatch (substring match 0 (match-beginning 0))
12261 todomatch (substring match (match-end 0)))
12262 (if (string-match "^!" todomatch)
12263 (setq todo-only t todomatch (substring todomatch 1)))
12264 (if (string-match "^\\s-*$" todomatch)
12265 (setq todomatch nil)))
12266 ;; only matching tags
12267 (setq tagsmatch match todomatch nil))
12269 ;; Make the tags matcher
12270 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12271 (setq tagsmatcher t)
12272 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12273 (while (setq term (pop orterms))
12274 (while (and (equal (substring term -1) "\\") orterms)
12275 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12276 (while (string-match re term)
12277 (setq rest (substring term (match-end 0))
12278 minus (and (match-end 1)
12279 (equal (match-string 1 term) "-"))
12280 tag (match-string 2 term)
12281 re-p (equal (string-to-char tag) ?{)
12282 level-p (match-end 4)
12283 prop-p (match-end 5)
12284 mm (cond
12285 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12286 (level-p
12287 (setq level-op (org-op-to-function (match-string 3 term)))
12288 `(,level-op level ,(string-to-number
12289 (match-string 4 term))))
12290 (prop-p
12291 (setq pn (match-string 5 term)
12292 po (match-string 6 term)
12293 pv (match-string 7 term)
12294 cat-p (equal pn "CATEGORY")
12295 re-p (equal (string-to-char pv) ?{)
12296 str-p (equal (string-to-char pv) ?\")
12297 time-p (save-match-data
12298 (string-match "^\"[[<].*[]>]\"$" pv))
12299 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12300 (if time-p (setq pv (org-matcher-time pv)))
12301 (setq po (org-op-to-function po (if time-p 'time str-p)))
12302 (cond
12303 ((equal pn "CATEGORY")
12304 (setq gv '(get-text-property (point) 'org-category)))
12305 ((equal pn "TODO")
12306 (setq gv 'todo))
12308 (setq gv `(org-cached-entry-get nil ,pn))))
12309 (if re-p
12310 (if (eq po 'org<>)
12311 `(not (string-match ,pv (or ,gv "")))
12312 `(string-match ,pv (or ,gv "")))
12313 (if str-p
12314 `(,po (or ,gv "") ,pv)
12315 `(,po (string-to-number (or ,gv ""))
12316 ,(string-to-number pv) ))))
12317 (t `(member ,tag tags-list)))
12318 mm (if minus (list 'not mm) mm)
12319 term rest)
12320 (push mm tagsmatcher))
12321 (push (if (> (length tagsmatcher) 1)
12322 (cons 'and tagsmatcher)
12323 (car tagsmatcher))
12324 orlist)
12325 (setq tagsmatcher nil))
12326 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12327 (setq tagsmatcher
12328 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12329 ;; Make the todo matcher
12330 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12331 (setq todomatcher t)
12332 (setq orterms (org-split-string todomatch "|") orlist nil)
12333 (while (setq term (pop orterms))
12334 (while (string-match re term)
12335 (setq minus (and (match-end 1)
12336 (equal (match-string 1 term) "-"))
12337 kwd (match-string 2 term)
12338 re-p (equal (string-to-char kwd) ?{)
12339 term (substring term (match-end 0))
12340 mm (if re-p
12341 `(string-match ,(substring kwd 1 -1) todo)
12342 (list 'equal 'todo kwd))
12343 mm (if minus (list 'not mm) mm))
12344 (push mm todomatcher))
12345 (push (if (> (length todomatcher) 1)
12346 (cons 'and todomatcher)
12347 (car todomatcher))
12348 orlist)
12349 (setq todomatcher nil))
12350 (setq todomatcher (if (> (length orlist) 1)
12351 (cons 'or orlist) (car orlist))))
12353 ;; Return the string and lisp forms of the matcher
12354 (setq matcher (if todomatcher
12355 (list 'and tagsmatcher todomatcher)
12356 tagsmatcher))
12357 (cons match0 matcher)))
12359 (defun org-op-to-function (op &optional stringp)
12360 "Turn an operator into the appropriate function."
12361 (setq op
12362 (cond
12363 ((equal op "<" ) '(< string< org-time<))
12364 ((equal op ">" ) '(> org-string> org-time>))
12365 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12366 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12367 ((member op '("=" "==")) '(= string= org-time=))
12368 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12369 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12371 (defun org<> (a b) (not (= a b)))
12372 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12373 (defun org-string>= (a b) (not (string< a b)))
12374 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12375 (defun org-string<> (a b) (not (string= a b)))
12376 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12377 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12378 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12379 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12380 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12381 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12382 (defun org-2ft (s)
12383 "Convert S to a floating point time.
12384 If S is already a number, just return it. If it is a string, parse
12385 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12386 (cond
12387 ((numberp s) s)
12388 ((stringp s)
12389 (condition-case nil
12390 (float-time (apply 'encode-time (org-parse-time-string s)))
12391 (error 0.)))
12392 (t 0.)))
12394 (defun org-time-today ()
12395 "Time in seconds today at 0:00.
12396 Returns the float number of seconds since the beginning of the
12397 epoch to the beginning of today (00:00)."
12398 (float-time (apply 'encode-time
12399 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12401 (defun org-matcher-time (s)
12402 "Interpret a time comparison value."
12403 (save-match-data
12404 (cond
12405 ((string= s "<now>") (float-time))
12406 ((string= s "<today>") (org-time-today))
12407 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12408 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12409 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12410 (+ (org-time-today)
12411 (* (string-to-number (match-string 1 s))
12412 (cdr (assoc (match-string 2 s)
12413 '(("d" . 86400.0) ("w" . 604800.0)
12414 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12415 (t (org-2ft s)))))
12417 (defun org-match-any-p (re list)
12418 "Does re match any element of list?"
12419 (setq list (mapcar (lambda (x) (string-match re x)) list))
12420 (delq nil list))
12422 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12423 (defvar org-tags-overlay (make-overlay 1 1))
12424 (org-detach-overlay org-tags-overlay)
12426 (defun org-get-local-tags-at (&optional pos)
12427 "Get a list of tags defined in the current headline."
12428 (org-get-tags-at pos 'local))
12430 (defun org-get-local-tags ()
12431 "Get a list of tags defined in the current headline."
12432 (org-get-tags-at nil 'local))
12434 (defun org-get-tags-at (&optional pos local)
12435 "Get a list of all headline tags applicable at POS.
12436 POS defaults to point. If tags are inherited, the list contains
12437 the targets in the same sequence as the headlines appear, i.e.
12438 the tags of the current headline come last.
12439 When LOCAL is non-nil, only return tags from the current headline,
12440 ignore inherited ones."
12441 (interactive)
12442 (if (and org-trust-scanner-tags
12443 (or (not pos) (equal pos (point)))
12444 (not local))
12445 org-scanner-tags
12446 (let (tags ltags lastpos parent)
12447 (save-excursion
12448 (save-restriction
12449 (widen)
12450 (goto-char (or pos (point)))
12451 (save-match-data
12452 (catch 'done
12453 (condition-case nil
12454 (progn
12455 (org-back-to-heading t)
12456 (while (not (equal lastpos (point)))
12457 (setq lastpos (point))
12458 (when (looking-at
12459 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12460 (setq ltags (org-split-string
12461 (org-match-string-no-properties 1) ":"))
12462 (when parent
12463 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12464 (setq tags (append
12465 (if parent
12466 (org-remove-uniherited-tags ltags)
12467 ltags)
12468 tags)))
12469 (or org-use-tag-inheritance (throw 'done t))
12470 (if local (throw 'done t))
12471 (or (org-up-heading-safe) (error nil))
12472 (setq parent t)))
12473 (error nil)))))
12474 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12476 (defun org-add-prop-inherited (s)
12477 (add-text-properties 0 (length s) '(inherited t) s)
12480 (defun org-toggle-tag (tag &optional onoff)
12481 "Toggle the tag TAG for the current line.
12482 If ONOFF is `on' or `off', don't toggle but set to this state."
12483 (let (res current)
12484 (save-excursion
12485 (org-back-to-heading t)
12486 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12487 (point-at-eol) t)
12488 (progn
12489 (setq current (match-string 1))
12490 (replace-match ""))
12491 (setq current ""))
12492 (setq current (nreverse (org-split-string current ":")))
12493 (cond
12494 ((eq onoff 'on)
12495 (setq res t)
12496 (or (member tag current) (push tag current)))
12497 ((eq onoff 'off)
12498 (or (not (member tag current)) (setq current (delete tag current))))
12499 (t (if (member tag current)
12500 (setq current (delete tag current))
12501 (setq res t)
12502 (push tag current))))
12503 (end-of-line 1)
12504 (if current
12505 (progn
12506 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12507 (org-set-tags nil t))
12508 (delete-horizontal-space))
12509 (run-hooks 'org-after-tags-change-hook))
12510 res))
12512 (defun org-align-tags-here (to-col)
12513 ;; Assumes that this is a headline
12514 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12515 (beginning-of-line 1)
12516 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12517 (< pos (match-beginning 2)))
12518 (progn
12519 (setq tags-l (- (match-end 2) (match-beginning 2)))
12520 (goto-char (match-beginning 1))
12521 (insert " ")
12522 (delete-region (point) (1+ (match-beginning 2)))
12523 (setq ncol (max (1+ (current-column))
12524 (1+ col)
12525 (if (> to-col 0)
12526 to-col
12527 (- (abs to-col) tags-l))))
12528 (setq p (point))
12529 (insert (make-string (- ncol (current-column)) ?\ ))
12530 (setq ncol (current-column))
12531 (when indent-tabs-mode (tabify p (point-at-eol)))
12532 (org-move-to-column (min ncol col) t))
12533 (goto-char pos))))
12535 (defun org-set-tags-command (&optional arg just-align)
12536 "Call the set-tags command for the current entry."
12537 (interactive "P")
12538 (if (org-on-heading-p)
12539 (org-set-tags arg just-align)
12540 (save-excursion
12541 (org-back-to-heading t)
12542 (org-set-tags arg just-align))))
12544 (defun org-set-tags-to (data)
12545 "Set the tags of the current entry to DATA, replacing the current tags.
12546 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12547 If DATA is nil or the empty string, any tags will be removed."
12548 (interactive "sTags: ")
12549 (setq data
12550 (cond
12551 ((eq data nil) "")
12552 ((equal data "") "")
12553 ((stringp data)
12554 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12555 ":"))
12556 ((listp data)
12557 (concat ":" (mapconcat 'identity data ":") ":"))
12558 (t nil)))
12559 (when data
12560 (save-excursion
12561 (org-back-to-heading t)
12562 (when (looking-at org-complex-heading-regexp)
12563 (if (match-end 5)
12564 (progn
12565 (goto-char (match-beginning 5))
12566 (insert data)
12567 (delete-region (point) (point-at-eol))
12568 (org-set-tags nil 'align))
12569 (goto-char (point-at-eol))
12570 (insert " " data)
12571 (org-set-tags nil 'align)))
12572 (beginning-of-line 1)
12573 (if (looking-at ".*?\\([ \t]+\\)$")
12574 (delete-region (match-beginning 1) (match-end 1))))))
12576 (defun org-align-all-tags ()
12577 "Align the tags i all headings."
12578 (interactive)
12579 (save-excursion
12580 (or (ignore-errors (org-back-to-heading t))
12581 (outline-next-heading))
12582 (if (org-on-heading-p)
12583 (org-set-tags t)
12584 (message "No headings"))))
12586 (defun org-set-tags (&optional arg just-align)
12587 "Set the tags for the current headline.
12588 With prefix ARG, realign all tags in headings in the current buffer."
12589 (interactive "P")
12590 (let* ((re (concat "^" outline-regexp))
12591 (current (org-get-tags-string))
12592 (col (current-column))
12593 (org-setting-tags t)
12594 table current-tags inherited-tags ; computed below when needed
12595 tags p0 c0 c1 rpl)
12596 (if arg
12597 (save-excursion
12598 (goto-char (point-min))
12599 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12600 (while (re-search-forward re nil t)
12601 (org-set-tags nil t)
12602 (end-of-line 1)))
12603 (message "All tags realigned to column %d" org-tags-column))
12604 (if just-align
12605 (setq tags current)
12606 ;; Get a new set of tags from the user
12607 (save-excursion
12608 (setq table (append org-tag-persistent-alist
12609 (or org-tag-alist (org-get-buffer-tags))
12610 (and org-complete-tags-always-offer-all-agenda-tags
12611 (org-global-tags-completion-table (org-agenda-files))))
12612 org-last-tags-completion-table table
12613 current-tags (org-split-string current ":")
12614 inherited-tags (nreverse
12615 (nthcdr (length current-tags)
12616 (nreverse (org-get-tags-at))))
12617 tags
12618 (if (or (eq t org-use-fast-tag-selection)
12619 (and org-use-fast-tag-selection
12620 (delq nil (mapcar 'cdr table))))
12621 (org-fast-tag-selection
12622 current-tags inherited-tags table
12623 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12624 (let ((org-add-colon-after-tag-completion t))
12625 (org-trim
12626 (org-without-partial-completion
12627 (org-icompleting-read "Tags: " 'org-tags-completion-function
12628 nil nil current 'org-tags-history)))))))
12629 (while (string-match "[-+&]+" tags)
12630 ;; No boolean logic, just a list
12631 (setq tags (replace-match ":" t t tags))))
12633 (if org-tags-sort-function
12634 (setq tags (mapconcat 'identity
12635 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12636 org-tags-sort-function) ":")))
12638 (if (string-match "\\`[\t ]*\\'" tags)
12639 (setq tags "")
12640 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12641 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12643 ;; Insert new tags at the correct column
12644 (beginning-of-line 1)
12645 (cond
12646 ((and (equal current "") (equal tags "")))
12647 ((re-search-forward
12648 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12649 (point-at-eol) t)
12650 (if (equal tags "")
12651 (setq rpl "")
12652 (goto-char (match-beginning 0))
12653 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12654 (1+ (point)) (point))
12655 c1 (max (1+ c0) (if (> org-tags-column 0)
12656 org-tags-column
12657 (- (- org-tags-column) (length tags))))
12658 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12659 (replace-match rpl t t)
12660 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12661 tags)
12662 (t (error "Tags alignment failed")))
12663 (org-move-to-column col)
12664 (unless just-align
12665 (run-hooks 'org-after-tags-change-hook)))))
12667 (defun org-change-tag-in-region (beg end tag off)
12668 "Add or remove TAG for each entry in the region.
12669 This works in the agenda, and also in an org-mode buffer."
12670 (interactive
12671 (list (region-beginning) (region-end)
12672 (let ((org-last-tags-completion-table
12673 (if (org-mode-p)
12674 (org-get-buffer-tags)
12675 (org-global-tags-completion-table))))
12676 (org-icompleting-read
12677 "Tag: " 'org-tags-completion-function nil nil nil
12678 'org-tags-history))
12679 (progn
12680 (message "[s]et or [r]emove? ")
12681 (equal (read-char-exclusive) ?r))))
12682 (if (fboundp 'deactivate-mark) (deactivate-mark))
12683 (let ((agendap (equal major-mode 'org-agenda-mode))
12684 l1 l2 m buf pos newhead (cnt 0))
12685 (goto-char end)
12686 (setq l2 (1- (org-current-line)))
12687 (goto-char beg)
12688 (setq l1 (org-current-line))
12689 (loop for l from l1 to l2 do
12690 (org-goto-line l)
12691 (setq m (get-text-property (point) 'org-hd-marker))
12692 (when (or (and (org-mode-p) (org-on-heading-p))
12693 (and agendap m))
12694 (setq buf (if agendap (marker-buffer m) (current-buffer))
12695 pos (if agendap m (point)))
12696 (with-current-buffer buf
12697 (save-excursion
12698 (save-restriction
12699 (goto-char pos)
12700 (setq cnt (1+ cnt))
12701 (org-toggle-tag tag (if off 'off 'on))
12702 (setq newhead (org-get-heading)))))
12703 (and agendap (org-agenda-change-all-lines newhead m))))
12704 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12706 (defun org-tags-completion-function (string predicate &optional flag)
12707 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12708 (confirm (lambda (x) (stringp (car x)))))
12709 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12710 (setq s1 (match-string 1 string)
12711 s2 (match-string 2 string))
12712 (setq s1 "" s2 string))
12713 (cond
12714 ((eq flag nil)
12715 ;; try completion
12716 (setq rtn (try-completion s2 ctable confirm))
12717 (if (stringp rtn)
12718 (setq rtn
12719 (concat s1 s2 (substring rtn (length s2))
12720 (if (and org-add-colon-after-tag-completion
12721 (assoc rtn ctable))
12722 ":" ""))))
12723 rtn)
12724 ((eq flag t)
12725 ;; all-completions
12726 (all-completions s2 ctable confirm)
12728 ((eq flag 'lambda)
12729 ;; exact match?
12730 (assoc s2 ctable)))
12733 (defun org-fast-tag-insert (kwd tags face &optional end)
12734 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12735 (insert (format "%-12s" (concat kwd ":"))
12736 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12737 (or end "")))
12739 (defun org-fast-tag-show-exit (flag)
12740 (save-excursion
12741 (org-goto-line 3)
12742 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12743 (replace-match ""))
12744 (when flag
12745 (end-of-line 1)
12746 (org-move-to-column (- (window-width) 19) t)
12747 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12749 (defun org-set-current-tags-overlay (current prefix)
12750 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12751 (if (featurep 'xemacs)
12752 (org-overlay-display org-tags-overlay (concat prefix s)
12753 'secondary-selection)
12754 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12755 (org-overlay-display org-tags-overlay (concat prefix s)))))
12757 (defvar org-last-tag-selection-key nil)
12758 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12759 "Fast tag selection with single keys.
12760 CURRENT is the current list of tags in the headline, INHERITED is the
12761 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12762 possibly with grouping information. TODO-TABLE is a similar table with
12763 TODO keywords, should these have keys assigned to them.
12764 If the keys are nil, a-z are automatically assigned.
12765 Returns the new tags string, or nil to not change the current settings."
12766 (let* ((fulltable (append table todo-table))
12767 (maxlen (apply 'max (mapcar
12768 (lambda (x)
12769 (if (stringp (car x)) (string-width (car x)) 0))
12770 fulltable)))
12771 (buf (current-buffer))
12772 (expert (eq org-fast-tag-selection-single-key 'expert))
12773 (buffer-tags nil)
12774 (fwidth (+ maxlen 3 1 3))
12775 (ncol (/ (- (window-width) 4) fwidth))
12776 (i-face 'org-done)
12777 (c-face 'org-todo)
12778 tg cnt e c char c1 c2 ntable tbl rtn
12779 ov-start ov-end ov-prefix
12780 (exit-after-next org-fast-tag-selection-single-key)
12781 (done-keywords org-done-keywords)
12782 groups ingroup)
12783 (save-excursion
12784 (beginning-of-line 1)
12785 (if (looking-at
12786 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12787 (setq ov-start (match-beginning 1)
12788 ov-end (match-end 1)
12789 ov-prefix "")
12790 (setq ov-start (1- (point-at-eol))
12791 ov-end (1+ ov-start))
12792 (skip-chars-forward "^\n\r")
12793 (setq ov-prefix
12794 (concat
12795 (buffer-substring (1- (point)) (point))
12796 (if (> (current-column) org-tags-column)
12798 (make-string (- org-tags-column (current-column)) ?\ ))))))
12799 (move-overlay org-tags-overlay ov-start ov-end)
12800 (save-window-excursion
12801 (if expert
12802 (set-buffer (get-buffer-create " *Org tags*"))
12803 (delete-other-windows)
12804 (split-window-vertically)
12805 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12806 (erase-buffer)
12807 (org-set-local 'org-done-keywords done-keywords)
12808 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12809 (org-fast-tag-insert "Current" current c-face "\n\n")
12810 (org-fast-tag-show-exit exit-after-next)
12811 (org-set-current-tags-overlay current ov-prefix)
12812 (setq tbl fulltable char ?a cnt 0)
12813 (while (setq e (pop tbl))
12814 (cond
12815 ((equal (car e) :startgroup)
12816 (push '() groups) (setq ingroup t)
12817 (when (not (= cnt 0))
12818 (setq cnt 0)
12819 (insert "\n"))
12820 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12821 ((equal (car e) :endgroup)
12822 (setq ingroup nil cnt 0)
12823 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12824 ((equal e '(:newline))
12825 (when (not (= cnt 0))
12826 (setq cnt 0)
12827 (insert "\n")
12828 (setq e (car tbl))
12829 (while (equal (car tbl) '(:newline))
12830 (insert "\n")
12831 (setq tbl (cdr tbl)))))
12833 (setq tg (copy-sequence (car e)) c2 nil)
12834 (if (cdr e)
12835 (setq c (cdr e))
12836 ;; automatically assign a character.
12837 (setq c1 (string-to-char
12838 (downcase (substring
12839 tg (if (= (string-to-char tg) ?@) 1 0)))))
12840 (if (or (rassoc c1 ntable) (rassoc c1 table))
12841 (while (or (rassoc char ntable) (rassoc char table))
12842 (setq char (1+ char)))
12843 (setq c2 c1))
12844 (setq c (or c2 char)))
12845 (if ingroup (push tg (car groups)))
12846 (setq tg (org-add-props tg nil 'face
12847 (cond
12848 ((not (assoc tg table))
12849 (org-get-todo-face tg))
12850 ((member tg current) c-face)
12851 ((member tg inherited) i-face)
12852 (t nil))))
12853 (if (and (= cnt 0) (not ingroup)) (insert " "))
12854 (insert "[" c "] " tg (make-string
12855 (- fwidth 4 (length tg)) ?\ ))
12856 (push (cons tg c) ntable)
12857 (when (= (setq cnt (1+ cnt)) ncol)
12858 (insert "\n")
12859 (if ingroup (insert " "))
12860 (setq cnt 0)))))
12861 (setq ntable (nreverse ntable))
12862 (insert "\n")
12863 (goto-char (point-min))
12864 (if (not expert) (org-fit-window-to-buffer))
12865 (setq rtn
12866 (catch 'exit
12867 (while t
12868 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12869 (if (not groups) "no " "")
12870 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12871 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12872 (setq org-last-tag-selection-key c)
12873 (cond
12874 ((= c ?\r) (throw 'exit t))
12875 ((= c ?!)
12876 (setq groups (not groups))
12877 (goto-char (point-min))
12878 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12879 ((= c ?\C-c)
12880 (if (not expert)
12881 (org-fast-tag-show-exit
12882 (setq exit-after-next (not exit-after-next)))
12883 (setq expert nil)
12884 (delete-other-windows)
12885 (split-window-vertically)
12886 (org-switch-to-buffer-other-window " *Org tags*")
12887 (org-fit-window-to-buffer)))
12888 ((or (= c ?\C-g)
12889 (and (= c ?q) (not (rassoc c ntable))))
12890 (org-detach-overlay org-tags-overlay)
12891 (setq quit-flag t))
12892 ((= c ?\ )
12893 (setq current nil)
12894 (if exit-after-next (setq exit-after-next 'now)))
12895 ((= c ?\t)
12896 (condition-case nil
12897 (setq tg (org-icompleting-read
12898 "Tag: "
12899 (or buffer-tags
12900 (with-current-buffer buf
12901 (org-get-buffer-tags)))))
12902 (quit (setq tg "")))
12903 (when (string-match "\\S-" tg)
12904 (add-to-list 'buffer-tags (list tg))
12905 (if (member tg current)
12906 (setq current (delete tg current))
12907 (push tg current)))
12908 (if exit-after-next (setq exit-after-next 'now)))
12909 ((setq e (rassoc c todo-table) tg (car e))
12910 (with-current-buffer buf
12911 (save-excursion (org-todo tg)))
12912 (if exit-after-next (setq exit-after-next 'now)))
12913 ((setq e (rassoc c ntable) tg (car e))
12914 (if (member tg current)
12915 (setq current (delete tg current))
12916 (loop for g in groups do
12917 (if (member tg g)
12918 (mapc (lambda (x)
12919 (setq current (delete x current)))
12920 g)))
12921 (push tg current))
12922 (if exit-after-next (setq exit-after-next 'now))))
12924 ;; Create a sorted list
12925 (setq current
12926 (sort current
12927 (lambda (a b)
12928 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12929 (if (eq exit-after-next 'now) (throw 'exit t))
12930 (goto-char (point-min))
12931 (beginning-of-line 2)
12932 (delete-region (point) (point-at-eol))
12933 (org-fast-tag-insert "Current" current c-face)
12934 (org-set-current-tags-overlay current ov-prefix)
12935 (while (re-search-forward
12936 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12937 (setq tg (match-string 1))
12938 (add-text-properties
12939 (match-beginning 1) (match-end 1)
12940 (list 'face
12941 (cond
12942 ((member tg current) c-face)
12943 ((member tg inherited) i-face)
12944 (t (get-text-property (match-beginning 1) 'face))))))
12945 (goto-char (point-min)))))
12946 (org-detach-overlay org-tags-overlay)
12947 (if rtn
12948 (mapconcat 'identity current ":")
12949 nil))))
12951 (defun org-get-tags-string ()
12952 "Get the TAGS string in the current headline."
12953 (unless (org-on-heading-p t)
12954 (error "Not on a heading"))
12955 (save-excursion
12956 (beginning-of-line 1)
12957 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12958 (org-match-string-no-properties 1)
12959 "")))
12961 (defun org-get-tags ()
12962 "Get the list of tags specified in the current headline."
12963 (org-split-string (org-get-tags-string) ":"))
12965 (defun org-get-buffer-tags ()
12966 "Get a table of all tags used in the buffer, for completion."
12967 (let (tags)
12968 (save-excursion
12969 (goto-char (point-min))
12970 (while (re-search-forward
12971 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12972 (when (equal (char-after (point-at-bol 0)) ?*)
12973 (mapc (lambda (x) (add-to-list 'tags x))
12974 (org-split-string (org-match-string-no-properties 1) ":")))))
12975 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12976 (mapcar 'list tags)))
12978 ;;;; The mapping API
12980 ;;;###autoload
12981 (defun org-map-entries (func &optional match scope &rest skip)
12982 "Call FUNC at each headline selected by MATCH in SCOPE.
12984 FUNC is a function or a lisp form. The function will be called without
12985 arguments, with the cursor positioned at the beginning of the headline.
12986 The return values of all calls to the function will be collected and
12987 returned as a list.
12989 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12990 does not need to preserve point. After evaluation, the cursor will be
12991 moved to the end of the line (presumably of the headline of the
12992 processed entry) and search continues from there. Under some
12993 circumstances, this may not produce the wanted results. For example,
12994 if you have removed (e.g. archived) the current (sub)tree it could
12995 mean that the next entry will be skipped entirely. In such cases, you
12996 can specify the position from where search should continue by making
12997 FUNC set the variable `org-map-continue-from' to the desired buffer
12998 position.
13000 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13001 Only headlines that are matched by this query will be considered during
13002 the iteration. When MATCH is nil or t, all headlines will be
13003 visited by the iteration.
13005 SCOPE determines the scope of this command. It can be any of:
13007 nil The current buffer, respecting the restriction if any
13008 tree The subtree started with the entry at point
13009 file The current buffer, without restriction
13010 file-with-archives
13011 The current buffer, and any archives associated with it
13012 agenda All agenda files
13013 agenda-with-archives
13014 All agenda files with any archive files associated with them
13015 \(file1 file2 ...)
13016 If this is a list, all files in the list will be scanned
13018 The remaining args are treated as settings for the skipping facilities of
13019 the scanner. The following items can be given here:
13021 archive skip trees with the archive tag.
13022 comment skip trees with the COMMENT keyword
13023 function or Emacs Lisp form:
13024 will be used as value for `org-agenda-skip-function', so whenever
13025 the function returns t, FUNC will not be called for that
13026 entry and search will continue from the point where the
13027 function leaves it.
13029 If your function needs to retrieve the tags including inherited tags
13030 at the *current* entry, you can use the value of the variable
13031 `org-scanner-tags' which will be much faster than getting the value
13032 with `org-get-tags-at'. If your function gets properties with
13033 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13034 to t around the call to `org-entry-properties' to get the same speedup.
13035 Note that if your function moves around to retrieve tags and properties at
13036 a *different* entry, you cannot use these techniques."
13037 (let* ((org-agenda-archives-mode nil) ; just to make sure
13038 (org-agenda-skip-archived-trees (memq 'archive skip))
13039 (org-agenda-skip-comment-trees (memq 'comment skip))
13040 (org-agenda-skip-function
13041 (car (org-delete-all '(comment archive) skip)))
13042 (org-tags-match-list-sublevels t)
13043 matcher file res
13044 org-todo-keywords-for-agenda
13045 org-done-keywords-for-agenda
13046 org-todo-keyword-alist-for-agenda
13047 org-drawers-for-agenda
13048 org-tag-alist-for-agenda)
13050 (cond
13051 ((eq match t) (setq matcher t))
13052 ((eq match nil) (setq matcher t))
13053 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13055 (save-excursion
13056 (save-restriction
13057 (when (eq scope 'tree)
13058 (org-back-to-heading t)
13059 (org-narrow-to-subtree)
13060 (setq scope nil))
13062 (if (not scope)
13063 (progn
13064 (org-prepare-agenda-buffers
13065 (list (buffer-file-name (current-buffer))))
13066 (setq res (org-scan-tags func matcher)))
13067 ;; Get the right scope
13068 (cond
13069 ((and scope (listp scope) (symbolp (car scope)))
13070 (setq scope (eval scope)))
13071 ((eq scope 'agenda)
13072 (setq scope (org-agenda-files t)))
13073 ((eq scope 'agenda-with-archives)
13074 (setq scope (org-agenda-files t))
13075 (setq scope (org-add-archive-files scope)))
13076 ((eq scope 'file)
13077 (setq scope (list (buffer-file-name))))
13078 ((eq scope 'file-with-archives)
13079 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13080 (org-prepare-agenda-buffers scope)
13081 (while (setq file (pop scope))
13082 (with-current-buffer (org-find-base-buffer-visiting file)
13083 (save-excursion
13084 (save-restriction
13085 (widen)
13086 (goto-char (point-min))
13087 (setq res (append res (org-scan-tags func matcher))))))))))
13088 res))
13090 ;;;; Properties
13092 ;;; Setting and retrieving properties
13094 (defconst org-special-properties
13095 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13096 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13097 "The special properties valid in Org-mode.
13099 These are properties that are not defined in the property drawer,
13100 but in some other way.")
13102 (defconst org-default-properties
13103 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13104 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13105 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13106 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13107 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13108 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13109 "Some properties that are used by Org-mode for various purposes.
13110 Being in this list makes sure that they are offered for completion.")
13112 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13113 "Regular expression matching the first line of a property drawer.")
13115 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13116 "Regular expression matching the last line of a property drawer.")
13118 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13119 "Regular expression matching the first line of a property drawer.")
13121 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13122 "Regular expression matching the first line of a property drawer.")
13124 (defconst org-property-drawer-re
13125 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13126 org-property-end-re "\\)\n?")
13127 "Matches an entire property drawer.")
13129 (defconst org-clock-drawer-re
13130 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13131 org-property-end-re "\\)\n?")
13132 "Matches an entire clock drawer.")
13134 (defun org-property-action ()
13135 "Do an action on properties."
13136 (interactive)
13137 (let (c)
13138 (org-at-property-p)
13139 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13140 (setq c (read-char-exclusive))
13141 (cond
13142 ((equal c ?s)
13143 (call-interactively 'org-set-property))
13144 ((equal c ?d)
13145 (call-interactively 'org-delete-property))
13146 ((equal c ?D)
13147 (call-interactively 'org-delete-property-globally))
13148 ((equal c ?c)
13149 (call-interactively 'org-compute-property-at-point))
13150 (t (error "No such property action %c" c)))))
13152 (defun org-set-effort (&optional value)
13153 "Set the effort property of the current entry.
13154 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13155 allowed value."
13156 (interactive "P")
13157 (if (equal value 0) (setq value 10))
13158 (let* ((completion-ignore-case t)
13159 (prop org-effort-property)
13160 (cur (org-entry-get nil prop))
13161 (allowed (org-property-get-allowed-values nil prop 'table))
13162 (existing (mapcar 'list (org-property-values prop)))
13164 (val (cond
13165 ((stringp value) value)
13166 ((and allowed (integerp value))
13167 (or (car (nth (1- value) allowed))
13168 (car (org-last allowed))))
13169 (allowed
13170 (message "Select 1-9,0, [RET%s]: %s"
13171 (if cur (concat "=" cur) "")
13172 (mapconcat 'car allowed " "))
13173 (setq rpl (read-char-exclusive))
13174 (if (equal rpl ?\r)
13176 (setq rpl (- rpl ?0))
13177 (if (equal rpl 0) (setq rpl 10))
13178 (if (and (> rpl 0) (<= rpl (length allowed)))
13179 (car (nth (1- rpl) allowed))
13180 (org-completing-read "Effort: " allowed nil))))
13182 (let (org-completion-use-ido org-completion-use-iswitchb)
13183 (org-completing-read
13184 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13185 (concat "[" cur "]") "")
13186 ": ")
13187 existing nil nil "" nil cur))))))
13188 (unless (equal (org-entry-get nil prop) val)
13189 (org-entry-put nil prop val))
13190 (message "%s is now %s" prop val)))
13192 (defun org-at-property-p ()
13193 "Is cursor inside a property drawer?"
13194 (save-excursion
13195 (beginning-of-line 1)
13196 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13197 (let ((match (match-data)) ;; Keep match-data for use by calling
13198 (p (point)) ;; procedures.
13199 (range (unless (org-before-first-heading-p)
13200 (org-get-property-block))))
13201 (prog1 (and range (<= (car range) p) (< p (cdr range)))
13202 (set-match-data match))))))
13204 (defun org-get-property-block (&optional beg end force)
13205 "Return the (beg . end) range of the body of the property drawer.
13206 BEG and END can be beginning and end of subtree, if not given
13207 they will be found.
13208 If the drawer does not exist and FORCE is non-nil, create the drawer."
13209 (catch 'exit
13210 (save-excursion
13211 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13212 (end (or end (progn (outline-next-heading) (point)))))
13213 (goto-char beg)
13214 (if (re-search-forward org-property-start-re end t)
13215 (setq beg (1+ (match-end 0)))
13216 (if force
13217 (save-excursion
13218 (org-insert-property-drawer)
13219 (setq end (progn (outline-next-heading) (point))))
13220 (throw 'exit nil))
13221 (goto-char beg)
13222 (if (re-search-forward org-property-start-re end t)
13223 (setq beg (1+ (match-end 0)))))
13224 (if (re-search-forward org-property-end-re end t)
13225 (setq end (match-beginning 0))
13226 (or force (throw 'exit nil))
13227 (goto-char beg)
13228 (setq end beg)
13229 (org-indent-line-function)
13230 (insert ":END:\n"))
13231 (cons beg end)))))
13233 (defun org-entry-properties (&optional pom which specific)
13234 "Get all properties of the entry at point-or-marker POM.
13235 This includes the TODO keyword, the tags, time strings for deadline,
13236 scheduled, and clocking, and any additional properties defined in the
13237 entry. The return value is an alist, keys may occur multiple times
13238 if the property key was used several times.
13239 POM may also be nil, in which case the current entry is used.
13240 If WHICH is nil or `all', get all properties. If WHICH is
13241 `special' or `standard', only get that subclass. If WHICH
13242 is a string only get exactly this property. Specific can be a string, the
13243 specific property we are interested in. Specifying it can speed
13244 things up because then unnecessary parsing is avoided."
13245 (setq which (or which 'all))
13246 (org-with-point-at pom
13247 (let ((clockstr (substring org-clock-string 0 -1))
13248 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13249 (case-fold-search nil)
13250 beg end range props sum-props key value string clocksum)
13251 (save-excursion
13252 (when (condition-case nil
13253 (and (org-mode-p) (org-back-to-heading t))
13254 (error nil))
13255 (setq beg (point))
13256 (setq sum-props (get-text-property (point) 'org-summaries))
13257 (setq clocksum (get-text-property (point) :org-clock-minutes))
13258 (outline-next-heading)
13259 (setq end (point))
13260 (when (memq which '(all special))
13261 ;; Get the special properties, like TODO and tags
13262 (goto-char beg)
13263 (when (and (or (not specific) (string= specific "TODO"))
13264 (looking-at org-todo-line-regexp) (match-end 2))
13265 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13266 (when (and (or (not specific) (string= specific "PRIORITY"))
13267 (looking-at org-priority-regexp))
13268 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13269 (when (and (or (not specific) (string= specific "TAGS"))
13270 (setq value (org-get-tags-string))
13271 (string-match "\\S-" value))
13272 (push (cons "TAGS" value) props))
13273 (when (and (or (not specific) (string= specific "ALLTAGS"))
13274 (setq value (org-get-tags-at)))
13275 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13276 ":"))
13277 props))
13278 (when (or (not specific) (string= specific "BLOCKED"))
13279 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13280 (when (or (not specific)
13281 (member specific org-all-time-keywords)
13282 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
13283 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13284 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
13285 string (if (equal key clockstr)
13286 (org-no-properties
13287 (org-trim
13288 (buffer-substring
13289 (match-beginning 3) (goto-char (point-at-eol)))))
13290 (substring (org-match-string-no-properties 3) 1 -1)))
13291 (unless key
13292 (if (= (char-after (match-beginning 3)) ?\[)
13293 (setq key "TIMESTAMP_IA")
13294 (setq key "TIMESTAMP")))
13295 (when (or (equal key clockstr) (not (assoc key props)))
13296 (push (cons key string) props))))
13300 (when (memq which '(all standard))
13301 ;; Get the standard properties, like :PROP: ...
13302 (setq range (org-get-property-block beg end))
13303 (when range
13304 (goto-char (car range))
13305 (while (re-search-forward
13306 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13307 (cdr range) t)
13308 (setq key (org-match-string-no-properties 1)
13309 value (org-trim (or (org-match-string-no-properties 2) "")))
13310 (unless (member key excluded)
13311 (push (cons key (or value "")) props)))))
13312 (if clocksum
13313 (push (cons "CLOCKSUM"
13314 (org-columns-number-to-string (/ (float clocksum) 60.)
13315 'add_times))
13316 props))
13317 (unless (assoc "CATEGORY" props)
13318 (setq value (or (org-get-category)
13319 (progn (org-refresh-category-properties)
13320 (org-get-category))))
13321 (push (cons "CATEGORY" value) props))
13322 (append sum-props (nreverse props)))))))
13324 (defun org-entry-get (pom property &optional inherit)
13325 "Get value of PROPERTY for entry at point-or-marker POM.
13326 If INHERIT is non-nil and the entry does not have the property,
13327 then also check higher levels of the hierarchy.
13328 If INHERIT is the symbol `selective', use inheritance only if the setting
13329 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13330 If the property is present but empty, the return value is the empty string.
13331 If the property is not present at all, nil is returned."
13332 (org-with-point-at pom
13333 (if (and inherit (if (eq inherit 'selective)
13334 (org-property-inherit-p property)
13336 (org-entry-get-with-inheritance property)
13337 (if (member property org-special-properties)
13338 ;; We need a special property. Use `org-entry-properties' to
13339 ;; retrieve it, but specify the wanted property
13340 (cdr (assoc property (org-entry-properties nil 'special property)))
13341 (let ((range (org-get-property-block)))
13342 (if (and range
13343 (goto-char (car range))
13344 (re-search-forward
13345 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13346 (cdr range) t))
13347 ;; Found the property, return it.
13348 (if (match-end 1)
13349 (org-match-string-no-properties 1)
13350 "")))))))
13352 (defun org-property-or-variable-value (var &optional inherit)
13353 "Check if there is a property fixing the value of VAR.
13354 If yes, return this value. If not, return the current value of the variable."
13355 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13356 (if (and prop (stringp prop) (string-match "\\S-" prop))
13357 (read prop)
13358 (symbol-value var))))
13360 (defun org-entry-delete (pom property)
13361 "Delete the property PROPERTY from entry at point-or-marker POM."
13362 (org-with-point-at pom
13363 (if (member property org-special-properties)
13364 nil ; cannot delete these properties.
13365 (let ((range (org-get-property-block)))
13366 (if (and range
13367 (goto-char (car range))
13368 (re-search-forward
13369 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13370 (cdr range) t))
13371 (progn
13372 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13374 nil)))))
13376 ;; Multi-values properties are properties that contain multiple values
13377 ;; These values are assumed to be single words, separated by whitespace.
13378 (defun org-entry-add-to-multivalued-property (pom property value)
13379 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13380 (let* ((old (org-entry-get pom property))
13381 (values (and old (org-split-string old "[ \t]"))))
13382 (setq value (org-entry-protect-space value))
13383 (unless (member value values)
13384 (setq values (cons value values))
13385 (org-entry-put pom property
13386 (mapconcat 'identity values " ")))))
13388 (defun org-entry-remove-from-multivalued-property (pom property value)
13389 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13390 (let* ((old (org-entry-get pom property))
13391 (values (and old (org-split-string old "[ \t]"))))
13392 (setq value (org-entry-protect-space value))
13393 (when (member value values)
13394 (setq values (delete value values))
13395 (org-entry-put pom property
13396 (mapconcat 'identity values " ")))))
13398 (defun org-entry-member-in-multivalued-property (pom property value)
13399 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13400 (let* ((old (org-entry-get pom property))
13401 (values (and old (org-split-string old "[ \t]"))))
13402 (setq value (org-entry-protect-space value))
13403 (member value values)))
13405 (defun org-entry-get-multivalued-property (pom property)
13406 "Return a list of values in a multivalued property."
13407 (let* ((value (org-entry-get pom property))
13408 (values (and value (org-split-string value "[ \t]"))))
13409 (mapcar 'org-entry-restore-space values)))
13411 (defun org-entry-put-multivalued-property (pom property &rest values)
13412 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13413 VALUES should be a list of strings. Spaces will be protected."
13414 (org-entry-put pom property
13415 (mapconcat 'org-entry-protect-space values " "))
13416 (let* ((value (org-entry-get pom property))
13417 (values (and value (org-split-string value "[ \t]"))))
13418 (mapcar 'org-entry-restore-space values)))
13420 (defun org-entry-protect-space (s)
13421 "Protect spaces and newline in string S."
13422 (while (string-match " " s)
13423 (setq s (replace-match "%20" t t s)))
13424 (while (string-match "\n" s)
13425 (setq s (replace-match "%0A" t t s)))
13428 (defun org-entry-restore-space (s)
13429 "Restore spaces and newline in string S."
13430 (while (string-match "%20" s)
13431 (setq s (replace-match " " t t s)))
13432 (while (string-match "%0A" s)
13433 (setq s (replace-match "\n" t t s)))
13436 (defvar org-entry-property-inherited-from (make-marker)
13437 "Marker pointing to the entry from where a property was inherited.
13438 Each call to `org-entry-get-with-inheritance' will set this marker to the
13439 location of the entry where the inheritance search matched. If there was
13440 no match, the marker will point nowhere.
13441 Note that also `org-entry-get' calls this function, if the INHERIT flag
13442 is set.")
13444 (defun org-entry-get-with-inheritance (property)
13445 "Get entry property, and search higher levels if not present."
13446 (move-marker org-entry-property-inherited-from nil)
13447 (let (tmp)
13448 (save-excursion
13449 (save-restriction
13450 (widen)
13451 (catch 'ex
13452 (while t
13453 (when (setq tmp (org-entry-get nil property))
13454 (org-back-to-heading t)
13455 (move-marker org-entry-property-inherited-from (point))
13456 (throw 'ex tmp))
13457 (or (org-up-heading-safe) (throw 'ex nil)))))
13458 (or tmp
13459 (cdr (assoc property org-file-properties))
13460 (cdr (assoc property org-global-properties))
13461 (cdr (assoc property org-global-properties-fixed))))))
13463 (defvar org-property-changed-functions nil
13464 "Hook called when the value of a property has changed.
13465 Each hook function should accept two arguments, the name of the property
13466 and the new value.")
13468 (defun org-entry-put (pom property value)
13469 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13470 (org-with-point-at pom
13471 (org-back-to-heading t)
13472 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13473 range)
13474 (cond
13475 ((equal property "TODO")
13476 (when (and (stringp value) (string-match "\\S-" value)
13477 (not (member value org-todo-keywords-1)))
13478 (error "\"%s\" is not a valid TODO state" value))
13479 (if (or (not value)
13480 (not (string-match "\\S-" value)))
13481 (setq value 'none))
13482 (org-todo value)
13483 (org-set-tags nil 'align))
13484 ((equal property "PRIORITY")
13485 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13486 (string-to-char value) ?\ ))
13487 (org-set-tags nil 'align))
13488 ((equal property "SCHEDULED")
13489 (if (re-search-forward org-scheduled-time-regexp end t)
13490 (cond
13491 ((eq value 'earlier) (org-timestamp-change -1 'day))
13492 ((eq value 'later) (org-timestamp-change 1 'day))
13493 (t (call-interactively 'org-schedule)))
13494 (call-interactively 'org-schedule)))
13495 ((equal property "DEADLINE")
13496 (if (re-search-forward org-deadline-time-regexp end t)
13497 (cond
13498 ((eq value 'earlier) (org-timestamp-change -1 'day))
13499 ((eq value 'later) (org-timestamp-change 1 'day))
13500 (t (call-interactively 'org-deadline)))
13501 (call-interactively 'org-deadline)))
13502 ((member property org-special-properties)
13503 (error "The %s property can not yet be set with `org-entry-put'"
13504 property))
13505 (t ; a non-special property
13506 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13507 (setq range (org-get-property-block beg end 'force))
13508 (goto-char (car range))
13509 (if (re-search-forward
13510 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13511 (progn
13512 (delete-region (match-beginning 1) (match-end 1))
13513 (goto-char (match-beginning 1)))
13514 (goto-char (cdr range))
13515 (insert "\n")
13516 (backward-char 1)
13517 (org-indent-line-function)
13518 (insert ":" property ":"))
13519 (and value (insert " " value))
13520 (org-indent-line-function)))))
13521 (run-hook-with-args 'org-property-changed-functions property value)))
13523 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13524 "Get all property keys in the current buffer.
13525 With INCLUDE-SPECIALS, also list the special properties that reflect things
13526 like tags and TODO state.
13527 With INCLUDE-DEFAULTS, also include properties that has special meaning
13528 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13529 With INCLUDE-COLUMNS, also include property names given in COLUMN
13530 formats in the current buffer."
13531 (let (rtn range cfmt s p)
13532 (save-excursion
13533 (save-restriction
13534 (widen)
13535 (goto-char (point-min))
13536 (while (re-search-forward org-property-start-re nil t)
13537 (setq range (org-get-property-block))
13538 (goto-char (car range))
13539 (while (re-search-forward
13540 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13541 (cdr range) t)
13542 (add-to-list 'rtn (org-match-string-no-properties 1)))
13543 (outline-next-heading))))
13545 (when include-specials
13546 (setq rtn (append org-special-properties rtn)))
13548 (when include-defaults
13549 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13550 (add-to-list 'rtn org-effort-property))
13552 (when include-columns
13553 (save-excursion
13554 (save-restriction
13555 (widen)
13556 (goto-char (point-min))
13557 (while (re-search-forward
13558 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13559 nil t)
13560 (setq cfmt (match-string 2) s 0)
13561 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13562 cfmt s)
13563 (setq s (match-end 0)
13564 p (match-string 1 cfmt))
13565 (unless (or (equal p "ITEM")
13566 (member p org-special-properties))
13567 (add-to-list 'rtn (match-string 1 cfmt))))))))
13569 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13571 (defun org-property-values (key)
13572 "Return a list of all values of property KEY."
13573 (save-excursion
13574 (save-restriction
13575 (widen)
13576 (goto-char (point-min))
13577 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13578 values)
13579 (while (re-search-forward re nil t)
13580 (add-to-list 'values (org-trim (match-string 1))))
13581 (delete "" values)))))
13583 (defun org-insert-property-drawer ()
13584 "Insert a property drawer into the current entry."
13585 (interactive)
13586 (org-back-to-heading t)
13587 (looking-at outline-regexp)
13588 (let ((indent (if org-adapt-indentation
13589 (- (match-end 0)(match-beginning 0))
13591 (beg (point))
13592 (re (concat "^[ \t]*" org-keyword-time-regexp))
13593 end hiddenp)
13594 (outline-next-heading)
13595 (setq end (point))
13596 (goto-char beg)
13597 (while (re-search-forward re end t))
13598 (setq hiddenp (org-invisible-p))
13599 (end-of-line 1)
13600 (and (equal (char-after) ?\n) (forward-char 1))
13601 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13602 (if (member (match-string 1) '("CLOCK:" ":END:"))
13603 ;; just skip this line
13604 (beginning-of-line 2)
13605 ;; Drawer start, find the end
13606 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13607 (beginning-of-line 1)))
13608 (org-skip-over-state-notes)
13609 (skip-chars-backward " \t\n\r")
13610 (if (eq (char-before) ?*) (forward-char 1))
13611 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13612 (beginning-of-line 0)
13613 (org-indent-to-column indent)
13614 (beginning-of-line 2)
13615 (org-indent-to-column indent)
13616 (beginning-of-line 0)
13617 (if hiddenp
13618 (save-excursion
13619 (org-back-to-heading t)
13620 (hide-entry))
13621 (org-flag-drawer t))))
13623 (defun org-set-property (property value)
13624 "In the current entry, set PROPERTY to VALUE.
13625 When called interactively, this will prompt for a property name, offering
13626 completion on existing and default properties. And then it will prompt
13627 for a value, offering completion either on allowed values (via an inherited
13628 xxx_ALL property) or on existing values in other instances of this property
13629 in the current file."
13630 (interactive
13631 (let* ((completion-ignore-case t)
13632 (keys (org-buffer-property-keys nil t t))
13633 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13634 (prop (if (member prop0 keys)
13635 prop0
13636 (or (cdr (assoc (downcase prop0)
13637 (mapcar (lambda (x) (cons (downcase x) x))
13638 keys)))
13639 prop0)))
13640 (cur (org-entry-get nil prop))
13641 (prompt (concat prop " value"
13642 (if (and cur (string-match "\\S-" cur))
13643 (concat " [" cur "]") "") ": "))
13644 (allowed (org-property-get-allowed-values nil prop 'table))
13645 (existing (mapcar 'list (org-property-values prop)))
13646 (val (if allowed
13647 (org-completing-read prompt allowed nil
13648 (not (get-text-property 0 'org-unrestricted
13649 (caar allowed))))
13650 (let (org-completion-use-ido org-completion-use-iswitchb)
13651 (org-completing-read prompt existing nil nil "" nil cur)))))
13652 (list prop (if (equal val "") cur val))))
13653 (unless (equal (org-entry-get nil property) value)
13654 (org-entry-put nil property value)))
13656 (defun org-delete-property (property)
13657 "In the current entry, delete PROPERTY."
13658 (interactive
13659 (let* ((completion-ignore-case t)
13660 (prop (org-icompleting-read "Property: "
13661 (org-entry-properties nil 'standard))))
13662 (list prop)))
13663 (message "Property %s %s" property
13664 (if (org-entry-delete nil property)
13665 "deleted"
13666 "was not present in the entry")))
13668 (defun org-delete-property-globally (property)
13669 "Remove PROPERTY globally, from all entries."
13670 (interactive
13671 (let* ((completion-ignore-case t)
13672 (prop (org-icompleting-read
13673 "Globally remove property: "
13674 (mapcar 'list (org-buffer-property-keys)))))
13675 (list prop)))
13676 (save-excursion
13677 (save-restriction
13678 (widen)
13679 (goto-char (point-min))
13680 (let ((cnt 0))
13681 (while (re-search-forward
13682 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13683 nil t)
13684 (setq cnt (1+ cnt))
13685 (replace-match ""))
13686 (message "Property \"%s\" removed from %d entries" property cnt)))))
13688 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13690 (defun org-compute-property-at-point ()
13691 "Compute the property at point.
13692 This looks for an enclosing column format, extracts the operator and
13693 then applies it to the property in the column format's scope."
13694 (interactive)
13695 (unless (org-at-property-p)
13696 (error "Not at a property"))
13697 (let ((prop (org-match-string-no-properties 2)))
13698 (org-columns-get-format-and-top-level)
13699 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13700 (error "No operator defined for property %s" prop))
13701 (org-columns-compute prop)))
13703 (defvar org-property-allowed-value-functions nil
13704 "Hook for functions supplying allowed values for a specific property.
13705 The functions must take a single argument, the name of the property, and
13706 return a flat list of allowed values. If \":ETC\" is one of
13707 the values, this means that these values are intended as defaults for
13708 completion, but that other values should be allowed too.
13709 The functions must return nil if they are not responsible for this
13710 property.")
13712 (defun org-property-get-allowed-values (pom property &optional table)
13713 "Get allowed values for the property PROPERTY.
13714 When TABLE is non-nil, return an alist that can directly be used for
13715 completion."
13716 (let (vals)
13717 (cond
13718 ((equal property "TODO")
13719 (setq vals (org-with-point-at pom
13720 (append org-todo-keywords-1 '("")))))
13721 ((equal property "PRIORITY")
13722 (let ((n org-lowest-priority))
13723 (while (>= n org-highest-priority)
13724 (push (char-to-string n) vals)
13725 (setq n (1- n)))))
13726 ((member property org-special-properties))
13727 ((setq vals (run-hook-with-args-until-success
13728 'org-property-allowed-value-functions property)))
13730 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13731 (when (and vals (string-match "\\S-" vals))
13732 (setq vals (car (read-from-string (concat "(" vals ")"))))
13733 (setq vals (mapcar (lambda (x)
13734 (cond ((stringp x) x)
13735 ((numberp x) (number-to-string x))
13736 ((symbolp x) (symbol-name x))
13737 (t "???")))
13738 vals)))))
13739 (when (member ":ETC" vals)
13740 (setq vals (remove ":ETC" vals))
13741 (org-add-props (car vals) '(org-unrestricted t)))
13742 (if table (mapcar 'list vals) vals)))
13744 (defun org-property-previous-allowed-value (&optional previous)
13745 "Switch to the next allowed value for this property."
13746 (interactive)
13747 (org-property-next-allowed-value t))
13749 (defun org-property-next-allowed-value (&optional previous)
13750 "Switch to the next allowed value for this property."
13751 (interactive)
13752 (unless (org-at-property-p)
13753 (error "Not at a property"))
13754 (let* ((key (match-string 2))
13755 (value (match-string 3))
13756 (allowed (or (org-property-get-allowed-values (point) key)
13757 (and (member value '("[ ]" "[-]" "[X]"))
13758 '("[ ]" "[X]"))))
13759 nval)
13760 (unless allowed
13761 (error "Allowed values for this property have not been defined"))
13762 (if previous (setq allowed (reverse allowed)))
13763 (if (member value allowed)
13764 (setq nval (car (cdr (member value allowed)))))
13765 (setq nval (or nval (car allowed)))
13766 (if (equal nval value)
13767 (error "Only one allowed value for this property"))
13768 (org-at-property-p)
13769 (replace-match (concat " :" key ": " nval) t t)
13770 (org-indent-line-function)
13771 (beginning-of-line 1)
13772 (skip-chars-forward " \t")
13773 (run-hook-with-args 'org-property-changed-functions key nval)))
13775 (defun org-find-olp (path)
13776 "Return a marker pointing to the entry at outline path OLP.
13777 If anything goes wrong, throw an error.
13778 You can wrap this call to cathc the error like this:
13780 (condition-case msg
13781 (org-mobile-locate-entry (match-string 4))
13782 (error (nth 1 msg)))
13784 The return value will then be either a string with the error message,
13785 or a marker if everyhing is OK."
13786 (let* ((file (pop path))
13787 (buffer (find-file-noselect file))
13788 (level 1)
13789 (lmin 1)
13790 (lmax 1)
13791 limit re end found pos heading cnt)
13792 (unless buffer (error "File not found :%s" file))
13793 (with-current-buffer buffer
13794 (save-excursion
13795 (save-restriction
13796 (widen)
13797 (setq limit (point-max))
13798 (goto-char (point-min))
13799 (while (setq heading (pop path))
13800 (setq re (format org-complex-heading-regexp-format
13801 (regexp-quote heading)))
13802 (setq cnt 0 pos (point))
13803 (while (re-search-forward re end t)
13804 (setq level (- (match-end 1) (match-beginning 1)))
13805 (if (and (>= level lmin) (<= level lmax))
13806 (setq found (match-beginning 0) cnt (1+ cnt))))
13807 (when (= cnt 0) (error "Heading not found on level %d: %s"
13808 lmax heading))
13809 (when (> cnt 1) (error "Heading not unique on level %d: %s"
13810 lmax heading))
13811 (goto-char found)
13812 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
13813 (setq end (save-excursion (org-end-of-subtree t t))))
13814 (when (org-on-heading-p)
13815 (move-marker (make-marker) (point))))))))
13817 (defun org-find-entry-with-id (ident)
13818 "Locate the entry that contains the ID property with exact value IDENT.
13819 IDENT can be a string, a symbol or a number, this function will search for
13820 the string representation of it.
13821 Return the position where this entry starts, or nil if there is no such entry."
13822 (interactive "sID: ")
13823 (let ((id (cond
13824 ((stringp ident) ident)
13825 ((symbol-name ident) (symbol-name ident))
13826 ((numberp ident) (number-to-string ident))
13827 (t (error "IDENT %s must be a string, symbol or number" ident))))
13828 (case-fold-search nil))
13829 (save-excursion
13830 (save-restriction
13831 (widen)
13832 (goto-char (point-min))
13833 (when (re-search-forward
13834 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13835 nil t)
13836 (org-back-to-heading t)
13837 (point))))))
13839 ;;;; Timestamps
13841 (defvar org-last-changed-timestamp nil)
13842 (defvar org-last-inserted-timestamp nil
13843 "The last time stamp inserted with `org-insert-time-stamp'.")
13844 (defvar org-time-was-given) ; dynamically scoped parameter
13845 (defvar org-end-time-was-given) ; dynamically scoped parameter
13846 (defvar org-ts-what) ; dynamically scoped parameter
13848 (defun org-time-stamp (arg &optional inactive)
13849 "Prompt for a date/time and insert a time stamp.
13850 If the user specifies a time like HH:MM, or if this command is called
13851 with a prefix argument, the time stamp will contain date and time.
13852 Otherwise, only the date will be included. All parts of a date not
13853 specified by the user will be filled in from the current date/time.
13854 So if you press just return without typing anything, the time stamp
13855 will represent the current date/time. If there is already a timestamp
13856 at the cursor, it will be modified."
13857 (interactive "P")
13858 (let* ((ts nil)
13859 (default-time
13860 ;; Default time is either today, or, when entering a range,
13861 ;; the range start.
13862 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13863 (save-excursion
13864 (re-search-backward
13865 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13866 (- (point) 20) t)))
13867 (apply 'encode-time (org-parse-time-string (match-string 1)))
13868 (current-time)))
13869 (default-input (and ts (org-get-compact-tod ts)))
13870 org-time-was-given org-end-time-was-given time)
13871 (cond
13872 ((and (org-at-timestamp-p t)
13873 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13874 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13875 (insert "--")
13876 (setq time (let ((this-command this-command))
13877 (org-read-date arg 'totime nil nil
13878 default-time default-input)))
13879 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13880 ((org-at-timestamp-p t)
13881 (setq time (let ((this-command this-command))
13882 (org-read-date arg 'totime nil nil default-time default-input)))
13883 (when (org-at-timestamp-p t) ; just to get the match data
13884 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13885 (replace-match "")
13886 (setq org-last-changed-timestamp
13887 (org-insert-time-stamp
13888 time (or org-time-was-given arg)
13889 inactive nil nil (list org-end-time-was-given))))
13890 (message "Timestamp updated"))
13892 (setq time (let ((this-command this-command))
13893 (org-read-date arg 'totime nil nil default-time default-input)))
13894 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13895 nil nil (list org-end-time-was-given))))))
13897 ;; FIXME: can we use this for something else, like computing time differences?
13898 (defun org-get-compact-tod (s)
13899 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13900 (let* ((t1 (match-string 1 s))
13901 (h1 (string-to-number (match-string 2 s)))
13902 (m1 (string-to-number (match-string 3 s)))
13903 (t2 (and (match-end 4) (match-string 5 s)))
13904 (h2 (and t2 (string-to-number (match-string 6 s))))
13905 (m2 (and t2 (string-to-number (match-string 7 s))))
13906 dh dm)
13907 (if (not t2)
13909 (setq dh (- h2 h1) dm (- m2 m1))
13910 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13911 (concat t1 "+" (number-to-string dh)
13912 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13914 (defun org-time-stamp-inactive (&optional arg)
13915 "Insert an inactive time stamp.
13916 An inactive time stamp is enclosed in square brackets instead of angle
13917 brackets. It is inactive in the sense that it does not trigger agenda entries,
13918 does not link to the calendar and cannot be changed with the S-cursor keys.
13919 So these are more for recording a certain time/date."
13920 (interactive "P")
13921 (org-time-stamp arg 'inactive))
13923 (defvar org-date-ovl (make-overlay 1 1))
13924 (overlay-put org-date-ovl 'face 'org-warning)
13925 (org-detach-overlay org-date-ovl)
13927 (defvar org-ans1) ; dynamically scoped parameter
13928 (defvar org-ans2) ; dynamically scoped parameter
13930 (defvar org-plain-time-of-day-regexp) ; defined below
13932 (defvar org-overriding-default-time nil) ; dynamically scoped
13933 (defvar org-read-date-overlay nil)
13934 (defvar org-dcst nil) ; dynamically scoped
13935 (defvar org-read-date-history nil)
13936 (defvar org-read-date-final-answer nil)
13938 (defun org-read-date (&optional with-time to-time from-string prompt
13939 default-time default-input)
13940 "Read a date, possibly a time, and make things smooth for the user.
13941 The prompt will suggest to enter an ISO date, but you can also enter anything
13942 which will at least partially be understood by `parse-time-string'.
13943 Unrecognized parts of the date will default to the current day, month, year,
13944 hour and minute. If this command is called to replace a timestamp at point,
13945 of to enter the second timestamp of a range, the default time is taken from the
13946 existing stamp. For example,
13947 3-2-5 --> 2003-02-05
13948 feb 15 --> currentyear-02-15
13949 sep 12 9 --> 2009-09-12
13950 12:45 --> today 12:45
13951 22 sept 0:34 --> currentyear-09-22 0:34
13952 12 --> currentyear-currentmonth-12
13953 Fri --> nearest Friday (today or later)
13954 etc.
13956 Furthermore you can specify a relative date by giving, as the *first* thing
13957 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13958 change in days weeks, months, years.
13959 With a single plus or minus, the date is relative to today. With a double
13960 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13961 +4d --> four days from today
13962 +4 --> same as above
13963 +2w --> two weeks from today
13964 ++5 --> five days from default date
13966 The function understands only English month and weekday abbreviations,
13967 but this can be configured with the variables `parse-time-months' and
13968 `parse-time-weekdays'.
13970 While prompting, a calendar is popped up - you can also select the
13971 date with the mouse (button 1). The calendar shows a period of three
13972 months. To scroll it to other months, use the keys `>' and `<'.
13973 If you don't like the calendar, turn it off with
13974 \(setq org-read-date-popup-calendar nil)
13976 With optional argument TO-TIME, the date will immediately be converted
13977 to an internal time.
13978 With an optional argument WITH-TIME, the prompt will suggest to also
13979 insert a time. Note that when WITH-TIME is not set, you can still
13980 enter a time, and this function will inform the calling routine about
13981 this change. The calling routine may then choose to change the format
13982 used to insert the time stamp into the buffer to include the time.
13983 With optional argument FROM-STRING, read from this string instead from
13984 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13985 the time/date that is used for everything that is not specified by the
13986 user."
13987 (require 'parse-time)
13988 (let* ((org-time-stamp-rounding-minutes
13989 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13990 (org-dcst org-display-custom-times)
13991 (ct (org-current-time))
13992 (def (or org-overriding-default-time default-time ct))
13993 (defdecode (decode-time def))
13994 (dummy (progn
13995 (when (< (nth 2 defdecode) org-extend-today-until)
13996 (setcar (nthcdr 2 defdecode) -1)
13997 (setcar (nthcdr 1 defdecode) 59)
13998 (setq def (apply 'encode-time defdecode)
13999 defdecode (decode-time def)))))
14000 (calendar-frame-setup nil)
14001 (calendar-move-hook nil)
14002 (calendar-view-diary-initially-flag nil)
14003 (calendar-view-holidays-initially-flag nil)
14004 (timestr (format-time-string
14005 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14006 (prompt (concat (if prompt (concat prompt " ") "")
14007 (format "Date+time [%s]: " timestr)))
14008 ans (org-ans0 "") org-ans1 org-ans2 final)
14010 (cond
14011 (from-string (setq ans from-string))
14012 (org-read-date-popup-calendar
14013 (save-excursion
14014 (save-window-excursion
14015 (calendar)
14016 (calendar-forward-day (- (time-to-days def)
14017 (calendar-absolute-from-gregorian
14018 (calendar-current-date))))
14019 (org-eval-in-calendar nil t)
14020 (let* ((old-map (current-local-map))
14021 (map (copy-keymap calendar-mode-map))
14022 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14023 (org-defkey map (kbd "RET") 'org-calendar-select)
14024 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14025 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14026 (org-defkey minibuffer-local-map [(meta shift left)]
14027 (lambda () (interactive)
14028 (org-eval-in-calendar '(calendar-backward-month 1))))
14029 (org-defkey minibuffer-local-map [(meta shift right)]
14030 (lambda () (interactive)
14031 (org-eval-in-calendar '(calendar-forward-month 1))))
14032 (org-defkey minibuffer-local-map [(meta shift up)]
14033 (lambda () (interactive)
14034 (org-eval-in-calendar '(calendar-backward-year 1))))
14035 (org-defkey minibuffer-local-map [(meta shift down)]
14036 (lambda () (interactive)
14037 (org-eval-in-calendar '(calendar-forward-year 1))))
14038 (org-defkey minibuffer-local-map [?\e (shift left)]
14039 (lambda () (interactive)
14040 (org-eval-in-calendar '(calendar-backward-month 1))))
14041 (org-defkey minibuffer-local-map [?\e (shift right)]
14042 (lambda () (interactive)
14043 (org-eval-in-calendar '(calendar-forward-month 1))))
14044 (org-defkey minibuffer-local-map [?\e (shift up)]
14045 (lambda () (interactive)
14046 (org-eval-in-calendar '(calendar-backward-year 1))))
14047 (org-defkey minibuffer-local-map [?\e (shift down)]
14048 (lambda () (interactive)
14049 (org-eval-in-calendar '(calendar-forward-year 1))))
14050 (org-defkey minibuffer-local-map [(shift up)]
14051 (lambda () (interactive)
14052 (org-eval-in-calendar '(calendar-backward-week 1))))
14053 (org-defkey minibuffer-local-map [(shift down)]
14054 (lambda () (interactive)
14055 (org-eval-in-calendar '(calendar-forward-week 1))))
14056 (org-defkey minibuffer-local-map [(shift left)]
14057 (lambda () (interactive)
14058 (org-eval-in-calendar '(calendar-backward-day 1))))
14059 (org-defkey minibuffer-local-map [(shift right)]
14060 (lambda () (interactive)
14061 (org-eval-in-calendar '(calendar-forward-day 1))))
14062 (org-defkey minibuffer-local-map ">"
14063 (lambda () (interactive)
14064 (org-eval-in-calendar '(scroll-calendar-left 1))))
14065 (org-defkey minibuffer-local-map "<"
14066 (lambda () (interactive)
14067 (org-eval-in-calendar '(scroll-calendar-right 1))))
14068 (org-defkey minibuffer-local-map "\C-v"
14069 (lambda () (interactive)
14070 (org-eval-in-calendar
14071 '(calendar-scroll-left-three-months 1))))
14072 (org-defkey minibuffer-local-map "\M-v"
14073 (lambda () (interactive)
14074 (org-eval-in-calendar
14075 '(calendar-scroll-right-three-months 1))))
14076 (run-hooks 'org-read-date-minibuffer-setup-hook)
14077 (unwind-protect
14078 (progn
14079 (use-local-map map)
14080 (add-hook 'post-command-hook 'org-read-date-display)
14081 (setq org-ans0 (read-string prompt default-input
14082 'org-read-date-history nil))
14083 ;; org-ans0: from prompt
14084 ;; org-ans1: from mouse click
14085 ;; org-ans2: from calendar motion
14086 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14087 (remove-hook 'post-command-hook 'org-read-date-display)
14088 (use-local-map old-map)
14089 (when org-read-date-overlay
14090 (delete-overlay org-read-date-overlay)
14091 (setq org-read-date-overlay nil)))))))
14093 (t ; Naked prompt only
14094 (unwind-protect
14095 (setq ans (read-string prompt default-input
14096 'org-read-date-history timestr))
14097 (when org-read-date-overlay
14098 (delete-overlay org-read-date-overlay)
14099 (setq org-read-date-overlay nil)))))
14101 (setq final (org-read-date-analyze ans def defdecode))
14102 (setq org-read-date-final-answer ans)
14104 (if to-time
14105 (apply 'encode-time final)
14106 (if (and (boundp 'org-time-was-given) org-time-was-given)
14107 (format "%04d-%02d-%02d %02d:%02d"
14108 (nth 5 final) (nth 4 final) (nth 3 final)
14109 (nth 2 final) (nth 1 final))
14110 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14112 (defvar def)
14113 (defvar defdecode)
14114 (defvar with-time)
14115 (defvar org-read-date-analyze-futurep nil)
14116 (defun org-read-date-display ()
14117 "Display the current date prompt interpretation in the minibuffer."
14118 (when org-read-date-display-live
14119 (when org-read-date-overlay
14120 (delete-overlay org-read-date-overlay))
14121 (let ((p (point)))
14122 (end-of-line 1)
14123 (while (not (equal (buffer-substring
14124 (max (point-min) (- (point) 4)) (point))
14125 " "))
14126 (insert " "))
14127 (goto-char p))
14128 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14129 " " (or org-ans1 org-ans2)))
14130 (org-end-time-was-given nil)
14131 (f (org-read-date-analyze ans def defdecode))
14132 (fmts (if org-dcst
14133 org-time-stamp-custom-formats
14134 org-time-stamp-formats))
14135 (fmt (if (or with-time
14136 (and (boundp 'org-time-was-given) org-time-was-given))
14137 (cdr fmts)
14138 (car fmts)))
14139 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14140 (when (and org-end-time-was-given
14141 (string-match org-plain-time-of-day-regexp txt))
14142 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14143 org-end-time-was-given
14144 (substring txt (match-end 0)))))
14145 (when org-read-date-analyze-futurep
14146 (setq txt (concat txt " (=>F)")))
14147 (setq org-read-date-overlay
14148 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14149 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14151 (defun org-read-date-analyze (ans def defdecode)
14152 "Analyse the combined answer of the date prompt."
14153 ;; FIXME: cleanup and comment
14154 (let ((nowdecode (decode-time (current-time)))
14155 delta deltan deltaw deltadef year month day
14156 hour minute second wday pm h2 m2 tl wday1
14157 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14158 (setq org-read-date-analyze-futurep nil)
14159 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14160 (setq ans "+0"))
14162 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14163 (setq ans (replace-match "" t t ans)
14164 deltan (car delta)
14165 deltaw (nth 1 delta)
14166 deltadef (nth 2 delta)))
14168 ;; Check if there is an iso week date in there
14169 ;; If yes, store the info and postpone interpreting it until the rest
14170 ;; of the parsing is done
14171 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14172 (setq iso-year (if (match-end 1)
14173 (org-small-year-to-year
14174 (string-to-number (match-string 1 ans))))
14175 iso-weekday (if (match-end 3)
14176 (string-to-number (match-string 3 ans)))
14177 iso-week (string-to-number (match-string 2 ans)))
14178 (setq ans (replace-match "" t t ans)))
14180 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14181 (when (string-match
14182 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14183 (setq year (if (match-end 2)
14184 (string-to-number (match-string 2 ans))
14185 (progn (setq kill-year t)
14186 (string-to-number (format-time-string "%Y"))))
14187 month (string-to-number (match-string 3 ans))
14188 day (string-to-number (match-string 4 ans)))
14189 (if (< year 100) (setq year (+ 2000 year)))
14190 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14191 t nil ans)))
14192 ;; Help matching american dates, like 5/30 or 5/30/7
14193 (when (string-match
14194 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14195 (setq year (if (match-end 4)
14196 (string-to-number (match-string 4 ans))
14197 (progn (setq kill-year t)
14198 (string-to-number (format-time-string "%Y"))))
14199 month (string-to-number (match-string 1 ans))
14200 day (string-to-number (match-string 2 ans)))
14201 (if (< year 100) (setq year (+ 2000 year)))
14202 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14203 t nil ans)))
14204 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14205 ;; If there is a time with am/pm, and *no* time without it, we convert
14206 ;; so that matching will be successful.
14207 (loop for i from 1 to 2 do ; twice, for end time as well
14208 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14209 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14210 (setq hour (string-to-number (match-string 1 ans))
14211 minute (if (match-end 3)
14212 (string-to-number (match-string 3 ans))
14214 pm (equal ?p
14215 (string-to-char (downcase (match-string 4 ans)))))
14216 (if (and (= hour 12) (not pm))
14217 (setq hour 0)
14218 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14219 (setq ans (replace-match (format "%02d:%02d" hour minute)
14220 t t ans))))
14222 ;; Check if a time range is given as a duration
14223 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14224 (setq hour (string-to-number (match-string 1 ans))
14225 h2 (+ hour (string-to-number (match-string 3 ans)))
14226 minute (string-to-number (match-string 2 ans))
14227 m2 (+ minute (if (match-end 5) (string-to-number
14228 (match-string 5 ans))0)))
14229 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14230 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14231 t t ans)))
14233 ;; Check if there is a time range
14234 (when (boundp 'org-end-time-was-given)
14235 (setq org-time-was-given nil)
14236 (when (and (string-match org-plain-time-of-day-regexp ans)
14237 (match-end 8))
14238 (setq org-end-time-was-given (match-string 8 ans))
14239 (setq ans (concat (substring ans 0 (match-beginning 7))
14240 (substring ans (match-end 7))))))
14242 (setq tl (parse-time-string ans)
14243 day (or (nth 3 tl) (nth 3 defdecode))
14244 month (or (nth 4 tl)
14245 (if (and org-read-date-prefer-future
14246 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14247 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14248 (nth 4 defdecode)))
14249 year (or (and (not kill-year) (nth 5 tl))
14250 (if (and org-read-date-prefer-future
14251 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14252 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14253 (nth 5 defdecode)))
14254 hour (or (nth 2 tl) (nth 2 defdecode))
14255 minute (or (nth 1 tl) (nth 1 defdecode))
14256 second (or (nth 0 tl) 0)
14257 wday (nth 6 tl))
14259 (when (and (eq org-read-date-prefer-future 'time)
14260 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14261 (equal day (nth 3 nowdecode))
14262 (equal month (nth 4 nowdecode))
14263 (equal year (nth 5 nowdecode))
14264 (nth 2 tl)
14265 (or (< (nth 2 tl) (nth 2 nowdecode))
14266 (and (= (nth 2 tl) (nth 2 nowdecode))
14267 (nth 1 tl)
14268 (< (nth 1 tl) (nth 1 nowdecode)))))
14269 (setq day (1+ day)
14270 futurep t))
14272 ;; Special date definitions below
14273 (cond
14274 (iso-week
14275 ;; There was an iso week
14276 (require 'cal-iso)
14277 (setq futurep nil)
14278 (setq year (or iso-year year)
14279 day (or iso-weekday wday 1)
14280 wday nil ; to make sure that the trigger below does not match
14281 iso-date (calendar-gregorian-from-absolute
14282 (calendar-absolute-from-iso
14283 (list iso-week day year))))
14284 ; FIXME: Should we also push ISO weeks into the future?
14285 ; (when (and org-read-date-prefer-future
14286 ; (not iso-year)
14287 ; (< (calendar-absolute-from-gregorian iso-date)
14288 ; (time-to-days (current-time))))
14289 ; (setq year (1+ year)
14290 ; iso-date (calendar-gregorian-from-absolute
14291 ; (calendar-absolute-from-iso
14292 ; (list iso-week day year)))))
14293 (setq month (car iso-date)
14294 year (nth 2 iso-date)
14295 day (nth 1 iso-date)))
14296 (deltan
14297 (setq futurep nil)
14298 (unless deltadef
14299 (let ((now (decode-time (current-time))))
14300 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14301 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14302 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14303 ((equal deltaw "m") (setq month (+ month deltan)))
14304 ((equal deltaw "y") (setq year (+ year deltan)))))
14305 ((and wday (not (nth 3 tl)))
14306 (setq futurep nil)
14307 ;; Weekday was given, but no day, so pick that day in the week
14308 ;; on or after the derived date.
14309 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14310 (unless (equal wday wday1)
14311 (setq day (+ day (% (- wday wday1 -7) 7))))))
14312 (if (and (boundp 'org-time-was-given)
14313 (nth 2 tl))
14314 (setq org-time-was-given t))
14315 (if (< year 100) (setq year (+ 2000 year)))
14316 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14317 (setq org-read-date-analyze-futurep futurep)
14318 (list second minute hour day month year)))
14320 (defvar parse-time-weekdays)
14322 (defun org-read-date-get-relative (s today default)
14323 "Check string S for special relative date string.
14324 TODAY and DEFAULT are internal times, for today and for a default.
14325 Return shift list (N what def-flag)
14326 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14327 N is the number of WHATs to shift.
14328 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14329 the DEFAULT date rather than TODAY."
14330 (when (and
14331 (string-match
14332 (concat
14333 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14334 "\\([0-9]+\\)?"
14335 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14336 "\\([ \t]\\|$\\)") s)
14337 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14338 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14339 (string-to-char (substring (match-string 1 s) -1))
14340 ?+))
14341 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14342 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14343 (what (if (match-end 3) (match-string 3 s) "d"))
14344 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14345 (date (if rel default today))
14346 (wday (nth 6 (decode-time date)))
14347 delta)
14348 (if wday1
14349 (progn
14350 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14351 (if (= dir ?-) (setq delta (- delta 7)))
14352 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14353 (list delta "d" rel))
14354 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14356 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14357 "Turn a user-specified date into the internal representation.
14358 The internal representation needed by the calendar is (month day year).
14359 This is a wrapper to handle the brain-dead convention in calendar that
14360 user function argument order change dependent on argument order."
14361 (if (boundp 'calendar-date-style)
14362 (cond
14363 ((eq calendar-date-style 'american)
14364 (list arg1 arg2 arg3))
14365 ((eq calendar-date-style 'european)
14366 (list arg2 arg1 arg3))
14367 ((eq calendar-date-style 'iso)
14368 (list arg2 arg3 arg1)))
14369 (if (org-bound-and-true-p european-calendar-style)
14370 (list arg2 arg1 arg3)
14371 (list arg1 arg2 arg3))))
14373 (defun org-eval-in-calendar (form &optional keepdate)
14374 "Eval FORM in the calendar window and return to current window.
14375 Also, store the cursor date in variable org-ans2."
14376 (let ((sf (selected-frame))
14377 (sw (selected-window)))
14378 (select-window (get-buffer-window "*Calendar*" t))
14379 (eval form)
14380 (when (and (not keepdate) (calendar-cursor-to-date))
14381 (let* ((date (calendar-cursor-to-date))
14382 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14383 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14384 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14385 (select-window sw)
14386 (org-select-frame-set-input-focus sf)))
14388 (defun org-calendar-select ()
14389 "Return to `org-read-date' with the date currently selected.
14390 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14391 (interactive)
14392 (when (calendar-cursor-to-date)
14393 (let* ((date (calendar-cursor-to-date))
14394 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14395 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14396 (if (active-minibuffer-window) (exit-minibuffer))))
14398 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14399 "Insert a date stamp for the date given by the internal TIME.
14400 WITH-HM means use the stamp format that includes the time of the day.
14401 INACTIVE means use square brackets instead of angular ones, so that the
14402 stamp will not contribute to the agenda.
14403 PRE and POST are optional strings to be inserted before and after the
14404 stamp.
14405 The command returns the inserted time stamp."
14406 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14407 stamp)
14408 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14409 (insert-before-markers (or pre ""))
14410 (insert-before-markers (setq stamp (format-time-string fmt time)))
14411 (when (listp extra)
14412 (setq extra (car extra))
14413 (if (and (stringp extra)
14414 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14415 (setq extra (format "-%02d:%02d"
14416 (string-to-number (match-string 1 extra))
14417 (string-to-number (match-string 2 extra))))
14418 (setq extra nil)))
14419 (when extra
14420 (backward-char 1)
14421 (insert-before-markers extra)
14422 (forward-char 1))
14423 (insert-before-markers (or post ""))
14424 (setq org-last-inserted-timestamp stamp)))
14426 (defun org-toggle-time-stamp-overlays ()
14427 "Toggle the use of custom time stamp formats."
14428 (interactive)
14429 (setq org-display-custom-times (not org-display-custom-times))
14430 (unless org-display-custom-times
14431 (let ((p (point-min)) (bmp (buffer-modified-p)))
14432 (while (setq p (next-single-property-change p 'display))
14433 (if (and (get-text-property p 'display)
14434 (eq (get-text-property p 'face) 'org-date))
14435 (remove-text-properties
14436 p (setq p (next-single-property-change p 'display))
14437 '(display t))))
14438 (set-buffer-modified-p bmp)))
14439 (if (featurep 'xemacs)
14440 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14441 (org-restart-font-lock)
14442 (setq org-table-may-need-update t)
14443 (if org-display-custom-times
14444 (message "Time stamps are overlayed with custom format")
14445 (message "Time stamp overlays removed")))
14447 (defun org-display-custom-time (beg end)
14448 "Overlay modified time stamp format over timestamp between BEG and END."
14449 (let* ((ts (buffer-substring beg end))
14450 t1 w1 with-hm tf time str w2 (off 0))
14451 (save-match-data
14452 (setq t1 (org-parse-time-string ts t))
14453 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14454 (setq off (- (match-end 0) (match-beginning 0)))))
14455 (setq end (- end off))
14456 (setq w1 (- end beg)
14457 with-hm (and (nth 1 t1) (nth 2 t1))
14458 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14459 time (org-fix-decoded-time t1)
14460 str (org-add-props
14461 (format-time-string
14462 (substring tf 1 -1) (apply 'encode-time time))
14463 nil 'mouse-face 'highlight)
14464 w2 (length str))
14465 (if (not (= w2 w1))
14466 (add-text-properties (1+ beg) (+ 2 beg)
14467 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14468 (if (featurep 'xemacs)
14469 (progn
14470 (put-text-property beg end 'invisible t)
14471 (put-text-property beg end 'end-glyph (make-glyph str)))
14472 (put-text-property beg end 'display str))))
14474 (defun org-translate-time (string)
14475 "Translate all timestamps in STRING to custom format.
14476 But do this only if the variable `org-display-custom-times' is set."
14477 (when org-display-custom-times
14478 (save-match-data
14479 (let* ((start 0)
14480 (re org-ts-regexp-both)
14481 t1 with-hm inactive tf time str beg end)
14482 (while (setq start (string-match re string start))
14483 (setq beg (match-beginning 0)
14484 end (match-end 0)
14485 t1 (save-match-data
14486 (org-parse-time-string (substring string beg end) t))
14487 with-hm (and (nth 1 t1) (nth 2 t1))
14488 inactive (equal (substring string beg (1+ beg)) "[")
14489 tf (funcall (if with-hm 'cdr 'car)
14490 org-time-stamp-custom-formats)
14491 time (org-fix-decoded-time t1)
14492 str (format-time-string
14493 (concat
14494 (if inactive "[" "<") (substring tf 1 -1)
14495 (if inactive "]" ">"))
14496 (apply 'encode-time time))
14497 string (replace-match str t t string)
14498 start (+ start (length str)))))))
14499 string)
14501 (defun org-fix-decoded-time (time)
14502 "Set 0 instead of nil for the first 6 elements of time.
14503 Don't touch the rest."
14504 (let ((n 0))
14505 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14507 (defun org-days-to-time (timestamp-string)
14508 "Difference between TIMESTAMP-STRING and now in days."
14509 (- (time-to-days (org-time-string-to-time timestamp-string))
14510 (time-to-days (current-time))))
14512 (defun org-deadline-close (timestamp-string &optional ndays)
14513 "Is the time in TIMESTAMP-STRING close to the current date?"
14514 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14515 (and (< (org-days-to-time timestamp-string) ndays)
14516 (not (org-entry-is-done-p))))
14518 (defun org-get-wdays (ts)
14519 "Get the deadline lead time appropriate for timestring TS."
14520 (cond
14521 ((<= org-deadline-warning-days 0)
14522 ;; 0 or negative, enforce this value no matter what
14523 (- org-deadline-warning-days))
14524 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14525 ;; lead time is specified.
14526 (floor (* (string-to-number (match-string 1 ts))
14527 (cdr (assoc (match-string 2 ts)
14528 '(("d" . 1) ("w" . 7)
14529 ("m" . 30.4) ("y" . 365.25)))))))
14530 ;; go for the default.
14531 (t org-deadline-warning-days)))
14533 (defun org-calendar-select-mouse (ev)
14534 "Return to `org-read-date' with the date currently selected.
14535 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14536 (interactive "e")
14537 (mouse-set-point ev)
14538 (when (calendar-cursor-to-date)
14539 (let* ((date (calendar-cursor-to-date))
14540 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14541 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14542 (if (active-minibuffer-window) (exit-minibuffer))))
14544 (defun org-check-deadlines (ndays)
14545 "Check if there are any deadlines due or past due.
14546 A deadline is considered due if it happens within `org-deadline-warning-days'
14547 days from today's date. If the deadline appears in an entry marked DONE,
14548 it is not shown. The prefix arg NDAYS can be used to test that many
14549 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14550 (interactive "P")
14551 (let* ((org-warn-days
14552 (cond
14553 ((equal ndays '(4)) 100000)
14554 (ndays (prefix-numeric-value ndays))
14555 (t (abs org-deadline-warning-days))))
14556 (case-fold-search nil)
14557 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14558 (callback
14559 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14561 (message "%d deadlines past-due or due within %d days"
14562 (org-occur regexp nil callback)
14563 org-warn-days)))
14565 (defun org-check-before-date (date)
14566 "Check if there are deadlines or scheduled entries before DATE."
14567 (interactive (list (org-read-date)))
14568 (let ((case-fold-search nil)
14569 (regexp (concat "\\<\\(" org-deadline-string
14570 "\\|" org-scheduled-string
14571 "\\) *<\\([^>]+\\)>"))
14572 (callback
14573 (lambda () (time-less-p
14574 (org-time-string-to-time (match-string 2))
14575 (org-time-string-to-time date)))))
14576 (message "%d entries before %s"
14577 (org-occur regexp nil callback) date)))
14579 (defun org-check-after-date (date)
14580 "Check if there are deadlines or scheduled entries after DATE."
14581 (interactive (list (org-read-date)))
14582 (let ((case-fold-search nil)
14583 (regexp (concat "\\<\\(" org-deadline-string
14584 "\\|" org-scheduled-string
14585 "\\) *<\\([^>]+\\)>"))
14586 (callback
14587 (lambda () (not
14588 (time-less-p
14589 (org-time-string-to-time (match-string 2))
14590 (org-time-string-to-time date))))))
14591 (message "%d entries after %s"
14592 (org-occur regexp nil callback) date)))
14594 (defun org-evaluate-time-range (&optional to-buffer)
14595 "Evaluate a time range by computing the difference between start and end.
14596 Normally the result is just printed in the echo area, but with prefix arg
14597 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14598 If the time range is actually in a table, the result is inserted into the
14599 next column.
14600 For time difference computation, a year is assumed to be exactly 365
14601 days in order to avoid rounding problems."
14602 (interactive "P")
14604 (org-clock-update-time-maybe)
14605 (save-excursion
14606 (unless (org-at-date-range-p t)
14607 (goto-char (point-at-bol))
14608 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14609 (if (not (org-at-date-range-p t))
14610 (error "Not at a time-stamp range, and none found in current line")))
14611 (let* ((ts1 (match-string 1))
14612 (ts2 (match-string 2))
14613 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14614 (match-end (match-end 0))
14615 (time1 (org-time-string-to-time ts1))
14616 (time2 (org-time-string-to-time ts2))
14617 (t1 (org-float-time time1))
14618 (t2 (org-float-time time2))
14619 (diff (abs (- t2 t1)))
14620 (negative (< (- t2 t1) 0))
14621 ;; (ys (floor (* 365 24 60 60)))
14622 (ds (* 24 60 60))
14623 (hs (* 60 60))
14624 (fy "%dy %dd %02d:%02d")
14625 (fy1 "%dy %dd")
14626 (fd "%dd %02d:%02d")
14627 (fd1 "%dd")
14628 (fh "%02d:%02d")
14629 y d h m align)
14630 (if havetime
14631 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14633 d (floor (/ diff ds)) diff (mod diff ds)
14634 h (floor (/ diff hs)) diff (mod diff hs)
14635 m (floor (/ diff 60)))
14636 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14638 d (floor (+ (/ diff ds) 0.5))
14639 h 0 m 0))
14640 (if (not to-buffer)
14641 (message "%s" (org-make-tdiff-string y d h m))
14642 (if (org-at-table-p)
14643 (progn
14644 (goto-char match-end)
14645 (setq align t)
14646 (and (looking-at " *|") (goto-char (match-end 0))))
14647 (goto-char match-end))
14648 (if (looking-at
14649 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14650 (replace-match ""))
14651 (if negative (insert " -"))
14652 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14653 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14654 (insert " " (format fh h m))))
14655 (if align (org-table-align))
14656 (message "Time difference inserted")))))
14658 (defun org-make-tdiff-string (y d h m)
14659 (let ((fmt "")
14660 (l nil))
14661 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14662 l (push y l)))
14663 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14664 l (push d l)))
14665 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14666 l (push h l)))
14667 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14668 l (push m l)))
14669 (apply 'format fmt (nreverse l))))
14671 (defun org-time-string-to-time (s)
14672 (apply 'encode-time (org-parse-time-string s)))
14673 (defun org-time-string-to-seconds (s)
14674 (org-float-time (org-time-string-to-time s)))
14676 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14677 "Convert a time stamp to an absolute day number.
14678 If there is a specifyer for a cyclic time stamp, get the closest date to
14679 DAYNR.
14680 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14681 the variable date is bound by the calendar when this is called."
14682 (cond
14683 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14684 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14685 daynr
14686 (+ daynr 1000)))
14687 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14688 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14689 (time-to-days (current-time))) (match-string 0 s)
14690 prefer show-all))
14691 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14693 (defun org-days-to-iso-week (days)
14694 "Return the iso week number."
14695 (require 'cal-iso)
14696 (car (calendar-iso-from-absolute days)))
14698 (defun org-small-year-to-year (year)
14699 "Convert 2-digit years into 4-digit years.
14700 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14701 The year 2000 cannot be abbreviated. Any year larger than 99
14702 is returned unchanged."
14703 (if (< year 38)
14704 (setq year (+ 2000 year))
14705 (if (< year 100)
14706 (setq year (+ 1900 year))))
14707 year)
14709 (defun org-time-from-absolute (d)
14710 "Return the time corresponding to date D.
14711 D may be an absolute day number, or a calendar-type list (month day year)."
14712 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14713 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14715 (defun org-calendar-holiday ()
14716 "List of holidays, for Diary display in Org-mode."
14717 (require 'holidays)
14718 (let ((hl (funcall
14719 (if (fboundp 'calendar-check-holidays)
14720 'calendar-check-holidays 'check-calendar-holidays) date)))
14721 (if hl (mapconcat 'identity hl "; "))))
14723 (defun org-diary-sexp-entry (sexp entry date)
14724 "Process a SEXP diary ENTRY for DATE."
14725 (require 'diary-lib)
14726 (let ((result (if calendar-debug-sexp
14727 (let ((stack-trace-on-error t))
14728 (eval (car (read-from-string sexp))))
14729 (condition-case nil
14730 (eval (car (read-from-string sexp)))
14731 (error
14732 (beep)
14733 (message "Bad sexp at line %d in %s: %s"
14734 (org-current-line)
14735 (buffer-file-name) sexp)
14736 (sleep-for 2))))))
14737 (cond ((stringp result) result)
14738 ((and (consp result)
14739 (stringp (cdr result))) (cdr result))
14740 (result entry)
14741 (t nil))))
14743 (defun org-diary-to-ical-string (frombuf)
14744 "Get iCalendar entries from diary entries in buffer FROMBUF.
14745 This uses the icalendar.el library."
14746 (let* ((tmpdir (if (featurep 'xemacs)
14747 (temp-directory)
14748 temporary-file-directory))
14749 (tmpfile (make-temp-name
14750 (expand-file-name "orgics" tmpdir)))
14751 buf rtn b e)
14752 (with-current-buffer frombuf
14753 (icalendar-export-region (point-min) (point-max) tmpfile)
14754 (setq buf (find-buffer-visiting tmpfile))
14755 (set-buffer buf)
14756 (goto-char (point-min))
14757 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14758 (setq b (match-beginning 0)))
14759 (goto-char (point-max))
14760 (if (re-search-backward "^END:VEVENT" nil t)
14761 (setq e (match-end 0)))
14762 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14763 (kill-buffer buf)
14764 (delete-file tmpfile)
14765 rtn))
14767 (defun org-closest-date (start current change prefer show-all)
14768 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14769 When PREFER is `past' return a date that is either CURRENT or past.
14770 When PREFER is `future', return a date that is either CURRENT or future.
14771 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14772 ;; Make the proper lists from the dates
14773 (catch 'exit
14774 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14775 dn dw sday cday n1 n2 n0
14776 d m y y1 y2 date1 date2 nmonths nm ny m2)
14778 (setq start (org-date-to-gregorian start)
14779 current (org-date-to-gregorian
14780 (if show-all
14781 current
14782 (time-to-days (current-time))))
14783 sday (calendar-absolute-from-gregorian start)
14784 cday (calendar-absolute-from-gregorian current))
14786 (if (<= cday sday) (throw 'exit sday))
14788 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14789 (setq dn (string-to-number (match-string 1 change))
14790 dw (cdr (assoc (match-string 2 change) a1)))
14791 (error "Invalid change specifyer: %s" change))
14792 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14793 (cond
14794 ((eq dw 'day)
14795 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14796 n2 (+ n1 dn)))
14797 ((eq dw 'year)
14798 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14799 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14800 (setq date1 (list m d y1)
14801 n1 (calendar-absolute-from-gregorian date1)
14802 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14803 n2 (calendar-absolute-from-gregorian date2)))
14804 ((eq dw 'month)
14805 ;; approx number of month between the two dates
14806 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14807 ;; How often does dn fit in there?
14808 (setq d (nth 1 start) m (car start) y (nth 2 start)
14809 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14810 m (+ m nm)
14811 ny (floor (/ m 12))
14812 y (+ y ny)
14813 m (- m (* ny 12)))
14814 (while (> m 12) (setq m (- m 12) y (1+ y)))
14815 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14816 (setq m2 (+ m dn) y2 y)
14817 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14818 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14819 (while (<= n2 cday)
14820 (setq n1 n2 m m2 y y2)
14821 (setq m2 (+ m dn) y2 y)
14822 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14823 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14824 ;; Make sure n1 is the earlier date
14825 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14826 (if show-all
14827 (cond
14828 ((eq prefer 'past) (if (= cday n2) n2 n1))
14829 ((eq prefer 'future) (if (= cday n1) n1 n2))
14830 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14831 (cond
14832 ((eq prefer 'past) (if (= cday n2) n2 n1))
14833 ((eq prefer 'future) (if (= cday n1) n1 n2))
14834 (t (if (= cday n1) n1 n2)))))))
14836 (defun org-date-to-gregorian (date)
14837 "Turn any specification of DATE into a gregorian date for the calendar."
14838 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14839 ((and (listp date) (= (length date) 3)) date)
14840 ((stringp date)
14841 (setq date (org-parse-time-string date))
14842 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14843 ((listp date)
14844 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14846 (defun org-parse-time-string (s &optional nodefault)
14847 "Parse the standard Org-mode time string.
14848 This should be a lot faster than the normal `parse-time-string'.
14849 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14850 hour and minute fields will be nil if not given."
14851 (if (string-match org-ts-regexp0 s)
14852 (list 0
14853 (if (or (match-beginning 8) (not nodefault))
14854 (string-to-number (or (match-string 8 s) "0")))
14855 (if (or (match-beginning 7) (not nodefault))
14856 (string-to-number (or (match-string 7 s) "0")))
14857 (string-to-number (match-string 4 s))
14858 (string-to-number (match-string 3 s))
14859 (string-to-number (match-string 2 s))
14860 nil nil nil)
14861 (error "Not a standard Org-mode time string: %s" s)))
14863 (defun org-timestamp-up (&optional arg)
14864 "Increase the date item at the cursor by one.
14865 If the cursor is on the year, change the year. If it is on the month or
14866 the day, change that.
14867 With prefix ARG, change by that many units."
14868 (interactive "p")
14869 (org-timestamp-change (prefix-numeric-value arg)))
14871 (defun org-timestamp-down (&optional arg)
14872 "Decrease the date item at the cursor by one.
14873 If the cursor is on the year, change the year. If it is on the month or
14874 the day, change that.
14875 With prefix ARG, change by that many units."
14876 (interactive "p")
14877 (org-timestamp-change (- (prefix-numeric-value arg))))
14879 (defun org-timestamp-up-day (&optional arg)
14880 "Increase the date in the time stamp by one day.
14881 With prefix ARG, change that many days."
14882 (interactive "p")
14883 (if (and (not (org-at-timestamp-p t))
14884 (org-on-heading-p))
14885 (org-todo 'up)
14886 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14888 (defun org-timestamp-down-day (&optional arg)
14889 "Decrease the date in the time stamp by one day.
14890 With prefix ARG, change that many days."
14891 (interactive "p")
14892 (if (and (not (org-at-timestamp-p t))
14893 (org-on-heading-p))
14894 (org-todo 'down)
14895 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14897 (defun org-at-timestamp-p (&optional inactive-ok)
14898 "Determine if the cursor is in or at a timestamp."
14899 (interactive)
14900 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14901 (pos (point))
14902 (ans (or (looking-at tsr)
14903 (save-excursion
14904 (skip-chars-backward "^[<\n\r\t")
14905 (if (> (point) (point-min)) (backward-char 1))
14906 (and (looking-at tsr)
14907 (> (- (match-end 0) pos) -1))))))
14908 (and ans
14909 (boundp 'org-ts-what)
14910 (setq org-ts-what
14911 (cond
14912 ((= pos (match-beginning 0)) 'bracket)
14913 ((= pos (1- (match-end 0))) 'bracket)
14914 ((org-pos-in-match-range pos 2) 'year)
14915 ((org-pos-in-match-range pos 3) 'month)
14916 ((org-pos-in-match-range pos 7) 'hour)
14917 ((org-pos-in-match-range pos 8) 'minute)
14918 ((or (org-pos-in-match-range pos 4)
14919 (org-pos-in-match-range pos 5)) 'day)
14920 ((and (> pos (or (match-end 8) (match-end 5)))
14921 (< pos (match-end 0)))
14922 (- pos (or (match-end 8) (match-end 5))))
14923 (t 'day))))
14924 ans))
14926 (defun org-toggle-timestamp-type ()
14927 "Toggle the type (<active> or [inactive]) of a time stamp."
14928 (interactive)
14929 (when (org-at-timestamp-p t)
14930 (let ((beg (match-beginning 0)) (end (match-end 0))
14931 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14932 (save-excursion
14933 (goto-char beg)
14934 (while (re-search-forward "[][<>]" end t)
14935 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14936 t t)))
14937 (message "Timestamp is now %sactive"
14938 (if (equal (char-after beg) ?<) "" "in")))))
14940 (defun org-timestamp-change (n &optional what)
14941 "Change the date in the time stamp at point.
14942 The date will be changed by N times WHAT. WHAT can be `day', `month',
14943 `year', `minute', `second'. If WHAT is not given, the cursor position
14944 in the timestamp determines what will be changed."
14945 (let ((pos (point))
14946 with-hm inactive
14947 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14948 org-ts-what
14949 extra rem
14950 ts time time0)
14951 (if (not (org-at-timestamp-p t))
14952 (error "Not at a timestamp"))
14953 (if (and (not what) (eq org-ts-what 'bracket))
14954 (org-toggle-timestamp-type)
14955 (if (and (not what) (not (eq org-ts-what 'day))
14956 org-display-custom-times
14957 (get-text-property (point) 'display)
14958 (not (get-text-property (1- (point)) 'display)))
14959 (setq org-ts-what 'day))
14960 (setq org-ts-what (or what org-ts-what)
14961 inactive (= (char-after (match-beginning 0)) ?\[)
14962 ts (match-string 0))
14963 (replace-match "")
14964 (if (string-match
14965 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14967 (setq extra (match-string 1 ts)))
14968 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14969 (setq with-hm t))
14970 (setq time0 (org-parse-time-string ts))
14971 (when (and (eq org-ts-what 'minute)
14972 (eq current-prefix-arg nil))
14973 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14974 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14975 (setcar (cdr time0) (+ (nth 1 time0)
14976 (if (> n 0) (- rem) (- dm rem))))))
14977 (setq time
14978 (encode-time (or (car time0) 0)
14979 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14980 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14981 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14982 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14983 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14984 (nthcdr 6 time0)))
14985 (when (and (member org-ts-what '(hour minute))
14986 extra
14987 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14988 (setq extra (org-modify-ts-extra
14989 extra
14990 (if (eq org-ts-what 'hour) 2 5)
14991 n dm)))
14992 (when (integerp org-ts-what)
14993 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14994 (if (eq what 'calendar)
14995 (let ((cal-date (org-get-date-from-calendar)))
14996 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14997 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14998 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14999 (setcar time0 (or (car time0) 0))
15000 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15001 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15002 (setq time (apply 'encode-time time0))))
15003 (setq org-last-changed-timestamp
15004 (org-insert-time-stamp time with-hm inactive nil nil extra))
15005 (org-clock-update-time-maybe)
15006 (goto-char pos)
15007 ;; Try to recenter the calendar window, if any
15008 (if (and org-calendar-follow-timestamp-change
15009 (get-buffer-window "*Calendar*" t)
15010 (memq org-ts-what '(day month year)))
15011 (org-recenter-calendar (time-to-days time))))))
15013 (defun org-modify-ts-extra (s pos n dm)
15014 "Change the different parts of the lead-time and repeat fields in timestamp."
15015 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15016 ng h m new rem)
15017 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15018 (cond
15019 ((or (org-pos-in-match-range pos 2)
15020 (org-pos-in-match-range pos 3))
15021 (setq m (string-to-number (match-string 3 s))
15022 h (string-to-number (match-string 2 s)))
15023 (if (org-pos-in-match-range pos 2)
15024 (setq h (+ h n))
15025 (setq n (* dm (org-no-warnings (signum n))))
15026 (when (not (= 0 (setq rem (% m dm))))
15027 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15028 (setq m (+ m n)))
15029 (if (< m 0) (setq m (+ m 60) h (1- h)))
15030 (if (> m 59) (setq m (- m 60) h (1+ h)))
15031 (setq h (min 24 (max 0 h)))
15032 (setq ng 1 new (format "-%02d:%02d" h m)))
15033 ((org-pos-in-match-range pos 6)
15034 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15035 ((org-pos-in-match-range pos 5)
15036 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15038 ((org-pos-in-match-range pos 9)
15039 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15040 ((org-pos-in-match-range pos 8)
15041 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15043 (when ng
15044 (setq s (concat
15045 (substring s 0 (match-beginning ng))
15047 (substring s (match-end ng))))))
15050 (defun org-recenter-calendar (date)
15051 "If the calendar is visible, recenter it to DATE."
15052 (let* ((win (selected-window))
15053 (cwin (get-buffer-window "*Calendar*" t))
15054 (calendar-move-hook nil))
15055 (when cwin
15056 (select-window cwin)
15057 (calendar-goto-date (if (listp date) date
15058 (calendar-gregorian-from-absolute date)))
15059 (select-window win))))
15061 (defun org-goto-calendar (&optional arg)
15062 "Go to the Emacs calendar at the current date.
15063 If there is a time stamp in the current line, go to that date.
15064 A prefix ARG can be used to force the current date."
15065 (interactive "P")
15066 (let ((tsr org-ts-regexp) diff
15067 (calendar-move-hook nil)
15068 (calendar-view-holidays-initially-flag nil)
15069 (calendar-view-diary-initially-flag nil))
15070 (if (or (org-at-timestamp-p)
15071 (save-excursion
15072 (beginning-of-line 1)
15073 (looking-at (concat ".*" tsr))))
15074 (let ((d1 (time-to-days (current-time)))
15075 (d2 (time-to-days
15076 (org-time-string-to-time (match-string 1)))))
15077 (setq diff (- d2 d1))))
15078 (calendar)
15079 (calendar-goto-today)
15080 (if (and diff (not arg)) (calendar-forward-day diff))))
15082 (defun org-get-date-from-calendar ()
15083 "Return a list (month day year) of date at point in calendar."
15084 (with-current-buffer "*Calendar*"
15085 (save-match-data
15086 (calendar-cursor-to-date))))
15088 (defun org-date-from-calendar ()
15089 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15090 If there is already a time stamp at the cursor position, update it."
15091 (interactive)
15092 (if (org-at-timestamp-p t)
15093 (org-timestamp-change 0 'calendar)
15094 (let ((cal-date (org-get-date-from-calendar)))
15095 (org-insert-time-stamp
15096 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15098 (defun org-minutes-to-hh:mm-string (m)
15099 "Compute H:MM from a number of minutes."
15100 (let ((h (/ m 60)))
15101 (setq m (- m (* 60 h)))
15102 (format org-time-clocksum-format h m)))
15104 (defun org-hh:mm-string-to-minutes (s)
15105 "Convert a string H:MM to a number of minutes.
15106 If the string is just a number, interpret it as minutes.
15107 In fact, the first hh:mm or number in the string will be taken,
15108 there can be extra stuff in the string.
15109 If no number is found, the return value is 0."
15110 (cond
15111 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15112 (+ (* (string-to-number (match-string 1 s)) 60)
15113 (string-to-number (match-string 2 s))))
15114 ((string-match "\\([0-9]+\\)" s)
15115 (string-to-number (match-string 1 s)))
15116 (t 0)))
15118 ;;;; Files
15120 (defun org-save-all-org-buffers ()
15121 "Save all Org-mode buffers without user confirmation."
15122 (interactive)
15123 (message "Saving all Org-mode buffers...")
15124 (save-some-buffers t 'org-mode-p)
15125 (when (featurep 'org-id) (org-id-locations-save))
15126 (message "Saving all Org-mode buffers... done"))
15128 (defun org-revert-all-org-buffers ()
15129 "Revert all Org-mode buffers.
15130 Prompt for confirmation when there are unsaved changes.
15131 Be sure you know what you are doing before letting this function
15132 overwrite your changes.
15134 This function is useful in a setup where one tracks org files
15135 with a version control system, to revert on one machine after pulling
15136 changes from another. I believe the procedure must be like this:
15138 1. M-x org-save-all-org-buffers
15139 2. Pull changes from the other machine, resolve conflicts
15140 3. M-x org-revert-all-org-buffers"
15141 (interactive)
15142 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15143 (error "Abort"))
15144 (save-excursion
15145 (save-window-excursion
15146 (mapc
15147 (lambda (b)
15148 (when (and (with-current-buffer b (org-mode-p))
15149 (with-current-buffer b buffer-file-name))
15150 (switch-to-buffer b)
15151 (revert-buffer t 'no-confirm)))
15152 (buffer-list))
15153 (when (and (featurep 'org-id) org-id-track-globally)
15154 (org-id-locations-load)))))
15156 ;;;; Agenda files
15158 ;;;###autoload
15159 (defun org-iswitchb (&optional arg)
15160 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
15161 With a prefix argument, restrict available to files.
15162 With two prefix arguments, restrict available buffers to agenda files."
15163 (interactive "P")
15164 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15165 ((equal arg '(16)) (org-buffer-list 'agenda))
15166 (t (org-buffer-list)))))
15167 (switch-to-buffer
15168 (org-icompleting-read "Org buffer: "
15169 (mapcar 'list (mapcar 'buffer-name blist))
15170 nil t))))
15172 ;;;###autoload
15173 (defalias 'org-ido-switchb 'org-iswitchb)
15175 (defun org-buffer-list (&optional predicate exclude-tmp)
15176 "Return a list of Org buffers.
15177 PREDICATE can be `export', `files' or `agenda'.
15179 export restrict the list to Export buffers.
15180 files restrict the list to buffers visiting Org files.
15181 agenda restrict the list to buffers visiting agenda files.
15183 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15184 (let* ((bfn nil)
15185 (agenda-files (and (eq predicate 'agenda)
15186 (mapcar 'file-truename (org-agenda-files t))))
15187 (filter
15188 (cond
15189 ((eq predicate 'files)
15190 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15191 ((eq predicate 'export)
15192 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15193 ((eq predicate 'agenda)
15194 (lambda (b)
15195 (with-current-buffer b
15196 (and (eq major-mode 'org-mode)
15197 (setq bfn (buffer-file-name b))
15198 (member (file-truename bfn) agenda-files)))))
15199 (t (lambda (b) (with-current-buffer b
15200 (or (eq major-mode 'org-mode)
15201 (string-match "\*Org .*Export"
15202 (buffer-name b)))))))))
15203 (delq nil
15204 (mapcar
15205 (lambda(b)
15206 (if (and (funcall filter b)
15207 (or (not exclude-tmp)
15208 (not (string-match "tmp" (buffer-name b)))))
15210 nil))
15211 (buffer-list)))))
15213 (defun org-agenda-files (&optional unrestricted archives)
15214 "Get the list of agenda files.
15215 Optional UNRESTRICTED means return the full list even if a restriction
15216 is currently in place.
15217 When ARCHIVES is t, include all archive files that are really being
15218 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15219 `org-agenda-archives-mode' is t."
15220 (let ((files
15221 (cond
15222 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15223 ((stringp org-agenda-files) (org-read-agenda-file-list))
15224 ((listp org-agenda-files) org-agenda-files)
15225 (t (error "Invalid value of `org-agenda-files'")))))
15226 (setq files (apply 'append
15227 (mapcar (lambda (f)
15228 (if (file-directory-p f)
15229 (directory-files
15230 f t org-agenda-file-regexp)
15231 (list f)))
15232 files)))
15233 (when org-agenda-skip-unavailable-files
15234 (setq files (delq nil
15235 (mapcar (function
15236 (lambda (file)
15237 (and (file-readable-p file) file)))
15238 files))))
15239 (when (or (eq archives t)
15240 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15241 (setq files (org-add-archive-files files)))
15242 files))
15244 (defun org-agenda-file-p (&optional file)
15245 "Return non-nil, if FILE is an agenda file.
15246 If FILE is omitted, use the file associated with the current
15247 buffer."
15248 (member (or file (buffer-file-name))
15249 (org-agenda-files t)))
15251 (defun org-edit-agenda-file-list ()
15252 "Edit the list of agenda files.
15253 Depending on setup, this either uses customize to edit the variable
15254 `org-agenda-files', or it visits the file that is holding the list. In the
15255 latter case, the buffer is set up in a way that saving it automatically kills
15256 the buffer and restores the previous window configuration."
15257 (interactive)
15258 (if (stringp org-agenda-files)
15259 (let ((cw (current-window-configuration)))
15260 (find-file org-agenda-files)
15261 (org-set-local 'org-window-configuration cw)
15262 (org-add-hook 'after-save-hook
15263 (lambda ()
15264 (set-window-configuration
15265 (prog1 org-window-configuration
15266 (kill-buffer (current-buffer))))
15267 (org-install-agenda-files-menu)
15268 (message "New agenda file list installed"))
15269 nil 'local)
15270 (message "%s" (substitute-command-keys
15271 "Edit list and finish with \\[save-buffer]")))
15272 (customize-variable 'org-agenda-files)))
15274 (defun org-store-new-agenda-file-list (list)
15275 "Set new value for the agenda file list and save it correctly."
15276 (if (stringp org-agenda-files)
15277 (let ((fe (org-read-agenda-file-list t)) b u)
15278 (while (setq b (find-buffer-visiting org-agenda-files))
15279 (kill-buffer b))
15280 (with-temp-file org-agenda-files
15281 (insert
15282 (mapconcat
15283 (lambda (f) ;; Keep un-expanded entries.
15284 (if (setq u (assoc f fe))
15285 (cdr u)
15287 list "\n")
15288 "\n")))
15289 (let ((org-mode-hook nil) (org-inhibit-startup t)
15290 (org-insert-mode-line-in-empty-file nil))
15291 (setq org-agenda-files list)
15292 (customize-save-variable 'org-agenda-files org-agenda-files))))
15294 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15295 "Read the list of agenda files from a file.
15296 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15297 filenames, used by `org-store-new-agenda-file-list' to write back
15298 un-expanded file names."
15299 (when (file-directory-p org-agenda-files)
15300 (error "`org-agenda-files' cannot be a single directory"))
15301 (when (stringp org-agenda-files)
15302 (with-temp-buffer
15303 (insert-file-contents org-agenda-files)
15304 (mapcar
15305 (lambda (f)
15306 (let ((e (expand-file-name (substitute-in-file-name f)
15307 org-directory)))
15308 (if pair-with-expansion
15309 (cons e f)
15310 e)))
15311 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15313 ;;;###autoload
15314 (defun org-cycle-agenda-files ()
15315 "Cycle through the files in `org-agenda-files'.
15316 If the current buffer visits an agenda file, find the next one in the list.
15317 If the current buffer does not, find the first agenda file."
15318 (interactive)
15319 (let* ((fs (org-agenda-files t))
15320 (files (append fs (list (car fs))))
15321 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15322 file)
15323 (unless files (error "No agenda files"))
15324 (catch 'exit
15325 (while (setq file (pop files))
15326 (if (equal (file-truename file) tcf)
15327 (when (car files)
15328 (find-file (car files))
15329 (throw 'exit t))))
15330 (find-file (car fs)))
15331 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15333 (defun org-agenda-file-to-front (&optional to-end)
15334 "Move/add the current file to the top of the agenda file list.
15335 If the file is not present in the list, it is added to the front. If it is
15336 present, it is moved there. With optional argument TO-END, add/move to the
15337 end of the list."
15338 (interactive "P")
15339 (let ((org-agenda-skip-unavailable-files nil)
15340 (file-alist (mapcar (lambda (x)
15341 (cons (file-truename x) x))
15342 (org-agenda-files t)))
15343 (ctf (file-truename buffer-file-name))
15344 x had)
15345 (setq x (assoc ctf file-alist) had x)
15347 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15348 (if to-end
15349 (setq file-alist (append (delq x file-alist) (list x)))
15350 (setq file-alist (cons x (delq x file-alist))))
15351 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15352 (org-install-agenda-files-menu)
15353 (message "File %s to %s of agenda file list"
15354 (if had "moved" "added") (if to-end "end" "front"))))
15356 (defun org-remove-file (&optional file)
15357 "Remove current file from the list of files in variable `org-agenda-files'.
15358 These are the files which are being checked for agenda entries.
15359 Optional argument FILE means use this file instead of the current."
15360 (interactive)
15361 (let* ((org-agenda-skip-unavailable-files nil)
15362 (file (or file buffer-file-name))
15363 (true-file (file-truename file))
15364 (afile (abbreviate-file-name file))
15365 (files (delq nil (mapcar
15366 (lambda (x)
15367 (if (equal true-file
15368 (file-truename x))
15369 nil x))
15370 (org-agenda-files t)))))
15371 (if (not (= (length files) (length (org-agenda-files t))))
15372 (progn
15373 (org-store-new-agenda-file-list files)
15374 (org-install-agenda-files-menu)
15375 (message "Removed file: %s" afile))
15376 (message "File was not in list: %s (not removed)" afile))))
15378 (defun org-file-menu-entry (file)
15379 (vector file (list 'find-file file) t))
15381 (defun org-check-agenda-file (file)
15382 "Make sure FILE exists. If not, ask user what to do."
15383 (when (not (file-exists-p file))
15384 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15385 (abbreviate-file-name file))
15386 (let ((r (downcase (read-char-exclusive))))
15387 (cond
15388 ((equal r ?r)
15389 (org-remove-file file)
15390 (throw 'nextfile t))
15391 (t (error "Abort"))))))
15393 (defun org-get-agenda-file-buffer (file)
15394 "Get a buffer visiting FILE. If the buffer needs to be created, add
15395 it to the list of buffers which might be released later."
15396 (let ((buf (org-find-base-buffer-visiting file)))
15397 (if buf
15398 buf ; just return it
15399 ;; Make a new buffer and remember it
15400 (setq buf (find-file-noselect file))
15401 (if buf (push buf org-agenda-new-buffers))
15402 buf)))
15404 (defun org-release-buffers (blist)
15405 "Release all buffers in list, asking the user for confirmation when needed.
15406 When a buffer is unmodified, it is just killed. When modified, it is saved
15407 \(if the user agrees) and then killed."
15408 (let (buf file)
15409 (while (setq buf (pop blist))
15410 (setq file (buffer-file-name buf))
15411 (when (and (buffer-modified-p buf)
15412 file
15413 (y-or-n-p (format "Save file %s? " file)))
15414 (with-current-buffer buf (save-buffer)))
15415 (kill-buffer buf))))
15417 (defun org-prepare-agenda-buffers (files)
15418 "Create buffers for all agenda files, protect archived trees and comments."
15419 (interactive)
15420 (let ((pa '(:org-archived t))
15421 (pc '(:org-comment t))
15422 (pall '(:org-archived t :org-comment t))
15423 (inhibit-read-only t)
15424 (rea (concat ":" org-archive-tag ":"))
15425 bmp file re)
15426 (save-excursion
15427 (save-restriction
15428 (while (setq file (pop files))
15429 (catch 'nextfile
15430 (if (bufferp file)
15431 (set-buffer file)
15432 (org-check-agenda-file file)
15433 (set-buffer (org-get-agenda-file-buffer file)))
15434 (widen)
15435 (setq bmp (buffer-modified-p))
15436 (org-refresh-category-properties)
15437 (setq org-todo-keywords-for-agenda
15438 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15439 (setq org-done-keywords-for-agenda
15440 (append org-done-keywords-for-agenda org-done-keywords))
15441 (setq org-todo-keyword-alist-for-agenda
15442 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15443 (setq org-drawers-for-agenda
15444 (append org-drawers-for-agenda org-drawers))
15445 (setq org-tag-alist-for-agenda
15446 (append org-tag-alist-for-agenda org-tag-alist))
15448 (save-excursion
15449 (remove-text-properties (point-min) (point-max) pall)
15450 (when org-agenda-skip-archived-trees
15451 (goto-char (point-min))
15452 (while (re-search-forward rea nil t)
15453 (if (org-on-heading-p t)
15454 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15455 (goto-char (point-min))
15456 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15457 (while (re-search-forward re nil t)
15458 (add-text-properties
15459 (match-beginning 0) (org-end-of-subtree t) pc)))
15460 (set-buffer-modified-p bmp)))))
15461 (setq org-todo-keywords-for-agenda
15462 (org-uniquify org-todo-keywords-for-agenda))
15463 (setq org-todo-keyword-alist-for-agenda
15464 (org-uniquify org-todo-keyword-alist-for-agenda)
15465 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15467 ;;;; Embedded LaTeX
15469 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15470 "Keymap for the minor `org-cdlatex-mode'.")
15472 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15473 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15474 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15475 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15476 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15478 (defvar org-cdlatex-texmathp-advice-is-done nil
15479 "Flag remembering if we have applied the advice to texmathp already.")
15481 (define-minor-mode org-cdlatex-mode
15482 "Toggle the minor `org-cdlatex-mode'.
15483 This mode supports entering LaTeX environment and math in LaTeX fragments
15484 in Org-mode.
15485 \\{org-cdlatex-mode-map}"
15486 nil " OCDL" nil
15487 (when org-cdlatex-mode (require 'cdlatex))
15488 (unless org-cdlatex-texmathp-advice-is-done
15489 (setq org-cdlatex-texmathp-advice-is-done t)
15490 (defadvice texmathp (around org-math-always-on activate)
15491 "Always return t in org-mode buffers.
15492 This is because we want to insert math symbols without dollars even outside
15493 the LaTeX math segments. If Orgmode thinks that point is actually inside
15494 an embedded LaTeX fragment, let texmathp do its job.
15495 \\[org-cdlatex-mode-map]"
15496 (interactive)
15497 (let (p)
15498 (cond
15499 ((not (org-mode-p)) ad-do-it)
15500 ((eq this-command 'cdlatex-math-symbol)
15501 (setq ad-return-value t
15502 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15504 (let ((p (org-inside-LaTeX-fragment-p)))
15505 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15506 (setq ad-return-value t
15507 texmathp-why '("Org-mode embedded math" . 0))
15508 (if p ad-do-it)))))))))
15510 (defun turn-on-org-cdlatex ()
15511 "Unconditionally turn on `org-cdlatex-mode'."
15512 (org-cdlatex-mode 1))
15514 (defun org-inside-LaTeX-fragment-p ()
15515 "Test if point is inside a LaTeX fragment.
15516 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15517 sequence appearing also before point.
15518 Even though the matchers for math are configurable, this function assumes
15519 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15520 delimiters are skipped when they have been removed by customization.
15521 The return value is nil, or a cons cell with the delimiter and
15522 and the position of this delimiter.
15524 This function does a reasonably good job, but can locally be fooled by
15525 for example currency specifications. For example it will assume being in
15526 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15527 fragments that are properly closed, but during editing, we have to live
15528 with the uncertainty caused by missing closing delimiters. This function
15529 looks only before point, not after."
15530 (catch 'exit
15531 (let ((pos (point))
15532 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15533 (lim (progn
15534 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15535 (point)))
15536 dd-on str (start 0) m re)
15537 (goto-char pos)
15538 (when dodollar
15539 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15540 re (nth 1 (assoc "$" org-latex-regexps)))
15541 (while (string-match re str start)
15542 (cond
15543 ((= (match-end 0) (length str))
15544 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15545 ((= (match-end 0) (- (length str) 5))
15546 (throw 'exit nil))
15547 (t (setq start (match-end 0))))))
15548 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15549 (goto-char pos)
15550 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15551 (and (match-beginning 2) (throw 'exit nil))
15552 ;; count $$
15553 (while (re-search-backward "\\$\\$" lim t)
15554 (setq dd-on (not dd-on)))
15555 (goto-char pos)
15556 (if dd-on (cons "$$" m))))))
15558 (defun org-inside-latex-macro-p ()
15559 "Is point inside a LaTeX macro or its arguments?"
15560 (save-match-data
15561 (org-in-regexp
15562 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15564 (defun test ()
15565 (interactive)
15566 (message "%s" (org-inside-latex-macro-p)))
15568 (defun org-try-cdlatex-tab ()
15569 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15570 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15571 - inside a LaTeX fragment, or
15572 - after the first word in a line, where an abbreviation expansion could
15573 insert a LaTeX environment."
15574 (when org-cdlatex-mode
15575 (cond
15576 ((save-excursion
15577 (skip-chars-backward "a-zA-Z0-9*")
15578 (skip-chars-backward " \t")
15579 (bolp))
15580 (cdlatex-tab) t)
15581 ((org-inside-LaTeX-fragment-p)
15582 (cdlatex-tab) t)
15583 (t nil))))
15585 (defun org-cdlatex-underscore-caret (&optional arg)
15586 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15587 Revert to the normal definition outside of these fragments."
15588 (interactive "P")
15589 (if (org-inside-LaTeX-fragment-p)
15590 (call-interactively 'cdlatex-sub-superscript)
15591 (let (org-cdlatex-mode)
15592 (call-interactively (key-binding (vector last-input-event))))))
15594 (defun org-cdlatex-math-modify (&optional arg)
15595 "Execute `cdlatex-math-modify' 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-math-modify)
15600 (let (org-cdlatex-mode)
15601 (call-interactively (key-binding (vector last-input-event))))))
15603 (defvar org-latex-fragment-image-overlays nil
15604 "List of overlays carrying the images of latex fragments.")
15605 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15607 (defun org-remove-latex-fragment-image-overlays ()
15608 "Remove all overlays with LaTeX fragment images in current buffer."
15609 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15610 (setq org-latex-fragment-image-overlays nil))
15612 (defun org-preview-latex-fragment (&optional subtree)
15613 "Preview the LaTeX fragment at point, or all locally or globally.
15614 If the cursor is in a LaTeX fragment, create the image and overlay
15615 it over the source code. If there is no fragment at point, display
15616 all fragments in the current text, from one headline to the next. With
15617 prefix SUBTREE, display all fragments in the current subtree. With a
15618 double prefix `C-u C-u', or when the cursor is before the first headline,
15619 display all fragments in the buffer.
15620 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15621 (interactive "P")
15622 (org-remove-latex-fragment-image-overlays)
15623 (save-excursion
15624 (save-restriction
15625 (let (beg end at msg)
15626 (cond
15627 ((or (equal subtree '(16))
15628 (not (save-excursion
15629 (re-search-backward (concat "^" outline-regexp) nil t))))
15630 (setq beg (point-min) end (point-max)
15631 msg "Creating images for buffer...%s"))
15632 ((equal subtree '(4))
15633 (org-back-to-heading)
15634 (setq beg (point) end (org-end-of-subtree t)
15635 msg "Creating images for subtree...%s"))
15637 (if (setq at (org-inside-LaTeX-fragment-p))
15638 (goto-char (max (point-min) (- (cdr at) 2)))
15639 (org-back-to-heading))
15640 (setq beg (point) end (progn (outline-next-heading) (point))
15641 msg (if at "Creating image...%s"
15642 "Creating images for entry...%s"))))
15643 (message msg "")
15644 (narrow-to-region beg end)
15645 (goto-char beg)
15646 (org-format-latex
15647 (concat "ltxpng/" (file-name-sans-extension
15648 (file-name-nondirectory
15649 buffer-file-name)))
15650 default-directory 'overlays msg at 'forbuffer)
15651 (message msg "done. Use `C-c C-c' to remove images.")))))
15653 (defvar org-latex-regexps
15654 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15655 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15656 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15657 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15658 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15659 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15660 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15661 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15662 "Regular expressions for matching embedded LaTeX.")
15664 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15665 "Replace LaTeX fragments with links to an image, and produce images.
15666 Some of the options can be changed using the variable
15667 `org-format-latex-options'."
15668 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15669 (let* ((prefixnodir (file-name-nondirectory prefix))
15670 (absprefix (expand-file-name prefix dir))
15671 (todir (file-name-directory absprefix))
15672 (opt org-format-latex-options)
15673 (matchers (plist-get opt :matchers))
15674 (re-list org-latex-regexps)
15675 (org-format-latex-header-extra
15676 (plist-get (org-infile-export-plist) :latex-header-extra))
15677 (cnt 0) txt hash link beg end re e checkdir
15678 executables-checked
15679 m n block linkfile movefile ov)
15680 ;; Check the different regular expressions
15681 (while (setq e (pop re-list))
15682 (setq m (car e) re (nth 1 e) n (nth 2 e)
15683 block (if (nth 3 e) "\n\n" ""))
15684 (when (member m matchers)
15685 (goto-char (point-min))
15686 (while (re-search-forward re nil t)
15687 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15688 (not (get-text-property (match-beginning n)
15689 'org-protected))
15690 (or (not overlays)
15691 (not (eq (get-char-property (match-beginning n)
15692 'org-overlay-type)
15693 'org-latex-overlay))))
15694 (setq txt (match-string n)
15695 beg (match-beginning n) end (match-end n)
15696 cnt (1+ cnt))
15697 (let (print-length print-level) ; make sure full list is printed
15698 (setq hash (sha1 (prin1-to-string
15699 (list org-format-latex-header
15700 org-format-latex-header-extra
15701 org-export-latex-default-packages-alist
15702 org-export-latex-packages-alist
15703 org-format-latex-options
15704 forbuffer txt)))
15705 linkfile (format "%s_%s.png" prefix hash)
15706 movefile (format "%s_%s.png" absprefix hash)))
15707 (setq link (concat block "[[file:" linkfile "]]" block))
15708 (if msg (message msg cnt))
15709 (goto-char beg)
15710 (unless checkdir ; make sure the directory exists
15711 (setq checkdir t)
15712 (or (file-directory-p todir) (make-directory todir)))
15714 (unless executables-checked
15715 (org-check-external-command
15716 "latex" "needed to convert LaTeX fragments to images")
15717 (org-check-external-command
15718 "dvipng" "needed to convert LaTeX fragments to images")
15719 (setq executables-checked t))
15721 (unless (file-exists-p movefile)
15722 (org-create-formula-image
15723 txt movefile opt forbuffer))
15724 (if overlays
15725 (progn
15726 (mapc (lambda (o)
15727 (if (eq (overlay-get o 'org-overlay-type)
15728 'org-latex-overlay)
15729 (delete-overlay o)))
15730 (overlays-in beg end))
15731 (setq ov (make-overlay beg end))
15732 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15733 (if (featurep 'xemacs)
15734 (progn
15735 (overlay-put ov 'invisible t)
15736 (overlay-put
15737 ov 'end-glyph
15738 (make-glyph (vector 'png :file movefile))))
15739 (overlay-put
15740 ov 'display
15741 (list 'image :type 'png :file movefile :ascent 'center)))
15742 (push ov org-latex-fragment-image-overlays)
15743 (goto-char end))
15744 (delete-region beg end)
15745 (insert (org-add-props link
15746 (list 'org-latex-src
15747 (replace-regexp-in-string "\"" "" txt)))))))))))
15749 ;; This function borrows from Ganesh Swami's latex2png.el
15750 (defun org-create-formula-image (string tofile options buffer)
15751 "This calls dvipng."
15752 (require 'org-latex)
15753 (let* ((tmpdir (if (featurep 'xemacs)
15754 (temp-directory)
15755 temporary-file-directory))
15756 (texfilebase (make-temp-name
15757 (expand-file-name "orgtex" tmpdir)))
15758 (texfile (concat texfilebase ".tex"))
15759 (dvifile (concat texfilebase ".dvi"))
15760 (pngfile (concat texfilebase ".png"))
15761 (fnh (if (featurep 'xemacs)
15762 (font-height (get-face-font 'default))
15763 (face-attribute 'default :height nil)))
15764 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15765 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15766 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15767 "Black"))
15768 (bg (or (plist-get options (if buffer :background :html-background))
15769 "Transparent")))
15770 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15771 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15772 (with-temp-file texfile
15773 (insert (org-splice-latex-header
15774 org-format-latex-header
15775 org-export-latex-default-packages-alist
15776 org-export-latex-packages-alist t
15777 org-format-latex-header-extra))
15778 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15779 (require 'org-latex)
15780 (org-export-latex-fix-inputenc))
15781 (let ((dir default-directory))
15782 (condition-case nil
15783 (progn
15784 (cd tmpdir)
15785 (call-process "latex" nil nil nil texfile))
15786 (error nil))
15787 (cd dir))
15788 (if (not (file-exists-p dvifile))
15789 (progn (message "Failed to create dvi file from %s" texfile) nil)
15790 (condition-case nil
15791 (call-process "dvipng" nil nil nil
15792 "-fg" fg "-bg" bg
15793 "-D" dpi
15794 ;;"-x" scale "-y" scale
15795 "-T" "tight"
15796 "-o" pngfile
15797 dvifile)
15798 (error nil))
15799 (if (not (file-exists-p pngfile))
15800 (if org-format-latex-signal-error
15801 (error "Failed to create png file from %s" texfile)
15802 (message "Failed to create png file from %s" texfile)
15803 nil)
15804 ;; Use the requested file name and clean up
15805 (copy-file pngfile tofile 'replace)
15806 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15807 (delete-file (concat texfilebase e)))
15808 pngfile))))
15810 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15811 "Fill a LaTeX header template TPL.
15812 In the template, the following place holders will be recognized:
15814 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15815 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15816 [PACKAGES] \\usepackage statements for PKG
15817 [NO-PACKAGES] do not include PKG
15818 [EXTRA] the string EXTRA
15819 [NO-EXTRA] do not include EXTRA
15821 For backward compatibility, if both the positive and the negative place
15822 holder is missing, the positive one (without the \"NO-\") will be
15823 assumed to be present at the end of the template.
15824 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15825 EXTRA is a string.
15826 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15827 (let (rpl (end ""))
15828 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15829 (setq rpl (if (or (match-end 1) (not def-pkg))
15830 "" (org-latex-packages-to-string def-pkg snippets-p t))
15831 tpl (replace-match rpl t t tpl))
15832 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15834 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15835 (setq rpl (if (or (match-end 1) (not pkg))
15836 "" (org-latex-packages-to-string pkg snippets-p t))
15837 tpl (replace-match rpl t t tpl))
15838 (if pkg (setq end
15839 (concat end "\n"
15840 (org-latex-packages-to-string pkg snippets-p)))))
15842 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15843 (setq rpl (if (or (match-end 1) (not extra))
15844 "" (concat extra "\n"))
15845 tpl (replace-match rpl t t tpl))
15846 (if (and extra (string-match "\\S-" extra))
15847 (setq end (concat end "\n" extra))))
15849 (if (string-match "\\S-" end)
15850 (concat tpl "\n" end)
15851 tpl)))
15853 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
15854 "Turn an alist of packages into a string with the \\usepackage macros."
15855 (setq pkg (mapconcat (lambda(p)
15856 (cond
15857 ((stringp p) p)
15858 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
15859 (format "%% Package %s omitted" (cadr p)))
15860 ((equal "" (car p))
15861 (format "\\usepackage{%s}" (cadr p)))
15863 (format "\\usepackage[%s]{%s}"
15864 (car p) (cadr p)))))
15866 "\n"))
15867 (if newline (concat pkg "\n") pkg))
15869 (defun org-dvipng-color (attr)
15870 "Return an rgb color specification for dvipng."
15871 (apply 'format "rgb %s %s %s"
15872 (mapcar 'org-normalize-color
15873 (color-values (face-attribute 'default attr nil)))))
15875 (defun org-normalize-color (value)
15876 "Return string to be used as color value for an RGB component."
15877 (format "%g" (/ value 65535.0)))
15879 ;; Image display
15882 (defvar org-inline-image-overlays nil)
15883 (make-variable-buffer-local 'org-inline-image-overlays)
15885 (defun org-toggle-inline-images (&optional include-linked)
15886 "Toggle the display of inline images.
15887 INCLUDE-LINKED is passed to `org-display-inline-images'."
15888 (interactive "P")
15889 (if org-inline-image-overlays
15890 (progn
15891 (org-remove-inline-images)
15892 (message "Inline image display turned off"))
15893 (org-display-inline-images include-linked)
15894 (if org-inline-image-overlays
15895 (message "%d images displayed inline"
15896 (length org-inline-image-overlays))
15897 (message "No images to display inline"))))
15899 (defun org-display-inline-images (&optional include-linked refresh beg end)
15900 "Display inline images.
15901 Normally only links without a description part are inlined, because this
15902 is how it will work for export. When INCLUDE-LINKED is set, also links
15903 with a description part will be inlined. This can be nice for a quick
15904 look at those images, but it does not reflect whatexported files will look
15905 like.
15906 When REFRESH is set, refresh existing images between BEG and END.
15907 This will create new image displays only if necessary.
15908 BEG and END default to the buffer boundaries."
15909 (interactive "P")
15910 (unless refresh
15911 (org-remove-inline-images)
15912 (clear-image-cache))
15913 (save-excursion
15914 (save-restriction
15915 (widen)
15916 (setq beg (or beg (point-min)) end (or end (point-max)))
15917 (goto-char (point-min))
15918 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~./_0-9a-zA-Z]+"
15919 (substring (org-image-file-name-regexp) 0 -2)
15920 "\\)\\]" (if include-linked "" "\\]")))
15921 old file ov img)
15922 (while (re-search-forward re end t)
15923 (setq old (get-char-property-and-overlay (match-beginning 1)
15924 'org-image-overlay))
15925 (setq file (expand-file-name
15926 (concat (or (match-string 3) "") (match-string 4))))
15927 (when (file-exists-p file)
15928 (if (and (car-safe old) refresh)
15929 (image-refresh (overlay-get (cdr old) 'display))
15930 (setq img (create-image file))
15931 (when img
15932 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
15933 (overlay-put ov 'display img)
15934 (overlay-put ov 'face 'default)
15935 (overlay-put ov 'org-image-overlay t)
15936 (push ov org-inline-image-overlays)))))))))
15938 (defun org-remove-inline-images ()
15939 "Remove inline display of images."
15940 (interactive)
15941 (mapc 'delete-overlay org-inline-image-overlays)
15942 (setq org-inline-image-overlays nil))
15944 ;;;; Key bindings
15946 ;; Make `C-c C-x' a prefix key
15947 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15949 ;; TAB key with modifiers
15950 (org-defkey org-mode-map "\C-i" 'org-cycle)
15951 (org-defkey org-mode-map [(tab)] 'org-cycle)
15952 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15953 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15954 (org-defkey org-mode-map "\M-\t" 'org-complete)
15955 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15956 ;; The following line is necessary under Suse GNU/Linux
15957 (unless (featurep 'xemacs)
15958 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15959 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15960 (define-key org-mode-map [backtab] 'org-shifttab)
15962 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15963 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15964 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15966 ;; Cursor keys with modifiers
15967 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15968 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15969 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15970 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15972 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15973 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15974 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15975 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15977 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15978 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15979 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15980 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15982 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15983 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15985 ;;; Extra keys for tty access.
15986 ;; We only set them when really needed because otherwise the
15987 ;; menus don't show the simple keys
15989 (when (or org-use-extra-keys
15990 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15991 (not window-system))
15992 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15993 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15994 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15995 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15996 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15997 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15998 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15999 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16000 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16001 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16002 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16003 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16004 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16005 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16006 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16007 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16008 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16009 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16010 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16011 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16012 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16013 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16014 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16015 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16016 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16017 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16018 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16019 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16021 ;; All the other keys
16023 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16024 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16025 (if (boundp 'narrow-map)
16026 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16027 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16028 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16029 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16030 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16031 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16032 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16033 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16034 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16035 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16036 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16037 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16038 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16039 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16040 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16041 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16042 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16043 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16044 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16045 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16046 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16047 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16048 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16049 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16050 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16051 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16052 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16053 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16054 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16055 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16056 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16057 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16058 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16059 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16060 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16061 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16062 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16063 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16064 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16065 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16066 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16067 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16068 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16069 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16070 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16071 (org-defkey org-mode-map "\C-c^" 'org-sort)
16072 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16073 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16074 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16075 (org-defkey org-mode-map "\C-m" 'org-return)
16076 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16077 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16078 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16079 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16080 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16081 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16082 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16083 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16084 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16085 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16086 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16087 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16088 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16089 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16090 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16091 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16092 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16093 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16094 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16095 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16096 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16098 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16099 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16100 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16101 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16103 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16104 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16105 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16106 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16107 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16108 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16109 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16110 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16111 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16112 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16113 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16114 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16115 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16116 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16117 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16118 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16119 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16121 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16122 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16123 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16124 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16126 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16128 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16130 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16131 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16133 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16136 (when (featurep 'xemacs)
16137 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16140 (defconst org-speed-commands-default
16142 ("Outline Navigation")
16143 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16144 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16145 ("f" . (org-speed-move-safe 'org-forward-same-level))
16146 ("b" . (org-speed-move-safe 'org-backward-same-level))
16147 ("u" . (org-speed-move-safe 'outline-up-heading))
16148 ("j" . org-goto)
16149 ("g" . (org-refile t))
16150 ("Outline Visibility")
16151 ("c" . org-cycle)
16152 ("C" . org-shifttab)
16153 (" " . org-display-outline-path)
16154 ("Outline Structure Editing")
16155 ("U" . org-shiftmetaup)
16156 ("D" . org-shiftmetadown)
16157 ("r" . org-metaright)
16158 ("l" . org-metaleft)
16159 ("R" . org-shiftmetaright)
16160 ("L" . org-shiftmetaleft)
16161 ("i" . (progn (forward-char 1) (call-interactively
16162 'org-insert-heading-respect-content)))
16163 ("^" . org-sort)
16164 ("w" . org-refile)
16165 ("a" . org-archive-subtree-default-with-confirmation)
16166 ("." . outline-mark-subtree)
16167 ("Clock Commands")
16168 ("I" . org-clock-in)
16169 ("O" . org-clock-out)
16170 ("Meta Data Editing")
16171 ("t" . org-todo)
16172 ("0" . (org-priority ?\ ))
16173 ("1" . (org-priority ?A))
16174 ("2" . (org-priority ?B))
16175 ("3" . (org-priority ?C))
16176 (";" . org-set-tags-command)
16177 ("e" . org-set-effort)
16178 ("Agenda Views etc")
16179 ("v" . org-agenda)
16180 ("/" . org-sparse-tree)
16181 ("Misc")
16182 ("o" . org-open-at-point)
16183 ("?" . org-speed-command-help)
16185 "The default speed commands.")
16187 (defun org-print-speed-command (e)
16188 (if (> (length (car e)) 1)
16189 (progn
16190 (princ "\n")
16191 (princ (car e))
16192 (princ "\n")
16193 (princ (make-string (length (car e)) ?-))
16194 (princ "\n"))
16195 (princ (car e))
16196 (princ " ")
16197 (if (symbolp (cdr e))
16198 (princ (symbol-name (cdr e)))
16199 (prin1 (cdr e)))
16200 (princ "\n")))
16202 (defun org-speed-command-help ()
16203 "Show the available speed commands."
16204 (interactive)
16205 (if (not org-use-speed-commands)
16206 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
16207 (with-output-to-temp-buffer "*Help*"
16208 (princ "User-defined Speed commands\n===========================\n")
16209 (mapc 'org-print-speed-command org-speed-commands-user)
16210 (princ "\n")
16211 (princ "Built-in Speed commands\n=======================\n")
16212 (mapc 'org-print-speed-command org-speed-commands-default))
16213 (with-current-buffer "*Help*"
16214 (setq truncate-lines t))))
16216 (defun org-speed-move-safe (cmd)
16217 "Execute CMD, but make sure that the cursor always ends up in a headline.
16218 If not, return to the original position and throw an error."
16219 (interactive)
16220 (let ((pos (point)))
16221 (call-interactively cmd)
16222 (unless (and (bolp) (org-on-heading-p))
16223 (goto-char pos)
16224 (error "Boundary reached while executing %s" cmd))))
16226 (defvar org-self-insert-command-undo-counter 0)
16228 (defvar org-table-auto-blank-field) ; defined in org-table.el
16229 (defvar org-speed-command nil)
16230 (defun org-self-insert-command (N)
16231 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16232 If the cursor is in a table looking at whitespace, the whitespace is
16233 overwritten, and the table is not marked as requiring realignment."
16234 (interactive "p")
16235 (cond
16236 ((and org-use-speed-commands
16237 (or (and (bolp) (looking-at outline-regexp))
16238 (and (functionp org-use-speed-commands)
16239 (funcall org-use-speed-commands)))
16240 (setq
16241 org-speed-command
16242 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16243 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16244 (cond
16245 ((commandp org-speed-command)
16246 (setq this-command org-speed-command)
16247 (call-interactively org-speed-command))
16248 ((functionp org-speed-command)
16249 (funcall org-speed-command))
16250 ((and org-speed-command (listp org-speed-command))
16251 (eval org-speed-command))
16252 (t (let (org-use-speed-commands)
16253 (call-interactively 'org-self-insert-command)))))
16254 ((and
16255 (org-table-p)
16256 (progn
16257 ;; check if we blank the field, and if that triggers align
16258 (and (featurep 'org-table) org-table-auto-blank-field
16259 (member last-command
16260 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16261 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16262 ;; got extra space, this field does not determine column width
16263 (let (org-table-may-need-update) (org-table-blank-field))
16264 ;; no extra space, this field may determine column width
16265 (org-table-blank-field)))
16267 (eq N 1)
16268 (looking-at "[^|\n]* |"))
16269 (let (org-table-may-need-update)
16270 (goto-char (1- (match-end 0)))
16271 (delete-backward-char 1)
16272 (goto-char (match-beginning 0))
16273 (self-insert-command N)))
16275 (setq org-table-may-need-update t)
16276 (self-insert-command N)
16277 (org-fix-tags-on-the-fly)
16278 (if org-self-insert-cluster-for-undo
16279 (if (not (eq last-command 'org-self-insert-command))
16280 (setq org-self-insert-command-undo-counter 1)
16281 (if (>= org-self-insert-command-undo-counter 20)
16282 (setq org-self-insert-command-undo-counter 1)
16283 (and (> org-self-insert-command-undo-counter 0)
16284 buffer-undo-list
16285 (not (cadr buffer-undo-list)) ; remove nil entry
16286 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16287 (setq org-self-insert-command-undo-counter
16288 (1+ org-self-insert-command-undo-counter))))))))
16290 (defun org-fix-tags-on-the-fly ()
16291 (when (and (equal (char-after (point-at-bol)) ?*)
16292 (org-on-heading-p))
16293 (org-align-tags-here org-tags-column)))
16295 (defun org-delete-backward-char (N)
16296 "Like `delete-backward-char', insert whitespace at field end in tables.
16297 When deleting backwards, in tables this function will insert whitespace in
16298 front of the next \"|\" separator, to keep the table aligned. The table will
16299 still be marked for re-alignment if the field did fill the entire column,
16300 because, in this case the deletion might narrow the column."
16301 (interactive "p")
16302 (if (and (org-table-p)
16303 (eq N 1)
16304 (string-match "|" (buffer-substring (point-at-bol) (point)))
16305 (looking-at ".*?|"))
16306 (let ((pos (point))
16307 (noalign (looking-at "[^|\n\r]* |"))
16308 (c org-table-may-need-update))
16309 (backward-delete-char N)
16310 (skip-chars-forward "^|")
16311 (insert " ")
16312 (goto-char (1- pos))
16313 ;; noalign: if there were two spaces at the end, this field
16314 ;; does not determine the width of the column.
16315 (if noalign (setq org-table-may-need-update c)))
16316 (backward-delete-char N)
16317 (org-fix-tags-on-the-fly)))
16319 (defun org-delete-char (N)
16320 "Like `delete-char', but insert whitespace at field end in tables.
16321 When deleting characters, in tables this function will insert whitespace in
16322 front of the next \"|\" separator, to keep the table aligned. The table will
16323 still be marked for re-alignment if the field did fill the entire column,
16324 because, in this case the deletion might narrow the column."
16325 (interactive "p")
16326 (if (and (org-table-p)
16327 (not (bolp))
16328 (not (= (char-after) ?|))
16329 (eq N 1))
16330 (if (looking-at ".*?|")
16331 (let ((pos (point))
16332 (noalign (looking-at "[^|\n\r]* |"))
16333 (c org-table-may-need-update))
16334 (replace-match (concat
16335 (substring (match-string 0) 1 -1)
16336 " |"))
16337 (goto-char pos)
16338 ;; noalign: if there were two spaces at the end, this field
16339 ;; does not determine the width of the column.
16340 (if noalign (setq org-table-may-need-update c)))
16341 (delete-char N))
16342 (delete-char N)
16343 (org-fix-tags-on-the-fly)))
16345 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16346 (put 'org-self-insert-command 'delete-selection t)
16347 (put 'orgtbl-self-insert-command 'delete-selection t)
16348 (put 'org-delete-char 'delete-selection 'supersede)
16349 (put 'org-delete-backward-char 'delete-selection 'supersede)
16350 (put 'org-yank 'delete-selection 'yank)
16352 ;; Make `flyspell-mode' delay after some commands
16353 (put 'org-self-insert-command 'flyspell-delayed t)
16354 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16355 (put 'org-delete-char 'flyspell-delayed t)
16356 (put 'org-delete-backward-char 'flyspell-delayed t)
16358 ;; Make pabbrev-mode expand after org-mode commands
16359 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16360 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16362 ;; How to do this: Measure non-white length of current string
16363 ;; If equal to column width, we should realign.
16365 (defun org-remap (map &rest commands)
16366 "In MAP, remap the functions given in COMMANDS.
16367 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16368 (let (new old)
16369 (while commands
16370 (setq old (pop commands) new (pop commands))
16371 (if (fboundp 'command-remapping)
16372 (org-defkey map (vector 'remap old) new)
16373 (substitute-key-definition old new map global-map)))))
16375 (when (eq org-enable-table-editor 'optimized)
16376 ;; If the user wants maximum table support, we need to hijack
16377 ;; some standard editing functions
16378 (org-remap org-mode-map
16379 'self-insert-command 'org-self-insert-command
16380 'delete-char 'org-delete-char
16381 'delete-backward-char 'org-delete-backward-char)
16382 (org-defkey org-mode-map "|" 'org-force-self-insert))
16384 (defvar org-ctrl-c-ctrl-c-hook nil
16385 "Hook for functions attaching themselves to `C-c C-c'.
16386 This can be used to add additional functionality to the C-c C-c key which
16387 executes context-dependent commands.
16388 Each function will be called with no arguments. The function must check
16389 if the context is appropriate for it to act. If yes, it should do its
16390 thing and then return a non-nil value. If the context is wrong,
16391 just do nothing and return nil.")
16393 (defvar org-tab-first-hook nil
16394 "Hook for functions to attach themselves to TAB.
16395 See `org-ctrl-c-ctrl-c-hook' for more information.
16396 This hook runs as the first action when TAB is pressed, even before
16397 `org-cycle' messes around with the `outline-regexp' to cater for
16398 inline tasks and plain list item folding.
16399 If any function in this hook returns t, any other actions that
16400 would have been caused by TAB (such as table field motion or visibility
16401 cycling) will not occur.")
16403 (defvar org-tab-after-check-for-table-hook nil
16404 "Hook for functions to attach themselves to TAB.
16405 See `org-ctrl-c-ctrl-c-hook' for more information.
16406 This hook runs after it has been established that the cursor is not in a
16407 table, but before checking if the cursor is in a headline or if global cycling
16408 should be done.
16409 If any function in this hook returns t, not other actions like visibility
16410 cycling will be done.")
16412 (defvar org-tab-after-check-for-cycling-hook nil
16413 "Hook for functions to attach themselves to TAB.
16414 See `org-ctrl-c-ctrl-c-hook' for more information.
16415 This hook runs after it has been established that not table field motion and
16416 not visibility should be done because of current context. This is probably
16417 the place where a package like yasnippets can hook in.")
16419 (defvar org-tab-before-tab-emulation-hook nil
16420 "Hook for functions to attach themselves to TAB.
16421 See `org-ctrl-c-ctrl-c-hook' for more information.
16422 This hook runs after every other options for TAB have been exhausted, but
16423 before indentation and \t insertion takes place.")
16425 (defvar org-metaleft-hook nil
16426 "Hook for functions attaching themselves to `M-left'.
16427 See `org-ctrl-c-ctrl-c-hook' for more information.")
16428 (defvar org-metaright-hook nil
16429 "Hook for functions attaching themselves to `M-right'.
16430 See `org-ctrl-c-ctrl-c-hook' for more information.")
16431 (defvar org-metaup-hook nil
16432 "Hook for functions attaching themselves to `M-up'.
16433 See `org-ctrl-c-ctrl-c-hook' for more information.")
16434 (defvar org-metadown-hook nil
16435 "Hook for functions attaching themselves to `M-down'.
16436 See `org-ctrl-c-ctrl-c-hook' for more information.")
16437 (defvar org-shiftmetaleft-hook nil
16438 "Hook for functions attaching themselves to `M-S-left'.
16439 See `org-ctrl-c-ctrl-c-hook' for more information.")
16440 (defvar org-shiftmetaright-hook nil
16441 "Hook for functions attaching themselves to `M-S-right'.
16442 See `org-ctrl-c-ctrl-c-hook' for more information.")
16443 (defvar org-shiftmetaup-hook nil
16444 "Hook for functions attaching themselves to `M-S-up'.
16445 See `org-ctrl-c-ctrl-c-hook' for more information.")
16446 (defvar org-shiftmetadown-hook nil
16447 "Hook for functions attaching themselves to `M-S-down'.
16448 See `org-ctrl-c-ctrl-c-hook' for more information.")
16449 (defvar org-metareturn-hook nil
16450 "Hook for functions attaching themselves to `M-RET'.
16451 See `org-ctrl-c-ctrl-c-hook' for more information.")
16452 (defvar org-shiftup-hook nil
16453 "Hook for functions attaching themselves to `S-up'.
16454 See `org-ctrl-c-ctrl-c-hook' for more information.")
16455 (defvar org-shiftup-final-hook nil
16456 "Hook for functions attaching themselves to `S-up'.
16457 This one runs after all other options except shift-select have been excluded.
16458 See `org-ctrl-c-ctrl-c-hook' for more information.")
16459 (defvar org-shiftdown-hook nil
16460 "Hook for functions attaching themselves to `S-down'.
16461 See `org-ctrl-c-ctrl-c-hook' for more information.")
16462 (defvar org-shiftdown-final-hook nil
16463 "Hook for functions attaching themselves to `S-down'.
16464 This one runs after all other options except shift-select have been excluded.
16465 See `org-ctrl-c-ctrl-c-hook' for more information.")
16466 (defvar org-shiftleft-hook nil
16467 "Hook for functions attaching themselves to `S-left'.
16468 See `org-ctrl-c-ctrl-c-hook' for more information.")
16469 (defvar org-shiftleft-final-hook nil
16470 "Hook for functions attaching themselves to `S-left'.
16471 This one runs after all other options except shift-select have been excluded.
16472 See `org-ctrl-c-ctrl-c-hook' for more information.")
16473 (defvar org-shiftright-hook nil
16474 "Hook for functions attaching themselves to `S-right'.
16475 See `org-ctrl-c-ctrl-c-hook' for more information.")
16476 (defvar org-shiftright-final-hook nil
16477 "Hook for functions attaching themselves to `S-right'.
16478 This one runs after all other options except shift-select have been excluded.
16479 See `org-ctrl-c-ctrl-c-hook' for more information.")
16481 (defun org-modifier-cursor-error ()
16482 "Throw an error, a modified cursor command was applied in wrong context."
16483 (error "This command is active in special context like tables, headlines or items"))
16485 (defun org-shiftselect-error ()
16486 "Throw an error because Shift-Cursor command was applied in wrong context."
16487 (if (and (boundp 'shift-select-mode) shift-select-mode)
16488 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16489 (error "This command works only in special context like headlines or timestamps")))
16491 (defun org-call-for-shift-select (cmd)
16492 (let ((this-command-keys-shift-translated t))
16493 (call-interactively cmd)))
16495 (defun org-shifttab (&optional arg)
16496 "Global visibility cycling or move to previous table field.
16497 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16498 on context.
16499 See the individual commands for more information."
16500 (interactive "P")
16501 (cond
16502 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16503 ((integerp arg)
16504 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16505 (message "Content view to level: %d" arg)
16506 (org-content (prefix-numeric-value arg2))
16507 (setq org-cycle-global-status 'overview)))
16508 (t (call-interactively 'org-global-cycle))))
16510 (defun org-shiftmetaleft ()
16511 "Promote subtree or delete table column.
16512 Calls `org-promote-subtree', `org-outdent-item',
16513 or `org-table-delete-column', depending on context.
16514 See the individual commands for more information."
16515 (interactive)
16516 (cond
16517 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16518 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16519 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16520 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16521 (t (org-modifier-cursor-error))))
16523 (defun org-shiftmetaright ()
16524 "Demote subtree or insert table column.
16525 Calls `org-demote-subtree', `org-indent-item',
16526 or `org-table-insert-column', depending on context.
16527 See the individual commands for more information."
16528 (interactive)
16529 (cond
16530 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16531 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16532 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16533 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16534 (t (org-modifier-cursor-error))))
16536 (defun org-shiftmetaup (&optional arg)
16537 "Move subtree up or kill table row.
16538 Calls `org-move-subtree-up' or `org-table-kill-row' or
16539 `org-move-item-up' depending on context. See the individual commands
16540 for more information."
16541 (interactive "P")
16542 (cond
16543 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16544 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16545 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16546 ((org-at-item-p) (call-interactively 'org-move-item-up))
16547 (t (org-modifier-cursor-error))))
16549 (defun org-shiftmetadown (&optional arg)
16550 "Move subtree down or insert table row.
16551 Calls `org-move-subtree-down' or `org-table-insert-row' or
16552 `org-move-item-down', depending on context. See the individual
16553 commands for more information."
16554 (interactive "P")
16555 (cond
16556 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16557 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16558 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16559 ((org-at-item-p) (call-interactively 'org-move-item-down))
16560 (t (org-modifier-cursor-error))))
16562 (defsubst org-hidden-tree-error ()
16563 (error
16564 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16566 (defun org-metaleft (&optional arg)
16567 "Promote heading or move table column to left.
16568 Calls `org-do-promote' or `org-table-move-column', depending on context.
16569 With no specific context, calls the Emacs default `backward-word'.
16570 See the individual commands for more information."
16571 (interactive "P")
16572 (cond
16573 ((run-hook-with-args-until-success 'org-metaleft-hook))
16574 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16575 ((or (org-on-heading-p)
16576 (and (org-region-active-p)
16577 (save-excursion
16578 (goto-char (region-beginning))
16579 (org-on-heading-p))))
16580 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16581 (call-interactively 'org-do-promote))
16582 ((or (org-at-item-p)
16583 (and (org-region-active-p)
16584 (save-excursion
16585 (goto-char (region-beginning))
16586 (org-at-item-p))))
16587 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16588 (call-interactively 'org-outdent-item))
16589 (t (call-interactively 'backward-word))))
16591 (defun org-metaright (&optional arg)
16592 "Demote subtree or move table column to right.
16593 Calls `org-do-demote' or `org-table-move-column', depending on context.
16594 With no specific context, calls the Emacs default `forward-word'.
16595 See the individual commands for more information."
16596 (interactive "P")
16597 (cond
16598 ((run-hook-with-args-until-success 'org-metaright-hook))
16599 ((org-at-table-p) (call-interactively 'org-table-move-column))
16600 ((or (org-on-heading-p)
16601 (and (org-region-active-p)
16602 (save-excursion
16603 (goto-char (region-beginning))
16604 (org-on-heading-p))))
16605 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16606 (call-interactively 'org-do-demote))
16607 ((or (org-at-item-p)
16608 (and (org-region-active-p)
16609 (save-excursion
16610 (goto-char (region-beginning))
16611 (org-at-item-p))))
16612 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16613 (call-interactively 'org-indent-item))
16614 (t (call-interactively 'forward-word))))
16616 (defun org-check-for-hidden (what)
16617 "Check if there are hidden headlines/items in the current visual line.
16618 WHAT can be either `headlines' or `items'. If the current line is
16619 an outline or item heading and it has a folded subtree below it,
16620 this fucntion returns t, nil otherwise."
16621 (let ((re (cond
16622 ((eq what 'headlines) (concat "^" org-outline-regexp))
16623 ((eq what 'items) (concat "^" (org-item-re t)))
16624 (t (error "This should not happen"))))
16625 beg end)
16626 (save-excursion
16627 (catch 'exit
16628 (unless (org-region-active-p)
16629 (setq beg (point-at-bol))
16630 (beginning-of-line 2)
16631 (while (and (not (eobp)) ;; this is like `next-line'
16632 (get-char-property (1- (point)) 'invisible))
16633 (beginning-of-line 2))
16634 (setq end (point))
16635 (goto-char beg)
16636 (goto-char (point-at-eol))
16637 (setq end (max end (point)))
16638 (while (re-search-forward re end t)
16639 (if (get-char-property (match-beginning 0) 'invisible)
16640 (throw 'exit t))))
16641 nil))))
16643 (defun org-metaup (&optional arg)
16644 "Move subtree up or move table row up.
16645 Calls `org-move-subtree-up' or `org-table-move-row' or
16646 `org-move-item-up', depending on context. See the individual commands
16647 for more information."
16648 (interactive "P")
16649 (cond
16650 ((run-hook-with-args-until-success 'org-metaup-hook))
16651 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16652 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16653 ((org-at-item-p) (call-interactively 'org-move-item-up))
16654 (t (transpose-lines 1) (beginning-of-line -1))))
16656 (defun org-metadown (&optional arg)
16657 "Move subtree down or move table row down.
16658 Calls `org-move-subtree-down' or `org-table-move-row' or
16659 `org-move-item-down', depending on context. See the individual
16660 commands for more information."
16661 (interactive "P")
16662 (cond
16663 ((run-hook-with-args-until-success 'org-metadown-hook))
16664 ((org-at-table-p) (call-interactively 'org-table-move-row))
16665 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16666 ((org-at-item-p) (call-interactively 'org-move-item-down))
16667 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16669 (defun org-shiftup (&optional arg)
16670 "Increase item in timestamp or increase priority of current headline.
16671 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16672 depending on context. See the individual commands for more information."
16673 (interactive "P")
16674 (cond
16675 ((run-hook-with-args-until-success 'org-shiftup-hook))
16676 ((and org-support-shift-select (org-region-active-p))
16677 (org-call-for-shift-select 'previous-line))
16678 ((org-at-timestamp-p t)
16679 (call-interactively (if org-edit-timestamp-down-means-later
16680 'org-timestamp-down 'org-timestamp-up)))
16681 ((and (not (eq org-support-shift-select 'always))
16682 org-enable-priority-commands
16683 (org-on-heading-p))
16684 (call-interactively 'org-priority-up))
16685 ((and (not org-support-shift-select) (org-at-item-p))
16686 (call-interactively 'org-previous-item))
16687 ((org-clocktable-try-shift 'up arg))
16688 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16689 (org-support-shift-select
16690 (org-call-for-shift-select 'previous-line))
16691 (t (org-shiftselect-error))))
16693 (defun org-shiftdown (&optional arg)
16694 "Decrease item in timestamp or decrease priority of current headline.
16695 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16696 depending on context. See the individual commands for more information."
16697 (interactive "P")
16698 (cond
16699 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16700 ((and org-support-shift-select (org-region-active-p))
16701 (org-call-for-shift-select 'next-line))
16702 ((org-at-timestamp-p t)
16703 (call-interactively (if org-edit-timestamp-down-means-later
16704 'org-timestamp-up 'org-timestamp-down)))
16705 ((and (not (eq org-support-shift-select 'always))
16706 org-enable-priority-commands
16707 (org-on-heading-p))
16708 (call-interactively 'org-priority-down))
16709 ((and (not org-support-shift-select) (org-at-item-p))
16710 (call-interactively 'org-next-item))
16711 ((org-clocktable-try-shift 'down arg))
16712 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16713 (org-support-shift-select
16714 (org-call-for-shift-select 'next-line))
16715 (t (org-shiftselect-error))))
16717 (defun org-shiftright (&optional arg)
16718 "Cycle the thing at point or in the current line, depending on context.
16719 Depending on context, this does one of the following:
16721 - switch a timestamp at point one day into the future
16722 - on a headline, switch to the next TODO keyword.
16723 - on an item, switch entire list to the next bullet type
16724 - on a property line, switch to the next allowed value
16725 - on a clocktable definition line, move time block into the future"
16726 (interactive "P")
16727 (cond
16728 ((run-hook-with-args-until-success 'org-shiftright-hook))
16729 ((and org-support-shift-select (org-region-active-p))
16730 (org-call-for-shift-select 'forward-char))
16731 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16732 ((and (not (eq org-support-shift-select 'always))
16733 (org-on-heading-p))
16734 (let ((org-inhibit-logging
16735 (not org-treat-S-cursor-todo-selection-as-state-change))
16736 (org-inhibit-blocking
16737 (not org-treat-S-cursor-todo-selection-as-state-change)))
16738 (org-call-with-arg 'org-todo 'right)))
16739 ((or (and org-support-shift-select
16740 (not (eq org-support-shift-select 'always))
16741 (org-at-item-bullet-p))
16742 (and (not org-support-shift-select) (org-at-item-p)))
16743 (org-call-with-arg 'org-cycle-list-bullet nil))
16744 ((and (not (eq org-support-shift-select 'always))
16745 (org-at-property-p))
16746 (call-interactively 'org-property-next-allowed-value))
16747 ((org-clocktable-try-shift 'right arg))
16748 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16749 (org-support-shift-select
16750 (org-call-for-shift-select 'forward-char))
16751 (t (org-shiftselect-error))))
16753 (defun org-shiftleft (&optional arg)
16754 "Cycle the thing at point or in the current line, depending on context.
16755 Depending on context, this does one of the following:
16757 - switch a timestamp at point one day into the past
16758 - on a headline, switch to the previous TODO keyword.
16759 - on an item, switch entire list to the previous bullet type
16760 - on a property line, switch to the previous allowed value
16761 - on a clocktable definition line, move time block into the past"
16762 (interactive "P")
16763 (cond
16764 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16765 ((and org-support-shift-select (org-region-active-p))
16766 (org-call-for-shift-select 'backward-char))
16767 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16768 ((and (not (eq org-support-shift-select 'always))
16769 (org-on-heading-p))
16770 (let ((org-inhibit-logging
16771 (not org-treat-S-cursor-todo-selection-as-state-change))
16772 (org-inhibit-blocking
16773 (not org-treat-S-cursor-todo-selection-as-state-change)))
16774 (org-call-with-arg 'org-todo 'left)))
16775 ((or (and org-support-shift-select
16776 (not (eq org-support-shift-select 'always))
16777 (org-at-item-bullet-p))
16778 (and (not org-support-shift-select) (org-at-item-p)))
16779 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16780 ((and (not (eq org-support-shift-select 'always))
16781 (org-at-property-p))
16782 (call-interactively 'org-property-previous-allowed-value))
16783 ((org-clocktable-try-shift 'left arg))
16784 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16785 (org-support-shift-select
16786 (org-call-for-shift-select 'backward-char))
16787 (t (org-shiftselect-error))))
16789 (defun org-shiftcontrolright ()
16790 "Switch to next TODO set."
16791 (interactive)
16792 (cond
16793 ((and org-support-shift-select (org-region-active-p))
16794 (org-call-for-shift-select 'forward-word))
16795 ((and (not (eq org-support-shift-select 'always))
16796 (org-on-heading-p))
16797 (org-call-with-arg 'org-todo 'nextset))
16798 (org-support-shift-select
16799 (org-call-for-shift-select 'forward-word))
16800 (t (org-shiftselect-error))))
16802 (defun org-shiftcontrolleft ()
16803 "Switch to previous TODO set."
16804 (interactive)
16805 (cond
16806 ((and org-support-shift-select (org-region-active-p))
16807 (org-call-for-shift-select 'backward-word))
16808 ((and (not (eq org-support-shift-select 'always))
16809 (org-on-heading-p))
16810 (org-call-with-arg 'org-todo 'previousset))
16811 (org-support-shift-select
16812 (org-call-for-shift-select 'backward-word))
16813 (t (org-shiftselect-error))))
16815 (defun org-ctrl-c-ret ()
16816 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16817 (interactive)
16818 (cond
16819 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16820 (t (call-interactively 'org-insert-heading))))
16822 (defun org-copy-special ()
16823 "Copy region in table or copy current subtree.
16824 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16825 See the individual commands for more information."
16826 (interactive)
16827 (call-interactively
16828 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16830 (defun org-cut-special ()
16831 "Cut region in table or cut current subtree.
16832 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16833 See the individual commands for more information."
16834 (interactive)
16835 (call-interactively
16836 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16838 (defun org-paste-special (arg)
16839 "Paste rectangular region into table, or past subtree relative to level.
16840 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16841 See the individual commands for more information."
16842 (interactive "P")
16843 (if (org-at-table-p)
16844 (org-table-paste-rectangle)
16845 (org-paste-subtree arg)))
16847 (defun org-edit-special ()
16848 "Call a special editor for the stuff at point.
16849 When at a table, call the formula editor with `org-table-edit-formulas'.
16850 When at the first line of an src example, call `org-edit-src-code'.
16851 When in an #+include line, visit the include file. Otherwise call
16852 `ffap' to visit the file at point."
16853 (interactive)
16854 (cond
16855 ((org-at-table.el-p)
16856 (org-edit-src-code))
16857 ((org-at-table-p)
16858 (call-interactively 'org-table-edit-formulas))
16859 ((save-excursion
16860 (beginning-of-line 1)
16861 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16862 (find-file (org-trim (match-string 1))))
16863 ((org-edit-src-code))
16864 ((org-edit-fixed-width-region))
16865 (t (call-interactively 'ffap))))
16868 (defun org-ctrl-c-ctrl-c (&optional arg)
16869 "Set tags in headline, or update according to changed information at point.
16871 This command does many different things, depending on context:
16873 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16874 this is what we do.
16876 - If the cursor is on a statistics cookie, update it.
16878 - If the cursor is in a headline, prompt for tags and insert them
16879 into the current line, aligned to `org-tags-column'. When called
16880 with prefix arg, realign all tags in the current buffer.
16882 - If the cursor is in one of the special #+KEYWORD lines, this
16883 triggers scanning the buffer for these lines and updating the
16884 information.
16886 - If the cursor is inside a table, realign the table. This command
16887 works even if the automatic table editor has been turned off.
16889 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16890 the entire table.
16892 - If the cursor is at a footnote reference or definition, jump to
16893 the corresponding definition or references, respectively.
16895 - If the cursor is a the beginning of a dynamic block, update it.
16897 - If the current buffer is a remember buffer, close note and file
16898 it. A prefix argument of 1 files to the default location
16899 without further interaction. A prefix argument of 2 files to
16900 the currently clocking task.
16902 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16903 links in this buffer.
16905 - If the cursor is on a numbered item in a plain list, renumber the
16906 ordered list.
16908 - If the cursor is on a checkbox, toggle it."
16909 (interactive "P")
16910 (let ((org-enable-table-editor t))
16911 (cond
16912 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16913 org-occur-highlights
16914 org-latex-fragment-image-overlays)
16915 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16916 (org-remove-occur-highlights)
16917 (org-remove-latex-fragment-image-overlays)
16918 (message "Temporary highlights/overlays removed from current buffer"))
16919 ((and (local-variable-p 'org-finish-function (current-buffer))
16920 (fboundp org-finish-function))
16921 (funcall org-finish-function))
16922 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16923 ((or (looking-at org-property-start-re)
16924 (org-at-property-p))
16925 (call-interactively 'org-property-action))
16926 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16927 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16928 (or (org-on-heading-p) (org-at-item-p)))
16929 (call-interactively 'org-update-statistics-cookies))
16930 ((org-on-heading-p) (call-interactively 'org-set-tags))
16931 ((org-at-table.el-p)
16932 (message "Use C-c ' to edit table.el tables"))
16933 ((org-at-table-p)
16934 (org-table-maybe-eval-formula)
16935 (if arg
16936 (call-interactively 'org-table-recalculate)
16937 (org-table-maybe-recalculate-line))
16938 (call-interactively 'org-table-align))
16939 ((or (org-footnote-at-reference-p)
16940 (org-footnote-at-definition-p))
16941 (call-interactively 'org-footnote-action))
16942 ((org-at-item-checkbox-p)
16943 (call-interactively 'org-toggle-checkbox))
16944 ((org-at-item-p)
16945 (if arg
16946 (call-interactively 'org-toggle-checkbox)
16947 (call-interactively 'org-maybe-renumber-ordered-list)))
16948 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16949 ;; Dynamic block
16950 (beginning-of-line 1)
16951 (save-excursion (org-update-dblock)))
16952 ((save-excursion
16953 (beginning-of-line 1)
16954 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16955 (cond
16956 ((equal (match-string 1) "TBLFM")
16957 ;; Recalculate the table before this line
16958 (save-excursion
16959 (beginning-of-line 1)
16960 (skip-chars-backward " \r\n\t")
16961 (if (org-at-table-p)
16962 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16964 (let ((org-inhibit-startup-visibility-stuff t)
16965 (org-startup-align-all-tables nil))
16966 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16967 (message "Local setup has been refreshed"))))
16968 ((org-clock-update-time-maybe))
16969 (t (error "C-c C-c can do nothing useful at this location")))))
16971 (defun org-mode-restart ()
16972 "Restart Org-mode, to scan again for special lines.
16973 Also updates the keyword regular expressions."
16974 (interactive)
16975 (org-mode)
16976 (message "Org-mode restarted"))
16978 (defun org-kill-note-or-show-branches ()
16979 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16980 (interactive)
16981 (if (not org-finish-function)
16982 (progn
16983 (hide-subtree)
16984 (call-interactively 'show-branches))
16985 (let ((org-note-abort t))
16986 (funcall org-finish-function))))
16988 (defun org-return (&optional indent)
16989 "Goto next table row or insert a newline.
16990 Calls `org-table-next-row' or `newline', depending on context.
16991 See the individual commands for more information."
16992 (interactive)
16993 (cond
16994 ((bobp) (if indent (newline-and-indent) (newline)))
16995 ((org-at-table-p)
16996 (org-table-justify-field-maybe)
16997 (call-interactively 'org-table-next-row))
16998 ((and org-return-follows-link
16999 (eq (get-text-property (point) 'face) 'org-link))
17000 (call-interactively 'org-open-at-point))
17001 ((and (org-at-heading-p)
17002 (looking-at
17003 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
17004 (org-show-entry)
17005 (end-of-line 1)
17006 (newline))
17007 (t (if indent (newline-and-indent) (newline)))))
17009 (defun org-return-indent ()
17010 "Goto next table row or insert a newline and indent.
17011 Calls `org-table-next-row' or `newline-and-indent', depending on
17012 context. See the individual commands for more information."
17013 (interactive)
17014 (org-return t))
17016 (defun org-ctrl-c-star ()
17017 "Compute table, or change heading status of lines.
17018 Calls `org-table-recalculate' or `org-toggle-heading',
17019 depending on context."
17020 (interactive)
17021 (cond
17022 ((org-at-table-p)
17023 (call-interactively 'org-table-recalculate))
17025 ;; Convert all lines in region to list items
17026 (call-interactively 'org-toggle-heading))))
17028 (defun org-ctrl-c-minus ()
17029 "Insert separator line in table or modify bullet status of line.
17030 Also turns a plain line or a region of lines into list items.
17031 Calls `org-table-insert-hline', `org-toggle-item', or
17032 `org-cycle-list-bullet', depending on context."
17033 (interactive)
17034 (cond
17035 ((org-at-table-p)
17036 (call-interactively 'org-table-insert-hline))
17037 ((org-region-active-p)
17038 (call-interactively 'org-toggle-item))
17039 ((org-in-item-p)
17040 (call-interactively 'org-cycle-list-bullet))
17042 (call-interactively 'org-toggle-item))))
17044 (defun org-toggle-item ()
17045 "Convert headings or normal lines to items, items to normal lines.
17046 If there is no active region, only the current line is considered.
17048 If the first line in the region is a headline, convert all headlines to items.
17050 If the first line in the region is an item, convert all items to normal lines.
17052 If the first line is normal text, add an item bullet to each line."
17053 (interactive)
17054 (let (l2 l beg end)
17055 (if (org-region-active-p)
17056 (setq beg (region-beginning) end (region-end))
17057 (setq beg (point-at-bol)
17058 end (min (1+ (point-at-eol)) (point-max))))
17059 (save-excursion
17060 (goto-char end)
17061 (setq l2 (org-current-line))
17062 (goto-char beg)
17063 (beginning-of-line 1)
17064 (setq l (1- (org-current-line)))
17065 (if (org-at-item-p)
17066 ;; We already have items, de-itemize
17067 (while (< (setq l (1+ l)) l2)
17068 (when (org-at-item-p)
17069 (goto-char (match-beginning 2))
17070 (delete-region (match-beginning 2) (match-end 2))
17071 (and (looking-at "[ \t]+") (replace-match "")))
17072 (beginning-of-line 2))
17073 (if (org-on-heading-p)
17074 ;; Headings, convert to items
17075 (while (< (setq l (1+ l)) l2)
17076 (if (looking-at org-outline-regexp)
17077 (replace-match "- " t t))
17078 (beginning-of-line 2))
17079 ;; normal lines, turn them into items
17080 (while (< (setq l (1+ l)) l2)
17081 (unless (org-at-item-p)
17082 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17083 (replace-match "\\1- \\2")))
17084 (beginning-of-line 2)))))))
17086 (defun org-toggle-heading (&optional nstars)
17087 "Convert headings to normal text, or items or text to headings.
17088 If there is no active region, only the current line is considered.
17090 If the first line is a heading, remove the stars from all headlines
17091 in the region.
17093 If the first line is a plain list item, turn all plain list items
17094 into headings.
17096 If the first line is a normal line, turn each and every line in the
17097 region into a heading.
17099 When converting a line into a heading, the number of stars is chosen
17100 such that the lines become children of the current entry. However,
17101 when a prefix argument is given, its value determines the number of
17102 stars to add."
17103 (interactive "P")
17104 (let (l2 l itemp beg end)
17105 (if (org-region-active-p)
17106 (setq beg (region-beginning) end (region-end))
17107 (setq beg (point-at-bol)
17108 end (min (1+ (point-at-eol)) (point-max))))
17109 (save-excursion
17110 (goto-char end)
17111 (setq l2 (org-current-line))
17112 (goto-char beg)
17113 (beginning-of-line 1)
17114 (setq l (1- (org-current-line)))
17115 (if (org-on-heading-p)
17116 ;; We already have headlines, de-star them
17117 (while (< (setq l (1+ l)) l2)
17118 (when (org-on-heading-p t)
17119 (and (looking-at outline-regexp) (replace-match "")))
17120 (beginning-of-line 2))
17121 (setq itemp (org-at-item-p))
17122 (let* ((stars
17123 (if nstars
17124 (make-string (prefix-numeric-value current-prefix-arg)
17126 (save-excursion
17127 (if (re-search-backward org-complex-heading-regexp nil t)
17128 (match-string 1) ""))))
17129 (add-stars (cond (nstars "")
17130 ((equal stars "") "*")
17131 (org-odd-levels-only "**")
17132 (t "*")))
17133 (rpl (concat stars add-stars " ")))
17134 (while (< (setq l (1+ l)) l2)
17135 (if itemp
17136 (and (org-at-item-p) (replace-match rpl t t))
17137 (unless (org-on-heading-p)
17138 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17139 (replace-match (concat rpl (match-string 2))))))
17140 (beginning-of-line 2)))))))
17142 (defun org-meta-return (&optional arg)
17143 "Insert a new heading or wrap a region in a table.
17144 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17145 See the individual commands for more information."
17146 (interactive "P")
17147 (cond
17148 ((run-hook-with-args-until-success 'org-metareturn-hook))
17149 ((org-at-table-p)
17150 (call-interactively 'org-table-wrap-region))
17151 (t (call-interactively 'org-insert-heading))))
17153 ;;; Menu entries
17155 ;; Define the Org-mode menus
17156 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17157 '("Tbl"
17158 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17159 ["Next Field" org-cycle (org-at-table-p)]
17160 ["Previous Field" org-shifttab (org-at-table-p)]
17161 ["Next Row" org-return (org-at-table-p)]
17162 "--"
17163 ["Blank Field" org-table-blank-field (org-at-table-p)]
17164 ["Edit Field" org-table-edit-field (org-at-table-p)]
17165 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17166 "--"
17167 ("Column"
17168 ["Move Column Left" org-metaleft (org-at-table-p)]
17169 ["Move Column Right" org-metaright (org-at-table-p)]
17170 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17171 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17172 ("Row"
17173 ["Move Row Up" org-metaup (org-at-table-p)]
17174 ["Move Row Down" org-metadown (org-at-table-p)]
17175 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17176 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17177 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17178 "--"
17179 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17180 ("Rectangle"
17181 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17182 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17183 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17184 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17185 "--"
17186 ("Calculate"
17187 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17188 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17189 ["Edit Formulas" org-edit-special (org-at-table-p)]
17190 "--"
17191 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17192 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17193 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17194 "--"
17195 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17196 "--"
17197 ["Sum Column/Rectangle" org-table-sum
17198 (or (org-at-table-p) (org-region-active-p))]
17199 ["Which Column?" org-table-current-column (org-at-table-p)])
17200 ["Debug Formulas"
17201 org-table-toggle-formula-debugger
17202 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17203 ["Show Col/Row Numbers"
17204 org-table-toggle-coordinate-overlays
17205 :style toggle
17206 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17207 "--"
17208 ["Create" org-table-create (and (not (org-at-table-p))
17209 org-enable-table-editor)]
17210 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17211 ["Import from File" org-table-import (not (org-at-table-p))]
17212 ["Export to File" org-table-export (org-at-table-p)]
17213 "--"
17214 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17216 (easy-menu-define org-org-menu org-mode-map "Org menu"
17217 '("Org"
17218 ("Show/Hide"
17219 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17220 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17221 ["Sparse Tree..." org-sparse-tree t]
17222 ["Reveal Context" org-reveal t]
17223 ["Show All" show-all t]
17224 "--"
17225 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17226 "--"
17227 ["New Heading" org-insert-heading t]
17228 ("Navigate Headings"
17229 ["Up" outline-up-heading t]
17230 ["Next" outline-next-visible-heading t]
17231 ["Previous" outline-previous-visible-heading t]
17232 ["Next Same Level" outline-forward-same-level t]
17233 ["Previous Same Level" outline-backward-same-level t]
17234 "--"
17235 ["Jump" org-goto t])
17236 ("Edit Structure"
17237 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17238 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17239 "--"
17240 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17241 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17242 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17243 "--"
17244 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17245 "--"
17246 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17247 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17248 ["Demote Heading" org-metaright (not (org-at-table-p))]
17249 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17250 "--"
17251 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17252 "--"
17253 ["Convert to odd levels" org-convert-to-odd-levels t]
17254 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17255 ("Editing"
17256 ["Emphasis..." org-emphasize t]
17257 ["Edit Source Example" org-edit-special t]
17258 "--"
17259 ["Footnote new/jump" org-footnote-action t]
17260 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17261 ("Archive"
17262 ["Archive (default method)" org-archive-subtree-default t]
17263 "--"
17264 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17265 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17266 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17268 "--"
17269 ("Hyperlinks"
17270 ["Store Link (Global)" org-store-link t]
17271 ["Find existing link to here" org-occur-link-in-agenda-files t]
17272 ["Insert Link" org-insert-link t]
17273 ["Follow Link" org-open-at-point t]
17274 "--"
17275 ["Next link" org-next-link t]
17276 ["Previous link" org-previous-link t]
17277 "--"
17278 ["Descriptive Links"
17279 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17280 :style radio
17281 :selected (member '(org-link) buffer-invisibility-spec)]
17282 ["Literal Links"
17283 (progn
17284 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17285 :style radio
17286 :selected (not (member '(org-link) buffer-invisibility-spec))])
17287 "--"
17288 ("TODO Lists"
17289 ["TODO/DONE/-" org-todo t]
17290 ("Select keyword"
17291 ["Next keyword" org-shiftright (org-on-heading-p)]
17292 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17293 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17294 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17295 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17296 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17297 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17298 "--"
17299 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17300 :selected org-enforce-todo-dependencies :style toggle :active t]
17301 "Settings for tree at point"
17302 ["Do Children sequentially" org-toggle-ordered-property :style radio
17303 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17304 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17305 ["Do Children parallel" org-toggle-ordered-property :style radio
17306 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17307 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17308 "--"
17309 ["Set Priority" org-priority t]
17310 ["Priority Up" org-shiftup t]
17311 ["Priority Down" org-shiftdown t]
17312 "--"
17313 ["Get news from all feeds" org-feed-update-all t]
17314 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17315 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17316 ("TAGS and Properties"
17317 ["Set Tags" org-set-tags-command t]
17318 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17319 "--"
17320 ["Set property" org-set-property t]
17321 ["Column view of properties" org-columns t]
17322 ["Insert Column View DBlock" org-insert-columns-dblock t])
17323 ("Dates and Scheduling"
17324 ["Timestamp" org-time-stamp t]
17325 ["Timestamp (inactive)" org-time-stamp-inactive t]
17326 ("Change Date"
17327 ["1 Day Later" org-shiftright t]
17328 ["1 Day Earlier" org-shiftleft t]
17329 ["1 ... Later" org-shiftup t]
17330 ["1 ... Earlier" org-shiftdown t])
17331 ["Compute Time Range" org-evaluate-time-range t]
17332 ["Schedule Item" org-schedule t]
17333 ["Deadline" org-deadline t]
17334 "--"
17335 ["Custom time format" org-toggle-time-stamp-overlays
17336 :style radio :selected org-display-custom-times]
17337 "--"
17338 ["Goto Calendar" org-goto-calendar t]
17339 ["Date from Calendar" org-date-from-calendar t]
17340 "--"
17341 ["Start/Restart Timer" org-timer-start t]
17342 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17343 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17344 ["Insert Timer String" org-timer t]
17345 ["Insert Timer Item" org-timer-item t])
17346 ("Logging work"
17347 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17348 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17349 ["Clock out" org-clock-out t]
17350 ["Clock cancel" org-clock-cancel t]
17351 "--"
17352 ["Mark as default task" org-clock-mark-default-task t]
17353 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17354 ["Goto running clock" org-clock-goto t]
17355 "--"
17356 ["Display times" org-clock-display t]
17357 ["Create clock table" org-clock-report t]
17358 "--"
17359 ["Record DONE time"
17360 (progn (setq org-log-done (not org-log-done))
17361 (message "Switching to %s will %s record a timestamp"
17362 (car org-done-keywords)
17363 (if org-log-done "automatically" "not")))
17364 :style toggle :selected org-log-done])
17365 "--"
17366 ["Agenda Command..." org-agenda t]
17367 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17368 ("File List for Agenda")
17369 ("Special views current file"
17370 ["TODO Tree" org-show-todo-tree t]
17371 ["Check Deadlines" org-check-deadlines t]
17372 ["Timeline" org-timeline t]
17373 ["Tags/Property tree" org-match-sparse-tree t])
17374 "--"
17375 ["Export/Publish..." org-export t]
17376 ("LaTeX"
17377 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17378 :selected org-cdlatex-mode]
17379 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17380 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17381 ["Modify math symbol" org-cdlatex-math-modify
17382 (org-inside-LaTeX-fragment-p)]
17383 ["Insert citation" org-reftex-citation t]
17384 "--"
17385 ["Export LaTeX fragments as images"
17386 (if (featurep 'org-exp)
17387 (setq org-export-with-LaTeX-fragments
17388 (not org-export-with-LaTeX-fragments))
17389 (require 'org-exp))
17390 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
17391 org-export-with-LaTeX-fragments)]
17392 "--"
17393 ["Template for BEAMER" org-insert-beamer-options-template t])
17394 "--"
17395 ("MobileOrg"
17396 ["Push Files and Views" org-mobile-push t]
17397 ["Get Captured and Flagged" org-mobile-pull t]
17398 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17399 "--"
17400 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17401 "--"
17402 ("Documentation"
17403 ["Show Version" org-version t]
17404 ["Info Documentation" org-info t])
17405 ("Customize"
17406 ["Browse Org Group" org-customize t]
17407 "--"
17408 ["Expand This Menu" org-create-customize-menu
17409 (fboundp 'customize-menu-create)])
17410 ["Send bug report" org-submit-bug-report t]
17411 "--"
17412 ("Refresh/Reload"
17413 ["Refresh setup current buffer" org-mode-restart t]
17414 ["Reload Org (after update)" org-reload t]
17415 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17418 (defun org-info (&optional node)
17419 "Read documentation for Org-mode in the info system.
17420 With optional NODE, go directly to that node."
17421 (interactive)
17422 (info (format "(org)%s" (or node ""))))
17424 ;;;###autoload
17425 (defun org-submit-bug-report ()
17426 "Submit a bug report on Org-mode via mail.
17428 Don't hesitate to report any problems or inaccurate documentation.
17430 If you don't have setup sending mail from (X)Emacs, please copy the
17431 output buffer into your mail program, as it gives us important
17432 information about your Org-mode version and configuration."
17433 (interactive)
17434 (require 'reporter)
17435 (org-load-modules-maybe)
17436 (org-require-autoloaded-modules)
17437 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17438 (reporter-submit-bug-report
17439 "emacs-orgmode@gnu.org"
17440 (org-version)
17441 (let (list)
17442 (save-window-excursion
17443 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17444 (delete-other-windows)
17445 (erase-buffer)
17446 (insert "You are about to submit a bug report to the Org-mode mailing list.
17448 We would like to add your full Org-mode and Outline configuration to the
17449 bug report. This greatly simplifies the work of the maintainer and
17450 other experts on the mailing list.
17452 HOWEVER, some variables you have customized may contain private
17453 information. The names of customers, colleagues, or friends, might
17454 appear in the form of file names, tags, todo states, or search strings.
17455 If you answer yes to the prompt, you might want to check and remove
17456 such private information before sending the email.")
17457 (add-text-properties (point-min) (point-max) '(face org-warning))
17458 (when (yes-or-no-p "Include your Org-mode configuration ")
17459 (mapatoms
17460 (lambda (v)
17461 (and (boundp v)
17462 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17463 (or (and (symbol-value v)
17464 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17465 (and
17466 (get v 'custom-type) (get v 'standard-value)
17467 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17468 (push v list)))))
17469 (kill-buffer (get-buffer "*Warn about privacy*"))
17470 list))
17471 nil nil
17472 "Remember to cover the basics, that is, what you expected to happen and
17473 what in fact did happen. You don't know how to make a good report? See
17475 http://orgmode.org/manual/Feedback.html#Feedback
17477 Your bug report will be posted to the Org-mode mailing list.
17478 ------------------------------------------------------------------------")
17479 (save-excursion
17480 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17481 (replace-match "\\1Bug: \\3 [\\2]")))))
17484 (defun org-install-agenda-files-menu ()
17485 (let ((bl (buffer-list)))
17486 (save-excursion
17487 (while bl
17488 (set-buffer (pop bl))
17489 (if (org-mode-p) (setq bl nil)))
17490 (when (org-mode-p)
17491 (easy-menu-change
17492 '("Org") "File List for Agenda"
17493 (append
17494 (list
17495 ["Edit File List" (org-edit-agenda-file-list) t]
17496 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17497 ["Remove Current File from List" org-remove-file t]
17498 ["Cycle through agenda files" org-cycle-agenda-files t]
17499 ["Occur in all agenda files" org-occur-in-agenda-files t]
17500 "--")
17501 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17503 ;;;; Documentation
17505 ;;;###autoload
17506 (defun org-require-autoloaded-modules ()
17507 (interactive)
17508 (mapc 'require
17509 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17510 org-docbook org-exp org-html org-icalendar
17511 org-id org-latex
17512 org-publish org-remember org-table
17513 org-timer org-xoxo)))
17515 ;;;###autoload
17516 (defun org-reload (&optional uncompiled)
17517 "Reload all org lisp files.
17518 With prefix arg UNCOMPILED, load the uncompiled versions."
17519 (interactive "P")
17520 (require 'find-func)
17521 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17522 (dir-org (file-name-directory (org-find-library-name "org")))
17523 (dir-org-contrib (ignore-errors
17524 (file-name-directory
17525 (org-find-library-name "org-contribdir"))))
17526 (files
17527 (append (directory-files dir-org t file-re)
17528 (and dir-org-contrib
17529 (directory-files dir-org-contrib t file-re))))
17530 (remove-re (concat (if (featurep 'xemacs)
17531 "org-colview" "org-colview-xemacs")
17532 "\\'")))
17533 (setq files (mapcar 'file-name-sans-extension files))
17534 (setq files (mapcar
17535 (lambda (x) (if (string-match remove-re x) nil x))
17536 files))
17537 (setq files (delq nil files))
17538 (mapc
17539 (lambda (f)
17540 (when (featurep (intern (file-name-nondirectory f)))
17541 (if (and (not uncompiled)
17542 (file-exists-p (concat f ".elc")))
17543 (load (concat f ".elc") nil nil t)
17544 (load (concat f ".el") nil nil t))))
17545 files))
17546 (org-version))
17548 ;;;###autoload
17549 (defun org-customize ()
17550 "Call the customize function with org as argument."
17551 (interactive)
17552 (org-load-modules-maybe)
17553 (org-require-autoloaded-modules)
17554 (customize-browse 'org))
17556 (defun org-create-customize-menu ()
17557 "Create a full customization menu for Org-mode, insert it into the menu."
17558 (interactive)
17559 (org-load-modules-maybe)
17560 (org-require-autoloaded-modules)
17561 (if (fboundp 'customize-menu-create)
17562 (progn
17563 (easy-menu-change
17564 '("Org") "Customize"
17565 `(["Browse Org group" org-customize t]
17566 "--"
17567 ,(customize-menu-create 'org)
17568 ["Set" Custom-set t]
17569 ["Save" Custom-save t]
17570 ["Reset to Current" Custom-reset-current t]
17571 ["Reset to Saved" Custom-reset-saved t]
17572 ["Reset to Standard Settings" Custom-reset-standard t]))
17573 (message "\"Org\"-menu now contains full customization menu"))
17574 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17576 ;;;; Miscellaneous stuff
17578 ;;; Generally useful functions
17580 (defun org-get-at-bol (property)
17581 "Get text property PROPERTY at beginning of line."
17582 (get-text-property (point-at-bol) property))
17584 (defun org-find-text-property-in-string (prop s)
17585 "Return the first non-nil value of property PROP in string S."
17586 (or (get-text-property 0 prop s)
17587 (get-text-property (or (next-single-property-change 0 prop s) 0)
17588 prop s)))
17590 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17591 "Display the given MESSAGE as a warning."
17592 (if (fboundp 'display-warning)
17593 (display-warning 'org message
17594 (if (featurep 'xemacs) 'warning :warning))
17595 (let ((buf (get-buffer-create "*Org warnings*")))
17596 (with-current-buffer buf
17597 (goto-char (point-max))
17598 (insert "Warning (Org): " message)
17599 (unless (bolp)
17600 (newline)))
17601 (display-buffer buf)
17602 (sit-for 0))))
17604 (defun org-in-commented-line ()
17605 "Is point in a line starting with `#'?"
17606 (equal (char-after (point-at-bol)) ?#))
17608 (defun org-in-indented-comment-line ()
17609 "Is point in a line starting with `#' after some white space?"
17610 (save-excursion
17611 (save-match-data
17612 (goto-char (point-at-bol))
17613 (looking-at "[ \t]*#"))))
17615 (defun org-in-verbatim-emphasis ()
17616 (save-match-data
17617 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17619 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17620 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17621 (if (and marker (marker-buffer marker)
17622 (buffer-live-p (marker-buffer marker)))
17623 (progn
17624 (switch-to-buffer (marker-buffer marker))
17625 (if (or (> marker (point-max)) (< marker (point-min)))
17626 (widen))
17627 (goto-char marker)
17628 (org-show-context 'org-goto))
17629 (if bookmark
17630 (bookmark-jump bookmark)
17631 (error "Cannot find location"))))
17633 (defun org-quote-csv-field (s)
17634 "Quote field for inclusion in CSV material."
17635 (if (string-match "[\",]" s)
17636 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17639 (defun org-plist-delete (plist property)
17640 "Delete PROPERTY from PLIST.
17641 This is in contrast to merely setting it to 0."
17642 (let (p)
17643 (while plist
17644 (if (not (eq property (car plist)))
17645 (setq p (plist-put p (car plist) (nth 1 plist))))
17646 (setq plist (cddr plist)))
17649 (defun org-force-self-insert (N)
17650 "Needed to enforce self-insert under remapping."
17651 (interactive "p")
17652 (self-insert-command N))
17654 (defun org-string-width (s)
17655 "Compute width of string, ignoring invisible characters.
17656 This ignores character with invisibility property `org-link', and also
17657 characters with property `org-cwidth', because these will become invisible
17658 upon the next fontification round."
17659 (let (b l)
17660 (when (or (eq t buffer-invisibility-spec)
17661 (assq 'org-link buffer-invisibility-spec))
17662 (while (setq b (text-property-any 0 (length s)
17663 'invisible 'org-link s))
17664 (setq s (concat (substring s 0 b)
17665 (substring s (or (next-single-property-change
17666 b 'invisible s) (length s)))))))
17667 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17668 (setq s (concat (substring s 0 b)
17669 (substring s (or (next-single-property-change
17670 b 'org-cwidth s) (length s))))))
17671 (setq l (string-width s) b -1)
17672 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17673 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17676 (defun org-get-indentation (&optional line)
17677 "Get the indentation of the current line, interpreting tabs.
17678 When LINE is given, assume it represents a line and compute its indentation."
17679 (if line
17680 (if (string-match "^ *" (org-remove-tabs line))
17681 (match-end 0))
17682 (save-excursion
17683 (beginning-of-line 1)
17684 (skip-chars-forward " \t")
17685 (current-column))))
17687 (defun org-remove-tabs (s &optional width)
17688 "Replace tabulators in S with spaces.
17689 Assumes that s is a single line, starting in column 0."
17690 (setq width (or width tab-width))
17691 (while (string-match "\t" s)
17692 (setq s (replace-match
17693 (make-string
17694 (- (* width (/ (+ (match-beginning 0) width) width))
17695 (match-beginning 0)) ?\ )
17696 t t s)))
17699 (defun org-fix-indentation (line ind)
17700 "Fix indentation in LINE.
17701 IND is a cons cell with target and minimum indentation.
17702 If the current indentation in LINE is smaller than the minimum,
17703 leave it alone. If it is larger than ind, set it to the target."
17704 (let* ((l (org-remove-tabs line))
17705 (i (org-get-indentation l))
17706 (i1 (car ind)) (i2 (cdr ind)))
17707 (if (>= i i2) (setq l (substring line i2)))
17708 (if (> i1 0)
17709 (concat (make-string i1 ?\ ) l)
17710 l)))
17712 (defun org-remove-indentation (code &optional n)
17713 "Remove the maximum common indentation from the lines in CODE.
17714 N may optionally be the number of spaces to remove."
17715 (with-temp-buffer
17716 (insert code)
17717 (org-do-remove-indentation n)
17718 (buffer-string)))
17720 (defun org-do-remove-indentation (&optional n)
17721 "Remove the maximum common indentation from the buffer."
17722 (untabify (point-min) (point-max))
17723 (let ((min 10000) re)
17724 (if n
17725 (setq min n)
17726 (goto-char (point-min))
17727 (while (re-search-forward "^ *[^ \n]" nil t)
17728 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17729 (unless (or (= min 0) (= min 10000))
17730 (setq re (format "^ \\{%d\\}" min))
17731 (goto-char (point-min))
17732 (while (re-search-forward re nil t)
17733 (replace-match "")
17734 (end-of-line 1))
17735 min)))
17737 (defun org-fill-template (template alist)
17738 "Find each %key of ALIST in TEMPLATE and replace it."
17739 (let ((case-fold-search nil)
17740 entry key value)
17741 (setq alist (sort (copy-sequence alist)
17742 (lambda (a b) (< (length (car a)) (length (car b))))))
17743 (while (setq entry (pop alist))
17744 (setq template
17745 (replace-regexp-in-string
17746 (concat "%" (regexp-quote (car entry)))
17747 (cdr entry) template t t)))
17748 template))
17750 (defun org-base-buffer (buffer)
17751 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17752 (if (not buffer)
17753 buffer
17754 (or (buffer-base-buffer buffer)
17755 buffer)))
17757 (defun org-trim (s)
17758 "Remove whitespace at beginning and end of string."
17759 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17760 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17763 (defun org-wrap (string &optional width lines)
17764 "Wrap string to either a number of lines, or a width in characters.
17765 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17766 that costs. If there is a word longer than WIDTH, the text is actually
17767 wrapped to the length of that word.
17768 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17769 many lines, whatever width that takes.
17770 The return value is a list of lines, without newlines at the end."
17771 (let* ((words (org-split-string string "[ \t\n]+"))
17772 (maxword (apply 'max (mapcar 'org-string-width words)))
17773 w ll)
17774 (cond (width
17775 (org-do-wrap words (max maxword width)))
17776 (lines
17777 (setq w maxword)
17778 (setq ll (org-do-wrap words maxword))
17779 (if (<= (length ll) lines)
17781 (setq ll words)
17782 (while (> (length ll) lines)
17783 (setq w (1+ w))
17784 (setq ll (org-do-wrap words w)))
17785 ll))
17786 (t (error "Cannot wrap this")))))
17788 (defun org-do-wrap (words width)
17789 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17790 (let (lines line)
17791 (while words
17792 (setq line (pop words))
17793 (while (and words (< (+ (length line) (length (car words))) width))
17794 (setq line (concat line " " (pop words))))
17795 (setq lines (push line lines)))
17796 (nreverse lines)))
17798 (defun org-split-string (string &optional separators)
17799 "Splits STRING into substrings at SEPARATORS.
17800 No empty strings are returned if there are matches at the beginning
17801 and end of string."
17802 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17803 (start 0)
17804 notfirst
17805 (list nil))
17806 (while (and (string-match rexp string
17807 (if (and notfirst
17808 (= start (match-beginning 0))
17809 (< start (length string)))
17810 (1+ start) start))
17811 (< (match-beginning 0) (length string)))
17812 (setq notfirst t)
17813 (or (eq (match-beginning 0) 0)
17814 (and (eq (match-beginning 0) (match-end 0))
17815 (eq (match-beginning 0) start))
17816 (setq list
17817 (cons (substring string start (match-beginning 0))
17818 list)))
17819 (setq start (match-end 0)))
17820 (or (eq start (length string))
17821 (setq list
17822 (cons (substring string start)
17823 list)))
17824 (nreverse list)))
17826 (defun org-quote-vert (s)
17827 "Replace \"|\" with \"\\vert\"."
17828 (while (string-match "|" s)
17829 (setq s (replace-match "\\vert" t t s)))
17832 (defun org-uuidgen-p (s)
17833 "Is S an ID created by UUIDGEN?"
17834 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17836 (defun org-context ()
17837 "Return a list of contexts of the current cursor position.
17838 If several contexts apply, all are returned.
17839 Each context entry is a list with a symbol naming the context, and
17840 two positions indicating start and end of the context. Possible
17841 contexts are:
17843 :headline anywhere in a headline
17844 :headline-stars on the leading stars in a headline
17845 :todo-keyword on a TODO keyword (including DONE) in a headline
17846 :tags on the TAGS in a headline
17847 :priority on the priority cookie in a headline
17848 :item on the first line of a plain list item
17849 :item-bullet on the bullet/number of a plain list item
17850 :checkbox on the checkbox in a plain list item
17851 :table in an org-mode table
17852 :table-special on a special filed in a table
17853 :table-table in a table.el table
17854 :link on a hyperlink
17855 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17856 :target on a <<target>>
17857 :radio-target on a <<<radio-target>>>
17858 :latex-fragment on a LaTeX fragment
17859 :latex-preview on a LaTeX fragment with overlayed preview image
17861 This function expects the position to be visible because it uses font-lock
17862 faces as a help to recognize the following contexts: :table-special, :link,
17863 and :keyword."
17864 (let* ((f (get-text-property (point) 'face))
17865 (faces (if (listp f) f (list f)))
17866 (p (point)) clist o)
17867 ;; First the large context
17868 (cond
17869 ((org-on-heading-p t)
17870 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17871 (when (progn
17872 (beginning-of-line 1)
17873 (looking-at org-todo-line-tags-regexp))
17874 (push (org-point-in-group p 1 :headline-stars) clist)
17875 (push (org-point-in-group p 2 :todo-keyword) clist)
17876 (push (org-point-in-group p 4 :tags) clist))
17877 (goto-char p)
17878 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17879 (if (looking-at "\\[#[A-Z0-9]\\]")
17880 (push (org-point-in-group p 0 :priority) clist)))
17882 ((org-at-item-p)
17883 (push (org-point-in-group p 2 :item-bullet) clist)
17884 (push (list :item (point-at-bol)
17885 (save-excursion (org-end-of-item) (point)))
17886 clist)
17887 (and (org-at-item-checkbox-p)
17888 (push (org-point-in-group p 0 :checkbox) clist)))
17890 ((org-at-table-p)
17891 (push (list :table (org-table-begin) (org-table-end)) clist)
17892 (if (memq 'org-formula faces)
17893 (push (list :table-special
17894 (previous-single-property-change p 'face)
17895 (next-single-property-change p 'face)) clist)))
17896 ((org-at-table-p 'any)
17897 (push (list :table-table) clist)))
17898 (goto-char p)
17900 ;; Now the small context
17901 (cond
17902 ((org-at-timestamp-p)
17903 (push (org-point-in-group p 0 :timestamp) clist))
17904 ((memq 'org-link faces)
17905 (push (list :link
17906 (previous-single-property-change p 'face)
17907 (next-single-property-change p 'face)) clist))
17908 ((memq 'org-special-keyword faces)
17909 (push (list :keyword
17910 (previous-single-property-change p 'face)
17911 (next-single-property-change p 'face)) clist))
17912 ((org-on-target-p)
17913 (push (org-point-in-group p 0 :target) clist)
17914 (goto-char (1- (match-beginning 0)))
17915 (if (looking-at org-radio-target-regexp)
17916 (push (org-point-in-group p 0 :radio-target) clist))
17917 (goto-char p))
17918 ((setq o (car (delq nil
17919 (mapcar
17920 (lambda (x)
17921 (if (memq x org-latex-fragment-image-overlays) x))
17922 (overlays-at (point))))))
17923 (push (list :latex-fragment
17924 (overlay-start o) (overlay-end o)) clist)
17925 (push (list :latex-preview
17926 (overlay-start o) (overlay-end o)) clist))
17927 ((org-inside-LaTeX-fragment-p)
17928 ;; FIXME: positions wrong.
17929 (push (list :latex-fragment (point) (point)) clist)))
17931 (setq clist (nreverse (delq nil clist)))
17932 clist))
17934 ;; FIXME: Compare with at-regexp-p Do we need both?
17935 (defun org-in-regexp (re &optional nlines visually)
17936 "Check if point is inside a match of regexp.
17937 Normally only the current line is checked, but you can include NLINES extra
17938 lines both before and after point into the search.
17939 If VISUALLY is set, require that the cursor is not after the match but
17940 really on, so that the block visually is on the match."
17941 (catch 'exit
17942 (let ((pos (point))
17943 (eol (point-at-eol (+ 1 (or nlines 0))))
17944 (inc (if visually 1 0)))
17945 (save-excursion
17946 (beginning-of-line (- 1 (or nlines 0)))
17947 (while (re-search-forward re eol t)
17948 (if (and (<= (match-beginning 0) pos)
17949 (>= (+ inc (match-end 0)) pos))
17950 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17952 (defun org-at-regexp-p (regexp)
17953 "Is point inside a match of REGEXP in the current line?"
17954 (catch 'exit
17955 (save-excursion
17956 (let ((pos (point)) (end (point-at-eol)))
17957 (beginning-of-line 1)
17958 (while (re-search-forward regexp end t)
17959 (if (and (<= (match-beginning 0) pos)
17960 (>= (match-end 0) pos))
17961 (throw 'exit t)))
17962 nil))))
17964 (defun org-in-regexps-block-p (start-re end-re)
17965 "Returns t if the current point is between matches of START-RE and END-RE.
17966 This will also return to if point is on one of the two matches."
17967 (interactive)
17968 (let ((p (point)))
17969 (save-excursion
17970 (and (or (org-at-regexp-p start-re)
17971 (re-search-backward start-re nil t))
17972 (re-search-forward end-re nil t)
17973 (>= (point) p)))))
17975 (defun org-occur-in-agenda-files (regexp &optional nlines)
17976 "Call `multi-occur' with buffers for all agenda files."
17977 (interactive "sOrg-files matching: \np")
17978 (let* ((files (org-agenda-files))
17979 (tnames (mapcar 'file-truename files))
17980 (extra org-agenda-text-search-extra-files)
17982 (when (eq (car extra) 'agenda-archives)
17983 (setq extra (cdr extra))
17984 (setq files (org-add-archive-files files)))
17985 (while (setq f (pop extra))
17986 (unless (member (file-truename f) tnames)
17987 (add-to-list 'files f 'append)
17988 (add-to-list 'tnames (file-truename f) 'append)))
17989 (multi-occur
17990 (mapcar (lambda (x)
17991 (with-current-buffer
17992 (or (get-file-buffer x) (find-file-noselect x))
17993 (widen)
17994 (current-buffer)))
17995 files)
17996 regexp)))
17998 (if (boundp 'occur-mode-find-occurrence-hook)
17999 ;; Emacs 23
18000 (add-hook 'occur-mode-find-occurrence-hook
18001 (lambda ()
18002 (when (org-mode-p)
18003 (org-reveal))))
18004 ;; Emacs 22
18005 (defadvice occur-mode-goto-occurrence
18006 (after org-occur-reveal activate)
18007 (and (org-mode-p) (org-reveal)))
18008 (defadvice occur-mode-goto-occurrence-other-window
18009 (after org-occur-reveal activate)
18010 (and (org-mode-p) (org-reveal)))
18011 (defadvice occur-mode-display-occurrence
18012 (after org-occur-reveal activate)
18013 (when (org-mode-p)
18014 (let ((pos (occur-mode-find-occurrence)))
18015 (with-current-buffer (marker-buffer pos)
18016 (save-excursion
18017 (goto-char pos)
18018 (org-reveal)))))))
18020 (defun org-occur-link-in-agenda-files ()
18021 "Create a link and search for it in the agendas.
18022 The link is not stored in `org-stored-links', it is just created
18023 for the search purpose."
18024 (interactive)
18025 (let ((link (condition-case nil
18026 (org-store-link nil)
18027 (error "Unable to create a link to here"))))
18028 (org-occur-in-agenda-files (regexp-quote link))))
18030 (defun org-uniquify (list)
18031 "Remove duplicate elements from LIST."
18032 (let (res)
18033 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18034 res))
18036 (defun org-delete-all (elts list)
18037 "Remove all elements in ELTS from LIST."
18038 (while elts
18039 (setq list (delete (pop elts) list)))
18040 list)
18042 (defun org-remove-if (predicate seq)
18043 "Remove everything from SEQ that fulfills PREDICATE."
18044 (let (res e)
18045 (while seq
18046 (setq e (pop seq))
18047 (if (not (funcall predicate e)) (push e res)))
18048 (nreverse res)))
18050 (defun org-remove-if-not (predicate seq)
18051 "Remove everything from SEQ that does not fulfill PREDICATE."
18052 (let (res e)
18053 (while seq
18054 (setq e (pop seq))
18055 (if (funcall predicate e) (push e res)))
18056 (nreverse res)))
18058 (defun org-back-over-empty-lines ()
18059 "Move backwards over whitespace, to the beginning of the first empty line.
18060 Returns the number of empty lines passed."
18061 (let ((pos (point)))
18062 (skip-chars-backward " \t\n\r")
18063 (beginning-of-line 2)
18064 (goto-char (min (point) pos))
18065 (count-lines (point) pos)))
18067 (defun org-skip-whitespace ()
18068 (skip-chars-forward " \t\n\r"))
18070 (defun org-point-in-group (point group &optional context)
18071 "Check if POINT is in match-group GROUP.
18072 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18073 match. If the match group does ot exist or point is not inside it,
18074 return nil."
18075 (and (match-beginning group)
18076 (>= point (match-beginning group))
18077 (<= point (match-end group))
18078 (if context
18079 (list context (match-beginning group) (match-end group))
18080 t)))
18082 (defun org-switch-to-buffer-other-window (&rest args)
18083 "Switch to buffer in a second window on the current frame.
18084 In particular, do not allow pop-up frames."
18085 (let (pop-up-frames special-display-buffer-names special-display-regexps
18086 special-display-function)
18087 (apply 'switch-to-buffer-other-window args)))
18089 (defun org-combine-plists (&rest plists)
18090 "Create a single property list from all plists in PLISTS.
18091 The process starts by copying the first list, and then setting properties
18092 from the other lists. Settings in the last list are the most significant
18093 ones and overrule settings in the other lists."
18094 (let ((rtn (copy-sequence (pop plists)))
18095 p v ls)
18096 (while plists
18097 (setq ls (pop plists))
18098 (while ls
18099 (setq p (pop ls) v (pop ls))
18100 (setq rtn (plist-put rtn p v))))
18101 rtn))
18103 (defun org-move-line-down (arg)
18104 "Move the current line down. With prefix argument, move it past ARG lines."
18105 (interactive "p")
18106 (let ((col (current-column))
18107 beg end pos)
18108 (beginning-of-line 1) (setq beg (point))
18109 (beginning-of-line 2) (setq end (point))
18110 (beginning-of-line (+ 1 arg))
18111 (setq pos (move-marker (make-marker) (point)))
18112 (insert (delete-and-extract-region beg end))
18113 (goto-char pos)
18114 (org-move-to-column col)))
18116 (defun org-move-line-up (arg)
18117 "Move the current line up. With prefix argument, move it past ARG lines."
18118 (interactive "p")
18119 (let ((col (current-column))
18120 beg end pos)
18121 (beginning-of-line 1) (setq beg (point))
18122 (beginning-of-line 2) (setq end (point))
18123 (beginning-of-line (- arg))
18124 (setq pos (move-marker (make-marker) (point)))
18125 (insert (delete-and-extract-region beg end))
18126 (goto-char pos)
18127 (org-move-to-column col)))
18129 (defun org-replace-escapes (string table)
18130 "Replace %-escapes in STRING with values in TABLE.
18131 TABLE is an association list with keys like \"%a\" and string values.
18132 The sequences in STRING may contain normal field width and padding information,
18133 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18134 so values can contain further %-escapes if they are define later in TABLE."
18135 (let ((tbl (copy-alist table))
18136 (case-fold-search nil)
18137 (pchg 0)
18138 e re rpl)
18139 (while (setq e (pop tbl))
18140 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18141 (when (and (cdr e) (string-match re (cdr e)))
18142 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18143 (safe "SREF"))
18144 (add-text-properties 0 3 (list 'sref sref) safe)
18145 (setcdr e (replace-match safe t t (cdr e)))))
18146 (while (string-match re string)
18147 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18148 (cdr e)))
18149 (setq string (replace-match rpl t t string))))
18150 (while (setq pchg (next-property-change pchg string))
18151 (let ((sref (get-text-property pchg 'sref string)))
18152 (when (and sref (string-match "SREF" string pchg))
18153 (setq string (replace-match sref t t string)))))
18154 string))
18156 (defun org-sublist (list start end)
18157 "Return a section of LIST, from START to END.
18158 Counting starts at 1."
18159 (let (rtn (c start))
18160 (setq list (nthcdr (1- start) list))
18161 (while (and list (<= c end))
18162 (push (pop list) rtn)
18163 (setq c (1+ c)))
18164 (nreverse rtn)))
18166 (defun org-find-base-buffer-visiting (file)
18167 "Like `find-buffer-visiting' but always return the base buffer and
18168 not an indirect buffer."
18169 (let ((buf (or (get-file-buffer file)
18170 (find-buffer-visiting file))))
18171 (if buf
18172 (or (buffer-base-buffer buf) buf)
18173 nil)))
18175 (defun org-image-file-name-regexp (&optional extensions)
18176 "Return regexp matching the file names of images.
18177 If EXTENSIONS is given, only match these."
18178 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18179 (image-file-name-regexp)
18180 (let ((image-file-name-extensions
18181 (or extensions
18182 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18183 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18184 (concat "\\."
18185 (regexp-opt (nconc (mapcar 'upcase
18186 image-file-name-extensions)
18187 image-file-name-extensions)
18189 "\\'"))))
18191 (defun org-file-image-p (file &optional extensions)
18192 "Return non-nil if FILE is an image."
18193 (save-match-data
18194 (string-match (org-image-file-name-regexp extensions) file)))
18196 (defun org-get-cursor-date ()
18197 "Return the date at cursor in as a time.
18198 This works in the calendar and in the agenda, anywhere else it just
18199 returns the current time."
18200 (let (date day defd)
18201 (cond
18202 ((eq major-mode 'calendar-mode)
18203 (setq date (calendar-cursor-to-date)
18204 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18205 ((eq major-mode 'org-agenda-mode)
18206 (setq day (get-text-property (point) 'day))
18207 (if day
18208 (setq date (calendar-gregorian-from-absolute day)
18209 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18210 (nth 2 date))))))
18211 (or defd (current-time))))
18213 (defvar org-agenda-action-marker (make-marker)
18214 "Marker pointing to the entry for the next agenda action.")
18216 (defun org-mark-entry-for-agenda-action ()
18217 "Mark the current entry as target of an agenda action.
18218 Agenda actions are actions executed from the agenda with the key `k',
18219 which make use of the date at the cursor."
18220 (interactive)
18221 (move-marker org-agenda-action-marker
18222 (save-excursion (org-back-to-heading t) (point))
18223 (current-buffer))
18224 (message
18225 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18227 ;;; Paragraph filling stuff.
18228 ;; We want this to be just right, so use the full arsenal.
18230 (defun org-indent-line-function ()
18231 "Indent line like previous, but further if previous was headline or item."
18232 (interactive)
18233 (let* ((pos (point))
18234 (itemp (org-at-item-p))
18235 (case-fold-search t)
18236 (org-drawer-regexp (or org-drawer-regexp "\000"))
18237 column bpos bcol tpos tcol bullet btype bullet-type)
18238 ;; Find the previous relevant line
18239 (beginning-of-line 1)
18240 (cond
18241 ((looking-at "#") (setq column 0))
18242 ((looking-at "\\*+ ") (setq column 0))
18243 ((and (looking-at "[ \t]*:END:")
18244 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18245 (save-excursion
18246 (goto-char (1- (match-beginning 1)))
18247 (setq column (current-column))))
18248 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18249 (save-excursion
18250 (re-search-backward
18251 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18252 (setq column (org-get-indentation (match-string 0))))
18254 (beginning-of-line 0)
18255 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18256 (not (looking-at "[ \t]*:END:"))
18257 (not (looking-at org-drawer-regexp)))
18258 (beginning-of-line 0))
18259 (cond
18260 ((looking-at "\\*+[ \t]+")
18261 (if (not org-adapt-indentation)
18262 (setq column 0)
18263 (goto-char (match-end 0))
18264 (setq column (current-column))))
18265 ((looking-at org-drawer-regexp)
18266 (goto-char (1- (match-beginning 1)))
18267 (setq column (current-column)))
18268 ((looking-at "\\([ \t]*\\):END:")
18269 (goto-char (match-end 1))
18270 (setq column (current-column)))
18271 ((org-in-item-p)
18272 (org-beginning-of-item)
18273 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18274 (setq bpos (match-beginning 1) tpos (match-end 0)
18275 bcol (progn (goto-char bpos) (current-column))
18276 tcol (progn (goto-char tpos) (current-column))
18277 bullet (match-string 1)
18278 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18279 (if (> tcol (+ bcol org-description-max-indent))
18280 (setq tcol (+ bcol 5)))
18281 (if (not itemp)
18282 (setq column tcol)
18283 (goto-char pos)
18284 (beginning-of-line 1)
18285 (if (looking-at "\\S-")
18286 (progn
18287 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18288 (setq bullet (match-string 1)
18289 btype (if (string-match "[0-9]" bullet) "n" bullet))
18290 (setq column (if (equal btype bullet-type) bcol tcol)))
18291 (setq column (org-get-indentation)))))
18292 (t (setq column (org-get-indentation))))))
18293 (goto-char pos)
18294 (if (<= (current-column) (current-indentation))
18295 (org-indent-line-to column)
18296 (save-excursion (org-indent-line-to column)))
18297 (setq column (current-column))
18298 (beginning-of-line 1)
18299 (if (looking-at
18300 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18301 (replace-match (concat (match-string 1)
18302 (format org-property-format
18303 (match-string 2) (match-string 3)))
18304 t t))
18305 (org-move-to-column column)))
18307 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18308 "Variable to store copy of `adaptive-fill-regexp'.
18309 Since `adaptive-fill-regexp' is set to never match, we need to
18310 store a backup of its value before entering `org-mode' so that
18311 the functionality can be provided as a fall-back.")
18313 (defun org-set-autofill-regexps ()
18314 (interactive)
18315 ;; In the paragraph separator we include headlines, because filling
18316 ;; text in a line directly attached to a headline would otherwise
18317 ;; fill the headline as well.
18318 (org-set-local 'comment-start-skip "^#+[ \t]*")
18319 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18320 ;; The paragraph starter includes hand-formatted lists.
18321 (org-set-local
18322 'paragraph-start
18323 (concat
18324 "\f" "\\|"
18325 "[ ]*$" "\\|"
18326 "\\*+ " "\\|"
18327 "[ \t]*#" "\\|"
18328 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18329 "[ \t]*[:|]" "\\|"
18330 "\\$\\$" "\\|"
18331 "\\\\\\(begin\\|end\\|[][]\\)"))
18332 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18333 ;; But only if the user has not turned off tables or fixed-width regions
18334 (org-set-local
18335 'auto-fill-inhibit-regexp
18336 (concat "\\*+ \\|#\\+"
18337 "\\|[ \t]*" org-keyword-time-regexp
18338 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18339 (concat
18340 "\\|[ \t]*["
18341 (if org-enable-table-editor "|" "")
18342 (if org-enable-fixed-width-editor ":" "")
18343 "]"))))
18344 ;; We use our own fill-paragraph function, to make sure that tables
18345 ;; and fixed-width regions are not wrapped. That function will pass
18346 ;; through to `fill-paragraph' when appropriate.
18347 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18348 ;; Adaptive filling: To get full control, first make sure that
18349 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18350 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18351 (org-set-local 'org-adaptive-fill-regexp-backup
18352 adaptive-fill-regexp))
18353 (org-set-local 'adaptive-fill-regexp "\000")
18354 (org-set-local 'adaptive-fill-function
18355 'org-adaptive-fill-function)
18356 (org-set-local
18357 'align-mode-rules-list
18358 '((org-in-buffer-settings
18359 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18360 (modes . '(org-mode))))))
18362 (defun org-fill-paragraph (&optional justify)
18363 "Re-align a table, pass through to fill-paragraph if no table."
18364 (let ((table-p (org-at-table-p))
18365 (table.el-p (org-at-table.el-p)))
18366 (cond ((and (equal (char-after (point-at-bol)) ?*)
18367 (save-excursion (goto-char (point-at-bol))
18368 (looking-at outline-regexp)))
18369 t) ; skip headlines
18370 (table.el-p t) ; skip table.el tables
18371 (table-p (org-table-align) t) ; align org-mode tables
18372 (t nil)))) ; call paragraph-fill
18374 ;; For reference, this is the default value of adaptive-fill-regexp
18375 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18377 (defun org-adaptive-fill-function ()
18378 "Return a fill prefix for org-mode files.
18379 In particular, this makes sure hanging paragraphs for hand-formatted lists
18380 work correctly."
18381 (cond
18382 ;; Comment line
18383 ((looking-at "#[ \t]+")
18384 (match-string-no-properties 0))
18385 ;; Description list
18386 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18387 (save-excursion
18388 (if (> (match-end 1) (+ (match-beginning 1)
18389 org-description-max-indent))
18390 (goto-char (+ (match-beginning 1) 5))
18391 (goto-char (match-end 0)))
18392 (make-string (current-column) ?\ )))
18393 ;; Ordered or unordered list
18394 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18395 (save-excursion
18396 (goto-char (match-end 0))
18397 (make-string (current-column) ?\ )))
18398 ;; Other text
18399 ((looking-at org-adaptive-fill-regexp-backup)
18400 (match-string-no-properties 0))))
18402 ;;; Other stuff.
18404 (defun org-toggle-fixed-width-section (arg)
18405 "Toggle the fixed-width export.
18406 If there is no active region, the QUOTE keyword at the current headline is
18407 inserted or removed. When present, it causes the text between this headline
18408 and the next to be exported as fixed-width text, and unmodified.
18409 If there is an active region, this command adds or removes a colon as the
18410 first character of this line. If the first character of a line is a colon,
18411 this line is also exported in fixed-width font."
18412 (interactive "P")
18413 (let* ((cc 0)
18414 (regionp (org-region-active-p))
18415 (beg (if regionp (region-beginning) (point)))
18416 (end (if regionp (region-end)))
18417 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18418 (case-fold-search nil)
18419 (re "[ \t]*\\(: \\)")
18420 off)
18421 (if regionp
18422 (save-excursion
18423 (goto-char beg)
18424 (setq cc (current-column))
18425 (beginning-of-line 1)
18426 (setq off (looking-at re))
18427 (while (> nlines 0)
18428 (setq nlines (1- nlines))
18429 (beginning-of-line 1)
18430 (cond
18431 (arg
18432 (org-move-to-column cc t)
18433 (insert ": \n")
18434 (forward-line -1))
18435 ((and off (looking-at re))
18436 (replace-match "" t t nil 1))
18437 ((not off) (org-move-to-column cc t) (insert ": ")))
18438 (forward-line 1)))
18439 (save-excursion
18440 (org-back-to-heading)
18441 (if (looking-at (concat outline-regexp
18442 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18443 (replace-match "" t t nil 1)
18444 (if (looking-at outline-regexp)
18445 (progn
18446 (goto-char (match-end 0))
18447 (insert org-quote-string " "))))))))
18449 (defun org-reftex-citation ()
18450 "Use reftex-citation to insert a citation into the buffer.
18451 This looks for a line like
18453 #+BIBLIOGRAPHY: foo plain option:-d
18455 and derives from it that foo.bib is the bibliography file relevant
18456 for this document. It then installs the necessary environment for RefTeX
18457 to work in this buffer and calls `reftex-citation' to insert a citation
18458 into the buffer.
18460 Export of such citations to both LaTeX and HTML is handled by the contributed
18461 package org-exp-bibtex by Taru Karttunen."
18462 (interactive)
18463 (let ((reftex-docstruct-symbol 'rds)
18464 (reftex-cite-format "\\cite{%l}")
18465 rds bib)
18466 (save-excursion
18467 (save-restriction
18468 (widen)
18469 (let ((case-fold-search t)
18470 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18471 (if (not (save-excursion
18472 (or (re-search-forward re nil t)
18473 (re-search-backward re nil t))))
18474 (error "No bibliography defined in file")
18475 (setq bib (concat (match-string 1) ".bib")
18476 rds (list (list 'bib bib)))))))
18477 (call-interactively 'reftex-citation)))
18479 ;;;; Functions extending outline functionality
18481 (defun org-beginning-of-line (&optional arg)
18482 "Go to the beginning of the current line. If that is invisible, continue
18483 to a visible line beginning. This makes the function of C-a more intuitive.
18484 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18485 first attempt, and only move to after the tags when the cursor is already
18486 beyond the end of the headline."
18487 (interactive "P")
18488 (let ((pos (point))
18489 (special (if (consp org-special-ctrl-a/e)
18490 (car org-special-ctrl-a/e)
18491 org-special-ctrl-a/e))
18492 refpos)
18493 (if (org-bound-and-true-p line-move-visual)
18494 (beginning-of-visual-line 1)
18495 (beginning-of-line 1))
18496 (if (and arg (fboundp 'move-beginning-of-line))
18497 (call-interactively 'move-beginning-of-line)
18498 (if (bobp)
18500 (backward-char 1)
18501 (if (org-invisible-p)
18502 (while (and (not (bobp)) (org-invisible-p))
18503 (backward-char 1)
18504 (beginning-of-line 1))
18505 (forward-char 1))))
18506 (when special
18507 (cond
18508 ((and (looking-at org-complex-heading-regexp)
18509 (= (char-after (match-end 1)) ?\ ))
18510 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18511 (point-at-eol)))
18512 (goto-char
18513 (if (eq special t)
18514 (cond ((> pos refpos) refpos)
18515 ((= pos (point)) refpos)
18516 (t (point)))
18517 (cond ((> pos (point)) (point))
18518 ((not (eq last-command this-command)) (point))
18519 (t refpos)))))
18520 ((org-at-item-p)
18521 (goto-char
18522 (if (eq special t)
18523 (cond ((> pos (match-end 4)) (match-end 4))
18524 ((= pos (point)) (match-end 4))
18525 (t (point)))
18526 (cond ((> pos (point)) (point))
18527 ((not (eq last-command this-command)) (point))
18528 (t (match-end 4))))))))
18529 (org-no-warnings
18530 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18532 (defun org-end-of-line (&optional arg)
18533 "Go to the end of the line.
18534 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18535 first attempt, and only move to after the tags when the cursor is already
18536 beyond the end of the headline."
18537 (interactive "P")
18538 (let ((special (if (consp org-special-ctrl-a/e)
18539 (cdr org-special-ctrl-a/e)
18540 org-special-ctrl-a/e)))
18541 (if (or (not special)
18542 (not (org-on-heading-p))
18543 arg)
18544 (call-interactively
18545 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18546 ((fboundp 'move-end-of-line) 'move-end-of-line)
18547 (t 'end-of-line)))
18548 (let ((pos (point)))
18549 (beginning-of-line 1)
18550 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18551 (if (eq special t)
18552 (if (or (< pos (match-beginning 1))
18553 (= pos (match-end 0)))
18554 (goto-char (match-beginning 1))
18555 (goto-char (match-end 0)))
18556 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18557 (goto-char (match-end 0))
18558 (goto-char (match-beginning 1))))
18559 (call-interactively (if (fboundp 'move-end-of-line)
18560 'move-end-of-line
18561 'end-of-line)))))
18562 (org-no-warnings
18563 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18565 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18566 (define-key org-mode-map "\C-e" 'org-end-of-line)
18567 (define-key org-mode-map [home] 'org-beginning-of-line)
18568 (define-key org-mode-map [end] 'org-end-of-line)
18570 (defun org-backward-sentence (&optional arg)
18571 "Go to beginning of sentence, or beginning of table field.
18572 This will call `backward-sentence' or `org-table-beginning-of-field',
18573 depending on context."
18574 (interactive "P")
18575 (cond
18576 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18577 (t (call-interactively 'backward-sentence))))
18579 (defun org-forward-sentence (&optional arg)
18580 "Go to end of sentence, or end of table field.
18581 This will call `forward-sentence' or `org-table-end-of-field',
18582 depending on context."
18583 (interactive "P")
18584 (cond
18585 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18586 (t (call-interactively 'forward-sentence))))
18588 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18589 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18591 (defun org-kill-line (&optional arg)
18592 "Kill line, to tags or end of line."
18593 (interactive "P")
18594 (cond
18595 ((or (not org-special-ctrl-k)
18596 (bolp)
18597 (not (org-on-heading-p)))
18598 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
18599 org-ctrl-k-protect-subtree)
18600 (if (or (eq org-ctrl-k-protect-subtree 'error)
18601 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
18602 (error "C-k aborted - would kill hidden subtree")))
18603 (call-interactively 'kill-line))
18604 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18605 (kill-region (point) (match-beginning 1))
18606 (org-set-tags nil t))
18607 (t (kill-region (point) (point-at-eol)))))
18609 (define-key org-mode-map "\C-k" 'org-kill-line)
18611 (defun org-yank (&optional arg)
18612 "Yank. If the kill is a subtree, treat it specially.
18613 This command will look at the current kill and check if is a single
18614 subtree, or a series of subtrees[1]. If it passes the test, and if the
18615 cursor is at the beginning of a line or after the stars of a currently
18616 empty headline, then the yank is handled specially. How exactly depends
18617 on the value of the following variables, both set by default.
18619 org-yank-folded-subtrees
18620 When set, the subtree(s) will be folded after insertion, but only
18621 if doing so would now swallow text after the yanked text.
18623 org-yank-adjusted-subtrees
18624 When set, the subtree will be promoted or demoted in order to
18625 fit into the local outline tree structure, which means that the level
18626 will be adjusted so that it becomes the smaller one of the two
18627 *visible* surrounding headings.
18629 Any prefix to this command will cause `yank' to be called directly with
18630 no special treatment. In particular, a simple `C-u' prefix will just
18631 plainly yank the text as it is.
18633 \[1] The test checks if the first non-white line is a heading
18634 and if there are no other headings with fewer stars."
18635 (interactive "P")
18636 (org-yank-generic 'yank arg))
18638 (defun org-yank-generic (command arg)
18639 "Perform some yank-like command.
18641 This function implements the behavior described in the `org-yank'
18642 documentation. However, it has been generalized to work for any
18643 interactive command with similar behavior."
18645 ;; pretend to be command COMMAND
18646 (setq this-command command)
18648 (if arg
18649 (call-interactively command)
18651 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18652 (and (org-kill-is-subtree-p)
18653 (or (bolp)
18654 (and (looking-at "[ \t]*$")
18655 (string-match
18656 "\\`\\*+\\'"
18657 (buffer-substring (point-at-bol) (point)))))))
18658 swallowp)
18659 (cond
18660 ((and subtreep org-yank-folded-subtrees)
18661 (let ((beg (point))
18662 end)
18663 (if (and subtreep org-yank-adjusted-subtrees)
18664 (org-paste-subtree nil nil 'for-yank)
18665 (call-interactively command))
18667 (setq end (point))
18668 (goto-char beg)
18669 (when (and (bolp) subtreep
18670 (not (setq swallowp
18671 (org-yank-folding-would-swallow-text beg end))))
18672 (or (looking-at outline-regexp)
18673 (re-search-forward (concat "^" outline-regexp) end t))
18674 (while (and (< (point) end) (looking-at outline-regexp))
18675 (hide-subtree)
18676 (org-cycle-show-empty-lines 'folded)
18677 (condition-case nil
18678 (outline-forward-same-level 1)
18679 (error (goto-char end)))))
18680 (when swallowp
18681 (message
18682 "Inserted text not folded because that would swallow text"))
18684 (goto-char end)
18685 (skip-chars-forward " \t\n\r")
18686 (beginning-of-line 1)
18687 (push-mark beg 'nomsg)))
18688 ((and subtreep org-yank-adjusted-subtrees)
18689 (let ((beg (point-at-bol)))
18690 (org-paste-subtree nil nil 'for-yank)
18691 (push-mark beg 'nomsg)))
18693 (call-interactively command))))))
18695 (defun org-yank-folding-would-swallow-text (beg end)
18696 "Would hide-subtree at BEG swallow any text after END?"
18697 (let (level)
18698 (save-excursion
18699 (goto-char beg)
18700 (when (or (looking-at outline-regexp)
18701 (re-search-forward (concat "^" outline-regexp) end t))
18702 (setq level (org-outline-level)))
18703 (goto-char end)
18704 (skip-chars-forward " \t\r\n\v\f")
18705 (if (or (eobp)
18706 (and (bolp) (looking-at org-outline-regexp)
18707 (<= (org-outline-level) level)))
18708 nil ; Nothing would be swallowed
18709 t)))) ; something would swallow
18711 (define-key org-mode-map "\C-y" 'org-yank)
18713 (defun org-invisible-p ()
18714 "Check if point is at a character currently not visible."
18715 ;; Early versions of noutline don't have `outline-invisible-p'.
18716 (if (fboundp 'outline-invisible-p)
18717 (outline-invisible-p)
18718 (get-char-property (point) 'invisible)))
18720 (defun org-invisible-p2 ()
18721 "Check if point is at a character currently not visible."
18722 (save-excursion
18723 (if (and (eolp) (not (bobp))) (backward-char 1))
18724 ;; Early versions of noutline don't have `outline-invisible-p'.
18725 (if (fboundp 'outline-invisible-p)
18726 (outline-invisible-p)
18727 (get-char-property (point) 'invisible))))
18729 (defun org-back-to-heading (&optional invisible-ok)
18730 "Call `outline-back-to-heading', but provide a better error message."
18731 (condition-case nil
18732 (outline-back-to-heading invisible-ok)
18733 (error (error "Before first headline at position %d in buffer %s"
18734 (point) (current-buffer)))))
18736 (defun org-beginning-of-defun ()
18737 "Go to the beginning of the subtree, i.e. back to the heading."
18738 (org-back-to-heading))
18739 (defun org-end-of-defun ()
18740 "Go to the end of the subtree."
18741 (org-end-of-subtree nil t))
18743 (defun org-before-first-heading-p ()
18744 "Before first heading?"
18745 (save-excursion
18746 (null (re-search-backward "^\\*+ " nil t))))
18748 (defun org-on-heading-p (&optional ignored)
18749 (outline-on-heading-p t))
18750 (defun org-at-heading-p (&optional ignored)
18751 (outline-on-heading-p t))
18753 (defun org-point-at-end-of-empty-headline ()
18754 "If point is at the end of an empty headline, return t, else nil.
18755 If the heading only contains a TODO keyword, it is still still considered
18756 empty."
18757 (and (looking-at "[ \t]*$")
18758 (save-excursion
18759 (beginning-of-line 1)
18760 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18761 "\\)?[ \t]*$")))))
18762 (defun org-at-heading-or-item-p ()
18763 (or (org-on-heading-p) (org-at-item-p)))
18765 (defun org-on-target-p ()
18766 (or (org-in-regexp org-radio-target-regexp)
18767 (org-in-regexp org-target-regexp)))
18769 (defun org-up-heading-all (arg)
18770 "Move to the heading line of which the present line is a subheading.
18771 This function considers both visible and invisible heading lines.
18772 With argument, move up ARG levels."
18773 (if (fboundp 'outline-up-heading-all)
18774 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18775 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18777 (defun org-up-heading-safe ()
18778 "Move to the heading line of which the present line is a subheading.
18779 This version will not throw an error. It will return the level of the
18780 headline found, or nil if no higher level is found.
18782 Also, this function will be a lot faster than `outline-up-heading',
18783 because it relies on stars being the outline starters. This can really
18784 make a significant difference in outlines with very many siblings."
18785 (let (start-level re)
18786 (org-back-to-heading t)
18787 (setq start-level (funcall outline-level))
18788 (if (equal start-level 1)
18790 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18791 (if (re-search-backward re nil t)
18792 (funcall outline-level)))))
18794 (defun org-first-sibling-p ()
18795 "Is this heading the first child of its parents?"
18796 (interactive)
18797 (let ((re (concat "^" outline-regexp))
18798 level l)
18799 (unless (org-at-heading-p t)
18800 (error "Not at a heading"))
18801 (setq level (funcall outline-level))
18802 (save-excursion
18803 (if (not (re-search-backward re nil t))
18805 (setq l (funcall outline-level))
18806 (< l level)))))
18808 (defun org-goto-sibling (&optional previous)
18809 "Goto the next sibling, even if it is invisible.
18810 When PREVIOUS is set, go to the previous sibling instead. Returns t
18811 when a sibling was found. When none is found, return nil and don't
18812 move point."
18813 (let ((fun (if previous 're-search-backward 're-search-forward))
18814 (pos (point))
18815 (re (concat "^" outline-regexp))
18816 level l)
18817 (when (condition-case nil (org-back-to-heading t) (error nil))
18818 (setq level (funcall outline-level))
18819 (catch 'exit
18820 (or previous (forward-char 1))
18821 (while (funcall fun re nil t)
18822 (setq l (funcall outline-level))
18823 (when (< l level) (goto-char pos) (throw 'exit nil))
18824 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18825 (goto-char pos)
18826 nil))))
18828 (defun org-show-siblings ()
18829 "Show all siblings of the current headline."
18830 (save-excursion
18831 (while (org-goto-sibling) (org-flag-heading nil)))
18832 (save-excursion
18833 (while (org-goto-sibling 'previous)
18834 (org-flag-heading nil))))
18836 (defun org-show-hidden-entry ()
18837 "Show an entry where even the heading is hidden."
18838 (save-excursion
18839 (org-show-entry)))
18841 (defun org-flag-heading (flag &optional entry)
18842 "Flag the current heading. FLAG non-nil means make invisible.
18843 When ENTRY is non-nil, show the entire entry."
18844 (save-excursion
18845 (org-back-to-heading t)
18846 ;; Check if we should show the entire entry
18847 (if entry
18848 (progn
18849 (org-show-entry)
18850 (save-excursion
18851 (and (outline-next-heading)
18852 (org-flag-heading nil))))
18853 (outline-flag-region (max (point-min) (1- (point)))
18854 (save-excursion (outline-end-of-heading) (point))
18855 flag))))
18857 (defun org-get-next-sibling ()
18858 "Move to next heading of the same level, and return point.
18859 If there is no such heading, return nil.
18860 This is like outline-next-sibling, but invisible headings are ok."
18861 (let ((level (funcall outline-level)))
18862 (outline-next-heading)
18863 (while (and (not (eobp)) (> (funcall outline-level) level))
18864 (outline-next-heading))
18865 (if (or (eobp) (< (funcall outline-level) level))
18867 (point))))
18869 (defun org-get-last-sibling ()
18870 "Move to previous heading of the same level, and return point.
18871 If there is no such heading, return nil."
18872 (let ((opoint (point))
18873 (level (funcall outline-level)))
18874 (outline-previous-heading)
18875 (when (and (/= (point) opoint) (outline-on-heading-p t))
18876 (while (and (> (funcall outline-level) level)
18877 (not (bobp)))
18878 (outline-previous-heading))
18879 (if (< (funcall outline-level) level)
18881 (point)))))
18883 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18884 ;; This contains an exact copy of the original function, but it uses
18885 ;; `org-back-to-heading', to make it work also in invisible
18886 ;; trees. And is uses an invisible-OK argument.
18887 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18888 ;; Furthermore, when used inside Org, finding the end of a large subtree
18889 ;; with many children and grandchildren etc, this can be much faster
18890 ;; than the outline version.
18891 (org-back-to-heading invisible-OK)
18892 (let ((first t)
18893 (level (funcall outline-level)))
18894 (if (and (org-mode-p) (< level 1000))
18895 ;; A true heading (not a plain list item), in Org-mode
18896 ;; This means we can easily find the end by looking
18897 ;; only for the right number of stars. Using a regexp to do
18898 ;; this is so much faster than using a Lisp loop.
18899 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18900 (forward-char 1)
18901 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18902 ;; something else, do it the slow way
18903 (while (and (not (eobp))
18904 (or first (> (funcall outline-level) level)))
18905 (setq first nil)
18906 (outline-next-heading)))
18907 (unless to-heading
18908 (if (memq (preceding-char) '(?\n ?\^M))
18909 (progn
18910 ;; Go to end of line before heading
18911 (forward-char -1)
18912 (if (memq (preceding-char) '(?\n ?\^M))
18913 ;; leave blank line before heading
18914 (forward-char -1))))))
18915 (point))
18917 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18918 "Use Org version in org-mode, for dramatic speed-up."
18919 (if (eq major-mode 'org-mode)
18920 (progn
18921 (org-end-of-subtree nil t)
18922 (unless (eobp) (backward-char 1)))
18923 ad-do-it))
18925 (defun org-forward-same-level (arg &optional invisible-ok)
18926 "Move forward to the arg'th subheading at same level as this one.
18927 Stop at the first and last subheadings of a superior heading."
18928 (interactive "p")
18929 (org-back-to-heading invisible-ok)
18930 (org-on-heading-p)
18931 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18932 (re (format "^\\*\\{1,%d\\} " level))
18934 (forward-char 1)
18935 (while (> arg 0)
18936 (while (and (re-search-forward re nil 'move)
18937 (setq l (- (match-end 0) (match-beginning 0) 1))
18938 (= l level)
18939 (not invisible-ok)
18940 (progn (backward-char 1) (org-invisible-p)))
18941 (if (< l level) (setq arg 1)))
18942 (setq arg (1- arg)))
18943 (beginning-of-line 1)))
18945 (defun org-backward-same-level (arg &optional invisible-ok)
18946 "Move backward to the arg'th subheading at same level as this one.
18947 Stop at the first and last subheadings of a superior heading."
18948 (interactive "p")
18949 (org-back-to-heading)
18950 (org-on-heading-p)
18951 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18952 (re (format "^\\*\\{1,%d\\} " level))
18954 (while (> arg 0)
18955 (while (and (re-search-backward re nil 'move)
18956 (setq l (- (match-end 0) (match-beginning 0) 1))
18957 (= l level)
18958 (not invisible-ok)
18959 (org-invisible-p))
18960 (if (< l level) (setq arg 1)))
18961 (setq arg (1- arg)))))
18963 (defun org-show-subtree ()
18964 "Show everything after this heading at deeper levels."
18965 (outline-flag-region
18966 (point)
18967 (save-excursion
18968 (org-end-of-subtree t t))
18969 nil))
18971 (defun org-show-entry ()
18972 "Show the body directly following this heading.
18973 Show the heading too, if it is currently invisible."
18974 (interactive)
18975 (save-excursion
18976 (condition-case nil
18977 (progn
18978 (org-back-to-heading t)
18979 (outline-flag-region
18980 (max (point-min) (1- (point)))
18981 (save-excursion
18982 (if (re-search-forward
18983 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18984 (match-beginning 1)
18985 (point-max)))
18986 nil)
18987 (org-cycle-hide-drawers 'children))
18988 (error nil))))
18990 (defun org-make-options-regexp (kwds &optional extra)
18991 "Make a regular expression for keyword lines."
18992 (concat
18994 "#?[ \t]*\\+\\("
18995 (mapconcat 'regexp-quote kwds "\\|")
18996 (if extra (concat "\\|" extra))
18997 "\\):[ \t]*"
18998 "\\(.*\\)"))
19000 ;; Make isearch reveal the necessary context
19001 (defun org-isearch-end ()
19002 "Reveal context after isearch exits."
19003 (when isearch-success ; only if search was successful
19004 (if (featurep 'xemacs)
19005 ;; Under XEmacs, the hook is run in the correct place,
19006 ;; we directly show the context.
19007 (org-show-context 'isearch)
19008 ;; In Emacs the hook runs *before* restoring the overlays.
19009 ;; So we have to use a one-time post-command-hook to do this.
19010 ;; (Emacs 22 has a special variable, see function `org-mode')
19011 (unless (and (boundp 'isearch-mode-end-hook-quit)
19012 isearch-mode-end-hook-quit)
19013 ;; Only when the isearch was not quitted.
19014 (org-add-hook 'post-command-hook 'org-isearch-post-command
19015 'append 'local)))))
19017 (defun org-isearch-post-command ()
19018 "Remove self from hook, and show context."
19019 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19020 (org-show-context 'isearch))
19023 ;;;; Integration with and fixes for other packages
19025 ;;; Imenu support
19027 (defvar org-imenu-markers nil
19028 "All markers currently used by Imenu.")
19029 (make-variable-buffer-local 'org-imenu-markers)
19031 (defun org-imenu-new-marker (&optional pos)
19032 "Return a new marker for use by Imenu, and remember the marker."
19033 (let ((m (make-marker)))
19034 (move-marker m (or pos (point)))
19035 (push m org-imenu-markers)
19038 (defun org-imenu-get-tree ()
19039 "Produce the index for Imenu."
19040 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19041 (setq org-imenu-markers nil)
19042 (let* ((n org-imenu-depth)
19043 (re (concat "^" outline-regexp))
19044 (subs (make-vector (1+ n) nil))
19045 (last-level 0)
19046 m level head)
19047 (save-excursion
19048 (save-restriction
19049 (widen)
19050 (goto-char (point-max))
19051 (while (re-search-backward re nil t)
19052 (setq level (org-reduced-level (funcall outline-level)))
19053 (when (<= level n)
19054 (looking-at org-complex-heading-regexp)
19055 (setq head (org-link-display-format
19056 (org-match-string-no-properties 4))
19057 m (org-imenu-new-marker))
19058 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19059 (if (>= level last-level)
19060 (push (cons head m) (aref subs level))
19061 (push (cons head (aref subs (1+ level))) (aref subs level))
19062 (loop for i from (1+ level) to n do (aset subs i nil)))
19063 (setq last-level level)))))
19064 (aref subs 1)))
19066 (eval-after-load "imenu"
19067 '(progn
19068 (add-hook 'imenu-after-jump-hook
19069 (lambda ()
19070 (if (eq major-mode 'org-mode)
19071 (org-show-context 'org-goto))))))
19073 (defun org-link-display-format (link)
19074 "Replace a link with either the description, or the link target
19075 if no description is present"
19076 (save-match-data
19077 (if (string-match org-bracket-link-analytic-regexp link)
19078 (replace-match (if (match-end 5)
19079 (match-string 5 link)
19080 (concat (match-string 1 link)
19081 (match-string 3 link)))
19082 nil t link)
19083 link)))
19085 ;; Speedbar support
19087 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19088 "Overlay marking the agenda restriction line in speedbar.")
19089 (overlay-put org-speedbar-restriction-lock-overlay
19090 'face 'org-agenda-restriction-lock)
19091 (overlay-put org-speedbar-restriction-lock-overlay
19092 'help-echo "Agendas are currently limited to this item.")
19093 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19095 (defun org-speedbar-set-agenda-restriction ()
19096 "Restrict future agenda commands to the location at point in speedbar.
19097 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19098 (interactive)
19099 (require 'org-agenda)
19100 (let (p m tp np dir txt)
19101 (cond
19102 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19103 'org-imenu t))
19104 (setq m (get-text-property p 'org-imenu-marker))
19105 (with-current-buffer (marker-buffer m)
19106 (goto-char m)
19107 (org-agenda-set-restriction-lock 'subtree)))
19108 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19109 'speedbar-function 'speedbar-find-file))
19110 (setq tp (previous-single-property-change
19111 (1+ p) 'speedbar-function)
19112 np (next-single-property-change
19113 tp 'speedbar-function)
19114 dir (speedbar-line-directory)
19115 txt (buffer-substring-no-properties (or tp (point-min))
19116 (or np (point-max))))
19117 (with-current-buffer (find-file-noselect
19118 (let ((default-directory dir))
19119 (expand-file-name txt)))
19120 (unless (org-mode-p)
19121 (error "Cannot restrict to non-Org-mode file"))
19122 (org-agenda-set-restriction-lock 'file)))
19123 (t (error "Don't know how to restrict Org-mode's agenda")))
19124 (move-overlay org-speedbar-restriction-lock-overlay
19125 (point-at-bol) (point-at-eol))
19126 (setq current-prefix-arg nil)
19127 (org-agenda-maybe-redo)))
19129 (eval-after-load "speedbar"
19130 '(progn
19131 (speedbar-add-supported-extension ".org")
19132 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19133 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19134 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19135 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19136 (add-hook 'speedbar-visiting-tag-hook
19137 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19139 ;;; Fixes and Hacks for problems with other packages
19141 ;; Make flyspell not check words in links, to not mess up our keymap
19142 (defun org-mode-flyspell-verify ()
19143 "Don't let flyspell put overlays at active buttons."
19144 (and (not (get-text-property (point) 'keymap))
19145 (not (get-text-property (point) 'org-no-flyspell))))
19147 (defun org-remove-flyspell-overlays-in (beg end)
19148 "Remove flyspell overlays in region."
19149 (and (org-bound-and-true-p flyspell-mode)
19150 (fboundp 'flyspell-delete-region-overlays)
19151 (flyspell-delete-region-overlays beg end))
19152 (add-text-properties beg end '(org-no-flyspell t)))
19154 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19155 (eval-after-load "bookmark"
19156 '(if (boundp 'bookmark-after-jump-hook)
19157 ;; We can use the hook
19158 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19159 ;; Hook not available, use advice
19160 (defadvice bookmark-jump (after org-make-visible activate)
19161 "Make the position visible."
19162 (org-bookmark-jump-unhide))))
19164 ;; Make sure saveplace shows the location if it was hidden
19165 (eval-after-load "saveplace"
19166 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19167 "Make the position visible."
19168 (org-bookmark-jump-unhide)))
19170 ;; Make sure ecb shows the location if it was hidden
19171 (eval-after-load "ecb"
19172 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19173 "Make hierarchy visible when jumping into location from ECB tree buffer."
19174 (if (eq major-mode 'org-mode)
19175 (org-show-context))))
19177 (defun org-bookmark-jump-unhide ()
19178 "Unhide the current position, to show the bookmark location."
19179 (and (org-mode-p)
19180 (or (org-invisible-p)
19181 (save-excursion (goto-char (max (point-min) (1- (point))))
19182 (org-invisible-p)))
19183 (org-show-context 'bookmark-jump)))
19185 ;; Make session.el ignore our circular variable
19186 (eval-after-load "session"
19187 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19189 ;;;; Experimental code
19191 (defun org-closed-in-range ()
19192 "Sparse tree of items closed in a certain time range.
19193 Still experimental, may disappear in the future."
19194 (interactive)
19195 ;; Get the time interval from the user.
19196 (let* ((time1 (org-float-time
19197 (org-read-date nil 'to-time nil "Starting date: ")))
19198 (time2 (org-float-time
19199 (org-read-date nil 'to-time nil "End date:")))
19200 ;; callback function
19201 (callback (lambda ()
19202 (let ((time
19203 (org-float-time
19204 (apply 'encode-time
19205 (org-parse-time-string
19206 (match-string 1))))))
19207 ;; check if time in interval
19208 (and (>= time time1) (<= time time2))))))
19209 ;; make tree, check each match with the callback
19210 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19212 ;;;; Finish up
19214 (provide 'org)
19216 (run-hooks 'org-load-hook)
19218 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19220 ;;; org.el ends here