Introduce a help function for entities
[org-mode.git] / lisp / org.el
bloba81ee593ee05800cf29add7961df71f2916ce802
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))
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 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)[^[:alnum:]]"
5385 limit t)
5386 (if (and (setq ee (org-entity-get (match-string 1)))
5387 (= (length (nth 6 ee)) 1))
5388 (progn
5389 (add-text-properties
5390 (match-beginning 0) (match-end 1)
5391 (list 'font-lock-fontified t))
5392 (compose-region (match-beginning 0) (match-end 1)
5393 (nth 6 ee) nil)
5394 (backward-char 1)
5395 (throw 'match t))))
5396 nil))))
5398 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5399 "Fontify string S like in Org-mode"
5400 (with-temp-buffer
5401 (insert s)
5402 (let ((org-odd-levels-only odd-levels))
5403 (org-mode)
5404 (font-lock-fontify-buffer)
5405 (buffer-string))))
5407 (defvar org-m nil)
5408 (defvar org-l nil)
5409 (defvar org-f nil)
5410 (defun org-get-level-face (n)
5411 "Get the right face for match N in font-lock matching of headlines."
5412 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5413 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5414 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5415 (cond
5416 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5417 ((eq n 2) org-f)
5418 (t (if org-level-color-stars-only nil org-f))))
5420 (defun org-get-todo-face (kwd)
5421 "Get the right face for a TODO keyword KWD.
5422 If KWD is a number, get the corresponding match group."
5423 (if (numberp kwd) (setq kwd (match-string kwd)))
5424 (or (org-face-from-face-or-color
5425 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5426 (and (member kwd org-done-keywords) 'org-done)
5427 'org-todo))
5429 (defun org-face-from-face-or-color (context inherit face-or-color)
5430 "Create a face list that inherits INHERIT, but sets the foreground color.
5431 When FACE-OR-COLOR is not a string, just return it."
5432 (if (stringp face-or-color)
5433 (list :inherit inherit
5434 (cdr (assoc context org-faces-easy-properties))
5435 face-or-color)
5436 face-or-color))
5438 (defun org-font-lock-add-tag-faces (limit)
5439 "Add the special tag faces."
5440 (when (and org-tag-faces org-tags-special-faces-re)
5441 (while (re-search-forward org-tags-special-faces-re limit t)
5442 (add-text-properties (match-beginning 1) (match-end 1)
5443 (list 'face (org-get-tag-face 1)
5444 'font-lock-fontified t))
5445 (backward-char 1))))
5447 (defun org-font-lock-add-priority-faces (limit)
5448 "Add the special priority faces."
5449 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5450 (add-text-properties
5451 (match-beginning 0) (match-end 0)
5452 (list 'face (or (org-face-from-face-or-color
5453 'priority 'org-special-keyword
5454 (cdr (assoc (char-after (match-beginning 1))
5455 org-priority-faces)))
5456 'org-special-keyword)
5457 'font-lock-fontified t))))
5459 (defun org-get-tag-face (kwd)
5460 "Get the right face for a TODO keyword KWD.
5461 If KWD is a number, get the corresponding match group."
5462 (if (numberp kwd) (setq kwd (match-string kwd)))
5463 (or (org-face-from-face-or-color
5464 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5465 'org-tag))
5467 (defun org-unfontify-region (beg end &optional maybe_loudly)
5468 "Remove fontification and activation overlays from links."
5469 (font-lock-default-unfontify-region beg end)
5470 (let* ((buffer-undo-list t)
5471 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5472 (inhibit-modification-hooks t)
5473 deactivate-mark buffer-file-name buffer-file-truename)
5474 (remove-text-properties
5475 beg end
5476 (if org-indent-mode
5477 ;; also remove line-prefix and wrap-prefix properties
5478 '(mouse-face t keymap t org-linked-text t
5479 invisible t intangible t
5480 line-prefix t wrap-prefix t
5481 org-no-flyspell t)
5482 '(mouse-face t keymap t org-linked-text t
5483 invisible t intangible t
5484 org-no-flyspell t)))
5485 (org-remove-font-lock-display-properties beg end)))
5487 (defconst org-script-display '(((raise -0.3) (height 0.7))
5488 ((raise 0.3) (height 0.7))
5489 ((raise -0.5))
5490 ((raise 0.5)))
5491 "Display properties for showing superscripts and subscripts.")
5493 (defun org-remove-font-lock-display-properties (beg end)
5494 "Remove specific display properties that have been added by font lock.
5495 The will remove the raise properties that are used to show superscripts
5496 and subscriipts."
5497 (let (next prop)
5498 (while (< beg end)
5499 (setq next (next-single-property-change beg 'display nil end)
5500 prop (get-text-property beg 'display))
5501 (if (member prop org-script-display)
5502 (put-text-property beg next 'display nil))
5503 (setq beg next))))
5505 (defun org-raise-scripts (limit)
5506 "Add raise properties to sub/superscripts."
5507 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5508 (if (re-search-forward
5509 (if (eq org-use-sub-superscripts t)
5510 org-match-substring-regexp
5511 org-match-substring-with-braces-regexp)
5512 limit t)
5513 (let* ((pos (point))
5514 (table-p (progn (goto-char (point-at-bol))
5515 (prog1 (org-looking-at-p
5516 org-table-dataline-regexp)
5517 (goto-char pos)))))
5518 (put-text-property (match-beginning 3) (match-end 0)
5519 'display
5520 (if (equal (char-after (match-beginning 2)) ?^)
5521 (nth (if table-p 3 1) org-script-display)
5522 (nth (if table-p 2 0) org-script-display)))
5523 (add-text-properties (match-beginning 2) (match-end 2)
5524 (list 'invisible t
5525 'org-dwidth t 'org-dwidth-n 1))
5526 (if (and (eq (char-after (match-beginning 3)) ?{)
5527 (eq (char-before (match-end 3)) ?}))
5528 (progn
5529 (add-text-properties
5530 (match-beginning 3) (1+ (match-beginning 3))
5531 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5532 (add-text-properties
5533 (1- (match-end 3)) (match-end 3)
5534 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5535 t))))
5537 ;;;; Visibility cycling, including org-goto and indirect buffer
5539 ;;; Cycling
5541 (defvar org-cycle-global-status nil)
5542 (make-variable-buffer-local 'org-cycle-global-status)
5543 (defvar org-cycle-subtree-status nil)
5544 (make-variable-buffer-local 'org-cycle-subtree-status)
5546 ;;;###autoload
5548 (defvar org-inlinetask-min-level)
5550 (defun org-cycle (&optional arg)
5551 "TAB-action and visibility cycling for Org-mode.
5553 This is the command invoked in Org-mode by the TAB key. Its main purpose
5554 is outline visibility cycling, but it also invokes other actions
5555 in special contexts.
5557 - When this function is called with a prefix argument, rotate the entire
5558 buffer through 3 states (global cycling)
5559 1. OVERVIEW: Show only top-level headlines.
5560 2. CONTENTS: Show all headlines of all levels, but no body text.
5561 3. SHOW ALL: Show everything.
5562 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5563 determined by the variable `org-startup-folded', and by any VISIBILITY
5564 properties in the buffer.
5565 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5566 including any drawers.
5568 - When inside a table, re-align the table and move to the next field.
5570 - When point is at the beginning of a headline, rotate the subtree started
5571 by this line through 3 different states (local cycling)
5572 1. FOLDED: Only the main headline is shown.
5573 2. CHILDREN: The main headline and the direct children are shown.
5574 From this state, you can move to one of the children
5575 and zoom in further.
5576 3. SUBTREE: Show the entire subtree, including body text.
5577 If there is no subtree, switch directly from CHILDREN to FOLDED.
5579 - When point is at the beginning of an empty headline and the variable
5580 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5581 of the headline by demoting and promoting it to likely levels. This
5582 speeds up creation document structure by presing TAB once or several
5583 times right after creating a new headline.
5585 - When there is a numeric prefix, go up to a heading with level ARG, do
5586 a `show-subtree' and return to the previous cursor position. If ARG
5587 is negative, go up that many levels.
5589 - When point is not at the beginning of a headline, execute the global
5590 binding for TAB, which is re-indenting the line. See the option
5591 `org-cycle-emulate-tab' for details.
5593 - Special case: if point is at the beginning of the buffer and there is
5594 no headline in line 1, this function will act as if called with prefix arg.
5595 But only if also the variable `org-cycle-global-at-bob' is t."
5596 (interactive "P")
5597 (org-load-modules-maybe)
5598 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5599 (and org-cycle-level-after-item/entry-creation
5600 (or (org-cycle-level)
5601 (org-cycle-item-indentation))))
5602 (let* ((limit-level
5603 (or org-cycle-max-level
5604 (and (boundp 'org-inlinetask-min-level)
5605 org-inlinetask-min-level
5606 (1- org-inlinetask-min-level))))
5607 (nstars (and limit-level
5608 (if org-odd-levels-only
5609 (and limit-level (1- (* limit-level 2)))
5610 limit-level)))
5611 (outline-regexp
5612 (cond
5613 ((not (org-mode-p)) outline-regexp)
5614 ((or (eq org-cycle-include-plain-lists 'integrate)
5615 (and org-cycle-include-plain-lists (org-at-item-p)))
5616 (concat "\\(?:\\*"
5617 (if nstars (format "\\{1,%d\\}" nstars) "+")
5618 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5619 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5620 (bob-special (and org-cycle-global-at-bob (bobp)
5621 (not (looking-at outline-regexp))))
5622 (org-cycle-hook
5623 (if bob-special
5624 (delq 'org-optimize-window-after-visibility-change
5625 (copy-sequence org-cycle-hook))
5626 org-cycle-hook))
5627 (pos (point)))
5629 (if (or bob-special (equal arg '(4)))
5630 ;; special case: use global cycling
5631 (setq arg t))
5633 (cond
5635 ((equal arg '(16))
5636 (org-set-startup-visibility)
5637 (message "Startup visibility, plus VISIBILITY properties"))
5639 ((equal arg '(64))
5640 (show-all)
5641 (message "Entire buffer visible, including drawers"))
5643 ((org-at-table-p 'any)
5644 ;; Enter the table or move to the next field in the table
5645 (if (org-at-table.el-p)
5646 (message "Use C-c ' to edit table.el tables")
5647 (if arg (org-table-edit-field t)
5648 (org-table-justify-field-maybe)
5649 (call-interactively 'org-table-next-field))))
5651 ((run-hook-with-args-until-success
5652 'org-tab-after-check-for-table-hook))
5654 ((eq arg t) ;; Global cycling
5655 (org-cycle-internal-global))
5657 ((and org-drawers org-drawer-regexp
5658 (save-excursion
5659 (beginning-of-line 1)
5660 (looking-at org-drawer-regexp)))
5661 ;; Toggle block visibility
5662 (org-flag-drawer
5663 (not (get-char-property (match-end 0) 'invisible))))
5665 ((integerp arg)
5666 ;; Show-subtree, ARG levels up from here.
5667 (save-excursion
5668 (org-back-to-heading)
5669 (outline-up-heading (if (< arg 0) (- arg)
5670 (- (funcall outline-level) arg)))
5671 (org-show-subtree)))
5673 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5674 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5676 (org-cycle-internal-local))
5678 ;; TAB emulation and template completion
5679 (buffer-read-only (org-back-to-heading))
5681 ((run-hook-with-args-until-success
5682 'org-tab-after-check-for-cycling-hook))
5684 ((org-try-structure-completion))
5686 ((org-try-cdlatex-tab))
5688 ((run-hook-with-args-until-success
5689 'org-tab-before-tab-emulation-hook))
5691 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5692 (or (not (bolp))
5693 (not (looking-at outline-regexp))))
5694 (call-interactively (global-key-binding "\t")))
5696 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5697 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5698 (or (and (eq org-cycle-emulate-tab 'white)
5699 (= (match-end 0) (point-at-eol)))
5700 (and (eq org-cycle-emulate-tab 'whitestart)
5701 (>= (match-end 0) pos))))
5703 (eq org-cycle-emulate-tab t))
5704 (call-interactively (global-key-binding "\t")))
5706 (t (save-excursion
5707 (org-back-to-heading)
5708 (org-cycle)))))))
5710 (defun org-cycle-internal-global ()
5711 "Do the global cycling action."
5712 (cond
5713 ((and (eq last-command this-command)
5714 (eq org-cycle-global-status 'overview))
5715 ;; We just created the overview - now do table of contents
5716 ;; This can be slow in very large buffers, so indicate action
5717 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5718 (message "CONTENTS...")
5719 (org-content)
5720 (message "CONTENTS...done")
5721 (setq org-cycle-global-status 'contents)
5722 (run-hook-with-args 'org-cycle-hook 'contents))
5724 ((and (eq last-command this-command)
5725 (eq org-cycle-global-status 'contents))
5726 ;; We just showed the table of contents - now show everything
5727 (run-hook-with-args 'org-pre-cycle-hook 'all)
5728 (show-all)
5729 (message "SHOW ALL")
5730 (setq org-cycle-global-status 'all)
5731 (run-hook-with-args 'org-cycle-hook 'all))
5734 ;; Default action: go to overview
5735 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5736 (org-overview)
5737 (message "OVERVIEW")
5738 (setq org-cycle-global-status 'overview)
5739 (run-hook-with-args 'org-cycle-hook 'overview))))
5741 (defun org-cycle-internal-local ()
5742 "Do the local cycling action."
5743 (org-back-to-heading)
5744 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5745 ;; First, some boundaries
5746 (save-excursion
5747 (org-back-to-heading)
5748 (setq level (funcall outline-level))
5749 (save-excursion
5750 (beginning-of-line 2)
5751 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5752 ; XEmacs does not have `next-single-char-property-change'
5753 ; I'm not sure about Emacs 21.
5754 (while (and (not (eobp)) ;; this is like `next-line'
5755 (get-char-property (1- (point)) 'invisible))
5756 (beginning-of-line 2))
5757 (while (and (not (eobp)) ;; this is like `next-line'
5758 (get-char-property (1- (point)) 'invisible))
5759 (goto-char (next-single-char-property-change (point) 'invisible))
5760 (and (eolp) (beginning-of-line 2))))
5761 (setq eol (point)))
5762 (outline-end-of-heading) (setq eoh (point))
5763 (save-excursion
5764 (outline-next-heading)
5765 (setq has-children (and (org-at-heading-p t)
5766 (> (funcall outline-level) level))))
5767 (org-end-of-subtree t)
5768 (unless (eobp)
5769 (skip-chars-forward " \t\n")
5770 (beginning-of-line 1) ; in case this is an item
5772 (setq eos (if (eobp) (point) (1- (point)))))
5773 ;; Find out what to do next and set `this-command'
5774 (cond
5775 ((= eos eoh)
5776 ;; Nothing is hidden behind this heading
5777 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5778 (message "EMPTY ENTRY")
5779 (setq org-cycle-subtree-status nil)
5780 (save-excursion
5781 (goto-char eos)
5782 (outline-next-heading)
5783 (if (org-invisible-p) (org-flag-heading nil))))
5784 ((and (or (>= eol eos)
5785 (not (string-match "\\S-" (buffer-substring eol eos))))
5786 (or has-children
5787 (not (setq children-skipped
5788 org-cycle-skip-children-state-if-no-children))))
5789 ;; Entire subtree is hidden in one line: children view
5790 (run-hook-with-args 'org-pre-cycle-hook 'children)
5791 (org-show-entry)
5792 (show-children)
5793 (message "CHILDREN")
5794 (save-excursion
5795 (goto-char eos)
5796 (outline-next-heading)
5797 (if (org-invisible-p) (org-flag-heading nil)))
5798 (setq org-cycle-subtree-status 'children)
5799 (run-hook-with-args 'org-cycle-hook 'children))
5800 ((or children-skipped
5801 (and (eq last-command this-command)
5802 (eq org-cycle-subtree-status 'children)))
5803 ;; We just showed the children, or no children are there,
5804 ;; now show everything.
5805 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5806 (org-show-subtree)
5807 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5808 (setq org-cycle-subtree-status 'subtree)
5809 (run-hook-with-args 'org-cycle-hook 'subtree))
5811 ;; Default action: hide the subtree.
5812 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5813 (hide-subtree)
5814 (message "FOLDED")
5815 (setq org-cycle-subtree-status 'folded)
5816 (run-hook-with-args 'org-cycle-hook 'folded)))))
5818 ;;;###autoload
5819 (defun org-global-cycle (&optional arg)
5820 "Cycle the global visibility. For details see `org-cycle'.
5821 With C-u prefix arg, switch to startup visibility.
5822 With a numeric prefix, show all headlines up to that level."
5823 (interactive "P")
5824 (let ((org-cycle-include-plain-lists
5825 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5826 (cond
5827 ((integerp arg)
5828 (show-all)
5829 (hide-sublevels arg)
5830 (setq org-cycle-global-status 'contents))
5831 ((equal arg '(4))
5832 (org-set-startup-visibility)
5833 (message "Startup visibility, plus VISIBILITY properties."))
5835 (org-cycle '(4))))))
5837 (defun org-set-startup-visibility ()
5838 "Set the visibility required by startup options and properties."
5839 (cond
5840 ((eq org-startup-folded t)
5841 (org-cycle '(4)))
5842 ((eq org-startup-folded 'content)
5843 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5844 (org-cycle '(4)) (org-cycle '(4)))))
5845 (unless (eq org-startup-folded 'showeverything)
5846 (if org-hide-block-startup (org-hide-block-all))
5847 (org-set-visibility-according-to-property 'no-cleanup)
5848 (org-cycle-hide-archived-subtrees 'all)
5849 (org-cycle-hide-drawers 'all)
5850 (org-cycle-show-empty-lines t)))
5852 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5853 "Switch subtree visibilities according to :VISIBILITY: property."
5854 (interactive)
5855 (let (org-show-entry-below state)
5856 (save-excursion
5857 (goto-char (point-min))
5858 (while (re-search-forward
5859 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5860 nil t)
5861 (setq state (match-string 1))
5862 (save-excursion
5863 (org-back-to-heading t)
5864 (hide-subtree)
5865 (org-reveal)
5866 (cond
5867 ((equal state '("fold" "folded"))
5868 (hide-subtree))
5869 ((equal state "children")
5870 (org-show-hidden-entry)
5871 (show-children))
5872 ((equal state "content")
5873 (save-excursion
5874 (save-restriction
5875 (org-narrow-to-subtree)
5876 (org-content))))
5877 ((member state '("all" "showall"))
5878 (show-subtree)))))
5879 (unless no-cleanup
5880 (org-cycle-hide-archived-subtrees 'all)
5881 (org-cycle-hide-drawers 'all)
5882 (org-cycle-show-empty-lines 'all)))))
5884 (defun org-overview ()
5885 "Switch to overview mode, showing only top-level headlines.
5886 Really, this shows all headlines with level equal or greater than the level
5887 of the first headline in the buffer. This is important, because if the
5888 first headline is not level one, then (hide-sublevels 1) gives confusing
5889 results."
5890 (interactive)
5891 (let ((level (save-excursion
5892 (goto-char (point-min))
5893 (if (re-search-forward (concat "^" outline-regexp) nil t)
5894 (progn
5895 (goto-char (match-beginning 0))
5896 (funcall outline-level))))))
5897 (and level (hide-sublevels level))))
5899 (defun org-content (&optional arg)
5900 "Show all headlines in the buffer, like a table of contents.
5901 With numerical argument N, show content up to level N."
5902 (interactive "P")
5903 (save-excursion
5904 ;; Visit all headings and show their offspring
5905 (and (integerp arg) (org-overview))
5906 (goto-char (point-max))
5907 (catch 'exit
5908 (while (and (progn (condition-case nil
5909 (outline-previous-visible-heading 1)
5910 (error (goto-char (point-min))))
5912 (looking-at outline-regexp))
5913 (if (integerp arg)
5914 (show-children (1- arg))
5915 (show-branches))
5916 (if (bobp) (throw 'exit nil))))))
5919 (defun org-optimize-window-after-visibility-change (state)
5920 "Adjust the window after a change in outline visibility.
5921 This function is the default value of the hook `org-cycle-hook'."
5922 (when (get-buffer-window (current-buffer))
5923 (cond
5924 ((eq state 'content) nil)
5925 ((eq state 'all) nil)
5926 ((eq state 'folded) nil)
5927 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5928 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5930 (defun org-remove-empty-overlays-at (pos)
5931 "Remove outline overlays that do not contain non-white stuff."
5932 (mapc
5933 (lambda (o)
5934 (and (eq 'outline (overlay-get o 'invisible))
5935 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5936 (overlay-end o))))
5937 (delete-overlay o)))
5938 (overlays-at pos)))
5940 (defun org-clean-visibility-after-subtree-move ()
5941 "Fix visibility issues after moving a subtree."
5942 ;; First, find a reasonable region to look at:
5943 ;; Start two siblings above, end three below
5944 (let* ((beg (save-excursion
5945 (and (org-get-last-sibling)
5946 (org-get-last-sibling))
5947 (point)))
5948 (end (save-excursion
5949 (and (org-get-next-sibling)
5950 (org-get-next-sibling)
5951 (org-get-next-sibling))
5952 (if (org-at-heading-p)
5953 (point-at-eol)
5954 (point))))
5955 (level (looking-at "\\*+"))
5956 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5957 (save-excursion
5958 (save-restriction
5959 (narrow-to-region beg end)
5960 (when re
5961 ;; Properly fold already folded siblings
5962 (goto-char (point-min))
5963 (while (re-search-forward re nil t)
5964 (if (and (not (org-invisible-p))
5965 (save-excursion
5966 (goto-char (point-at-eol)) (org-invisible-p)))
5967 (hide-entry))))
5968 (org-cycle-show-empty-lines 'overview)
5969 (org-cycle-hide-drawers 'overview)))))
5971 (defun org-cycle-show-empty-lines (state)
5972 "Show empty lines above all visible headlines.
5973 The region to be covered depends on STATE when called through
5974 `org-cycle-hook'. Lisp program can use t for STATE to get the
5975 entire buffer covered. Note that an empty line is only shown if there
5976 are at least `org-cycle-separator-lines' empty lines before the headline."
5977 (when (not (= org-cycle-separator-lines 0))
5978 (save-excursion
5979 (let* ((n (abs org-cycle-separator-lines))
5980 (re (cond
5981 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5982 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5983 (t (let ((ns (number-to-string (- n 2))))
5984 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5985 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5986 beg end b e)
5987 (cond
5988 ((memq state '(overview contents t))
5989 (setq beg (point-min) end (point-max)))
5990 ((memq state '(children folded))
5991 (setq beg (point) end (progn (org-end-of-subtree t t)
5992 (beginning-of-line 2)
5993 (point)))))
5994 (when beg
5995 (goto-char beg)
5996 (while (re-search-forward re end t)
5997 (unless (get-char-property (match-end 1) 'invisible)
5998 (setq e (match-end 1))
5999 (if (< org-cycle-separator-lines 0)
6000 (setq b (save-excursion
6001 (goto-char (match-beginning 0))
6002 (org-back-over-empty-lines)
6003 (if (save-excursion
6004 (goto-char (max (point-min) (1- (point))))
6005 (org-on-heading-p))
6006 (1- (point))
6007 (point))))
6008 (setq b (match-beginning 1)))
6009 (outline-flag-region b e nil)))))))
6010 ;; Never hide empty lines at the end of the file.
6011 (save-excursion
6012 (goto-char (point-max))
6013 (outline-previous-heading)
6014 (outline-end-of-heading)
6015 (if (and (looking-at "[ \t\n]+")
6016 (= (match-end 0) (point-max)))
6017 (outline-flag-region (point) (match-end 0) nil))))
6019 (defun org-show-empty-lines-in-parent ()
6020 "Move to the parent and re-show empty lines before visible headlines."
6021 (save-excursion
6022 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6023 (org-cycle-show-empty-lines context))))
6025 (defun org-files-list ()
6026 "Return `org-agenda-files' list, plus all open org-mode files.
6027 This is useful for operations that need to scan all of a user's
6028 open and agenda-wise Org files."
6029 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6030 (dolist (buf (buffer-list))
6031 (with-current-buffer buf
6032 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6033 (let ((file (expand-file-name (buffer-file-name))))
6034 (unless (member file files)
6035 (push file files))))))
6036 files))
6038 (defsubst org-entry-beginning-position ()
6039 "Return the beginning position of the current entry."
6040 (save-excursion (outline-back-to-heading t) (point)))
6042 (defsubst org-entry-end-position ()
6043 "Return the end position of the current entry."
6044 (save-excursion (outline-next-heading) (point)))
6046 (defun org-cycle-hide-drawers (state)
6047 "Re-hide all drawers after a visibility state change."
6048 (when (and (org-mode-p)
6049 (not (memq state '(overview folded contents))))
6050 (save-excursion
6051 (let* ((globalp (memq state '(contents all)))
6052 (beg (if globalp (point-min) (point)))
6053 (end (if globalp (point-max)
6054 (if (eq state 'children)
6055 (save-excursion (outline-next-heading) (point))
6056 (org-end-of-subtree t)))))
6057 (goto-char beg)
6058 (while (re-search-forward org-drawer-regexp end t)
6059 (org-flag-drawer t))))))
6061 (defun org-flag-drawer (flag)
6062 (save-excursion
6063 (beginning-of-line 1)
6064 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6065 (let ((b (match-end 0))
6066 (outline-regexp org-outline-regexp))
6067 (if (re-search-forward
6068 "^[ \t]*:END:"
6069 (save-excursion (outline-next-heading) (point)) t)
6070 (outline-flag-region b (point-at-eol) flag)
6071 (error ":END: line missing at position %s" b))))))
6073 (defun org-subtree-end-visible-p ()
6074 "Is the end of the current subtree visible?"
6075 (pos-visible-in-window-p
6076 (save-excursion (org-end-of-subtree t) (point))))
6078 (defun org-first-headline-recenter (&optional N)
6079 "Move cursor to the first headline and recenter the headline.
6080 Optional argument N means put the headline into the Nth line of the window."
6081 (goto-char (point-min))
6082 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6083 (beginning-of-line)
6084 (recenter (prefix-numeric-value N))))
6086 ;;; Saving and restoring visibility
6088 (defun org-outline-overlay-data (&optional use-markers)
6089 "Return a list of the locations of all outline overlays.
6090 The are overlays with the `invisible' property value `outline'.
6091 The return valus is a list of cons cells, with start and stop
6092 positions for each overlay.
6093 If USE-MARKERS is set, return the positions as markers."
6094 (let (beg end)
6095 (save-excursion
6096 (save-restriction
6097 (widen)
6098 (delq nil
6099 (mapcar (lambda (o)
6100 (when (eq (overlay-get o 'invisible) 'outline)
6101 (setq beg (overlay-start o)
6102 end (overlay-end o))
6103 (and beg end (> end beg)
6104 (if use-markers
6105 (cons (move-marker (make-marker) beg)
6106 (move-marker (make-marker) end))
6107 (cons beg end)))))
6108 (overlays-in (point-min) (point-max))))))))
6110 (defun org-set-outline-overlay-data (data)
6111 "Create visibility overlays for all positions in DATA.
6112 DATA should have been made by `org-outline-overlay-data'."
6113 (let (o)
6114 (save-excursion
6115 (save-restriction
6116 (widen)
6117 (show-all)
6118 (mapc (lambda (c)
6119 (setq o (make-overlay (car c) (cdr c)))
6120 (overlay-put o 'invisible 'outline))
6121 data)))))
6123 (defmacro org-save-outline-visibility (use-markers &rest body)
6124 "Save and restore outline visibility around BODY.
6125 If USE-MARKERS is non-nil, use markers for the positions.
6126 This means that the buffer may change while running BODY,
6127 but it also means that the buffer should stay alive
6128 during the operation, because otherwise all these markers will
6129 point nowhere."
6130 (declare (indent 1))
6131 `(let ((data (org-outline-overlay-data ,use-markers)))
6132 (unwind-protect
6133 (progn
6134 ,@body
6135 (org-set-outline-overlay-data data))
6136 (when ,use-markers
6137 (mapc (lambda (c)
6138 (and (markerp (car c)) (move-marker (car c) nil))
6139 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
6140 data)))))
6143 ;;; Folding of blocks
6145 (defconst org-block-regexp
6147 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6148 "Regular expression for hiding blocks.")
6150 (defvar org-hide-block-overlays nil
6151 "Overlays hiding blocks.")
6152 (make-variable-buffer-local 'org-hide-block-overlays)
6154 (defun org-block-map (function &optional start end)
6155 "Call func at the head of all source blocks in the current
6156 buffer. Optional arguments START and END can be used to limit
6157 the range."
6158 (let ((start (or start (point-min)))
6159 (end (or end (point-max))))
6160 (save-excursion
6161 (goto-char start)
6162 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6163 (save-excursion
6164 (save-match-data
6165 (goto-char (match-beginning 0))
6166 (funcall function)))))))
6168 (defun org-hide-block-toggle-all ()
6169 "Toggle the visibility of all blocks in the current buffer."
6170 (org-block-map #'org-hide-block-toggle))
6172 (defun org-hide-block-all ()
6173 "Fold all blocks in the current buffer."
6174 (interactive)
6175 (org-show-block-all)
6176 (org-block-map #'org-hide-block-toggle-maybe))
6178 (defun org-show-block-all ()
6179 "Unfold all blocks in the current buffer."
6180 (mapc 'delete-overlay org-hide-block-overlays)
6181 (setq org-hide-block-overlays nil))
6183 (defun org-hide-block-toggle-maybe ()
6184 "Toggle visibility of block at point."
6185 (interactive)
6186 (let ((case-fold-search t))
6187 (if (save-excursion
6188 (beginning-of-line 1)
6189 (looking-at org-block-regexp))
6190 (progn (org-hide-block-toggle)
6191 t) ;; to signal that we took action
6192 nil))) ;; to signal that we did not
6194 (defun org-hide-block-toggle (&optional force)
6195 "Toggle the visibility of the current block."
6196 (interactive)
6197 (save-excursion
6198 (beginning-of-line)
6199 (if (re-search-forward org-block-regexp nil t)
6200 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6201 (end (match-end 0)) ;; end of entire body
6203 (if (memq t (mapcar (lambda (overlay)
6204 (eq (overlay-get overlay 'invisible)
6205 'org-hide-block))
6206 (overlays-at start)))
6207 (if (or (not force) (eq force 'off))
6208 (mapc (lambda (ov)
6209 (when (member ov org-hide-block-overlays)
6210 (setq org-hide-block-overlays
6211 (delq ov org-hide-block-overlays)))
6212 (when (eq (overlay-get ov 'invisible)
6213 'org-hide-block)
6214 (delete-overlay ov)))
6215 (overlays-at start)))
6216 (setq ov (make-overlay start end))
6217 (overlay-put ov 'invisible 'org-hide-block)
6218 ;; make the block accessible to isearch
6219 (overlay-put
6220 ov 'isearch-open-invisible
6221 (lambda (ov)
6222 (when (member ov org-hide-block-overlays)
6223 (setq org-hide-block-overlays
6224 (delq ov org-hide-block-overlays)))
6225 (when (eq (overlay-get ov 'invisible)
6226 'org-hide-block)
6227 (delete-overlay ov))))
6228 (push ov org-hide-block-overlays)))
6229 (error "Not looking at a source block"))))
6231 ;; org-tab-after-check-for-cycling-hook
6232 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6233 ;; Remove overlays when changing major mode
6234 (add-hook 'org-mode-hook
6235 (lambda () (org-add-hook 'change-major-mode-hook
6236 'org-show-block-all 'append 'local)))
6238 ;;; Org-goto
6240 (defvar org-goto-window-configuration nil)
6241 (defvar org-goto-marker nil)
6242 (defvar org-goto-map
6243 (let ((map (make-sparse-keymap)))
6244 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6245 (while (setq cmd (pop cmds))
6246 (substitute-key-definition cmd cmd map global-map)))
6247 (suppress-keymap map)
6248 (org-defkey map "\C-m" 'org-goto-ret)
6249 (org-defkey map [(return)] 'org-goto-ret)
6250 (org-defkey map [(left)] 'org-goto-left)
6251 (org-defkey map [(right)] 'org-goto-right)
6252 (org-defkey map [(control ?g)] 'org-goto-quit)
6253 (org-defkey map "\C-i" 'org-cycle)
6254 (org-defkey map [(tab)] 'org-cycle)
6255 (org-defkey map [(down)] 'outline-next-visible-heading)
6256 (org-defkey map [(up)] 'outline-previous-visible-heading)
6257 (if org-goto-auto-isearch
6258 (if (fboundp 'define-key-after)
6259 (define-key-after map [t] 'org-goto-local-auto-isearch)
6260 nil)
6261 (org-defkey map "q" 'org-goto-quit)
6262 (org-defkey map "n" 'outline-next-visible-heading)
6263 (org-defkey map "p" 'outline-previous-visible-heading)
6264 (org-defkey map "f" 'outline-forward-same-level)
6265 (org-defkey map "b" 'outline-backward-same-level)
6266 (org-defkey map "u" 'outline-up-heading))
6267 (org-defkey map "/" 'org-occur)
6268 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6269 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6270 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6271 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6272 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6273 map))
6275 (defconst org-goto-help
6276 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6277 RET=jump to location [Q]uit and return to previous location
6278 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6280 (defvar org-goto-start-pos) ; dynamically scoped parameter
6282 ;; FIXME: Docstring does not mention both interfaces
6283 (defun org-goto (&optional alternative-interface)
6284 "Look up a different location in the current file, keeping current visibility.
6286 When you want look-up or go to a different location in a document, the
6287 fastest way is often to fold the entire buffer and then dive into the tree.
6288 This method has the disadvantage, that the previous location will be folded,
6289 which may not be what you want.
6291 This command works around this by showing a copy of the current buffer
6292 in an indirect buffer, in overview mode. You can dive into the tree in
6293 that copy, use org-occur and incremental search to find a location.
6294 When pressing RET or `Q', the command returns to the original buffer in
6295 which the visibility is still unchanged. After RET is will also jump to
6296 the location selected in the indirect buffer and expose the
6297 the headline hierarchy above."
6298 (interactive "P")
6299 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6300 (org-refile-use-outline-path t)
6301 (org-refile-target-verify-function nil)
6302 (interface
6303 (if (not alternative-interface)
6304 org-goto-interface
6305 (if (eq org-goto-interface 'outline)
6306 'outline-path-completion
6307 'outline)))
6308 (org-goto-start-pos (point))
6309 (selected-point
6310 (if (eq interface 'outline)
6311 (car (org-get-location (current-buffer) org-goto-help))
6312 (nth 3 (org-refile-get-location "Goto: ")))))
6313 (if selected-point
6314 (progn
6315 (org-mark-ring-push org-goto-start-pos)
6316 (goto-char selected-point)
6317 (if (or (org-invisible-p) (org-invisible-p2))
6318 (org-show-context 'org-goto)))
6319 (message "Quit"))))
6321 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6322 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6323 (defvar org-goto-local-auto-isearch-map) ; defined below
6325 (defun org-get-location (buf help)
6326 "Let the user select a location in the Org-mode buffer BUF.
6327 This function uses a recursive edit. It returns the selected position
6328 or nil."
6329 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6330 (isearch-hide-immediately nil)
6331 (isearch-search-fun-function
6332 (lambda () 'org-goto-local-search-headings))
6333 (org-goto-selected-point org-goto-exit-command)
6334 (pop-up-frames nil)
6335 (special-display-buffer-names nil)
6336 (special-display-regexps nil)
6337 (special-display-function nil))
6338 (save-excursion
6339 (save-window-excursion
6340 (delete-other-windows)
6341 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6342 (switch-to-buffer
6343 (condition-case nil
6344 (make-indirect-buffer (current-buffer) "*org-goto*")
6345 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6346 (with-output-to-temp-buffer "*Help*"
6347 (princ help))
6348 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6349 (setq buffer-read-only nil)
6350 (let ((org-startup-truncated t)
6351 (org-startup-folded nil)
6352 (org-startup-align-all-tables nil))
6353 (org-mode)
6354 (org-overview))
6355 (setq buffer-read-only t)
6356 (if (and (boundp 'org-goto-start-pos)
6357 (integer-or-marker-p org-goto-start-pos))
6358 (let ((org-show-hierarchy-above t)
6359 (org-show-siblings t)
6360 (org-show-following-heading t))
6361 (goto-char org-goto-start-pos)
6362 (and (org-invisible-p) (org-show-context)))
6363 (goto-char (point-min)))
6364 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6365 (message "Select location and press RET")
6366 (use-local-map org-goto-map)
6367 (recursive-edit)
6369 (kill-buffer "*org-goto*")
6370 (cons org-goto-selected-point org-goto-exit-command)))
6372 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6373 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6374 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6375 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6377 (defun org-goto-local-search-headings (string bound noerror)
6378 "Search and make sure that any matches are in headlines."
6379 (catch 'return
6380 (while (if isearch-forward
6381 (search-forward string bound noerror)
6382 (search-backward string bound noerror))
6383 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6384 (and (member :headline context)
6385 (not (member :tags context))))
6386 (throw 'return (point))))))
6388 (defun org-goto-local-auto-isearch ()
6389 "Start isearch."
6390 (interactive)
6391 (goto-char (point-min))
6392 (let ((keys (this-command-keys)))
6393 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6394 (isearch-mode t)
6395 (isearch-process-search-char (string-to-char keys)))))
6397 (defun org-goto-ret (&optional arg)
6398 "Finish `org-goto' by going to the new location."
6399 (interactive "P")
6400 (setq org-goto-selected-point (point)
6401 org-goto-exit-command 'return)
6402 (throw 'exit nil))
6404 (defun org-goto-left ()
6405 "Finish `org-goto' by going to the new location."
6406 (interactive)
6407 (if (org-on-heading-p)
6408 (progn
6409 (beginning-of-line 1)
6410 (setq org-goto-selected-point (point)
6411 org-goto-exit-command 'left)
6412 (throw 'exit nil))
6413 (error "Not on a heading")))
6415 (defun org-goto-right ()
6416 "Finish `org-goto' by going to the new location."
6417 (interactive)
6418 (if (org-on-heading-p)
6419 (progn
6420 (setq org-goto-selected-point (point)
6421 org-goto-exit-command 'right)
6422 (throw 'exit nil))
6423 (error "Not on a heading")))
6425 (defun org-goto-quit ()
6426 "Finish `org-goto' without cursor motion."
6427 (interactive)
6428 (setq org-goto-selected-point nil)
6429 (setq org-goto-exit-command 'quit)
6430 (throw 'exit nil))
6432 ;;; Indirect buffer display of subtrees
6434 (defvar org-indirect-dedicated-frame nil
6435 "This is the frame being used for indirect tree display.")
6436 (defvar org-last-indirect-buffer nil)
6438 (defun org-tree-to-indirect-buffer (&optional arg)
6439 "Create indirect buffer and narrow it to current subtree.
6440 With numerical prefix ARG, go up to this level and then take that tree.
6441 If ARG is negative, go up that many levels.
6442 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6443 indirect buffer previously made with this command, to avoid proliferation of
6444 indirect buffers. However, when you call the command with a `C-u' prefix, or
6445 when `org-indirect-buffer-display' is `new-frame', the last buffer
6446 is kept so that you can work with several indirect buffers at the same time.
6447 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6448 requests that a new frame be made for the new buffer, so that the dedicated
6449 frame is not changed."
6450 (interactive "P")
6451 (let ((cbuf (current-buffer))
6452 (cwin (selected-window))
6453 (pos (point))
6454 beg end level heading ibuf)
6455 (save-excursion
6456 (org-back-to-heading t)
6457 (when (numberp arg)
6458 (setq level (org-outline-level))
6459 (if (< arg 0) (setq arg (+ level arg)))
6460 (while (> (setq level (org-outline-level)) arg)
6461 (outline-up-heading 1 t)))
6462 (setq beg (point)
6463 heading (org-get-heading))
6464 (org-end-of-subtree t t)
6465 (if (org-on-heading-p) (backward-char 1))
6466 (setq end (point)))
6467 (if (and (buffer-live-p org-last-indirect-buffer)
6468 (not (eq org-indirect-buffer-display 'new-frame))
6469 (not arg))
6470 (kill-buffer org-last-indirect-buffer))
6471 (setq ibuf (org-get-indirect-buffer cbuf)
6472 org-last-indirect-buffer ibuf)
6473 (cond
6474 ((or (eq org-indirect-buffer-display 'new-frame)
6475 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6476 (select-frame (make-frame))
6477 (delete-other-windows)
6478 (switch-to-buffer ibuf)
6479 (org-set-frame-title heading))
6480 ((eq org-indirect-buffer-display 'dedicated-frame)
6481 (raise-frame
6482 (select-frame (or (and org-indirect-dedicated-frame
6483 (frame-live-p org-indirect-dedicated-frame)
6484 org-indirect-dedicated-frame)
6485 (setq org-indirect-dedicated-frame (make-frame)))))
6486 (delete-other-windows)
6487 (switch-to-buffer ibuf)
6488 (org-set-frame-title (concat "Indirect: " heading)))
6489 ((eq org-indirect-buffer-display 'current-window)
6490 (switch-to-buffer ibuf))
6491 ((eq org-indirect-buffer-display 'other-window)
6492 (pop-to-buffer ibuf))
6493 (t (error "Invalid value")))
6494 (if (featurep 'xemacs)
6495 (save-excursion (org-mode) (turn-on-font-lock)))
6496 (narrow-to-region beg end)
6497 (show-all)
6498 (goto-char pos)
6499 (and (window-live-p cwin) (select-window cwin))))
6501 (defun org-get-indirect-buffer (&optional buffer)
6502 (setq buffer (or buffer (current-buffer)))
6503 (let ((n 1) (base (buffer-name buffer)) bname)
6504 (while (buffer-live-p
6505 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6506 (setq n (1+ n)))
6507 (condition-case nil
6508 (make-indirect-buffer buffer bname 'clone)
6509 (error (make-indirect-buffer buffer bname)))))
6511 (defun org-set-frame-title (title)
6512 "Set the title of the current frame to the string TITLE."
6513 ;; FIXME: how to name a single frame in XEmacs???
6514 (unless (featurep 'xemacs)
6515 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6517 ;;;; Structure editing
6519 ;;; Inserting headlines
6521 (defun org-previous-line-empty-p ()
6522 (save-excursion
6523 (and (not (bobp))
6524 (or (beginning-of-line 0) t)
6525 (save-match-data
6526 (looking-at "[ \t]*$")))))
6528 (defun org-insert-heading (&optional force-heading invisible-ok)
6529 "Insert a new heading or item with same depth at point.
6530 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6531 If point is at the beginning of a headline, insert a sibling before the
6532 current headline. If point is not at the beginning, do not split the line,
6533 but create the new headline after the current line.
6534 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6535 This is important for non-interactive uses of the command."
6536 (interactive "P")
6537 (if (or (= (buffer-size) 0)
6538 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6539 (org-on-heading-p))))
6540 (not (org-in-item-p))))
6541 (insert "\n* ")
6542 (when (or force-heading (not (org-insert-item)))
6543 (let* ((empty-line-p nil)
6544 (head (save-excursion
6545 (condition-case nil
6546 (progn
6547 (org-back-to-heading invisible-ok)
6548 (setq empty-line-p (org-previous-line-empty-p))
6549 (match-string 0))
6550 (error "*"))))
6551 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6552 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6553 pos hide-previous previous-pos)
6554 (cond
6555 ((and (org-on-heading-p) (bolp)
6556 (or (bobp)
6557 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6558 ;; insert before the current line
6559 (open-line (if blank 2 1)))
6560 ((and (bolp)
6561 (not org-insert-heading-respect-content)
6562 (or (bobp)
6563 (save-excursion
6564 (backward-char 1) (not (org-invisible-p)))))
6565 ;; insert right here
6566 nil)
6568 ;; somewhere in the line
6569 (save-excursion
6570 (setq previous-pos (point-at-bol))
6571 (end-of-line)
6572 (setq hide-previous (org-invisible-p)))
6573 (and org-insert-heading-respect-content (org-show-subtree))
6574 (let ((split
6575 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6576 (save-excursion
6577 (let ((p (point)))
6578 (goto-char (point-at-bol))
6579 (and (looking-at org-complex-heading-regexp)
6580 (> p (match-beginning 4)))))))
6581 tags pos)
6582 (cond
6583 (org-insert-heading-respect-content
6584 (org-end-of-subtree nil t)
6585 (or (bolp) (newline))
6586 (or (org-previous-line-empty-p)
6587 (and blank (newline)))
6588 (open-line 1))
6589 ((org-on-heading-p)
6590 (when hide-previous
6591 (show-children)
6592 (org-show-entry))
6593 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6594 (setq tags (and (match-end 2) (match-string 2)))
6595 (and (match-end 1)
6596 (delete-region (match-beginning 1) (match-end 1)))
6597 (setq pos (point-at-bol))
6598 (or split (end-of-line 1))
6599 (delete-horizontal-space)
6600 (if (string-match "\\`\\*+\\'"
6601 (buffer-substring (point-at-bol) (point)))
6602 (insert " "))
6603 (newline (if blank 2 1))
6604 (when tags
6605 (save-excursion
6606 (goto-char pos)
6607 (end-of-line 1)
6608 (insert " " tags)
6609 (org-set-tags nil 'align))))
6611 (or split (end-of-line 1))
6612 (newline (if blank 2 1)))))))
6613 (insert head) (just-one-space)
6614 (setq pos (point))
6615 (end-of-line 1)
6616 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6617 (when (and org-insert-heading-respect-content hide-previous)
6618 (save-excursion
6619 (goto-char previous-pos)
6620 (hide-subtree)))
6621 (run-hooks 'org-insert-heading-hook)))))
6623 (defun org-get-heading (&optional no-tags)
6624 "Return the heading of the current entry, without the stars."
6625 (save-excursion
6626 (org-back-to-heading t)
6627 (if (looking-at
6628 (if no-tags
6629 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6630 "\\*+[ \t]+\\([^\r\n]*\\)"))
6631 (match-string 1) "")))
6633 (defun org-heading-components ()
6634 "Return the components of the current heading.
6635 This is a list with the following elements:
6636 - the level as an integer
6637 - the reduced level, different if `org-odd-levels-only' is set.
6638 - the TODO keyword, or nil
6639 - the priority character, like ?A, or nil if no priority is given
6640 - the headline text itself, or the tags string if no headline text
6641 - the tags string, or nil."
6642 (save-excursion
6643 (org-back-to-heading t)
6644 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6645 (list (length (match-string 1))
6646 (org-reduced-level (length (match-string 1)))
6647 (org-match-string-no-properties 2)
6648 (and (match-end 3) (aref (match-string 3) 2))
6649 (org-match-string-no-properties 4)
6650 (org-match-string-no-properties 5)))))
6652 (defun org-get-entry ()
6653 "Get the entry text, after heading, entire subtree."
6654 (save-excursion
6655 (org-back-to-heading t)
6656 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6658 (defun org-insert-heading-after-current ()
6659 "Insert a new heading with same level as current, after current subtree."
6660 (interactive)
6661 (org-back-to-heading)
6662 (org-insert-heading)
6663 (org-move-subtree-down)
6664 (end-of-line 1))
6666 (defun org-insert-heading-respect-content ()
6667 (interactive)
6668 (let ((org-insert-heading-respect-content t))
6669 (org-insert-heading t)))
6671 (defun org-insert-todo-heading-respect-content (&optional force-state)
6672 (interactive "P")
6673 (let ((org-insert-heading-respect-content t))
6674 (org-insert-todo-heading force-state t)))
6676 (defun org-insert-todo-heading (arg &optional force-heading)
6677 "Insert a new heading with the same level and TODO state as current heading.
6678 If the heading has no TODO state, or if the state is DONE, use the first
6679 state (TODO by default). Also with prefix arg, force first state."
6680 (interactive "P")
6681 (when (or force-heading (not (org-insert-item 'checkbox)))
6682 (org-insert-heading force-heading)
6683 (save-excursion
6684 (org-back-to-heading)
6685 (outline-previous-heading)
6686 (looking-at org-todo-line-regexp))
6687 (let*
6688 ((new-mark-x
6689 (if (or arg
6690 (not (match-beginning 2))
6691 (member (match-string 2) org-done-keywords))
6692 (car org-todo-keywords-1)
6693 (match-string 2)))
6694 (new-mark
6696 (run-hook-with-args-until-success
6697 'org-todo-get-default-hook new-mark-x nil)
6698 new-mark-x)))
6699 (beginning-of-line 1)
6700 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6701 (if org-treat-insert-todo-heading-as-state-change
6702 (org-todo new-mark)
6703 (insert new-mark " "))))
6704 (when org-provide-todo-statistics
6705 (org-update-parent-todo-statistics))))
6707 (defun org-insert-subheading (arg)
6708 "Insert a new subheading and demote it.
6709 Works for outline headings and for plain lists alike."
6710 (interactive "P")
6711 (org-insert-heading arg)
6712 (cond
6713 ((org-on-heading-p) (org-do-demote))
6714 ((org-at-item-p) (org-indent-item 1))))
6716 (defun org-insert-todo-subheading (arg)
6717 "Insert a new subheading with TODO keyword or checkbox and demote it.
6718 Works for outline headings and for plain lists alike."
6719 (interactive "P")
6720 (org-insert-todo-heading arg)
6721 (cond
6722 ((org-on-heading-p) (org-do-demote))
6723 ((org-at-item-p) (org-indent-item 1))))
6725 ;;; Promotion and Demotion
6727 (defvar org-after-demote-entry-hook nil
6728 "Hook run after an entry has been demoted.
6729 The cursor will be at the beginning of the entry.
6730 When a subtree is being demoted, the hook will be called for each node.")
6732 (defvar org-after-promote-entry-hook nil
6733 "Hook run after an entry has been promoted.
6734 The cursor will be at the beginning of the entry.
6735 When a subtree is being promoted, the hook will be called for each node.")
6737 (defun org-promote-subtree ()
6738 "Promote the entire subtree.
6739 See also `org-promote'."
6740 (interactive)
6741 (save-excursion
6742 (org-map-tree 'org-promote))
6743 (org-fix-position-after-promote))
6745 (defun org-demote-subtree ()
6746 "Demote the entire subtree. See `org-demote'.
6747 See also `org-promote'."
6748 (interactive)
6749 (save-excursion
6750 (org-map-tree 'org-demote))
6751 (org-fix-position-after-promote))
6754 (defun org-do-promote ()
6755 "Promote the current heading higher up the tree.
6756 If the region is active in `transient-mark-mode', promote all headings
6757 in the region."
6758 (interactive)
6759 (save-excursion
6760 (if (org-region-active-p)
6761 (org-map-region 'org-promote (region-beginning) (region-end))
6762 (org-promote)))
6763 (org-fix-position-after-promote))
6765 (defun org-do-demote ()
6766 "Demote the current heading lower down the tree.
6767 If the region is active in `transient-mark-mode', demote all headings
6768 in the region."
6769 (interactive)
6770 (save-excursion
6771 (if (org-region-active-p)
6772 (org-map-region 'org-demote (region-beginning) (region-end))
6773 (org-demote)))
6774 (org-fix-position-after-promote))
6776 (defun org-fix-position-after-promote ()
6777 "Make sure that after pro/demotion cursor position is right."
6778 (let ((pos (point)))
6779 (when (save-excursion
6780 (beginning-of-line 1)
6781 (looking-at org-todo-line-regexp)
6782 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6783 (cond ((eobp) (insert " "))
6784 ((eolp) (insert " "))
6785 ((equal (char-after) ?\ ) (forward-char 1))))))
6787 (defun org-current-level ()
6788 "Return the level of the current entry, or nil if before the first headline.
6789 The level is the number of stars at the beginning of the headline."
6790 (save-excursion
6791 (condition-case nil
6792 (progn
6793 (org-back-to-heading t)
6794 (funcall outline-level))
6795 (error nil))))
6797 (defun org-get-previous-line-level ()
6798 "Return the outline depth of the last headline before the current line.
6799 Returns 0 for the first headline in the buffer, and nil if before the
6800 first headline."
6801 (let ((current-level (org-current-level))
6802 (prev-level (when (> (line-number-at-pos) 1)
6803 (save-excursion
6804 (beginning-of-line 0)
6805 (org-current-level)))))
6806 (cond ((null current-level) nil) ; Before first headline
6807 ((null prev-level) 0) ; At first headline
6808 (prev-level))))
6810 (defun org-reduced-level (l)
6811 "Compute the effective level of a heading.
6812 This takes into account the setting of `org-odd-levels-only'."
6813 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6815 (defun org-level-increment ()
6816 "Return the number of stars that will be added or removed at a
6817 time to headlines when structure editing, based on the value of
6818 `org-odd-levels-only'."
6819 (if org-odd-levels-only 2 1))
6821 (defun org-get-valid-level (level &optional change)
6822 "Rectify a level change under the influence of `org-odd-levels-only'
6823 LEVEL is a current level, CHANGE is by how much the level should be
6824 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6825 even level numbers will become the next higher odd number."
6826 (if org-odd-levels-only
6827 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6828 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6829 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6830 (max 1 (+ level (or change 0)))))
6832 (if (boundp 'define-obsolete-function-alias)
6833 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6834 (define-obsolete-function-alias 'org-get-legal-level
6835 'org-get-valid-level)
6836 (define-obsolete-function-alias 'org-get-legal-level
6837 'org-get-valid-level "23.1")))
6839 (defun org-promote ()
6840 "Promote the current heading higher up the tree.
6841 If the region is active in `transient-mark-mode', promote all headings
6842 in the region."
6843 (org-back-to-heading t)
6844 (let* ((level (save-match-data (funcall outline-level)))
6845 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6846 (diff (abs (- level (length up-head) -1))))
6847 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6848 (replace-match up-head nil t)
6849 ;; Fixup tag positioning
6850 (and org-auto-align-tags (org-set-tags nil t))
6851 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6852 (run-hooks 'org-after-promote-entry-hook)))
6854 (defun org-demote ()
6855 "Demote the current heading lower down the tree.
6856 If the region is active in `transient-mark-mode', demote all headings
6857 in the region."
6858 (org-back-to-heading t)
6859 (let* ((level (save-match-data (funcall outline-level)))
6860 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6861 (diff (abs (- level (length down-head) -1))))
6862 (replace-match down-head nil t)
6863 ;; Fixup tag positioning
6864 (and org-auto-align-tags (org-set-tags nil t))
6865 (if org-adapt-indentation (org-fixup-indentation diff))
6866 (run-hooks 'org-after-demote-entry-hook)))
6868 (defun org-cycle-level ()
6869 "Cycle the level of an empty headline through possible states.
6870 This goes first to child, then to parent, level, then up the hierarchy.
6871 After top level, it switches back to sibling level."
6872 (interactive)
6873 (let ((org-adapt-indentation nil))
6874 (when (org-point-at-end-of-empty-headline)
6875 (setq this-command 'org-cycle-level) ; Only needed for caching
6876 (let ((cur-level (org-current-level))
6877 (prev-level (org-get-previous-line-level)))
6878 (cond
6879 ;; If first headline in file, promote to top-level.
6880 ((= prev-level 0)
6881 (loop repeat (/ (- cur-level 1) (org-level-increment))
6882 do (org-do-promote)))
6883 ;; If same level as prev, demote one.
6884 ((= prev-level cur-level)
6885 (org-do-demote))
6886 ;; If parent is top-level, promote to top level if not already.
6887 ((= prev-level 1)
6888 (loop repeat (/ (- cur-level 1) (org-level-increment))
6889 do (org-do-promote)))
6890 ;; If top-level, return to prev-level.
6891 ((= cur-level 1)
6892 (loop repeat (/ (- prev-level 1) (org-level-increment))
6893 do (org-do-demote)))
6894 ;; If less than prev-level, promote one.
6895 ((< cur-level prev-level)
6896 (org-do-promote))
6897 ;; If deeper than prev-level, promote until higher than
6898 ;; prev-level.
6899 ((> cur-level prev-level)
6900 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6901 do (org-do-promote))))
6902 t))))
6904 (defun org-map-tree (fun)
6905 "Call FUN for every heading underneath the current one."
6906 (org-back-to-heading)
6907 (let ((level (funcall outline-level)))
6908 (save-excursion
6909 (funcall fun)
6910 (while (and (progn
6911 (outline-next-heading)
6912 (> (funcall outline-level) level))
6913 (not (eobp)))
6914 (funcall fun)))))
6916 (defun org-map-region (fun beg end)
6917 "Call FUN for every heading between BEG and END."
6918 (let ((org-ignore-region t))
6919 (save-excursion
6920 (setq end (copy-marker end))
6921 (goto-char beg)
6922 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6923 (< (point) end))
6924 (funcall fun))
6925 (while (and (progn
6926 (outline-next-heading)
6927 (< (point) end))
6928 (not (eobp)))
6929 (funcall fun)))))
6931 (defun org-fixup-indentation (diff)
6932 "Change the indentation in the current entry by DIFF
6933 However, if any line in the current entry has no indentation, or if it
6934 would end up with no indentation after the change, nothing at all is done."
6935 (save-excursion
6936 (let ((end (save-excursion (outline-next-heading)
6937 (point-marker)))
6938 (prohibit (if (> diff 0)
6939 "^\\S-"
6940 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6941 col)
6942 (unless (save-excursion (end-of-line 1)
6943 (re-search-forward prohibit end t))
6944 (while (and (< (point) end)
6945 (re-search-forward "^[ \t]+" end t))
6946 (goto-char (match-end 0))
6947 (setq col (current-column))
6948 (if (< diff 0) (replace-match ""))
6949 (org-indent-to-column (+ diff col))))
6950 (move-marker end nil))))
6952 (defun org-convert-to-odd-levels ()
6953 "Convert an org-mode file with all levels allowed to one with odd levels.
6954 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6955 level 5 etc."
6956 (interactive)
6957 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6958 (let ((outline-regexp org-outline-regexp)
6959 (outline-level 'org-outline-level)
6960 (org-odd-levels-only nil) n)
6961 (save-excursion
6962 (goto-char (point-min))
6963 (while (re-search-forward "^\\*\\*+ " nil t)
6964 (setq n (- (length (match-string 0)) 2))
6965 (while (>= (setq n (1- n)) 0)
6966 (org-demote))
6967 (end-of-line 1))))))
6969 (defun org-convert-to-oddeven-levels ()
6970 "Convert an org-mode file with only odd levels to one with odd and even levels.
6971 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6972 section with an even level, conversion would destroy the structure of the file. An error
6973 is signaled in this case."
6974 (interactive)
6975 (goto-char (point-min))
6976 ;; First check if there are no even levels
6977 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6978 (org-show-context t)
6979 (error "Not all levels are odd in this file. Conversion not possible"))
6980 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6981 (let ((outline-regexp org-outline-regexp)
6982 (outline-level 'org-outline-level)
6983 (org-odd-levels-only nil) n)
6984 (save-excursion
6985 (goto-char (point-min))
6986 (while (re-search-forward "^\\*\\*+ " nil t)
6987 (setq n (/ (1- (length (match-string 0))) 2))
6988 (while (>= (setq n (1- n)) 0)
6989 (org-promote))
6990 (end-of-line 1))))))
6992 (defun org-tr-level (n)
6993 "Make N odd if required."
6994 (if org-odd-levels-only (1+ (/ n 2)) n))
6996 ;;; Vertical tree motion, cutting and pasting of subtrees
6998 (defun org-move-subtree-up (&optional arg)
6999 "Move the current subtree up past ARG headlines of the same level."
7000 (interactive "p")
7001 (org-move-subtree-down (- (prefix-numeric-value arg))))
7003 (defun org-move-subtree-down (&optional arg)
7004 "Move the current subtree down past ARG headlines of the same level."
7005 (interactive "p")
7006 (setq arg (prefix-numeric-value arg))
7007 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7008 'org-get-last-sibling))
7009 (ins-point (make-marker))
7010 (cnt (abs arg))
7011 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7012 ;; Select the tree
7013 (org-back-to-heading)
7014 (setq beg0 (point))
7015 (save-excursion
7016 (setq ne-beg (org-back-over-empty-lines))
7017 (setq beg (point)))
7018 (save-match-data
7019 (save-excursion (outline-end-of-heading)
7020 (setq folded (org-invisible-p)))
7021 (outline-end-of-subtree))
7022 (outline-next-heading)
7023 (setq ne-end (org-back-over-empty-lines))
7024 (setq end (point))
7025 (goto-char beg0)
7026 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7027 ;; include less whitespace
7028 (save-excursion
7029 (goto-char beg)
7030 (forward-line (- ne-beg ne-end))
7031 (setq beg (point))))
7032 ;; Find insertion point, with error handling
7033 (while (> cnt 0)
7034 (or (and (funcall movfunc) (looking-at outline-regexp))
7035 (progn (goto-char beg0)
7036 (error "Cannot move past superior level or buffer limit")))
7037 (setq cnt (1- cnt)))
7038 (if (> arg 0)
7039 ;; Moving forward - still need to move over subtree
7040 (progn (org-end-of-subtree t t)
7041 (save-excursion
7042 (org-back-over-empty-lines)
7043 (or (bolp) (newline)))))
7044 (setq ne-ins (org-back-over-empty-lines))
7045 (move-marker ins-point (point))
7046 (setq txt (buffer-substring beg end))
7047 (org-save-markers-in-region beg end)
7048 (delete-region beg end)
7049 (org-remove-empty-overlays-at beg)
7050 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7051 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7052 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7053 (let ((bbb (point)))
7054 (insert-before-markers txt)
7055 (org-reinstall-markers-in-region bbb)
7056 (move-marker ins-point bbb))
7057 (or (bolp) (insert "\n"))
7058 (setq ins-end (point))
7059 (goto-char ins-point)
7060 (org-skip-whitespace)
7061 (when (and (< arg 0)
7062 (org-first-sibling-p)
7063 (> ne-ins ne-beg))
7064 ;; Move whitespace back to beginning
7065 (save-excursion
7066 (goto-char ins-end)
7067 (let ((kill-whole-line t))
7068 (kill-line (- ne-ins ne-beg)) (point)))
7069 (insert (make-string (- ne-ins ne-beg) ?\n)))
7070 (move-marker ins-point nil)
7071 (if folded
7072 (hide-subtree)
7073 (org-show-entry)
7074 (show-children)
7075 (org-cycle-hide-drawers 'children))
7076 (org-clean-visibility-after-subtree-move)))
7078 (defvar org-subtree-clip ""
7079 "Clipboard for cut and paste of subtrees.
7080 This is actually only a copy of the kill, because we use the normal kill
7081 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7083 (defvar org-subtree-clip-folded nil
7084 "Was the last copied subtree folded?
7085 This is used to fold the tree back after pasting.")
7087 (defun org-cut-subtree (&optional n)
7088 "Cut the current subtree into the clipboard.
7089 With prefix arg N, cut this many sequential subtrees.
7090 This is a short-hand for marking the subtree and then cutting it."
7091 (interactive "p")
7092 (org-copy-subtree n 'cut))
7094 (defun org-copy-subtree (&optional n cut force-store-markers)
7095 "Cut the current subtree into the clipboard.
7096 With prefix arg N, cut this many sequential subtrees.
7097 This is a short-hand for marking the subtree and then copying it.
7098 If CUT is non-nil, actually cut the subtree.
7099 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7100 of some markers in the region, even if CUT is non-nil. This is
7101 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7102 (interactive "p")
7103 (let (beg end folded (beg0 (point)))
7104 (if (interactive-p)
7105 (org-back-to-heading nil) ; take what looks like a subtree
7106 (org-back-to-heading t)) ; take what is really there
7107 (org-back-over-empty-lines)
7108 (setq beg (point))
7109 (skip-chars-forward " \t\r\n")
7110 (save-match-data
7111 (save-excursion (outline-end-of-heading)
7112 (setq folded (org-invisible-p)))
7113 (condition-case nil
7114 (org-forward-same-level (1- n) t)
7115 (error nil))
7116 (org-end-of-subtree t t))
7117 (org-back-over-empty-lines)
7118 (setq end (point))
7119 (goto-char beg0)
7120 (when (> end beg)
7121 (setq org-subtree-clip-folded folded)
7122 (when (or cut force-store-markers)
7123 (org-save-markers-in-region beg end))
7124 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7125 (setq org-subtree-clip (current-kill 0))
7126 (message "%s: Subtree(s) with %d characters"
7127 (if cut "Cut" "Copied")
7128 (length org-subtree-clip)))))
7130 (defun org-paste-subtree (&optional level tree for-yank)
7131 "Paste the clipboard as a subtree, with modification of headline level.
7132 The entire subtree is promoted or demoted in order to match a new headline
7133 level.
7135 If the cursor is at the beginning of a headline, the same level as
7136 that headline is used to paste the tree
7138 If not, the new level is derived from the *visible* headings
7139 before and after the insertion point, and taken to be the inferior headline
7140 level of the two. So if the previous visible heading is level 3 and the
7141 next is level 4 (or vice versa), level 4 will be used for insertion.
7142 This makes sure that the subtree remains an independent subtree and does
7143 not swallow low level entries.
7145 You can also force a different level, either by using a numeric prefix
7146 argument, or by inserting the heading marker by hand. For example, if the
7147 cursor is after \"*****\", then the tree will be shifted to level 5.
7149 If optional TREE is given, use this text instead of the kill ring.
7151 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7152 move back over whitespace before inserting, and move point to the end of
7153 the inserted text when done."
7154 (interactive "P")
7155 (setq tree (or tree (and kill-ring (current-kill 0))))
7156 (unless (org-kill-is-subtree-p tree)
7157 (error "%s"
7158 (substitute-command-keys
7159 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7160 (let* ((visp (not (org-invisible-p)))
7161 (txt tree)
7162 (^re (concat "^\\(" outline-regexp "\\)"))
7163 (re (concat "\\(" outline-regexp "\\)"))
7164 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7166 (old-level (if (string-match ^re txt)
7167 (- (match-end 0) (match-beginning 0) 1)
7168 -1))
7169 (force-level (cond (level (prefix-numeric-value level))
7170 ((and (looking-at "[ \t]*$")
7171 (string-match
7172 ^re_ (buffer-substring
7173 (point-at-bol) (point))))
7174 (- (match-end 1) (match-beginning 1)))
7175 ((and (bolp)
7176 (looking-at org-outline-regexp))
7177 (- (match-end 0) (point) 1))
7178 (t nil)))
7179 (previous-level (save-excursion
7180 (condition-case nil
7181 (progn
7182 (outline-previous-visible-heading 1)
7183 (if (looking-at re)
7184 (- (match-end 0) (match-beginning 0) 1)
7186 (error 1))))
7187 (next-level (save-excursion
7188 (condition-case nil
7189 (progn
7190 (or (looking-at outline-regexp)
7191 (outline-next-visible-heading 1))
7192 (if (looking-at re)
7193 (- (match-end 0) (match-beginning 0) 1)
7195 (error 1))))
7196 (new-level (or force-level (max previous-level next-level)))
7197 (shift (if (or (= old-level -1)
7198 (= new-level -1)
7199 (= old-level new-level))
7201 (- new-level old-level)))
7202 (delta (if (> shift 0) -1 1))
7203 (func (if (> shift 0) 'org-demote 'org-promote))
7204 (org-odd-levels-only nil)
7205 beg end newend)
7206 ;; Remove the forced level indicator
7207 (if force-level
7208 (delete-region (point-at-bol) (point)))
7209 ;; Paste
7210 (beginning-of-line 1)
7211 (unless for-yank (org-back-over-empty-lines))
7212 (setq beg (point))
7213 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7214 (insert-before-markers txt)
7215 (unless (string-match "\n\\'" txt) (insert "\n"))
7216 (setq newend (point))
7217 (org-reinstall-markers-in-region beg)
7218 (setq end (point))
7219 (goto-char beg)
7220 (skip-chars-forward " \t\n\r")
7221 (setq beg (point))
7222 (if (and (org-invisible-p) visp)
7223 (save-excursion (outline-show-heading)))
7224 ;; Shift if necessary
7225 (unless (= shift 0)
7226 (save-restriction
7227 (narrow-to-region beg end)
7228 (while (not (= shift 0))
7229 (org-map-region func (point-min) (point-max))
7230 (setq shift (+ delta shift)))
7231 (goto-char (point-min))
7232 (setq newend (point-max))))
7233 (when (or (interactive-p) for-yank)
7234 (message "Clipboard pasted as level %d subtree" new-level))
7235 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7236 kill-ring
7237 (eq org-subtree-clip (current-kill 0))
7238 org-subtree-clip-folded)
7239 ;; The tree was folded before it was killed/copied
7240 (hide-subtree))
7241 (and for-yank (goto-char newend))))
7243 (defun org-kill-is-subtree-p (&optional txt)
7244 "Check if the current kill is an outline subtree, or a set of trees.
7245 Returns nil if kill does not start with a headline, or if the first
7246 headline level is not the largest headline level in the tree.
7247 So this will actually accept several entries of equal levels as well,
7248 which is OK for `org-paste-subtree'.
7249 If optional TXT is given, check this string instead of the current kill."
7250 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7251 (start-level (and kill
7252 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7253 org-outline-regexp "\\)")
7254 kill)
7255 (- (match-end 2) (match-beginning 2) 1)))
7256 (re (concat "^" org-outline-regexp))
7257 (start (1+ (or (match-beginning 2) -1))))
7258 (if (not start-level)
7259 (progn
7260 nil) ;; does not even start with a heading
7261 (catch 'exit
7262 (while (setq start (string-match re kill (1+ start)))
7263 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7264 (throw 'exit nil)))
7265 t))))
7267 (defvar org-markers-to-move nil
7268 "Markers that should be moved with a cut-and-paste operation.
7269 Those markers are stored together with their positions relative to
7270 the start of the region.")
7272 (defun org-save-markers-in-region (beg end)
7273 "Check markers in region.
7274 If these markers are between BEG and END, record their position relative
7275 to BEG, so that after moving the block of text, we can put the markers back
7276 into place.
7277 This function gets called just before an entry or tree gets cut from the
7278 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7279 called immediately, to move the markers with the entries."
7280 (setq org-markers-to-move nil)
7281 (when (featurep 'org-clock)
7282 (org-clock-save-markers-for-cut-and-paste beg end))
7283 (when (featurep 'org-agenda)
7284 (org-agenda-save-markers-for-cut-and-paste beg end)))
7286 (defun org-check-and-save-marker (marker beg end)
7287 "Check if MARKER is between BEG and END.
7288 If yes, remember the marker and the distance to BEG."
7289 (when (and (marker-buffer marker)
7290 (equal (marker-buffer marker) (current-buffer)))
7291 (if (and (>= marker beg) (< marker end))
7292 (push (cons marker (- marker beg)) org-markers-to-move))))
7294 (defun org-reinstall-markers-in-region (beg)
7295 "Move all remembered markers to their position relative to BEG."
7296 (mapc (lambda (x)
7297 (move-marker (car x) (+ beg (cdr x))))
7298 org-markers-to-move)
7299 (setq org-markers-to-move nil))
7301 (defun org-narrow-to-subtree ()
7302 "Narrow buffer to the current subtree."
7303 (interactive)
7304 (save-excursion
7305 (save-match-data
7306 (narrow-to-region
7307 (progn (org-back-to-heading t) (point))
7308 (progn (org-end-of-subtree t t)
7309 (if (org-on-heading-p) (backward-char 1))
7310 (point))))))
7312 (eval-when-compile
7313 (defvar org-property-drawer-re))
7315 (defun org-clone-subtree-with-time-shift (n &optional shift)
7316 "Clone the task (subtree) at point N times.
7317 The clones will be inserted as siblings.
7319 In interactive use, the user will be prompted for the number of
7320 clones to be produced, and for a time SHIFT, which may be a
7321 repeater as used in time stamps, for example `+3d'.
7323 When a valid repeater is given and the entry contains any time
7324 stamps, the clones will become a sequence in time, with time
7325 stamps in the subtree shifted for each clone produced. If SHIFT
7326 is nil or the empty string, time stamps will be left alone. The
7327 ID property of the original subtree is removed.
7329 If the original subtree did contain time stamps with a repeater,
7330 the following will happen:
7331 - the repeater will be removed in each clone
7332 - an additional clone will be produced, with the current, unshifted
7333 date(s) in the entry.
7334 - the original entry will be placed *after* all the clones, with
7335 repeater intact.
7336 - the start days in the repeater in the original entry will be shifted
7337 to past the last clone.
7338 I this way you can spell out a number of instances of a repeating task,
7339 and still retain the repeater to cover future instances of the task."
7340 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7341 (let (beg end template task idprop
7342 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7343 (if (not (and (integerp n) (> n 0)))
7344 (error "Invalid number of replications %s" n))
7345 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7346 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7347 shift)))
7348 (error "Invalid shift specification %s" shift))
7349 (when doshift
7350 (setq shift-n (string-to-number (match-string 1 shift))
7351 shift-what (cdr (assoc (match-string 2 shift)
7352 '(("d" . day) ("w" . week)
7353 ("m" . month) ("y" . year))))))
7354 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7355 (setq nmin 1 nmax n)
7356 (org-back-to-heading t)
7357 (setq beg (point))
7358 (setq idprop (org-entry-get nil "ID"))
7359 (org-end-of-subtree t t)
7360 (or (bolp) (insert "\n"))
7361 (setq end (point))
7362 (setq template (buffer-substring beg end))
7363 (when (and doshift
7364 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7365 (delete-region beg end)
7366 (setq end beg)
7367 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7368 (goto-char end)
7369 (loop for n from nmin to nmax do
7370 ;; prepare clone
7371 (with-temp-buffer
7372 (insert template)
7373 (org-mode)
7374 (goto-char (point-min))
7375 (and idprop (if org-clone-delete-id
7376 (org-entry-delete nil "ID")
7377 (org-id-get-create t)))
7378 (while (re-search-forward org-property-drawer-re nil t)
7379 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7380 (goto-char (point-min))
7381 (when doshift
7382 (while (re-search-forward org-ts-regexp-both nil t)
7383 (org-timestamp-change (* n shift-n) shift-what))
7384 (unless (= n n-no-remove)
7385 (goto-char (point-min))
7386 (while (re-search-forward org-ts-regexp nil t)
7387 (save-excursion
7388 (goto-char (match-beginning 0))
7389 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7390 (delete-region (match-beginning 1) (match-end 1)))))))
7391 (setq task (buffer-string)))
7392 (insert task))
7393 (goto-char beg)))
7395 ;;; Outline Sorting
7397 (defun org-sort (with-case)
7398 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7399 Optional argument WITH-CASE means sort case-sensitively.
7400 With a double prefix argument, also remove duplicate entries."
7401 (interactive "P")
7402 (if (org-at-table-p)
7403 (org-call-with-arg 'org-table-sort-lines with-case)
7404 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7406 (defun org-sort-remove-invisible (s)
7407 (remove-text-properties 0 (length s) org-rm-props s)
7408 (while (string-match org-bracket-link-regexp s)
7409 (setq s (replace-match (if (match-end 2)
7410 (match-string 3 s)
7411 (match-string 1 s)) t t s)))
7414 (defvar org-priority-regexp) ; defined later in the file
7416 (defvar org-after-sorting-entries-or-items-hook nil
7417 "Hook that is run after a bunch of entries or items have been sorted.
7418 When children are sorted, the cursor is in the parent line when this
7419 hook gets called. When a region or a plain list is sorted, the cursor
7420 will be in the first entry of the sorted region/list.")
7422 (defun org-sort-entries-or-items
7423 (&optional with-case sorting-type getkey-func compare-func property)
7424 "Sort entries on a certain level of an outline tree, or plain list items.
7425 If there is an active region, the entries in the region are sorted.
7426 Else, if the cursor is before the first entry, sort the top-level items.
7427 Else, the children of the entry at point are sorted.
7428 If the cursor is at the first item in a plain list, the list items will be
7429 sorted.
7431 Sorting can be alphabetically, numerically, by date/time as given by
7432 a time stamp, by a property or by priority.
7434 The command prompts for the sorting type unless it has been given to the
7435 function through the SORTING-TYPE argument, which needs to be a character,
7436 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7437 precise meaning of each character:
7439 n Numerically, by converting the beginning of the entry/item to a number.
7440 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7441 t By date/time, either the first active time stamp in the entry, or, if
7442 none exist, by the first inactive one.
7443 In items, only the first line will be checked.
7444 s By the scheduled date/time.
7445 d By deadline date/time.
7446 c By creation time, which is assumed to be the first inactive time stamp
7447 at the beginning of a line.
7448 p By priority according to the cookie.
7449 r By the value of a property.
7451 Capital letters will reverse the sort order.
7453 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7454 called with point at the beginning of the record. It must return either
7455 a string or a number that should serve as the sorting key for that record.
7457 Comparing entries ignores case by default. However, with an optional argument
7458 WITH-CASE, the sorting considers case as well."
7459 (interactive "P")
7460 (let ((case-func (if with-case 'identity 'downcase))
7461 start beg end stars re re2
7462 txt what tmp plain-list-p)
7463 ;; Find beginning and end of region to sort
7464 (cond
7465 ((org-region-active-p)
7466 ;; we will sort the region
7467 (setq end (region-end)
7468 what "region")
7469 (goto-char (region-beginning))
7470 (if (not (org-on-heading-p)) (outline-next-heading))
7471 (setq start (point)))
7472 ((org-at-item-p)
7473 ;; we will sort this plain list
7474 (org-beginning-of-item-list) (setq start (point))
7475 (org-end-of-item-list)
7476 (or (bolp) (insert "\n"))
7477 (setq end (point))
7478 (goto-char start)
7479 (setq plain-list-p t
7480 what "plain list"))
7481 ((or (org-on-heading-p)
7482 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7483 ;; we will sort the children of the current headline
7484 (org-back-to-heading)
7485 (setq start (point)
7486 end (progn (org-end-of-subtree t t)
7487 (or (bolp) (insert "\n"))
7488 (org-back-over-empty-lines)
7489 (point))
7490 what "children")
7491 (goto-char start)
7492 (show-subtree)
7493 (outline-next-heading))
7495 ;; we will sort the top-level entries in this file
7496 (goto-char (point-min))
7497 (or (org-on-heading-p) (outline-next-heading))
7498 (setq start (point))
7499 (goto-char (point-max))
7500 (beginning-of-line 1)
7501 (when (looking-at ".*?\\S-")
7502 ;; File ends in a non-white line
7503 (end-of-line 1)
7504 (insert "\n"))
7505 (setq end (point-max))
7506 (setq what "top-level")
7507 (goto-char start)
7508 (show-all)))
7510 (setq beg (point))
7511 (if (>= beg end) (error "Nothing to sort"))
7513 (unless plain-list-p
7514 (looking-at "\\(\\*+\\)")
7515 (setq stars (match-string 1)
7516 re (concat "^" (regexp-quote stars) " +")
7517 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7518 txt (buffer-substring beg end))
7519 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7520 (if (and (not (equal stars "*")) (string-match re2 txt))
7521 (error "Region to sort contains a level above the first entry")))
7523 (unless sorting-type
7524 (message
7525 (if plain-list-p
7526 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7527 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7528 [t]ime [s]cheduled [d]eadline [c]reated
7529 A/N/T/S/D/C/P/O/F means reversed:")
7530 what)
7531 (setq sorting-type (read-char-exclusive))
7533 (and (= (downcase sorting-type) ?f)
7534 (setq getkey-func
7535 (org-icompleting-read "Sort using function: "
7536 obarray 'fboundp t nil nil))
7537 (setq getkey-func (intern getkey-func)))
7539 (and (= (downcase sorting-type) ?r)
7540 (setq property
7541 (org-icompleting-read "Property: "
7542 (mapcar 'list (org-buffer-property-keys t))
7543 nil t))))
7545 (message "Sorting entries...")
7547 (save-restriction
7548 (narrow-to-region start end)
7550 (let ((dcst (downcase sorting-type))
7551 (case-fold-search nil)
7552 (now (current-time)))
7553 (sort-subr
7554 (/= dcst sorting-type)
7555 ;; This function moves to the beginning character of the "record" to
7556 ;; be sorted.
7557 (if plain-list-p
7558 (lambda nil
7559 (if (org-at-item-p) t (goto-char (point-max))))
7560 (lambda nil
7561 (if (re-search-forward re nil t)
7562 (goto-char (match-beginning 0))
7563 (goto-char (point-max)))))
7564 ;; This function moves to the last character of the "record" being
7565 ;; sorted.
7566 (if plain-list-p
7567 'org-end-of-item
7568 (lambda nil
7569 (save-match-data
7570 (condition-case nil
7571 (outline-forward-same-level 1)
7572 (error
7573 (goto-char (point-max)))))))
7575 ;; This function returns the value that gets sorted against.
7576 (if plain-list-p
7577 (lambda nil
7578 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7579 (cond
7580 ((= dcst ?n)
7581 (string-to-number (buffer-substring (match-end 0)
7582 (point-at-eol))))
7583 ((= dcst ?a)
7584 (buffer-substring (match-end 0) (point-at-eol)))
7585 ((= dcst ?t)
7586 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7587 (re-search-forward org-ts-regexp-both
7588 (point-at-eol) t))
7589 (org-time-string-to-seconds (match-string 0))
7590 (org-float-time now)))
7591 ((= dcst ?f)
7592 (if getkey-func
7593 (progn
7594 (setq tmp (funcall getkey-func))
7595 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7596 tmp)
7597 (error "Invalid key function `%s'" getkey-func)))
7598 (t (error "Invalid sorting type `%c'" sorting-type)))))
7599 (lambda nil
7600 (cond
7601 ((= dcst ?n)
7602 (if (looking-at org-complex-heading-regexp)
7603 (string-to-number (match-string 4))
7604 nil))
7605 ((= dcst ?a)
7606 (if (looking-at org-complex-heading-regexp)
7607 (funcall case-func (match-string 4))
7608 nil))
7609 ((= dcst ?t)
7610 (let ((end (save-excursion (outline-next-heading) (point))))
7611 (if (or (re-search-forward org-ts-regexp end t)
7612 (re-search-forward org-ts-regexp-both end t))
7613 (org-time-string-to-seconds (match-string 0))
7614 (org-float-time now))))
7615 ((= dcst ?c)
7616 (let ((end (save-excursion (outline-next-heading) (point))))
7617 (if (re-search-forward
7618 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7619 end t)
7620 (org-time-string-to-seconds (match-string 0))
7621 (org-float-time now))))
7622 ((= dcst ?s)
7623 (let ((end (save-excursion (outline-next-heading) (point))))
7624 (if (re-search-forward org-scheduled-time-regexp end t)
7625 (org-time-string-to-seconds (match-string 1))
7626 (org-float-time now))))
7627 ((= dcst ?d)
7628 (let ((end (save-excursion (outline-next-heading) (point))))
7629 (if (re-search-forward org-deadline-time-regexp end t)
7630 (org-time-string-to-seconds (match-string 1))
7631 (org-float-time now))))
7632 ((= dcst ?p)
7633 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7634 (string-to-char (match-string 2))
7635 org-default-priority))
7636 ((= dcst ?r)
7637 (or (org-entry-get nil property) ""))
7638 ((= dcst ?o)
7639 (if (looking-at org-complex-heading-regexp)
7640 (- 9999 (length (member (match-string 2)
7641 org-todo-keywords-1)))))
7642 ((= dcst ?f)
7643 (if getkey-func
7644 (progn
7645 (setq tmp (funcall getkey-func))
7646 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7647 tmp)
7648 (error "Invalid key function `%s'" getkey-func)))
7649 (t (error "Invalid sorting type `%c'" sorting-type)))))
7651 (cond
7652 ((= dcst ?a) 'string<)
7653 ((= dcst ?f) compare-func)
7654 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7655 (t nil)))))
7656 (run-hooks 'org-after-sorting-entries-or-items-hook)
7657 (message "Sorting entries...done")))
7659 (defun org-do-sort (table what &optional with-case sorting-type)
7660 "Sort TABLE of WHAT according to SORTING-TYPE.
7661 The user will be prompted for the SORTING-TYPE if the call to this
7662 function does not specify it. WHAT is only for the prompt, to indicate
7663 what is being sorted. The sorting key will be extracted from
7664 the car of the elements of the table.
7665 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7666 (unless sorting-type
7667 (message
7668 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7669 what)
7670 (setq sorting-type (read-char-exclusive)))
7671 (let ((dcst (downcase sorting-type))
7672 extractfun comparefun)
7673 ;; Define the appropriate functions
7674 (cond
7675 ((= dcst ?n)
7676 (setq extractfun 'string-to-number
7677 comparefun (if (= dcst sorting-type) '< '>)))
7678 ((= dcst ?a)
7679 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7680 (lambda(x) (downcase (org-sort-remove-invisible x))))
7681 comparefun (if (= dcst sorting-type)
7682 'string<
7683 (lambda (a b) (and (not (string< a b))
7684 (not (string= a b)))))))
7685 ((= dcst ?t)
7686 (setq extractfun
7687 (lambda (x)
7688 (if (or (string-match org-ts-regexp x)
7689 (string-match org-ts-regexp-both x))
7690 (org-float-time
7691 (org-time-string-to-time (match-string 0 x)))
7693 comparefun (if (= dcst sorting-type) '< '>)))
7694 (t (error "Invalid sorting type `%c'" sorting-type)))
7696 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7697 table)
7698 (lambda (a b) (funcall comparefun (car a) (car b))))))
7701 ;;; The orgstruct minor mode
7703 ;; Define a minor mode which can be used in other modes in order to
7704 ;; integrate the org-mode structure editing commands.
7706 ;; This is really a hack, because the org-mode structure commands use
7707 ;; keys which normally belong to the major mode. Here is how it
7708 ;; works: The minor mode defines all the keys necessary to operate the
7709 ;; structure commands, but wraps the commands into a function which
7710 ;; tests if the cursor is currently at a headline or a plain list
7711 ;; item. If that is the case, the structure command is used,
7712 ;; temporarily setting many Org-mode variables like regular
7713 ;; expressions for filling etc. However, when any of those keys is
7714 ;; used at a different location, function uses `key-binding' to look
7715 ;; up if the key has an associated command in another currently active
7716 ;; keymap (minor modes, major mode, global), and executes that
7717 ;; command. There might be problems if any of the keys is otherwise
7718 ;; used as a prefix key.
7720 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7721 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7722 ;; addresses this by checking explicitly for both bindings.
7724 (defvar orgstruct-mode-map (make-sparse-keymap)
7725 "Keymap for the minor `orgstruct-mode'.")
7727 (defvar org-local-vars nil
7728 "List of local variables, for use by `orgstruct-mode'")
7730 ;;;###autoload
7731 (define-minor-mode orgstruct-mode
7732 "Toggle the minor mode `orgstruct-mode'.
7733 This mode is for using Org-mode structure commands in other
7734 modes. The following keys behave as if Org-mode were active, if
7735 the cursor is on a headline, or on a plain list item (both as
7736 defined by Org-mode).
7738 M-up Move entry/item up
7739 M-down Move entry/item down
7740 M-left Promote
7741 M-right Demote
7742 M-S-up Move entry/item up
7743 M-S-down Move entry/item down
7744 M-S-left Promote subtree
7745 M-S-right Demote subtree
7746 M-q Fill paragraph and items like in Org-mode
7747 C-c ^ Sort entries
7748 C-c - Cycle list bullet
7749 TAB Cycle item visibility
7750 M-RET Insert new heading/item
7751 S-M-RET Insert new TODO heading / Checkbox item
7752 C-c C-c Set tags / toggle checkbox"
7753 nil " OrgStruct" nil
7754 (org-load-modules-maybe)
7755 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7757 ;;;###autoload
7758 (defun turn-on-orgstruct ()
7759 "Unconditionally turn on `orgstruct-mode'."
7760 (orgstruct-mode 1))
7762 (defun orgstruct++-mode (&optional arg)
7763 "Toggle `orgstruct-mode', the enhanced version of it.
7764 In addition to setting orgstruct-mode, this also exports all indentation
7765 and autofilling variables from org-mode into the buffer. It will also
7766 recognize item context in multiline items.
7767 Note that turning off orgstruct-mode will *not* remove the
7768 indentation/paragraph settings. This can only be done by refreshing the
7769 major mode, for example with \\[normal-mode]."
7770 (interactive "P")
7771 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7772 (if (< arg 1)
7773 (orgstruct-mode -1)
7774 (orgstruct-mode 1)
7775 (let (var val)
7776 (mapc
7777 (lambda (x)
7778 (when (string-match
7779 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7780 (symbol-name (car x)))
7781 (setq var (car x) val (nth 1 x))
7782 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7783 org-local-vars)
7784 (org-set-local 'orgstruct-is-++ t))))
7786 (defvar orgstruct-is-++ nil
7787 "Is orgstruct-mode in ++ version in the current-buffer?")
7788 (make-variable-buffer-local 'orgstruct-is-++)
7790 ;;;###autoload
7791 (defun turn-on-orgstruct++ ()
7792 "Unconditionally turn on `orgstruct++-mode'."
7793 (orgstruct++-mode 1))
7795 (defun orgstruct-error ()
7796 "Error when there is no default binding for a structure key."
7797 (interactive)
7798 (error "This key has no function outside structure elements"))
7800 (defun orgstruct-setup ()
7801 "Setup orgstruct keymaps."
7802 (let ((nfunc 0)
7803 (bindings
7804 (list
7805 '([(meta up)] org-metaup)
7806 '([(meta down)] org-metadown)
7807 '([(meta left)] org-metaleft)
7808 '([(meta right)] org-metaright)
7809 '([(meta shift up)] org-shiftmetaup)
7810 '([(meta shift down)] org-shiftmetadown)
7811 '([(meta shift left)] org-shiftmetaleft)
7812 '([(meta shift right)] org-shiftmetaright)
7813 '([?\e (up)] org-metaup)
7814 '([?\e (down)] org-metadown)
7815 '([?\e (left)] org-metaleft)
7816 '([?\e (right)] org-metaright)
7817 '([?\e (shift up)] org-shiftmetaup)
7818 '([?\e (shift down)] org-shiftmetadown)
7819 '([?\e (shift left)] org-shiftmetaleft)
7820 '([?\e (shift right)] org-shiftmetaright)
7821 '([(shift up)] org-shiftup)
7822 '([(shift down)] org-shiftdown)
7823 '([(shift left)] org-shiftleft)
7824 '([(shift right)] org-shiftright)
7825 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7826 '("\M-q" fill-paragraph)
7827 '("\C-c^" org-sort)
7828 '("\C-c-" org-cycle-list-bullet)))
7829 elt key fun cmd)
7830 (while (setq elt (pop bindings))
7831 (setq nfunc (1+ nfunc))
7832 (setq key (org-key (car elt))
7833 fun (nth 1 elt)
7834 cmd (orgstruct-make-binding fun nfunc key))
7835 (org-defkey orgstruct-mode-map key cmd))
7837 ;; Special treatment needed for TAB and RET
7838 (org-defkey orgstruct-mode-map [(tab)]
7839 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7840 (org-defkey orgstruct-mode-map "\C-i"
7841 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7843 (org-defkey orgstruct-mode-map "\M-\C-m"
7844 (orgstruct-make-binding 'org-insert-heading 105
7845 "\M-\C-m" [(meta return)]))
7846 (org-defkey orgstruct-mode-map [(meta return)]
7847 (orgstruct-make-binding 'org-insert-heading 106
7848 [(meta return)] "\M-\C-m"))
7850 (org-defkey orgstruct-mode-map [(shift meta return)]
7851 (orgstruct-make-binding 'org-insert-todo-heading 107
7852 [(meta return)] "\M-\C-m"))
7854 (org-defkey orgstruct-mode-map "\e\C-m"
7855 (orgstruct-make-binding 'org-insert-heading 108
7856 "\e\C-m" [?\e (return)]))
7857 (org-defkey orgstruct-mode-map [?\e (return)]
7858 (orgstruct-make-binding 'org-insert-heading 109
7859 [?\e (return)] "\e\C-m"))
7860 (org-defkey orgstruct-mode-map [?\e (shift return)]
7861 (orgstruct-make-binding 'org-insert-todo-heading 110
7862 [?\e (return)] "\e\C-m"))
7864 (unless org-local-vars
7865 (setq org-local-vars (org-get-local-variables)))
7869 (defun orgstruct-make-binding (fun n &rest keys)
7870 "Create a function for binding in the structure minor mode.
7871 FUN is the command to call inside a table. N is used to create a unique
7872 command name. KEYS are keys that should be checked in for a command
7873 to execute outside of tables."
7874 (eval
7875 (list 'defun
7876 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7877 '(arg)
7878 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7879 "Outside of structure, run the binding of `"
7880 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7881 "'.")
7882 '(interactive "p")
7883 (list 'if
7884 `(org-context-p 'headline 'item
7885 (and orgstruct-is-++
7886 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7887 'item-body))
7888 (list 'org-run-like-in-org-mode (list 'quote fun))
7889 (list 'let '(orgstruct-mode)
7890 (list 'call-interactively
7891 (append '(or)
7892 (mapcar (lambda (k)
7893 (list 'key-binding k))
7894 keys)
7895 '('orgstruct-error))))))))
7897 (defun org-context-p (&rest contexts)
7898 "Check if local context is any of CONTEXTS.
7899 Possible values in the list of contexts are `table', `headline', and `item'."
7900 (let ((pos (point)))
7901 (goto-char (point-at-bol))
7902 (prog1 (or (and (memq 'table contexts)
7903 (looking-at "[ \t]*|"))
7904 (and (memq 'headline contexts)
7905 ;;????????? (looking-at "\\*+"))
7906 (looking-at outline-regexp))
7907 (and (memq 'item contexts)
7908 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7909 (and (memq 'item-body contexts)
7910 (org-in-item-p)))
7911 (goto-char pos))))
7913 (defun org-get-local-variables ()
7914 "Return a list of all local variables in an org-mode buffer."
7915 (let (varlist)
7916 (with-current-buffer (get-buffer-create "*Org tmp*")
7917 (erase-buffer)
7918 (org-mode)
7919 (setq varlist (buffer-local-variables)))
7920 (kill-buffer "*Org tmp*")
7921 (delq nil
7922 (mapcar
7923 (lambda (x)
7924 (setq x
7925 (if (symbolp x)
7926 (list x)
7927 (list (car x) (list 'quote (cdr x)))))
7928 (if (string-match
7929 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7930 (symbol-name (car x)))
7931 x nil))
7932 varlist))))
7934 ;;;###autoload
7935 (defun org-run-like-in-org-mode (cmd)
7936 "Run a command, pretending that the current buffer is in Org-mode.
7937 This will temporarily bind local variables that are typically bound in
7938 Org-mode to the values they have in Org-mode, and then interactively
7939 call CMD."
7940 (org-load-modules-maybe)
7941 (unless org-local-vars
7942 (setq org-local-vars (org-get-local-variables)))
7943 (eval (list 'let org-local-vars
7944 (list 'call-interactively (list 'quote cmd)))))
7946 ;;;; Archiving
7948 (defun org-get-category (&optional pos)
7949 "Get the category applying to position POS."
7950 (get-text-property (or pos (point)) 'org-category))
7952 (defun org-refresh-category-properties ()
7953 "Refresh category text properties in the buffer."
7954 (let ((def-cat (cond
7955 ((null org-category)
7956 (if buffer-file-name
7957 (file-name-sans-extension
7958 (file-name-nondirectory buffer-file-name))
7959 "???"))
7960 ((symbolp org-category) (symbol-name org-category))
7961 (t org-category)))
7962 beg end cat pos optionp)
7963 (org-unmodified
7964 (save-excursion
7965 (save-restriction
7966 (widen)
7967 (goto-char (point-min))
7968 (put-text-property (point) (point-max) 'org-category def-cat)
7969 (while (re-search-forward
7970 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7971 (setq pos (match-end 0)
7972 optionp (equal (char-after (match-beginning 0)) ?#)
7973 cat (org-trim (match-string 2)))
7974 (if optionp
7975 (setq beg (point-at-bol) end (point-max))
7976 (org-back-to-heading t)
7977 (setq beg (point) end (org-end-of-subtree t t)))
7978 (put-text-property beg end 'org-category cat)
7979 (goto-char pos)))))))
7982 ;;;; Link Stuff
7984 ;;; Link abbreviations
7986 (defun org-link-expand-abbrev (link)
7987 "Apply replacements as defined in `org-link-abbrev-alist."
7988 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7989 (let* ((key (match-string 1 link))
7990 (as (or (assoc key org-link-abbrev-alist-local)
7991 (assoc key org-link-abbrev-alist)))
7992 (tag (and (match-end 2) (match-string 3 link)))
7993 rpl)
7994 (if (not as)
7995 link
7996 (setq rpl (cdr as))
7997 (cond
7998 ((symbolp rpl) (funcall rpl tag))
7999 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8000 ((string-match "%h" rpl)
8001 (replace-match (url-hexify-string (or tag "")) t t rpl))
8002 (t (concat rpl tag)))))
8003 link))
8005 ;;; Storing and inserting links
8007 (defvar org-insert-link-history nil
8008 "Minibuffer history for links inserted with `org-insert-link'.")
8010 (defvar org-stored-links nil
8011 "Contains the links stored with `org-store-link'.")
8013 (defvar org-store-link-plist nil
8014 "Plist with info about the most recently link created with `org-store-link'.")
8016 (defvar org-link-protocols nil
8017 "Link protocols added to Org-mode using `org-add-link-type'.")
8019 (defvar org-store-link-functions nil
8020 "List of functions that are called to create and store a link.
8021 Each function will be called in turn until one returns a non-nil
8022 value. Each function should check if it is responsible for creating
8023 this link (for example by looking at the major mode).
8024 If not, it must exit and return nil.
8025 If yes, it should return a non-nil value after a calling
8026 `org-store-link-props' with a list of properties and values.
8027 Special properties are:
8029 :type The link prefix. like \"http\". This must be given.
8030 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8031 This is obligatory as well.
8032 :description Optional default description for the second pair
8033 of brackets in an Org-mode link. The user can still change
8034 this when inserting this link into an Org-mode buffer.
8036 In addition to these, any additional properties can be specified
8037 and then used in remember templates.")
8039 (defun org-add-link-type (type &optional follow export)
8040 "Add TYPE to the list of `org-link-types'.
8041 Re-compute all regular expressions depending on `org-link-types'
8043 FOLLOW and EXPORT are two functions.
8045 FOLLOW should take the link path as the single argument and do whatever
8046 is necessary to follow the link, for example find a file or display
8047 a mail message.
8049 EXPORT should format the link path for export to one of the export formats.
8050 It should be a function accepting three arguments:
8052 path the path of the link, the text after the prefix (like \"http:\")
8053 desc the description of the link, if any, nil if there was no description
8054 format the export format, a symbol like `html' or `latex'.
8056 The function may use the FORMAT information to return different values
8057 depending on the format. The return value will be put literally into
8058 the exported file.
8059 Org-mode has a built-in default for exporting links. If you are happy with
8060 this default, there is no need to define an export function for the link
8061 type. For a simple example of an export function, see `org-bbdb.el'."
8062 (add-to-list 'org-link-types type t)
8063 (org-make-link-regexps)
8064 (if (assoc type org-link-protocols)
8065 (setcdr (assoc type org-link-protocols) (list follow export))
8066 (push (list type follow export) org-link-protocols)))
8068 (defvar org-agenda-buffer-name)
8070 ;;;###autoload
8071 (defun org-store-link (arg)
8072 "\\<org-mode-map>Store an org-link to the current location.
8073 This link is added to `org-stored-links' and can later be inserted
8074 into an org-buffer with \\[org-insert-link].
8076 For some link types, a prefix arg is interpreted:
8077 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8078 For file links, arg negates `org-context-in-file-links'."
8079 (interactive "P")
8080 (org-load-modules-maybe)
8081 (setq org-store-link-plist nil) ; reset
8082 (let ((outline-regexp (org-get-limited-outline-regexp))
8083 link cpltxt desc description search txt custom-id)
8084 (cond
8086 ((run-hook-with-args-until-success 'org-store-link-functions)
8087 (setq link (plist-get org-store-link-plist :link)
8088 desc (or (plist-get org-store-link-plist :description) link)))
8090 ((equal (buffer-name) "*Org Edit Src Example*")
8091 (let (label gc)
8092 (while (or (not label)
8093 (save-excursion
8094 (save-restriction
8095 (widen)
8096 (goto-char (point-min))
8097 (re-search-forward
8098 (regexp-quote (format org-coderef-label-format label))
8099 nil t))))
8100 (when label (message "Label exists already") (sit-for 2))
8101 (setq label (read-string "Code line label: " label)))
8102 (end-of-line 1)
8103 (setq link (format org-coderef-label-format label))
8104 (setq gc (- 79 (length link)))
8105 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8106 (insert link)
8107 (setq link (concat "(" label ")") desc nil)))
8109 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8110 ;; We are in the agenda, link to referenced location
8111 (let ((m (or (get-text-property (point) 'org-hd-marker)
8112 (get-text-property (point) 'org-marker))))
8113 (when m
8114 (org-with-point-at m
8115 (if (interactive-p)
8116 (call-interactively 'org-store-link)
8117 (org-store-link nil))))))
8119 ((eq major-mode 'calendar-mode)
8120 (let ((cd (calendar-cursor-to-date)))
8121 (setq link
8122 (format-time-string
8123 (car org-time-stamp-formats)
8124 (apply 'encode-time
8125 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8126 nil nil nil))))
8127 (org-store-link-props :type "calendar" :date cd)))
8129 ((eq major-mode 'w3-mode)
8130 (setq cpltxt (if (and (buffer-name)
8131 (not (string-match "Untitled" (buffer-name))))
8132 (buffer-name)
8133 (url-view-url t))
8134 link (org-make-link (url-view-url t)))
8135 (org-store-link-props :type "w3" :url (url-view-url t)))
8137 ((eq major-mode 'w3m-mode)
8138 (setq cpltxt (or w3m-current-title w3m-current-url)
8139 link (org-make-link w3m-current-url))
8140 (org-store-link-props :type "w3m" :url (url-view-url t)))
8142 ((setq search (run-hook-with-args-until-success
8143 'org-create-file-search-functions))
8144 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8145 "::" search))
8146 (setq cpltxt (or description link)))
8148 ((eq major-mode 'image-mode)
8149 (setq cpltxt (concat "file:"
8150 (abbreviate-file-name buffer-file-name))
8151 link (org-make-link cpltxt))
8152 (org-store-link-props :type "image" :file buffer-file-name))
8154 ((eq major-mode 'dired-mode)
8155 ;; link to the file in the current line
8156 (let ((file (dired-get-filename nil t)))
8157 (setq file (if file
8158 (abbreviate-file-name
8159 (expand-file-name (dired-get-filename nil t)))
8160 ;; otherwise, no file so use current directory.
8161 default-directory))
8162 (setq cpltxt (concat "file:" file)
8163 link (org-make-link cpltxt))))
8165 ((and buffer-file-name (org-mode-p))
8166 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8167 (cond
8168 ((org-in-regexp "<<\\(.*?\\)>>")
8169 (setq cpltxt
8170 (concat "file:"
8171 (abbreviate-file-name buffer-file-name)
8172 "::" (match-string 1))
8173 link (org-make-link cpltxt)))
8174 ((and (featurep 'org-id)
8175 (or (eq org-link-to-org-use-id t)
8176 (and (eq org-link-to-org-use-id 'create-if-interactive)
8177 (interactive-p))
8178 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8179 (interactive-p)
8180 (not custom-id))
8181 (and org-link-to-org-use-id
8182 (condition-case nil
8183 (org-entry-get nil "ID")
8184 (error nil)))))
8185 ;; We can make a link using the ID.
8186 (setq link (condition-case nil
8187 (prog1 (org-id-store-link)
8188 (setq desc (plist-get org-store-link-plist
8189 :description)))
8190 (error
8191 ;; probably before first headline, link to file only
8192 (concat "file:"
8193 (abbreviate-file-name buffer-file-name))))))
8195 ;; Just link to current headline
8196 (setq cpltxt (concat "file:"
8197 (abbreviate-file-name buffer-file-name)))
8198 ;; Add a context search string
8199 (when (org-xor org-context-in-file-links arg)
8200 (setq txt (cond
8201 ((org-on-heading-p) nil)
8202 ((org-region-active-p)
8203 (buffer-substring (region-beginning) (region-end)))
8204 (t nil)))
8205 (when (or (null txt) (string-match "\\S-" txt))
8206 (setq cpltxt
8207 (concat cpltxt "::"
8208 (condition-case nil
8209 (org-make-org-heading-search-string txt)
8210 (error "")))
8211 desc (or (nth 4 (ignore-errors
8212 (org-heading-components))) "NONE"))))
8213 (if (string-match "::\\'" cpltxt)
8214 (setq cpltxt (substring cpltxt 0 -2)))
8215 (setq link (org-make-link cpltxt)))))
8217 ((buffer-file-name (buffer-base-buffer))
8218 ;; Just link to this file here.
8219 (setq cpltxt (concat "file:"
8220 (abbreviate-file-name
8221 (buffer-file-name (buffer-base-buffer)))))
8222 ;; Add a context string
8223 (when (org-xor org-context-in-file-links arg)
8224 (setq txt (if (org-region-active-p)
8225 (buffer-substring (region-beginning) (region-end))
8226 (buffer-substring (point-at-bol) (point-at-eol))))
8227 ;; Only use search option if there is some text.
8228 (when (string-match "\\S-" txt)
8229 (setq cpltxt
8230 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8231 desc "NONE")))
8232 (setq link (org-make-link cpltxt)))
8234 ((interactive-p)
8235 (error "Cannot link to a buffer which is not visiting a file"))
8237 (t (setq link nil)))
8239 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8240 (setq link (or link cpltxt)
8241 desc (or desc cpltxt))
8242 (if (equal desc "NONE") (setq desc nil))
8244 (if (and (or (interactive-p) executing-kbd-macro) link)
8245 (progn
8246 (setq org-stored-links
8247 (cons (list link desc) org-stored-links))
8248 (message "Stored: %s" (or desc link))
8249 (when custom-id
8250 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8251 "::#" custom-id))
8252 (setq org-stored-links
8253 (cons (list link desc) org-stored-links))))
8254 (and link (org-make-link-string link desc)))))
8256 (defun org-store-link-props (&rest plist)
8257 "Store link properties, extract names and addresses."
8258 (let (x adr)
8259 (when (setq x (plist-get plist :from))
8260 (setq adr (mail-extract-address-components x))
8261 (setq plist (plist-put plist :fromname (car adr)))
8262 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8263 (when (setq x (plist-get plist :to))
8264 (setq adr (mail-extract-address-components x))
8265 (setq plist (plist-put plist :toname (car adr)))
8266 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8267 (let ((from (plist-get plist :from))
8268 (to (plist-get plist :to)))
8269 (when (and from to org-from-is-user-regexp)
8270 (setq plist
8271 (plist-put plist :fromto
8272 (if (string-match org-from-is-user-regexp from)
8273 (concat "to %t")
8274 (concat "from %f"))))))
8275 (setq org-store-link-plist plist))
8277 (defun org-add-link-props (&rest plist)
8278 "Add these properties to the link property list."
8279 (let (key value)
8280 (while plist
8281 (setq key (pop plist) value (pop plist))
8282 (setq org-store-link-plist
8283 (plist-put org-store-link-plist key value)))))
8285 (defun org-email-link-description (&optional fmt)
8286 "Return the description part of an email link.
8287 This takes information from `org-store-link-plist' and formats it
8288 according to FMT (default from `org-email-link-description-format')."
8289 (setq fmt (or fmt org-email-link-description-format))
8290 (let* ((p org-store-link-plist)
8291 (to (plist-get p :toaddress))
8292 (from (plist-get p :fromaddress))
8293 (table
8294 (list
8295 (cons "%c" (plist-get p :fromto))
8296 (cons "%F" (plist-get p :from))
8297 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8298 (cons "%T" (plist-get p :to))
8299 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8300 (cons "%s" (plist-get p :subject))
8301 (cons "%m" (plist-get p :message-id)))))
8302 (when (string-match "%c" fmt)
8303 ;; Check if the user wrote this message
8304 (if (and org-from-is-user-regexp from to
8305 (save-match-data (string-match org-from-is-user-regexp from)))
8306 (setq fmt (replace-match "to %t" t t fmt))
8307 (setq fmt (replace-match "from %f" t t fmt))))
8308 (org-replace-escapes fmt table)))
8310 (defun org-make-org-heading-search-string (&optional string heading)
8311 "Make search string for STRING or current headline."
8312 (interactive)
8313 (let ((s (or string (org-get-heading))))
8314 (unless (and string (not heading))
8315 ;; We are using a headline, clean up garbage in there.
8316 (if (string-match org-todo-regexp s)
8317 (setq s (replace-match "" t t s)))
8318 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8319 (setq s (replace-match "" t t s)))
8320 (setq s (org-trim s))
8321 (if (string-match (concat "^\\(" org-quote-string "\\|"
8322 org-comment-string "\\)") s)
8323 (setq s (replace-match "" t t s)))
8324 (while (string-match org-ts-regexp s)
8325 (setq s (replace-match "" t t s))))
8326 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8327 (setq s (replace-match " " t t s)))
8328 (or string (setq s (concat "*" s))) ; Add * for headlines
8329 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8331 (defun org-make-link (&rest strings)
8332 "Concatenate STRINGS."
8333 (apply 'concat strings))
8335 (defun org-make-link-string (link &optional description)
8336 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8337 (unless (string-match "\\S-" link)
8338 (error "Empty link"))
8339 (when (and description
8340 (stringp description)
8341 (not (string-match "\\S-" description)))
8342 (setq description nil))
8343 (when (stringp description)
8344 ;; Remove brackets from the description, they are fatal.
8345 (while (string-match "\\[" description)
8346 (setq description (replace-match "{" t t description)))
8347 (while (string-match "\\]" description)
8348 (setq description (replace-match "}" t t description))))
8349 (when (equal (org-link-escape link) description)
8350 ;; No description needed, it is identical
8351 (setq description nil))
8352 (when (and (not description)
8353 (not (equal link (org-link-escape link))))
8354 (setq description (org-extract-attributes link)))
8355 (concat "[[" (org-link-escape link) "]"
8356 (if description (concat "[" description "]") "")
8357 "]"))
8359 (defconst org-link-escape-chars
8360 '((?\ . "%20")
8361 (?\[ . "%5B")
8362 (?\] . "%5D")
8363 (?\340 . "%E0") ; `a
8364 (?\342 . "%E2") ; ^a
8365 (?\347 . "%E7") ; ,c
8366 (?\350 . "%E8") ; `e
8367 (?\351 . "%E9") ; 'e
8368 (?\352 . "%EA") ; ^e
8369 (?\356 . "%EE") ; ^i
8370 (?\364 . "%F4") ; ^o
8371 (?\371 . "%F9") ; `u
8372 (?\373 . "%FB") ; ^u
8373 (?\; . "%3B")
8374 ;; (?? . "%3F")
8375 (?= . "%3D")
8376 (?+ . "%2B")
8378 "Association list of escapes for some characters problematic in links.
8379 This is the list that is used for internal purposes.")
8381 (defvar org-url-encoding-use-url-hexify nil)
8383 (defconst org-link-escape-chars-browser
8384 '((?\ . "%20")) ; 32 for the SPC char
8385 "Association list of escapes for some characters problematic in links.
8386 This is the list that is used before handing over to the browser.")
8388 (defun org-link-escape (text &optional table)
8389 "Escape characters in TEXT that are problematic for links."
8390 (if (and org-url-encoding-use-url-hexify (not table))
8391 (url-hexify-string text)
8392 (setq table (or table org-link-escape-chars))
8393 (when text
8394 (let ((re (mapconcat (lambda (x) (regexp-quote
8395 (char-to-string (car x))))
8396 table "\\|")))
8397 (while (string-match re text)
8398 (setq text
8399 (replace-match
8400 (cdr (assoc (string-to-char (match-string 0 text))
8401 table))
8402 t t text)))
8403 text))))
8405 (defun org-link-unescape (text &optional table)
8406 "Reverse the action of `org-link-escape'."
8407 (if (and org-url-encoding-use-url-hexify (not table))
8408 (url-unhex-string text)
8409 (setq table (or table org-link-escape-chars))
8410 (when text
8411 (let ((case-fold-search t)
8412 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8413 table "\\|")))
8414 (while (string-match re text)
8415 (setq text
8416 (replace-match
8417 (char-to-string (car (rassoc (upcase (match-string 0 text))
8418 table)))
8419 t t text)))
8420 text))))
8422 (defun org-xor (a b)
8423 "Exclusive or."
8424 (if a (not b) b))
8426 (defun org-fixup-message-id-for-http (s)
8427 "Replace special characters in a message id, so it can be used in an http query."
8428 (when (string-match "%" s)
8429 (setq s (mapconcat (lambda (c)
8430 (if (eq c ?%)
8431 "%25"
8432 (char-to-string c)))
8433 s "")))
8434 (while (string-match "<" s)
8435 (setq s (replace-match "%3C" t t s)))
8436 (while (string-match ">" s)
8437 (setq s (replace-match "%3E" t t s)))
8438 (while (string-match "@" s)
8439 (setq s (replace-match "%40" t t s)))
8442 ;;;###autoload
8443 (defun org-insert-link-global ()
8444 "Insert a link like Org-mode does.
8445 This command can be called in any mode to insert a link in Org-mode syntax."
8446 (interactive)
8447 (org-load-modules-maybe)
8448 (org-run-like-in-org-mode 'org-insert-link))
8450 (defun org-insert-link (&optional complete-file link-location)
8451 "Insert a link. At the prompt, enter the link.
8453 Completion can be used to insert any of the link protocol prefixes like
8454 http or ftp in use.
8456 The history can be used to select a link previously stored with
8457 `org-store-link'. When the empty string is entered (i.e. if you just
8458 press RET at the prompt), the link defaults to the most recently
8459 stored link. As SPC triggers completion in the minibuffer, you need to
8460 use M-SPC or C-q SPC to force the insertion of a space character.
8462 You will also be prompted for a description, and if one is given, it will
8463 be displayed in the buffer instead of the link.
8465 If there is already a link at point, this command will allow you to edit link
8466 and description parts.
8468 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8469 be selected using completion. The path to the file will be relative to the
8470 current directory if the file is in the current directory or a subdirectory.
8471 Otherwise, the link will be the absolute path as completed in the minibuffer
8472 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8473 option `org-link-file-path-type'.
8475 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8476 the current directory or below.
8478 With three \\[universal-argument] prefixes, negate the meaning of
8479 `org-keep-stored-link-after-insertion'.
8481 If `org-make-link-description-function' is non-nil, this function will be
8482 called with the link target, and the result will be the default
8483 link description.
8485 If the LINK-LOCATION parameter is non-nil, this value will be
8486 used as the link location instead of reading one interactively."
8487 (interactive "P")
8488 (let* ((wcf (current-window-configuration))
8489 (region (if (org-region-active-p)
8490 (buffer-substring (region-beginning) (region-end))))
8491 (remove (and region (list (region-beginning) (region-end))))
8492 (desc region)
8493 tmphist ; byte-compile incorrectly complains about this
8494 (link link-location)
8495 entry file all-prefixes)
8496 (cond
8497 (link-location) ; specified by arg, just use it.
8498 ((org-in-regexp org-bracket-link-regexp 1)
8499 ;; We do have a link at point, and we are going to edit it.
8500 (setq remove (list (match-beginning 0) (match-end 0)))
8501 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8502 (setq link (read-string "Link: "
8503 (org-link-unescape
8504 (org-match-string-no-properties 1)))))
8505 ((or (org-in-regexp org-angle-link-re)
8506 (org-in-regexp org-plain-link-re))
8507 ;; Convert to bracket link
8508 (setq remove (list (match-beginning 0) (match-end 0))
8509 link (read-string "Link: "
8510 (org-remove-angle-brackets (match-string 0)))))
8511 ((member complete-file '((4) (16)))
8512 ;; Completing read for file names.
8513 (setq link (org-file-complete-link complete-file)))
8515 ;; Read link, with completion for stored links.
8516 (with-output-to-temp-buffer "*Org Links*"
8517 (princ "Insert a link.
8518 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8519 (when org-stored-links
8520 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8521 (princ (mapconcat
8522 (lambda (x)
8523 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8524 (reverse org-stored-links) "\n"))))
8525 (let ((cw (selected-window)))
8526 (select-window (get-buffer-window "*Org Links*" 'visible))
8527 (setq truncate-lines t)
8528 (unless (pos-visible-in-window-p (point-max))
8529 (org-fit-window-to-buffer))
8530 (and (window-live-p cw) (select-window cw)))
8531 ;; Fake a link history, containing the stored links.
8532 (setq tmphist (append (mapcar 'car org-stored-links)
8533 org-insert-link-history))
8534 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8535 (mapcar 'car org-link-abbrev-alist)
8536 org-link-types))
8537 (unwind-protect
8538 (progn
8539 (setq link
8540 (let ((org-completion-use-ido nil)
8541 (org-completion-use-iswitchb nil))
8542 (org-completing-read
8543 "Link: "
8544 (append
8545 (mapcar (lambda (x) (list (concat x ":")))
8546 all-prefixes)
8547 (mapcar 'car org-stored-links))
8548 nil nil nil
8549 'tmphist
8550 (car (car org-stored-links)))))
8551 (if (not (string-match "\\S-" link))
8552 (error "No link selected"))
8553 (if (or (member link all-prefixes)
8554 (and (equal ":" (substring link -1))
8555 (member (substring link 0 -1) all-prefixes)
8556 (setq link (substring link 0 -1))))
8557 (setq link (org-link-try-special-completion link))))
8558 (set-window-configuration wcf)
8559 (kill-buffer "*Org Links*"))
8560 (setq entry (assoc link org-stored-links))
8561 (or entry (push link org-insert-link-history))
8562 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8563 (not org-keep-stored-link-after-insertion))
8564 (setq org-stored-links (delq (assoc link org-stored-links)
8565 org-stored-links)))
8566 (setq desc (or desc (nth 1 entry)))))
8568 (if (string-match org-plain-link-re link)
8569 ;; URL-like link, normalize the use of angular brackets.
8570 (setq link (org-make-link (org-remove-angle-brackets link))))
8572 ;; Check if we are linking to the current file with a search option
8573 ;; If yes, simplify the link by using only the search option.
8574 (when (and buffer-file-name
8575 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8576 (let* ((path (match-string 1 link))
8577 (case-fold-search nil)
8578 (search (match-string 2 link)))
8579 (save-match-data
8580 (if (equal (file-truename buffer-file-name) (file-truename path))
8581 ;; We are linking to this same file, with a search option
8582 (setq link search)))))
8584 ;; Check if we can/should use a relative path. If yes, simplify the link
8585 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8586 (let* ((type (match-string 1 link))
8587 (path (match-string 2 link))
8588 (origpath path)
8589 (case-fold-search nil))
8590 (cond
8591 ((or (eq org-link-file-path-type 'absolute)
8592 (equal complete-file '(16)))
8593 (setq path (abbreviate-file-name (expand-file-name path))))
8594 ((eq org-link-file-path-type 'noabbrev)
8595 (setq path (expand-file-name path)))
8596 ((eq org-link-file-path-type 'relative)
8597 (setq path (file-relative-name path)))
8599 (save-match-data
8600 (if (string-match (concat "^" (regexp-quote
8601 (file-name-as-directory
8602 (expand-file-name "."))))
8603 (expand-file-name path))
8604 ;; We are linking a file with relative path name.
8605 (setq path (substring (expand-file-name path)
8606 (match-end 0)))
8607 (setq path (abbreviate-file-name (expand-file-name path)))))))
8608 (setq link (concat type path))
8609 (if (equal desc origpath)
8610 (setq desc path))))
8612 (if org-make-link-description-function
8613 (setq desc (funcall org-make-link-description-function link desc)))
8615 (setq desc (read-string "Description: " desc))
8616 (unless (string-match "\\S-" desc) (setq desc nil))
8617 (if remove (apply 'delete-region remove))
8618 (insert (org-make-link-string link desc))))
8620 (defun org-link-try-special-completion (type)
8621 "If there is completion support for link type TYPE, offer it."
8622 (let ((fun (intern (concat "org-" type "-complete-link"))))
8623 (if (functionp fun)
8624 (funcall fun)
8625 (read-string "Link (no completion support): " (concat type ":")))))
8627 (defun org-file-complete-link (&optional arg)
8628 "Create a file link using completion."
8629 (let (file link)
8630 (setq file (read-file-name "File: "))
8631 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8632 (pwd1 (file-name-as-directory (abbreviate-file-name
8633 (expand-file-name ".")))))
8634 (cond
8635 ((equal arg '(16))
8636 (setq link (org-make-link
8637 "file:"
8638 (abbreviate-file-name (expand-file-name file)))))
8639 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8640 (setq link (org-make-link "file:" (match-string 1 file))))
8641 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8642 (expand-file-name file))
8643 (setq link (org-make-link
8644 "file:" (match-string 1 (expand-file-name file)))))
8645 (t (setq link (org-make-link "file:" file)))))
8646 link))
8648 (defun org-completing-read (&rest args)
8649 "Completing-read with SPACE being a normal character."
8650 (let ((minibuffer-local-completion-map
8651 (copy-keymap minibuffer-local-completion-map)))
8652 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8653 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8654 (apply 'org-icompleting-read args)))
8656 (defun org-completing-read-no-i (&rest args)
8657 (let (org-completion-use-ido org-completion-use-iswitchb)
8658 (apply 'org-completing-read args)))
8660 (defun org-iswitchb-completing-read (prompt choices &rest args)
8661 "Use iswitch as a completing-read replacement to choose from choices.
8662 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8663 from."
8664 (let* ((iswitchb-use-virtual-buffers nil)
8665 (iswitchb-make-buflist-hook
8666 (lambda ()
8667 (setq iswitchb-temp-buflist choices))))
8668 (iswitchb-read-buffer prompt)))
8670 (defun org-icompleting-read (&rest args)
8671 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8672 (org-without-partial-completion
8673 (if (and org-completion-use-ido
8674 (fboundp 'ido-completing-read)
8675 (boundp 'ido-mode) ido-mode
8676 (listp (second args)))
8677 (let ((ido-enter-matching-directory nil))
8678 (apply 'ido-completing-read (concat (car args))
8679 (if (consp (car (nth 1 args)))
8680 (mapcar (lambda (x) (car x)) (nth 1 args))
8681 (nth 1 args))
8682 (cddr args)))
8683 (if (and org-completion-use-iswitchb
8684 (boundp 'iswitchb-mode) iswitchb-mode
8685 (listp (second args)))
8686 (apply 'org-iswitchb-completing-read (concat (car args))
8687 (if (consp (car (nth 1 args)))
8688 (mapcar (lambda (x) (car x)) (nth 1 args))
8689 (nth 1 args))
8690 (cddr args))
8691 (apply 'completing-read args)))))
8693 (defun org-extract-attributes (s)
8694 "Extract the attributes cookie from a string and set as text property."
8695 (let (a attr (start 0) key value)
8696 (save-match-data
8697 (when (string-match "{{\\([^}]+\\)}}$" s)
8698 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8699 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8700 (setq key (match-string 1 a) value (match-string 2 a)
8701 start (match-end 0)
8702 attr (plist-put attr (intern key) value))))
8703 (org-add-props s nil 'org-attr attr))
8706 (defun org-extract-attributes-from-string (tag)
8707 (let (key value attr)
8708 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8709 (setq key (match-string 1 tag) value (match-string 2 tag)
8710 tag (replace-match "" t t tag)
8711 attr (plist-put attr (intern key) value)))
8712 (cons tag attr)))
8714 (defun org-attributes-to-string (plist)
8715 "Format a property list into an HTML attribute list."
8716 (let ((s "") key value)
8717 (while plist
8718 (setq key (pop plist) value (pop plist))
8719 (and value
8720 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8723 ;;; Opening/following a link
8725 (defvar org-link-search-failed nil)
8727 (defvar org-open-link-functions nil
8728 "Hook for functions finding a plain text link.
8729 These functions must take a single argument, the link content.
8730 They will be called for links that look like [[link text][description]]
8731 when LINK TEXT does not have a protocol like \"http:\" and does not look
8732 like a filename (e.g. \"./blue.png\").
8734 These functions will be called *before* Org attempts to resolve the
8735 link by doing text searches in the current buffer - so if you want a
8736 link \"[[target]]\" to still find \"<<target>>\", your function should
8737 handle this as a special case.
8739 When the function does handle the link, it must return a non-nil value.
8740 If it decides that it is not responsible for this link, it must return
8741 nil to indicate that that Org-mode can continue with other options
8742 like exact and fuzzy text search.")
8744 (defun org-next-link ()
8745 "Move forward to the next link.
8746 If the link is in hidden text, expose it."
8747 (interactive)
8748 (when (and org-link-search-failed (eq this-command last-command))
8749 (goto-char (point-min))
8750 (message "Link search wrapped back to beginning of buffer"))
8751 (setq org-link-search-failed nil)
8752 (let* ((pos (point))
8753 (ct (org-context))
8754 (a (assoc :link ct)))
8755 (if a (goto-char (nth 2 a)))
8756 (if (re-search-forward org-any-link-re nil t)
8757 (progn
8758 (goto-char (match-beginning 0))
8759 (if (org-invisible-p) (org-show-context)))
8760 (goto-char pos)
8761 (setq org-link-search-failed t)
8762 (error "No further link found"))))
8764 (defun org-previous-link ()
8765 "Move backward to the previous link.
8766 If the link is in hidden text, expose it."
8767 (interactive)
8768 (when (and org-link-search-failed (eq this-command last-command))
8769 (goto-char (point-max))
8770 (message "Link search wrapped back to end of buffer"))
8771 (setq org-link-search-failed nil)
8772 (let* ((pos (point))
8773 (ct (org-context))
8774 (a (assoc :link ct)))
8775 (if a (goto-char (nth 1 a)))
8776 (if (re-search-backward org-any-link-re nil t)
8777 (progn
8778 (goto-char (match-beginning 0))
8779 (if (org-invisible-p) (org-show-context)))
8780 (goto-char pos)
8781 (setq org-link-search-failed t)
8782 (error "No further link found"))))
8784 (defun org-translate-link (s)
8785 "Translate a link string if a translation function has been defined."
8786 (if (and org-link-translation-function
8787 (fboundp org-link-translation-function)
8788 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8789 (progn
8790 (setq s (funcall org-link-translation-function
8791 (match-string 1) (match-string 2)))
8792 (concat (car s) ":" (cdr s)))
8795 (defun org-translate-link-from-planner (type path)
8796 "Translate a link from Emacs Planner syntax so that Org can follow it.
8797 This is still an experimental function, your mileage may vary."
8798 (cond
8799 ((member type '("http" "https" "news" "ftp"))
8800 ;; standard Internet links are the same.
8801 nil)
8802 ((and (equal type "irc") (string-match "^//" path))
8803 ;; Planner has two / at the beginning of an irc link, we have 1.
8804 ;; We should have zero, actually....
8805 (setq path (substring path 1)))
8806 ((and (equal type "lisp") (string-match "^/" path))
8807 ;; Planner has a slash, we do not.
8808 (setq type "elisp" path (substring path 1)))
8809 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8810 ;; A typical message link. Planner has the id after the final slash,
8811 ;; we separate it with a hash mark
8812 (setq path (concat (match-string 1 path) "#"
8813 (org-remove-angle-brackets (match-string 2 path)))))
8815 (cons type path))
8817 (defun org-find-file-at-mouse (ev)
8818 "Open file link or URL at mouse."
8819 (interactive "e")
8820 (mouse-set-point ev)
8821 (org-open-at-point 'in-emacs))
8823 (defun org-open-at-mouse (ev)
8824 "Open file link or URL at mouse."
8825 (interactive "e")
8826 (mouse-set-point ev)
8827 (if (eq major-mode 'org-agenda-mode)
8828 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8829 (org-open-at-point))
8831 (defvar org-window-config-before-follow-link nil
8832 "The window configuration before following a link.
8833 This is saved in case the need arises to restore it.")
8835 (defvar org-open-link-marker (make-marker)
8836 "Marker pointing to the location where `org-open-at-point; was called.")
8838 ;;;###autoload
8839 (defun org-open-at-point-global ()
8840 "Follow a link like Org-mode does.
8841 This command can be called in any mode to follow a link that has
8842 Org-mode syntax."
8843 (interactive)
8844 (org-run-like-in-org-mode 'org-open-at-point))
8846 ;;;###autoload
8847 (defun org-open-link-from-string (s &optional arg reference-buffer)
8848 "Open a link in the string S, as if it was in Org-mode."
8849 (interactive "sLink: \nP")
8850 (let ((reference-buffer (or reference-buffer (current-buffer))))
8851 (with-temp-buffer
8852 (let ((org-inhibit-startup t))
8853 (org-mode)
8854 (insert s)
8855 (goto-char (point-min))
8856 (when reference-buffer
8857 (setq org-link-abbrev-alist-local
8858 (with-current-buffer reference-buffer
8859 org-link-abbrev-alist-local)))
8860 (org-open-at-point arg reference-buffer)))))
8862 (defun org-open-at-point (&optional in-emacs reference-buffer)
8863 "Open link at or after point.
8864 If there is no link at point, this function will search forward up to
8865 the end of the current line.
8866 Normally, files will be opened by an appropriate application. If the
8867 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8868 With a double prefix argument, try to open outside of Emacs, in the
8869 application the system uses for this file type."
8870 (interactive "P")
8871 (org-load-modules-maybe)
8872 (move-marker org-open-link-marker (point))
8873 (setq org-window-config-before-follow-link (current-window-configuration))
8874 (org-remove-occur-highlights nil nil t)
8875 (cond
8876 ((and (org-on-heading-p)
8877 (not (org-in-regexp
8878 (concat org-plain-link-re "\\|"
8879 org-bracket-link-regexp "\\|"
8880 org-angle-link-re "\\|"
8881 "[ \t]:[^ \t\n]+:[ \t]*$")))
8882 (not (get-text-property (point) 'org-linked-text)))
8883 (or (org-offer-links-in-entry in-emacs)
8884 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8885 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8886 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8887 (org-footnote-action))
8889 (let (type path link line search (pos (point)))
8890 (catch 'match
8891 (save-excursion
8892 (skip-chars-forward "^]\n\r")
8893 (when (org-in-regexp org-bracket-link-regexp 1)
8894 (setq link (org-extract-attributes
8895 (org-link-unescape (org-match-string-no-properties 1))))
8896 (while (string-match " *\n *" link)
8897 (setq link (replace-match " " t t link)))
8898 (setq link (org-link-expand-abbrev link))
8899 (cond
8900 ((or (file-name-absolute-p link)
8901 (string-match "^\\.\\.?/" link))
8902 (setq type "file" path link))
8903 ((string-match org-link-re-with-space3 link)
8904 (setq type (match-string 1 link) path (match-string 2 link)))
8905 (t (setq type "thisfile" path link)))
8906 (throw 'match t)))
8908 (when (get-text-property (point) 'org-linked-text)
8909 (setq type "thisfile"
8910 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8911 (1+ (point)) (point))
8912 path (buffer-substring
8913 (previous-single-property-change pos 'org-linked-text)
8914 (next-single-property-change pos 'org-linked-text)))
8915 (throw 'match t))
8917 (save-excursion
8918 (when (or (org-in-regexp org-angle-link-re)
8919 (org-in-regexp org-plain-link-re))
8920 (setq type (match-string 1) path (match-string 2))
8921 (throw 'match t)))
8922 (save-excursion
8923 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8924 (setq type "tags"
8925 path (match-string 1))
8926 (while (string-match ":" path)
8927 (setq path (replace-match "+" t t path)))
8928 (throw 'match t)))
8929 (when (org-in-regexp "<\\([^><\n]+\\)>")
8930 (setq type "tree-match"
8931 path (match-string 1))
8932 (throw 'match t)))
8933 (unless path
8934 (error "No link found"))
8936 ;; switch back to reference buffer
8937 ;; needed when if called in a temporary buffer through
8938 ;; org-open-link-from-string
8939 (with-current-buffer (or reference-buffer (current-buffer))
8941 ;; Remove any trailing spaces in path
8942 (if (string-match " +\\'" path)
8943 (setq path (replace-match "" t t path)))
8944 (if (and org-link-translation-function
8945 (fboundp org-link-translation-function))
8946 ;; Check if we need to translate the link
8947 (let ((tmp (funcall org-link-translation-function type path)))
8948 (setq type (car tmp) path (cdr tmp))))
8950 (cond
8952 ((assoc type org-link-protocols)
8953 (funcall (nth 1 (assoc type org-link-protocols)) path))
8955 ((equal type "mailto")
8956 (let ((cmd (car org-link-mailto-program))
8957 (args (cdr org-link-mailto-program)) args1
8958 (address path) (subject "") a)
8959 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8960 (setq address (match-string 1 path)
8961 subject (org-link-escape (match-string 2 path))))
8962 (while args
8963 (cond
8964 ((not (stringp (car args))) (push (pop args) args1))
8965 (t (setq a (pop args))
8966 (if (string-match "%a" a)
8967 (setq a (replace-match address t t a)))
8968 (if (string-match "%s" a)
8969 (setq a (replace-match subject t t a)))
8970 (push a args1))))
8971 (apply cmd (nreverse args1))))
8973 ((member type '("http" "https" "ftp" "news"))
8974 (browse-url (concat type ":" (org-link-escape
8975 path org-link-escape-chars-browser))))
8977 ((string= type "doi")
8978 (browse-url (concat "http://dx.doi.org/"
8979 (org-link-escape
8980 path org-link-escape-chars-browser))))
8982 ((member type '("message"))
8983 (browse-url (concat type ":" path)))
8985 ((string= type "tags")
8986 (org-tags-view in-emacs path))
8988 ((string= type "tree-match")
8989 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8991 ((string= type "file")
8992 (if (string-match "::\\([0-9]+\\)\\'" path)
8993 (setq line (string-to-number (match-string 1 path))
8994 path (substring path 0 (match-beginning 0)))
8995 (if (string-match "::\\(.+\\)\\'" path)
8996 (setq search (match-string 1 path)
8997 path (substring path 0 (match-beginning 0)))))
8998 (if (string-match "[*?{]" (file-name-nondirectory path))
8999 (dired path)
9000 (org-open-file path in-emacs line search)))
9002 ((string= type "news")
9003 (require 'org-gnus)
9004 (org-gnus-follow-link path))
9006 ((string= type "shell")
9007 (let ((cmd path))
9008 (if (or (not org-confirm-shell-link-function)
9009 (funcall org-confirm-shell-link-function
9010 (format "Execute \"%s\" in shell? "
9011 (org-add-props cmd nil
9012 'face 'org-warning))))
9013 (progn
9014 (message "Executing %s" cmd)
9015 (shell-command cmd))
9016 (error "Abort"))))
9018 ((string= type "elisp")
9019 (let ((cmd path))
9020 (if (or (not org-confirm-elisp-link-function)
9021 (funcall org-confirm-elisp-link-function
9022 (format "Execute \"%s\" as elisp? "
9023 (org-add-props cmd nil
9024 'face 'org-warning))))
9025 (message "%s => %s" cmd
9026 (if (equal (string-to-char cmd) ?\()
9027 (eval (read cmd))
9028 (call-interactively (read cmd))))
9029 (error "Abort"))))
9031 ((and (string= type "thisfile")
9032 (run-hook-with-args-until-success
9033 'org-open-link-functions path)))
9035 ((string= type "thisfile")
9036 (if in-emacs
9037 (switch-to-buffer-other-window
9038 (org-get-buffer-for-internal-link (current-buffer)))
9039 (org-mark-ring-push))
9040 (let ((cmd `(org-link-search
9041 ,path
9042 ,(cond ((equal in-emacs '(4)) 'occur)
9043 ((equal in-emacs '(16)) 'org-occur)
9044 (t nil))
9045 ,pos)))
9046 (condition-case nil (eval cmd)
9047 (error (progn (widen) (eval cmd))))))
9050 (browse-url-at-point)))))))
9051 (move-marker org-open-link-marker nil)
9052 (run-hook-with-args 'org-follow-link-hook))
9054 (defun org-offer-links-in-entry (&optional nth zero)
9055 "Offer links in the current entry and follow the selected link.
9056 If there is only one link, follow it immediately as well.
9057 If NTH is an integer, immediately pick the NTH link found.
9058 If ZERO is a string, check also this string for a link, and if
9059 there is one, offer it as link number zero."
9060 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9061 "\\(" org-angle-link-re "\\)\\|"
9062 "\\(" org-plain-link-re "\\)"))
9063 (cnt ?0)
9064 (in-emacs (if (integerp nth) nil nth))
9065 have-zero end links link c)
9066 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9067 (push (match-string 0 zero) links)
9068 (setq cnt (1- cnt) have-zero t))
9069 (save-excursion
9070 (org-back-to-heading t)
9071 (setq end (save-excursion (outline-next-heading) (point)))
9072 (while (re-search-forward re end t)
9073 (push (match-string 0) links))
9074 (setq links (org-uniquify (reverse links))))
9076 (cond
9077 ((null links)
9078 (message "No links"))
9079 ((equal (length links) 1)
9080 (setq link (list (car links))))
9081 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9082 (setq link (nth (if have-zero nth (1- nth)) links)))
9083 (t ; we have to select a link
9084 (save-excursion
9085 (save-window-excursion
9086 (delete-other-windows)
9087 (with-output-to-temp-buffer "*Select Link*"
9088 (mapc (lambda (l)
9089 (if (not (string-match org-bracket-link-regexp l))
9090 (princ (format "[%c] %s\n" (incf cnt)
9091 (org-remove-angle-brackets l)))
9092 (if (match-end 3)
9093 (princ (format "[%c] %s (%s)\n" (incf cnt)
9094 (match-string 3 l) (match-string 1 l)))
9095 (princ (format "[%c] %s\n" (incf cnt)
9096 (match-string 1 l))))))
9097 links))
9098 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9099 (message "Select link to open, RET to open all:")
9100 (setq c (read-char-exclusive))
9101 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9102 (when (equal c ?q) (error "Abort"))
9103 (if (equal c ?\C-m)
9104 (setq link links)
9105 (setq nth (- c ?0))
9106 (if have-zero (setq nth (1+ nth)))
9107 (unless (and (integerp nth) (>= (length links) nth))
9108 (error "Invalid link selection"))
9109 (setq link (list (nth (1- nth) links))))))
9110 (if link
9111 (let ((buf (current-buffer)))
9112 (dolist (l link)
9113 (org-open-link-from-string l in-emacs buf))
9115 nil)))
9117 ;; Add special file links that specify the way of opening
9119 (org-add-link-type "file+sys" 'org-open-file-with-system)
9120 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9121 (defun org-open-file-with-system (path)
9122 "Open file at PATH using the system way of opeing it."
9123 (org-open-file path 'system))
9124 (defun org-open-file-with-emacs (path)
9125 "Open file at PATH in emacs."
9126 (org-open-file path 'emacs))
9127 (defun org-remove-file-link-modifiers ()
9128 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9129 (goto-char (point-min))
9130 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9131 (org-if-unprotected
9132 (replace-match "file:" t t))))
9133 (eval-after-load "org-exp"
9134 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9135 'org-remove-file-link-modifiers))
9137 ;;;; Time estimates
9139 (defun org-get-effort (&optional pom)
9140 "Get the effort estimate for the current entry."
9141 (org-entry-get pom org-effort-property))
9143 ;;; File search
9145 (defvar org-create-file-search-functions nil
9146 "List of functions to construct the right search string for a file link.
9147 These functions are called in turn with point at the location to
9148 which the link should point.
9150 A function in the hook should first test if it would like to
9151 handle this file type, for example by checking the major-mode or
9152 the file extension. If it decides not to handle this file, it
9153 should just return nil to give other functions a chance. If it
9154 does handle the file, it must return the search string to be used
9155 when following the link. The search string will be part of the
9156 file link, given after a double colon, and `org-open-at-point'
9157 will automatically search for it. If special measures must be
9158 taken to make the search successful, another function should be
9159 added to the companion hook `org-execute-file-search-functions',
9160 which see.
9162 A function in this hook may also use `setq' to set the variable
9163 `description' to provide a suggestion for the descriptive text to
9164 be used for this link when it gets inserted into an Org-mode
9165 buffer with \\[org-insert-link].")
9167 (defvar org-execute-file-search-functions nil
9168 "List of functions to execute a file search triggered by a link.
9170 Functions added to this hook must accept a single argument, the
9171 search string that was part of the file link, the part after the
9172 double colon. The function must first check if it would like to
9173 handle this search, for example by checking the major-mode or the
9174 file extension. If it decides not to handle this search, it
9175 should just return nil to give other functions a chance. If it
9176 does handle the search, it must return a non-nil value to keep
9177 other functions from trying.
9179 Each function can access the current prefix argument through the
9180 variable `current-prefix-argument'. Note that a single prefix is
9181 used to force opening a link in Emacs, so it may be good to only
9182 use a numeric or double prefix to guide the search function.
9184 In case this is needed, a function in this hook can also restore
9185 the window configuration before `org-open-at-point' was called using:
9187 (set-window-configuration org-window-config-before-follow-link)")
9189 (defun org-link-search (s &optional type avoid-pos)
9190 "Search for a link search option.
9191 If S is surrounded by forward slashes, it is interpreted as a
9192 regular expression. In org-mode files, this will create an `org-occur'
9193 sparse tree. In ordinary files, `occur' will be used to list matches.
9194 If the current buffer is in `dired-mode', grep will be used to search
9195 in all files. If AVOID-POS is given, ignore matches near that position."
9196 (let ((case-fold-search t)
9197 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9198 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9199 (append '(("") (" ") ("\t") ("\n"))
9200 org-emphasis-alist)
9201 "\\|") "\\)"))
9202 (pos (point))
9203 (pre nil) (post nil)
9204 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9205 (cond
9206 ;; First check if there are any special
9207 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9208 ;; Now try the builtin stuff
9209 ((and (equal (string-to-char s0) ?#)
9210 (> (length s0) 1)
9211 (save-excursion
9212 (goto-char (point-min))
9213 (and
9214 (re-search-forward
9215 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9216 (setq type 'dedicated
9217 pos (match-beginning 0))))
9218 ;; There is an exact target for this
9219 (goto-char pos)
9220 (org-back-to-heading t)))
9221 ((save-excursion
9222 (goto-char (point-min))
9223 (and
9224 (re-search-forward
9225 (concat "<<" (regexp-quote s0) ">>") nil t)
9226 (setq type 'dedicated
9227 pos (match-beginning 0))))
9228 ;; There is an exact target for this
9229 (goto-char pos))
9230 ((and (string-match "^(\\(.*\\))$" s0)
9231 (save-excursion
9232 (goto-char (point-min))
9233 (and
9234 (re-search-forward
9235 (concat "[^[]" (regexp-quote
9236 (format org-coderef-label-format
9237 (match-string 1 s0))))
9238 nil t)
9239 (setq type 'dedicated
9240 pos (1+ (match-beginning 0))))))
9241 ;; There is a coderef target for this
9242 (goto-char pos))
9243 ((string-match "^/\\(.*\\)/$" s)
9244 ;; A regular expression
9245 (cond
9246 ((org-mode-p)
9247 (org-occur (match-string 1 s)))
9248 ;;((eq major-mode 'dired-mode)
9249 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9250 (t (org-do-occur (match-string 1 s)))))
9252 ;; A normal search strings
9253 (when (equal (string-to-char s) ?*)
9254 ;; Anchor on headlines, post may include tags.
9255 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9256 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9257 s (substring s 1)))
9258 (remove-text-properties
9259 0 (length s)
9260 '(face nil mouse-face nil keymap nil fontified nil) s)
9261 ;; Make a series of regular expressions to find a match
9262 (setq words (org-split-string s "[ \n\r\t]+")
9264 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9265 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9266 "\\)" markers)
9267 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9268 re2a (concat "[ \t\r\n]" re2a_)
9269 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9270 re4 (concat "[^a-zA-Z_]" re4_)
9272 re1 (concat pre re2 post)
9273 re3 (concat pre (if pre re4_ re4) post)
9274 re5 (concat pre ".*" re4)
9275 re2 (concat pre re2)
9276 re2a (concat pre (if pre re2a_ re2a))
9277 re4 (concat pre (if pre re4_ re4))
9278 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9279 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9280 re5 "\\)"
9282 (cond
9283 ((eq type 'org-occur) (org-occur reall))
9284 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9285 (t (goto-char (point-min))
9286 (setq type 'fuzzy)
9287 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9288 (org-search-not-self 1 re1 nil t)
9289 (org-search-not-self 1 re2 nil t)
9290 (org-search-not-self 1 re2a nil t)
9291 (org-search-not-self 1 re3 nil t)
9292 (org-search-not-self 1 re4 nil t)
9293 (org-search-not-self 1 re5 nil t)
9295 (goto-char (match-beginning 1))
9296 (goto-char pos)
9297 (error "No match")))))
9299 ;; Normal string-search
9300 (goto-char (point-min))
9301 (if (search-forward s nil t)
9302 (goto-char (match-beginning 0))
9303 (error "No match"))))
9304 (and (org-mode-p) (org-show-context 'link-search))
9305 type))
9307 (defun org-search-not-self (group &rest args)
9308 "Execute `re-search-forward', but only accept matches that do not
9309 enclose the position of `org-open-link-marker'."
9310 (let ((m org-open-link-marker))
9311 (catch 'exit
9312 (while (apply 're-search-forward args)
9313 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9314 (goto-char (match-end group))
9315 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9316 (> (match-beginning 0) (marker-position m))
9317 (< (match-end 0) (marker-position m)))
9318 (save-match-data
9319 (or (not (org-in-regexp
9320 org-bracket-link-analytic-regexp 1))
9321 (not (match-end 4)) ; no description
9322 (and (<= (match-beginning 4) (point))
9323 (>= (match-end 4) (point))))))
9324 (throw 'exit (point))))))))
9326 (defun org-get-buffer-for-internal-link (buffer)
9327 "Return a buffer to be used for displaying the link target of internal links."
9328 (cond
9329 ((not org-display-internal-link-with-indirect-buffer)
9330 buffer)
9331 ((string-match "(Clone)$" (buffer-name buffer))
9332 (message "Buffer is already a clone, not making another one")
9333 ;; we also do not modify visibility in this case
9334 buffer)
9335 (t ; make a new indirect buffer for displaying the link
9336 (let* ((bn (buffer-name buffer))
9337 (ibn (concat bn "(Clone)"))
9338 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9339 (with-current-buffer ib (org-overview))
9340 ib))))
9342 (defun org-do-occur (regexp &optional cleanup)
9343 "Call the Emacs command `occur'.
9344 If CLEANUP is non-nil, remove the printout of the regular expression
9345 in the *Occur* buffer. This is useful if the regex is long and not useful
9346 to read."
9347 (occur regexp)
9348 (when cleanup
9349 (let ((cwin (selected-window)) win beg end)
9350 (when (setq win (get-buffer-window "*Occur*"))
9351 (select-window win))
9352 (goto-char (point-min))
9353 (when (re-search-forward "match[a-z]+" nil t)
9354 (setq beg (match-end 0))
9355 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9356 (setq end (1- (match-beginning 0)))))
9357 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9358 (goto-char (point-min))
9359 (select-window cwin))))
9361 ;;; The mark ring for links jumps
9363 (defvar org-mark-ring nil
9364 "Mark ring for positions before jumps in Org-mode.")
9365 (defvar org-mark-ring-last-goto nil
9366 "Last position in the mark ring used to go back.")
9367 ;; Fill and close the ring
9368 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9369 (loop for i from 1 to org-mark-ring-length do
9370 (push (make-marker) org-mark-ring))
9371 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9372 org-mark-ring)
9374 (defun org-mark-ring-push (&optional pos buffer)
9375 "Put the current position or POS into the mark ring and rotate it."
9376 (interactive)
9377 (setq pos (or pos (point)))
9378 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9379 (move-marker (car org-mark-ring)
9380 (or pos (point))
9381 (or buffer (current-buffer)))
9382 (message "%s"
9383 (substitute-command-keys
9384 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9386 (defun org-mark-ring-goto (&optional n)
9387 "Jump to the previous position in the mark ring.
9388 With prefix arg N, jump back that many stored positions. When
9389 called several times in succession, walk through the entire ring.
9390 Org-mode commands jumping to a different position in the current file,
9391 or to another Org-mode file, automatically push the old position
9392 onto the ring."
9393 (interactive "p")
9394 (let (p m)
9395 (if (eq last-command this-command)
9396 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9397 (setq p org-mark-ring))
9398 (setq org-mark-ring-last-goto p)
9399 (setq m (car p))
9400 (switch-to-buffer (marker-buffer m))
9401 (goto-char m)
9402 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9404 (defun org-remove-angle-brackets (s)
9405 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9406 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9408 (defun org-add-angle-brackets (s)
9409 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9410 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9412 (defun org-remove-double-quotes (s)
9413 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9414 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9417 ;;; Following specific links
9419 (defun org-follow-timestamp-link ()
9420 (cond
9421 ((org-at-date-range-p t)
9422 (let ((org-agenda-start-on-weekday)
9423 (t1 (match-string 1))
9424 (t2 (match-string 2)))
9425 (setq t1 (time-to-days (org-time-string-to-time t1))
9426 t2 (time-to-days (org-time-string-to-time t2)))
9427 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9428 ((org-at-timestamp-p t)
9429 (org-agenda-list nil (time-to-days (org-time-string-to-time
9430 (substring (match-string 1) 0 10)))
9432 (t (error "This should not happen"))))
9435 ;;; Following file links
9436 (defvar org-wait nil)
9437 (defun org-open-file (path &optional in-emacs line search)
9438 "Open the file at PATH.
9439 First, this expands any special file name abbreviations. Then the
9440 configuration variable `org-file-apps' is checked if it contains an
9441 entry for this file type, and if yes, the corresponding command is launched.
9443 If no application is found, Emacs simply visits the file.
9445 With optional prefix argument IN-EMACS, Emacs will visit the file.
9446 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9447 and to use an external application to visit the file.
9449 Optional LINE specifies a line to go to, optional SEARCH a string
9450 to search for. If LINE or SEARCH is given, the file will be
9451 opened in Emacs, unless an entry from org-file-apps that makes
9452 use of groups in a regexp matches.
9453 If the file does not exist, an error is thrown."
9454 (let* ((file (if (equal path "")
9455 buffer-file-name
9456 (substitute-in-file-name (expand-file-name path))))
9457 (file-apps (append org-file-apps (org-default-apps)))
9458 (apps (org-remove-if
9459 'org-file-apps-entry-match-against-dlink-p file-apps))
9460 (apps-dlink (org-remove-if-not
9461 'org-file-apps-entry-match-against-dlink-p file-apps))
9462 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9463 (dirp (if remp nil (file-directory-p file)))
9464 (file (if (and dirp org-open-directory-means-index-dot-org)
9465 (concat (file-name-as-directory file) "index.org")
9466 file))
9467 (a-m-a-p (assq 'auto-mode apps))
9468 (dfile (downcase file))
9469 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9470 (link (cond ((and (eq line nil)
9471 (eq search nil))
9472 file)
9473 (line
9474 (concat file "::" (number-to-string line)))
9475 (search
9476 (concat file "::" search))))
9477 (dlink (downcase link))
9478 (old-buffer (current-buffer))
9479 (old-pos (point))
9480 (old-mode major-mode)
9481 ext cmd link-match-data)
9482 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9483 (setq ext (match-string 1 dfile))
9484 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9485 (setq ext (match-string 1 dfile))))
9486 (cond
9487 ((member in-emacs '((16) system))
9488 (setq cmd (cdr (assoc 'system apps))))
9489 (in-emacs (setq cmd 'emacs))
9491 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9492 (and dirp (cdr (assoc 'directory apps)))
9493 ; first, try matching against apps-dlink
9494 ; if we get a match here, store the match data for later
9495 (let ((match (assoc-default dlink apps-dlink
9496 'string-match)))
9497 (if match
9498 (progn (setq link-match-data (match-data))
9499 match)
9500 (progn (setq in-emacs (or in-emacs line search))
9501 nil))) ; if we have no match in apps-dlink,
9502 ; always open the file in emacs if line or search
9503 ; is given (for backwards compatibility)
9504 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9505 'string-match)
9506 (cdr (assoc ext apps))
9507 (cdr (assoc t apps))))))
9508 (when (eq cmd 'system)
9509 (setq cmd (cdr (assoc 'system apps))))
9510 (when (eq cmd 'default)
9511 (setq cmd (cdr (assoc t apps))))
9512 (when (eq cmd 'mailcap)
9513 (require 'mailcap)
9514 (mailcap-parse-mailcaps)
9515 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9516 (command (mailcap-mime-info mime-type)))
9517 (if (stringp command)
9518 (setq cmd command)
9519 (setq cmd 'emacs))))
9520 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9521 (not (file-exists-p file))
9522 (not org-open-non-existing-files))
9523 (error "No such file: %s" file))
9524 (cond
9525 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9526 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9527 (while (string-match "['\"]%s['\"]" cmd)
9528 (setq cmd (replace-match "%s" t t cmd)))
9529 (while (string-match "%s" cmd)
9530 (setq cmd (replace-match
9531 (save-match-data
9532 (shell-quote-argument
9533 (convert-standard-filename file)))
9534 t t cmd)))
9536 ;; Replace "%1", "%2" etc. in command with group matches from regex
9537 (save-match-data
9538 (let ((match-index 1)
9539 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9540 (set-match-data link-match-data)
9541 (while (<= match-index number-of-groups)
9542 (let ((regex (concat "%" (number-to-string match-index)))
9543 (replace-with (match-string match-index dlink)))
9544 (while (string-match regex cmd)
9545 (setq cmd (replace-match replace-with t t cmd))))
9546 (setq match-index (+ match-index 1)))))
9548 (save-window-excursion
9549 (start-process-shell-command cmd nil cmd)
9550 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9552 ((or (stringp cmd)
9553 (eq cmd 'emacs))
9554 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9555 (widen)
9556 (if line (org-goto-line line)
9557 (if search (org-link-search search))))
9558 ((consp cmd)
9559 (let ((file (convert-standard-filename file)))
9560 (save-match-data
9561 (set-match-data link-match-data)
9562 (eval cmd))))
9563 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9564 (and (org-mode-p) (eq old-mode 'org-mode)
9565 (or (not (equal old-buffer (current-buffer)))
9566 (not (equal old-pos (point))))
9567 (org-mark-ring-push old-pos old-buffer))))
9569 (defun org-file-apps-entry-match-against-dlink-p (entry)
9570 "This function returns non-nil if `entry' uses a regular
9571 expression which should be matched against the whole link by
9572 org-open-file.
9574 It assumes that is the case when the entry uses a regular
9575 expression which has at least one grouping construct and the
9576 action is either a lisp form or a command string containing
9577 '%1', i.e. using at least one subexpression match as a
9578 parameter."
9579 (let ((selector (car entry))
9580 (action (cdr entry)))
9581 (if (stringp selector)
9582 (and (> (regexp-opt-depth selector) 0)
9583 (or (and (stringp action)
9584 (string-match "%[0-9]" action))
9585 (consp action)))
9586 nil)))
9588 (defun org-default-apps ()
9589 "Return the default applications for this operating system."
9590 (cond
9591 ((eq system-type 'darwin)
9592 org-file-apps-defaults-macosx)
9593 ((eq system-type 'windows-nt)
9594 org-file-apps-defaults-windowsnt)
9595 (t org-file-apps-defaults-gnu)))
9597 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9598 "Convert extensions to regular expressions in the cars of LIST.
9599 Also, weed out any non-string entries, because the return value is used
9600 only for regexp matching.
9601 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9602 point to the symbol `emacs', indicating that the file should
9603 be opened in Emacs."
9604 (append
9605 (delq nil
9606 (mapcar (lambda (x)
9607 (if (not (stringp (car x)))
9609 (if (string-match "\\W" (car x))
9611 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9612 list))
9613 (if add-auto-mode
9614 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9616 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9617 (defun org-file-remote-p (file)
9618 "Test whether FILE specifies a location on a remote system.
9619 Return non-nil if the location is indeed remote.
9621 For example, the filename \"/user@host:/foo\" specifies a location
9622 on the system \"/user@host:\"."
9623 (cond ((fboundp 'file-remote-p)
9624 (file-remote-p file))
9625 ((fboundp 'tramp-handle-file-remote-p)
9626 (tramp-handle-file-remote-p file))
9627 ((and (boundp 'ange-ftp-name-format)
9628 (string-match (car ange-ftp-name-format) file))
9630 (t nil)))
9633 ;;;; Refiling
9635 (defun org-get-org-file ()
9636 "Read a filename, with default directory `org-directory'."
9637 (let ((default (or org-default-notes-file remember-data-file)))
9638 (read-file-name (format "File name [%s]: " default)
9639 (file-name-as-directory org-directory)
9640 default)))
9642 (defun org-notes-order-reversed-p ()
9643 "Check if the current file should receive notes in reversed order."
9644 (cond
9645 ((not org-reverse-note-order) nil)
9646 ((eq t org-reverse-note-order) t)
9647 ((not (listp org-reverse-note-order)) nil)
9648 (t (catch 'exit
9649 (let ((all org-reverse-note-order)
9650 entry)
9651 (while (setq entry (pop all))
9652 (if (string-match (car entry) buffer-file-name)
9653 (throw 'exit (cdr entry))))
9654 nil)))))
9656 (defvar org-refile-target-table nil
9657 "The list of refile targets, created by `org-refile'.")
9659 (defvar org-agenda-new-buffers nil
9660 "Buffers created to visit agenda files.")
9662 (defvar org-refile-cache nil
9663 "Cache for refile targets.")
9666 (defvar org-refile-markers nil
9667 "All the markers used for caching refile locations.")
9669 (defun org-refile-marker (pos)
9670 "Get a new refile marker, but only if caching is in use."
9671 (if (not org-refile-use-cache)
9673 (let ((m (make-marker)))
9674 (move-marker m pos)
9675 (push m org-refile-markers)
9676 m)))
9678 (defun org-refile-cache-clear ()
9679 "Clear the refile cache and disable all the markers."
9680 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9681 (setq org-refile-markers nil)
9682 (setq org-refile-cache nil)
9683 (message "Refile cache has been cleared"))
9685 (defun org-refile-cache-check-set (set)
9686 "Check if all the markers in the cache still have live buffers."
9687 (let (marker)
9688 (catch 'exit
9689 (while (and set (setq marker (nth 3 (pop set))))
9690 ;; if org-refile-use-outline-path is 'file, marker may be nil
9691 (when (and marker (null (marker-buffer marker)))
9692 (message "not found") (sit-for 3)
9693 (throw 'exit nil)))
9694 t)))
9696 (defun org-refile-cache-put (set &rest identifiers)
9697 "Push the refile targets SET into the cache, under IDENTIFIERS."
9698 (let* ((key (sha1 (prin1-to-string identifiers)))
9699 (entry (assoc key org-refile-cache)))
9700 (if entry
9701 (setcdr entry set)
9702 (push (cons key set) org-refile-cache))))
9704 (defun org-refile-cache-get (&rest identifiers)
9705 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9706 (cond
9707 ((not org-refile-cache) nil)
9708 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9710 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9711 org-refile-cache))))
9712 (and set (org-refile-cache-check-set set) set)))))
9714 (defun org-get-refile-targets (&optional default-buffer)
9715 "Produce a table with refile targets."
9716 (let ((case-fold-search nil)
9717 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9718 (entries (or org-refile-targets '((nil . (:level . 1)))))
9719 targets tgs txt re files f desc descre fast-path-p level pos0)
9720 (message "Getting targets...")
9721 (with-current-buffer (or default-buffer (current-buffer))
9722 (while (setq entry (pop entries))
9723 (setq files (car entry) desc (cdr entry))
9724 (setq fast-path-p nil)
9725 (cond
9726 ((null files) (setq files (list (current-buffer))))
9727 ((eq files 'org-agenda-files)
9728 (setq files (org-agenda-files 'unrestricted)))
9729 ((and (symbolp files) (fboundp files))
9730 (setq files (funcall files)))
9731 ((and (symbolp files) (boundp files))
9732 (setq files (symbol-value files))))
9733 (if (stringp files) (setq files (list files)))
9734 (cond
9735 ((eq (car desc) :tag)
9736 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9737 ((eq (car desc) :todo)
9738 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9739 ((eq (car desc) :regexp)
9740 (setq descre (cdr desc)))
9741 ((eq (car desc) :level)
9742 (setq descre (concat "^\\*\\{" (number-to-string
9743 (if org-odd-levels-only
9744 (1- (* 2 (cdr desc)))
9745 (cdr desc)))
9746 "\\}[ \t]")))
9747 ((eq (car desc) :maxlevel)
9748 (setq fast-path-p t)
9749 (setq descre (concat "^\\*\\{1," (number-to-string
9750 (if org-odd-levels-only
9751 (1- (* 2 (cdr desc)))
9752 (cdr desc)))
9753 "\\}[ \t]")))
9754 (t (error "Bad refiling target description %s" desc)))
9755 (while (setq f (pop files))
9756 (with-current-buffer
9757 (if (bufferp f) f (org-get-agenda-file-buffer f))
9759 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9760 (progn
9761 (if (bufferp f) (setq f (buffer-file-name
9762 (buffer-base-buffer f))))
9763 (setq f (and f (expand-file-name f)))
9764 (if (eq org-refile-use-outline-path 'file)
9765 (push (list (file-name-nondirectory f) f nil nil) tgs))
9766 (save-excursion
9767 (save-restriction
9768 (widen)
9769 (goto-char (point-min))
9770 (while (re-search-forward descre nil t)
9771 (goto-char (setq pos0 (point-at-bol)))
9772 (catch 'next
9773 (when org-refile-target-verify-function
9774 (save-match-data
9775 (or (funcall org-refile-target-verify-function)
9776 (throw 'next t))))
9777 (when (looking-at org-complex-heading-regexp)
9778 (setq level (org-reduced-level
9779 (- (match-end 1) (match-beginning 1)))
9780 txt (org-link-display-format (match-string 4))
9781 re (concat "^" (regexp-quote
9782 (buffer-substring
9783 (match-beginning 1)
9784 (match-end 4)))))
9785 (if (match-end 5) (setq re (concat
9786 re "[ \t]+"
9787 (regexp-quote
9788 (match-string 5)))))
9789 (setq re (concat re "[ \t]*$"))
9790 (when org-refile-use-outline-path
9791 (setq txt (mapconcat
9792 'org-protect-slash
9793 (append
9794 (if (eq org-refile-use-outline-path
9795 'file)
9796 (list (file-name-nondirectory
9797 (buffer-file-name
9798 (buffer-base-buffer))))
9799 (if (eq org-refile-use-outline-path
9800 'full-file-path)
9801 (list (buffer-file-name
9802 (buffer-base-buffer)))))
9803 (org-get-outline-path fast-path-p
9804 level txt)
9805 (list txt))
9806 "/")))
9807 (push (list txt f re (org-refile-marker (point)))
9808 tgs)))
9809 (when (= (point) pos0)
9810 ;; verification function has not moved point
9811 (goto-char (point-at-eol))))))))
9812 (when org-refile-use-cache
9813 (org-refile-cache-put tgs (buffer-file-name) descre))
9814 (setq targets (append tgs targets))
9815 ))))
9816 (message "Getting targets...done")
9817 (nreverse targets)))
9819 (defun org-protect-slash (s)
9820 (while (string-match "/" s)
9821 (setq s (replace-match "\\" t t s)))
9824 (defvar org-olpa (make-vector 20 nil))
9826 (defun org-get-outline-path (&optional fastp level heading)
9827 "Return the outline path to the current entry, as a list.
9829 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9830 routine which makes outline path derivations for an entire file,
9831 avoiding backtracing. Refile target collection makes use of that."
9832 (if fastp
9833 (progn
9834 (if (> level 19)
9835 (error "Outline path failure, more than 19 levels."))
9836 (loop for i from level upto 19 do
9837 (aset org-olpa i nil))
9838 (prog1
9839 (delq nil (append org-olpa nil))
9840 (aset org-olpa level heading)))
9841 (let (rtn case-fold-search)
9842 (save-excursion
9843 (save-restriction
9844 (widen)
9845 (while (org-up-heading-safe)
9846 (when (looking-at org-complex-heading-regexp)
9847 (push (org-match-string-no-properties 4) rtn)))
9848 rtn)))))
9850 (defun org-format-outline-path (path &optional width prefix)
9851 "Format the outlie path PATH for display.
9852 Width is the maximum number of characters that is available.
9853 Prefix is a prefix to be included in the returned string,
9854 such as the file name."
9855 (setq width (or width 79))
9856 (if prefix (setq width (- width (length prefix))))
9857 (if (not path)
9858 (or prefix "")
9859 (let* ((nsteps (length path))
9860 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9861 (maxwidth (if (<= total-width width)
9862 10000 ;; everything fits
9863 ;; we need to shorten the level headings
9864 (/ (- width nsteps) nsteps)))
9865 (org-odd-levels-only nil)
9866 (n 0)
9867 (total (1+ (length prefix))))
9868 (setq maxwidth (max maxwidth 10))
9869 (concat prefix
9870 (mapconcat
9871 (lambda (h)
9872 (setq n (1+ n))
9873 (if (and (= n nsteps) (< maxwidth 10000))
9874 (setq maxwidth (- total-width total)))
9875 (if (< (length h) maxwidth)
9876 (progn (setq total (+ total (length h) 1)) h)
9877 (setq h (substring h 0 (- maxwidth 2))
9878 total (+ total maxwidth 1))
9879 (if (string-match "[ \t]+\\'" h)
9880 (setq h (substring h 0 (match-beginning 0))))
9881 (setq h (concat h "..")))
9882 (org-add-props h nil 'face
9883 (nth (% (1- n) org-n-level-faces)
9884 org-level-faces))
9886 path "/")))))
9888 (defun org-display-outline-path (&optional file current)
9889 "Display the current outline path in the echo area."
9890 (interactive "P")
9891 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9892 (case-fold-search nil)
9893 (path (and (org-mode-p) (org-get-outline-path))))
9894 (if current (setq path (append path
9895 (save-excursion
9896 (org-back-to-heading t)
9897 (if (looking-at org-complex-heading-regexp)
9898 (list (match-string 4)))))))
9899 (message "%s"
9900 (org-format-outline-path
9901 path
9902 (1- (frame-width))
9903 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9905 (defvar org-refile-history nil
9906 "History for refiling operations.")
9908 (defvar org-after-refile-insert-hook nil
9909 "Hook run after `org-refile' has inserted its stuff at the new location.
9910 Note that this is still *before* the stuff will be removed from
9911 the *old* location.")
9913 (defun org-refile (&optional goto default-buffer rfloc)
9914 "Move the entry at point to another heading.
9915 The list of target headings is compiled using the information in
9916 `org-refile-targets', which see. This list is created before each use
9917 and will therefore always be up-to-date.
9919 At the target location, the entry is filed as a subitem of the target heading.
9920 Depending on `org-reverse-note-order', the new subitem will either be the
9921 first or the last subitem.
9923 If there is an active region, all entries in that region will be moved.
9924 However, the region must fulfil the requirement that the first heading
9925 is the first one sets the top-level of the moved text - at most siblings
9926 below it are allowed.
9928 With prefix arg GOTO, the command will only visit the target location,
9929 not actually move anything.
9930 With a double prefix `C-u C-u', go to the location where the last refiling
9931 operation has put the subtree.
9932 With a prefix argument of `2', refile to the running clock.
9934 RFLOC can be a refile location obtained in a different way.
9936 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
9938 If you are using target caching (see `org-refile-use-cache'),
9939 You have to clear the target cache in order to find new targets.
9940 This can be done with a 0 prefix: `C-0 C-c C-w'"
9941 (interactive "P")
9942 (if (member goto '(0 (64)))
9943 (org-refile-cache-clear)
9944 (let* ((cbuf (current-buffer))
9945 (regionp (org-region-active-p))
9946 (region-start (and regionp (region-beginning)))
9947 (region-end (and regionp (region-end)))
9948 (region-length (and regionp (- region-end region-start)))
9949 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9950 pos it nbuf file re level reversed)
9951 (setq last-command nil)
9952 (when regionp
9953 (goto-char region-start)
9954 (or (bolp) (goto-char (point-at-bol)))
9955 (setq region-start (point))
9956 (unless (org-kill-is-subtree-p
9957 (buffer-substring region-start region-end))
9958 (error "The region is not a (sequence of) subtree(s)")))
9959 (if (equal goto '(16))
9960 (org-refile-goto-last-stored)
9961 (when (or
9962 (and (equal goto 2)
9963 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9964 (prog1
9965 (setq it (list (or org-clock-heading "running clock")
9966 (buffer-file-name
9967 (marker-buffer org-clock-hd-marker))
9969 (marker-position org-clock-hd-marker)))
9970 (setq goto nil)))
9971 (setq it (or rfloc
9972 (save-excursion
9973 (org-refile-get-location
9974 (if goto "Goto: " "Refile to: ") default-buffer
9975 org-refile-allow-creating-parent-nodes)))))
9976 (setq file (nth 1 it)
9977 re (nth 2 it)
9978 pos (nth 3 it))
9979 (if (and (not goto)
9981 (equal (buffer-file-name) file)
9982 (if regionp
9983 (and (>= pos region-start)
9984 (<= pos region-end))
9985 (and (>= pos (point))
9986 (< pos (save-excursion
9987 (org-end-of-subtree t t))))))
9988 (error "Cannot refile to position inside the tree or region"))
9990 (setq nbuf (or (find-buffer-visiting file)
9991 (find-file-noselect file)))
9992 (if goto
9993 (progn
9994 (switch-to-buffer nbuf)
9995 (goto-char pos)
9996 (org-show-context 'org-goto))
9997 (if regionp
9998 (progn
9999 (org-kill-new (buffer-substring region-start region-end))
10000 (org-save-markers-in-region region-start region-end))
10001 (org-copy-subtree 1 nil t))
10002 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10003 (find-file-noselect file)))
10004 (setq reversed (org-notes-order-reversed-p))
10005 (save-excursion
10006 (save-restriction
10007 (widen)
10008 (if pos
10009 (progn
10010 (goto-char pos)
10011 (looking-at outline-regexp)
10012 (setq level (org-get-valid-level (funcall outline-level) 1))
10013 (goto-char
10014 (if reversed
10015 (or (outline-next-heading) (point-max))
10016 (or (save-excursion (org-get-next-sibling))
10017 (org-end-of-subtree t t)
10018 (point-max)))))
10019 (setq level 1)
10020 (if (not reversed)
10021 (goto-char (point-max))
10022 (goto-char (point-min))
10023 (or (outline-next-heading) (goto-char (point-max)))))
10024 (if (not (bolp)) (newline))
10025 (org-paste-subtree level)
10026 (when org-log-refile
10027 (org-add-log-setup 'refile nil nil 'findpos
10028 org-log-refile)
10029 (unless (eq org-log-refile 'note)
10030 (save-excursion (org-add-log-note))))
10031 (and org-auto-align-tags (org-set-tags nil t))
10032 (bookmark-set "org-refile-last-stored")
10033 (if (fboundp 'deactivate-mark) (deactivate-mark))
10034 (run-hooks 'org-after-refile-insert-hook))))
10035 (if regionp
10036 (delete-region (point) (+ (point) region-length))
10037 (org-cut-subtree))
10038 (when (featurep 'org-inlinetask)
10039 (org-inlinetask-remove-END-maybe))
10040 (setq org-markers-to-move nil)
10041 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10043 (defun org-refile-goto-last-stored ()
10044 "Go to the location where the last refile was stored."
10045 (interactive)
10046 (bookmark-jump "org-refile-last-stored")
10047 (message "This is the location of the last refile"))
10049 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10050 "Prompt the user for a refile location, using PROMPT."
10051 (let ((org-refile-targets org-refile-targets)
10052 (org-refile-use-outline-path org-refile-use-outline-path))
10053 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10054 (unless org-refile-target-table
10055 (error "No refile targets"))
10056 (let* ((cbuf (current-buffer))
10057 (partial-completion-mode nil)
10058 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10059 (cfunc (if (and org-refile-use-outline-path
10060 org-outline-path-complete-in-steps)
10061 'org-olpath-completing-read
10062 'org-icompleting-read))
10063 (extra (if org-refile-use-outline-path "/" ""))
10064 (filename (and cfn (expand-file-name cfn)))
10065 (tbl (mapcar
10066 (lambda (x)
10067 (if (and (not (member org-refile-use-outline-path
10068 '(file full-file-path)))
10069 (not (equal filename (nth 1 x))))
10070 (cons (concat (car x) extra " ("
10071 (file-name-nondirectory (nth 1 x)) ")")
10072 (cdr x))
10073 (cons (concat (car x) extra) (cdr x))))
10074 org-refile-target-table))
10075 (completion-ignore-case t)
10076 pa answ parent-target child parent old-hist)
10077 (setq old-hist org-refile-history)
10078 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10079 nil 'org-refile-history))
10080 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10081 (if pa
10082 (progn
10083 (when (or (not org-refile-history)
10084 (not (eq old-hist org-refile-history))
10085 (not (equal (car pa) (car org-refile-history))))
10086 (setq org-refile-history
10087 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10088 org-refile-history
10089 (cdr org-refile-history))))
10090 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10091 (pop org-refile-history)))
10093 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10094 (progn
10095 (setq parent (match-string 1 answ)
10096 child (match-string 2 answ))
10097 (setq parent-target (or (assoc parent tbl)
10098 (assoc (concat parent "/") tbl)))
10099 (when (and parent-target
10100 (or (eq new-nodes t)
10101 (and (eq new-nodes 'confirm)
10102 (y-or-n-p (format "Create new node \"%s\"? "
10103 child)))))
10104 (org-refile-new-child parent-target child)))
10105 (error "Invalid target location")))))
10107 (defun org-refile-new-child (parent-target child)
10108 "Use refile target PARENT-TARGET to add new CHILD below it."
10109 (unless parent-target
10110 (error "Cannot find parent for new node"))
10111 (let ((file (nth 1 parent-target))
10112 (pos (nth 3 parent-target))
10113 level)
10114 (with-current-buffer (or (find-buffer-visiting file)
10115 (find-file-noselect file))
10116 (save-excursion
10117 (save-restriction
10118 (widen)
10119 (if pos
10120 (goto-char pos)
10121 (goto-char (point-max))
10122 (if (not (bolp)) (newline)))
10123 (when (looking-at outline-regexp)
10124 (setq level (funcall outline-level))
10125 (org-end-of-subtree t t))
10126 (org-back-over-empty-lines)
10127 (insert "\n" (make-string
10128 (if pos (org-get-valid-level level 1) 1) ?*)
10129 " " child "\n")
10130 (beginning-of-line 0)
10131 (list (concat (car parent-target) "/" child) file "" (point)))))))
10133 (defun org-olpath-completing-read (prompt collection &rest args)
10134 "Read an outline path like a file name."
10135 (let ((thetable collection)
10136 (org-completion-use-ido nil) ; does not work with ido.
10137 (org-completion-use-iswitchb nil)) ; or iswitchb
10138 (apply
10139 'org-icompleting-read prompt
10140 (lambda (string predicate &optional flag)
10141 (let (rtn r f (l (length string)))
10142 (cond
10143 ((eq flag nil)
10144 ;; try completion
10145 (try-completion string thetable))
10146 ((eq flag t)
10147 ;; all-completions
10148 (setq rtn (all-completions string thetable predicate))
10149 (mapcar
10150 (lambda (x)
10151 (setq r (substring x l))
10152 (if (string-match " ([^)]*)$" x)
10153 (setq f (match-string 0 x))
10154 (setq f ""))
10155 (if (string-match "/" r)
10156 (concat string (substring r 0 (match-end 0)) f)
10158 rtn))
10159 ((eq flag 'lambda)
10160 ;; exact match?
10161 (assoc string thetable)))
10163 args)))
10165 ;;;; Dynamic blocks
10167 (defun org-find-dblock (name)
10168 "Find the first dynamic block with name NAME in the buffer.
10169 If not found, stay at current position and return nil."
10170 (let (pos)
10171 (save-excursion
10172 (goto-char (point-min))
10173 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10174 nil t)
10175 (match-beginning 0))))
10176 (if pos (goto-char pos))
10177 pos))
10179 (defconst org-dblock-start-re
10180 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10181 "Matches the start line of a dynamic block, with parameters.")
10183 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10184 "Matches the end of a dynamic block.")
10186 (defun org-create-dblock (plist)
10187 "Create a dynamic block section, with parameters taken from PLIST.
10188 PLIST must contain a :name entry which is used as name of the block."
10189 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10190 (end-of-line 1)
10191 (newline))
10192 (let ((col (current-column))
10193 (name (plist-get plist :name)))
10194 (insert "#+BEGIN: " name)
10195 (while plist
10196 (if (eq (car plist) :name)
10197 (setq plist (cddr plist))
10198 (insert " " (prin1-to-string (pop plist)))))
10199 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10200 (beginning-of-line -2)))
10202 (defun org-prepare-dblock ()
10203 "Prepare dynamic block for refresh.
10204 This empties the block, puts the cursor at the insert position and returns
10205 the property list including an extra property :name with the block name."
10206 (unless (looking-at org-dblock-start-re)
10207 (error "Not at a dynamic block"))
10208 (let* ((begdel (1+ (match-end 0)))
10209 (name (org-no-properties (match-string 1)))
10210 (params (append (list :name name)
10211 (read (concat "(" (match-string 3) ")")))))
10212 (save-excursion
10213 (beginning-of-line 1)
10214 (skip-chars-forward " \t")
10215 (setq params (plist-put params :indentation-column (current-column))))
10216 (unless (re-search-forward org-dblock-end-re nil t)
10217 (error "Dynamic block not terminated"))
10218 (setq params
10219 (append params
10220 (list :content (buffer-substring
10221 begdel (match-beginning 0)))))
10222 (delete-region begdel (match-beginning 0))
10223 (goto-char begdel)
10224 (open-line 1)
10225 params))
10227 (defun org-map-dblocks (&optional command)
10228 "Apply COMMAND to all dynamic blocks in the current buffer.
10229 If COMMAND is not given, use `org-update-dblock'."
10230 (let ((cmd (or command 'org-update-dblock)))
10231 (save-excursion
10232 (goto-char (point-min))
10233 (while (re-search-forward org-dblock-start-re nil t)
10234 (goto-char (match-beginning 0))
10235 (save-excursion
10236 (condition-case nil
10237 (funcall cmd)
10238 (error (message "Error during update of dynamic block"))))
10239 (unless (re-search-forward org-dblock-end-re nil t)
10240 (error "Dynamic block not terminated"))))))
10242 (defun org-dblock-update (&optional arg)
10243 "User command for updating dynamic blocks.
10244 Update the dynamic block at point. With prefix ARG, update all dynamic
10245 blocks in the buffer."
10246 (interactive "P")
10247 (if arg
10248 (org-update-all-dblocks)
10249 (or (looking-at org-dblock-start-re)
10250 (org-beginning-of-dblock))
10251 (org-update-dblock)))
10253 (defun org-update-dblock ()
10254 "Update the dynamic block at point
10255 This means to empty the block, parse for parameters and then call
10256 the correct writing function."
10257 (save-window-excursion
10258 (let* ((pos (point))
10259 (line (org-current-line))
10260 (params (org-prepare-dblock))
10261 (name (plist-get params :name))
10262 (indent (plist-get params :indentation-column))
10263 (cmd (intern (concat "org-dblock-write:" name))))
10264 (message "Updating dynamic block `%s' at line %d..." name line)
10265 (funcall cmd params)
10266 (message "Updating dynamic block `%s' at line %d...done" name line)
10267 (goto-char pos)
10268 (when (and indent (> indent 0))
10269 (setq indent (make-string indent ?\ ))
10270 (save-excursion
10271 (org-beginning-of-dblock)
10272 (forward-line 1)
10273 (while (not (looking-at org-dblock-end-re))
10274 (insert indent)
10275 (beginning-of-line 2))
10276 (when (looking-at org-dblock-end-re)
10277 (and (looking-at "[ \t]+")
10278 (replace-match ""))
10279 (insert indent)))))))
10281 (defun org-beginning-of-dblock ()
10282 "Find the beginning of the dynamic block at point.
10283 Error if there is no such block at point."
10284 (let ((pos (point))
10285 beg)
10286 (end-of-line 1)
10287 (if (and (re-search-backward org-dblock-start-re nil t)
10288 (setq beg (match-beginning 0))
10289 (re-search-forward org-dblock-end-re nil t)
10290 (> (match-end 0) pos))
10291 (goto-char beg)
10292 (goto-char pos)
10293 (error "Not in a dynamic block"))))
10295 (defun org-update-all-dblocks ()
10296 "Update all dynamic blocks in the buffer.
10297 This function can be used in a hook."
10298 (when (org-mode-p)
10299 (org-map-dblocks 'org-update-dblock)))
10302 ;;;; Completion
10304 (defconst org-additional-option-like-keywords
10305 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10306 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10307 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10308 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10309 "BEGIN:" "END:"
10310 "ORGTBL" "TBLFM:" "TBLNAME:"
10311 "BEGIN_EXAMPLE" "END_EXAMPLE"
10312 "BEGIN_QUOTE" "END_QUOTE"
10313 "BEGIN_VERSE" "END_VERSE"
10314 "BEGIN_CENTER" "END_CENTER"
10315 "BEGIN_SRC" "END_SRC"
10316 "CATEGORY" "COLUMNS"
10317 "CAPTION" "LABEL"
10318 "SETUPFILE"
10319 "BIND"
10320 "MACRO"))
10322 (defcustom org-structure-template-alist
10324 ("s" "#+begin_src ?\n\n#+end_src"
10325 "<src lang=\"?\">\n\n</src>")
10326 ("e" "#+begin_example\n?\n#+end_example"
10327 "<example>\n?\n</example>")
10328 ("q" "#+begin_quote\n?\n#+end_quote"
10329 "<quote>\n?\n</quote>")
10330 ("v" "#+begin_verse\n?\n#+end_verse"
10331 "<verse>\n?\n/verse>")
10332 ("c" "#+begin_center\n?\n#+end_center"
10333 "<center>\n?\n/center>")
10334 ("l" "#+begin_latex\n?\n#+end_latex"
10335 "<literal style=\"latex\">\n?\n</literal>")
10336 ("L" "#+latex: "
10337 "<literal style=\"latex\">?</literal>")
10338 ("h" "#+begin_html\n?\n#+end_html"
10339 "<literal style=\"html\">\n?\n</literal>")
10340 ("H" "#+html: "
10341 "<literal style=\"html\">?</literal>")
10342 ("a" "#+begin_ascii\n?\n#+end_ascii")
10343 ("A" "#+ascii: ")
10344 ("i" "#+include %file ?"
10345 "<include file=%file markup=\"?\">")
10347 "Structure completion elements.
10348 This is a list of abbreviation keys and values. The value gets inserted
10349 if you type `<' followed by the key and then press the completion key,
10350 usually `M-TAB'. %file will be replaced by a file name after prompting
10351 for the file using completion.
10352 There are two templates for each key, the first uses the original Org syntax,
10353 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10354 the default when the /org-mtags.el/ module has been loaded. See also the
10355 variable `org-mtags-prefer-muse-templates'.
10356 This is an experimental feature, it is undecided if it is going to stay in."
10357 :group 'org-completion
10358 :type '(repeat
10359 (string :tag "Key")
10360 (string :tag "Template")
10361 (string :tag "Muse Template")))
10363 (defun org-try-structure-completion ()
10364 "Try to complete a structure template before point.
10365 This looks for strings like \"<e\" on an otherwise empty line and
10366 expands them."
10367 (let ((l (buffer-substring (point-at-bol) (point)))
10369 (when (and (looking-at "[ \t]*$")
10370 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10371 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10372 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10373 (match-beginning 1)) a)
10374 t)))
10376 (defun org-complete-expand-structure-template (start cell)
10377 "Expand a structure template."
10378 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10379 (rpl (nth (if musep 2 1) cell))
10380 (ind ""))
10381 (delete-region start (point))
10382 (when (string-match "\\`#\\+" rpl)
10383 (cond
10384 ((bolp))
10385 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10386 (setq ind (buffer-substring (point-at-bol) (point))))
10387 (t (newline))))
10388 (setq start (point))
10389 (if (string-match "%file" rpl)
10390 (setq rpl (replace-match
10391 (concat
10392 "\""
10393 (save-match-data
10394 (abbreviate-file-name (read-file-name "Include file: ")))
10395 "\"")
10396 t t rpl)))
10397 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10398 (concat "\n" ind)))
10399 (insert rpl)
10400 (if (re-search-backward "\\?" start t) (delete-char 1))))
10403 (defun org-complete (&optional arg)
10404 "Perform completion on word at point.
10405 At the beginning of a headline, this completes TODO keywords as given in
10406 `org-todo-keywords'.
10407 If the current word is preceded by a backslash, completes the TeX symbols
10408 that are supported for HTML support.
10409 If the current word is preceded by \"#+\", completes special words for
10410 setting file options.
10411 In the line after \"#+STARTUP:, complete valid keywords.\"
10412 At all other locations, this simply calls the value of
10413 `org-completion-fallback-command'."
10414 (interactive "P")
10415 (org-without-partial-completion
10416 (catch 'exit
10417 (let* ((a nil)
10418 (end (point))
10419 (beg1 (save-excursion
10420 (skip-chars-backward (org-re "[:alnum:]_@"))
10421 (point)))
10422 (beg (save-excursion
10423 (skip-chars-backward "a-zA-Z0-9_:$")
10424 (point)))
10425 (confirm (lambda (x) (stringp (car x))))
10426 (searchhead (equal (char-before beg) ?*))
10427 (struct
10428 (when (and (member (char-before beg1) '(?. ?<))
10429 (setq a (assoc (buffer-substring beg1 (point))
10430 org-structure-template-alist)))
10431 (org-complete-expand-structure-template (1- beg1) a)
10432 (throw 'exit t)))
10433 (tag (and (equal (char-before beg1) ?:)
10434 (equal (char-after (point-at-bol)) ?*)))
10435 (prop (and (equal (char-before beg1) ?:)
10436 (not (equal (char-after (point-at-bol)) ?*))))
10437 (texp (equal (char-before beg) ?\\))
10438 (link (equal (char-before beg) ?\[))
10439 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10440 beg)
10441 "#+"))
10442 (startup (string-match "^#\\+STARTUP:.*"
10443 (buffer-substring (point-at-bol) (point))))
10444 (completion-ignore-case opt)
10445 (type nil)
10446 (tbl nil)
10447 (table (cond
10448 (opt
10449 (setq type :opt)
10450 (require 'org-exp)
10451 (append
10452 (delq nil
10453 (mapcar
10454 (lambda (x)
10455 (if (string-match
10456 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10457 (cons (match-string 2 x)
10458 (match-string 1 x))))
10459 (org-split-string (org-get-current-options) "\n")))
10460 (mapcar 'list org-additional-option-like-keywords)))
10461 (startup
10462 (setq type :startup)
10463 org-startup-options)
10464 (link (append org-link-abbrev-alist-local
10465 org-link-abbrev-alist))
10466 (texp
10467 (setq type :tex)
10468 (append org-entities-user org-entities))
10469 ((string-match "\\`\\*+[ \t]+\\'"
10470 (buffer-substring (point-at-bol) beg))
10471 (setq type :todo)
10472 (mapcar 'list org-todo-keywords-1))
10473 (searchhead
10474 (setq type :searchhead)
10475 (save-excursion
10476 (goto-char (point-min))
10477 (while (re-search-forward org-todo-line-regexp nil t)
10478 (push (list
10479 (org-make-org-heading-search-string
10480 (match-string 3) t))
10481 tbl)))
10482 tbl)
10483 (tag (setq type :tag beg beg1)
10484 (or org-tag-alist (org-get-buffer-tags)))
10485 (prop (setq type :prop beg beg1)
10486 (mapcar 'list (org-buffer-property-keys nil t t)))
10487 (t (progn
10488 (call-interactively org-completion-fallback-command)
10489 (throw 'exit nil)))))
10490 (pattern (buffer-substring-no-properties beg end))
10491 (completion (try-completion pattern table confirm)))
10492 (cond ((eq completion t)
10493 (if (not (assoc (upcase pattern) table))
10494 (message "Already complete")
10495 (if (and (equal type :opt)
10496 (not (member (car (assoc (upcase pattern) table))
10497 org-additional-option-like-keywords)))
10498 (insert (substring (cdr (assoc (upcase pattern) table))
10499 (length pattern)))
10500 (if (memq type '(:tag :prop)) (insert ":")))))
10501 ((null completion)
10502 (message "Can't find completion for \"%s\"" pattern)
10503 (ding))
10504 ((not (string= pattern completion))
10505 (delete-region beg end)
10506 (if (string-match " +$" completion)
10507 (setq completion (replace-match "" t t completion)))
10508 (insert completion)
10509 (if (get-buffer-window "*Completions*")
10510 (delete-window (get-buffer-window "*Completions*")))
10511 (if (assoc completion table)
10512 (if (eq type :todo) (insert " ")
10513 (if (memq type '(:tag :prop)) (insert ":"))))
10514 (if (and (equal type :opt) (assoc completion table))
10515 (message "%s" (substitute-command-keys
10516 "Press \\[org-complete] again to insert example settings"))))
10518 (message "Making completion list...")
10519 (let ((list (sort (all-completions pattern table confirm)
10520 'string<)))
10521 (with-output-to-temp-buffer "*Completions*"
10522 (condition-case nil
10523 ;; Protection needed for XEmacs and emacs 21
10524 (display-completion-list list pattern)
10525 (error (display-completion-list list)))))
10526 (message "Making completion list...%s" "done")))))))
10528 ;;;; TODO, DEADLINE, Comments
10530 (defun org-toggle-comment ()
10531 "Change the COMMENT state of an entry."
10532 (interactive)
10533 (save-excursion
10534 (org-back-to-heading)
10535 (let (case-fold-search)
10536 (if (looking-at (concat outline-regexp
10537 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10538 (replace-match "" t t nil 1)
10539 (if (looking-at outline-regexp)
10540 (progn
10541 (goto-char (match-end 0))
10542 (insert org-comment-string " ")))))))
10544 (defvar org-last-todo-state-is-todo nil
10545 "This is non-nil when the last TODO state change led to a TODO state.
10546 If the last change removed the TODO tag or switched to DONE, then
10547 this is nil.")
10549 (defvar org-setting-tags nil) ; dynamically skipped
10551 (defun org-parse-local-options (string var)
10552 "Parse STRING for startup setting relevant for variable VAR."
10553 (let ((rtn (symbol-value var))
10554 e opts)
10555 (save-match-data
10556 (if (or (not string) (not (string-match "\\S-" string)))
10558 (setq opts (delq nil (mapcar (lambda (x)
10559 (setq e (assoc x org-startup-options))
10560 (if (eq (nth 1 e) var) e nil))
10561 (org-split-string string "[ \t]+"))))
10562 (if (not opts)
10564 (setq rtn nil)
10565 (while (setq e (pop opts))
10566 (if (not (nth 3 e))
10567 (setq rtn (nth 2 e))
10568 (if (not (listp rtn)) (setq rtn nil))
10569 (push (nth 2 e) rtn)))
10570 rtn)))))
10572 (defvar org-todo-setup-filter-hook nil
10573 "Hook for functions that pre-filter todo specs.
10575 Each function takes a todo spec and returns either `nil' or the spec
10576 transformed into canonical form." )
10578 (defvar org-todo-get-default-hook nil
10579 "Hook for functions that get a default item for todo.
10581 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10582 `nil' or a string to be used for the todo mark." )
10584 (defvar org-agenda-headline-snapshot-before-repeat)
10586 (defun org-todo (&optional arg)
10587 "Change the TODO state of an item.
10588 The state of an item is given by a keyword at the start of the heading,
10589 like
10590 *** TODO Write paper
10591 *** DONE Call mom
10593 The different keywords are specified in the variable `org-todo-keywords'.
10594 By default the available states are \"TODO\" and \"DONE\".
10595 So for this example: when the item starts with TODO, it is changed to DONE.
10596 When it starts with DONE, the DONE is removed. And when neither TODO nor
10597 DONE are present, add TODO at the beginning of the heading.
10599 With C-u prefix arg, use completion to determine the new state.
10600 With numeric prefix arg, switch to that state.
10601 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10602 With a triple C-u prefix, circumvent any state blocking.
10604 For calling through lisp, arg is also interpreted in the following way:
10605 'none -> empty state
10606 \"\"(empty string) -> switch to empty state
10607 'done -> switch to DONE
10608 'nextset -> switch to the next set of keywords
10609 'previousset -> switch to the previous set of keywords
10610 \"WAITING\" -> switch to the specified keyword, but only if it
10611 really is a member of `org-todo-keywords'."
10612 (interactive "P")
10613 (if (equal arg '(16)) (setq arg 'nextset))
10614 (let ((org-blocker-hook org-blocker-hook)
10615 (case-fold-search nil))
10616 (when (equal arg '(64))
10617 (setq arg nil org-blocker-hook nil))
10618 (when (and org-blocker-hook
10619 (or org-inhibit-blocking
10620 (org-entry-get nil "NOBLOCKING")))
10621 (setq org-blocker-hook nil))
10622 (save-excursion
10623 (catch 'exit
10624 (org-back-to-heading t)
10625 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10626 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10627 (looking-at " *"))
10628 (let* ((match-data (match-data))
10629 (startpos (point-at-bol))
10630 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10631 (org-log-done org-log-done)
10632 (org-log-repeat org-log-repeat)
10633 (org-todo-log-states org-todo-log-states)
10634 (this (match-string 1))
10635 (hl-pos (match-beginning 0))
10636 (head (org-get-todo-sequence-head this))
10637 (ass (assoc head org-todo-kwd-alist))
10638 (interpret (nth 1 ass))
10639 (done-word (nth 3 ass))
10640 (final-done-word (nth 4 ass))
10641 (last-state (or this ""))
10642 (completion-ignore-case t)
10643 (member (member this org-todo-keywords-1))
10644 (tail (cdr member))
10645 (state (cond
10646 ((and org-todo-key-trigger
10647 (or (and (equal arg '(4))
10648 (eq org-use-fast-todo-selection 'prefix))
10649 (and (not arg) org-use-fast-todo-selection
10650 (not (eq org-use-fast-todo-selection
10651 'prefix)))))
10652 ;; Use fast selection
10653 (org-fast-todo-selection))
10654 ((and (equal arg '(4))
10655 (or (not org-use-fast-todo-selection)
10656 (not org-todo-key-trigger)))
10657 ;; Read a state with completion
10658 (org-icompleting-read
10659 "State: " (mapcar (lambda(x) (list x))
10660 org-todo-keywords-1)
10661 nil t))
10662 ((eq arg 'right)
10663 (if this
10664 (if tail (car tail) nil)
10665 (car org-todo-keywords-1)))
10666 ((eq arg 'left)
10667 (if (equal member org-todo-keywords-1)
10669 (if this
10670 (nth (- (length org-todo-keywords-1)
10671 (length tail) 2)
10672 org-todo-keywords-1)
10673 (org-last org-todo-keywords-1))))
10674 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10675 (setq arg nil))) ; hack to fall back to cycling
10676 (arg
10677 ;; user or caller requests a specific state
10678 (cond
10679 ((equal arg "") nil)
10680 ((eq arg 'none) nil)
10681 ((eq arg 'done) (or done-word (car org-done-keywords)))
10682 ((eq arg 'nextset)
10683 (or (car (cdr (member head org-todo-heads)))
10684 (car org-todo-heads)))
10685 ((eq arg 'previousset)
10686 (let ((org-todo-heads (reverse org-todo-heads)))
10687 (or (car (cdr (member head org-todo-heads)))
10688 (car org-todo-heads))))
10689 ((car (member arg org-todo-keywords-1)))
10690 ((stringp arg)
10691 (error "State `%s' not valid in this file" arg))
10692 ((nth (1- (prefix-numeric-value arg))
10693 org-todo-keywords-1))))
10694 ((null member) (or head (car org-todo-keywords-1)))
10695 ((equal this final-done-word) nil) ;; -> make empty
10696 ((null tail) nil) ;; -> first entry
10697 ((memq interpret '(type priority))
10698 (if (eq this-command last-command)
10699 (car tail)
10700 (if (> (length tail) 0)
10701 (or done-word (car org-done-keywords))
10702 nil)))
10704 (car tail))))
10705 (state (or
10706 (run-hook-with-args-until-success
10707 'org-todo-get-default-hook state last-state)
10708 state))
10709 (next (if state (concat " " state " ") " "))
10710 (change-plist (list :type 'todo-state-change :from this :to state
10711 :position startpos))
10712 dolog now-done-p)
10713 (when org-blocker-hook
10714 (setq org-last-todo-state-is-todo
10715 (not (member this org-done-keywords)))
10716 (unless (save-excursion
10717 (save-match-data
10718 (run-hook-with-args-until-failure
10719 'org-blocker-hook change-plist)))
10720 (if (interactive-p)
10721 (error "TODO state change from %s to %s blocked" this state)
10722 ;; fail silently
10723 (message "TODO state change from %s to %s blocked" this state)
10724 (throw 'exit nil))))
10725 (store-match-data match-data)
10726 (replace-match next t t)
10727 (unless (pos-visible-in-window-p hl-pos)
10728 (message "TODO state changed to %s" (org-trim next)))
10729 (unless head
10730 (setq head (org-get-todo-sequence-head state)
10731 ass (assoc head org-todo-kwd-alist)
10732 interpret (nth 1 ass)
10733 done-word (nth 3 ass)
10734 final-done-word (nth 4 ass)))
10735 (when (memq arg '(nextset previousset))
10736 (message "Keyword-Set %d/%d: %s"
10737 (- (length org-todo-sets) -1
10738 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10739 (length org-todo-sets)
10740 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10741 (setq org-last-todo-state-is-todo
10742 (not (member state org-done-keywords)))
10743 (setq now-done-p (and (member state org-done-keywords)
10744 (not (member this org-done-keywords))))
10745 (and logging (org-local-logging logging))
10746 (when (and (or org-todo-log-states org-log-done)
10747 (not (eq org-inhibit-logging t))
10748 (not (memq arg '(nextset previousset))))
10749 ;; we need to look at recording a time and note
10750 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10751 (nth 2 (assoc this org-todo-log-states))))
10752 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10753 (setq dolog 'time))
10754 (when (and state
10755 (member state org-not-done-keywords)
10756 (not (member this org-not-done-keywords)))
10757 ;; This is now a todo state and was not one before
10758 ;; If there was a CLOSED time stamp, get rid of it.
10759 (org-add-planning-info nil nil 'closed))
10760 (when (and now-done-p org-log-done)
10761 ;; It is now done, and it was not done before
10762 (org-add-planning-info 'closed (org-current-time))
10763 (if (and (not dolog) (eq 'note org-log-done))
10764 (org-add-log-setup 'done state this 'findpos 'note)))
10765 (when (and state dolog)
10766 ;; This is a non-nil state, and we need to log it
10767 (org-add-log-setup 'state state this 'findpos dolog)))
10768 ;; Fixup tag positioning
10769 (org-todo-trigger-tag-changes state)
10770 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10771 (when org-provide-todo-statistics
10772 (org-update-parent-todo-statistics))
10773 (run-hooks 'org-after-todo-state-change-hook)
10774 (if (and arg (not (member state org-done-keywords)))
10775 (setq head (org-get-todo-sequence-head state)))
10776 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10777 ;; Do we need to trigger a repeat?
10778 (when now-done-p
10779 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10780 ;; This is for the agenda, take a snapshot of the headline.
10781 (save-match-data
10782 (setq org-agenda-headline-snapshot-before-repeat
10783 (org-get-heading))))
10784 (org-auto-repeat-maybe state))
10785 ;; Fixup cursor location if close to the keyword
10786 (if (and (outline-on-heading-p)
10787 (not (bolp))
10788 (save-excursion (beginning-of-line 1)
10789 (looking-at org-todo-line-regexp))
10790 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10791 (progn
10792 (goto-char (or (match-end 2) (match-end 1)))
10793 (and (looking-at " ") (just-one-space))))
10794 (when org-trigger-hook
10795 (save-excursion
10796 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10798 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10799 "Block turning an entry into a TODO, using the hierarchy.
10800 This checks whether the current task should be blocked from state
10801 changes. Such blocking occurs when:
10803 1. The task has children which are not all in a completed state.
10805 2. A task has a parent with the property :ORDERED:, and there
10806 are siblings prior to the current task with incomplete
10807 status.
10809 3. The parent of the task is blocked because it has siblings that should
10810 be done first, or is child of a block grandparent TODO entry."
10812 (if (not org-enforce-todo-dependencies)
10813 t ; if locally turned off don't block
10814 (catch 'dont-block
10815 ;; If this is not a todo state change, or if this entry is already DONE,
10816 ;; do not block
10817 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10818 (member (plist-get change-plist :from)
10819 (cons 'done org-done-keywords))
10820 (member (plist-get change-plist :to)
10821 (cons 'todo org-not-done-keywords))
10822 (not (plist-get change-plist :to)))
10823 (throw 'dont-block t))
10824 ;; If this task has children, and any are undone, it's blocked
10825 (save-excursion
10826 (org-back-to-heading t)
10827 (let ((this-level (funcall outline-level)))
10828 (outline-next-heading)
10829 (let ((child-level (funcall outline-level)))
10830 (while (and (not (eobp))
10831 (> child-level this-level))
10832 ;; this todo has children, check whether they are all
10833 ;; completed
10834 (if (and (not (org-entry-is-done-p))
10835 (org-entry-is-todo-p))
10836 (throw 'dont-block nil))
10837 (outline-next-heading)
10838 (setq child-level (funcall outline-level))))))
10839 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10840 ;; any previous siblings are undone, it's blocked
10841 (save-excursion
10842 (org-back-to-heading t)
10843 (let* ((pos (point))
10844 (parent-pos (and (org-up-heading-safe) (point))))
10845 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10846 (when (and (org-entry-get (point) "ORDERED")
10847 (forward-line 1)
10848 (re-search-forward org-not-done-heading-regexp pos t))
10849 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10850 ;; Search further up the hierarchy, to see if an anchestor is blocked
10851 (while t
10852 (goto-char parent-pos)
10853 (if (not (looking-at org-not-done-heading-regexp))
10854 (throw 'dont-block t)) ; do not block, parent is not a TODO
10855 (setq pos (point))
10856 (setq parent-pos (and (org-up-heading-safe) (point)))
10857 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10858 (when (and (org-entry-get (point) "ORDERED")
10859 (forward-line 1)
10860 (re-search-forward org-not-done-heading-regexp pos t))
10861 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10863 (defcustom org-track-ordered-property-with-tag nil
10864 "Should the ORDERED property also be shown as a tag?
10865 The ORDERED property decides if an entry should require subtasks to be
10866 completed in sequence. Since a property is not very visible, setting
10867 this option means that toggling the ORDERED property with the command
10868 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10869 not relevant for the behavior, but it makes things more visible.
10871 Note that toggling the tag with tags commands will not change the property
10872 and therefore not influence behavior!
10874 This can be t, meaning the tag ORDERED should be used, It can also be a
10875 string to select a different tag for this task."
10876 :group 'org-todo
10877 :type '(choice
10878 (const :tag "No tracking" nil)
10879 (const :tag "Track with ORDERED tag" t)
10880 (string :tag "Use other tag")))
10882 (defun org-toggle-ordered-property ()
10883 "Toggle the ORDERED property of the current entry.
10884 For better visibility, you can track the value of this property with a tag.
10885 See variable `org-track-ordered-property-with-tag'."
10886 (interactive)
10887 (let* ((t1 org-track-ordered-property-with-tag)
10888 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10889 (save-excursion
10890 (org-back-to-heading)
10891 (if (org-entry-get nil "ORDERED")
10892 (progn
10893 (org-delete-property "ORDERED")
10894 (and tag (org-toggle-tag tag 'off))
10895 (message "Subtasks can be completed in arbitrary order"))
10896 (org-entry-put nil "ORDERED" "t")
10897 (and tag (org-toggle-tag tag 'on))
10898 (message "Subtasks must be completed in sequence")))))
10900 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10901 (defun org-block-todo-from-checkboxes (change-plist)
10902 "Block turning an entry into a TODO, using checkboxes.
10903 This checks whether the current task should be blocked from state
10904 changes because there are unchecked boxes in this entry."
10905 (if (not org-enforce-todo-checkbox-dependencies)
10906 t ; if locally turned off don't block
10907 (catch 'dont-block
10908 ;; If this is not a todo state change, or if this entry is already DONE,
10909 ;; do not block
10910 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10911 (member (plist-get change-plist :from)
10912 (cons 'done org-done-keywords))
10913 (member (plist-get change-plist :to)
10914 (cons 'todo org-not-done-keywords))
10915 (not (plist-get change-plist :to)))
10916 (throw 'dont-block t))
10917 ;; If this task has checkboxes that are not checked, it's blocked
10918 (save-excursion
10919 (org-back-to-heading t)
10920 (let ((beg (point)) end)
10921 (outline-next-heading)
10922 (setq end (point))
10923 (goto-char beg)
10924 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10925 end t)
10926 (progn
10927 (if (boundp 'org-blocked-by-checkboxes)
10928 (setq org-blocked-by-checkboxes t))
10929 (throw 'dont-block nil)))))
10930 t))) ; do not block
10932 (defun org-entry-blocked-p ()
10933 "Is the current entry blocked?"
10934 (if (org-entry-get nil "NOBLOCKING")
10935 nil ;; Never block this entry
10936 (not
10937 (run-hook-with-args-until-failure
10938 'org-blocker-hook
10939 (list :type 'todo-state-change
10940 :position (point)
10941 :from 'todo
10942 :to 'done)))))
10944 (defun org-update-statistics-cookies (all)
10945 "Update the statistics cookie, either from TODO or from checkboxes.
10946 This should be called with the cursor in a line with a statistics cookie."
10947 (interactive "P")
10948 (if all
10949 (progn
10950 (org-update-checkbox-count 'all)
10951 (org-map-entries 'org-update-parent-todo-statistics))
10952 (if (not (org-on-heading-p))
10953 (org-update-checkbox-count)
10954 (let ((pos (move-marker (make-marker) (point)))
10955 end l1 l2)
10956 (ignore-errors (org-back-to-heading t))
10957 (if (not (org-on-heading-p))
10958 (org-update-checkbox-count)
10959 (setq l1 (org-outline-level))
10960 (setq end (save-excursion
10961 (outline-next-heading)
10962 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10963 (point)))
10964 (if (and (save-excursion
10965 (re-search-forward
10966 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10967 (not (save-excursion (re-search-forward
10968 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10969 (org-update-checkbox-count)
10970 (if (and l2 (> l2 l1))
10971 (progn
10972 (goto-char end)
10973 (org-update-parent-todo-statistics))
10974 (goto-char pos)
10975 (beginning-of-line 1)
10976 (while (re-search-forward
10977 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10978 (point-at-eol) t)
10979 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10980 (goto-char pos)
10981 (move-marker pos nil)))))
10983 (defvar org-entry-property-inherited-from) ;; defined below
10984 (defun org-update-parent-todo-statistics ()
10985 "Update any statistics cookie in the parent of the current headline.
10986 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10987 the entire subtree and this will travel up the hierarchy and update
10988 statistics everywhere."
10989 (interactive)
10990 (let* ((lim 0) prop
10991 (recursive (or (not org-hierarchical-todo-statistics)
10992 (string-match
10993 "\\<recursive\\>"
10994 (or (setq prop (org-entry-get
10995 nil "COOKIE_DATA" 'inherit)) ""))))
10996 (lim (or (and prop (marker-position
10997 org-entry-property-inherited-from))
10998 lim))
10999 (first t)
11000 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11001 level ltoggle l1 new ndel
11002 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11003 (catch 'exit
11004 (save-excursion
11005 (beginning-of-line 1)
11006 (if (org-at-heading-p)
11007 (setq ltoggle (funcall outline-level))
11008 (error "This should not happen"))
11009 (while (and (setq level (org-up-heading-safe))
11010 (or recursive first)
11011 (>= (point) lim))
11012 (setq first nil cookie-present nil)
11013 (unless (and level
11014 (not (string-match
11015 "\\<checkbox\\>"
11016 (downcase
11017 (or (org-entry-get
11018 nil "COOKIE_DATA")
11019 "")))))
11020 (throw 'exit nil))
11021 (while (re-search-forward box-re (point-at-eol) t)
11022 (setq cnt-all 0 cnt-done 0 cookie-present t)
11023 (setq is-percent (match-end 2))
11024 (save-match-data
11025 (unless (outline-next-heading) (throw 'exit nil))
11026 (while (and (looking-at org-complex-heading-regexp)
11027 (> (setq l1 (length (match-string 1))) level))
11028 (setq kwd (and (or recursive (= l1 ltoggle))
11029 (match-string 2)))
11030 (if (or (eq org-provide-todo-statistics 'all-headlines)
11031 (and (listp org-provide-todo-statistics)
11032 (or (member kwd org-provide-todo-statistics)
11033 (member kwd org-done-keywords))))
11034 (setq cnt-all (1+ cnt-all))
11035 (if (eq org-provide-todo-statistics t)
11036 (and kwd (setq cnt-all (1+ cnt-all)))))
11037 (and (member kwd org-done-keywords)
11038 (setq cnt-done (1+ cnt-done)))
11039 (outline-next-heading)))
11040 (setq new
11041 (if is-percent
11042 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11043 (format "[%d/%d]" cnt-done cnt-all))
11044 ndel (- (match-end 0) (match-beginning 0)))
11045 (goto-char (match-beginning 0))
11046 (insert new)
11047 (delete-region (point) (+ (point) ndel)))
11048 (when cookie-present
11049 (run-hook-with-args 'org-after-todo-statistics-hook
11050 cnt-done (- cnt-all cnt-done))))))
11051 (run-hooks 'org-todo-statistics-hook)))
11053 (defvar org-after-todo-statistics-hook nil
11054 "Hook that is called after a TODO statistics cookie has been updated.
11055 Each function is called with two arguments: the number of not-done entries
11056 and the number of done entries.
11058 For example, the following function, when added to this hook, will switch
11059 an entry to DONE when all children are done, and back to TODO when new
11060 entries are set to a TODO status. Note that this hook is only called
11061 when there is a statistics cookie in the headline!
11063 (defun org-summary-todo (n-done n-not-done)
11064 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11065 (let (org-log-done org-log-states) ; turn off logging
11066 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11069 (defvar org-todo-statistics-hook nil
11070 "Hook that is run whenever Org thinks TODO statistics should be updated.
11071 This hook runs even if there is no statistics cookie present, in which case
11072 `org-after-todo-statistics-hook' would not run.")
11074 (defun org-todo-trigger-tag-changes (state)
11075 "Apply the changes defined in `org-todo-state-tags-triggers'."
11076 (let ((l org-todo-state-tags-triggers)
11077 changes)
11078 (when (or (not state) (equal state ""))
11079 (setq changes (append changes (cdr (assoc "" l)))))
11080 (when (and (stringp state) (> (length state) 0))
11081 (setq changes (append changes (cdr (assoc state l)))))
11082 (when (member state org-not-done-keywords)
11083 (setq changes (append changes (cdr (assoc 'todo l)))))
11084 (when (member state org-done-keywords)
11085 (setq changes (append changes (cdr (assoc 'done l)))))
11086 (dolist (c changes)
11087 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11089 (defun org-local-logging (value)
11090 "Get logging settings from a property VALUE."
11091 (let* (words w a)
11092 ;; directly set the variables, they are already local.
11093 (setq org-log-done nil
11094 org-log-repeat nil
11095 org-todo-log-states nil)
11096 (setq words (org-split-string value))
11097 (while (setq w (pop words))
11098 (cond
11099 ((setq a (assoc w org-startup-options))
11100 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11101 (set (nth 1 a) (nth 2 a))))
11102 ((setq a (org-extract-log-state-settings w))
11103 (and (member (car a) org-todo-keywords-1)
11104 (push a org-todo-log-states)))))))
11106 (defun org-get-todo-sequence-head (kwd)
11107 "Return the head of the TODO sequence to which KWD belongs.
11108 If KWD is not set, check if there is a text property remembering the
11109 right sequence."
11110 (let (p)
11111 (cond
11112 ((not kwd)
11113 (or (get-text-property (point-at-bol) 'org-todo-head)
11114 (progn
11115 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11116 nil (point-at-eol)))
11117 (get-text-property p 'org-todo-head))))
11118 ((not (member kwd org-todo-keywords-1))
11119 (car org-todo-keywords-1))
11120 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11122 (defun org-fast-todo-selection ()
11123 "Fast TODO keyword selection with single keys.
11124 Returns the new TODO keyword, or nil if no state change should occur."
11125 (let* ((fulltable org-todo-key-alist)
11126 (done-keywords org-done-keywords) ;; needed for the faces.
11127 (maxlen (apply 'max (mapcar
11128 (lambda (x)
11129 (if (stringp (car x)) (string-width (car x)) 0))
11130 fulltable)))
11131 (expert nil)
11132 (fwidth (+ maxlen 3 1 3))
11133 (ncol (/ (- (window-width) 4) fwidth))
11134 tg cnt e c tbl
11135 groups ingroup)
11136 (save-excursion
11137 (save-window-excursion
11138 (if expert
11139 (set-buffer (get-buffer-create " *Org todo*"))
11140 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11141 (erase-buffer)
11142 (org-set-local 'org-done-keywords done-keywords)
11143 (setq tbl fulltable cnt 0)
11144 (while (setq e (pop tbl))
11145 (cond
11146 ((equal e '(:startgroup))
11147 (push '() groups) (setq ingroup t)
11148 (when (not (= cnt 0))
11149 (setq cnt 0)
11150 (insert "\n"))
11151 (insert "{ "))
11152 ((equal e '(:endgroup))
11153 (setq ingroup nil cnt 0)
11154 (insert "}\n"))
11155 ((equal e '(:newline))
11156 (when (not (= cnt 0))
11157 (setq cnt 0)
11158 (insert "\n")
11159 (setq e (car tbl))
11160 (while (equal (car tbl) '(:newline))
11161 (insert "\n")
11162 (setq tbl (cdr tbl)))))
11164 (setq tg (car e) c (cdr e))
11165 (if ingroup (push tg (car groups)))
11166 (setq tg (org-add-props tg nil 'face
11167 (org-get-todo-face tg)))
11168 (if (and (= cnt 0) (not ingroup)) (insert " "))
11169 (insert "[" c "] " tg (make-string
11170 (- fwidth 4 (length tg)) ?\ ))
11171 (when (= (setq cnt (1+ cnt)) ncol)
11172 (insert "\n")
11173 (if ingroup (insert " "))
11174 (setq cnt 0)))))
11175 (insert "\n")
11176 (goto-char (point-min))
11177 (if (not expert) (org-fit-window-to-buffer))
11178 (message "[a-z..]:Set [SPC]:clear")
11179 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11180 (cond
11181 ((or (= c ?\C-g)
11182 (and (= c ?q) (not (rassoc c fulltable))))
11183 (setq quit-flag t))
11184 ((= c ?\ ) nil)
11185 ((setq e (rassoc c fulltable) tg (car e))
11187 (t (setq quit-flag t)))))))
11189 (defun org-entry-is-todo-p ()
11190 (member (org-get-todo-state) org-not-done-keywords))
11192 (defun org-entry-is-done-p ()
11193 (member (org-get-todo-state) org-done-keywords))
11195 (defun org-get-todo-state ()
11196 (save-excursion
11197 (org-back-to-heading t)
11198 (and (looking-at org-todo-line-regexp)
11199 (match-end 2)
11200 (match-string 2))))
11202 (defun org-at-date-range-p (&optional inactive-ok)
11203 "Is the cursor inside a date range?"
11204 (interactive)
11205 (save-excursion
11206 (catch 'exit
11207 (let ((pos (point)))
11208 (skip-chars-backward "^[<\r\n")
11209 (skip-chars-backward "<[")
11210 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11211 (>= (match-end 0) pos)
11212 (throw 'exit t))
11213 (skip-chars-backward "^<[\r\n")
11214 (skip-chars-backward "<[")
11215 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11216 (>= (match-end 0) pos)
11217 (throw 'exit t)))
11218 nil)))
11220 (defun org-get-repeat (&optional tagline)
11221 "Check if there is a deadline/schedule with repeater in this entry."
11222 (save-match-data
11223 (save-excursion
11224 (org-back-to-heading t)
11225 (and (re-search-forward (if tagline
11226 (concat tagline "\\s-*" org-repeat-re)
11227 org-repeat-re)
11228 (org-entry-end-position) t)
11229 (match-string-no-properties 1)))))
11231 (defvar org-last-changed-timestamp)
11232 (defvar org-last-inserted-timestamp)
11233 (defvar org-log-post-message)
11234 (defvar org-log-note-purpose)
11235 (defvar org-log-note-how)
11236 (defvar org-log-note-extra)
11237 (defun org-auto-repeat-maybe (done-word)
11238 "Check if the current headline contains a repeated deadline/schedule.
11239 If yes, set TODO state back to what it was and change the base date
11240 of repeating deadline/scheduled time stamps to new date.
11241 This function is run automatically after each state change to a DONE state."
11242 ;; last-state is dynamically scoped into this function
11243 (let* ((repeat (org-get-repeat))
11244 (aa (assoc last-state org-todo-kwd-alist))
11245 (interpret (nth 1 aa))
11246 (head (nth 2 aa))
11247 (whata '(("d" . day) ("m" . month) ("y" . year)))
11248 (msg "Entry repeats: ")
11249 (org-log-done nil)
11250 (org-todo-log-states nil)
11251 (nshiftmax 10) (nshift 0)
11252 re type n what ts time to-state)
11253 (when repeat
11254 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11255 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11256 org-todo-repeat-to-state))
11257 (unless (and to-state (member to-state org-todo-keywords-1))
11258 (setq to-state (if (eq interpret 'type) last-state head)))
11259 (org-todo to-state)
11260 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11261 (org-entry-put nil "LAST_REPEAT" (format-time-string
11262 (org-time-stamp-format t t))))
11263 (when org-log-repeat
11264 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11265 (memq 'org-add-log-note post-command-hook))
11266 ;; OK, we are already setup for some record
11267 (if (eq org-log-repeat 'note)
11268 ;; make sure we take a note, not only a time stamp
11269 (setq org-log-note-how 'note))
11270 ;; Set up for taking a record
11271 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11272 last-state
11273 'findpos org-log-repeat)))
11274 (org-back-to-heading t)
11275 (org-add-planning-info nil nil 'closed)
11276 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11277 org-deadline-time-regexp "\\)\\|\\("
11278 org-ts-regexp "\\)"))
11279 (while (re-search-forward
11280 re (save-excursion (outline-next-heading) (point)) t)
11281 (setq type (if (match-end 1) org-scheduled-string
11282 (if (match-end 3) org-deadline-string "Plain:"))
11283 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11284 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11285 (setq n (string-to-number (match-string 2 ts))
11286 what (match-string 3 ts))
11287 (if (equal what "w") (setq n (* n 7) what "d"))
11288 ;; Preparation, see if we need to modify the start date for the change
11289 (when (match-end 1)
11290 (setq time (save-match-data (org-time-string-to-time ts)))
11291 (cond
11292 ((equal (match-string 1 ts) ".")
11293 ;; Shift starting date to today
11294 (org-timestamp-change
11295 (- (time-to-days (current-time)) (time-to-days time))
11296 'day))
11297 ((equal (match-string 1 ts) "+")
11298 (while (or (= nshift 0)
11299 (<= (time-to-days time) (time-to-days (current-time))))
11300 (when (= (incf nshift) nshiftmax)
11301 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11302 (error "Abort")))
11303 (org-timestamp-change n (cdr (assoc what whata)))
11304 (org-at-timestamp-p t)
11305 (setq ts (match-string 1))
11306 (setq time (save-match-data (org-time-string-to-time ts))))
11307 (org-timestamp-change (- n) (cdr (assoc what whata)))
11308 ;; rematch, so that we have everything in place for the real shift
11309 (org-at-timestamp-p t)
11310 (setq ts (match-string 1))
11311 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11312 (org-timestamp-change n (cdr (assoc what whata)))
11313 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11314 (setq org-log-post-message msg)
11315 (message "%s" msg))))
11317 (defun org-show-todo-tree (arg)
11318 "Make a compact tree which shows all headlines marked with TODO.
11319 The tree will show the lines where the regexp matches, and all higher
11320 headlines above the match.
11321 With a \\[universal-argument] prefix, prompt for a regexp to match.
11322 With a numeric prefix N, construct a sparse tree for the Nth element
11323 of `org-todo-keywords-1'."
11324 (interactive "P")
11325 (let ((case-fold-search nil)
11326 (kwd-re
11327 (cond ((null arg) org-not-done-regexp)
11328 ((equal arg '(4))
11329 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11330 (mapcar 'list org-todo-keywords-1))))
11331 (concat "\\("
11332 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11333 "\\)\\>")))
11334 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11335 (regexp-quote (nth (1- (prefix-numeric-value arg))
11336 org-todo-keywords-1)))
11337 (t (error "Invalid prefix argument: %s" arg)))))
11338 (message "%d TODO entries found"
11339 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11341 (defun org-deadline (&optional remove time)
11342 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11343 With argument REMOVE, remove any deadline from the item.
11344 When TIME is set, it should be an internal time specification, and the
11345 scheduling will use the corresponding date."
11346 (interactive "P")
11347 (let* ((old-date (org-entry-get nil "DEADLINE"))
11348 (repeater (and old-date
11349 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11350 (match-string 1 old-date))))
11351 (if remove
11352 (progn
11353 (when (and old-date org-log-redeadline)
11354 (org-add-log-setup 'deldeadline nil old-date 'findpos
11355 org-log-redeadline))
11356 (org-remove-timestamp-with-keyword org-deadline-string)
11357 (message "Item no longer has a deadline."))
11358 (org-add-planning-info 'deadline time 'closed)
11359 (when (and old-date org-log-redeadline
11360 (not (equal old-date
11361 (substring org-last-inserted-timestamp 1 -1))))
11362 (org-add-log-setup 'redeadline nil old-date 'findpos
11363 org-log-redeadline))
11364 (when repeater
11365 (save-excursion
11366 (org-back-to-heading t)
11367 (when (re-search-forward (concat org-deadline-string " "
11368 org-last-inserted-timestamp)
11369 (save-excursion
11370 (outline-next-heading) (point)) t)
11371 (goto-char (1- (match-end 0)))
11372 (insert " " repeater)
11373 (setq org-last-inserted-timestamp
11374 (concat (substring org-last-inserted-timestamp 0 -1)
11375 " " repeater
11376 (substring org-last-inserted-timestamp -1))))))
11377 (message "Deadline on %s" org-last-inserted-timestamp))))
11379 (defun org-schedule (&optional remove time)
11380 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11381 With argument REMOVE, remove any scheduling date from the item.
11382 When TIME is set, it should be an internal time specification, and the
11383 scheduling will use the corresponding date."
11384 (interactive "P")
11385 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11386 (repeater (and old-date
11387 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11388 (match-string 1 old-date))))
11389 (if remove
11390 (progn
11391 (when (and old-date org-log-reschedule)
11392 (org-add-log-setup 'delschedule nil old-date 'findpos
11393 org-log-reschedule))
11394 (org-remove-timestamp-with-keyword org-scheduled-string)
11395 (message "Item is no longer scheduled."))
11396 (org-add-planning-info 'scheduled time 'closed)
11397 (when (and old-date org-log-reschedule
11398 (not (equal old-date
11399 (substring org-last-inserted-timestamp 1 -1))))
11400 (org-add-log-setup 'reschedule nil old-date 'findpos
11401 org-log-reschedule))
11402 (when repeater
11403 (save-excursion
11404 (org-back-to-heading t)
11405 (when (re-search-forward (concat org-scheduled-string " "
11406 org-last-inserted-timestamp)
11407 (save-excursion
11408 (outline-next-heading) (point)) t)
11409 (goto-char (1- (match-end 0)))
11410 (insert " " repeater)
11411 (setq org-last-inserted-timestamp
11412 (concat (substring org-last-inserted-timestamp 0 -1)
11413 " " repeater
11414 (substring org-last-inserted-timestamp -1))))))
11415 (message "Scheduled to %s" org-last-inserted-timestamp))))
11417 (defun org-get-scheduled-time (pom &optional inherit)
11418 "Get the scheduled time as a time tuple, of a format suitable
11419 for calling org-schedule with, or if there is no scheduling,
11420 returns nil."
11421 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11422 (when time
11423 (apply 'encode-time (org-parse-time-string time)))))
11425 (defun org-get-deadline-time (pom &optional inherit)
11426 "Get the deadine as a time tuple, of a format suitable for
11427 calling org-deadline with, or if there is no scheduling, returns
11428 nil."
11429 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11430 (when time
11431 (apply 'encode-time (org-parse-time-string time)))))
11433 (defun org-remove-timestamp-with-keyword (keyword)
11434 "Remove all time stamps with KEYWORD in the current entry."
11435 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11436 beg)
11437 (save-excursion
11438 (org-back-to-heading t)
11439 (setq beg (point))
11440 (outline-next-heading)
11441 (while (re-search-backward re beg t)
11442 (replace-match "")
11443 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11444 (equal (char-before) ?\ ))
11445 (backward-delete-char 1)
11446 (if (string-match "^[ \t]*$" (buffer-substring
11447 (point-at-bol) (point-at-eol)))
11448 (delete-region (point-at-bol)
11449 (min (point-max) (1+ (point-at-eol))))))))))
11451 (defun org-add-planning-info (what &optional time &rest remove)
11452 "Insert new timestamp with keyword in the line directly after the headline.
11453 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11454 If non is given, the user is prompted for a date.
11455 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11456 be removed."
11457 (interactive)
11458 (let (org-time-was-given org-end-time-was-given ts
11459 end default-time default-input)
11461 (catch 'exit
11462 (when (and (not time) (memq what '(scheduled deadline)))
11463 ;; Try to get a default date/time from existing timestamp
11464 (save-excursion
11465 (org-back-to-heading t)
11466 (setq end (save-excursion (outline-next-heading) (point)))
11467 (when (re-search-forward (if (eq what 'scheduled)
11468 org-scheduled-time-regexp
11469 org-deadline-time-regexp)
11470 end t)
11471 (setq ts (match-string 1)
11472 default-time
11473 (apply 'encode-time (org-parse-time-string ts))
11474 default-input (and ts (org-get-compact-tod ts))))))
11475 (when what
11476 ;; If necessary, get the time from the user
11477 (setq time (or time (org-read-date nil 'to-time nil nil
11478 default-time default-input))))
11480 (when (and org-insert-labeled-timestamps-at-point
11481 (member what '(scheduled deadline)))
11482 (insert
11483 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11484 (org-insert-time-stamp time org-time-was-given
11485 nil nil nil (list org-end-time-was-given))
11486 (setq what nil))
11487 (save-excursion
11488 (save-restriction
11489 (let (col list elt ts buffer-invisibility-spec)
11490 (org-back-to-heading t)
11491 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11492 (goto-char (match-end 1))
11493 (setq col (current-column))
11494 (goto-char (match-end 0))
11495 (if (eobp) (insert "\n") (forward-char 1))
11496 (when (and (not what)
11497 (not (looking-at
11498 (concat "[ \t]*"
11499 org-keyword-time-not-clock-regexp))))
11500 ;; Nothing to add, nothing to remove...... :-)
11501 (throw 'exit nil))
11502 (if (and (not (looking-at outline-regexp))
11503 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11504 "[^\r\n]*"))
11505 (not (equal (match-string 1) org-clock-string)))
11506 (narrow-to-region (match-beginning 0) (match-end 0))
11507 (insert-before-markers "\n")
11508 (backward-char 1)
11509 (narrow-to-region (point) (point))
11510 (and org-adapt-indentation (org-indent-to-column col)))
11511 ;; Check if we have to remove something.
11512 (setq list (cons what remove))
11513 (while list
11514 (setq elt (pop list))
11515 (goto-char (point-min))
11516 (when (or (and (eq elt 'scheduled)
11517 (re-search-forward org-scheduled-time-regexp nil t))
11518 (and (eq elt 'deadline)
11519 (re-search-forward org-deadline-time-regexp nil t))
11520 (and (eq elt 'closed)
11521 (re-search-forward org-closed-time-regexp nil t)))
11522 (replace-match "")
11523 (if (looking-at "--+<[^>]+>") (replace-match ""))
11524 (skip-chars-backward " ")
11525 (if (looking-at " +") (replace-match ""))))
11526 (goto-char (point-max))
11527 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11528 (when what
11529 (insert
11530 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11531 (cond ((eq what 'scheduled) org-scheduled-string)
11532 ((eq what 'deadline) org-deadline-string)
11533 ((eq what 'closed) org-closed-string))
11534 " ")
11535 (setq ts (org-insert-time-stamp
11536 time
11537 (or org-time-was-given
11538 (and (eq what 'closed) org-log-done-with-time))
11539 (eq what 'closed)
11540 nil nil (list org-end-time-was-given)))
11541 (end-of-line 1))
11542 (goto-char (point-min))
11543 (widen)
11544 (if (and (looking-at "[ \t]*\n")
11545 (equal (char-before) ?\n))
11546 (delete-region (1- (point)) (point-at-eol)))
11547 ts))))))
11549 (defvar org-log-note-marker (make-marker))
11550 (defvar org-log-note-purpose nil)
11551 (defvar org-log-note-state nil)
11552 (defvar org-log-note-previous-state nil)
11553 (defvar org-log-note-how nil)
11554 (defvar org-log-note-extra nil)
11555 (defvar org-log-note-window-configuration nil)
11556 (defvar org-log-note-return-to (make-marker))
11557 (defvar org-log-post-message nil
11558 "Message to be displayed after a log note has been stored.
11559 The auto-repeater uses this.")
11561 (defun org-add-note ()
11562 "Add a note to the current entry.
11563 This is done in the same way as adding a state change note."
11564 (interactive)
11565 (org-add-log-setup 'note nil nil 'findpos nil))
11567 (defvar org-property-end-re)
11568 (defun org-add-log-setup (&optional purpose state prev-state
11569 findpos how &optional extra)
11570 "Set up the post command hook to take a note.
11571 If this is about to TODO state change, the new state is expected in STATE.
11572 When FINDPOS is non-nil, find the correct position for the note in
11573 the current entry. If not, assume that it can be inserted at point.
11574 HOW is an indicator what kind of note should be created.
11575 EXTRA is additional text that will be inserted into the notes buffer."
11576 (let* ((org-log-into-drawer (org-log-into-drawer))
11577 (drawer (cond ((stringp org-log-into-drawer)
11578 org-log-into-drawer)
11579 (org-log-into-drawer "LOGBOOK")
11580 (t nil))))
11581 (save-restriction
11582 (save-excursion
11583 (when findpos
11584 (org-back-to-heading t)
11585 (narrow-to-region (point) (save-excursion
11586 (outline-next-heading) (point)))
11587 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11588 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11589 "[^\r\n]*\\)?"))
11590 (goto-char (match-end 0))
11591 (cond
11592 (drawer
11593 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11594 nil t)
11595 (progn
11596 (goto-char (match-end 0))
11597 (or org-log-states-order-reversed
11598 (and (re-search-forward org-property-end-re nil t)
11599 (goto-char (1- (match-beginning 0))))))
11600 (insert "\n:" drawer ":\n:END:")
11601 (beginning-of-line 0)
11602 (org-indent-line-function)
11603 (beginning-of-line 2)
11604 (org-indent-line-function)
11605 (end-of-line 0)))
11606 ((and org-log-state-notes-insert-after-drawers
11607 (save-excursion
11608 (forward-line) (looking-at org-drawer-regexp)))
11609 (forward-line)
11610 (while (looking-at org-drawer-regexp)
11611 (goto-char (match-end 0))
11612 (re-search-forward org-property-end-re (point-max) t)
11613 (forward-line))
11614 (forward-line -1)))
11615 (unless org-log-states-order-reversed
11616 (and (= (char-after) ?\n) (forward-char 1))
11617 (org-skip-over-state-notes)
11618 (skip-chars-backward " \t\n\r")))
11619 (move-marker org-log-note-marker (point))
11620 (setq org-log-note-purpose purpose
11621 org-log-note-state state
11622 org-log-note-previous-state prev-state
11623 org-log-note-how how
11624 org-log-note-extra extra)
11625 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11627 (defun org-skip-over-state-notes ()
11628 "Skip past the list of State notes in an entry."
11629 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11630 (while (looking-at "[ \t]*- State")
11631 (condition-case nil
11632 (org-next-item)
11633 (error (org-end-of-item)))))
11635 (defun org-add-log-note (&optional purpose)
11636 "Pop up a window for taking a note, and add this note later at point."
11637 (remove-hook 'post-command-hook 'org-add-log-note)
11638 (setq org-log-note-window-configuration (current-window-configuration))
11639 (delete-other-windows)
11640 (move-marker org-log-note-return-to (point))
11641 (switch-to-buffer (marker-buffer org-log-note-marker))
11642 (goto-char org-log-note-marker)
11643 (org-switch-to-buffer-other-window "*Org Note*")
11644 (erase-buffer)
11645 (if (memq org-log-note-how '(time state))
11646 (let (current-prefix-arg) (org-store-log-note))
11647 (let ((org-inhibit-startup t)) (org-mode))
11648 (insert (format "# Insert note for %s.
11649 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11650 (cond
11651 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11652 ((eq org-log-note-purpose 'done) "closed todo item")
11653 ((eq org-log-note-purpose 'state)
11654 (format "state change from \"%s\" to \"%s\""
11655 (or org-log-note-previous-state "")
11656 (or org-log-note-state "")))
11657 ((eq org-log-note-purpose 'reschedule)
11658 "rescheduling")
11659 ((eq org-log-note-purpose 'delschedule)
11660 "no longer scheduled")
11661 ((eq org-log-note-purpose 'redeadline)
11662 "changing deadline")
11663 ((eq org-log-note-purpose 'deldeadline)
11664 "removing deadline")
11665 ((eq org-log-note-purpose 'refile)
11666 "refiling")
11667 ((eq org-log-note-purpose 'note)
11668 "this entry")
11669 (t (error "This should not happen")))))
11670 (if org-log-note-extra (insert org-log-note-extra))
11671 (org-set-local 'org-finish-function 'org-store-log-note)))
11673 (defvar org-note-abort nil) ; dynamically scoped
11674 (defun org-store-log-note ()
11675 "Finish taking a log note, and insert it to where it belongs."
11676 (let ((txt (buffer-string))
11677 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11678 lines ind)
11679 (kill-buffer (current-buffer))
11680 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11681 (setq txt (replace-match "" t t txt)))
11682 (if (string-match "\\s-+\\'" txt)
11683 (setq txt (replace-match "" t t txt)))
11684 (setq lines (org-split-string txt "\n"))
11685 (when (and note (string-match "\\S-" note))
11686 (setq note
11687 (org-replace-escapes
11688 note
11689 (list (cons "%u" (user-login-name))
11690 (cons "%U" user-full-name)
11691 (cons "%t" (format-time-string
11692 (org-time-stamp-format 'long 'inactive)
11693 (current-time)))
11694 (cons "%T" (format-time-string
11695 (org-time-stamp-format 'long nil)
11696 (current-time)))
11697 (cons "%s" (if org-log-note-state
11698 (concat "\"" org-log-note-state "\"")
11699 ""))
11700 (cons "%S" (if org-log-note-previous-state
11701 (concat "\"" org-log-note-previous-state "\"")
11702 "\"\"")))))
11703 (if lines (setq note (concat note " \\\\")))
11704 (push note lines))
11705 (when (or current-prefix-arg org-note-abort)
11706 (when org-log-into-drawer
11707 (org-remove-empty-drawer-at
11708 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11709 org-log-note-marker))
11710 (setq lines nil))
11711 (when lines
11712 (with-current-buffer (marker-buffer org-log-note-marker)
11713 (save-excursion
11714 (goto-char org-log-note-marker)
11715 (move-marker org-log-note-marker nil)
11716 (end-of-line 1)
11717 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11718 (insert "- " (pop lines))
11719 (org-indent-line-function)
11720 (beginning-of-line 1)
11721 (looking-at "[ \t]*")
11722 (setq ind (concat (match-string 0) " "))
11723 (end-of-line 1)
11724 (while lines (insert "\n" ind (pop lines)))
11725 (message "Note stored")
11726 (org-back-to-heading t)
11727 (org-cycle-hide-drawers 'children)))))
11728 (set-window-configuration org-log-note-window-configuration)
11729 (with-current-buffer (marker-buffer org-log-note-return-to)
11730 (goto-char org-log-note-return-to))
11731 (move-marker org-log-note-return-to nil)
11732 (and org-log-post-message (message "%s" org-log-post-message)))
11734 (defun org-remove-empty-drawer-at (drawer pos)
11735 "Remove an empty drawer DRAWER at position POS.
11736 POS may also be a marker."
11737 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11738 (save-excursion
11739 (save-restriction
11740 (widen)
11741 (goto-char pos)
11742 (if (org-in-regexp
11743 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11744 (replace-match ""))))))
11746 (defun org-sparse-tree (&optional arg)
11747 "Create a sparse tree, prompt for the details.
11748 This command can create sparse trees. You first need to select the type
11749 of match used to create the tree:
11751 t Show all TODO entries.
11752 T Show entries with a specific TODO keyword.
11753 m Show entries selected by a tags/property match.
11754 p Enter a property name and its value (both with completion on existing
11755 names/values) and show entries with that property.
11756 / Show entries matching a regular expression (`r' can be used as well)
11757 d Show deadlines due within `org-deadline-warning-days'.
11758 b Show deadlines and scheduled items before a date.
11759 a Show deadlines and scheduled items after a date."
11760 (interactive "P")
11761 (let (ans kwd value)
11762 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11763 (setq ans (read-char-exclusive))
11764 (cond
11765 ((equal ans ?d)
11766 (call-interactively 'org-check-deadlines))
11767 ((equal ans ?b)
11768 (call-interactively 'org-check-before-date))
11769 ((equal ans ?a)
11770 (call-interactively 'org-check-after-date))
11771 ((equal ans ?t)
11772 (org-show-todo-tree nil))
11773 ((equal ans ?T)
11774 (org-show-todo-tree '(4)))
11775 ((member ans '(?T ?m))
11776 (call-interactively 'org-match-sparse-tree))
11777 ((member ans '(?p ?P))
11778 (setq kwd (org-icompleting-read "Property: "
11779 (mapcar 'list (org-buffer-property-keys))))
11780 (setq value (org-icompleting-read "Value: "
11781 (mapcar 'list (org-property-values kwd))))
11782 (unless (string-match "\\`{.*}\\'" value)
11783 (setq value (concat "\"" value "\"")))
11784 (org-match-sparse-tree arg (concat kwd "=" value)))
11785 ((member ans '(?r ?R ?/))
11786 (call-interactively 'org-occur))
11787 (t (error "No such sparse tree command \"%c\"" ans)))))
11789 (defvar org-occur-highlights nil
11790 "List of overlays used for occur matches.")
11791 (make-variable-buffer-local 'org-occur-highlights)
11792 (defvar org-occur-parameters nil
11793 "Parameters of the active org-occur calls.
11794 This is a list, each call to org-occur pushes as cons cell,
11795 containing the regular expression and the callback, onto the list.
11796 The list can contain several entries if `org-occur' has been called
11797 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11798 will only contain one set of parameters. When the highlights are
11799 removed (for example with `C-c C-c', or with the next edit (depending
11800 on `org-remove-highlights-with-change'), this variable is emptied
11801 as well.")
11802 (make-variable-buffer-local 'org-occur-parameters)
11804 (defun org-occur (regexp &optional keep-previous callback)
11805 "Make a compact tree which shows all matches of REGEXP.
11806 The tree will show the lines where the regexp matches, and all higher
11807 headlines above the match. It will also show the heading after the match,
11808 to make sure editing the matching entry is easy.
11809 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11810 call to `org-occur' will be kept, to allow stacking of calls to this
11811 command.
11812 If CALLBACK is non-nil, it is a function which is called to confirm
11813 that the match should indeed be shown."
11814 (interactive "sRegexp: \nP")
11815 (when (equal regexp "")
11816 (error "Regexp cannot be empty"))
11817 (unless keep-previous
11818 (org-remove-occur-highlights nil nil t))
11819 (push (cons regexp callback) org-occur-parameters)
11820 (let ((cnt 0))
11821 (save-excursion
11822 (goto-char (point-min))
11823 (if (or (not keep-previous) ; do not want to keep
11824 (not org-occur-highlights)) ; no previous matches
11825 ;; hide everything
11826 (org-overview))
11827 (while (re-search-forward regexp nil t)
11828 (when (or (not callback)
11829 (save-match-data (funcall callback)))
11830 (setq cnt (1+ cnt))
11831 (when org-highlight-sparse-tree-matches
11832 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11833 (org-show-context 'occur-tree))))
11834 (when org-remove-highlights-with-change
11835 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11836 nil 'local))
11837 (unless org-sparse-tree-open-archived-trees
11838 (org-hide-archived-subtrees (point-min) (point-max)))
11839 (run-hooks 'org-occur-hook)
11840 (if (interactive-p)
11841 (message "%d match(es) for regexp %s" cnt regexp))
11842 cnt))
11844 (defun org-show-context (&optional key)
11845 "Make sure point and context are visible.
11846 How much context is shown depends upon the variables
11847 `org-show-hierarchy-above', `org-show-following-heading'. and
11848 `org-show-siblings'."
11849 (let ((heading-p (org-on-heading-p t))
11850 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11851 (following-p (org-get-alist-option org-show-following-heading key))
11852 (entry-p (org-get-alist-option org-show-entry-below key))
11853 (siblings-p (org-get-alist-option org-show-siblings key)))
11854 (catch 'exit
11855 ;; Show heading or entry text
11856 (if (and heading-p (not entry-p))
11857 (org-flag-heading nil) ; only show the heading
11858 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11859 (org-show-hidden-entry))) ; show entire entry
11860 (when following-p
11861 ;; Show next sibling, or heading below text
11862 (save-excursion
11863 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11864 (org-flag-heading nil))))
11865 (when siblings-p (org-show-siblings))
11866 (when hierarchy-p
11867 ;; show all higher headings, possibly with siblings
11868 (save-excursion
11869 (while (and (condition-case nil
11870 (progn (org-up-heading-all 1) t)
11871 (error nil))
11872 (not (bobp)))
11873 (org-flag-heading nil)
11874 (when siblings-p (org-show-siblings))))))))
11876 (defvar org-reveal-start-hook nil
11877 "Hook run before revealing a location.")
11879 (defun org-reveal (&optional siblings)
11880 "Show current entry, hierarchy above it, and the following headline.
11881 This can be used to show a consistent set of context around locations
11882 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11883 not t for the search context.
11885 With optional argument SIBLINGS, on each level of the hierarchy all
11886 siblings are shown. This repairs the tree structure to what it would
11887 look like when opened with hierarchical calls to `org-cycle'.
11888 With double optional argument `C-u C-u', go to the parent and show the
11889 entire tree."
11890 (interactive "P")
11891 (run-hooks 'org-reveal-start-hook)
11892 (let ((org-show-hierarchy-above t)
11893 (org-show-following-heading t)
11894 (org-show-siblings (if siblings t org-show-siblings)))
11895 (org-show-context nil))
11896 (when (equal siblings '(16))
11897 (save-excursion
11898 (when (org-up-heading-safe)
11899 (org-show-subtree)
11900 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11902 (defun org-highlight-new-match (beg end)
11903 "Highlight from BEG to END and mark the highlight is an occur headline."
11904 (let ((ov (make-overlay beg end)))
11905 (overlay-put ov 'face 'secondary-selection)
11906 (push ov org-occur-highlights)))
11908 (defun org-remove-occur-highlights (&optional beg end noremove)
11909 "Remove the occur highlights from the buffer.
11910 BEG and END are ignored. If NOREMOVE is nil, remove this function
11911 from the `before-change-functions' in the current buffer."
11912 (interactive)
11913 (unless org-inhibit-highlight-removal
11914 (mapc 'delete-overlay org-occur-highlights)
11915 (setq org-occur-highlights nil)
11916 (setq org-occur-parameters nil)
11917 (unless noremove
11918 (remove-hook 'before-change-functions
11919 'org-remove-occur-highlights 'local))))
11921 ;;;; Priorities
11923 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11924 "Regular expression matching the priority indicator.")
11926 (defvar org-remove-priority-next-time nil)
11928 (defun org-priority-up ()
11929 "Increase the priority of the current item."
11930 (interactive)
11931 (org-priority 'up))
11933 (defun org-priority-down ()
11934 "Decrease the priority of the current item."
11935 (interactive)
11936 (org-priority 'down))
11938 (defun org-priority (&optional action)
11939 "Change the priority of an item by ARG.
11940 ACTION can be `set', `up', `down', or a character."
11941 (interactive)
11942 (unless org-enable-priority-commands
11943 (error "Priority commands are disabled"))
11944 (setq action (or action 'set))
11945 (let (current new news have remove)
11946 (save-excursion
11947 (org-back-to-heading t)
11948 (if (looking-at org-priority-regexp)
11949 (setq current (string-to-char (match-string 2))
11950 have t)
11951 (setq current org-default-priority))
11952 (cond
11953 ((eq action 'remove)
11954 (setq remove t new ?\ ))
11955 ((or (eq action 'set)
11956 (if (featurep 'xemacs) (characterp action) (integerp action)))
11957 (if (not (eq action 'set))
11958 (setq new action)
11959 (message "Priority %c-%c, SPC to remove: "
11960 org-highest-priority org-lowest-priority)
11961 (setq new (read-char-exclusive)))
11962 (if (and (= (upcase org-highest-priority) org-highest-priority)
11963 (= (upcase org-lowest-priority) org-lowest-priority))
11964 (setq new (upcase new)))
11965 (cond ((equal new ?\ ) (setq remove t))
11966 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11967 (error "Priority must be between `%c' and `%c'"
11968 org-highest-priority org-lowest-priority))))
11969 ((eq action 'up)
11970 (if (and (not have) (eq last-command this-command))
11971 (setq new org-lowest-priority)
11972 (setq new (if (and org-priority-start-cycle-with-default (not have))
11973 org-default-priority (1- current)))))
11974 ((eq action 'down)
11975 (if (and (not have) (eq last-command this-command))
11976 (setq new org-highest-priority)
11977 (setq new (if (and org-priority-start-cycle-with-default (not have))
11978 org-default-priority (1+ current)))))
11979 (t (error "Invalid action")))
11980 (if (or (< (upcase new) org-highest-priority)
11981 (> (upcase new) org-lowest-priority))
11982 (setq remove t))
11983 (setq news (format "%c" new))
11984 (if have
11985 (if remove
11986 (replace-match "" t t nil 1)
11987 (replace-match news t t nil 2))
11988 (if remove
11989 (error "No priority cookie found in line")
11990 (let ((case-fold-search nil))
11991 (looking-at org-todo-line-regexp))
11992 (if (match-end 2)
11993 (progn
11994 (goto-char (match-end 2))
11995 (insert " [#" news "]"))
11996 (goto-char (match-beginning 3))
11997 (insert "[#" news "] "))))
11998 (org-preserve-lc (org-set-tags nil 'align)))
11999 (if remove
12000 (message "Priority removed")
12001 (message "Priority of current item set to %s" news))))
12003 (defun org-get-priority (s)
12004 "Find priority cookie and return priority."
12005 (save-match-data
12006 (if (not (string-match org-priority-regexp s))
12007 (* 1000 (- org-lowest-priority org-default-priority))
12008 (* 1000 (- org-lowest-priority
12009 (string-to-char (match-string 2 s)))))))
12011 ;;;; Tags
12013 (defvar org-agenda-archives-mode)
12014 (defvar org-map-continue-from nil
12015 "Position from where mapping should continue.
12016 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12018 (defvar org-scanner-tags nil
12019 "The current tag list while the tags scanner is running.")
12020 (defvar org-trust-scanner-tags nil
12021 "Should `org-get-tags-at' use the tags fro the scanner.
12022 This is for internal dynamical scoping only.
12023 When this is non-nil, the function `org-get-tags-at' will return the value
12024 of `org-scanner-tags' instead of building the list by itself. This
12025 can lead to large speed-ups when the tags scanner is used in a file with
12026 many entries, and when the list of tags is retrieved, for example to
12027 obtain a list of properties. Building the tags list for each entry in such
12028 a file becomes an N^2 operation - but with this variable set, it scales
12029 as N.")
12031 (defun org-scan-tags (action matcher &optional todo-only)
12032 "Scan headline tags with inheritance and produce output ACTION.
12034 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12035 or `agenda' to produce an entry list for an agenda view. It can also be
12036 a Lisp form or a function that should be called at each matched headline, in
12037 this case the return value is a list of all return values from these calls.
12039 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12040 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12041 only lines with a TODO keyword are included in the output."
12042 (require 'org-agenda)
12043 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12044 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12045 (org-re
12046 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12047 (props (list 'face 'default
12048 'done-face 'org-agenda-done
12049 'undone-face 'default
12050 'mouse-face 'highlight
12051 'org-not-done-regexp org-not-done-regexp
12052 'org-todo-regexp org-todo-regexp
12053 'help-echo
12054 (format "mouse-2 or RET jump to org file %s"
12055 (abbreviate-file-name
12056 (or (buffer-file-name (buffer-base-buffer))
12057 (buffer-name (buffer-base-buffer)))))))
12058 (case-fold-search nil)
12059 (org-map-continue-from nil)
12060 lspos tags tags-list
12061 (tags-alist (list (cons 0 org-file-tags)))
12062 (llast 0) rtn rtn1 level category i txt
12063 todo marker entry priority)
12064 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12065 (setq action (list 'lambda nil action)))
12066 (save-excursion
12067 (goto-char (point-min))
12068 (when (eq action 'sparse-tree)
12069 (org-overview)
12070 (org-remove-occur-highlights))
12071 (while (re-search-forward re nil t)
12072 (catch :skip
12073 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12074 tags (if (match-end 4) (org-match-string-no-properties 4)))
12075 (goto-char (setq lspos (match-beginning 0)))
12076 (setq level (org-reduced-level (funcall outline-level))
12077 category (org-get-category))
12078 (setq i llast llast level)
12079 ;; remove tag lists from same and sublevels
12080 (while (>= i level)
12081 (when (setq entry (assoc i tags-alist))
12082 (setq tags-alist (delete entry tags-alist)))
12083 (setq i (1- i)))
12084 ;; add the next tags
12085 (when tags
12086 (setq tags (org-split-string tags ":")
12087 tags-alist
12088 (cons (cons level tags) tags-alist)))
12089 ;; compile tags for current headline
12090 (setq tags-list
12091 (if org-use-tag-inheritance
12092 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12093 tags)
12094 org-scanner-tags tags-list)
12095 (when org-use-tag-inheritance
12096 (setcdr (car tags-alist)
12097 (mapcar (lambda (x)
12098 (setq x (copy-sequence x))
12099 (org-add-prop-inherited x))
12100 (cdar tags-alist))))
12101 (when (and tags org-use-tag-inheritance
12102 (or (not (eq t org-use-tag-inheritance))
12103 org-tags-exclude-from-inheritance))
12104 ;; selective inheritance, remove uninherited ones
12105 (setcdr (car tags-alist)
12106 (org-remove-uniherited-tags (cdar tags-alist))))
12107 (when (and (or (not todo-only)
12108 (and (member todo org-not-done-keywords)
12109 (or (not org-agenda-tags-todo-honor-ignore-options)
12110 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12111 (let ((case-fold-search t)) (eval matcher))
12113 (not (member org-archive-tag tags-list))
12114 ;; we have an archive tag, should we use this anyway?
12115 (or (not org-agenda-skip-archived-trees)
12116 (and (eq action 'agenda) org-agenda-archives-mode))))
12117 (unless (eq action 'sparse-tree) (org-agenda-skip))
12119 ;; select this headline
12121 (cond
12122 ((eq action 'sparse-tree)
12123 (and org-highlight-sparse-tree-matches
12124 (org-get-heading) (match-end 0)
12125 (org-highlight-new-match
12126 (match-beginning 0) (match-beginning 1)))
12127 (org-show-context 'tags-tree))
12128 ((eq action 'agenda)
12129 (setq txt (org-format-agenda-item
12131 (concat
12132 (if (eq org-tags-match-list-sublevels 'indented)
12133 (make-string (1- level) ?.) "")
12134 (org-get-heading))
12135 category
12136 tags-list
12138 priority (org-get-priority txt))
12139 (goto-char lspos)
12140 (setq marker (org-agenda-new-marker))
12141 (org-add-props txt props
12142 'org-marker marker 'org-hd-marker marker 'org-category category
12143 'todo-state todo
12144 'priority priority 'type "tagsmatch")
12145 (push txt rtn))
12146 ((functionp action)
12147 (setq org-map-continue-from nil)
12148 (save-excursion
12149 (setq rtn1 (funcall action))
12150 (push rtn1 rtn)))
12151 (t (error "Invalid action")))
12153 ;; if we are to skip sublevels, jump to end of subtree
12154 (unless org-tags-match-list-sublevels
12155 (org-end-of-subtree t)
12156 (backward-char 1))))
12157 ;; Get the correct position from where to continue
12158 (if org-map-continue-from
12159 (goto-char org-map-continue-from)
12160 (and (= (point) lspos) (end-of-line 1)))))
12161 (when (and (eq action 'sparse-tree)
12162 (not org-sparse-tree-open-archived-trees))
12163 (org-hide-archived-subtrees (point-min) (point-max)))
12164 (nreverse rtn)))
12166 (defun org-remove-uniherited-tags (tags)
12167 "Remove all tags that are not inherited from the list TAGS."
12168 (cond
12169 ((eq org-use-tag-inheritance t)
12170 (if org-tags-exclude-from-inheritance
12171 (org-delete-all org-tags-exclude-from-inheritance tags)
12172 tags))
12173 ((not org-use-tag-inheritance) nil)
12174 ((stringp org-use-tag-inheritance)
12175 (delq nil (mapcar
12176 (lambda (x)
12177 (if (and (string-match org-use-tag-inheritance x)
12178 (not (member x org-tags-exclude-from-inheritance)))
12179 x nil))
12180 tags)))
12181 ((listp org-use-tag-inheritance)
12182 (delq nil (mapcar
12183 (lambda (x)
12184 (if (member x org-use-tag-inheritance) x nil))
12185 tags)))))
12187 (defvar todo-only) ;; dynamically scoped
12189 (defun org-match-sparse-tree (&optional todo-only match)
12190 "Create a sparse tree according to tags string MATCH.
12191 MATCH can contain positive and negative selection of tags, like
12192 \"+WORK+URGENT-WITHBOSS\".
12193 If optional argument TODO-ONLY is non-nil, only select lines that are
12194 also TODO lines."
12195 (interactive "P")
12196 (org-prepare-agenda-buffers (list (current-buffer)))
12197 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12199 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12201 (defvar org-cached-props nil)
12202 (defun org-cached-entry-get (pom property)
12203 (if (or (eq t org-use-property-inheritance)
12204 (and (stringp org-use-property-inheritance)
12205 (string-match org-use-property-inheritance property))
12206 (and (listp org-use-property-inheritance)
12207 (member property org-use-property-inheritance)))
12208 ;; Caching is not possible, check it directly
12209 (org-entry-get pom property 'inherit)
12210 ;; Get all properties, so that we can do complicated checks easily
12211 (cdr (assoc property (or org-cached-props
12212 (setq org-cached-props
12213 (org-entry-properties pom)))))))
12215 (defun org-global-tags-completion-table (&optional files)
12216 "Return the list of all tags in all agenda buffer/files."
12217 (save-excursion
12218 (org-uniquify
12219 (delq nil
12220 (apply 'append
12221 (mapcar
12222 (lambda (file)
12223 (set-buffer (find-file-noselect file))
12224 (append (org-get-buffer-tags)
12225 (mapcar (lambda (x) (if (stringp (car-safe x))
12226 (list (car-safe x)) nil))
12227 org-tag-alist)))
12228 (if (and files (car files))
12229 files
12230 (org-agenda-files))))))))
12232 (defun org-make-tags-matcher (match)
12233 "Create the TAGS//TODO matcher form for the selection string MATCH."
12234 ;; todo-only is scoped dynamically into this function, and the function
12235 ;; may change it if the matcher asks for it.
12236 (unless match
12237 ;; Get a new match request, with completion
12238 (let ((org-last-tags-completion-table
12239 (org-global-tags-completion-table)))
12240 (setq match (org-completing-read-no-i
12241 "Match: " 'org-tags-completion-function nil nil nil
12242 'org-tags-history))))
12244 ;; Parse the string and create a lisp form
12245 (let ((match0 match)
12246 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12247 minus tag mm
12248 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12249 orterms term orlist re-p str-p level-p level-op time-p
12250 prop-p pn pv po cat-p gv rest)
12251 (if (string-match "/+" match)
12252 ;; match contains also a todo-matching request
12253 (progn
12254 (setq tagsmatch (substring match 0 (match-beginning 0))
12255 todomatch (substring match (match-end 0)))
12256 (if (string-match "^!" todomatch)
12257 (setq todo-only t todomatch (substring todomatch 1)))
12258 (if (string-match "^\\s-*$" todomatch)
12259 (setq todomatch nil)))
12260 ;; only matching tags
12261 (setq tagsmatch match todomatch nil))
12263 ;; Make the tags matcher
12264 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12265 (setq tagsmatcher t)
12266 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12267 (while (setq term (pop orterms))
12268 (while (and (equal (substring term -1) "\\") orterms)
12269 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12270 (while (string-match re term)
12271 (setq rest (substring term (match-end 0))
12272 minus (and (match-end 1)
12273 (equal (match-string 1 term) "-"))
12274 tag (match-string 2 term)
12275 re-p (equal (string-to-char tag) ?{)
12276 level-p (match-end 4)
12277 prop-p (match-end 5)
12278 mm (cond
12279 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12280 (level-p
12281 (setq level-op (org-op-to-function (match-string 3 term)))
12282 `(,level-op level ,(string-to-number
12283 (match-string 4 term))))
12284 (prop-p
12285 (setq pn (match-string 5 term)
12286 po (match-string 6 term)
12287 pv (match-string 7 term)
12288 cat-p (equal pn "CATEGORY")
12289 re-p (equal (string-to-char pv) ?{)
12290 str-p (equal (string-to-char pv) ?\")
12291 time-p (save-match-data
12292 (string-match "^\"[[<].*[]>]\"$" pv))
12293 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12294 (if time-p (setq pv (org-matcher-time pv)))
12295 (setq po (org-op-to-function po (if time-p 'time str-p)))
12296 (cond
12297 ((equal pn "CATEGORY")
12298 (setq gv '(get-text-property (point) 'org-category)))
12299 ((equal pn "TODO")
12300 (setq gv 'todo))
12302 (setq gv `(org-cached-entry-get nil ,pn))))
12303 (if re-p
12304 (if (eq po 'org<>)
12305 `(not (string-match ,pv (or ,gv "")))
12306 `(string-match ,pv (or ,gv "")))
12307 (if str-p
12308 `(,po (or ,gv "") ,pv)
12309 `(,po (string-to-number (or ,gv ""))
12310 ,(string-to-number pv) ))))
12311 (t `(member ,tag tags-list)))
12312 mm (if minus (list 'not mm) mm)
12313 term rest)
12314 (push mm tagsmatcher))
12315 (push (if (> (length tagsmatcher) 1)
12316 (cons 'and tagsmatcher)
12317 (car tagsmatcher))
12318 orlist)
12319 (setq tagsmatcher nil))
12320 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12321 (setq tagsmatcher
12322 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12323 ;; Make the todo matcher
12324 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12325 (setq todomatcher t)
12326 (setq orterms (org-split-string todomatch "|") orlist nil)
12327 (while (setq term (pop orterms))
12328 (while (string-match re term)
12329 (setq minus (and (match-end 1)
12330 (equal (match-string 1 term) "-"))
12331 kwd (match-string 2 term)
12332 re-p (equal (string-to-char kwd) ?{)
12333 term (substring term (match-end 0))
12334 mm (if re-p
12335 `(string-match ,(substring kwd 1 -1) todo)
12336 (list 'equal 'todo kwd))
12337 mm (if minus (list 'not mm) mm))
12338 (push mm todomatcher))
12339 (push (if (> (length todomatcher) 1)
12340 (cons 'and todomatcher)
12341 (car todomatcher))
12342 orlist)
12343 (setq todomatcher nil))
12344 (setq todomatcher (if (> (length orlist) 1)
12345 (cons 'or orlist) (car orlist))))
12347 ;; Return the string and lisp forms of the matcher
12348 (setq matcher (if todomatcher
12349 (list 'and tagsmatcher todomatcher)
12350 tagsmatcher))
12351 (cons match0 matcher)))
12353 (defun org-op-to-function (op &optional stringp)
12354 "Turn an operator into the appropriate function."
12355 (setq op
12356 (cond
12357 ((equal op "<" ) '(< string< org-time<))
12358 ((equal op ">" ) '(> org-string> org-time>))
12359 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12360 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12361 ((member op '("=" "==")) '(= string= org-time=))
12362 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12363 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12365 (defun org<> (a b) (not (= a b)))
12366 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12367 (defun org-string>= (a b) (not (string< a b)))
12368 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12369 (defun org-string<> (a b) (not (string= a b)))
12370 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12371 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12372 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12373 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12374 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12375 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12376 (defun org-2ft (s)
12377 "Convert S to a floating point time.
12378 If S is already a number, just return it. If it is a string, parse
12379 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12380 (cond
12381 ((numberp s) s)
12382 ((stringp s)
12383 (condition-case nil
12384 (float-time (apply 'encode-time (org-parse-time-string s)))
12385 (error 0.)))
12386 (t 0.)))
12388 (defun org-time-today ()
12389 "Time in seconds today at 0:00.
12390 Returns the float number of seconds since the beginning of the
12391 epoch to the beginning of today (00:00)."
12392 (float-time (apply 'encode-time
12393 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12395 (defun org-matcher-time (s)
12396 "Interpret a time comparison value."
12397 (save-match-data
12398 (cond
12399 ((string= s "<now>") (float-time))
12400 ((string= s "<today>") (org-time-today))
12401 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12402 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12403 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12404 (+ (org-time-today)
12405 (* (string-to-number (match-string 1 s))
12406 (cdr (assoc (match-string 2 s)
12407 '(("d" . 86400.0) ("w" . 604800.0)
12408 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12409 (t (org-2ft s)))))
12411 (defun org-match-any-p (re list)
12412 "Does re match any element of list?"
12413 (setq list (mapcar (lambda (x) (string-match re x)) list))
12414 (delq nil list))
12416 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12417 (defvar org-tags-overlay (make-overlay 1 1))
12418 (org-detach-overlay org-tags-overlay)
12420 (defun org-get-local-tags-at (&optional pos)
12421 "Get a list of tags defined in the current headline."
12422 (org-get-tags-at pos 'local))
12424 (defun org-get-local-tags ()
12425 "Get a list of tags defined in the current headline."
12426 (org-get-tags-at nil 'local))
12428 (defun org-get-tags-at (&optional pos local)
12429 "Get a list of all headline tags applicable at POS.
12430 POS defaults to point. If tags are inherited, the list contains
12431 the targets in the same sequence as the headlines appear, i.e.
12432 the tags of the current headline come last.
12433 When LOCAL is non-nil, only return tags from the current headline,
12434 ignore inherited ones."
12435 (interactive)
12436 (if (and org-trust-scanner-tags
12437 (or (not pos) (equal pos (point)))
12438 (not local))
12439 org-scanner-tags
12440 (let (tags ltags lastpos parent)
12441 (save-excursion
12442 (save-restriction
12443 (widen)
12444 (goto-char (or pos (point)))
12445 (save-match-data
12446 (catch 'done
12447 (condition-case nil
12448 (progn
12449 (org-back-to-heading t)
12450 (while (not (equal lastpos (point)))
12451 (setq lastpos (point))
12452 (when (looking-at
12453 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12454 (setq ltags (org-split-string
12455 (org-match-string-no-properties 1) ":"))
12456 (when parent
12457 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12458 (setq tags (append
12459 (if parent
12460 (org-remove-uniherited-tags ltags)
12461 ltags)
12462 tags)))
12463 (or org-use-tag-inheritance (throw 'done t))
12464 (if local (throw 'done t))
12465 (or (org-up-heading-safe) (error nil))
12466 (setq parent t)))
12467 (error nil)))))
12468 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12470 (defun org-add-prop-inherited (s)
12471 (add-text-properties 0 (length s) '(inherited t) s)
12474 (defun org-toggle-tag (tag &optional onoff)
12475 "Toggle the tag TAG for the current line.
12476 If ONOFF is `on' or `off', don't toggle but set to this state."
12477 (let (res current)
12478 (save-excursion
12479 (org-back-to-heading t)
12480 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12481 (point-at-eol) t)
12482 (progn
12483 (setq current (match-string 1))
12484 (replace-match ""))
12485 (setq current ""))
12486 (setq current (nreverse (org-split-string current ":")))
12487 (cond
12488 ((eq onoff 'on)
12489 (setq res t)
12490 (or (member tag current) (push tag current)))
12491 ((eq onoff 'off)
12492 (or (not (member tag current)) (setq current (delete tag current))))
12493 (t (if (member tag current)
12494 (setq current (delete tag current))
12495 (setq res t)
12496 (push tag current))))
12497 (end-of-line 1)
12498 (if current
12499 (progn
12500 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12501 (org-set-tags nil t))
12502 (delete-horizontal-space))
12503 (run-hooks 'org-after-tags-change-hook))
12504 res))
12506 (defun org-align-tags-here (to-col)
12507 ;; Assumes that this is a headline
12508 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12509 (beginning-of-line 1)
12510 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12511 (< pos (match-beginning 2)))
12512 (progn
12513 (setq tags-l (- (match-end 2) (match-beginning 2)))
12514 (goto-char (match-beginning 1))
12515 (insert " ")
12516 (delete-region (point) (1+ (match-beginning 2)))
12517 (setq ncol (max (1+ (current-column))
12518 (1+ col)
12519 (if (> to-col 0)
12520 to-col
12521 (- (abs to-col) tags-l))))
12522 (setq p (point))
12523 (insert (make-string (- ncol (current-column)) ?\ ))
12524 (setq ncol (current-column))
12525 (when indent-tabs-mode (tabify p (point-at-eol)))
12526 (org-move-to-column (min ncol col) t))
12527 (goto-char pos))))
12529 (defun org-set-tags-command (&optional arg just-align)
12530 "Call the set-tags command for the current entry."
12531 (interactive "P")
12532 (if (org-on-heading-p)
12533 (org-set-tags arg just-align)
12534 (save-excursion
12535 (org-back-to-heading t)
12536 (org-set-tags arg just-align))))
12538 (defun org-set-tags-to (data)
12539 "Set the tags of the current entry to DATA, replacing the current tags.
12540 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12541 If DATA is nil or the empty string, any tags will be removed."
12542 (interactive "sTags: ")
12543 (setq data
12544 (cond
12545 ((eq data nil) "")
12546 ((equal data "") "")
12547 ((stringp data)
12548 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12549 ":"))
12550 ((listp data)
12551 (concat ":" (mapconcat 'identity data ":") ":"))
12552 (t nil)))
12553 (when data
12554 (save-excursion
12555 (org-back-to-heading t)
12556 (when (looking-at org-complex-heading-regexp)
12557 (if (match-end 5)
12558 (progn
12559 (goto-char (match-beginning 5))
12560 (insert data)
12561 (delete-region (point) (point-at-eol))
12562 (org-set-tags nil 'align))
12563 (goto-char (point-at-eol))
12564 (insert " " data)
12565 (org-set-tags nil 'align)))
12566 (beginning-of-line 1)
12567 (if (looking-at ".*?\\([ \t]+\\)$")
12568 (delete-region (match-beginning 1) (match-end 1))))))
12570 (defun org-align-all-tags ()
12571 "Align the tags i all headings."
12572 (interactive)
12573 (save-excursion
12574 (or (ignore-errors (org-back-to-heading t))
12575 (outline-next-heading))
12576 (if (org-on-heading-p)
12577 (org-set-tags t)
12578 (message "No headings"))))
12580 (defun org-set-tags (&optional arg just-align)
12581 "Set the tags for the current headline.
12582 With prefix ARG, realign all tags in headings in the current buffer."
12583 (interactive "P")
12584 (let* ((re (concat "^" outline-regexp))
12585 (current (org-get-tags-string))
12586 (col (current-column))
12587 (org-setting-tags t)
12588 table current-tags inherited-tags ; computed below when needed
12589 tags p0 c0 c1 rpl)
12590 (if arg
12591 (save-excursion
12592 (goto-char (point-min))
12593 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12594 (while (re-search-forward re nil t)
12595 (org-set-tags nil t)
12596 (end-of-line 1)))
12597 (message "All tags realigned to column %d" org-tags-column))
12598 (if just-align
12599 (setq tags current)
12600 ;; Get a new set of tags from the user
12601 (save-excursion
12602 (setq table (append org-tag-persistent-alist
12603 (or org-tag-alist (org-get-buffer-tags))
12604 (and org-complete-tags-always-offer-all-agenda-tags
12605 (org-global-tags-completion-table (org-agenda-files))))
12606 org-last-tags-completion-table table
12607 current-tags (org-split-string current ":")
12608 inherited-tags (nreverse
12609 (nthcdr (length current-tags)
12610 (nreverse (org-get-tags-at))))
12611 tags
12612 (if (or (eq t org-use-fast-tag-selection)
12613 (and org-use-fast-tag-selection
12614 (delq nil (mapcar 'cdr table))))
12615 (org-fast-tag-selection
12616 current-tags inherited-tags table
12617 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12618 (let ((org-add-colon-after-tag-completion t))
12619 (org-trim
12620 (org-without-partial-completion
12621 (org-icompleting-read "Tags: " 'org-tags-completion-function
12622 nil nil current 'org-tags-history)))))))
12623 (while (string-match "[-+&]+" tags)
12624 ;; No boolean logic, just a list
12625 (setq tags (replace-match ":" t t tags))))
12627 (if org-tags-sort-function
12628 (setq tags (mapconcat 'identity
12629 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12630 org-tags-sort-function) ":")))
12632 (if (string-match "\\`[\t ]*\\'" tags)
12633 (setq tags "")
12634 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12635 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12637 ;; Insert new tags at the correct column
12638 (beginning-of-line 1)
12639 (cond
12640 ((and (equal current "") (equal tags "")))
12641 ((re-search-forward
12642 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12643 (point-at-eol) t)
12644 (if (equal tags "")
12645 (setq rpl "")
12646 (goto-char (match-beginning 0))
12647 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12648 (1+ (point)) (point))
12649 c1 (max (1+ c0) (if (> org-tags-column 0)
12650 org-tags-column
12651 (- (- org-tags-column) (length tags))))
12652 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12653 (replace-match rpl t t)
12654 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12655 tags)
12656 (t (error "Tags alignment failed")))
12657 (org-move-to-column col)
12658 (unless just-align
12659 (run-hooks 'org-after-tags-change-hook)))))
12661 (defun org-change-tag-in-region (beg end tag off)
12662 "Add or remove TAG for each entry in the region.
12663 This works in the agenda, and also in an org-mode buffer."
12664 (interactive
12665 (list (region-beginning) (region-end)
12666 (let ((org-last-tags-completion-table
12667 (if (org-mode-p)
12668 (org-get-buffer-tags)
12669 (org-global-tags-completion-table))))
12670 (org-icompleting-read
12671 "Tag: " 'org-tags-completion-function nil nil nil
12672 'org-tags-history))
12673 (progn
12674 (message "[s]et or [r]emove? ")
12675 (equal (read-char-exclusive) ?r))))
12676 (if (fboundp 'deactivate-mark) (deactivate-mark))
12677 (let ((agendap (equal major-mode 'org-agenda-mode))
12678 l1 l2 m buf pos newhead (cnt 0))
12679 (goto-char end)
12680 (setq l2 (1- (org-current-line)))
12681 (goto-char beg)
12682 (setq l1 (org-current-line))
12683 (loop for l from l1 to l2 do
12684 (org-goto-line l)
12685 (setq m (get-text-property (point) 'org-hd-marker))
12686 (when (or (and (org-mode-p) (org-on-heading-p))
12687 (and agendap m))
12688 (setq buf (if agendap (marker-buffer m) (current-buffer))
12689 pos (if agendap m (point)))
12690 (with-current-buffer buf
12691 (save-excursion
12692 (save-restriction
12693 (goto-char pos)
12694 (setq cnt (1+ cnt))
12695 (org-toggle-tag tag (if off 'off 'on))
12696 (setq newhead (org-get-heading)))))
12697 (and agendap (org-agenda-change-all-lines newhead m))))
12698 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12700 (defun org-tags-completion-function (string predicate &optional flag)
12701 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12702 (confirm (lambda (x) (stringp (car x)))))
12703 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12704 (setq s1 (match-string 1 string)
12705 s2 (match-string 2 string))
12706 (setq s1 "" s2 string))
12707 (cond
12708 ((eq flag nil)
12709 ;; try completion
12710 (setq rtn (try-completion s2 ctable confirm))
12711 (if (stringp rtn)
12712 (setq rtn
12713 (concat s1 s2 (substring rtn (length s2))
12714 (if (and org-add-colon-after-tag-completion
12715 (assoc rtn ctable))
12716 ":" ""))))
12717 rtn)
12718 ((eq flag t)
12719 ;; all-completions
12720 (all-completions s2 ctable confirm)
12722 ((eq flag 'lambda)
12723 ;; exact match?
12724 (assoc s2 ctable)))
12727 (defun org-fast-tag-insert (kwd tags face &optional end)
12728 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12729 (insert (format "%-12s" (concat kwd ":"))
12730 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12731 (or end "")))
12733 (defun org-fast-tag-show-exit (flag)
12734 (save-excursion
12735 (org-goto-line 3)
12736 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12737 (replace-match ""))
12738 (when flag
12739 (end-of-line 1)
12740 (org-move-to-column (- (window-width) 19) t)
12741 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12743 (defun org-set-current-tags-overlay (current prefix)
12744 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12745 (if (featurep 'xemacs)
12746 (org-overlay-display org-tags-overlay (concat prefix s)
12747 'secondary-selection)
12748 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12749 (org-overlay-display org-tags-overlay (concat prefix s)))))
12751 (defvar org-last-tag-selection-key nil)
12752 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12753 "Fast tag selection with single keys.
12754 CURRENT is the current list of tags in the headline, INHERITED is the
12755 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12756 possibly with grouping information. TODO-TABLE is a similar table with
12757 TODO keywords, should these have keys assigned to them.
12758 If the keys are nil, a-z are automatically assigned.
12759 Returns the new tags string, or nil to not change the current settings."
12760 (let* ((fulltable (append table todo-table))
12761 (maxlen (apply 'max (mapcar
12762 (lambda (x)
12763 (if (stringp (car x)) (string-width (car x)) 0))
12764 fulltable)))
12765 (buf (current-buffer))
12766 (expert (eq org-fast-tag-selection-single-key 'expert))
12767 (buffer-tags nil)
12768 (fwidth (+ maxlen 3 1 3))
12769 (ncol (/ (- (window-width) 4) fwidth))
12770 (i-face 'org-done)
12771 (c-face 'org-todo)
12772 tg cnt e c char c1 c2 ntable tbl rtn
12773 ov-start ov-end ov-prefix
12774 (exit-after-next org-fast-tag-selection-single-key)
12775 (done-keywords org-done-keywords)
12776 groups ingroup)
12777 (save-excursion
12778 (beginning-of-line 1)
12779 (if (looking-at
12780 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12781 (setq ov-start (match-beginning 1)
12782 ov-end (match-end 1)
12783 ov-prefix "")
12784 (setq ov-start (1- (point-at-eol))
12785 ov-end (1+ ov-start))
12786 (skip-chars-forward "^\n\r")
12787 (setq ov-prefix
12788 (concat
12789 (buffer-substring (1- (point)) (point))
12790 (if (> (current-column) org-tags-column)
12792 (make-string (- org-tags-column (current-column)) ?\ ))))))
12793 (move-overlay org-tags-overlay ov-start ov-end)
12794 (save-window-excursion
12795 (if expert
12796 (set-buffer (get-buffer-create " *Org tags*"))
12797 (delete-other-windows)
12798 (split-window-vertically)
12799 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12800 (erase-buffer)
12801 (org-set-local 'org-done-keywords done-keywords)
12802 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12803 (org-fast-tag-insert "Current" current c-face "\n\n")
12804 (org-fast-tag-show-exit exit-after-next)
12805 (org-set-current-tags-overlay current ov-prefix)
12806 (setq tbl fulltable char ?a cnt 0)
12807 (while (setq e (pop tbl))
12808 (cond
12809 ((equal (car e) :startgroup)
12810 (push '() groups) (setq ingroup t)
12811 (when (not (= cnt 0))
12812 (setq cnt 0)
12813 (insert "\n"))
12814 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12815 ((equal (car e) :endgroup)
12816 (setq ingroup nil cnt 0)
12817 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12818 ((equal e '(:newline))
12819 (when (not (= cnt 0))
12820 (setq cnt 0)
12821 (insert "\n")
12822 (setq e (car tbl))
12823 (while (equal (car tbl) '(:newline))
12824 (insert "\n")
12825 (setq tbl (cdr tbl)))))
12827 (setq tg (copy-sequence (car e)) c2 nil)
12828 (if (cdr e)
12829 (setq c (cdr e))
12830 ;; automatically assign a character.
12831 (setq c1 (string-to-char
12832 (downcase (substring
12833 tg (if (= (string-to-char tg) ?@) 1 0)))))
12834 (if (or (rassoc c1 ntable) (rassoc c1 table))
12835 (while (or (rassoc char ntable) (rassoc char table))
12836 (setq char (1+ char)))
12837 (setq c2 c1))
12838 (setq c (or c2 char)))
12839 (if ingroup (push tg (car groups)))
12840 (setq tg (org-add-props tg nil 'face
12841 (cond
12842 ((not (assoc tg table))
12843 (org-get-todo-face tg))
12844 ((member tg current) c-face)
12845 ((member tg inherited) i-face)
12846 (t nil))))
12847 (if (and (= cnt 0) (not ingroup)) (insert " "))
12848 (insert "[" c "] " tg (make-string
12849 (- fwidth 4 (length tg)) ?\ ))
12850 (push (cons tg c) ntable)
12851 (when (= (setq cnt (1+ cnt)) ncol)
12852 (insert "\n")
12853 (if ingroup (insert " "))
12854 (setq cnt 0)))))
12855 (setq ntable (nreverse ntable))
12856 (insert "\n")
12857 (goto-char (point-min))
12858 (if (not expert) (org-fit-window-to-buffer))
12859 (setq rtn
12860 (catch 'exit
12861 (while t
12862 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12863 (if (not groups) "no " "")
12864 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12865 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12866 (setq org-last-tag-selection-key c)
12867 (cond
12868 ((= c ?\r) (throw 'exit t))
12869 ((= c ?!)
12870 (setq groups (not groups))
12871 (goto-char (point-min))
12872 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12873 ((= c ?\C-c)
12874 (if (not expert)
12875 (org-fast-tag-show-exit
12876 (setq exit-after-next (not exit-after-next)))
12877 (setq expert nil)
12878 (delete-other-windows)
12879 (split-window-vertically)
12880 (org-switch-to-buffer-other-window " *Org tags*")
12881 (org-fit-window-to-buffer)))
12882 ((or (= c ?\C-g)
12883 (and (= c ?q) (not (rassoc c ntable))))
12884 (org-detach-overlay org-tags-overlay)
12885 (setq quit-flag t))
12886 ((= c ?\ )
12887 (setq current nil)
12888 (if exit-after-next (setq exit-after-next 'now)))
12889 ((= c ?\t)
12890 (condition-case nil
12891 (setq tg (org-icompleting-read
12892 "Tag: "
12893 (or buffer-tags
12894 (with-current-buffer buf
12895 (org-get-buffer-tags)))))
12896 (quit (setq tg "")))
12897 (when (string-match "\\S-" tg)
12898 (add-to-list 'buffer-tags (list tg))
12899 (if (member tg current)
12900 (setq current (delete tg current))
12901 (push tg current)))
12902 (if exit-after-next (setq exit-after-next 'now)))
12903 ((setq e (rassoc c todo-table) tg (car e))
12904 (with-current-buffer buf
12905 (save-excursion (org-todo tg)))
12906 (if exit-after-next (setq exit-after-next 'now)))
12907 ((setq e (rassoc c ntable) tg (car e))
12908 (if (member tg current)
12909 (setq current (delete tg current))
12910 (loop for g in groups do
12911 (if (member tg g)
12912 (mapc (lambda (x)
12913 (setq current (delete x current)))
12914 g)))
12915 (push tg current))
12916 (if exit-after-next (setq exit-after-next 'now))))
12918 ;; Create a sorted list
12919 (setq current
12920 (sort current
12921 (lambda (a b)
12922 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12923 (if (eq exit-after-next 'now) (throw 'exit t))
12924 (goto-char (point-min))
12925 (beginning-of-line 2)
12926 (delete-region (point) (point-at-eol))
12927 (org-fast-tag-insert "Current" current c-face)
12928 (org-set-current-tags-overlay current ov-prefix)
12929 (while (re-search-forward
12930 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12931 (setq tg (match-string 1))
12932 (add-text-properties
12933 (match-beginning 1) (match-end 1)
12934 (list 'face
12935 (cond
12936 ((member tg current) c-face)
12937 ((member tg inherited) i-face)
12938 (t (get-text-property (match-beginning 1) 'face))))))
12939 (goto-char (point-min)))))
12940 (org-detach-overlay org-tags-overlay)
12941 (if rtn
12942 (mapconcat 'identity current ":")
12943 nil))))
12945 (defun org-get-tags-string ()
12946 "Get the TAGS string in the current headline."
12947 (unless (org-on-heading-p t)
12948 (error "Not on a heading"))
12949 (save-excursion
12950 (beginning-of-line 1)
12951 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12952 (org-match-string-no-properties 1)
12953 "")))
12955 (defun org-get-tags ()
12956 "Get the list of tags specified in the current headline."
12957 (org-split-string (org-get-tags-string) ":"))
12959 (defun org-get-buffer-tags ()
12960 "Get a table of all tags used in the buffer, for completion."
12961 (let (tags)
12962 (save-excursion
12963 (goto-char (point-min))
12964 (while (re-search-forward
12965 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12966 (when (equal (char-after (point-at-bol 0)) ?*)
12967 (mapc (lambda (x) (add-to-list 'tags x))
12968 (org-split-string (org-match-string-no-properties 1) ":")))))
12969 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12970 (mapcar 'list tags)))
12972 ;;;; The mapping API
12974 ;;;###autoload
12975 (defun org-map-entries (func &optional match scope &rest skip)
12976 "Call FUNC at each headline selected by MATCH in SCOPE.
12978 FUNC is a function or a lisp form. The function will be called without
12979 arguments, with the cursor positioned at the beginning of the headline.
12980 The return values of all calls to the function will be collected and
12981 returned as a list.
12983 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12984 does not need to preserve point. After evaluation, the cursor will be
12985 moved to the end of the line (presumably of the headline of the
12986 processed entry) and search continues from there. Under some
12987 circumstances, this may not produce the wanted results. For example,
12988 if you have removed (e.g. archived) the current (sub)tree it could
12989 mean that the next entry will be skipped entirely. In such cases, you
12990 can specify the position from where search should continue by making
12991 FUNC set the variable `org-map-continue-from' to the desired buffer
12992 position.
12994 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12995 Only headlines that are matched by this query will be considered during
12996 the iteration. When MATCH is nil or t, all headlines will be
12997 visited by the iteration.
12999 SCOPE determines the scope of this command. It can be any of:
13001 nil The current buffer, respecting the restriction if any
13002 tree The subtree started with the entry at point
13003 file The current buffer, without restriction
13004 file-with-archives
13005 The current buffer, and any archives associated with it
13006 agenda All agenda files
13007 agenda-with-archives
13008 All agenda files with any archive files associated with them
13009 \(file1 file2 ...)
13010 If this is a list, all files in the list will be scanned
13012 The remaining args are treated as settings for the skipping facilities of
13013 the scanner. The following items can be given here:
13015 archive skip trees with the archive tag.
13016 comment skip trees with the COMMENT keyword
13017 function or Emacs Lisp form:
13018 will be used as value for `org-agenda-skip-function', so whenever
13019 the function returns t, FUNC will not be called for that
13020 entry and search will continue from the point where the
13021 function leaves it.
13023 If your function needs to retrieve the tags including inherited tags
13024 at the *current* entry, you can use the value of the variable
13025 `org-scanner-tags' which will be much faster than getting the value
13026 with `org-get-tags-at'. If your function gets properties with
13027 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13028 to t around the call to `org-entry-properties' to get the same speedup.
13029 Note that if your function moves around to retrieve tags and properties at
13030 a *different* entry, you cannot use these techniques."
13031 (let* ((org-agenda-archives-mode nil) ; just to make sure
13032 (org-agenda-skip-archived-trees (memq 'archive skip))
13033 (org-agenda-skip-comment-trees (memq 'comment skip))
13034 (org-agenda-skip-function
13035 (car (org-delete-all '(comment archive) skip)))
13036 (org-tags-match-list-sublevels t)
13037 matcher file res
13038 org-todo-keywords-for-agenda
13039 org-done-keywords-for-agenda
13040 org-todo-keyword-alist-for-agenda
13041 org-drawers-for-agenda
13042 org-tag-alist-for-agenda)
13044 (cond
13045 ((eq match t) (setq matcher t))
13046 ((eq match nil) (setq matcher t))
13047 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13049 (save-excursion
13050 (save-restriction
13051 (when (eq scope 'tree)
13052 (org-back-to-heading t)
13053 (org-narrow-to-subtree)
13054 (setq scope nil))
13056 (if (not scope)
13057 (progn
13058 (org-prepare-agenda-buffers
13059 (list (buffer-file-name (current-buffer))))
13060 (setq res (org-scan-tags func matcher)))
13061 ;; Get the right scope
13062 (cond
13063 ((and scope (listp scope) (symbolp (car scope)))
13064 (setq scope (eval scope)))
13065 ((eq scope 'agenda)
13066 (setq scope (org-agenda-files t)))
13067 ((eq scope 'agenda-with-archives)
13068 (setq scope (org-agenda-files t))
13069 (setq scope (org-add-archive-files scope)))
13070 ((eq scope 'file)
13071 (setq scope (list (buffer-file-name))))
13072 ((eq scope 'file-with-archives)
13073 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13074 (org-prepare-agenda-buffers scope)
13075 (while (setq file (pop scope))
13076 (with-current-buffer (org-find-base-buffer-visiting file)
13077 (save-excursion
13078 (save-restriction
13079 (widen)
13080 (goto-char (point-min))
13081 (setq res (append res (org-scan-tags func matcher))))))))))
13082 res))
13084 ;;;; Properties
13086 ;;; Setting and retrieving properties
13088 (defconst org-special-properties
13089 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13090 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13091 "The special properties valid in Org-mode.
13093 These are properties that are not defined in the property drawer,
13094 but in some other way.")
13096 (defconst org-default-properties
13097 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13098 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13099 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13100 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13101 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13102 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13103 "Some properties that are used by Org-mode for various purposes.
13104 Being in this list makes sure that they are offered for completion.")
13106 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13107 "Regular expression matching the first line of a property drawer.")
13109 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13110 "Regular expression matching the last line of a property drawer.")
13112 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13113 "Regular expression matching the first line of a property drawer.")
13115 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13116 "Regular expression matching the first line of a property drawer.")
13118 (defconst org-property-drawer-re
13119 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13120 org-property-end-re "\\)\n?")
13121 "Matches an entire property drawer.")
13123 (defconst org-clock-drawer-re
13124 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13125 org-property-end-re "\\)\n?")
13126 "Matches an entire clock drawer.")
13128 (defun org-property-action ()
13129 "Do an action on properties."
13130 (interactive)
13131 (let (c)
13132 (org-at-property-p)
13133 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13134 (setq c (read-char-exclusive))
13135 (cond
13136 ((equal c ?s)
13137 (call-interactively 'org-set-property))
13138 ((equal c ?d)
13139 (call-interactively 'org-delete-property))
13140 ((equal c ?D)
13141 (call-interactively 'org-delete-property-globally))
13142 ((equal c ?c)
13143 (call-interactively 'org-compute-property-at-point))
13144 (t (error "No such property action %c" c)))))
13146 (defun org-set-effort (&optional value)
13147 "Set the effort property of the current entry.
13148 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13149 allowed value."
13150 (interactive "P")
13151 (if (equal value 0) (setq value 10))
13152 (let* ((completion-ignore-case t)
13153 (prop org-effort-property)
13154 (cur (org-entry-get nil prop))
13155 (allowed (org-property-get-allowed-values nil prop 'table))
13156 (existing (mapcar 'list (org-property-values prop)))
13158 (val (cond
13159 ((stringp value) value)
13160 ((and allowed (integerp value))
13161 (or (car (nth (1- value) allowed))
13162 (car (org-last allowed))))
13163 (allowed
13164 (message "Select 1-9,0, [RET%s]: %s"
13165 (if cur (concat "=" cur) "")
13166 (mapconcat 'car allowed " "))
13167 (setq rpl (read-char-exclusive))
13168 (if (equal rpl ?\r)
13170 (setq rpl (- rpl ?0))
13171 (if (equal rpl 0) (setq rpl 10))
13172 (if (and (> rpl 0) (<= rpl (length allowed)))
13173 (car (nth (1- rpl) allowed))
13174 (org-completing-read "Effort: " allowed nil))))
13176 (let (org-completion-use-ido org-completion-use-iswitchb)
13177 (org-completing-read
13178 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13179 (concat "[" cur "]") "")
13180 ": ")
13181 existing nil nil "" nil cur))))))
13182 (unless (equal (org-entry-get nil prop) val)
13183 (org-entry-put nil prop val))
13184 (message "%s is now %s" prop val)))
13186 (defun org-at-property-p ()
13187 "Is cursor inside a property drawer?"
13188 (save-excursion
13189 (beginning-of-line 1)
13190 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13191 (let ((match (match-data)) ;; Keep match-data for use by calling
13192 (p (point)) ;; procedures.
13193 (range (unless (org-before-first-heading-p)
13194 (org-get-property-block))))
13195 (prog1 (and range (<= (car range) p) (< p (cdr range)))
13196 (set-match-data match))))))
13198 (defun org-get-property-block (&optional beg end force)
13199 "Return the (beg . end) range of the body of the property drawer.
13200 BEG and END can be beginning and end of subtree, if not given
13201 they will be found.
13202 If the drawer does not exist and FORCE is non-nil, create the drawer."
13203 (catch 'exit
13204 (save-excursion
13205 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13206 (end (or end (progn (outline-next-heading) (point)))))
13207 (goto-char beg)
13208 (if (re-search-forward org-property-start-re end t)
13209 (setq beg (1+ (match-end 0)))
13210 (if force
13211 (save-excursion
13212 (org-insert-property-drawer)
13213 (setq end (progn (outline-next-heading) (point))))
13214 (throw 'exit nil))
13215 (goto-char beg)
13216 (if (re-search-forward org-property-start-re end t)
13217 (setq beg (1+ (match-end 0)))))
13218 (if (re-search-forward org-property-end-re end t)
13219 (setq end (match-beginning 0))
13220 (or force (throw 'exit nil))
13221 (goto-char beg)
13222 (setq end beg)
13223 (org-indent-line-function)
13224 (insert ":END:\n"))
13225 (cons beg end)))))
13227 (defun org-entry-properties (&optional pom which specific)
13228 "Get all properties of the entry at point-or-marker POM.
13229 This includes the TODO keyword, the tags, time strings for deadline,
13230 scheduled, and clocking, and any additional properties defined in the
13231 entry. The return value is an alist, keys may occur multiple times
13232 if the property key was used several times.
13233 POM may also be nil, in which case the current entry is used.
13234 If WHICH is nil or `all', get all properties. If WHICH is
13235 `special' or `standard', only get that subclass. If WHICH
13236 is a string only get exactly this property. Specific can be a string, the
13237 specific property we are interested in. Specifying it can speed
13238 things up because then unnecessary parsing is avoided."
13239 (setq which (or which 'all))
13240 (org-with-point-at pom
13241 (let ((clockstr (substring org-clock-string 0 -1))
13242 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13243 (case-fold-search nil)
13244 beg end range props sum-props key value string clocksum)
13245 (save-excursion
13246 (when (condition-case nil
13247 (and (org-mode-p) (org-back-to-heading t))
13248 (error nil))
13249 (setq beg (point))
13250 (setq sum-props (get-text-property (point) 'org-summaries))
13251 (setq clocksum (get-text-property (point) :org-clock-minutes))
13252 (outline-next-heading)
13253 (setq end (point))
13254 (when (memq which '(all special))
13255 ;; Get the special properties, like TODO and tags
13256 (goto-char beg)
13257 (when (and (or (not specific) (string= specific "TODO"))
13258 (looking-at org-todo-line-regexp) (match-end 2))
13259 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13260 (when (and (or (not specific) (string= specific "PRIORITY"))
13261 (looking-at org-priority-regexp))
13262 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13263 (when (and (or (not specific) (string= specific "TAGS"))
13264 (setq value (org-get-tags-string))
13265 (string-match "\\S-" value))
13266 (push (cons "TAGS" value) props))
13267 (when (and (or (not specific) (string= specific "ALLTAGS"))
13268 (setq value (org-get-tags-at)))
13269 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13270 ":"))
13271 props))
13272 (when (or (not specific) (string= specific "BLOCKED"))
13273 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13274 (when (or (not specific)
13275 (member specific org-all-time-keywords)
13276 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
13277 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13278 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
13279 string (if (equal key clockstr)
13280 (org-no-properties
13281 (org-trim
13282 (buffer-substring
13283 (match-beginning 3) (goto-char (point-at-eol)))))
13284 (substring (org-match-string-no-properties 3) 1 -1)))
13285 (unless key
13286 (if (= (char-after (match-beginning 3)) ?\[)
13287 (setq key "TIMESTAMP_IA")
13288 (setq key "TIMESTAMP")))
13289 (when (or (equal key clockstr) (not (assoc key props)))
13290 (push (cons key string) props))))
13294 (when (memq which '(all standard))
13295 ;; Get the standard properties, like :PROP: ...
13296 (setq range (org-get-property-block beg end))
13297 (when range
13298 (goto-char (car range))
13299 (while (re-search-forward
13300 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13301 (cdr range) t)
13302 (setq key (org-match-string-no-properties 1)
13303 value (org-trim (or (org-match-string-no-properties 2) "")))
13304 (unless (member key excluded)
13305 (push (cons key (or value "")) props)))))
13306 (if clocksum
13307 (push (cons "CLOCKSUM"
13308 (org-columns-number-to-string (/ (float clocksum) 60.)
13309 'add_times))
13310 props))
13311 (unless (assoc "CATEGORY" props)
13312 (setq value (or (org-get-category)
13313 (progn (org-refresh-category-properties)
13314 (org-get-category))))
13315 (push (cons "CATEGORY" value) props))
13316 (append sum-props (nreverse props)))))))
13318 (defun org-entry-get (pom property &optional inherit)
13319 "Get value of PROPERTY for entry at point-or-marker POM.
13320 If INHERIT is non-nil and the entry does not have the property,
13321 then also check higher levels of the hierarchy.
13322 If INHERIT is the symbol `selective', use inheritance only if the setting
13323 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13324 If the property is present but empty, the return value is the empty string.
13325 If the property is not present at all, nil is returned."
13326 (org-with-point-at pom
13327 (if (and inherit (if (eq inherit 'selective)
13328 (org-property-inherit-p property)
13330 (org-entry-get-with-inheritance property)
13331 (if (member property org-special-properties)
13332 ;; We need a special property. Use `org-entry-properties' to
13333 ;; retrieve it, but specify the wanted property
13334 (cdr (assoc property (org-entry-properties nil 'special property)))
13335 (let ((range (org-get-property-block)))
13336 (if (and range
13337 (goto-char (car range))
13338 (re-search-forward
13339 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13340 (cdr range) t))
13341 ;; Found the property, return it.
13342 (if (match-end 1)
13343 (org-match-string-no-properties 1)
13344 "")))))))
13346 (defun org-property-or-variable-value (var &optional inherit)
13347 "Check if there is a property fixing the value of VAR.
13348 If yes, return this value. If not, return the current value of the variable."
13349 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13350 (if (and prop (stringp prop) (string-match "\\S-" prop))
13351 (read prop)
13352 (symbol-value var))))
13354 (defun org-entry-delete (pom property)
13355 "Delete the property PROPERTY from entry at point-or-marker POM."
13356 (org-with-point-at pom
13357 (if (member property org-special-properties)
13358 nil ; cannot delete these properties.
13359 (let ((range (org-get-property-block)))
13360 (if (and range
13361 (goto-char (car range))
13362 (re-search-forward
13363 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13364 (cdr range) t))
13365 (progn
13366 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13368 nil)))))
13370 ;; Multi-values properties are properties that contain multiple values
13371 ;; These values are assumed to be single words, separated by whitespace.
13372 (defun org-entry-add-to-multivalued-property (pom property value)
13373 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13374 (let* ((old (org-entry-get pom property))
13375 (values (and old (org-split-string old "[ \t]"))))
13376 (setq value (org-entry-protect-space value))
13377 (unless (member value values)
13378 (setq values (cons value values))
13379 (org-entry-put pom property
13380 (mapconcat 'identity values " ")))))
13382 (defun org-entry-remove-from-multivalued-property (pom property value)
13383 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13384 (let* ((old (org-entry-get pom property))
13385 (values (and old (org-split-string old "[ \t]"))))
13386 (setq value (org-entry-protect-space value))
13387 (when (member value values)
13388 (setq values (delete value values))
13389 (org-entry-put pom property
13390 (mapconcat 'identity values " ")))))
13392 (defun org-entry-member-in-multivalued-property (pom property value)
13393 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13394 (let* ((old (org-entry-get pom property))
13395 (values (and old (org-split-string old "[ \t]"))))
13396 (setq value (org-entry-protect-space value))
13397 (member value values)))
13399 (defun org-entry-get-multivalued-property (pom property)
13400 "Return a list of values in a multivalued property."
13401 (let* ((value (org-entry-get pom property))
13402 (values (and value (org-split-string value "[ \t]"))))
13403 (mapcar 'org-entry-restore-space values)))
13405 (defun org-entry-put-multivalued-property (pom property &rest values)
13406 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13407 VALUES should be a list of strings. Spaces will be protected."
13408 (org-entry-put pom property
13409 (mapconcat 'org-entry-protect-space values " "))
13410 (let* ((value (org-entry-get pom property))
13411 (values (and value (org-split-string value "[ \t]"))))
13412 (mapcar 'org-entry-restore-space values)))
13414 (defun org-entry-protect-space (s)
13415 "Protect spaces and newline in string S."
13416 (while (string-match " " s)
13417 (setq s (replace-match "%20" t t s)))
13418 (while (string-match "\n" s)
13419 (setq s (replace-match "%0A" t t s)))
13422 (defun org-entry-restore-space (s)
13423 "Restore spaces and newline in string S."
13424 (while (string-match "%20" s)
13425 (setq s (replace-match " " t t s)))
13426 (while (string-match "%0A" s)
13427 (setq s (replace-match "\n" t t s)))
13430 (defvar org-entry-property-inherited-from (make-marker)
13431 "Marker pointing to the entry from where a property was inherited.
13432 Each call to `org-entry-get-with-inheritance' will set this marker to the
13433 location of the entry where the inheritance search matched. If there was
13434 no match, the marker will point nowhere.
13435 Note that also `org-entry-get' calls this function, if the INHERIT flag
13436 is set.")
13438 (defun org-entry-get-with-inheritance (property)
13439 "Get entry property, and search higher levels if not present."
13440 (move-marker org-entry-property-inherited-from nil)
13441 (let (tmp)
13442 (save-excursion
13443 (save-restriction
13444 (widen)
13445 (catch 'ex
13446 (while t
13447 (when (setq tmp (org-entry-get nil property))
13448 (org-back-to-heading t)
13449 (move-marker org-entry-property-inherited-from (point))
13450 (throw 'ex tmp))
13451 (or (org-up-heading-safe) (throw 'ex nil)))))
13452 (or tmp
13453 (cdr (assoc property org-file-properties))
13454 (cdr (assoc property org-global-properties))
13455 (cdr (assoc property org-global-properties-fixed))))))
13457 (defvar org-property-changed-functions nil
13458 "Hook called when the value of a property has changed.
13459 Each hook function should accept two arguments, the name of the property
13460 and the new value.")
13462 (defun org-entry-put (pom property value)
13463 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13464 (org-with-point-at pom
13465 (org-back-to-heading t)
13466 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13467 range)
13468 (cond
13469 ((equal property "TODO")
13470 (when (and (stringp value) (string-match "\\S-" value)
13471 (not (member value org-todo-keywords-1)))
13472 (error "\"%s\" is not a valid TODO state" value))
13473 (if (or (not value)
13474 (not (string-match "\\S-" value)))
13475 (setq value 'none))
13476 (org-todo value)
13477 (org-set-tags nil 'align))
13478 ((equal property "PRIORITY")
13479 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13480 (string-to-char value) ?\ ))
13481 (org-set-tags nil 'align))
13482 ((equal property "SCHEDULED")
13483 (if (re-search-forward org-scheduled-time-regexp end t)
13484 (cond
13485 ((eq value 'earlier) (org-timestamp-change -1 'day))
13486 ((eq value 'later) (org-timestamp-change 1 'day))
13487 (t (call-interactively 'org-schedule)))
13488 (call-interactively 'org-schedule)))
13489 ((equal property "DEADLINE")
13490 (if (re-search-forward org-deadline-time-regexp end t)
13491 (cond
13492 ((eq value 'earlier) (org-timestamp-change -1 'day))
13493 ((eq value 'later) (org-timestamp-change 1 'day))
13494 (t (call-interactively 'org-deadline)))
13495 (call-interactively 'org-deadline)))
13496 ((member property org-special-properties)
13497 (error "The %s property can not yet be set with `org-entry-put'"
13498 property))
13499 (t ; a non-special property
13500 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13501 (setq range (org-get-property-block beg end 'force))
13502 (goto-char (car range))
13503 (if (re-search-forward
13504 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13505 (progn
13506 (delete-region (match-beginning 1) (match-end 1))
13507 (goto-char (match-beginning 1)))
13508 (goto-char (cdr range))
13509 (insert "\n")
13510 (backward-char 1)
13511 (org-indent-line-function)
13512 (insert ":" property ":"))
13513 (and value (insert " " value))
13514 (org-indent-line-function)))))
13515 (run-hook-with-args 'org-property-changed-functions property value)))
13517 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13518 "Get all property keys in the current buffer.
13519 With INCLUDE-SPECIALS, also list the special properties that reflect things
13520 like tags and TODO state.
13521 With INCLUDE-DEFAULTS, also include properties that has special meaning
13522 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13523 With INCLUDE-COLUMNS, also include property names given in COLUMN
13524 formats in the current buffer."
13525 (let (rtn range cfmt s p)
13526 (save-excursion
13527 (save-restriction
13528 (widen)
13529 (goto-char (point-min))
13530 (while (re-search-forward org-property-start-re nil t)
13531 (setq range (org-get-property-block))
13532 (goto-char (car range))
13533 (while (re-search-forward
13534 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13535 (cdr range) t)
13536 (add-to-list 'rtn (org-match-string-no-properties 1)))
13537 (outline-next-heading))))
13539 (when include-specials
13540 (setq rtn (append org-special-properties rtn)))
13542 (when include-defaults
13543 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13544 (add-to-list 'rtn org-effort-property))
13546 (when include-columns
13547 (save-excursion
13548 (save-restriction
13549 (widen)
13550 (goto-char (point-min))
13551 (while (re-search-forward
13552 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13553 nil t)
13554 (setq cfmt (match-string 2) s 0)
13555 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13556 cfmt s)
13557 (setq s (match-end 0)
13558 p (match-string 1 cfmt))
13559 (unless (or (equal p "ITEM")
13560 (member p org-special-properties))
13561 (add-to-list 'rtn (match-string 1 cfmt))))))))
13563 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13565 (defun org-property-values (key)
13566 "Return a list of all values of property KEY."
13567 (save-excursion
13568 (save-restriction
13569 (widen)
13570 (goto-char (point-min))
13571 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13572 values)
13573 (while (re-search-forward re nil t)
13574 (add-to-list 'values (org-trim (match-string 1))))
13575 (delete "" values)))))
13577 (defun org-insert-property-drawer ()
13578 "Insert a property drawer into the current entry."
13579 (interactive)
13580 (org-back-to-heading t)
13581 (looking-at outline-regexp)
13582 (let ((indent (if org-adapt-indentation
13583 (- (match-end 0)(match-beginning 0))
13585 (beg (point))
13586 (re (concat "^[ \t]*" org-keyword-time-regexp))
13587 end hiddenp)
13588 (outline-next-heading)
13589 (setq end (point))
13590 (goto-char beg)
13591 (while (re-search-forward re end t))
13592 (setq hiddenp (org-invisible-p))
13593 (end-of-line 1)
13594 (and (equal (char-after) ?\n) (forward-char 1))
13595 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13596 (if (member (match-string 1) '("CLOCK:" ":END:"))
13597 ;; just skip this line
13598 (beginning-of-line 2)
13599 ;; Drawer start, find the end
13600 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13601 (beginning-of-line 1)))
13602 (org-skip-over-state-notes)
13603 (skip-chars-backward " \t\n\r")
13604 (if (eq (char-before) ?*) (forward-char 1))
13605 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13606 (beginning-of-line 0)
13607 (org-indent-to-column indent)
13608 (beginning-of-line 2)
13609 (org-indent-to-column indent)
13610 (beginning-of-line 0)
13611 (if hiddenp
13612 (save-excursion
13613 (org-back-to-heading t)
13614 (hide-entry))
13615 (org-flag-drawer t))))
13617 (defun org-set-property (property value)
13618 "In the current entry, set PROPERTY to VALUE.
13619 When called interactively, this will prompt for a property name, offering
13620 completion on existing and default properties. And then it will prompt
13621 for a value, offering completion either on allowed values (via an inherited
13622 xxx_ALL property) or on existing values in other instances of this property
13623 in the current file."
13624 (interactive
13625 (let* ((completion-ignore-case t)
13626 (keys (org-buffer-property-keys nil t t))
13627 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13628 (prop (if (member prop0 keys)
13629 prop0
13630 (or (cdr (assoc (downcase prop0)
13631 (mapcar (lambda (x) (cons (downcase x) x))
13632 keys)))
13633 prop0)))
13634 (cur (org-entry-get nil prop))
13635 (prompt (concat prop " value"
13636 (if (and cur (string-match "\\S-" cur))
13637 (concat " [" cur "]") "") ": "))
13638 (allowed (org-property-get-allowed-values nil prop 'table))
13639 (existing (mapcar 'list (org-property-values prop)))
13640 (val (if allowed
13641 (org-completing-read prompt allowed nil
13642 (not (get-text-property 0 'org-unrestricted
13643 (caar allowed))))
13644 (let (org-completion-use-ido org-completion-use-iswitchb)
13645 (org-completing-read prompt existing nil nil "" nil cur)))))
13646 (list prop (if (equal val "") cur val))))
13647 (unless (equal (org-entry-get nil property) value)
13648 (org-entry-put nil property value)))
13650 (defun org-delete-property (property)
13651 "In the current entry, delete PROPERTY."
13652 (interactive
13653 (let* ((completion-ignore-case t)
13654 (prop (org-icompleting-read "Property: "
13655 (org-entry-properties nil 'standard))))
13656 (list prop)))
13657 (message "Property %s %s" property
13658 (if (org-entry-delete nil property)
13659 "deleted"
13660 "was not present in the entry")))
13662 (defun org-delete-property-globally (property)
13663 "Remove PROPERTY globally, from all entries."
13664 (interactive
13665 (let* ((completion-ignore-case t)
13666 (prop (org-icompleting-read
13667 "Globally remove property: "
13668 (mapcar 'list (org-buffer-property-keys)))))
13669 (list prop)))
13670 (save-excursion
13671 (save-restriction
13672 (widen)
13673 (goto-char (point-min))
13674 (let ((cnt 0))
13675 (while (re-search-forward
13676 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13677 nil t)
13678 (setq cnt (1+ cnt))
13679 (replace-match ""))
13680 (message "Property \"%s\" removed from %d entries" property cnt)))))
13682 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13684 (defun org-compute-property-at-point ()
13685 "Compute the property at point.
13686 This looks for an enclosing column format, extracts the operator and
13687 then applies it to the property in the column format's scope."
13688 (interactive)
13689 (unless (org-at-property-p)
13690 (error "Not at a property"))
13691 (let ((prop (org-match-string-no-properties 2)))
13692 (org-columns-get-format-and-top-level)
13693 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13694 (error "No operator defined for property %s" prop))
13695 (org-columns-compute prop)))
13697 (defvar org-property-allowed-value-functions nil
13698 "Hook for functions supplying allowed values for a specific property.
13699 The functions must take a single argument, the name of the property, and
13700 return a flat list of allowed values. If \":ETC\" is one of
13701 the values, this means that these values are intended as defaults for
13702 completion, but that other values should be allowed too.
13703 The functions must return nil if they are not responsible for this
13704 property.")
13706 (defun org-property-get-allowed-values (pom property &optional table)
13707 "Get allowed values for the property PROPERTY.
13708 When TABLE is non-nil, return an alist that can directly be used for
13709 completion."
13710 (let (vals)
13711 (cond
13712 ((equal property "TODO")
13713 (setq vals (org-with-point-at pom
13714 (append org-todo-keywords-1 '("")))))
13715 ((equal property "PRIORITY")
13716 (let ((n org-lowest-priority))
13717 (while (>= n org-highest-priority)
13718 (push (char-to-string n) vals)
13719 (setq n (1- n)))))
13720 ((member property org-special-properties))
13721 ((setq vals (run-hook-with-args-until-success
13722 'org-property-allowed-value-functions property)))
13724 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13725 (when (and vals (string-match "\\S-" vals))
13726 (setq vals (car (read-from-string (concat "(" vals ")"))))
13727 (setq vals (mapcar (lambda (x)
13728 (cond ((stringp x) x)
13729 ((numberp x) (number-to-string x))
13730 ((symbolp x) (symbol-name x))
13731 (t "???")))
13732 vals)))))
13733 (when (member ":ETC" vals)
13734 (setq vals (remove ":ETC" vals))
13735 (org-add-props (car vals) '(org-unrestricted t)))
13736 (if table (mapcar 'list vals) vals)))
13738 (defun org-property-previous-allowed-value (&optional previous)
13739 "Switch to the next allowed value for this property."
13740 (interactive)
13741 (org-property-next-allowed-value t))
13743 (defun org-property-next-allowed-value (&optional previous)
13744 "Switch to the next allowed value for this property."
13745 (interactive)
13746 (unless (org-at-property-p)
13747 (error "Not at a property"))
13748 (let* ((key (match-string 2))
13749 (value (match-string 3))
13750 (allowed (or (org-property-get-allowed-values (point) key)
13751 (and (member value '("[ ]" "[-]" "[X]"))
13752 '("[ ]" "[X]"))))
13753 nval)
13754 (unless allowed
13755 (error "Allowed values for this property have not been defined"))
13756 (if previous (setq allowed (reverse allowed)))
13757 (if (member value allowed)
13758 (setq nval (car (cdr (member value allowed)))))
13759 (setq nval (or nval (car allowed)))
13760 (if (equal nval value)
13761 (error "Only one allowed value for this property"))
13762 (org-at-property-p)
13763 (replace-match (concat " :" key ": " nval) t t)
13764 (org-indent-line-function)
13765 (beginning-of-line 1)
13766 (skip-chars-forward " \t")
13767 (run-hook-with-args 'org-property-changed-functions key nval)))
13769 (defun org-find-olp (path)
13770 "Return a marker pointing to the entry at outline path OLP.
13771 If anything goes wrong, throw an error.
13772 You can wrap this call to cathc the error like this:
13774 (condition-case msg
13775 (org-mobile-locate-entry (match-string 4))
13776 (error (nth 1 msg)))
13778 The return value will then be either a string with the error message,
13779 or a marker if everyhing is OK."
13780 (let* ((file (pop path))
13781 (buffer (find-file-noselect file))
13782 (level 1)
13783 (lmin 1)
13784 (lmax 1)
13785 limit re end found pos heading cnt)
13786 (unless buffer (error "File not found :%s" file))
13787 (with-current-buffer buffer
13788 (save-excursion
13789 (save-restriction
13790 (widen)
13791 (setq limit (point-max))
13792 (goto-char (point-min))
13793 (while (setq heading (pop path))
13794 (setq re (format org-complex-heading-regexp-format
13795 (regexp-quote heading)))
13796 (setq cnt 0 pos (point))
13797 (while (re-search-forward re end t)
13798 (setq level (- (match-end 1) (match-beginning 1)))
13799 (if (and (>= level lmin) (<= level lmax))
13800 (setq found (match-beginning 0) cnt (1+ cnt))))
13801 (when (= cnt 0) (error "Heading not found on level %d: %s"
13802 lmax heading))
13803 (when (> cnt 1) (error "Heading not unique on level %d: %s"
13804 lmax heading))
13805 (goto-char found)
13806 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
13807 (setq end (save-excursion (org-end-of-subtree t t))))
13808 (when (org-on-heading-p)
13809 (move-marker (make-marker) (point))))))))
13811 (defun org-find-entry-with-id (ident)
13812 "Locate the entry that contains the ID property with exact value IDENT.
13813 IDENT can be a string, a symbol or a number, this function will search for
13814 the string representation of it.
13815 Return the position where this entry starts, or nil if there is no such entry."
13816 (interactive "sID: ")
13817 (let ((id (cond
13818 ((stringp ident) ident)
13819 ((symbol-name ident) (symbol-name ident))
13820 ((numberp ident) (number-to-string ident))
13821 (t (error "IDENT %s must be a string, symbol or number" ident))))
13822 (case-fold-search nil))
13823 (save-excursion
13824 (save-restriction
13825 (widen)
13826 (goto-char (point-min))
13827 (when (re-search-forward
13828 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13829 nil t)
13830 (org-back-to-heading t)
13831 (point))))))
13833 ;;;; Timestamps
13835 (defvar org-last-changed-timestamp nil)
13836 (defvar org-last-inserted-timestamp nil
13837 "The last time stamp inserted with `org-insert-time-stamp'.")
13838 (defvar org-time-was-given) ; dynamically scoped parameter
13839 (defvar org-end-time-was-given) ; dynamically scoped parameter
13840 (defvar org-ts-what) ; dynamically scoped parameter
13842 (defun org-time-stamp (arg &optional inactive)
13843 "Prompt for a date/time and insert a time stamp.
13844 If the user specifies a time like HH:MM, or if this command is called
13845 with a prefix argument, the time stamp will contain date and time.
13846 Otherwise, only the date will be included. All parts of a date not
13847 specified by the user will be filled in from the current date/time.
13848 So if you press just return without typing anything, the time stamp
13849 will represent the current date/time. If there is already a timestamp
13850 at the cursor, it will be modified."
13851 (interactive "P")
13852 (let* ((ts nil)
13853 (default-time
13854 ;; Default time is either today, or, when entering a range,
13855 ;; the range start.
13856 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13857 (save-excursion
13858 (re-search-backward
13859 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13860 (- (point) 20) t)))
13861 (apply 'encode-time (org-parse-time-string (match-string 1)))
13862 (current-time)))
13863 (default-input (and ts (org-get-compact-tod ts)))
13864 org-time-was-given org-end-time-was-given time)
13865 (cond
13866 ((and (org-at-timestamp-p t)
13867 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13868 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13869 (insert "--")
13870 (setq time (let ((this-command this-command))
13871 (org-read-date arg 'totime nil nil
13872 default-time default-input)))
13873 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13874 ((org-at-timestamp-p t)
13875 (setq time (let ((this-command this-command))
13876 (org-read-date arg 'totime nil nil default-time default-input)))
13877 (when (org-at-timestamp-p t) ; just to get the match data
13878 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13879 (replace-match "")
13880 (setq org-last-changed-timestamp
13881 (org-insert-time-stamp
13882 time (or org-time-was-given arg)
13883 inactive nil nil (list org-end-time-was-given))))
13884 (message "Timestamp updated"))
13886 (setq time (let ((this-command this-command))
13887 (org-read-date arg 'totime nil nil default-time default-input)))
13888 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13889 nil nil (list org-end-time-was-given))))))
13891 ;; FIXME: can we use this for something else, like computing time differences?
13892 (defun org-get-compact-tod (s)
13893 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13894 (let* ((t1 (match-string 1 s))
13895 (h1 (string-to-number (match-string 2 s)))
13896 (m1 (string-to-number (match-string 3 s)))
13897 (t2 (and (match-end 4) (match-string 5 s)))
13898 (h2 (and t2 (string-to-number (match-string 6 s))))
13899 (m2 (and t2 (string-to-number (match-string 7 s))))
13900 dh dm)
13901 (if (not t2)
13903 (setq dh (- h2 h1) dm (- m2 m1))
13904 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13905 (concat t1 "+" (number-to-string dh)
13906 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13908 (defun org-time-stamp-inactive (&optional arg)
13909 "Insert an inactive time stamp.
13910 An inactive time stamp is enclosed in square brackets instead of angle
13911 brackets. It is inactive in the sense that it does not trigger agenda entries,
13912 does not link to the calendar and cannot be changed with the S-cursor keys.
13913 So these are more for recording a certain time/date."
13914 (interactive "P")
13915 (org-time-stamp arg 'inactive))
13917 (defvar org-date-ovl (make-overlay 1 1))
13918 (overlay-put org-date-ovl 'face 'org-warning)
13919 (org-detach-overlay org-date-ovl)
13921 (defvar org-ans1) ; dynamically scoped parameter
13922 (defvar org-ans2) ; dynamically scoped parameter
13924 (defvar org-plain-time-of-day-regexp) ; defined below
13926 (defvar org-overriding-default-time nil) ; dynamically scoped
13927 (defvar org-read-date-overlay nil)
13928 (defvar org-dcst nil) ; dynamically scoped
13929 (defvar org-read-date-history nil)
13930 (defvar org-read-date-final-answer nil)
13932 (defun org-read-date (&optional with-time to-time from-string prompt
13933 default-time default-input)
13934 "Read a date, possibly a time, and make things smooth for the user.
13935 The prompt will suggest to enter an ISO date, but you can also enter anything
13936 which will at least partially be understood by `parse-time-string'.
13937 Unrecognized parts of the date will default to the current day, month, year,
13938 hour and minute. If this command is called to replace a timestamp at point,
13939 of to enter the second timestamp of a range, the default time is taken from the
13940 existing stamp. For example,
13941 3-2-5 --> 2003-02-05
13942 feb 15 --> currentyear-02-15
13943 sep 12 9 --> 2009-09-12
13944 12:45 --> today 12:45
13945 22 sept 0:34 --> currentyear-09-22 0:34
13946 12 --> currentyear-currentmonth-12
13947 Fri --> nearest Friday (today or later)
13948 etc.
13950 Furthermore you can specify a relative date by giving, as the *first* thing
13951 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13952 change in days weeks, months, years.
13953 With a single plus or minus, the date is relative to today. With a double
13954 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13955 +4d --> four days from today
13956 +4 --> same as above
13957 +2w --> two weeks from today
13958 ++5 --> five days from default date
13960 The function understands only English month and weekday abbreviations,
13961 but this can be configured with the variables `parse-time-months' and
13962 `parse-time-weekdays'.
13964 While prompting, a calendar is popped up - you can also select the
13965 date with the mouse (button 1). The calendar shows a period of three
13966 months. To scroll it to other months, use the keys `>' and `<'.
13967 If you don't like the calendar, turn it off with
13968 \(setq org-read-date-popup-calendar nil)
13970 With optional argument TO-TIME, the date will immediately be converted
13971 to an internal time.
13972 With an optional argument WITH-TIME, the prompt will suggest to also
13973 insert a time. Note that when WITH-TIME is not set, you can still
13974 enter a time, and this function will inform the calling routine about
13975 this change. The calling routine may then choose to change the format
13976 used to insert the time stamp into the buffer to include the time.
13977 With optional argument FROM-STRING, read from this string instead from
13978 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13979 the time/date that is used for everything that is not specified by the
13980 user."
13981 (require 'parse-time)
13982 (let* ((org-time-stamp-rounding-minutes
13983 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13984 (org-dcst org-display-custom-times)
13985 (ct (org-current-time))
13986 (def (or org-overriding-default-time default-time ct))
13987 (defdecode (decode-time def))
13988 (dummy (progn
13989 (when (< (nth 2 defdecode) org-extend-today-until)
13990 (setcar (nthcdr 2 defdecode) -1)
13991 (setcar (nthcdr 1 defdecode) 59)
13992 (setq def (apply 'encode-time defdecode)
13993 defdecode (decode-time def)))))
13994 (calendar-frame-setup nil)
13995 (calendar-move-hook nil)
13996 (calendar-view-diary-initially-flag nil)
13997 (calendar-view-holidays-initially-flag nil)
13998 (timestr (format-time-string
13999 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14000 (prompt (concat (if prompt (concat prompt " ") "")
14001 (format "Date+time [%s]: " timestr)))
14002 ans (org-ans0 "") org-ans1 org-ans2 final)
14004 (cond
14005 (from-string (setq ans from-string))
14006 (org-read-date-popup-calendar
14007 (save-excursion
14008 (save-window-excursion
14009 (calendar)
14010 (calendar-forward-day (- (time-to-days def)
14011 (calendar-absolute-from-gregorian
14012 (calendar-current-date))))
14013 (org-eval-in-calendar nil t)
14014 (let* ((old-map (current-local-map))
14015 (map (copy-keymap calendar-mode-map))
14016 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14017 (org-defkey map (kbd "RET") 'org-calendar-select)
14018 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14019 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14020 (org-defkey minibuffer-local-map [(meta shift left)]
14021 (lambda () (interactive)
14022 (org-eval-in-calendar '(calendar-backward-month 1))))
14023 (org-defkey minibuffer-local-map [(meta shift right)]
14024 (lambda () (interactive)
14025 (org-eval-in-calendar '(calendar-forward-month 1))))
14026 (org-defkey minibuffer-local-map [(meta shift up)]
14027 (lambda () (interactive)
14028 (org-eval-in-calendar '(calendar-backward-year 1))))
14029 (org-defkey minibuffer-local-map [(meta shift down)]
14030 (lambda () (interactive)
14031 (org-eval-in-calendar '(calendar-forward-year 1))))
14032 (org-defkey minibuffer-local-map [?\e (shift left)]
14033 (lambda () (interactive)
14034 (org-eval-in-calendar '(calendar-backward-month 1))))
14035 (org-defkey minibuffer-local-map [?\e (shift right)]
14036 (lambda () (interactive)
14037 (org-eval-in-calendar '(calendar-forward-month 1))))
14038 (org-defkey minibuffer-local-map [?\e (shift up)]
14039 (lambda () (interactive)
14040 (org-eval-in-calendar '(calendar-backward-year 1))))
14041 (org-defkey minibuffer-local-map [?\e (shift down)]
14042 (lambda () (interactive)
14043 (org-eval-in-calendar '(calendar-forward-year 1))))
14044 (org-defkey minibuffer-local-map [(shift up)]
14045 (lambda () (interactive)
14046 (org-eval-in-calendar '(calendar-backward-week 1))))
14047 (org-defkey minibuffer-local-map [(shift down)]
14048 (lambda () (interactive)
14049 (org-eval-in-calendar '(calendar-forward-week 1))))
14050 (org-defkey minibuffer-local-map [(shift left)]
14051 (lambda () (interactive)
14052 (org-eval-in-calendar '(calendar-backward-day 1))))
14053 (org-defkey minibuffer-local-map [(shift right)]
14054 (lambda () (interactive)
14055 (org-eval-in-calendar '(calendar-forward-day 1))))
14056 (org-defkey minibuffer-local-map ">"
14057 (lambda () (interactive)
14058 (org-eval-in-calendar '(scroll-calendar-left 1))))
14059 (org-defkey minibuffer-local-map "<"
14060 (lambda () (interactive)
14061 (org-eval-in-calendar '(scroll-calendar-right 1))))
14062 (org-defkey minibuffer-local-map "\C-v"
14063 (lambda () (interactive)
14064 (org-eval-in-calendar
14065 '(calendar-scroll-left-three-months 1))))
14066 (org-defkey minibuffer-local-map "\M-v"
14067 (lambda () (interactive)
14068 (org-eval-in-calendar
14069 '(calendar-scroll-right-three-months 1))))
14070 (run-hooks 'org-read-date-minibuffer-setup-hook)
14071 (unwind-protect
14072 (progn
14073 (use-local-map map)
14074 (add-hook 'post-command-hook 'org-read-date-display)
14075 (setq org-ans0 (read-string prompt default-input
14076 'org-read-date-history nil))
14077 ;; org-ans0: from prompt
14078 ;; org-ans1: from mouse click
14079 ;; org-ans2: from calendar motion
14080 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14081 (remove-hook 'post-command-hook 'org-read-date-display)
14082 (use-local-map old-map)
14083 (when org-read-date-overlay
14084 (delete-overlay org-read-date-overlay)
14085 (setq org-read-date-overlay nil)))))))
14087 (t ; Naked prompt only
14088 (unwind-protect
14089 (setq ans (read-string prompt default-input
14090 'org-read-date-history timestr))
14091 (when org-read-date-overlay
14092 (delete-overlay org-read-date-overlay)
14093 (setq org-read-date-overlay nil)))))
14095 (setq final (org-read-date-analyze ans def defdecode))
14096 (setq org-read-date-final-answer ans)
14098 (if to-time
14099 (apply 'encode-time final)
14100 (if (and (boundp 'org-time-was-given) org-time-was-given)
14101 (format "%04d-%02d-%02d %02d:%02d"
14102 (nth 5 final) (nth 4 final) (nth 3 final)
14103 (nth 2 final) (nth 1 final))
14104 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14106 (defvar def)
14107 (defvar defdecode)
14108 (defvar with-time)
14109 (defvar org-read-date-analyze-futurep nil)
14110 (defun org-read-date-display ()
14111 "Display the current date prompt interpretation in the minibuffer."
14112 (when org-read-date-display-live
14113 (when org-read-date-overlay
14114 (delete-overlay org-read-date-overlay))
14115 (let ((p (point)))
14116 (end-of-line 1)
14117 (while (not (equal (buffer-substring
14118 (max (point-min) (- (point) 4)) (point))
14119 " "))
14120 (insert " "))
14121 (goto-char p))
14122 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14123 " " (or org-ans1 org-ans2)))
14124 (org-end-time-was-given nil)
14125 (f (org-read-date-analyze ans def defdecode))
14126 (fmts (if org-dcst
14127 org-time-stamp-custom-formats
14128 org-time-stamp-formats))
14129 (fmt (if (or with-time
14130 (and (boundp 'org-time-was-given) org-time-was-given))
14131 (cdr fmts)
14132 (car fmts)))
14133 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14134 (when (and org-end-time-was-given
14135 (string-match org-plain-time-of-day-regexp txt))
14136 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14137 org-end-time-was-given
14138 (substring txt (match-end 0)))))
14139 (when org-read-date-analyze-futurep
14140 (setq txt (concat txt " (=>F)")))
14141 (setq org-read-date-overlay
14142 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14143 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14145 (defun org-read-date-analyze (ans def defdecode)
14146 "Analyse the combined answer of the date prompt."
14147 ;; FIXME: cleanup and comment
14148 (let ((nowdecode (decode-time (current-time)))
14149 delta deltan deltaw deltadef year month day
14150 hour minute second wday pm h2 m2 tl wday1
14151 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14152 (setq org-read-date-analyze-futurep nil)
14153 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14154 (setq ans "+0"))
14156 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14157 (setq ans (replace-match "" t t ans)
14158 deltan (car delta)
14159 deltaw (nth 1 delta)
14160 deltadef (nth 2 delta)))
14162 ;; Check if there is an iso week date in there
14163 ;; If yes, store the info and postpone interpreting it until the rest
14164 ;; of the parsing is done
14165 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14166 (setq iso-year (if (match-end 1)
14167 (org-small-year-to-year
14168 (string-to-number (match-string 1 ans))))
14169 iso-weekday (if (match-end 3)
14170 (string-to-number (match-string 3 ans)))
14171 iso-week (string-to-number (match-string 2 ans)))
14172 (setq ans (replace-match "" t t ans)))
14174 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14175 (when (string-match
14176 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14177 (setq year (if (match-end 2)
14178 (string-to-number (match-string 2 ans))
14179 (progn (setq kill-year t)
14180 (string-to-number (format-time-string "%Y"))))
14181 month (string-to-number (match-string 3 ans))
14182 day (string-to-number (match-string 4 ans)))
14183 (if (< year 100) (setq year (+ 2000 year)))
14184 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14185 t nil ans)))
14186 ;; Help matching american dates, like 5/30 or 5/30/7
14187 (when (string-match
14188 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14189 (setq year (if (match-end 4)
14190 (string-to-number (match-string 4 ans))
14191 (progn (setq kill-year t)
14192 (string-to-number (format-time-string "%Y"))))
14193 month (string-to-number (match-string 1 ans))
14194 day (string-to-number (match-string 2 ans)))
14195 (if (< year 100) (setq year (+ 2000 year)))
14196 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14197 t nil ans)))
14198 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14199 ;; If there is a time with am/pm, and *no* time without it, we convert
14200 ;; so that matching will be successful.
14201 (loop for i from 1 to 2 do ; twice, for end time as well
14202 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14203 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14204 (setq hour (string-to-number (match-string 1 ans))
14205 minute (if (match-end 3)
14206 (string-to-number (match-string 3 ans))
14208 pm (equal ?p
14209 (string-to-char (downcase (match-string 4 ans)))))
14210 (if (and (= hour 12) (not pm))
14211 (setq hour 0)
14212 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14213 (setq ans (replace-match (format "%02d:%02d" hour minute)
14214 t t ans))))
14216 ;; Check if a time range is given as a duration
14217 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14218 (setq hour (string-to-number (match-string 1 ans))
14219 h2 (+ hour (string-to-number (match-string 3 ans)))
14220 minute (string-to-number (match-string 2 ans))
14221 m2 (+ minute (if (match-end 5) (string-to-number
14222 (match-string 5 ans))0)))
14223 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14224 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14225 t t ans)))
14227 ;; Check if there is a time range
14228 (when (boundp 'org-end-time-was-given)
14229 (setq org-time-was-given nil)
14230 (when (and (string-match org-plain-time-of-day-regexp ans)
14231 (match-end 8))
14232 (setq org-end-time-was-given (match-string 8 ans))
14233 (setq ans (concat (substring ans 0 (match-beginning 7))
14234 (substring ans (match-end 7))))))
14236 (setq tl (parse-time-string ans)
14237 day (or (nth 3 tl) (nth 3 defdecode))
14238 month (or (nth 4 tl)
14239 (if (and org-read-date-prefer-future
14240 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14241 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14242 (nth 4 defdecode)))
14243 year (or (and (not kill-year) (nth 5 tl))
14244 (if (and org-read-date-prefer-future
14245 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14246 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14247 (nth 5 defdecode)))
14248 hour (or (nth 2 tl) (nth 2 defdecode))
14249 minute (or (nth 1 tl) (nth 1 defdecode))
14250 second (or (nth 0 tl) 0)
14251 wday (nth 6 tl))
14253 (when (and (eq org-read-date-prefer-future 'time)
14254 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14255 (equal day (nth 3 nowdecode))
14256 (equal month (nth 4 nowdecode))
14257 (equal year (nth 5 nowdecode))
14258 (nth 2 tl)
14259 (or (< (nth 2 tl) (nth 2 nowdecode))
14260 (and (= (nth 2 tl) (nth 2 nowdecode))
14261 (nth 1 tl)
14262 (< (nth 1 tl) (nth 1 nowdecode)))))
14263 (setq day (1+ day)
14264 futurep t))
14266 ;; Special date definitions below
14267 (cond
14268 (iso-week
14269 ;; There was an iso week
14270 (require 'cal-iso)
14271 (setq futurep nil)
14272 (setq year (or iso-year year)
14273 day (or iso-weekday wday 1)
14274 wday nil ; to make sure that the trigger below does not match
14275 iso-date (calendar-gregorian-from-absolute
14276 (calendar-absolute-from-iso
14277 (list iso-week day year))))
14278 ; FIXME: Should we also push ISO weeks into the future?
14279 ; (when (and org-read-date-prefer-future
14280 ; (not iso-year)
14281 ; (< (calendar-absolute-from-gregorian iso-date)
14282 ; (time-to-days (current-time))))
14283 ; (setq year (1+ year)
14284 ; iso-date (calendar-gregorian-from-absolute
14285 ; (calendar-absolute-from-iso
14286 ; (list iso-week day year)))))
14287 (setq month (car iso-date)
14288 year (nth 2 iso-date)
14289 day (nth 1 iso-date)))
14290 (deltan
14291 (setq futurep nil)
14292 (unless deltadef
14293 (let ((now (decode-time (current-time))))
14294 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14295 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14296 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14297 ((equal deltaw "m") (setq month (+ month deltan)))
14298 ((equal deltaw "y") (setq year (+ year deltan)))))
14299 ((and wday (not (nth 3 tl)))
14300 (setq futurep nil)
14301 ;; Weekday was given, but no day, so pick that day in the week
14302 ;; on or after the derived date.
14303 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14304 (unless (equal wday wday1)
14305 (setq day (+ day (% (- wday wday1 -7) 7))))))
14306 (if (and (boundp 'org-time-was-given)
14307 (nth 2 tl))
14308 (setq org-time-was-given t))
14309 (if (< year 100) (setq year (+ 2000 year)))
14310 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14311 (setq org-read-date-analyze-futurep futurep)
14312 (list second minute hour day month year)))
14314 (defvar parse-time-weekdays)
14316 (defun org-read-date-get-relative (s today default)
14317 "Check string S for special relative date string.
14318 TODAY and DEFAULT are internal times, for today and for a default.
14319 Return shift list (N what def-flag)
14320 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14321 N is the number of WHATs to shift.
14322 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14323 the DEFAULT date rather than TODAY."
14324 (when (and
14325 (string-match
14326 (concat
14327 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14328 "\\([0-9]+\\)?"
14329 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14330 "\\([ \t]\\|$\\)") s)
14331 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14332 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14333 (string-to-char (substring (match-string 1 s) -1))
14334 ?+))
14335 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14336 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14337 (what (if (match-end 3) (match-string 3 s) "d"))
14338 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14339 (date (if rel default today))
14340 (wday (nth 6 (decode-time date)))
14341 delta)
14342 (if wday1
14343 (progn
14344 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14345 (if (= dir ?-) (setq delta (- delta 7)))
14346 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14347 (list delta "d" rel))
14348 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14350 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14351 "Turn a user-specified date into the internal representation.
14352 The internal representation needed by the calendar is (month day year).
14353 This is a wrapper to handle the brain-dead convention in calendar that
14354 user function argument order change dependent on argument order."
14355 (if (boundp 'calendar-date-style)
14356 (cond
14357 ((eq calendar-date-style 'american)
14358 (list arg1 arg2 arg3))
14359 ((eq calendar-date-style 'european)
14360 (list arg2 arg1 arg3))
14361 ((eq calendar-date-style 'iso)
14362 (list arg2 arg3 arg1)))
14363 (if (org-bound-and-true-p european-calendar-style)
14364 (list arg2 arg1 arg3)
14365 (list arg1 arg2 arg3))))
14367 (defun org-eval-in-calendar (form &optional keepdate)
14368 "Eval FORM in the calendar window and return to current window.
14369 Also, store the cursor date in variable org-ans2."
14370 (let ((sf (selected-frame))
14371 (sw (selected-window)))
14372 (select-window (get-buffer-window "*Calendar*" t))
14373 (eval form)
14374 (when (and (not keepdate) (calendar-cursor-to-date))
14375 (let* ((date (calendar-cursor-to-date))
14376 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14377 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14378 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14379 (select-window sw)
14380 (org-select-frame-set-input-focus sf)))
14382 (defun org-calendar-select ()
14383 "Return to `org-read-date' with the date currently selected.
14384 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14385 (interactive)
14386 (when (calendar-cursor-to-date)
14387 (let* ((date (calendar-cursor-to-date))
14388 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14389 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14390 (if (active-minibuffer-window) (exit-minibuffer))))
14392 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14393 "Insert a date stamp for the date given by the internal TIME.
14394 WITH-HM means use the stamp format that includes the time of the day.
14395 INACTIVE means use square brackets instead of angular ones, so that the
14396 stamp will not contribute to the agenda.
14397 PRE and POST are optional strings to be inserted before and after the
14398 stamp.
14399 The command returns the inserted time stamp."
14400 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14401 stamp)
14402 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14403 (insert-before-markers (or pre ""))
14404 (insert-before-markers (setq stamp (format-time-string fmt time)))
14405 (when (listp extra)
14406 (setq extra (car extra))
14407 (if (and (stringp extra)
14408 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14409 (setq extra (format "-%02d:%02d"
14410 (string-to-number (match-string 1 extra))
14411 (string-to-number (match-string 2 extra))))
14412 (setq extra nil)))
14413 (when extra
14414 (backward-char 1)
14415 (insert-before-markers extra)
14416 (forward-char 1))
14417 (insert-before-markers (or post ""))
14418 (setq org-last-inserted-timestamp stamp)))
14420 (defun org-toggle-time-stamp-overlays ()
14421 "Toggle the use of custom time stamp formats."
14422 (interactive)
14423 (setq org-display-custom-times (not org-display-custom-times))
14424 (unless org-display-custom-times
14425 (let ((p (point-min)) (bmp (buffer-modified-p)))
14426 (while (setq p (next-single-property-change p 'display))
14427 (if (and (get-text-property p 'display)
14428 (eq (get-text-property p 'face) 'org-date))
14429 (remove-text-properties
14430 p (setq p (next-single-property-change p 'display))
14431 '(display t))))
14432 (set-buffer-modified-p bmp)))
14433 (if (featurep 'xemacs)
14434 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14435 (org-restart-font-lock)
14436 (setq org-table-may-need-update t)
14437 (if org-display-custom-times
14438 (message "Time stamps are overlayed with custom format")
14439 (message "Time stamp overlays removed")))
14441 (defun org-display-custom-time (beg end)
14442 "Overlay modified time stamp format over timestamp between BEG and END."
14443 (let* ((ts (buffer-substring beg end))
14444 t1 w1 with-hm tf time str w2 (off 0))
14445 (save-match-data
14446 (setq t1 (org-parse-time-string ts t))
14447 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14448 (setq off (- (match-end 0) (match-beginning 0)))))
14449 (setq end (- end off))
14450 (setq w1 (- end beg)
14451 with-hm (and (nth 1 t1) (nth 2 t1))
14452 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14453 time (org-fix-decoded-time t1)
14454 str (org-add-props
14455 (format-time-string
14456 (substring tf 1 -1) (apply 'encode-time time))
14457 nil 'mouse-face 'highlight)
14458 w2 (length str))
14459 (if (not (= w2 w1))
14460 (add-text-properties (1+ beg) (+ 2 beg)
14461 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14462 (if (featurep 'xemacs)
14463 (progn
14464 (put-text-property beg end 'invisible t)
14465 (put-text-property beg end 'end-glyph (make-glyph str)))
14466 (put-text-property beg end 'display str))))
14468 (defun org-translate-time (string)
14469 "Translate all timestamps in STRING to custom format.
14470 But do this only if the variable `org-display-custom-times' is set."
14471 (when org-display-custom-times
14472 (save-match-data
14473 (let* ((start 0)
14474 (re org-ts-regexp-both)
14475 t1 with-hm inactive tf time str beg end)
14476 (while (setq start (string-match re string start))
14477 (setq beg (match-beginning 0)
14478 end (match-end 0)
14479 t1 (save-match-data
14480 (org-parse-time-string (substring string beg end) t))
14481 with-hm (and (nth 1 t1) (nth 2 t1))
14482 inactive (equal (substring string beg (1+ beg)) "[")
14483 tf (funcall (if with-hm 'cdr 'car)
14484 org-time-stamp-custom-formats)
14485 time (org-fix-decoded-time t1)
14486 str (format-time-string
14487 (concat
14488 (if inactive "[" "<") (substring tf 1 -1)
14489 (if inactive "]" ">"))
14490 (apply 'encode-time time))
14491 string (replace-match str t t string)
14492 start (+ start (length str)))))))
14493 string)
14495 (defun org-fix-decoded-time (time)
14496 "Set 0 instead of nil for the first 6 elements of time.
14497 Don't touch the rest."
14498 (let ((n 0))
14499 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14501 (defun org-days-to-time (timestamp-string)
14502 "Difference between TIMESTAMP-STRING and now in days."
14503 (- (time-to-days (org-time-string-to-time timestamp-string))
14504 (time-to-days (current-time))))
14506 (defun org-deadline-close (timestamp-string &optional ndays)
14507 "Is the time in TIMESTAMP-STRING close to the current date?"
14508 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14509 (and (< (org-days-to-time timestamp-string) ndays)
14510 (not (org-entry-is-done-p))))
14512 (defun org-get-wdays (ts)
14513 "Get the deadline lead time appropriate for timestring TS."
14514 (cond
14515 ((<= org-deadline-warning-days 0)
14516 ;; 0 or negative, enforce this value no matter what
14517 (- org-deadline-warning-days))
14518 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14519 ;; lead time is specified.
14520 (floor (* (string-to-number (match-string 1 ts))
14521 (cdr (assoc (match-string 2 ts)
14522 '(("d" . 1) ("w" . 7)
14523 ("m" . 30.4) ("y" . 365.25)))))))
14524 ;; go for the default.
14525 (t org-deadline-warning-days)))
14527 (defun org-calendar-select-mouse (ev)
14528 "Return to `org-read-date' with the date currently selected.
14529 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14530 (interactive "e")
14531 (mouse-set-point ev)
14532 (when (calendar-cursor-to-date)
14533 (let* ((date (calendar-cursor-to-date))
14534 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14535 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14536 (if (active-minibuffer-window) (exit-minibuffer))))
14538 (defun org-check-deadlines (ndays)
14539 "Check if there are any deadlines due or past due.
14540 A deadline is considered due if it happens within `org-deadline-warning-days'
14541 days from today's date. If the deadline appears in an entry marked DONE,
14542 it is not shown. The prefix arg NDAYS can be used to test that many
14543 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14544 (interactive "P")
14545 (let* ((org-warn-days
14546 (cond
14547 ((equal ndays '(4)) 100000)
14548 (ndays (prefix-numeric-value ndays))
14549 (t (abs org-deadline-warning-days))))
14550 (case-fold-search nil)
14551 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14552 (callback
14553 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14555 (message "%d deadlines past-due or due within %d days"
14556 (org-occur regexp nil callback)
14557 org-warn-days)))
14559 (defun org-check-before-date (date)
14560 "Check if there are deadlines or scheduled entries before DATE."
14561 (interactive (list (org-read-date)))
14562 (let ((case-fold-search nil)
14563 (regexp (concat "\\<\\(" org-deadline-string
14564 "\\|" org-scheduled-string
14565 "\\) *<\\([^>]+\\)>"))
14566 (callback
14567 (lambda () (time-less-p
14568 (org-time-string-to-time (match-string 2))
14569 (org-time-string-to-time date)))))
14570 (message "%d entries before %s"
14571 (org-occur regexp nil callback) date)))
14573 (defun org-check-after-date (date)
14574 "Check if there are deadlines or scheduled entries after DATE."
14575 (interactive (list (org-read-date)))
14576 (let ((case-fold-search nil)
14577 (regexp (concat "\\<\\(" org-deadline-string
14578 "\\|" org-scheduled-string
14579 "\\) *<\\([^>]+\\)>"))
14580 (callback
14581 (lambda () (not
14582 (time-less-p
14583 (org-time-string-to-time (match-string 2))
14584 (org-time-string-to-time date))))))
14585 (message "%d entries after %s"
14586 (org-occur regexp nil callback) date)))
14588 (defun org-evaluate-time-range (&optional to-buffer)
14589 "Evaluate a time range by computing the difference between start and end.
14590 Normally the result is just printed in the echo area, but with prefix arg
14591 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14592 If the time range is actually in a table, the result is inserted into the
14593 next column.
14594 For time difference computation, a year is assumed to be exactly 365
14595 days in order to avoid rounding problems."
14596 (interactive "P")
14598 (org-clock-update-time-maybe)
14599 (save-excursion
14600 (unless (org-at-date-range-p t)
14601 (goto-char (point-at-bol))
14602 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14603 (if (not (org-at-date-range-p t))
14604 (error "Not at a time-stamp range, and none found in current line")))
14605 (let* ((ts1 (match-string 1))
14606 (ts2 (match-string 2))
14607 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14608 (match-end (match-end 0))
14609 (time1 (org-time-string-to-time ts1))
14610 (time2 (org-time-string-to-time ts2))
14611 (t1 (org-float-time time1))
14612 (t2 (org-float-time time2))
14613 (diff (abs (- t2 t1)))
14614 (negative (< (- t2 t1) 0))
14615 ;; (ys (floor (* 365 24 60 60)))
14616 (ds (* 24 60 60))
14617 (hs (* 60 60))
14618 (fy "%dy %dd %02d:%02d")
14619 (fy1 "%dy %dd")
14620 (fd "%dd %02d:%02d")
14621 (fd1 "%dd")
14622 (fh "%02d:%02d")
14623 y d h m align)
14624 (if havetime
14625 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14627 d (floor (/ diff ds)) diff (mod diff ds)
14628 h (floor (/ diff hs)) diff (mod diff hs)
14629 m (floor (/ diff 60)))
14630 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14632 d (floor (+ (/ diff ds) 0.5))
14633 h 0 m 0))
14634 (if (not to-buffer)
14635 (message "%s" (org-make-tdiff-string y d h m))
14636 (if (org-at-table-p)
14637 (progn
14638 (goto-char match-end)
14639 (setq align t)
14640 (and (looking-at " *|") (goto-char (match-end 0))))
14641 (goto-char match-end))
14642 (if (looking-at
14643 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14644 (replace-match ""))
14645 (if negative (insert " -"))
14646 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14647 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14648 (insert " " (format fh h m))))
14649 (if align (org-table-align))
14650 (message "Time difference inserted")))))
14652 (defun org-make-tdiff-string (y d h m)
14653 (let ((fmt "")
14654 (l nil))
14655 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14656 l (push y l)))
14657 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14658 l (push d l)))
14659 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14660 l (push h l)))
14661 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14662 l (push m l)))
14663 (apply 'format fmt (nreverse l))))
14665 (defun org-time-string-to-time (s)
14666 (apply 'encode-time (org-parse-time-string s)))
14667 (defun org-time-string-to-seconds (s)
14668 (org-float-time (org-time-string-to-time s)))
14670 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14671 "Convert a time stamp to an absolute day number.
14672 If there is a specifyer for a cyclic time stamp, get the closest date to
14673 DAYNR.
14674 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14675 the variable date is bound by the calendar when this is called."
14676 (cond
14677 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14678 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14679 daynr
14680 (+ daynr 1000)))
14681 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14682 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14683 (time-to-days (current-time))) (match-string 0 s)
14684 prefer show-all))
14685 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14687 (defun org-days-to-iso-week (days)
14688 "Return the iso week number."
14689 (require 'cal-iso)
14690 (car (calendar-iso-from-absolute days)))
14692 (defun org-small-year-to-year (year)
14693 "Convert 2-digit years into 4-digit years.
14694 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14695 The year 2000 cannot be abbreviated. Any year larger than 99
14696 is returned unchanged."
14697 (if (< year 38)
14698 (setq year (+ 2000 year))
14699 (if (< year 100)
14700 (setq year (+ 1900 year))))
14701 year)
14703 (defun org-time-from-absolute (d)
14704 "Return the time corresponding to date D.
14705 D may be an absolute day number, or a calendar-type list (month day year)."
14706 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14707 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14709 (defun org-calendar-holiday ()
14710 "List of holidays, for Diary display in Org-mode."
14711 (require 'holidays)
14712 (let ((hl (funcall
14713 (if (fboundp 'calendar-check-holidays)
14714 'calendar-check-holidays 'check-calendar-holidays) date)))
14715 (if hl (mapconcat 'identity hl "; "))))
14717 (defun org-diary-sexp-entry (sexp entry date)
14718 "Process a SEXP diary ENTRY for DATE."
14719 (require 'diary-lib)
14720 (let ((result (if calendar-debug-sexp
14721 (let ((stack-trace-on-error t))
14722 (eval (car (read-from-string sexp))))
14723 (condition-case nil
14724 (eval (car (read-from-string sexp)))
14725 (error
14726 (beep)
14727 (message "Bad sexp at line %d in %s: %s"
14728 (org-current-line)
14729 (buffer-file-name) sexp)
14730 (sleep-for 2))))))
14731 (cond ((stringp result) result)
14732 ((and (consp result)
14733 (stringp (cdr result))) (cdr result))
14734 (result entry)
14735 (t nil))))
14737 (defun org-diary-to-ical-string (frombuf)
14738 "Get iCalendar entries from diary entries in buffer FROMBUF.
14739 This uses the icalendar.el library."
14740 (let* ((tmpdir (if (featurep 'xemacs)
14741 (temp-directory)
14742 temporary-file-directory))
14743 (tmpfile (make-temp-name
14744 (expand-file-name "orgics" tmpdir)))
14745 buf rtn b e)
14746 (with-current-buffer frombuf
14747 (icalendar-export-region (point-min) (point-max) tmpfile)
14748 (setq buf (find-buffer-visiting tmpfile))
14749 (set-buffer buf)
14750 (goto-char (point-min))
14751 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14752 (setq b (match-beginning 0)))
14753 (goto-char (point-max))
14754 (if (re-search-backward "^END:VEVENT" nil t)
14755 (setq e (match-end 0)))
14756 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14757 (kill-buffer buf)
14758 (delete-file tmpfile)
14759 rtn))
14761 (defun org-closest-date (start current change prefer show-all)
14762 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14763 When PREFER is `past' return a date that is either CURRENT or past.
14764 When PREFER is `future', return a date that is either CURRENT or future.
14765 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14766 ;; Make the proper lists from the dates
14767 (catch 'exit
14768 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14769 dn dw sday cday n1 n2 n0
14770 d m y y1 y2 date1 date2 nmonths nm ny m2)
14772 (setq start (org-date-to-gregorian start)
14773 current (org-date-to-gregorian
14774 (if show-all
14775 current
14776 (time-to-days (current-time))))
14777 sday (calendar-absolute-from-gregorian start)
14778 cday (calendar-absolute-from-gregorian current))
14780 (if (<= cday sday) (throw 'exit sday))
14782 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14783 (setq dn (string-to-number (match-string 1 change))
14784 dw (cdr (assoc (match-string 2 change) a1)))
14785 (error "Invalid change specifyer: %s" change))
14786 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14787 (cond
14788 ((eq dw 'day)
14789 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14790 n2 (+ n1 dn)))
14791 ((eq dw 'year)
14792 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14793 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14794 (setq date1 (list m d y1)
14795 n1 (calendar-absolute-from-gregorian date1)
14796 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14797 n2 (calendar-absolute-from-gregorian date2)))
14798 ((eq dw 'month)
14799 ;; approx number of month between the two dates
14800 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14801 ;; How often does dn fit in there?
14802 (setq d (nth 1 start) m (car start) y (nth 2 start)
14803 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14804 m (+ m nm)
14805 ny (floor (/ m 12))
14806 y (+ y ny)
14807 m (- m (* ny 12)))
14808 (while (> m 12) (setq m (- m 12) y (1+ y)))
14809 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14810 (setq m2 (+ m dn) y2 y)
14811 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14812 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14813 (while (<= n2 cday)
14814 (setq n1 n2 m m2 y y2)
14815 (setq m2 (+ m dn) y2 y)
14816 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14817 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14818 ;; Make sure n1 is the earlier date
14819 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14820 (if show-all
14821 (cond
14822 ((eq prefer 'past) (if (= cday n2) n2 n1))
14823 ((eq prefer 'future) (if (= cday n1) n1 n2))
14824 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14825 (cond
14826 ((eq prefer 'past) (if (= cday n2) n2 n1))
14827 ((eq prefer 'future) (if (= cday n1) n1 n2))
14828 (t (if (= cday n1) n1 n2)))))))
14830 (defun org-date-to-gregorian (date)
14831 "Turn any specification of DATE into a gregorian date for the calendar."
14832 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14833 ((and (listp date) (= (length date) 3)) date)
14834 ((stringp date)
14835 (setq date (org-parse-time-string date))
14836 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14837 ((listp date)
14838 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14840 (defun org-parse-time-string (s &optional nodefault)
14841 "Parse the standard Org-mode time string.
14842 This should be a lot faster than the normal `parse-time-string'.
14843 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14844 hour and minute fields will be nil if not given."
14845 (if (string-match org-ts-regexp0 s)
14846 (list 0
14847 (if (or (match-beginning 8) (not nodefault))
14848 (string-to-number (or (match-string 8 s) "0")))
14849 (if (or (match-beginning 7) (not nodefault))
14850 (string-to-number (or (match-string 7 s) "0")))
14851 (string-to-number (match-string 4 s))
14852 (string-to-number (match-string 3 s))
14853 (string-to-number (match-string 2 s))
14854 nil nil nil)
14855 (error "Not a standard Org-mode time string: %s" s)))
14857 (defun org-timestamp-up (&optional arg)
14858 "Increase the date item at the cursor by one.
14859 If the cursor is on the year, change the year. If it is on the month or
14860 the day, change that.
14861 With prefix ARG, change by that many units."
14862 (interactive "p")
14863 (org-timestamp-change (prefix-numeric-value arg)))
14865 (defun org-timestamp-down (&optional arg)
14866 "Decrease the date item at the cursor by one.
14867 If the cursor is on the year, change the year. If it is on the month or
14868 the day, change that.
14869 With prefix ARG, change by that many units."
14870 (interactive "p")
14871 (org-timestamp-change (- (prefix-numeric-value arg))))
14873 (defun org-timestamp-up-day (&optional arg)
14874 "Increase the date in the time stamp by one day.
14875 With prefix ARG, change that many days."
14876 (interactive "p")
14877 (if (and (not (org-at-timestamp-p t))
14878 (org-on-heading-p))
14879 (org-todo 'up)
14880 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14882 (defun org-timestamp-down-day (&optional arg)
14883 "Decrease the date in the time stamp by one day.
14884 With prefix ARG, change that many days."
14885 (interactive "p")
14886 (if (and (not (org-at-timestamp-p t))
14887 (org-on-heading-p))
14888 (org-todo 'down)
14889 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14891 (defun org-at-timestamp-p (&optional inactive-ok)
14892 "Determine if the cursor is in or at a timestamp."
14893 (interactive)
14894 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14895 (pos (point))
14896 (ans (or (looking-at tsr)
14897 (save-excursion
14898 (skip-chars-backward "^[<\n\r\t")
14899 (if (> (point) (point-min)) (backward-char 1))
14900 (and (looking-at tsr)
14901 (> (- (match-end 0) pos) -1))))))
14902 (and ans
14903 (boundp 'org-ts-what)
14904 (setq org-ts-what
14905 (cond
14906 ((= pos (match-beginning 0)) 'bracket)
14907 ((= pos (1- (match-end 0))) 'bracket)
14908 ((org-pos-in-match-range pos 2) 'year)
14909 ((org-pos-in-match-range pos 3) 'month)
14910 ((org-pos-in-match-range pos 7) 'hour)
14911 ((org-pos-in-match-range pos 8) 'minute)
14912 ((or (org-pos-in-match-range pos 4)
14913 (org-pos-in-match-range pos 5)) 'day)
14914 ((and (> pos (or (match-end 8) (match-end 5)))
14915 (< pos (match-end 0)))
14916 (- pos (or (match-end 8) (match-end 5))))
14917 (t 'day))))
14918 ans))
14920 (defun org-toggle-timestamp-type ()
14921 "Toggle the type (<active> or [inactive]) of a time stamp."
14922 (interactive)
14923 (when (org-at-timestamp-p t)
14924 (let ((beg (match-beginning 0)) (end (match-end 0))
14925 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14926 (save-excursion
14927 (goto-char beg)
14928 (while (re-search-forward "[][<>]" end t)
14929 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14930 t t)))
14931 (message "Timestamp is now %sactive"
14932 (if (equal (char-after beg) ?<) "" "in")))))
14934 (defun org-timestamp-change (n &optional what)
14935 "Change the date in the time stamp at point.
14936 The date will be changed by N times WHAT. WHAT can be `day', `month',
14937 `year', `minute', `second'. If WHAT is not given, the cursor position
14938 in the timestamp determines what will be changed."
14939 (let ((pos (point))
14940 with-hm inactive
14941 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14942 org-ts-what
14943 extra rem
14944 ts time time0)
14945 (if (not (org-at-timestamp-p t))
14946 (error "Not at a timestamp"))
14947 (if (and (not what) (eq org-ts-what 'bracket))
14948 (org-toggle-timestamp-type)
14949 (if (and (not what) (not (eq org-ts-what 'day))
14950 org-display-custom-times
14951 (get-text-property (point) 'display)
14952 (not (get-text-property (1- (point)) 'display)))
14953 (setq org-ts-what 'day))
14954 (setq org-ts-what (or what org-ts-what)
14955 inactive (= (char-after (match-beginning 0)) ?\[)
14956 ts (match-string 0))
14957 (replace-match "")
14958 (if (string-match
14959 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14961 (setq extra (match-string 1 ts)))
14962 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14963 (setq with-hm t))
14964 (setq time0 (org-parse-time-string ts))
14965 (when (and (eq org-ts-what 'minute)
14966 (eq current-prefix-arg nil))
14967 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14968 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14969 (setcar (cdr time0) (+ (nth 1 time0)
14970 (if (> n 0) (- rem) (- dm rem))))))
14971 (setq time
14972 (encode-time (or (car time0) 0)
14973 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14974 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14975 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14976 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14977 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14978 (nthcdr 6 time0)))
14979 (when (and (member org-ts-what '(hour minute))
14980 extra
14981 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14982 (setq extra (org-modify-ts-extra
14983 extra
14984 (if (eq org-ts-what 'hour) 2 5)
14985 n dm)))
14986 (when (integerp org-ts-what)
14987 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14988 (if (eq what 'calendar)
14989 (let ((cal-date (org-get-date-from-calendar)))
14990 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14991 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14992 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14993 (setcar time0 (or (car time0) 0))
14994 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14995 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14996 (setq time (apply 'encode-time time0))))
14997 (setq org-last-changed-timestamp
14998 (org-insert-time-stamp time with-hm inactive nil nil extra))
14999 (org-clock-update-time-maybe)
15000 (goto-char pos)
15001 ;; Try to recenter the calendar window, if any
15002 (if (and org-calendar-follow-timestamp-change
15003 (get-buffer-window "*Calendar*" t)
15004 (memq org-ts-what '(day month year)))
15005 (org-recenter-calendar (time-to-days time))))))
15007 (defun org-modify-ts-extra (s pos n dm)
15008 "Change the different parts of the lead-time and repeat fields in timestamp."
15009 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15010 ng h m new rem)
15011 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15012 (cond
15013 ((or (org-pos-in-match-range pos 2)
15014 (org-pos-in-match-range pos 3))
15015 (setq m (string-to-number (match-string 3 s))
15016 h (string-to-number (match-string 2 s)))
15017 (if (org-pos-in-match-range pos 2)
15018 (setq h (+ h n))
15019 (setq n (* dm (org-no-warnings (signum n))))
15020 (when (not (= 0 (setq rem (% m dm))))
15021 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15022 (setq m (+ m n)))
15023 (if (< m 0) (setq m (+ m 60) h (1- h)))
15024 (if (> m 59) (setq m (- m 60) h (1+ h)))
15025 (setq h (min 24 (max 0 h)))
15026 (setq ng 1 new (format "-%02d:%02d" h m)))
15027 ((org-pos-in-match-range pos 6)
15028 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15029 ((org-pos-in-match-range pos 5)
15030 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15032 ((org-pos-in-match-range pos 9)
15033 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15034 ((org-pos-in-match-range pos 8)
15035 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15037 (when ng
15038 (setq s (concat
15039 (substring s 0 (match-beginning ng))
15041 (substring s (match-end ng))))))
15044 (defun org-recenter-calendar (date)
15045 "If the calendar is visible, recenter it to DATE."
15046 (let* ((win (selected-window))
15047 (cwin (get-buffer-window "*Calendar*" t))
15048 (calendar-move-hook nil))
15049 (when cwin
15050 (select-window cwin)
15051 (calendar-goto-date (if (listp date) date
15052 (calendar-gregorian-from-absolute date)))
15053 (select-window win))))
15055 (defun org-goto-calendar (&optional arg)
15056 "Go to the Emacs calendar at the current date.
15057 If there is a time stamp in the current line, go to that date.
15058 A prefix ARG can be used to force the current date."
15059 (interactive "P")
15060 (let ((tsr org-ts-regexp) diff
15061 (calendar-move-hook nil)
15062 (calendar-view-holidays-initially-flag nil)
15063 (calendar-view-diary-initially-flag nil))
15064 (if (or (org-at-timestamp-p)
15065 (save-excursion
15066 (beginning-of-line 1)
15067 (looking-at (concat ".*" tsr))))
15068 (let ((d1 (time-to-days (current-time)))
15069 (d2 (time-to-days
15070 (org-time-string-to-time (match-string 1)))))
15071 (setq diff (- d2 d1))))
15072 (calendar)
15073 (calendar-goto-today)
15074 (if (and diff (not arg)) (calendar-forward-day diff))))
15076 (defun org-get-date-from-calendar ()
15077 "Return a list (month day year) of date at point in calendar."
15078 (with-current-buffer "*Calendar*"
15079 (save-match-data
15080 (calendar-cursor-to-date))))
15082 (defun org-date-from-calendar ()
15083 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15084 If there is already a time stamp at the cursor position, update it."
15085 (interactive)
15086 (if (org-at-timestamp-p t)
15087 (org-timestamp-change 0 'calendar)
15088 (let ((cal-date (org-get-date-from-calendar)))
15089 (org-insert-time-stamp
15090 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15092 (defun org-minutes-to-hh:mm-string (m)
15093 "Compute H:MM from a number of minutes."
15094 (let ((h (/ m 60)))
15095 (setq m (- m (* 60 h)))
15096 (format org-time-clocksum-format h m)))
15098 (defun org-hh:mm-string-to-minutes (s)
15099 "Convert a string H:MM to a number of minutes.
15100 If the string is just a number, interpret it as minutes.
15101 In fact, the first hh:mm or number in the string will be taken,
15102 there can be extra stuff in the string.
15103 If no number is found, the return value is 0."
15104 (cond
15105 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15106 (+ (* (string-to-number (match-string 1 s)) 60)
15107 (string-to-number (match-string 2 s))))
15108 ((string-match "\\([0-9]+\\)" s)
15109 (string-to-number (match-string 1 s)))
15110 (t 0)))
15112 ;;;; Files
15114 (defun org-save-all-org-buffers ()
15115 "Save all Org-mode buffers without user confirmation."
15116 (interactive)
15117 (message "Saving all Org-mode buffers...")
15118 (save-some-buffers t 'org-mode-p)
15119 (when (featurep 'org-id) (org-id-locations-save))
15120 (message "Saving all Org-mode buffers... done"))
15122 (defun org-revert-all-org-buffers ()
15123 "Revert all Org-mode buffers.
15124 Prompt for confirmation when there are unsaved changes.
15125 Be sure you know what you are doing before letting this function
15126 overwrite your changes.
15128 This function is useful in a setup where one tracks org files
15129 with a version control system, to revert on one machine after pulling
15130 changes from another. I believe the procedure must be like this:
15132 1. M-x org-save-all-org-buffers
15133 2. Pull changes from the other machine, resolve conflicts
15134 3. M-x org-revert-all-org-buffers"
15135 (interactive)
15136 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15137 (error "Abort"))
15138 (save-excursion
15139 (save-window-excursion
15140 (mapc
15141 (lambda (b)
15142 (when (and (with-current-buffer b (org-mode-p))
15143 (with-current-buffer b buffer-file-name))
15144 (switch-to-buffer b)
15145 (revert-buffer t 'no-confirm)))
15146 (buffer-list))
15147 (when (and (featurep 'org-id) org-id-track-globally)
15148 (org-id-locations-load)))))
15150 ;;;; Agenda files
15152 ;;;###autoload
15153 (defun org-iswitchb (&optional arg)
15154 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
15155 With a prefix argument, restrict available to files.
15156 With two prefix arguments, restrict available buffers to agenda files."
15157 (interactive "P")
15158 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15159 ((equal arg '(16)) (org-buffer-list 'agenda))
15160 (t (org-buffer-list)))))
15161 (switch-to-buffer
15162 (org-icompleting-read "Org buffer: "
15163 (mapcar 'list (mapcar 'buffer-name blist))
15164 nil t))))
15166 ;;;###autoload
15167 (defalias 'org-ido-switchb 'org-iswitchb)
15169 (defun org-buffer-list (&optional predicate exclude-tmp)
15170 "Return a list of Org buffers.
15171 PREDICATE can be `export', `files' or `agenda'.
15173 export restrict the list to Export buffers.
15174 files restrict the list to buffers visiting Org files.
15175 agenda restrict the list to buffers visiting agenda files.
15177 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15178 (let* ((bfn nil)
15179 (agenda-files (and (eq predicate 'agenda)
15180 (mapcar 'file-truename (org-agenda-files t))))
15181 (filter
15182 (cond
15183 ((eq predicate 'files)
15184 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15185 ((eq predicate 'export)
15186 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15187 ((eq predicate 'agenda)
15188 (lambda (b)
15189 (with-current-buffer b
15190 (and (eq major-mode 'org-mode)
15191 (setq bfn (buffer-file-name b))
15192 (member (file-truename bfn) agenda-files)))))
15193 (t (lambda (b) (with-current-buffer b
15194 (or (eq major-mode 'org-mode)
15195 (string-match "\*Org .*Export"
15196 (buffer-name b)))))))))
15197 (delq nil
15198 (mapcar
15199 (lambda(b)
15200 (if (and (funcall filter b)
15201 (or (not exclude-tmp)
15202 (not (string-match "tmp" (buffer-name b)))))
15204 nil))
15205 (buffer-list)))))
15207 (defun org-agenda-files (&optional unrestricted archives)
15208 "Get the list of agenda files.
15209 Optional UNRESTRICTED means return the full list even if a restriction
15210 is currently in place.
15211 When ARCHIVES is t, include all archive files that are really being
15212 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15213 `org-agenda-archives-mode' is t."
15214 (let ((files
15215 (cond
15216 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15217 ((stringp org-agenda-files) (org-read-agenda-file-list))
15218 ((listp org-agenda-files) org-agenda-files)
15219 (t (error "Invalid value of `org-agenda-files'")))))
15220 (setq files (apply 'append
15221 (mapcar (lambda (f)
15222 (if (file-directory-p f)
15223 (directory-files
15224 f t org-agenda-file-regexp)
15225 (list f)))
15226 files)))
15227 (when org-agenda-skip-unavailable-files
15228 (setq files (delq nil
15229 (mapcar (function
15230 (lambda (file)
15231 (and (file-readable-p file) file)))
15232 files))))
15233 (when (or (eq archives t)
15234 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15235 (setq files (org-add-archive-files files)))
15236 files))
15238 (defun org-agenda-file-p (&optional file)
15239 "Return non-nil, if FILE is an agenda file.
15240 If FILE is omitted, use the file associated with the current
15241 buffer."
15242 (member (or file (buffer-file-name))
15243 (org-agenda-files t)))
15245 (defun org-edit-agenda-file-list ()
15246 "Edit the list of agenda files.
15247 Depending on setup, this either uses customize to edit the variable
15248 `org-agenda-files', or it visits the file that is holding the list. In the
15249 latter case, the buffer is set up in a way that saving it automatically kills
15250 the buffer and restores the previous window configuration."
15251 (interactive)
15252 (if (stringp org-agenda-files)
15253 (let ((cw (current-window-configuration)))
15254 (find-file org-agenda-files)
15255 (org-set-local 'org-window-configuration cw)
15256 (org-add-hook 'after-save-hook
15257 (lambda ()
15258 (set-window-configuration
15259 (prog1 org-window-configuration
15260 (kill-buffer (current-buffer))))
15261 (org-install-agenda-files-menu)
15262 (message "New agenda file list installed"))
15263 nil 'local)
15264 (message "%s" (substitute-command-keys
15265 "Edit list and finish with \\[save-buffer]")))
15266 (customize-variable 'org-agenda-files)))
15268 (defun org-store-new-agenda-file-list (list)
15269 "Set new value for the agenda file list and save it correctly."
15270 (if (stringp org-agenda-files)
15271 (let ((fe (org-read-agenda-file-list t)) b u)
15272 (while (setq b (find-buffer-visiting org-agenda-files))
15273 (kill-buffer b))
15274 (with-temp-file org-agenda-files
15275 (insert
15276 (mapconcat
15277 (lambda (f) ;; Keep un-expanded entries.
15278 (if (setq u (assoc f fe))
15279 (cdr u)
15281 list "\n")
15282 "\n")))
15283 (let ((org-mode-hook nil) (org-inhibit-startup t)
15284 (org-insert-mode-line-in-empty-file nil))
15285 (setq org-agenda-files list)
15286 (customize-save-variable 'org-agenda-files org-agenda-files))))
15288 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15289 "Read the list of agenda files from a file.
15290 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15291 filenames, used by `org-store-new-agenda-file-list' to write back
15292 un-expanded file names."
15293 (when (file-directory-p org-agenda-files)
15294 (error "`org-agenda-files' cannot be a single directory"))
15295 (when (stringp org-agenda-files)
15296 (with-temp-buffer
15297 (insert-file-contents org-agenda-files)
15298 (mapcar
15299 (lambda (f)
15300 (let ((e (expand-file-name (substitute-in-file-name f)
15301 org-directory)))
15302 (if pair-with-expansion
15303 (cons e f)
15304 e)))
15305 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15307 ;;;###autoload
15308 (defun org-cycle-agenda-files ()
15309 "Cycle through the files in `org-agenda-files'.
15310 If the current buffer visits an agenda file, find the next one in the list.
15311 If the current buffer does not, find the first agenda file."
15312 (interactive)
15313 (let* ((fs (org-agenda-files t))
15314 (files (append fs (list (car fs))))
15315 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15316 file)
15317 (unless files (error "No agenda files"))
15318 (catch 'exit
15319 (while (setq file (pop files))
15320 (if (equal (file-truename file) tcf)
15321 (when (car files)
15322 (find-file (car files))
15323 (throw 'exit t))))
15324 (find-file (car fs)))
15325 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15327 (defun org-agenda-file-to-front (&optional to-end)
15328 "Move/add the current file to the top of the agenda file list.
15329 If the file is not present in the list, it is added to the front. If it is
15330 present, it is moved there. With optional argument TO-END, add/move to the
15331 end of the list."
15332 (interactive "P")
15333 (let ((org-agenda-skip-unavailable-files nil)
15334 (file-alist (mapcar (lambda (x)
15335 (cons (file-truename x) x))
15336 (org-agenda-files t)))
15337 (ctf (file-truename buffer-file-name))
15338 x had)
15339 (setq x (assoc ctf file-alist) had x)
15341 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15342 (if to-end
15343 (setq file-alist (append (delq x file-alist) (list x)))
15344 (setq file-alist (cons x (delq x file-alist))))
15345 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15346 (org-install-agenda-files-menu)
15347 (message "File %s to %s of agenda file list"
15348 (if had "moved" "added") (if to-end "end" "front"))))
15350 (defun org-remove-file (&optional file)
15351 "Remove current file from the list of files in variable `org-agenda-files'.
15352 These are the files which are being checked for agenda entries.
15353 Optional argument FILE means use this file instead of the current."
15354 (interactive)
15355 (let* ((org-agenda-skip-unavailable-files nil)
15356 (file (or file buffer-file-name))
15357 (true-file (file-truename file))
15358 (afile (abbreviate-file-name file))
15359 (files (delq nil (mapcar
15360 (lambda (x)
15361 (if (equal true-file
15362 (file-truename x))
15363 nil x))
15364 (org-agenda-files t)))))
15365 (if (not (= (length files) (length (org-agenda-files t))))
15366 (progn
15367 (org-store-new-agenda-file-list files)
15368 (org-install-agenda-files-menu)
15369 (message "Removed file: %s" afile))
15370 (message "File was not in list: %s (not removed)" afile))))
15372 (defun org-file-menu-entry (file)
15373 (vector file (list 'find-file file) t))
15375 (defun org-check-agenda-file (file)
15376 "Make sure FILE exists. If not, ask user what to do."
15377 (when (not (file-exists-p file))
15378 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15379 (abbreviate-file-name file))
15380 (let ((r (downcase (read-char-exclusive))))
15381 (cond
15382 ((equal r ?r)
15383 (org-remove-file file)
15384 (throw 'nextfile t))
15385 (t (error "Abort"))))))
15387 (defun org-get-agenda-file-buffer (file)
15388 "Get a buffer visiting FILE. If the buffer needs to be created, add
15389 it to the list of buffers which might be released later."
15390 (let ((buf (org-find-base-buffer-visiting file)))
15391 (if buf
15392 buf ; just return it
15393 ;; Make a new buffer and remember it
15394 (setq buf (find-file-noselect file))
15395 (if buf (push buf org-agenda-new-buffers))
15396 buf)))
15398 (defun org-release-buffers (blist)
15399 "Release all buffers in list, asking the user for confirmation when needed.
15400 When a buffer is unmodified, it is just killed. When modified, it is saved
15401 \(if the user agrees) and then killed."
15402 (let (buf file)
15403 (while (setq buf (pop blist))
15404 (setq file (buffer-file-name buf))
15405 (when (and (buffer-modified-p buf)
15406 file
15407 (y-or-n-p (format "Save file %s? " file)))
15408 (with-current-buffer buf (save-buffer)))
15409 (kill-buffer buf))))
15411 (defun org-prepare-agenda-buffers (files)
15412 "Create buffers for all agenda files, protect archived trees and comments."
15413 (interactive)
15414 (let ((pa '(:org-archived t))
15415 (pc '(:org-comment t))
15416 (pall '(:org-archived t :org-comment t))
15417 (inhibit-read-only t)
15418 (rea (concat ":" org-archive-tag ":"))
15419 bmp file re)
15420 (save-excursion
15421 (save-restriction
15422 (while (setq file (pop files))
15423 (catch 'nextfile
15424 (if (bufferp file)
15425 (set-buffer file)
15426 (org-check-agenda-file file)
15427 (set-buffer (org-get-agenda-file-buffer file)))
15428 (widen)
15429 (setq bmp (buffer-modified-p))
15430 (org-refresh-category-properties)
15431 (setq org-todo-keywords-for-agenda
15432 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15433 (setq org-done-keywords-for-agenda
15434 (append org-done-keywords-for-agenda org-done-keywords))
15435 (setq org-todo-keyword-alist-for-agenda
15436 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15437 (setq org-drawers-for-agenda
15438 (append org-drawers-for-agenda org-drawers))
15439 (setq org-tag-alist-for-agenda
15440 (append org-tag-alist-for-agenda org-tag-alist))
15442 (save-excursion
15443 (remove-text-properties (point-min) (point-max) pall)
15444 (when org-agenda-skip-archived-trees
15445 (goto-char (point-min))
15446 (while (re-search-forward rea nil t)
15447 (if (org-on-heading-p t)
15448 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15449 (goto-char (point-min))
15450 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15451 (while (re-search-forward re nil t)
15452 (add-text-properties
15453 (match-beginning 0) (org-end-of-subtree t) pc)))
15454 (set-buffer-modified-p bmp)))))
15455 (setq org-todo-keywords-for-agenda
15456 (org-uniquify org-todo-keywords-for-agenda))
15457 (setq org-todo-keyword-alist-for-agenda
15458 (org-uniquify org-todo-keyword-alist-for-agenda)
15459 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15461 ;;;; Embedded LaTeX
15463 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15464 "Keymap for the minor `org-cdlatex-mode'.")
15466 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15467 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15468 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15469 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15470 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15472 (defvar org-cdlatex-texmathp-advice-is-done nil
15473 "Flag remembering if we have applied the advice to texmathp already.")
15475 (define-minor-mode org-cdlatex-mode
15476 "Toggle the minor `org-cdlatex-mode'.
15477 This mode supports entering LaTeX environment and math in LaTeX fragments
15478 in Org-mode.
15479 \\{org-cdlatex-mode-map}"
15480 nil " OCDL" nil
15481 (when org-cdlatex-mode (require 'cdlatex))
15482 (unless org-cdlatex-texmathp-advice-is-done
15483 (setq org-cdlatex-texmathp-advice-is-done t)
15484 (defadvice texmathp (around org-math-always-on activate)
15485 "Always return t in org-mode buffers.
15486 This is because we want to insert math symbols without dollars even outside
15487 the LaTeX math segments. If Orgmode thinks that point is actually inside
15488 an embedded LaTeX fragment, let texmathp do its job.
15489 \\[org-cdlatex-mode-map]"
15490 (interactive)
15491 (let (p)
15492 (cond
15493 ((not (org-mode-p)) ad-do-it)
15494 ((eq this-command 'cdlatex-math-symbol)
15495 (setq ad-return-value t
15496 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15498 (let ((p (org-inside-LaTeX-fragment-p)))
15499 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15500 (setq ad-return-value t
15501 texmathp-why '("Org-mode embedded math" . 0))
15502 (if p ad-do-it)))))))))
15504 (defun turn-on-org-cdlatex ()
15505 "Unconditionally turn on `org-cdlatex-mode'."
15506 (org-cdlatex-mode 1))
15508 (defun org-inside-LaTeX-fragment-p ()
15509 "Test if point is inside a LaTeX fragment.
15510 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15511 sequence appearing also before point.
15512 Even though the matchers for math are configurable, this function assumes
15513 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15514 delimiters are skipped when they have been removed by customization.
15515 The return value is nil, or a cons cell with the delimiter and
15516 and the position of this delimiter.
15518 This function does a reasonably good job, but can locally be fooled by
15519 for example currency specifications. For example it will assume being in
15520 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15521 fragments that are properly closed, but during editing, we have to live
15522 with the uncertainty caused by missing closing delimiters. This function
15523 looks only before point, not after."
15524 (catch 'exit
15525 (let ((pos (point))
15526 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15527 (lim (progn
15528 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15529 (point)))
15530 dd-on str (start 0) m re)
15531 (goto-char pos)
15532 (when dodollar
15533 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15534 re (nth 1 (assoc "$" org-latex-regexps)))
15535 (while (string-match re str start)
15536 (cond
15537 ((= (match-end 0) (length str))
15538 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15539 ((= (match-end 0) (- (length str) 5))
15540 (throw 'exit nil))
15541 (t (setq start (match-end 0))))))
15542 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15543 (goto-char pos)
15544 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15545 (and (match-beginning 2) (throw 'exit nil))
15546 ;; count $$
15547 (while (re-search-backward "\\$\\$" lim t)
15548 (setq dd-on (not dd-on)))
15549 (goto-char pos)
15550 (if dd-on (cons "$$" m))))))
15552 (defun org-inside-latex-macro-p ()
15553 "Is point inside a LaTeX macro or its arguments?"
15554 (save-match-data
15555 (org-in-regexp
15556 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15558 (defun test ()
15559 (interactive)
15560 (message "%s" (org-inside-latex-macro-p)))
15562 (defun org-try-cdlatex-tab ()
15563 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15564 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15565 - inside a LaTeX fragment, or
15566 - after the first word in a line, where an abbreviation expansion could
15567 insert a LaTeX environment."
15568 (when org-cdlatex-mode
15569 (cond
15570 ((save-excursion
15571 (skip-chars-backward "a-zA-Z0-9*")
15572 (skip-chars-backward " \t")
15573 (bolp))
15574 (cdlatex-tab) t)
15575 ((org-inside-LaTeX-fragment-p)
15576 (cdlatex-tab) t)
15577 (t nil))))
15579 (defun org-cdlatex-underscore-caret (&optional arg)
15580 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15581 Revert to the normal definition outside of these fragments."
15582 (interactive "P")
15583 (if (org-inside-LaTeX-fragment-p)
15584 (call-interactively 'cdlatex-sub-superscript)
15585 (let (org-cdlatex-mode)
15586 (call-interactively (key-binding (vector last-input-event))))))
15588 (defun org-cdlatex-math-modify (&optional arg)
15589 "Execute `cdlatex-math-modify' in LaTeX fragments.
15590 Revert to the normal definition outside of these fragments."
15591 (interactive "P")
15592 (if (org-inside-LaTeX-fragment-p)
15593 (call-interactively 'cdlatex-math-modify)
15594 (let (org-cdlatex-mode)
15595 (call-interactively (key-binding (vector last-input-event))))))
15597 (defvar org-latex-fragment-image-overlays nil
15598 "List of overlays carrying the images of latex fragments.")
15599 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15601 (defun org-remove-latex-fragment-image-overlays ()
15602 "Remove all overlays with LaTeX fragment images in current buffer."
15603 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15604 (setq org-latex-fragment-image-overlays nil))
15606 (defun org-preview-latex-fragment (&optional subtree)
15607 "Preview the LaTeX fragment at point, or all locally or globally.
15608 If the cursor is in a LaTeX fragment, create the image and overlay
15609 it over the source code. If there is no fragment at point, display
15610 all fragments in the current text, from one headline to the next. With
15611 prefix SUBTREE, display all fragments in the current subtree. With a
15612 double prefix `C-u C-u', or when the cursor is before the first headline,
15613 display all fragments in the buffer.
15614 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15615 (interactive "P")
15616 (org-remove-latex-fragment-image-overlays)
15617 (save-excursion
15618 (save-restriction
15619 (let (beg end at msg)
15620 (cond
15621 ((or (equal subtree '(16))
15622 (not (save-excursion
15623 (re-search-backward (concat "^" outline-regexp) nil t))))
15624 (setq beg (point-min) end (point-max)
15625 msg "Creating images for buffer...%s"))
15626 ((equal subtree '(4))
15627 (org-back-to-heading)
15628 (setq beg (point) end (org-end-of-subtree t)
15629 msg "Creating images for subtree...%s"))
15631 (if (setq at (org-inside-LaTeX-fragment-p))
15632 (goto-char (max (point-min) (- (cdr at) 2)))
15633 (org-back-to-heading))
15634 (setq beg (point) end (progn (outline-next-heading) (point))
15635 msg (if at "Creating image...%s"
15636 "Creating images for entry...%s"))))
15637 (message msg "")
15638 (narrow-to-region beg end)
15639 (goto-char beg)
15640 (org-format-latex
15641 (concat "ltxpng/" (file-name-sans-extension
15642 (file-name-nondirectory
15643 buffer-file-name)))
15644 default-directory 'overlays msg at 'forbuffer)
15645 (message msg "done. Use `C-c C-c' to remove images.")))))
15647 (defvar org-latex-regexps
15648 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15649 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15650 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15651 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15652 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15653 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15654 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15655 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15656 "Regular expressions for matching embedded LaTeX.")
15658 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15659 "Replace LaTeX fragments with links to an image, and produce images.
15660 Some of the options can be changed using the variable
15661 `org-format-latex-options'."
15662 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15663 (let* ((prefixnodir (file-name-nondirectory prefix))
15664 (absprefix (expand-file-name prefix dir))
15665 (todir (file-name-directory absprefix))
15666 (opt org-format-latex-options)
15667 (matchers (plist-get opt :matchers))
15668 (re-list org-latex-regexps)
15669 (org-format-latex-header-extra
15670 (plist-get (org-infile-export-plist) :latex-header-extra))
15671 (cnt 0) txt hash link beg end re e checkdir
15672 executables-checked
15673 m n block linkfile movefile ov)
15674 ;; Check the different regular expressions
15675 (while (setq e (pop re-list))
15676 (setq m (car e) re (nth 1 e) n (nth 2 e)
15677 block (if (nth 3 e) "\n\n" ""))
15678 (when (member m matchers)
15679 (goto-char (point-min))
15680 (while (re-search-forward re nil t)
15681 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15682 (not (get-text-property (match-beginning n)
15683 'org-protected))
15684 (or (not overlays)
15685 (not (eq (get-char-property (match-beginning n)
15686 'org-overlay-type)
15687 'org-latex-overlay))))
15688 (setq txt (match-string n)
15689 beg (match-beginning n) end (match-end n)
15690 cnt (1+ cnt))
15691 (let (print-length print-level) ; make sure full list is printed
15692 (setq hash (sha1 (prin1-to-string
15693 (list org-format-latex-header
15694 org-format-latex-header-extra
15695 org-export-latex-default-packages-alist
15696 org-export-latex-packages-alist
15697 org-format-latex-options
15698 forbuffer txt)))
15699 linkfile (format "%s_%s.png" prefix hash)
15700 movefile (format "%s_%s.png" absprefix hash)))
15701 (setq link (concat block "[[file:" linkfile "]]" block))
15702 (if msg (message msg cnt))
15703 (goto-char beg)
15704 (unless checkdir ; make sure the directory exists
15705 (setq checkdir t)
15706 (or (file-directory-p todir) (make-directory todir)))
15708 (unless executables-checked
15709 (org-check-external-command
15710 "latex" "needed to convert LaTeX fragments to images")
15711 (org-check-external-command
15712 "dvipng" "needed to convert LaTeX fragments to images")
15713 (setq executables-checked t))
15715 (unless (file-exists-p movefile)
15716 (org-create-formula-image
15717 txt movefile opt forbuffer))
15718 (if overlays
15719 (progn
15720 (mapc (lambda (o)
15721 (if (eq (overlay-get o 'org-overlay-type)
15722 'org-latex-overlay)
15723 (delete-overlay o)))
15724 (overlays-in beg end))
15725 (setq ov (make-overlay beg end))
15726 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15727 (if (featurep 'xemacs)
15728 (progn
15729 (overlay-put ov 'invisible t)
15730 (overlay-put
15731 ov 'end-glyph
15732 (make-glyph (vector 'png :file movefile))))
15733 (overlay-put
15734 ov 'display
15735 (list 'image :type 'png :file movefile :ascent 'center)))
15736 (push ov org-latex-fragment-image-overlays)
15737 (goto-char end))
15738 (delete-region beg end)
15739 (insert (org-add-props link
15740 (list 'org-latex-src
15741 (replace-regexp-in-string "\"" "" txt)))))))))))
15743 ;; This function borrows from Ganesh Swami's latex2png.el
15744 (defun org-create-formula-image (string tofile options buffer)
15745 "This calls dvipng."
15746 (require 'org-latex)
15747 (let* ((tmpdir (if (featurep 'xemacs)
15748 (temp-directory)
15749 temporary-file-directory))
15750 (texfilebase (make-temp-name
15751 (expand-file-name "orgtex" tmpdir)))
15752 (texfile (concat texfilebase ".tex"))
15753 (dvifile (concat texfilebase ".dvi"))
15754 (pngfile (concat texfilebase ".png"))
15755 (fnh (if (featurep 'xemacs)
15756 (font-height (get-face-font 'default))
15757 (face-attribute 'default :height nil)))
15758 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15759 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15760 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15761 "Black"))
15762 (bg (or (plist-get options (if buffer :background :html-background))
15763 "Transparent")))
15764 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15765 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15766 (with-temp-file texfile
15767 (insert (org-splice-latex-header
15768 org-format-latex-header
15769 org-export-latex-default-packages-alist
15770 org-export-latex-packages-alist t
15771 org-format-latex-header-extra))
15772 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15773 (require 'org-latex)
15774 (org-export-latex-fix-inputenc))
15775 (let ((dir default-directory))
15776 (condition-case nil
15777 (progn
15778 (cd tmpdir)
15779 (call-process "latex" nil nil nil texfile))
15780 (error nil))
15781 (cd dir))
15782 (if (not (file-exists-p dvifile))
15783 (progn (message "Failed to create dvi file from %s" texfile) nil)
15784 (condition-case nil
15785 (call-process "dvipng" nil nil nil
15786 "-fg" fg "-bg" bg
15787 "-D" dpi
15788 ;;"-x" scale "-y" scale
15789 "-T" "tight"
15790 "-o" pngfile
15791 dvifile)
15792 (error nil))
15793 (if (not (file-exists-p pngfile))
15794 (if org-format-latex-signal-error
15795 (error "Failed to create png file from %s" texfile)
15796 (message "Failed to create png file from %s" texfile)
15797 nil)
15798 ;; Use the requested file name and clean up
15799 (copy-file pngfile tofile 'replace)
15800 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15801 (delete-file (concat texfilebase e)))
15802 pngfile))))
15804 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15805 "Fill a LaTeX header template TPL.
15806 In the template, the following place holders will be recognized:
15808 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15809 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15810 [PACKAGES] \\usepackage statements for PKG
15811 [NO-PACKAGES] do not include PKG
15812 [EXTRA] the string EXTRA
15813 [NO-EXTRA] do not include EXTRA
15815 For backward compatibility, if both the positive and the negative place
15816 holder is missing, the positive one (without the \"NO-\") will be
15817 assumed to be present at the end of the template.
15818 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15819 EXTRA is a string.
15820 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15821 (let (rpl (end ""))
15822 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15823 (setq rpl (if (or (match-end 1) (not def-pkg))
15824 "" (org-latex-packages-to-string def-pkg snippets-p t))
15825 tpl (replace-match rpl t t tpl))
15826 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15828 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15829 (setq rpl (if (or (match-end 1) (not pkg))
15830 "" (org-latex-packages-to-string pkg snippets-p t))
15831 tpl (replace-match rpl t t tpl))
15832 (if pkg (setq end
15833 (concat end "\n"
15834 (org-latex-packages-to-string pkg snippets-p)))))
15836 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15837 (setq rpl (if (or (match-end 1) (not extra))
15838 "" (concat extra "\n"))
15839 tpl (replace-match rpl t t tpl))
15840 (if (and extra (string-match "\\S-" extra))
15841 (setq end (concat end "\n" extra))))
15843 (if (string-match "\\S-" end)
15844 (concat tpl "\n" end)
15845 tpl)))
15847 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
15848 "Turn an alist of packages into a string with the \\usepackage macros."
15849 (setq pkg (mapconcat (lambda(p)
15850 (cond
15851 ((stringp p) p)
15852 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
15853 (format "%% Package %s omitted" (cadr p)))
15854 ((equal "" (car p))
15855 (format "\\usepackage{%s}" (cadr p)))
15857 (format "\\usepackage[%s]{%s}"
15858 (car p) (cadr p)))))
15860 "\n"))
15861 (if newline (concat pkg "\n") pkg))
15863 (defun org-dvipng-color (attr)
15864 "Return an rgb color specification for dvipng."
15865 (apply 'format "rgb %s %s %s"
15866 (mapcar 'org-normalize-color
15867 (color-values (face-attribute 'default attr nil)))))
15869 (defun org-normalize-color (value)
15870 "Return string to be used as color value for an RGB component."
15871 (format "%g" (/ value 65535.0)))
15873 ;; Image display
15876 (defvar org-inline-image-overlays nil)
15877 (make-variable-buffer-local 'org-inline-image-overlays)
15879 (defun org-toggle-inline-images (&optional include-linked)
15880 "Toggle the display of inline images.
15881 INCLUDE-LINKED is passed to `org-display-inline-images'."
15882 (interactive "P")
15883 (if org-inline-image-overlays
15884 (progn
15885 (org-remove-inline-images)
15886 (message "Inline image display turned off"))
15887 (org-display-inline-images include-linked)
15888 (if org-inline-image-overlays
15889 (message "%d images displayed inline"
15890 (length org-inline-image-overlays))
15891 (message "No images to display inline"))))
15893 (defun org-display-inline-images (&optional include-linked refresh beg end)
15894 "Display inline images.
15895 Normally only links without a description part are inlined, because this
15896 is how it will work for export. When INCLUDE-LINKED is set, also links
15897 with a description part will be inlined. This can be nice for a quick
15898 look at those images, but it does not reflect whatexported files will look
15899 like.
15900 When REFRESH is set, refresh existing images between BEG and END.
15901 This will create new image displays only if necessary.
15902 BEG and END default to the buffer boundaries."
15903 (interactive "P")
15904 (unless refresh
15905 (org-remove-inline-images)
15906 (clear-image-cache))
15907 (save-excursion
15908 (save-restriction
15909 (widen)
15910 (setq beg (or beg (point-min)) end (or end (point-max)))
15911 (goto-char (point-min))
15912 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~./_0-9a-zA-Z]+"
15913 (substring (org-image-file-name-regexp) 0 -2)
15914 "\\)\\]" (if include-linked "" "\\]")))
15915 old file ov img)
15916 (while (re-search-forward re end t)
15917 (setq old (get-char-property-and-overlay (match-beginning 1)
15918 'org-image-overlay))
15919 (setq file (expand-file-name
15920 (concat (or (match-string 3) "") (match-string 4))))
15921 (when (file-exists-p file)
15922 (if (and (car-safe old) refresh)
15923 (image-refresh (overlay-get (cdr old) 'display))
15924 (setq img (create-image file))
15925 (when img
15926 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
15927 (overlay-put ov 'display img)
15928 (overlay-put ov 'face 'default)
15929 (overlay-put ov 'org-image-overlay t)
15930 (push ov org-inline-image-overlays)))))))))
15932 (defun org-remove-inline-images ()
15933 "Remove inline display of images."
15934 (interactive)
15935 (mapc 'delete-overlay org-inline-image-overlays)
15936 (setq org-inline-image-overlays nil))
15938 ;;;; Key bindings
15940 ;; Make `C-c C-x' a prefix key
15941 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15943 ;; TAB key with modifiers
15944 (org-defkey org-mode-map "\C-i" 'org-cycle)
15945 (org-defkey org-mode-map [(tab)] 'org-cycle)
15946 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15947 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15948 (org-defkey org-mode-map "\M-\t" 'org-complete)
15949 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15950 ;; The following line is necessary under Suse GNU/Linux
15951 (unless (featurep 'xemacs)
15952 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15953 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15954 (define-key org-mode-map [backtab] 'org-shifttab)
15956 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15957 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15958 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15960 ;; Cursor keys with modifiers
15961 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15962 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15963 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15964 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15966 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15967 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15968 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15969 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15971 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15972 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15973 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15974 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15976 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15977 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15979 ;;; Extra keys for tty access.
15980 ;; We only set them when really needed because otherwise the
15981 ;; menus don't show the simple keys
15983 (when (or org-use-extra-keys
15984 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15985 (not window-system))
15986 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15987 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15988 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15989 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15990 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15991 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15992 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15993 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15994 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15995 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15996 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15997 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15998 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15999 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16000 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16001 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16002 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16003 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16004 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16005 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16006 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16007 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16008 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16009 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16010 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16011 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16012 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16013 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16015 ;; All the other keys
16017 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16018 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16019 (if (boundp 'narrow-map)
16020 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16021 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16022 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16023 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16024 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16025 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16026 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16027 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16028 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16029 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16030 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16031 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16032 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16033 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16034 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16035 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16036 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16037 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16038 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16039 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16040 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16041 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16042 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16043 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16044 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16045 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16046 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16047 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16048 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16049 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16050 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16051 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16052 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16053 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16054 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16055 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16056 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16057 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16058 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16059 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16060 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16061 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16062 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16063 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16064 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16065 (org-defkey org-mode-map "\C-c^" 'org-sort)
16066 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16067 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16068 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16069 (org-defkey org-mode-map "\C-m" 'org-return)
16070 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16071 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16072 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16073 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16074 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16075 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16076 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16077 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16078 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16079 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16080 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16081 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16082 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16083 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16084 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16085 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16086 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16087 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16088 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16089 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16090 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16092 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16093 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16094 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16095 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16097 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16098 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16099 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16100 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16101 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16102 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16103 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16104 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16105 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16106 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16107 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16108 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16109 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16110 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16111 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16112 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16113 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16115 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16116 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16117 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16118 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16120 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16122 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16124 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16125 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16127 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16130 (when (featurep 'xemacs)
16131 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16134 (defconst org-speed-commands-default
16136 ("Outline Navigation")
16137 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16138 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16139 ("f" . (org-speed-move-safe 'org-forward-same-level))
16140 ("b" . (org-speed-move-safe 'org-backward-same-level))
16141 ("u" . (org-speed-move-safe 'outline-up-heading))
16142 ("j" . org-goto)
16143 ("g" . (org-refile t))
16144 ("Outline Visibility")
16145 ("c" . org-cycle)
16146 ("C" . org-shifttab)
16147 (" " . org-display-outline-path)
16148 ("Outline Structure Editing")
16149 ("U" . org-shiftmetaup)
16150 ("D" . org-shiftmetadown)
16151 ("r" . org-metaright)
16152 ("l" . org-metaleft)
16153 ("R" . org-shiftmetaright)
16154 ("L" . org-shiftmetaleft)
16155 ("i" . (progn (forward-char 1) (call-interactively
16156 'org-insert-heading-respect-content)))
16157 ("^" . org-sort)
16158 ("w" . org-refile)
16159 ("a" . org-archive-subtree-default-with-confirmation)
16160 ("." . outline-mark-subtree)
16161 ("Clock Commands")
16162 ("I" . org-clock-in)
16163 ("O" . org-clock-out)
16164 ("Meta Data Editing")
16165 ("t" . org-todo)
16166 ("0" . (org-priority ?\ ))
16167 ("1" . (org-priority ?A))
16168 ("2" . (org-priority ?B))
16169 ("3" . (org-priority ?C))
16170 (";" . org-set-tags-command)
16171 ("e" . org-set-effort)
16172 ("Agenda Views etc")
16173 ("v" . org-agenda)
16174 ("/" . org-sparse-tree)
16175 ("Misc")
16176 ("o" . org-open-at-point)
16177 ("?" . org-speed-command-help)
16179 "The default speed commands.")
16181 (defun org-print-speed-command (e)
16182 (if (> (length (car e)) 1)
16183 (progn
16184 (princ "\n")
16185 (princ (car e))
16186 (princ "\n")
16187 (princ (make-string (length (car e)) ?-))
16188 (princ "\n"))
16189 (princ (car e))
16190 (princ " ")
16191 (if (symbolp (cdr e))
16192 (princ (symbol-name (cdr e)))
16193 (prin1 (cdr e)))
16194 (princ "\n")))
16196 (defun org-speed-command-help ()
16197 "Show the available speed commands."
16198 (interactive)
16199 (if (not org-use-speed-commands)
16200 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
16201 (with-output-to-temp-buffer "*Help*"
16202 (princ "User-defined Speed commands\n===========================\n")
16203 (mapc 'org-print-speed-command org-speed-commands-user)
16204 (princ "\n")
16205 (princ "Built-in Speed commands\n=======================\n")
16206 (mapc 'org-print-speed-command org-speed-commands-default))
16207 (with-current-buffer "*Help*"
16208 (setq truncate-lines t))))
16210 (defun org-speed-move-safe (cmd)
16211 "Execute CMD, but make sure that the cursor always ends up in a headline.
16212 If not, return to the original position and throw an error."
16213 (interactive)
16214 (let ((pos (point)))
16215 (call-interactively cmd)
16216 (unless (and (bolp) (org-on-heading-p))
16217 (goto-char pos)
16218 (error "Boundary reached while executing %s" cmd))))
16220 (defvar org-self-insert-command-undo-counter 0)
16222 (defvar org-table-auto-blank-field) ; defined in org-table.el
16223 (defvar org-speed-command nil)
16224 (defun org-self-insert-command (N)
16225 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16226 If the cursor is in a table looking at whitespace, the whitespace is
16227 overwritten, and the table is not marked as requiring realignment."
16228 (interactive "p")
16229 (cond
16230 ((and org-use-speed-commands
16231 (or (and (bolp) (looking-at outline-regexp))
16232 (and (functionp org-use-speed-commands)
16233 (funcall org-use-speed-commands)))
16234 (setq
16235 org-speed-command
16236 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16237 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16238 (cond
16239 ((commandp org-speed-command)
16240 (setq this-command org-speed-command)
16241 (call-interactively org-speed-command))
16242 ((functionp org-speed-command)
16243 (funcall org-speed-command))
16244 ((and org-speed-command (listp org-speed-command))
16245 (eval org-speed-command))
16246 (t (let (org-use-speed-commands)
16247 (call-interactively 'org-self-insert-command)))))
16248 ((and
16249 (org-table-p)
16250 (progn
16251 ;; check if we blank the field, and if that triggers align
16252 (and (featurep 'org-table) org-table-auto-blank-field
16253 (member last-command
16254 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16255 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16256 ;; got extra space, this field does not determine column width
16257 (let (org-table-may-need-update) (org-table-blank-field))
16258 ;; no extra space, this field may determine column width
16259 (org-table-blank-field)))
16261 (eq N 1)
16262 (looking-at "[^|\n]* |"))
16263 (let (org-table-may-need-update)
16264 (goto-char (1- (match-end 0)))
16265 (delete-backward-char 1)
16266 (goto-char (match-beginning 0))
16267 (self-insert-command N)))
16269 (setq org-table-may-need-update t)
16270 (self-insert-command N)
16271 (org-fix-tags-on-the-fly)
16272 (if org-self-insert-cluster-for-undo
16273 (if (not (eq last-command 'org-self-insert-command))
16274 (setq org-self-insert-command-undo-counter 1)
16275 (if (>= org-self-insert-command-undo-counter 20)
16276 (setq org-self-insert-command-undo-counter 1)
16277 (and (> org-self-insert-command-undo-counter 0)
16278 buffer-undo-list
16279 (not (cadr buffer-undo-list)) ; remove nil entry
16280 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16281 (setq org-self-insert-command-undo-counter
16282 (1+ org-self-insert-command-undo-counter))))))))
16284 (defun org-fix-tags-on-the-fly ()
16285 (when (and (equal (char-after (point-at-bol)) ?*)
16286 (org-on-heading-p))
16287 (org-align-tags-here org-tags-column)))
16289 (defun org-delete-backward-char (N)
16290 "Like `delete-backward-char', insert whitespace at field end in tables.
16291 When deleting backwards, in tables this function will insert whitespace in
16292 front of the next \"|\" separator, to keep the table aligned. The table will
16293 still be marked for re-alignment if the field did fill the entire column,
16294 because, in this case the deletion might narrow the column."
16295 (interactive "p")
16296 (if (and (org-table-p)
16297 (eq N 1)
16298 (string-match "|" (buffer-substring (point-at-bol) (point)))
16299 (looking-at ".*?|"))
16300 (let ((pos (point))
16301 (noalign (looking-at "[^|\n\r]* |"))
16302 (c org-table-may-need-update))
16303 (backward-delete-char N)
16304 (skip-chars-forward "^|")
16305 (insert " ")
16306 (goto-char (1- pos))
16307 ;; noalign: if there were two spaces at the end, this field
16308 ;; does not determine the width of the column.
16309 (if noalign (setq org-table-may-need-update c)))
16310 (backward-delete-char N)
16311 (org-fix-tags-on-the-fly)))
16313 (defun org-delete-char (N)
16314 "Like `delete-char', but insert whitespace at field end in tables.
16315 When deleting characters, in tables this function will insert whitespace in
16316 front of the next \"|\" separator, to keep the table aligned. The table will
16317 still be marked for re-alignment if the field did fill the entire column,
16318 because, in this case the deletion might narrow the column."
16319 (interactive "p")
16320 (if (and (org-table-p)
16321 (not (bolp))
16322 (not (= (char-after) ?|))
16323 (eq N 1))
16324 (if (looking-at ".*?|")
16325 (let ((pos (point))
16326 (noalign (looking-at "[^|\n\r]* |"))
16327 (c org-table-may-need-update))
16328 (replace-match (concat
16329 (substring (match-string 0) 1 -1)
16330 " |"))
16331 (goto-char pos)
16332 ;; noalign: if there were two spaces at the end, this field
16333 ;; does not determine the width of the column.
16334 (if noalign (setq org-table-may-need-update c)))
16335 (delete-char N))
16336 (delete-char N)
16337 (org-fix-tags-on-the-fly)))
16339 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16340 (put 'org-self-insert-command 'delete-selection t)
16341 (put 'orgtbl-self-insert-command 'delete-selection t)
16342 (put 'org-delete-char 'delete-selection 'supersede)
16343 (put 'org-delete-backward-char 'delete-selection 'supersede)
16344 (put 'org-yank 'delete-selection 'yank)
16346 ;; Make `flyspell-mode' delay after some commands
16347 (put 'org-self-insert-command 'flyspell-delayed t)
16348 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16349 (put 'org-delete-char 'flyspell-delayed t)
16350 (put 'org-delete-backward-char 'flyspell-delayed t)
16352 ;; Make pabbrev-mode expand after org-mode commands
16353 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16354 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16356 ;; How to do this: Measure non-white length of current string
16357 ;; If equal to column width, we should realign.
16359 (defun org-remap (map &rest commands)
16360 "In MAP, remap the functions given in COMMANDS.
16361 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16362 (let (new old)
16363 (while commands
16364 (setq old (pop commands) new (pop commands))
16365 (if (fboundp 'command-remapping)
16366 (org-defkey map (vector 'remap old) new)
16367 (substitute-key-definition old new map global-map)))))
16369 (when (eq org-enable-table-editor 'optimized)
16370 ;; If the user wants maximum table support, we need to hijack
16371 ;; some standard editing functions
16372 (org-remap org-mode-map
16373 'self-insert-command 'org-self-insert-command
16374 'delete-char 'org-delete-char
16375 'delete-backward-char 'org-delete-backward-char)
16376 (org-defkey org-mode-map "|" 'org-force-self-insert))
16378 (defvar org-ctrl-c-ctrl-c-hook nil
16379 "Hook for functions attaching themselves to `C-c C-c'.
16380 This can be used to add additional functionality to the C-c C-c key which
16381 executes context-dependent commands.
16382 Each function will be called with no arguments. The function must check
16383 if the context is appropriate for it to act. If yes, it should do its
16384 thing and then return a non-nil value. If the context is wrong,
16385 just do nothing and return nil.")
16387 (defvar org-tab-first-hook nil
16388 "Hook for functions to attach themselves to TAB.
16389 See `org-ctrl-c-ctrl-c-hook' for more information.
16390 This hook runs as the first action when TAB is pressed, even before
16391 `org-cycle' messes around with the `outline-regexp' to cater for
16392 inline tasks and plain list item folding.
16393 If any function in this hook returns t, any other actions that
16394 would have been caused by TAB (such as table field motion or visibility
16395 cycling) will not occur.")
16397 (defvar org-tab-after-check-for-table-hook nil
16398 "Hook for functions to attach themselves to TAB.
16399 See `org-ctrl-c-ctrl-c-hook' for more information.
16400 This hook runs after it has been established that the cursor is not in a
16401 table, but before checking if the cursor is in a headline or if global cycling
16402 should be done.
16403 If any function in this hook returns t, not other actions like visibility
16404 cycling will be done.")
16406 (defvar org-tab-after-check-for-cycling-hook nil
16407 "Hook for functions to attach themselves to TAB.
16408 See `org-ctrl-c-ctrl-c-hook' for more information.
16409 This hook runs after it has been established that not table field motion and
16410 not visibility should be done because of current context. This is probably
16411 the place where a package like yasnippets can hook in.")
16413 (defvar org-tab-before-tab-emulation-hook nil
16414 "Hook for functions to attach themselves to TAB.
16415 See `org-ctrl-c-ctrl-c-hook' for more information.
16416 This hook runs after every other options for TAB have been exhausted, but
16417 before indentation and \t insertion takes place.")
16419 (defvar org-metaleft-hook nil
16420 "Hook for functions attaching themselves to `M-left'.
16421 See `org-ctrl-c-ctrl-c-hook' for more information.")
16422 (defvar org-metaright-hook nil
16423 "Hook for functions attaching themselves to `M-right'.
16424 See `org-ctrl-c-ctrl-c-hook' for more information.")
16425 (defvar org-metaup-hook nil
16426 "Hook for functions attaching themselves to `M-up'.
16427 See `org-ctrl-c-ctrl-c-hook' for more information.")
16428 (defvar org-metadown-hook nil
16429 "Hook for functions attaching themselves to `M-down'.
16430 See `org-ctrl-c-ctrl-c-hook' for more information.")
16431 (defvar org-shiftmetaleft-hook nil
16432 "Hook for functions attaching themselves to `M-S-left'.
16433 See `org-ctrl-c-ctrl-c-hook' for more information.")
16434 (defvar org-shiftmetaright-hook nil
16435 "Hook for functions attaching themselves to `M-S-right'.
16436 See `org-ctrl-c-ctrl-c-hook' for more information.")
16437 (defvar org-shiftmetaup-hook nil
16438 "Hook for functions attaching themselves to `M-S-up'.
16439 See `org-ctrl-c-ctrl-c-hook' for more information.")
16440 (defvar org-shiftmetadown-hook nil
16441 "Hook for functions attaching themselves to `M-S-down'.
16442 See `org-ctrl-c-ctrl-c-hook' for more information.")
16443 (defvar org-metareturn-hook nil
16444 "Hook for functions attaching themselves to `M-RET'.
16445 See `org-ctrl-c-ctrl-c-hook' for more information.")
16446 (defvar org-shiftup-hook nil
16447 "Hook for functions attaching themselves to `S-up'.
16448 See `org-ctrl-c-ctrl-c-hook' for more information.")
16449 (defvar org-shiftup-final-hook nil
16450 "Hook for functions attaching themselves to `S-up'.
16451 This one runs after all other options except shift-select have been excluded.
16452 See `org-ctrl-c-ctrl-c-hook' for more information.")
16453 (defvar org-shiftdown-hook nil
16454 "Hook for functions attaching themselves to `S-down'.
16455 See `org-ctrl-c-ctrl-c-hook' for more information.")
16456 (defvar org-shiftdown-final-hook nil
16457 "Hook for functions attaching themselves to `S-down'.
16458 This one runs after all other options except shift-select have been excluded.
16459 See `org-ctrl-c-ctrl-c-hook' for more information.")
16460 (defvar org-shiftleft-hook nil
16461 "Hook for functions attaching themselves to `S-left'.
16462 See `org-ctrl-c-ctrl-c-hook' for more information.")
16463 (defvar org-shiftleft-final-hook nil
16464 "Hook for functions attaching themselves to `S-left'.
16465 This one runs after all other options except shift-select have been excluded.
16466 See `org-ctrl-c-ctrl-c-hook' for more information.")
16467 (defvar org-shiftright-hook nil
16468 "Hook for functions attaching themselves to `S-right'.
16469 See `org-ctrl-c-ctrl-c-hook' for more information.")
16470 (defvar org-shiftright-final-hook nil
16471 "Hook for functions attaching themselves to `S-right'.
16472 This one runs after all other options except shift-select have been excluded.
16473 See `org-ctrl-c-ctrl-c-hook' for more information.")
16475 (defun org-modifier-cursor-error ()
16476 "Throw an error, a modified cursor command was applied in wrong context."
16477 (error "This command is active in special context like tables, headlines or items"))
16479 (defun org-shiftselect-error ()
16480 "Throw an error because Shift-Cursor command was applied in wrong context."
16481 (if (and (boundp 'shift-select-mode) shift-select-mode)
16482 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16483 (error "This command works only in special context like headlines or timestamps")))
16485 (defun org-call-for-shift-select (cmd)
16486 (let ((this-command-keys-shift-translated t))
16487 (call-interactively cmd)))
16489 (defun org-shifttab (&optional arg)
16490 "Global visibility cycling or move to previous table field.
16491 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16492 on context.
16493 See the individual commands for more information."
16494 (interactive "P")
16495 (cond
16496 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16497 ((integerp arg)
16498 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16499 (message "Content view to level: %d" arg)
16500 (org-content (prefix-numeric-value arg2))
16501 (setq org-cycle-global-status 'overview)))
16502 (t (call-interactively 'org-global-cycle))))
16504 (defun org-shiftmetaleft ()
16505 "Promote subtree or delete table column.
16506 Calls `org-promote-subtree', `org-outdent-item',
16507 or `org-table-delete-column', depending on context.
16508 See the individual commands for more information."
16509 (interactive)
16510 (cond
16511 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16512 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16513 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16514 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16515 (t (org-modifier-cursor-error))))
16517 (defun org-shiftmetaright ()
16518 "Demote subtree or insert table column.
16519 Calls `org-demote-subtree', `org-indent-item',
16520 or `org-table-insert-column', depending on context.
16521 See the individual commands for more information."
16522 (interactive)
16523 (cond
16524 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16525 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16526 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16527 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16528 (t (org-modifier-cursor-error))))
16530 (defun org-shiftmetaup (&optional arg)
16531 "Move subtree up or kill table row.
16532 Calls `org-move-subtree-up' or `org-table-kill-row' or
16533 `org-move-item-up' depending on context. See the individual commands
16534 for more information."
16535 (interactive "P")
16536 (cond
16537 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16538 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16539 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16540 ((org-at-item-p) (call-interactively 'org-move-item-up))
16541 (t (org-modifier-cursor-error))))
16543 (defun org-shiftmetadown (&optional arg)
16544 "Move subtree down or insert table row.
16545 Calls `org-move-subtree-down' or `org-table-insert-row' or
16546 `org-move-item-down', depending on context. See the individual
16547 commands for more information."
16548 (interactive "P")
16549 (cond
16550 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16551 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16552 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16553 ((org-at-item-p) (call-interactively 'org-move-item-down))
16554 (t (org-modifier-cursor-error))))
16556 (defsubst org-hidden-tree-error ()
16557 (error
16558 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16560 (defun org-metaleft (&optional arg)
16561 "Promote heading or move table column to left.
16562 Calls `org-do-promote' or `org-table-move-column', depending on context.
16563 With no specific context, calls the Emacs default `backward-word'.
16564 See the individual commands for more information."
16565 (interactive "P")
16566 (cond
16567 ((run-hook-with-args-until-success 'org-metaleft-hook))
16568 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16569 ((or (org-on-heading-p)
16570 (and (org-region-active-p)
16571 (save-excursion
16572 (goto-char (region-beginning))
16573 (org-on-heading-p))))
16574 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16575 (call-interactively 'org-do-promote))
16576 ((or (org-at-item-p)
16577 (and (org-region-active-p)
16578 (save-excursion
16579 (goto-char (region-beginning))
16580 (org-at-item-p))))
16581 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16582 (call-interactively 'org-outdent-item))
16583 (t (call-interactively 'backward-word))))
16585 (defun org-metaright (&optional arg)
16586 "Demote subtree or move table column to right.
16587 Calls `org-do-demote' or `org-table-move-column', depending on context.
16588 With no specific context, calls the Emacs default `forward-word'.
16589 See the individual commands for more information."
16590 (interactive "P")
16591 (cond
16592 ((run-hook-with-args-until-success 'org-metaright-hook))
16593 ((org-at-table-p) (call-interactively 'org-table-move-column))
16594 ((or (org-on-heading-p)
16595 (and (org-region-active-p)
16596 (save-excursion
16597 (goto-char (region-beginning))
16598 (org-on-heading-p))))
16599 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16600 (call-interactively 'org-do-demote))
16601 ((or (org-at-item-p)
16602 (and (org-region-active-p)
16603 (save-excursion
16604 (goto-char (region-beginning))
16605 (org-at-item-p))))
16606 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16607 (call-interactively 'org-indent-item))
16608 (t (call-interactively 'forward-word))))
16610 (defun org-check-for-hidden (what)
16611 "Check if there are hidden headlines/items in the current visual line.
16612 WHAT can be either `headlines' or `items'. If the current line is
16613 an outline or item heading and it has a folded subtree below it,
16614 this fucntion returns t, nil otherwise."
16615 (let ((re (cond
16616 ((eq what 'headlines) (concat "^" org-outline-regexp))
16617 ((eq what 'items) (concat "^" (org-item-re t)))
16618 (t (error "This should not happen"))))
16619 beg end)
16620 (save-excursion
16621 (catch 'exit
16622 (unless (org-region-active-p)
16623 (setq beg (point-at-bol))
16624 (beginning-of-line 2)
16625 (while (and (not (eobp)) ;; this is like `next-line'
16626 (get-char-property (1- (point)) 'invisible))
16627 (beginning-of-line 2))
16628 (setq end (point))
16629 (goto-char beg)
16630 (goto-char (point-at-eol))
16631 (setq end (max end (point)))
16632 (while (re-search-forward re end t)
16633 (if (get-char-property (match-beginning 0) 'invisible)
16634 (throw 'exit t))))
16635 nil))))
16637 (defun org-metaup (&optional arg)
16638 "Move subtree up or move table row up.
16639 Calls `org-move-subtree-up' or `org-table-move-row' or
16640 `org-move-item-up', depending on context. See the individual commands
16641 for more information."
16642 (interactive "P")
16643 (cond
16644 ((run-hook-with-args-until-success 'org-metaup-hook))
16645 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16646 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16647 ((org-at-item-p) (call-interactively 'org-move-item-up))
16648 (t (transpose-lines 1) (beginning-of-line -1))))
16650 (defun org-metadown (&optional arg)
16651 "Move subtree down or move table row down.
16652 Calls `org-move-subtree-down' or `org-table-move-row' or
16653 `org-move-item-down', depending on context. See the individual
16654 commands for more information."
16655 (interactive "P")
16656 (cond
16657 ((run-hook-with-args-until-success 'org-metadown-hook))
16658 ((org-at-table-p) (call-interactively 'org-table-move-row))
16659 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16660 ((org-at-item-p) (call-interactively 'org-move-item-down))
16661 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16663 (defun org-shiftup (&optional arg)
16664 "Increase item in timestamp or increase priority of current headline.
16665 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16666 depending on context. See the individual commands for more information."
16667 (interactive "P")
16668 (cond
16669 ((run-hook-with-args-until-success 'org-shiftup-hook))
16670 ((and org-support-shift-select (org-region-active-p))
16671 (org-call-for-shift-select 'previous-line))
16672 ((org-at-timestamp-p t)
16673 (call-interactively (if org-edit-timestamp-down-means-later
16674 'org-timestamp-down 'org-timestamp-up)))
16675 ((and (not (eq org-support-shift-select 'always))
16676 org-enable-priority-commands
16677 (org-on-heading-p))
16678 (call-interactively 'org-priority-up))
16679 ((and (not org-support-shift-select) (org-at-item-p))
16680 (call-interactively 'org-previous-item))
16681 ((org-clocktable-try-shift 'up arg))
16682 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16683 (org-support-shift-select
16684 (org-call-for-shift-select 'previous-line))
16685 (t (org-shiftselect-error))))
16687 (defun org-shiftdown (&optional arg)
16688 "Decrease item in timestamp or decrease priority of current headline.
16689 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16690 depending on context. See the individual commands for more information."
16691 (interactive "P")
16692 (cond
16693 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16694 ((and org-support-shift-select (org-region-active-p))
16695 (org-call-for-shift-select 'next-line))
16696 ((org-at-timestamp-p t)
16697 (call-interactively (if org-edit-timestamp-down-means-later
16698 'org-timestamp-up 'org-timestamp-down)))
16699 ((and (not (eq org-support-shift-select 'always))
16700 org-enable-priority-commands
16701 (org-on-heading-p))
16702 (call-interactively 'org-priority-down))
16703 ((and (not org-support-shift-select) (org-at-item-p))
16704 (call-interactively 'org-next-item))
16705 ((org-clocktable-try-shift 'down arg))
16706 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16707 (org-support-shift-select
16708 (org-call-for-shift-select 'next-line))
16709 (t (org-shiftselect-error))))
16711 (defun org-shiftright (&optional arg)
16712 "Cycle the thing at point or in the current line, depending on context.
16713 Depending on context, this does one of the following:
16715 - switch a timestamp at point one day into the future
16716 - on a headline, switch to the next TODO keyword.
16717 - on an item, switch entire list to the next bullet type
16718 - on a property line, switch to the next allowed value
16719 - on a clocktable definition line, move time block into the future"
16720 (interactive "P")
16721 (cond
16722 ((run-hook-with-args-until-success 'org-shiftright-hook))
16723 ((and org-support-shift-select (org-region-active-p))
16724 (org-call-for-shift-select 'forward-char))
16725 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16726 ((and (not (eq org-support-shift-select 'always))
16727 (org-on-heading-p))
16728 (let ((org-inhibit-logging
16729 (not org-treat-S-cursor-todo-selection-as-state-change))
16730 (org-inhibit-blocking
16731 (not org-treat-S-cursor-todo-selection-as-state-change)))
16732 (org-call-with-arg 'org-todo 'right)))
16733 ((or (and org-support-shift-select
16734 (not (eq org-support-shift-select 'always))
16735 (org-at-item-bullet-p))
16736 (and (not org-support-shift-select) (org-at-item-p)))
16737 (org-call-with-arg 'org-cycle-list-bullet nil))
16738 ((and (not (eq org-support-shift-select 'always))
16739 (org-at-property-p))
16740 (call-interactively 'org-property-next-allowed-value))
16741 ((org-clocktable-try-shift 'right arg))
16742 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16743 (org-support-shift-select
16744 (org-call-for-shift-select 'forward-char))
16745 (t (org-shiftselect-error))))
16747 (defun org-shiftleft (&optional arg)
16748 "Cycle the thing at point or in the current line, depending on context.
16749 Depending on context, this does one of the following:
16751 - switch a timestamp at point one day into the past
16752 - on a headline, switch to the previous TODO keyword.
16753 - on an item, switch entire list to the previous bullet type
16754 - on a property line, switch to the previous allowed value
16755 - on a clocktable definition line, move time block into the past"
16756 (interactive "P")
16757 (cond
16758 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16759 ((and org-support-shift-select (org-region-active-p))
16760 (org-call-for-shift-select 'backward-char))
16761 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16762 ((and (not (eq org-support-shift-select 'always))
16763 (org-on-heading-p))
16764 (let ((org-inhibit-logging
16765 (not org-treat-S-cursor-todo-selection-as-state-change))
16766 (org-inhibit-blocking
16767 (not org-treat-S-cursor-todo-selection-as-state-change)))
16768 (org-call-with-arg 'org-todo 'left)))
16769 ((or (and org-support-shift-select
16770 (not (eq org-support-shift-select 'always))
16771 (org-at-item-bullet-p))
16772 (and (not org-support-shift-select) (org-at-item-p)))
16773 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16774 ((and (not (eq org-support-shift-select 'always))
16775 (org-at-property-p))
16776 (call-interactively 'org-property-previous-allowed-value))
16777 ((org-clocktable-try-shift 'left arg))
16778 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16779 (org-support-shift-select
16780 (org-call-for-shift-select 'backward-char))
16781 (t (org-shiftselect-error))))
16783 (defun org-shiftcontrolright ()
16784 "Switch to next TODO set."
16785 (interactive)
16786 (cond
16787 ((and org-support-shift-select (org-region-active-p))
16788 (org-call-for-shift-select 'forward-word))
16789 ((and (not (eq org-support-shift-select 'always))
16790 (org-on-heading-p))
16791 (org-call-with-arg 'org-todo 'nextset))
16792 (org-support-shift-select
16793 (org-call-for-shift-select 'forward-word))
16794 (t (org-shiftselect-error))))
16796 (defun org-shiftcontrolleft ()
16797 "Switch to previous TODO set."
16798 (interactive)
16799 (cond
16800 ((and org-support-shift-select (org-region-active-p))
16801 (org-call-for-shift-select 'backward-word))
16802 ((and (not (eq org-support-shift-select 'always))
16803 (org-on-heading-p))
16804 (org-call-with-arg 'org-todo 'previousset))
16805 (org-support-shift-select
16806 (org-call-for-shift-select 'backward-word))
16807 (t (org-shiftselect-error))))
16809 (defun org-ctrl-c-ret ()
16810 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16811 (interactive)
16812 (cond
16813 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16814 (t (call-interactively 'org-insert-heading))))
16816 (defun org-copy-special ()
16817 "Copy region in table or copy current subtree.
16818 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16819 See the individual commands for more information."
16820 (interactive)
16821 (call-interactively
16822 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16824 (defun org-cut-special ()
16825 "Cut region in table or cut current subtree.
16826 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16827 See the individual commands for more information."
16828 (interactive)
16829 (call-interactively
16830 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16832 (defun org-paste-special (arg)
16833 "Paste rectangular region into table, or past subtree relative to level.
16834 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16835 See the individual commands for more information."
16836 (interactive "P")
16837 (if (org-at-table-p)
16838 (org-table-paste-rectangle)
16839 (org-paste-subtree arg)))
16841 (defun org-edit-special ()
16842 "Call a special editor for the stuff at point.
16843 When at a table, call the formula editor with `org-table-edit-formulas'.
16844 When at the first line of an src example, call `org-edit-src-code'.
16845 When in an #+include line, visit the include file. Otherwise call
16846 `ffap' to visit the file at point."
16847 (interactive)
16848 (cond
16849 ((org-at-table.el-p)
16850 (org-edit-src-code))
16851 ((org-at-table-p)
16852 (call-interactively 'org-table-edit-formulas))
16853 ((save-excursion
16854 (beginning-of-line 1)
16855 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16856 (find-file (org-trim (match-string 1))))
16857 ((org-edit-src-code))
16858 ((org-edit-fixed-width-region))
16859 (t (call-interactively 'ffap))))
16862 (defun org-ctrl-c-ctrl-c (&optional arg)
16863 "Set tags in headline, or update according to changed information at point.
16865 This command does many different things, depending on context:
16867 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16868 this is what we do.
16870 - If the cursor is on a statistics cookie, update it.
16872 - If the cursor is in a headline, prompt for tags and insert them
16873 into the current line, aligned to `org-tags-column'. When called
16874 with prefix arg, realign all tags in the current buffer.
16876 - If the cursor is in one of the special #+KEYWORD lines, this
16877 triggers scanning the buffer for these lines and updating the
16878 information.
16880 - If the cursor is inside a table, realign the table. This command
16881 works even if the automatic table editor has been turned off.
16883 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16884 the entire table.
16886 - If the cursor is at a footnote reference or definition, jump to
16887 the corresponding definition or references, respectively.
16889 - If the cursor is a the beginning of a dynamic block, update it.
16891 - If the current buffer is a remember buffer, close note and file
16892 it. A prefix argument of 1 files to the default location
16893 without further interaction. A prefix argument of 2 files to
16894 the currently clocking task.
16896 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16897 links in this buffer.
16899 - If the cursor is on a numbered item in a plain list, renumber the
16900 ordered list.
16902 - If the cursor is on a checkbox, toggle it."
16903 (interactive "P")
16904 (let ((org-enable-table-editor t))
16905 (cond
16906 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16907 org-occur-highlights
16908 org-latex-fragment-image-overlays)
16909 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16910 (org-remove-occur-highlights)
16911 (org-remove-latex-fragment-image-overlays)
16912 (message "Temporary highlights/overlays removed from current buffer"))
16913 ((and (local-variable-p 'org-finish-function (current-buffer))
16914 (fboundp org-finish-function))
16915 (funcall org-finish-function))
16916 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16917 ((or (looking-at org-property-start-re)
16918 (org-at-property-p))
16919 (call-interactively 'org-property-action))
16920 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16921 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16922 (or (org-on-heading-p) (org-at-item-p)))
16923 (call-interactively 'org-update-statistics-cookies))
16924 ((org-on-heading-p) (call-interactively 'org-set-tags))
16925 ((org-at-table.el-p)
16926 (message "Use C-c ' to edit table.el tables"))
16927 ((org-at-table-p)
16928 (org-table-maybe-eval-formula)
16929 (if arg
16930 (call-interactively 'org-table-recalculate)
16931 (org-table-maybe-recalculate-line))
16932 (call-interactively 'org-table-align))
16933 ((or (org-footnote-at-reference-p)
16934 (org-footnote-at-definition-p))
16935 (call-interactively 'org-footnote-action))
16936 ((org-at-item-checkbox-p)
16937 (call-interactively 'org-toggle-checkbox))
16938 ((org-at-item-p)
16939 (if arg
16940 (call-interactively 'org-toggle-checkbox)
16941 (call-interactively 'org-maybe-renumber-ordered-list)))
16942 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16943 ;; Dynamic block
16944 (beginning-of-line 1)
16945 (save-excursion (org-update-dblock)))
16946 ((save-excursion
16947 (beginning-of-line 1)
16948 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16949 (cond
16950 ((equal (match-string 1) "TBLFM")
16951 ;; Recalculate the table before this line
16952 (save-excursion
16953 (beginning-of-line 1)
16954 (skip-chars-backward " \r\n\t")
16955 (if (org-at-table-p)
16956 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16958 (let ((org-inhibit-startup-visibility-stuff t)
16959 (org-startup-align-all-tables nil))
16960 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16961 (message "Local setup has been refreshed"))))
16962 ((org-clock-update-time-maybe))
16963 (t (error "C-c C-c can do nothing useful at this location")))))
16965 (defun org-mode-restart ()
16966 "Restart Org-mode, to scan again for special lines.
16967 Also updates the keyword regular expressions."
16968 (interactive)
16969 (org-mode)
16970 (message "Org-mode restarted"))
16972 (defun org-kill-note-or-show-branches ()
16973 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16974 (interactive)
16975 (if (not org-finish-function)
16976 (progn
16977 (hide-subtree)
16978 (call-interactively 'show-branches))
16979 (let ((org-note-abort t))
16980 (funcall org-finish-function))))
16982 (defun org-return (&optional indent)
16983 "Goto next table row or insert a newline.
16984 Calls `org-table-next-row' or `newline', depending on context.
16985 See the individual commands for more information."
16986 (interactive)
16987 (cond
16988 ((bobp) (if indent (newline-and-indent) (newline)))
16989 ((org-at-table-p)
16990 (org-table-justify-field-maybe)
16991 (call-interactively 'org-table-next-row))
16992 ((and org-return-follows-link
16993 (eq (get-text-property (point) 'face) 'org-link))
16994 (call-interactively 'org-open-at-point))
16995 ((and (org-at-heading-p)
16996 (looking-at
16997 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16998 (org-show-entry)
16999 (end-of-line 1)
17000 (newline))
17001 (t (if indent (newline-and-indent) (newline)))))
17003 (defun org-return-indent ()
17004 "Goto next table row or insert a newline and indent.
17005 Calls `org-table-next-row' or `newline-and-indent', depending on
17006 context. See the individual commands for more information."
17007 (interactive)
17008 (org-return t))
17010 (defun org-ctrl-c-star ()
17011 "Compute table, or change heading status of lines.
17012 Calls `org-table-recalculate' or `org-toggle-heading',
17013 depending on context."
17014 (interactive)
17015 (cond
17016 ((org-at-table-p)
17017 (call-interactively 'org-table-recalculate))
17019 ;; Convert all lines in region to list items
17020 (call-interactively 'org-toggle-heading))))
17022 (defun org-ctrl-c-minus ()
17023 "Insert separator line in table or modify bullet status of line.
17024 Also turns a plain line or a region of lines into list items.
17025 Calls `org-table-insert-hline', `org-toggle-item', or
17026 `org-cycle-list-bullet', depending on context."
17027 (interactive)
17028 (cond
17029 ((org-at-table-p)
17030 (call-interactively 'org-table-insert-hline))
17031 ((org-region-active-p)
17032 (call-interactively 'org-toggle-item))
17033 ((org-in-item-p)
17034 (call-interactively 'org-cycle-list-bullet))
17036 (call-interactively 'org-toggle-item))))
17038 (defun org-toggle-item ()
17039 "Convert headings or normal lines to items, items to normal lines.
17040 If there is no active region, only the current line is considered.
17042 If the first line in the region is a headline, convert all headlines to items.
17044 If the first line in the region is an item, convert all items to normal lines.
17046 If the first line is normal text, add an item bullet to each line."
17047 (interactive)
17048 (let (l2 l beg end)
17049 (if (org-region-active-p)
17050 (setq beg (region-beginning) end (region-end))
17051 (setq beg (point-at-bol)
17052 end (min (1+ (point-at-eol)) (point-max))))
17053 (save-excursion
17054 (goto-char end)
17055 (setq l2 (org-current-line))
17056 (goto-char beg)
17057 (beginning-of-line 1)
17058 (setq l (1- (org-current-line)))
17059 (if (org-at-item-p)
17060 ;; We already have items, de-itemize
17061 (while (< (setq l (1+ l)) l2)
17062 (when (org-at-item-p)
17063 (goto-char (match-beginning 2))
17064 (delete-region (match-beginning 2) (match-end 2))
17065 (and (looking-at "[ \t]+") (replace-match "")))
17066 (beginning-of-line 2))
17067 (if (org-on-heading-p)
17068 ;; Headings, convert to items
17069 (while (< (setq l (1+ l)) l2)
17070 (if (looking-at org-outline-regexp)
17071 (replace-match "- " t t))
17072 (beginning-of-line 2))
17073 ;; normal lines, turn them into items
17074 (while (< (setq l (1+ l)) l2)
17075 (unless (org-at-item-p)
17076 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17077 (replace-match "\\1- \\2")))
17078 (beginning-of-line 2)))))))
17080 (defun org-toggle-heading (&optional nstars)
17081 "Convert headings to normal text, or items or text to headings.
17082 If there is no active region, only the current line is considered.
17084 If the first line is a heading, remove the stars from all headlines
17085 in the region.
17087 If the first line is a plain list item, turn all plain list items
17088 into headings.
17090 If the first line is a normal line, turn each and every line in the
17091 region into a heading.
17093 When converting a line into a heading, the number of stars is chosen
17094 such that the lines become children of the current entry. However,
17095 when a prefix argument is given, its value determines the number of
17096 stars to add."
17097 (interactive "P")
17098 (let (l2 l itemp beg end)
17099 (if (org-region-active-p)
17100 (setq beg (region-beginning) end (region-end))
17101 (setq beg (point-at-bol)
17102 end (min (1+ (point-at-eol)) (point-max))))
17103 (save-excursion
17104 (goto-char end)
17105 (setq l2 (org-current-line))
17106 (goto-char beg)
17107 (beginning-of-line 1)
17108 (setq l (1- (org-current-line)))
17109 (if (org-on-heading-p)
17110 ;; We already have headlines, de-star them
17111 (while (< (setq l (1+ l)) l2)
17112 (when (org-on-heading-p t)
17113 (and (looking-at outline-regexp) (replace-match "")))
17114 (beginning-of-line 2))
17115 (setq itemp (org-at-item-p))
17116 (let* ((stars
17117 (if nstars
17118 (make-string (prefix-numeric-value current-prefix-arg)
17120 (save-excursion
17121 (if (re-search-backward org-complex-heading-regexp nil t)
17122 (match-string 1) ""))))
17123 (add-stars (cond (nstars "")
17124 ((equal stars "") "*")
17125 (org-odd-levels-only "**")
17126 (t "*")))
17127 (rpl (concat stars add-stars " ")))
17128 (while (< (setq l (1+ l)) l2)
17129 (if itemp
17130 (and (org-at-item-p) (replace-match rpl t t))
17131 (unless (org-on-heading-p)
17132 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17133 (replace-match (concat rpl (match-string 2))))))
17134 (beginning-of-line 2)))))))
17136 (defun org-meta-return (&optional arg)
17137 "Insert a new heading or wrap a region in a table.
17138 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17139 See the individual commands for more information."
17140 (interactive "P")
17141 (cond
17142 ((run-hook-with-args-until-success 'org-metareturn-hook))
17143 ((org-at-table-p)
17144 (call-interactively 'org-table-wrap-region))
17145 (t (call-interactively 'org-insert-heading))))
17147 ;;; Menu entries
17149 ;; Define the Org-mode menus
17150 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17151 '("Tbl"
17152 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17153 ["Next Field" org-cycle (org-at-table-p)]
17154 ["Previous Field" org-shifttab (org-at-table-p)]
17155 ["Next Row" org-return (org-at-table-p)]
17156 "--"
17157 ["Blank Field" org-table-blank-field (org-at-table-p)]
17158 ["Edit Field" org-table-edit-field (org-at-table-p)]
17159 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17160 "--"
17161 ("Column"
17162 ["Move Column Left" org-metaleft (org-at-table-p)]
17163 ["Move Column Right" org-metaright (org-at-table-p)]
17164 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17165 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17166 ("Row"
17167 ["Move Row Up" org-metaup (org-at-table-p)]
17168 ["Move Row Down" org-metadown (org-at-table-p)]
17169 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17170 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17171 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17172 "--"
17173 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17174 ("Rectangle"
17175 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17176 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17177 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17178 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17179 "--"
17180 ("Calculate"
17181 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17182 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17183 ["Edit Formulas" org-edit-special (org-at-table-p)]
17184 "--"
17185 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17186 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17187 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17188 "--"
17189 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17190 "--"
17191 ["Sum Column/Rectangle" org-table-sum
17192 (or (org-at-table-p) (org-region-active-p))]
17193 ["Which Column?" org-table-current-column (org-at-table-p)])
17194 ["Debug Formulas"
17195 org-table-toggle-formula-debugger
17196 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17197 ["Show Col/Row Numbers"
17198 org-table-toggle-coordinate-overlays
17199 :style toggle
17200 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17201 "--"
17202 ["Create" org-table-create (and (not (org-at-table-p))
17203 org-enable-table-editor)]
17204 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17205 ["Import from File" org-table-import (not (org-at-table-p))]
17206 ["Export to File" org-table-export (org-at-table-p)]
17207 "--"
17208 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17210 (easy-menu-define org-org-menu org-mode-map "Org menu"
17211 '("Org"
17212 ("Show/Hide"
17213 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17214 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17215 ["Sparse Tree..." org-sparse-tree t]
17216 ["Reveal Context" org-reveal t]
17217 ["Show All" show-all t]
17218 "--"
17219 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17220 "--"
17221 ["New Heading" org-insert-heading t]
17222 ("Navigate Headings"
17223 ["Up" outline-up-heading t]
17224 ["Next" outline-next-visible-heading t]
17225 ["Previous" outline-previous-visible-heading t]
17226 ["Next Same Level" outline-forward-same-level t]
17227 ["Previous Same Level" outline-backward-same-level t]
17228 "--"
17229 ["Jump" org-goto t])
17230 ("Edit Structure"
17231 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17232 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17233 "--"
17234 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17235 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17236 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17237 "--"
17238 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17239 "--"
17240 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17241 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17242 ["Demote Heading" org-metaright (not (org-at-table-p))]
17243 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17244 "--"
17245 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17246 "--"
17247 ["Convert to odd levels" org-convert-to-odd-levels t]
17248 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17249 ("Editing"
17250 ["Emphasis..." org-emphasize t]
17251 ["Edit Source Example" org-edit-special t]
17252 "--"
17253 ["Footnote new/jump" org-footnote-action t]
17254 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17255 ("Archive"
17256 ["Archive (default method)" org-archive-subtree-default t]
17257 "--"
17258 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17259 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17260 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17262 "--"
17263 ("Hyperlinks"
17264 ["Store Link (Global)" org-store-link t]
17265 ["Find existing link to here" org-occur-link-in-agenda-files t]
17266 ["Insert Link" org-insert-link t]
17267 ["Follow Link" org-open-at-point t]
17268 "--"
17269 ["Next link" org-next-link t]
17270 ["Previous link" org-previous-link t]
17271 "--"
17272 ["Descriptive Links"
17273 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17274 :style radio
17275 :selected (member '(org-link) buffer-invisibility-spec)]
17276 ["Literal Links"
17277 (progn
17278 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17279 :style radio
17280 :selected (not (member '(org-link) buffer-invisibility-spec))])
17281 "--"
17282 ("TODO Lists"
17283 ["TODO/DONE/-" org-todo t]
17284 ("Select keyword"
17285 ["Next keyword" org-shiftright (org-on-heading-p)]
17286 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17287 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17288 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17289 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17290 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17291 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17292 "--"
17293 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17294 :selected org-enforce-todo-dependencies :style toggle :active t]
17295 "Settings for tree at point"
17296 ["Do Children sequentially" org-toggle-ordered-property :style radio
17297 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17298 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17299 ["Do Children parallel" org-toggle-ordered-property :style radio
17300 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17301 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17302 "--"
17303 ["Set Priority" org-priority t]
17304 ["Priority Up" org-shiftup t]
17305 ["Priority Down" org-shiftdown t]
17306 "--"
17307 ["Get news from all feeds" org-feed-update-all t]
17308 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17309 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17310 ("TAGS and Properties"
17311 ["Set Tags" org-set-tags-command t]
17312 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17313 "--"
17314 ["Set property" org-set-property t]
17315 ["Column view of properties" org-columns t]
17316 ["Insert Column View DBlock" org-insert-columns-dblock t])
17317 ("Dates and Scheduling"
17318 ["Timestamp" org-time-stamp t]
17319 ["Timestamp (inactive)" org-time-stamp-inactive t]
17320 ("Change Date"
17321 ["1 Day Later" org-shiftright t]
17322 ["1 Day Earlier" org-shiftleft t]
17323 ["1 ... Later" org-shiftup t]
17324 ["1 ... Earlier" org-shiftdown t])
17325 ["Compute Time Range" org-evaluate-time-range t]
17326 ["Schedule Item" org-schedule t]
17327 ["Deadline" org-deadline t]
17328 "--"
17329 ["Custom time format" org-toggle-time-stamp-overlays
17330 :style radio :selected org-display-custom-times]
17331 "--"
17332 ["Goto Calendar" org-goto-calendar t]
17333 ["Date from Calendar" org-date-from-calendar t]
17334 "--"
17335 ["Start/Restart Timer" org-timer-start t]
17336 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17337 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17338 ["Insert Timer String" org-timer t]
17339 ["Insert Timer Item" org-timer-item t])
17340 ("Logging work"
17341 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17342 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17343 ["Clock out" org-clock-out t]
17344 ["Clock cancel" org-clock-cancel t]
17345 "--"
17346 ["Mark as default task" org-clock-mark-default-task t]
17347 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17348 ["Goto running clock" org-clock-goto t]
17349 "--"
17350 ["Display times" org-clock-display t]
17351 ["Create clock table" org-clock-report t]
17352 "--"
17353 ["Record DONE time"
17354 (progn (setq org-log-done (not org-log-done))
17355 (message "Switching to %s will %s record a timestamp"
17356 (car org-done-keywords)
17357 (if org-log-done "automatically" "not")))
17358 :style toggle :selected org-log-done])
17359 "--"
17360 ["Agenda Command..." org-agenda t]
17361 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17362 ("File List for Agenda")
17363 ("Special views current file"
17364 ["TODO Tree" org-show-todo-tree t]
17365 ["Check Deadlines" org-check-deadlines t]
17366 ["Timeline" org-timeline t]
17367 ["Tags/Property tree" org-match-sparse-tree t])
17368 "--"
17369 ["Export/Publish..." org-export t]
17370 ("LaTeX"
17371 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17372 :selected org-cdlatex-mode]
17373 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17374 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17375 ["Modify math symbol" org-cdlatex-math-modify
17376 (org-inside-LaTeX-fragment-p)]
17377 ["Insert citation" org-reftex-citation t]
17378 "--"
17379 ["Export LaTeX fragments as images"
17380 (if (featurep 'org-exp)
17381 (setq org-export-with-LaTeX-fragments
17382 (not org-export-with-LaTeX-fragments))
17383 (require 'org-exp))
17384 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
17385 org-export-with-LaTeX-fragments)]
17386 "--"
17387 ["Template for BEAMER" org-insert-beamer-options-template t])
17388 "--"
17389 ("MobileOrg"
17390 ["Push Files and Views" org-mobile-push t]
17391 ["Get Captured and Flagged" org-mobile-pull t]
17392 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17393 "--"
17394 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17395 "--"
17396 ("Documentation"
17397 ["Show Version" org-version t]
17398 ["Info Documentation" org-info t])
17399 ("Customize"
17400 ["Browse Org Group" org-customize t]
17401 "--"
17402 ["Expand This Menu" org-create-customize-menu
17403 (fboundp 'customize-menu-create)])
17404 ["Send bug report" org-submit-bug-report t]
17405 "--"
17406 ("Refresh/Reload"
17407 ["Refresh setup current buffer" org-mode-restart t]
17408 ["Reload Org (after update)" org-reload t]
17409 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17412 (defun org-info (&optional node)
17413 "Read documentation for Org-mode in the info system.
17414 With optional NODE, go directly to that node."
17415 (interactive)
17416 (info (format "(org)%s" (or node ""))))
17418 ;;;###autoload
17419 (defun org-submit-bug-report ()
17420 "Submit a bug report on Org-mode via mail.
17422 Don't hesitate to report any problems or inaccurate documentation.
17424 If you don't have setup sending mail from (X)Emacs, please copy the
17425 output buffer into your mail program, as it gives us important
17426 information about your Org-mode version and configuration."
17427 (interactive)
17428 (require 'reporter)
17429 (org-load-modules-maybe)
17430 (org-require-autoloaded-modules)
17431 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17432 (reporter-submit-bug-report
17433 "emacs-orgmode@gnu.org"
17434 (org-version)
17435 (let (list)
17436 (save-window-excursion
17437 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17438 (delete-other-windows)
17439 (erase-buffer)
17440 (insert "You are about to submit a bug report to the Org-mode mailing list.
17442 We would like to add your full Org-mode and Outline configuration to the
17443 bug report. This greatly simplifies the work of the maintainer and
17444 other experts on the mailing list.
17446 HOWEVER, some variables you have customized may contain private
17447 information. The names of customers, colleagues, or friends, might
17448 appear in the form of file names, tags, todo states, or search strings.
17449 If you answer yes to the prompt, you might want to check and remove
17450 such private information before sending the email.")
17451 (add-text-properties (point-min) (point-max) '(face org-warning))
17452 (when (yes-or-no-p "Include your Org-mode configuration ")
17453 (mapatoms
17454 (lambda (v)
17455 (and (boundp v)
17456 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17457 (or (and (symbol-value v)
17458 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17459 (and
17460 (get v 'custom-type) (get v 'standard-value)
17461 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17462 (push v list)))))
17463 (kill-buffer (get-buffer "*Warn about privacy*"))
17464 list))
17465 nil nil
17466 "Remember to cover the basics, that is, what you expected to happen and
17467 what in fact did happen. You don't know how to make a good report? See
17469 http://orgmode.org/manual/Feedback.html#Feedback
17471 Your bug report will be posted to the Org-mode mailing list.
17472 ------------------------------------------------------------------------")
17473 (save-excursion
17474 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17475 (replace-match "\\1Bug: \\3 [\\2]")))))
17478 (defun org-install-agenda-files-menu ()
17479 (let ((bl (buffer-list)))
17480 (save-excursion
17481 (while bl
17482 (set-buffer (pop bl))
17483 (if (org-mode-p) (setq bl nil)))
17484 (when (org-mode-p)
17485 (easy-menu-change
17486 '("Org") "File List for Agenda"
17487 (append
17488 (list
17489 ["Edit File List" (org-edit-agenda-file-list) t]
17490 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17491 ["Remove Current File from List" org-remove-file t]
17492 ["Cycle through agenda files" org-cycle-agenda-files t]
17493 ["Occur in all agenda files" org-occur-in-agenda-files t]
17494 "--")
17495 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17497 ;;;; Documentation
17499 ;;;###autoload
17500 (defun org-require-autoloaded-modules ()
17501 (interactive)
17502 (mapc 'require
17503 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17504 org-docbook org-exp org-html org-icalendar
17505 org-id org-latex
17506 org-publish org-remember org-table
17507 org-timer org-xoxo)))
17509 ;;;###autoload
17510 (defun org-reload (&optional uncompiled)
17511 "Reload all org lisp files.
17512 With prefix arg UNCOMPILED, load the uncompiled versions."
17513 (interactive "P")
17514 (require 'find-func)
17515 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17516 (dir-org (file-name-directory (org-find-library-name "org")))
17517 (dir-org-contrib (ignore-errors
17518 (file-name-directory
17519 (org-find-library-name "org-contribdir"))))
17520 (files
17521 (append (directory-files dir-org t file-re)
17522 (and dir-org-contrib
17523 (directory-files dir-org-contrib t file-re))))
17524 (remove-re (concat (if (featurep 'xemacs)
17525 "org-colview" "org-colview-xemacs")
17526 "\\'")))
17527 (setq files (mapcar 'file-name-sans-extension files))
17528 (setq files (mapcar
17529 (lambda (x) (if (string-match remove-re x) nil x))
17530 files))
17531 (setq files (delq nil files))
17532 (mapc
17533 (lambda (f)
17534 (when (featurep (intern (file-name-nondirectory f)))
17535 (if (and (not uncompiled)
17536 (file-exists-p (concat f ".elc")))
17537 (load (concat f ".elc") nil nil t)
17538 (load (concat f ".el") nil nil t))))
17539 files))
17540 (org-version))
17542 ;;;###autoload
17543 (defun org-customize ()
17544 "Call the customize function with org as argument."
17545 (interactive)
17546 (org-load-modules-maybe)
17547 (org-require-autoloaded-modules)
17548 (customize-browse 'org))
17550 (defun org-create-customize-menu ()
17551 "Create a full customization menu for Org-mode, insert it into the menu."
17552 (interactive)
17553 (org-load-modules-maybe)
17554 (org-require-autoloaded-modules)
17555 (if (fboundp 'customize-menu-create)
17556 (progn
17557 (easy-menu-change
17558 '("Org") "Customize"
17559 `(["Browse Org group" org-customize t]
17560 "--"
17561 ,(customize-menu-create 'org)
17562 ["Set" Custom-set t]
17563 ["Save" Custom-save t]
17564 ["Reset to Current" Custom-reset-current t]
17565 ["Reset to Saved" Custom-reset-saved t]
17566 ["Reset to Standard Settings" Custom-reset-standard t]))
17567 (message "\"Org\"-menu now contains full customization menu"))
17568 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17570 ;;;; Miscellaneous stuff
17572 ;;; Generally useful functions
17574 (defun org-get-at-bol (property)
17575 "Get text property PROPERTY at beginning of line."
17576 (get-text-property (point-at-bol) property))
17578 (defun org-find-text-property-in-string (prop s)
17579 "Return the first non-nil value of property PROP in string S."
17580 (or (get-text-property 0 prop s)
17581 (get-text-property (or (next-single-property-change 0 prop s) 0)
17582 prop s)))
17584 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17585 "Display the given MESSAGE as a warning."
17586 (if (fboundp 'display-warning)
17587 (display-warning 'org message
17588 (if (featurep 'xemacs) 'warning :warning))
17589 (let ((buf (get-buffer-create "*Org warnings*")))
17590 (with-current-buffer buf
17591 (goto-char (point-max))
17592 (insert "Warning (Org): " message)
17593 (unless (bolp)
17594 (newline)))
17595 (display-buffer buf)
17596 (sit-for 0))))
17598 (defun org-in-commented-line ()
17599 "Is point in a line starting with `#'?"
17600 (equal (char-after (point-at-bol)) ?#))
17602 (defun org-in-indented-comment-line ()
17603 "Is point in a line starting with `#' after some white space?"
17604 (save-excursion
17605 (save-match-data
17606 (goto-char (point-at-bol))
17607 (looking-at "[ \t]*#"))))
17609 (defun org-in-verbatim-emphasis ()
17610 (save-match-data
17611 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17613 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17614 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17615 (if (and marker (marker-buffer marker)
17616 (buffer-live-p (marker-buffer marker)))
17617 (progn
17618 (switch-to-buffer (marker-buffer marker))
17619 (if (or (> marker (point-max)) (< marker (point-min)))
17620 (widen))
17621 (goto-char marker)
17622 (org-show-context 'org-goto))
17623 (if bookmark
17624 (bookmark-jump bookmark)
17625 (error "Cannot find location"))))
17627 (defun org-quote-csv-field (s)
17628 "Quote field for inclusion in CSV material."
17629 (if (string-match "[\",]" s)
17630 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17633 (defun org-plist-delete (plist property)
17634 "Delete PROPERTY from PLIST.
17635 This is in contrast to merely setting it to 0."
17636 (let (p)
17637 (while plist
17638 (if (not (eq property (car plist)))
17639 (setq p (plist-put p (car plist) (nth 1 plist))))
17640 (setq plist (cddr plist)))
17643 (defun org-force-self-insert (N)
17644 "Needed to enforce self-insert under remapping."
17645 (interactive "p")
17646 (self-insert-command N))
17648 (defun org-string-width (s)
17649 "Compute width of string, ignoring invisible characters.
17650 This ignores character with invisibility property `org-link', and also
17651 characters with property `org-cwidth', because these will become invisible
17652 upon the next fontification round."
17653 (let (b l)
17654 (when (or (eq t buffer-invisibility-spec)
17655 (assq 'org-link buffer-invisibility-spec))
17656 (while (setq b (text-property-any 0 (length s)
17657 'invisible 'org-link s))
17658 (setq s (concat (substring s 0 b)
17659 (substring s (or (next-single-property-change
17660 b 'invisible s) (length s)))))))
17661 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17662 (setq s (concat (substring s 0 b)
17663 (substring s (or (next-single-property-change
17664 b 'org-cwidth s) (length s))))))
17665 (setq l (string-width s) b -1)
17666 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17667 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17670 (defun org-get-indentation (&optional line)
17671 "Get the indentation of the current line, interpreting tabs.
17672 When LINE is given, assume it represents a line and compute its indentation."
17673 (if line
17674 (if (string-match "^ *" (org-remove-tabs line))
17675 (match-end 0))
17676 (save-excursion
17677 (beginning-of-line 1)
17678 (skip-chars-forward " \t")
17679 (current-column))))
17681 (defun org-remove-tabs (s &optional width)
17682 "Replace tabulators in S with spaces.
17683 Assumes that s is a single line, starting in column 0."
17684 (setq width (or width tab-width))
17685 (while (string-match "\t" s)
17686 (setq s (replace-match
17687 (make-string
17688 (- (* width (/ (+ (match-beginning 0) width) width))
17689 (match-beginning 0)) ?\ )
17690 t t s)))
17693 (defun org-fix-indentation (line ind)
17694 "Fix indentation in LINE.
17695 IND is a cons cell with target and minimum indentation.
17696 If the current indentation in LINE is smaller than the minimum,
17697 leave it alone. If it is larger than ind, set it to the target."
17698 (let* ((l (org-remove-tabs line))
17699 (i (org-get-indentation l))
17700 (i1 (car ind)) (i2 (cdr ind)))
17701 (if (>= i i2) (setq l (substring line i2)))
17702 (if (> i1 0)
17703 (concat (make-string i1 ?\ ) l)
17704 l)))
17706 (defun org-remove-indentation (code &optional n)
17707 "Remove the maximum common indentation from the lines in CODE.
17708 N may optionally be the number of spaces to remove."
17709 (with-temp-buffer
17710 (insert code)
17711 (org-do-remove-indentation n)
17712 (buffer-string)))
17714 (defun org-do-remove-indentation (&optional n)
17715 "Remove the maximum common indentation from the buffer."
17716 (untabify (point-min) (point-max))
17717 (let ((min 10000) re)
17718 (if n
17719 (setq min n)
17720 (goto-char (point-min))
17721 (while (re-search-forward "^ *[^ \n]" nil t)
17722 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17723 (unless (or (= min 0) (= min 10000))
17724 (setq re (format "^ \\{%d\\}" min))
17725 (goto-char (point-min))
17726 (while (re-search-forward re nil t)
17727 (replace-match "")
17728 (end-of-line 1))
17729 min)))
17731 (defun org-fill-template (template alist)
17732 "Find each %key of ALIST in TEMPLATE and replace it."
17733 (let ((case-fold-search nil)
17734 entry key value)
17735 (setq alist (sort (copy-sequence alist)
17736 (lambda (a b) (< (length (car a)) (length (car b))))))
17737 (while (setq entry (pop alist))
17738 (setq template
17739 (replace-regexp-in-string
17740 (concat "%" (regexp-quote (car entry)))
17741 (cdr entry) template t t)))
17742 template))
17744 (defun org-base-buffer (buffer)
17745 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17746 (if (not buffer)
17747 buffer
17748 (or (buffer-base-buffer buffer)
17749 buffer)))
17751 (defun org-trim (s)
17752 "Remove whitespace at beginning and end of string."
17753 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17754 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17757 (defun org-wrap (string &optional width lines)
17758 "Wrap string to either a number of lines, or a width in characters.
17759 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17760 that costs. If there is a word longer than WIDTH, the text is actually
17761 wrapped to the length of that word.
17762 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17763 many lines, whatever width that takes.
17764 The return value is a list of lines, without newlines at the end."
17765 (let* ((words (org-split-string string "[ \t\n]+"))
17766 (maxword (apply 'max (mapcar 'org-string-width words)))
17767 w ll)
17768 (cond (width
17769 (org-do-wrap words (max maxword width)))
17770 (lines
17771 (setq w maxword)
17772 (setq ll (org-do-wrap words maxword))
17773 (if (<= (length ll) lines)
17775 (setq ll words)
17776 (while (> (length ll) lines)
17777 (setq w (1+ w))
17778 (setq ll (org-do-wrap words w)))
17779 ll))
17780 (t (error "Cannot wrap this")))))
17782 (defun org-do-wrap (words width)
17783 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17784 (let (lines line)
17785 (while words
17786 (setq line (pop words))
17787 (while (and words (< (+ (length line) (length (car words))) width))
17788 (setq line (concat line " " (pop words))))
17789 (setq lines (push line lines)))
17790 (nreverse lines)))
17792 (defun org-split-string (string &optional separators)
17793 "Splits STRING into substrings at SEPARATORS.
17794 No empty strings are returned if there are matches at the beginning
17795 and end of string."
17796 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17797 (start 0)
17798 notfirst
17799 (list nil))
17800 (while (and (string-match rexp string
17801 (if (and notfirst
17802 (= start (match-beginning 0))
17803 (< start (length string)))
17804 (1+ start) start))
17805 (< (match-beginning 0) (length string)))
17806 (setq notfirst t)
17807 (or (eq (match-beginning 0) 0)
17808 (and (eq (match-beginning 0) (match-end 0))
17809 (eq (match-beginning 0) start))
17810 (setq list
17811 (cons (substring string start (match-beginning 0))
17812 list)))
17813 (setq start (match-end 0)))
17814 (or (eq start (length string))
17815 (setq list
17816 (cons (substring string start)
17817 list)))
17818 (nreverse list)))
17820 (defun org-quote-vert (s)
17821 "Replace \"|\" with \"\\vert\"."
17822 (while (string-match "|" s)
17823 (setq s (replace-match "\\vert" t t s)))
17826 (defun org-uuidgen-p (s)
17827 "Is S an ID created by UUIDGEN?"
17828 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17830 (defun org-context ()
17831 "Return a list of contexts of the current cursor position.
17832 If several contexts apply, all are returned.
17833 Each context entry is a list with a symbol naming the context, and
17834 two positions indicating start and end of the context. Possible
17835 contexts are:
17837 :headline anywhere in a headline
17838 :headline-stars on the leading stars in a headline
17839 :todo-keyword on a TODO keyword (including DONE) in a headline
17840 :tags on the TAGS in a headline
17841 :priority on the priority cookie in a headline
17842 :item on the first line of a plain list item
17843 :item-bullet on the bullet/number of a plain list item
17844 :checkbox on the checkbox in a plain list item
17845 :table in an org-mode table
17846 :table-special on a special filed in a table
17847 :table-table in a table.el table
17848 :link on a hyperlink
17849 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17850 :target on a <<target>>
17851 :radio-target on a <<<radio-target>>>
17852 :latex-fragment on a LaTeX fragment
17853 :latex-preview on a LaTeX fragment with overlayed preview image
17855 This function expects the position to be visible because it uses font-lock
17856 faces as a help to recognize the following contexts: :table-special, :link,
17857 and :keyword."
17858 (let* ((f (get-text-property (point) 'face))
17859 (faces (if (listp f) f (list f)))
17860 (p (point)) clist o)
17861 ;; First the large context
17862 (cond
17863 ((org-on-heading-p t)
17864 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17865 (when (progn
17866 (beginning-of-line 1)
17867 (looking-at org-todo-line-tags-regexp))
17868 (push (org-point-in-group p 1 :headline-stars) clist)
17869 (push (org-point-in-group p 2 :todo-keyword) clist)
17870 (push (org-point-in-group p 4 :tags) clist))
17871 (goto-char p)
17872 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17873 (if (looking-at "\\[#[A-Z0-9]\\]")
17874 (push (org-point-in-group p 0 :priority) clist)))
17876 ((org-at-item-p)
17877 (push (org-point-in-group p 2 :item-bullet) clist)
17878 (push (list :item (point-at-bol)
17879 (save-excursion (org-end-of-item) (point)))
17880 clist)
17881 (and (org-at-item-checkbox-p)
17882 (push (org-point-in-group p 0 :checkbox) clist)))
17884 ((org-at-table-p)
17885 (push (list :table (org-table-begin) (org-table-end)) clist)
17886 (if (memq 'org-formula faces)
17887 (push (list :table-special
17888 (previous-single-property-change p 'face)
17889 (next-single-property-change p 'face)) clist)))
17890 ((org-at-table-p 'any)
17891 (push (list :table-table) clist)))
17892 (goto-char p)
17894 ;; Now the small context
17895 (cond
17896 ((org-at-timestamp-p)
17897 (push (org-point-in-group p 0 :timestamp) clist))
17898 ((memq 'org-link faces)
17899 (push (list :link
17900 (previous-single-property-change p 'face)
17901 (next-single-property-change p 'face)) clist))
17902 ((memq 'org-special-keyword faces)
17903 (push (list :keyword
17904 (previous-single-property-change p 'face)
17905 (next-single-property-change p 'face)) clist))
17906 ((org-on-target-p)
17907 (push (org-point-in-group p 0 :target) clist)
17908 (goto-char (1- (match-beginning 0)))
17909 (if (looking-at org-radio-target-regexp)
17910 (push (org-point-in-group p 0 :radio-target) clist))
17911 (goto-char p))
17912 ((setq o (car (delq nil
17913 (mapcar
17914 (lambda (x)
17915 (if (memq x org-latex-fragment-image-overlays) x))
17916 (overlays-at (point))))))
17917 (push (list :latex-fragment
17918 (overlay-start o) (overlay-end o)) clist)
17919 (push (list :latex-preview
17920 (overlay-start o) (overlay-end o)) clist))
17921 ((org-inside-LaTeX-fragment-p)
17922 ;; FIXME: positions wrong.
17923 (push (list :latex-fragment (point) (point)) clist)))
17925 (setq clist (nreverse (delq nil clist)))
17926 clist))
17928 ;; FIXME: Compare with at-regexp-p Do we need both?
17929 (defun org-in-regexp (re &optional nlines visually)
17930 "Check if point is inside a match of regexp.
17931 Normally only the current line is checked, but you can include NLINES extra
17932 lines both before and after point into the search.
17933 If VISUALLY is set, require that the cursor is not after the match but
17934 really on, so that the block visually is on the match."
17935 (catch 'exit
17936 (let ((pos (point))
17937 (eol (point-at-eol (+ 1 (or nlines 0))))
17938 (inc (if visually 1 0)))
17939 (save-excursion
17940 (beginning-of-line (- 1 (or nlines 0)))
17941 (while (re-search-forward re eol t)
17942 (if (and (<= (match-beginning 0) pos)
17943 (>= (+ inc (match-end 0)) pos))
17944 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17946 (defun org-at-regexp-p (regexp)
17947 "Is point inside a match of REGEXP in the current line?"
17948 (catch 'exit
17949 (save-excursion
17950 (let ((pos (point)) (end (point-at-eol)))
17951 (beginning-of-line 1)
17952 (while (re-search-forward regexp end t)
17953 (if (and (<= (match-beginning 0) pos)
17954 (>= (match-end 0) pos))
17955 (throw 'exit t)))
17956 nil))))
17958 (defun org-in-regexps-block-p (start-re end-re)
17959 "Returns t if the current point is between matches of START-RE and END-RE.
17960 This will also return to if point is on one of the two matches."
17961 (interactive)
17962 (let ((p (point)))
17963 (save-excursion
17964 (and (or (org-at-regexp-p start-re)
17965 (re-search-backward start-re nil t))
17966 (re-search-forward end-re nil t)
17967 (>= (point) p)))))
17969 (defun org-occur-in-agenda-files (regexp &optional nlines)
17970 "Call `multi-occur' with buffers for all agenda files."
17971 (interactive "sOrg-files matching: \np")
17972 (let* ((files (org-agenda-files))
17973 (tnames (mapcar 'file-truename files))
17974 (extra org-agenda-text-search-extra-files)
17976 (when (eq (car extra) 'agenda-archives)
17977 (setq extra (cdr extra))
17978 (setq files (org-add-archive-files files)))
17979 (while (setq f (pop extra))
17980 (unless (member (file-truename f) tnames)
17981 (add-to-list 'files f 'append)
17982 (add-to-list 'tnames (file-truename f) 'append)))
17983 (multi-occur
17984 (mapcar (lambda (x)
17985 (with-current-buffer
17986 (or (get-file-buffer x) (find-file-noselect x))
17987 (widen)
17988 (current-buffer)))
17989 files)
17990 regexp)))
17992 (if (boundp 'occur-mode-find-occurrence-hook)
17993 ;; Emacs 23
17994 (add-hook 'occur-mode-find-occurrence-hook
17995 (lambda ()
17996 (when (org-mode-p)
17997 (org-reveal))))
17998 ;; Emacs 22
17999 (defadvice occur-mode-goto-occurrence
18000 (after org-occur-reveal activate)
18001 (and (org-mode-p) (org-reveal)))
18002 (defadvice occur-mode-goto-occurrence-other-window
18003 (after org-occur-reveal activate)
18004 (and (org-mode-p) (org-reveal)))
18005 (defadvice occur-mode-display-occurrence
18006 (after org-occur-reveal activate)
18007 (when (org-mode-p)
18008 (let ((pos (occur-mode-find-occurrence)))
18009 (with-current-buffer (marker-buffer pos)
18010 (save-excursion
18011 (goto-char pos)
18012 (org-reveal)))))))
18014 (defun org-occur-link-in-agenda-files ()
18015 "Create a link and search for it in the agendas.
18016 The link is not stored in `org-stored-links', it is just created
18017 for the search purpose."
18018 (interactive)
18019 (let ((link (condition-case nil
18020 (org-store-link nil)
18021 (error "Unable to create a link to here"))))
18022 (org-occur-in-agenda-files (regexp-quote link))))
18024 (defun org-uniquify (list)
18025 "Remove duplicate elements from LIST."
18026 (let (res)
18027 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18028 res))
18030 (defun org-delete-all (elts list)
18031 "Remove all elements in ELTS from LIST."
18032 (while elts
18033 (setq list (delete (pop elts) list)))
18034 list)
18036 (defun org-remove-if (predicate seq)
18037 "Remove everything from SEQ that fulfills PREDICATE."
18038 (let (res e)
18039 (while seq
18040 (setq e (pop seq))
18041 (if (not (funcall predicate e)) (push e res)))
18042 (nreverse res)))
18044 (defun org-remove-if-not (predicate seq)
18045 "Remove everything from SEQ that does not fulfill PREDICATE."
18046 (let (res e)
18047 (while seq
18048 (setq e (pop seq))
18049 (if (funcall predicate e) (push e res)))
18050 (nreverse res)))
18052 (defun org-back-over-empty-lines ()
18053 "Move backwards over whitespace, to the beginning of the first empty line.
18054 Returns the number of empty lines passed."
18055 (let ((pos (point)))
18056 (skip-chars-backward " \t\n\r")
18057 (beginning-of-line 2)
18058 (goto-char (min (point) pos))
18059 (count-lines (point) pos)))
18061 (defun org-skip-whitespace ()
18062 (skip-chars-forward " \t\n\r"))
18064 (defun org-point-in-group (point group &optional context)
18065 "Check if POINT is in match-group GROUP.
18066 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18067 match. If the match group does ot exist or point is not inside it,
18068 return nil."
18069 (and (match-beginning group)
18070 (>= point (match-beginning group))
18071 (<= point (match-end group))
18072 (if context
18073 (list context (match-beginning group) (match-end group))
18074 t)))
18076 (defun org-switch-to-buffer-other-window (&rest args)
18077 "Switch to buffer in a second window on the current frame.
18078 In particular, do not allow pop-up frames."
18079 (let (pop-up-frames special-display-buffer-names special-display-regexps
18080 special-display-function)
18081 (apply 'switch-to-buffer-other-window args)))
18083 (defun org-combine-plists (&rest plists)
18084 "Create a single property list from all plists in PLISTS.
18085 The process starts by copying the first list, and then setting properties
18086 from the other lists. Settings in the last list are the most significant
18087 ones and overrule settings in the other lists."
18088 (let ((rtn (copy-sequence (pop plists)))
18089 p v ls)
18090 (while plists
18091 (setq ls (pop plists))
18092 (while ls
18093 (setq p (pop ls) v (pop ls))
18094 (setq rtn (plist-put rtn p v))))
18095 rtn))
18097 (defun org-move-line-down (arg)
18098 "Move the current line down. With prefix argument, move it past ARG lines."
18099 (interactive "p")
18100 (let ((col (current-column))
18101 beg end pos)
18102 (beginning-of-line 1) (setq beg (point))
18103 (beginning-of-line 2) (setq end (point))
18104 (beginning-of-line (+ 1 arg))
18105 (setq pos (move-marker (make-marker) (point)))
18106 (insert (delete-and-extract-region beg end))
18107 (goto-char pos)
18108 (org-move-to-column col)))
18110 (defun org-move-line-up (arg)
18111 "Move the current line up. With prefix argument, move it past ARG lines."
18112 (interactive "p")
18113 (let ((col (current-column))
18114 beg end pos)
18115 (beginning-of-line 1) (setq beg (point))
18116 (beginning-of-line 2) (setq end (point))
18117 (beginning-of-line (- arg))
18118 (setq pos (move-marker (make-marker) (point)))
18119 (insert (delete-and-extract-region beg end))
18120 (goto-char pos)
18121 (org-move-to-column col)))
18123 (defun org-replace-escapes (string table)
18124 "Replace %-escapes in STRING with values in TABLE.
18125 TABLE is an association list with keys like \"%a\" and string values.
18126 The sequences in STRING may contain normal field width and padding information,
18127 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18128 so values can contain further %-escapes if they are define later in TABLE."
18129 (let ((tbl (copy-alist table))
18130 (case-fold-search nil)
18131 (pchg 0)
18132 e re rpl)
18133 (while (setq e (pop tbl))
18134 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18135 (when (and (cdr e) (string-match re (cdr e)))
18136 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18137 (safe "SREF"))
18138 (add-text-properties 0 3 (list 'sref sref) safe)
18139 (setcdr e (replace-match safe t t (cdr e)))))
18140 (while (string-match re string)
18141 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18142 (cdr e)))
18143 (setq string (replace-match rpl t t string))))
18144 (while (setq pchg (next-property-change pchg string))
18145 (let ((sref (get-text-property pchg 'sref string)))
18146 (when (and sref (string-match "SREF" string pchg))
18147 (setq string (replace-match sref t t string)))))
18148 string))
18150 (defun org-sublist (list start end)
18151 "Return a section of LIST, from START to END.
18152 Counting starts at 1."
18153 (let (rtn (c start))
18154 (setq list (nthcdr (1- start) list))
18155 (while (and list (<= c end))
18156 (push (pop list) rtn)
18157 (setq c (1+ c)))
18158 (nreverse rtn)))
18160 (defun org-find-base-buffer-visiting (file)
18161 "Like `find-buffer-visiting' but always return the base buffer and
18162 not an indirect buffer."
18163 (let ((buf (or (get-file-buffer file)
18164 (find-buffer-visiting file))))
18165 (if buf
18166 (or (buffer-base-buffer buf) buf)
18167 nil)))
18169 (defun org-image-file-name-regexp (&optional extensions)
18170 "Return regexp matching the file names of images.
18171 If EXTENSIONS is given, only match these."
18172 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18173 (image-file-name-regexp)
18174 (let ((image-file-name-extensions
18175 (or extensions
18176 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18177 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18178 (concat "\\."
18179 (regexp-opt (nconc (mapcar 'upcase
18180 image-file-name-extensions)
18181 image-file-name-extensions)
18183 "\\'"))))
18185 (defun org-file-image-p (file &optional extensions)
18186 "Return non-nil if FILE is an image."
18187 (save-match-data
18188 (string-match (org-image-file-name-regexp extensions) file)))
18190 (defun org-get-cursor-date ()
18191 "Return the date at cursor in as a time.
18192 This works in the calendar and in the agenda, anywhere else it just
18193 returns the current time."
18194 (let (date day defd)
18195 (cond
18196 ((eq major-mode 'calendar-mode)
18197 (setq date (calendar-cursor-to-date)
18198 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18199 ((eq major-mode 'org-agenda-mode)
18200 (setq day (get-text-property (point) 'day))
18201 (if day
18202 (setq date (calendar-gregorian-from-absolute day)
18203 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18204 (nth 2 date))))))
18205 (or defd (current-time))))
18207 (defvar org-agenda-action-marker (make-marker)
18208 "Marker pointing to the entry for the next agenda action.")
18210 (defun org-mark-entry-for-agenda-action ()
18211 "Mark the current entry as target of an agenda action.
18212 Agenda actions are actions executed from the agenda with the key `k',
18213 which make use of the date at the cursor."
18214 (interactive)
18215 (move-marker org-agenda-action-marker
18216 (save-excursion (org-back-to-heading t) (point))
18217 (current-buffer))
18218 (message
18219 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18221 ;;; Paragraph filling stuff.
18222 ;; We want this to be just right, so use the full arsenal.
18224 (defun org-indent-line-function ()
18225 "Indent line like previous, but further if previous was headline or item."
18226 (interactive)
18227 (let* ((pos (point))
18228 (itemp (org-at-item-p))
18229 (case-fold-search t)
18230 (org-drawer-regexp (or org-drawer-regexp "\000"))
18231 column bpos bcol tpos tcol bullet btype bullet-type)
18232 ;; Find the previous relevant line
18233 (beginning-of-line 1)
18234 (cond
18235 ((looking-at "#") (setq column 0))
18236 ((looking-at "\\*+ ") (setq column 0))
18237 ((and (looking-at "[ \t]*:END:")
18238 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18239 (save-excursion
18240 (goto-char (1- (match-beginning 1)))
18241 (setq column (current-column))))
18242 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18243 (save-excursion
18244 (re-search-backward
18245 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18246 (setq column (org-get-indentation (match-string 0))))
18248 (beginning-of-line 0)
18249 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18250 (not (looking-at "[ \t]*:END:"))
18251 (not (looking-at org-drawer-regexp)))
18252 (beginning-of-line 0))
18253 (cond
18254 ((looking-at "\\*+[ \t]+")
18255 (if (not org-adapt-indentation)
18256 (setq column 0)
18257 (goto-char (match-end 0))
18258 (setq column (current-column))))
18259 ((looking-at org-drawer-regexp)
18260 (goto-char (1- (match-beginning 1)))
18261 (setq column (current-column)))
18262 ((looking-at "\\([ \t]*\\):END:")
18263 (goto-char (match-end 1))
18264 (setq column (current-column)))
18265 ((org-in-item-p)
18266 (org-beginning-of-item)
18267 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18268 (setq bpos (match-beginning 1) tpos (match-end 0)
18269 bcol (progn (goto-char bpos) (current-column))
18270 tcol (progn (goto-char tpos) (current-column))
18271 bullet (match-string 1)
18272 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18273 (if (> tcol (+ bcol org-description-max-indent))
18274 (setq tcol (+ bcol 5)))
18275 (if (not itemp)
18276 (setq column tcol)
18277 (goto-char pos)
18278 (beginning-of-line 1)
18279 (if (looking-at "\\S-")
18280 (progn
18281 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18282 (setq bullet (match-string 1)
18283 btype (if (string-match "[0-9]" bullet) "n" bullet))
18284 (setq column (if (equal btype bullet-type) bcol tcol)))
18285 (setq column (org-get-indentation)))))
18286 (t (setq column (org-get-indentation))))))
18287 (goto-char pos)
18288 (if (<= (current-column) (current-indentation))
18289 (org-indent-line-to column)
18290 (save-excursion (org-indent-line-to column)))
18291 (setq column (current-column))
18292 (beginning-of-line 1)
18293 (if (looking-at
18294 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18295 (replace-match (concat (match-string 1)
18296 (format org-property-format
18297 (match-string 2) (match-string 3)))
18298 t t))
18299 (org-move-to-column column)))
18301 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18302 "Variable to store copy of `adaptive-fill-regexp'.
18303 Since `adaptive-fill-regexp' is set to never match, we need to
18304 store a backup of its value before entering `org-mode' so that
18305 the functionality can be provided as a fall-back.")
18307 (defun org-set-autofill-regexps ()
18308 (interactive)
18309 ;; In the paragraph separator we include headlines, because filling
18310 ;; text in a line directly attached to a headline would otherwise
18311 ;; fill the headline as well.
18312 (org-set-local 'comment-start-skip "^#+[ \t]*")
18313 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18314 ;; The paragraph starter includes hand-formatted lists.
18315 (org-set-local
18316 'paragraph-start
18317 (concat
18318 "\f" "\\|"
18319 "[ ]*$" "\\|"
18320 "\\*+ " "\\|"
18321 "[ \t]*#" "\\|"
18322 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18323 "[ \t]*[:|]" "\\|"
18324 "\\$\\$" "\\|"
18325 "\\\\\\(begin\\|end\\|[][]\\)"))
18326 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18327 ;; But only if the user has not turned off tables or fixed-width regions
18328 (org-set-local
18329 'auto-fill-inhibit-regexp
18330 (concat "\\*+ \\|#\\+"
18331 "\\|[ \t]*" org-keyword-time-regexp
18332 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18333 (concat
18334 "\\|[ \t]*["
18335 (if org-enable-table-editor "|" "")
18336 (if org-enable-fixed-width-editor ":" "")
18337 "]"))))
18338 ;; We use our own fill-paragraph function, to make sure that tables
18339 ;; and fixed-width regions are not wrapped. That function will pass
18340 ;; through to `fill-paragraph' when appropriate.
18341 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18342 ;; Adaptive filling: To get full control, first make sure that
18343 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18344 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18345 (org-set-local 'org-adaptive-fill-regexp-backup
18346 adaptive-fill-regexp))
18347 (org-set-local 'adaptive-fill-regexp "\000")
18348 (org-set-local 'adaptive-fill-function
18349 'org-adaptive-fill-function)
18350 (org-set-local
18351 'align-mode-rules-list
18352 '((org-in-buffer-settings
18353 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18354 (modes . '(org-mode))))))
18356 (defun org-fill-paragraph (&optional justify)
18357 "Re-align a table, pass through to fill-paragraph if no table."
18358 (let ((table-p (org-at-table-p))
18359 (table.el-p (org-at-table.el-p)))
18360 (cond ((and (equal (char-after (point-at-bol)) ?*)
18361 (save-excursion (goto-char (point-at-bol))
18362 (looking-at outline-regexp)))
18363 t) ; skip headlines
18364 (table.el-p t) ; skip table.el tables
18365 (table-p (org-table-align) t) ; align org-mode tables
18366 (t nil)))) ; call paragraph-fill
18368 ;; For reference, this is the default value of adaptive-fill-regexp
18369 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18371 (defun org-adaptive-fill-function ()
18372 "Return a fill prefix for org-mode files.
18373 In particular, this makes sure hanging paragraphs for hand-formatted lists
18374 work correctly."
18375 (cond
18376 ;; Comment line
18377 ((looking-at "#[ \t]+")
18378 (match-string-no-properties 0))
18379 ;; Description list
18380 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18381 (save-excursion
18382 (if (> (match-end 1) (+ (match-beginning 1)
18383 org-description-max-indent))
18384 (goto-char (+ (match-beginning 1) 5))
18385 (goto-char (match-end 0)))
18386 (make-string (current-column) ?\ )))
18387 ;; Ordered or unordered list
18388 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18389 (save-excursion
18390 (goto-char (match-end 0))
18391 (make-string (current-column) ?\ )))
18392 ;; Other text
18393 ((looking-at org-adaptive-fill-regexp-backup)
18394 (match-string-no-properties 0))))
18396 ;;; Other stuff.
18398 (defun org-toggle-fixed-width-section (arg)
18399 "Toggle the fixed-width export.
18400 If there is no active region, the QUOTE keyword at the current headline is
18401 inserted or removed. When present, it causes the text between this headline
18402 and the next to be exported as fixed-width text, and unmodified.
18403 If there is an active region, this command adds or removes a colon as the
18404 first character of this line. If the first character of a line is a colon,
18405 this line is also exported in fixed-width font."
18406 (interactive "P")
18407 (let* ((cc 0)
18408 (regionp (org-region-active-p))
18409 (beg (if regionp (region-beginning) (point)))
18410 (end (if regionp (region-end)))
18411 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18412 (case-fold-search nil)
18413 (re "[ \t]*\\(: \\)")
18414 off)
18415 (if regionp
18416 (save-excursion
18417 (goto-char beg)
18418 (setq cc (current-column))
18419 (beginning-of-line 1)
18420 (setq off (looking-at re))
18421 (while (> nlines 0)
18422 (setq nlines (1- nlines))
18423 (beginning-of-line 1)
18424 (cond
18425 (arg
18426 (org-move-to-column cc t)
18427 (insert ": \n")
18428 (forward-line -1))
18429 ((and off (looking-at re))
18430 (replace-match "" t t nil 1))
18431 ((not off) (org-move-to-column cc t) (insert ": ")))
18432 (forward-line 1)))
18433 (save-excursion
18434 (org-back-to-heading)
18435 (if (looking-at (concat outline-regexp
18436 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18437 (replace-match "" t t nil 1)
18438 (if (looking-at outline-regexp)
18439 (progn
18440 (goto-char (match-end 0))
18441 (insert org-quote-string " "))))))))
18443 (defun org-reftex-citation ()
18444 "Use reftex-citation to insert a citation into the buffer.
18445 This looks for a line like
18447 #+BIBLIOGRAPHY: foo plain option:-d
18449 and derives from it that foo.bib is the bibliography file relevant
18450 for this document. It then installs the necessary environment for RefTeX
18451 to work in this buffer and calls `reftex-citation' to insert a citation
18452 into the buffer.
18454 Export of such citations to both LaTeX and HTML is handled by the contributed
18455 package org-exp-bibtex by Taru Karttunen."
18456 (interactive)
18457 (let ((reftex-docstruct-symbol 'rds)
18458 (reftex-cite-format "\\cite{%l}")
18459 rds bib)
18460 (save-excursion
18461 (save-restriction
18462 (widen)
18463 (let ((case-fold-search t)
18464 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18465 (if (not (save-excursion
18466 (or (re-search-forward re nil t)
18467 (re-search-backward re nil t))))
18468 (error "No bibliography defined in file")
18469 (setq bib (concat (match-string 1) ".bib")
18470 rds (list (list 'bib bib)))))))
18471 (call-interactively 'reftex-citation)))
18473 ;;;; Functions extending outline functionality
18475 (defun org-beginning-of-line (&optional arg)
18476 "Go to the beginning of the current line. If that is invisible, continue
18477 to a visible line beginning. This makes the function of C-a more intuitive.
18478 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18479 first attempt, and only move to after the tags when the cursor is already
18480 beyond the end of the headline."
18481 (interactive "P")
18482 (let ((pos (point))
18483 (special (if (consp org-special-ctrl-a/e)
18484 (car org-special-ctrl-a/e)
18485 org-special-ctrl-a/e))
18486 refpos)
18487 (if (org-bound-and-true-p line-move-visual)
18488 (beginning-of-visual-line 1)
18489 (beginning-of-line 1))
18490 (if (and arg (fboundp 'move-beginning-of-line))
18491 (call-interactively 'move-beginning-of-line)
18492 (if (bobp)
18494 (backward-char 1)
18495 (if (org-invisible-p)
18496 (while (and (not (bobp)) (org-invisible-p))
18497 (backward-char 1)
18498 (beginning-of-line 1))
18499 (forward-char 1))))
18500 (when special
18501 (cond
18502 ((and (looking-at org-complex-heading-regexp)
18503 (= (char-after (match-end 1)) ?\ ))
18504 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18505 (point-at-eol)))
18506 (goto-char
18507 (if (eq special t)
18508 (cond ((> pos refpos) refpos)
18509 ((= pos (point)) refpos)
18510 (t (point)))
18511 (cond ((> pos (point)) (point))
18512 ((not (eq last-command this-command)) (point))
18513 (t refpos)))))
18514 ((org-at-item-p)
18515 (goto-char
18516 (if (eq special t)
18517 (cond ((> pos (match-end 4)) (match-end 4))
18518 ((= pos (point)) (match-end 4))
18519 (t (point)))
18520 (cond ((> pos (point)) (point))
18521 ((not (eq last-command this-command)) (point))
18522 (t (match-end 4))))))))
18523 (org-no-warnings
18524 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18526 (defun org-end-of-line (&optional arg)
18527 "Go to the end of the line.
18528 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18529 first attempt, and only move to after the tags when the cursor is already
18530 beyond the end of the headline."
18531 (interactive "P")
18532 (let ((special (if (consp org-special-ctrl-a/e)
18533 (cdr org-special-ctrl-a/e)
18534 org-special-ctrl-a/e)))
18535 (if (or (not special)
18536 (not (org-on-heading-p))
18537 arg)
18538 (call-interactively
18539 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18540 ((fboundp 'move-end-of-line) 'move-end-of-line)
18541 (t 'end-of-line)))
18542 (let ((pos (point)))
18543 (beginning-of-line 1)
18544 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18545 (if (eq special t)
18546 (if (or (< pos (match-beginning 1))
18547 (= pos (match-end 0)))
18548 (goto-char (match-beginning 1))
18549 (goto-char (match-end 0)))
18550 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18551 (goto-char (match-end 0))
18552 (goto-char (match-beginning 1))))
18553 (call-interactively (if (fboundp 'move-end-of-line)
18554 'move-end-of-line
18555 'end-of-line)))))
18556 (org-no-warnings
18557 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18559 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18560 (define-key org-mode-map "\C-e" 'org-end-of-line)
18561 (define-key org-mode-map [home] 'org-beginning-of-line)
18562 (define-key org-mode-map [end] 'org-end-of-line)
18564 (defun org-backward-sentence (&optional arg)
18565 "Go to beginning of sentence, or beginning of table field.
18566 This will call `backward-sentence' or `org-table-beginning-of-field',
18567 depending on context."
18568 (interactive "P")
18569 (cond
18570 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18571 (t (call-interactively 'backward-sentence))))
18573 (defun org-forward-sentence (&optional arg)
18574 "Go to end of sentence, or end of table field.
18575 This will call `forward-sentence' or `org-table-end-of-field',
18576 depending on context."
18577 (interactive "P")
18578 (cond
18579 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18580 (t (call-interactively 'forward-sentence))))
18582 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18583 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18585 (defun org-kill-line (&optional arg)
18586 "Kill line, to tags or end of line."
18587 (interactive "P")
18588 (cond
18589 ((or (not org-special-ctrl-k)
18590 (bolp)
18591 (not (org-on-heading-p)))
18592 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
18593 org-ctrl-k-protect-subtree)
18594 (if (or (eq org-ctrl-k-protect-subtree 'error)
18595 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
18596 (error "C-k aborted - would kill hidden subtree")))
18597 (call-interactively 'kill-line))
18598 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18599 (kill-region (point) (match-beginning 1))
18600 (org-set-tags nil t))
18601 (t (kill-region (point) (point-at-eol)))))
18603 (define-key org-mode-map "\C-k" 'org-kill-line)
18605 (defun org-yank (&optional arg)
18606 "Yank. If the kill is a subtree, treat it specially.
18607 This command will look at the current kill and check if is a single
18608 subtree, or a series of subtrees[1]. If it passes the test, and if the
18609 cursor is at the beginning of a line or after the stars of a currently
18610 empty headline, then the yank is handled specially. How exactly depends
18611 on the value of the following variables, both set by default.
18613 org-yank-folded-subtrees
18614 When set, the subtree(s) will be folded after insertion, but only
18615 if doing so would now swallow text after the yanked text.
18617 org-yank-adjusted-subtrees
18618 When set, the subtree will be promoted or demoted in order to
18619 fit into the local outline tree structure, which means that the level
18620 will be adjusted so that it becomes the smaller one of the two
18621 *visible* surrounding headings.
18623 Any prefix to this command will cause `yank' to be called directly with
18624 no special treatment. In particular, a simple `C-u' prefix will just
18625 plainly yank the text as it is.
18627 \[1] The test checks if the first non-white line is a heading
18628 and if there are no other headings with fewer stars."
18629 (interactive "P")
18630 (org-yank-generic 'yank arg))
18632 (defun org-yank-generic (command arg)
18633 "Perform some yank-like command.
18635 This function implements the behavior described in the `org-yank'
18636 documentation. However, it has been generalized to work for any
18637 interactive command with similar behavior."
18639 ;; pretend to be command COMMAND
18640 (setq this-command command)
18642 (if arg
18643 (call-interactively command)
18645 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18646 (and (org-kill-is-subtree-p)
18647 (or (bolp)
18648 (and (looking-at "[ \t]*$")
18649 (string-match
18650 "\\`\\*+\\'"
18651 (buffer-substring (point-at-bol) (point)))))))
18652 swallowp)
18653 (cond
18654 ((and subtreep org-yank-folded-subtrees)
18655 (let ((beg (point))
18656 end)
18657 (if (and subtreep org-yank-adjusted-subtrees)
18658 (org-paste-subtree nil nil 'for-yank)
18659 (call-interactively command))
18661 (setq end (point))
18662 (goto-char beg)
18663 (when (and (bolp) subtreep
18664 (not (setq swallowp
18665 (org-yank-folding-would-swallow-text beg end))))
18666 (or (looking-at outline-regexp)
18667 (re-search-forward (concat "^" outline-regexp) end t))
18668 (while (and (< (point) end) (looking-at outline-regexp))
18669 (hide-subtree)
18670 (org-cycle-show-empty-lines 'folded)
18671 (condition-case nil
18672 (outline-forward-same-level 1)
18673 (error (goto-char end)))))
18674 (when swallowp
18675 (message
18676 "Inserted text not folded because that would swallow text"))
18678 (goto-char end)
18679 (skip-chars-forward " \t\n\r")
18680 (beginning-of-line 1)
18681 (push-mark beg 'nomsg)))
18682 ((and subtreep org-yank-adjusted-subtrees)
18683 (let ((beg (point-at-bol)))
18684 (org-paste-subtree nil nil 'for-yank)
18685 (push-mark beg 'nomsg)))
18687 (call-interactively command))))))
18689 (defun org-yank-folding-would-swallow-text (beg end)
18690 "Would hide-subtree at BEG swallow any text after END?"
18691 (let (level)
18692 (save-excursion
18693 (goto-char beg)
18694 (when (or (looking-at outline-regexp)
18695 (re-search-forward (concat "^" outline-regexp) end t))
18696 (setq level (org-outline-level)))
18697 (goto-char end)
18698 (skip-chars-forward " \t\r\n\v\f")
18699 (if (or (eobp)
18700 (and (bolp) (looking-at org-outline-regexp)
18701 (<= (org-outline-level) level)))
18702 nil ; Nothing would be swallowed
18703 t)))) ; something would swallow
18705 (define-key org-mode-map "\C-y" 'org-yank)
18707 (defun org-invisible-p ()
18708 "Check if point is at a character currently not visible."
18709 ;; Early versions of noutline don't have `outline-invisible-p'.
18710 (if (fboundp 'outline-invisible-p)
18711 (outline-invisible-p)
18712 (get-char-property (point) 'invisible)))
18714 (defun org-invisible-p2 ()
18715 "Check if point is at a character currently not visible."
18716 (save-excursion
18717 (if (and (eolp) (not (bobp))) (backward-char 1))
18718 ;; Early versions of noutline don't have `outline-invisible-p'.
18719 (if (fboundp 'outline-invisible-p)
18720 (outline-invisible-p)
18721 (get-char-property (point) 'invisible))))
18723 (defun org-back-to-heading (&optional invisible-ok)
18724 "Call `outline-back-to-heading', but provide a better error message."
18725 (condition-case nil
18726 (outline-back-to-heading invisible-ok)
18727 (error (error "Before first headline at position %d in buffer %s"
18728 (point) (current-buffer)))))
18730 (defun org-beginning-of-defun ()
18731 "Go to the beginning of the subtree, i.e. back to the heading."
18732 (org-back-to-heading))
18733 (defun org-end-of-defun ()
18734 "Go to the end of the subtree."
18735 (org-end-of-subtree nil t))
18737 (defun org-before-first-heading-p ()
18738 "Before first heading?"
18739 (save-excursion
18740 (null (re-search-backward "^\\*+ " nil t))))
18742 (defun org-on-heading-p (&optional ignored)
18743 (outline-on-heading-p t))
18744 (defun org-at-heading-p (&optional ignored)
18745 (outline-on-heading-p t))
18747 (defun org-point-at-end-of-empty-headline ()
18748 "If point is at the end of an empty headline, return t, else nil.
18749 If the heading only contains a TODO keyword, it is still still considered
18750 empty."
18751 (and (looking-at "[ \t]*$")
18752 (save-excursion
18753 (beginning-of-line 1)
18754 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18755 "\\)?[ \t]*$")))))
18756 (defun org-at-heading-or-item-p ()
18757 (or (org-on-heading-p) (org-at-item-p)))
18759 (defun org-on-target-p ()
18760 (or (org-in-regexp org-radio-target-regexp)
18761 (org-in-regexp org-target-regexp)))
18763 (defun org-up-heading-all (arg)
18764 "Move to the heading line of which the present line is a subheading.
18765 This function considers both visible and invisible heading lines.
18766 With argument, move up ARG levels."
18767 (if (fboundp 'outline-up-heading-all)
18768 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18769 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18771 (defun org-up-heading-safe ()
18772 "Move to the heading line of which the present line is a subheading.
18773 This version will not throw an error. It will return the level of the
18774 headline found, or nil if no higher level is found.
18776 Also, this function will be a lot faster than `outline-up-heading',
18777 because it relies on stars being the outline starters. This can really
18778 make a significant difference in outlines with very many siblings."
18779 (let (start-level re)
18780 (org-back-to-heading t)
18781 (setq start-level (funcall outline-level))
18782 (if (equal start-level 1)
18784 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18785 (if (re-search-backward re nil t)
18786 (funcall outline-level)))))
18788 (defun org-first-sibling-p ()
18789 "Is this heading the first child of its parents?"
18790 (interactive)
18791 (let ((re (concat "^" outline-regexp))
18792 level l)
18793 (unless (org-at-heading-p t)
18794 (error "Not at a heading"))
18795 (setq level (funcall outline-level))
18796 (save-excursion
18797 (if (not (re-search-backward re nil t))
18799 (setq l (funcall outline-level))
18800 (< l level)))))
18802 (defun org-goto-sibling (&optional previous)
18803 "Goto the next sibling, even if it is invisible.
18804 When PREVIOUS is set, go to the previous sibling instead. Returns t
18805 when a sibling was found. When none is found, return nil and don't
18806 move point."
18807 (let ((fun (if previous 're-search-backward 're-search-forward))
18808 (pos (point))
18809 (re (concat "^" outline-regexp))
18810 level l)
18811 (when (condition-case nil (org-back-to-heading t) (error nil))
18812 (setq level (funcall outline-level))
18813 (catch 'exit
18814 (or previous (forward-char 1))
18815 (while (funcall fun re nil t)
18816 (setq l (funcall outline-level))
18817 (when (< l level) (goto-char pos) (throw 'exit nil))
18818 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18819 (goto-char pos)
18820 nil))))
18822 (defun org-show-siblings ()
18823 "Show all siblings of the current headline."
18824 (save-excursion
18825 (while (org-goto-sibling) (org-flag-heading nil)))
18826 (save-excursion
18827 (while (org-goto-sibling 'previous)
18828 (org-flag-heading nil))))
18830 (defun org-show-hidden-entry ()
18831 "Show an entry where even the heading is hidden."
18832 (save-excursion
18833 (org-show-entry)))
18835 (defun org-flag-heading (flag &optional entry)
18836 "Flag the current heading. FLAG non-nil means make invisible.
18837 When ENTRY is non-nil, show the entire entry."
18838 (save-excursion
18839 (org-back-to-heading t)
18840 ;; Check if we should show the entire entry
18841 (if entry
18842 (progn
18843 (org-show-entry)
18844 (save-excursion
18845 (and (outline-next-heading)
18846 (org-flag-heading nil))))
18847 (outline-flag-region (max (point-min) (1- (point)))
18848 (save-excursion (outline-end-of-heading) (point))
18849 flag))))
18851 (defun org-get-next-sibling ()
18852 "Move to next heading of the same level, and return point.
18853 If there is no such heading, return nil.
18854 This is like outline-next-sibling, but invisible headings are ok."
18855 (let ((level (funcall outline-level)))
18856 (outline-next-heading)
18857 (while (and (not (eobp)) (> (funcall outline-level) level))
18858 (outline-next-heading))
18859 (if (or (eobp) (< (funcall outline-level) level))
18861 (point))))
18863 (defun org-get-last-sibling ()
18864 "Move to previous heading of the same level, and return point.
18865 If there is no such heading, return nil."
18866 (let ((opoint (point))
18867 (level (funcall outline-level)))
18868 (outline-previous-heading)
18869 (when (and (/= (point) opoint) (outline-on-heading-p t))
18870 (while (and (> (funcall outline-level) level)
18871 (not (bobp)))
18872 (outline-previous-heading))
18873 (if (< (funcall outline-level) level)
18875 (point)))))
18877 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18878 ;; This contains an exact copy of the original function, but it uses
18879 ;; `org-back-to-heading', to make it work also in invisible
18880 ;; trees. And is uses an invisible-OK argument.
18881 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18882 ;; Furthermore, when used inside Org, finding the end of a large subtree
18883 ;; with many children and grandchildren etc, this can be much faster
18884 ;; than the outline version.
18885 (org-back-to-heading invisible-OK)
18886 (let ((first t)
18887 (level (funcall outline-level)))
18888 (if (and (org-mode-p) (< level 1000))
18889 ;; A true heading (not a plain list item), in Org-mode
18890 ;; This means we can easily find the end by looking
18891 ;; only for the right number of stars. Using a regexp to do
18892 ;; this is so much faster than using a Lisp loop.
18893 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18894 (forward-char 1)
18895 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18896 ;; something else, do it the slow way
18897 (while (and (not (eobp))
18898 (or first (> (funcall outline-level) level)))
18899 (setq first nil)
18900 (outline-next-heading)))
18901 (unless to-heading
18902 (if (memq (preceding-char) '(?\n ?\^M))
18903 (progn
18904 ;; Go to end of line before heading
18905 (forward-char -1)
18906 (if (memq (preceding-char) '(?\n ?\^M))
18907 ;; leave blank line before heading
18908 (forward-char -1))))))
18909 (point))
18911 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18912 "Use Org version in org-mode, for dramatic speed-up."
18913 (if (eq major-mode 'org-mode)
18914 (progn
18915 (org-end-of-subtree nil t)
18916 (unless (eobp) (backward-char 1)))
18917 ad-do-it))
18919 (defun org-forward-same-level (arg &optional invisible-ok)
18920 "Move forward to the arg'th subheading at same level as this one.
18921 Stop at the first and last subheadings of a superior heading."
18922 (interactive "p")
18923 (org-back-to-heading invisible-ok)
18924 (org-on-heading-p)
18925 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18926 (re (format "^\\*\\{1,%d\\} " level))
18928 (forward-char 1)
18929 (while (> arg 0)
18930 (while (and (re-search-forward re nil 'move)
18931 (setq l (- (match-end 0) (match-beginning 0) 1))
18932 (= l level)
18933 (not invisible-ok)
18934 (progn (backward-char 1) (org-invisible-p)))
18935 (if (< l level) (setq arg 1)))
18936 (setq arg (1- arg)))
18937 (beginning-of-line 1)))
18939 (defun org-backward-same-level (arg &optional invisible-ok)
18940 "Move backward to the arg'th subheading at same level as this one.
18941 Stop at the first and last subheadings of a superior heading."
18942 (interactive "p")
18943 (org-back-to-heading)
18944 (org-on-heading-p)
18945 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18946 (re (format "^\\*\\{1,%d\\} " level))
18948 (while (> arg 0)
18949 (while (and (re-search-backward re nil 'move)
18950 (setq l (- (match-end 0) (match-beginning 0) 1))
18951 (= l level)
18952 (not invisible-ok)
18953 (org-invisible-p))
18954 (if (< l level) (setq arg 1)))
18955 (setq arg (1- arg)))))
18957 (defun org-show-subtree ()
18958 "Show everything after this heading at deeper levels."
18959 (outline-flag-region
18960 (point)
18961 (save-excursion
18962 (org-end-of-subtree t t))
18963 nil))
18965 (defun org-show-entry ()
18966 "Show the body directly following this heading.
18967 Show the heading too, if it is currently invisible."
18968 (interactive)
18969 (save-excursion
18970 (condition-case nil
18971 (progn
18972 (org-back-to-heading t)
18973 (outline-flag-region
18974 (max (point-min) (1- (point)))
18975 (save-excursion
18976 (if (re-search-forward
18977 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18978 (match-beginning 1)
18979 (point-max)))
18980 nil)
18981 (org-cycle-hide-drawers 'children))
18982 (error nil))))
18984 (defun org-make-options-regexp (kwds &optional extra)
18985 "Make a regular expression for keyword lines."
18986 (concat
18988 "#?[ \t]*\\+\\("
18989 (mapconcat 'regexp-quote kwds "\\|")
18990 (if extra (concat "\\|" extra))
18991 "\\):[ \t]*"
18992 "\\(.*\\)"))
18994 ;; Make isearch reveal the necessary context
18995 (defun org-isearch-end ()
18996 "Reveal context after isearch exits."
18997 (when isearch-success ; only if search was successful
18998 (if (featurep 'xemacs)
18999 ;; Under XEmacs, the hook is run in the correct place,
19000 ;; we directly show the context.
19001 (org-show-context 'isearch)
19002 ;; In Emacs the hook runs *before* restoring the overlays.
19003 ;; So we have to use a one-time post-command-hook to do this.
19004 ;; (Emacs 22 has a special variable, see function `org-mode')
19005 (unless (and (boundp 'isearch-mode-end-hook-quit)
19006 isearch-mode-end-hook-quit)
19007 ;; Only when the isearch was not quitted.
19008 (org-add-hook 'post-command-hook 'org-isearch-post-command
19009 'append 'local)))))
19011 (defun org-isearch-post-command ()
19012 "Remove self from hook, and show context."
19013 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19014 (org-show-context 'isearch))
19017 ;;;; Integration with and fixes for other packages
19019 ;;; Imenu support
19021 (defvar org-imenu-markers nil
19022 "All markers currently used by Imenu.")
19023 (make-variable-buffer-local 'org-imenu-markers)
19025 (defun org-imenu-new-marker (&optional pos)
19026 "Return a new marker for use by Imenu, and remember the marker."
19027 (let ((m (make-marker)))
19028 (move-marker m (or pos (point)))
19029 (push m org-imenu-markers)
19032 (defun org-imenu-get-tree ()
19033 "Produce the index for Imenu."
19034 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19035 (setq org-imenu-markers nil)
19036 (let* ((n org-imenu-depth)
19037 (re (concat "^" outline-regexp))
19038 (subs (make-vector (1+ n) nil))
19039 (last-level 0)
19040 m level head)
19041 (save-excursion
19042 (save-restriction
19043 (widen)
19044 (goto-char (point-max))
19045 (while (re-search-backward re nil t)
19046 (setq level (org-reduced-level (funcall outline-level)))
19047 (when (<= level n)
19048 (looking-at org-complex-heading-regexp)
19049 (setq head (org-link-display-format
19050 (org-match-string-no-properties 4))
19051 m (org-imenu-new-marker))
19052 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19053 (if (>= level last-level)
19054 (push (cons head m) (aref subs level))
19055 (push (cons head (aref subs (1+ level))) (aref subs level))
19056 (loop for i from (1+ level) to n do (aset subs i nil)))
19057 (setq last-level level)))))
19058 (aref subs 1)))
19060 (eval-after-load "imenu"
19061 '(progn
19062 (add-hook 'imenu-after-jump-hook
19063 (lambda ()
19064 (if (eq major-mode 'org-mode)
19065 (org-show-context 'org-goto))))))
19067 (defun org-link-display-format (link)
19068 "Replace a link with either the description, or the link target
19069 if no description is present"
19070 (save-match-data
19071 (if (string-match org-bracket-link-analytic-regexp link)
19072 (replace-match (if (match-end 5)
19073 (match-string 5 link)
19074 (concat (match-string 1 link)
19075 (match-string 3 link)))
19076 nil t link)
19077 link)))
19079 ;; Speedbar support
19081 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19082 "Overlay marking the agenda restriction line in speedbar.")
19083 (overlay-put org-speedbar-restriction-lock-overlay
19084 'face 'org-agenda-restriction-lock)
19085 (overlay-put org-speedbar-restriction-lock-overlay
19086 'help-echo "Agendas are currently limited to this item.")
19087 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19089 (defun org-speedbar-set-agenda-restriction ()
19090 "Restrict future agenda commands to the location at point in speedbar.
19091 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19092 (interactive)
19093 (require 'org-agenda)
19094 (let (p m tp np dir txt)
19095 (cond
19096 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19097 'org-imenu t))
19098 (setq m (get-text-property p 'org-imenu-marker))
19099 (with-current-buffer (marker-buffer m)
19100 (goto-char m)
19101 (org-agenda-set-restriction-lock 'subtree)))
19102 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19103 'speedbar-function 'speedbar-find-file))
19104 (setq tp (previous-single-property-change
19105 (1+ p) 'speedbar-function)
19106 np (next-single-property-change
19107 tp 'speedbar-function)
19108 dir (speedbar-line-directory)
19109 txt (buffer-substring-no-properties (or tp (point-min))
19110 (or np (point-max))))
19111 (with-current-buffer (find-file-noselect
19112 (let ((default-directory dir))
19113 (expand-file-name txt)))
19114 (unless (org-mode-p)
19115 (error "Cannot restrict to non-Org-mode file"))
19116 (org-agenda-set-restriction-lock 'file)))
19117 (t (error "Don't know how to restrict Org-mode's agenda")))
19118 (move-overlay org-speedbar-restriction-lock-overlay
19119 (point-at-bol) (point-at-eol))
19120 (setq current-prefix-arg nil)
19121 (org-agenda-maybe-redo)))
19123 (eval-after-load "speedbar"
19124 '(progn
19125 (speedbar-add-supported-extension ".org")
19126 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19127 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19128 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19129 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19130 (add-hook 'speedbar-visiting-tag-hook
19131 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19133 ;;; Fixes and Hacks for problems with other packages
19135 ;; Make flyspell not check words in links, to not mess up our keymap
19136 (defun org-mode-flyspell-verify ()
19137 "Don't let flyspell put overlays at active buttons."
19138 (and (not (get-text-property (point) 'keymap))
19139 (not (get-text-property (point) 'org-no-flyspell))))
19141 (defun org-remove-flyspell-overlays-in (beg end)
19142 "Remove flyspell overlays in region."
19143 (and (org-bound-and-true-p flyspell-mode)
19144 (fboundp 'flyspell-delete-region-overlays)
19145 (flyspell-delete-region-overlays beg end))
19146 (add-text-properties beg end '(org-no-flyspell t)))
19148 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19149 (eval-after-load "bookmark"
19150 '(if (boundp 'bookmark-after-jump-hook)
19151 ;; We can use the hook
19152 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19153 ;; Hook not available, use advice
19154 (defadvice bookmark-jump (after org-make-visible activate)
19155 "Make the position visible."
19156 (org-bookmark-jump-unhide))))
19158 ;; Make sure saveplace shows the location if it was hidden
19159 (eval-after-load "saveplace"
19160 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19161 "Make the position visible."
19162 (org-bookmark-jump-unhide)))
19164 ;; Make sure ecb shows the location if it was hidden
19165 (eval-after-load "ecb"
19166 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19167 "Make hierarchy visible when jumping into location from ECB tree buffer."
19168 (if (eq major-mode 'org-mode)
19169 (org-show-context))))
19171 (defun org-bookmark-jump-unhide ()
19172 "Unhide the current position, to show the bookmark location."
19173 (and (org-mode-p)
19174 (or (org-invisible-p)
19175 (save-excursion (goto-char (max (point-min) (1- (point))))
19176 (org-invisible-p)))
19177 (org-show-context 'bookmark-jump)))
19179 ;; Make session.el ignore our circular variable
19180 (eval-after-load "session"
19181 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19183 ;;;; Experimental code
19185 (defun org-closed-in-range ()
19186 "Sparse tree of items closed in a certain time range.
19187 Still experimental, may disappear in the future."
19188 (interactive)
19189 ;; Get the time interval from the user.
19190 (let* ((time1 (org-float-time
19191 (org-read-date nil 'to-time nil "Starting date: ")))
19192 (time2 (org-float-time
19193 (org-read-date nil 'to-time nil "End date:")))
19194 ;; callback function
19195 (callback (lambda ()
19196 (let ((time
19197 (org-float-time
19198 (apply 'encode-time
19199 (org-parse-time-string
19200 (match-string 1))))))
19201 ;; check if time in interval
19202 (and (>= time time1) (<= time time2))))))
19203 ;; make tree, check each match with the callback
19204 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19206 ;;;; Finish up
19208 (provide 'org)
19210 (run-hooks 'org-load-hook)
19212 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19214 ;;; org.el ends here