List of user-visible changes in 6.34
[org-mode.git] / lisp / org.el
blob0720d301f6247e7607092be078c1e9148610786e
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
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.33trans
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)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.33trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message version)))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (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)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
193 (const :tag " docview: Links to doc-view buffers" org-docview)
194 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
195 (const :tag " id: Global IDs for identifying entries" org-id)
196 (const :tag " info: Links to Info nodes" org-info)
197 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
198 (const :tag " habit: Track your consistency with habits" org-habit)
199 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
200 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
201 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
202 (const :tag " mew Links to Mew folders/messages" org-mew)
203 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
204 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
205 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
206 (const :tag " vm: Links to VM folders/messages" org-vm)
207 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
208 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
209 (const :tag " mouse: Additional mouse support" org-mouse)
211 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
212 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
225 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
227 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
229 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
230 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
231 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
232 (const :tag "C mtags: Support for muse-like tags" org-mtags)
233 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
234 (const :tag "C R: Computation using the R language" org-R)
235 (const :tag "C registry: A registry for Org-mode links" org-registry)
236 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
237 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
238 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
239 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
240 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
241 (const :tag "C track: Keep up with Org-mode development" org-track)
242 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
244 (defcustom org-support-shift-select nil
245 "Non-nil means, make shift-cursor commands select text when possible.
247 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
248 selecting a region, or enlarge thusly regions started in this way.
249 In Org-mode, in special contexts, these same keys are used for other
250 purposes, important enough to compete with shift selection. Org tries
251 to balance these needs by supporting `shift-select-mode' outside these
252 special contexts, under control of this variable.
254 The default of this variable is nil, to avoid confusing behavior. Shifted
255 cursor keys will then execute Org commands in the following contexts:
256 - on a headline, changing TODO state (left/right) and priority (up/down)
257 - on a time stamp, changing the time
258 - in a plain list item, changing the bullet type
259 - in a property definition line, switching between allowed values
260 - in the BEGIN line of a clock table (changing the time block).
261 Outside these contexts, the commands will throw an error.
263 When this variable is t and the cursor is not in a special context,
264 Org-mode will support shift-selection for making and enlarging regions.
265 To make this more effective, the bullet cycling will no longer happen
266 anywhere in an item line, but only if the cursor is exactly on the bullet.
268 If you set this variable to the symbol `always', then the keys
269 will not be special in headlines, property lines, and item lines, to make
270 shift selection work there as well. If this is what you want, you can
271 use the following alternative commands: `C-c C-t' and `C-c ,' to
272 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
273 TODO sets, `C-c -' to cycle item bullet types, and properties can be
274 edited by hand or in column view.
276 However, when the cursor is on a timestamp, shift-cursor commands
277 will still edit the time stamp - this is just too good to give up.
279 XEmacs user should have this variable set to nil, because shift-select-mode
280 is Emacs 23 only."
281 :group 'org
282 :type '(choice
283 (const :tag "Never" nil)
284 (const :tag "When outside special context" t)
285 (const :tag "Everywhere except timestamps" always)))
287 (defgroup org-startup nil
288 "Options concerning startup of Org-mode."
289 :tag "Org Startup"
290 :group 'org)
292 (defcustom org-startup-folded t
293 "Non-nil means, entering Org-mode will switch to OVERVIEW.
294 This can also be configured on a per-file basis by adding one of
295 the following lines anywhere in the buffer:
297 #+STARTUP: fold (or `overview', this is equivalent)
298 #+STARTUP: nofold (or `showall', this is equivalent)
299 #+STARTUP: content
300 #+STARTUP: showeverything"
301 :group 'org-startup
302 :type '(choice
303 (const :tag "nofold: show all" nil)
304 (const :tag "fold: overview" t)
305 (const :tag "content: all headlines" content)
306 (const :tag "show everything, even drawers" showeverything)))
308 (defcustom org-startup-truncated t
309 "Non-nil means, entering Org-mode will set `truncate-lines'.
310 This is useful since some lines containing links can be very long and
311 uninteresting. Also tables look terrible when wrapped."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-startup-indented nil
316 "Non-nil means, turn on `org-indent-mode' on startup.
317 This can also be configured on a per-file basis by adding one of
318 the following lines anywhere in the buffer:
320 #+STARTUP: indent
321 #+STARTUP: noindent"
322 :group 'org-structure
323 :type '(choice
324 (const :tag "Not" nil)
325 (const :tag "Globally (slow on startup in large files)" t)))
327 (defcustom org-startup-with-beamer-mode nil
328 "Non-nil means, turn on `org-beamer-mode' on startup.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
332 #+STARTUP: beamer"
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-startup-align-all-tables nil
337 "Non-nil means, align all tables when visiting a file.
338 This is useful when the column width in tables is forced with <N> cookies
339 in table fields. Such tables will look correct only after the first re-align.
340 This can also be configured on a per-file basis by adding one of
341 the following lines anywhere in the buffer:
342 #+STARTUP: align
343 #+STARTUP: noalign"
344 :group 'org-startup
345 :type 'boolean)
347 (defcustom org-insert-mode-line-in-empty-file nil
348 "Non-nil means insert the first line setting Org-mode in empty files.
349 When the function `org-mode' is called interactively in an empty file, this
350 normally means that the file name does not automatically trigger Org-mode.
351 To ensure that the file will always be in Org-mode in the future, a
352 line enforcing Org-mode will be inserted into the buffer, if this option
353 has been set."
354 :group 'org-startup
355 :type 'boolean)
357 (defcustom org-replace-disputed-keys nil
358 "Non-nil means use alternative key bindings for some keys.
359 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
360 These keys are also used by other packages like shift-selection-mode'
361 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
362 If you want to use Org-mode together with one of these other modes,
363 or more generally if you would like to move some Org-mode commands to
364 other keys, set this variable and configure the keys with the variable
365 `org-disputed-keys'.
367 This option is only relevant at load-time of Org-mode, and must be set
368 *before* org.el is loaded. Changing it requires a restart of Emacs to
369 become effective."
370 :group 'org-startup
371 :type 'boolean)
373 (defcustom org-use-extra-keys nil
374 "Non-nil means use extra key sequence definitions for certain
375 commands. This happens automatically if you run XEmacs or if
376 window-system is nil. This variable lets you do the same
377 manually. You must set it before loading org.
379 Example: on Carbon Emacs 22 running graphically, with an external
380 keyboard on a Powerbook, the default way of setting M-left might
381 not work for either Alt or ESC. Setting this variable will make
382 it work for ESC."
383 :group 'org-startup
384 :type 'boolean)
386 (if (fboundp 'defvaralias)
387 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
389 (defcustom org-disputed-keys
390 '(([(shift up)] . [(meta p)])
391 ([(shift down)] . [(meta n)])
392 ([(shift left)] . [(meta -)])
393 ([(shift right)] . [(meta +)])
394 ([(control shift right)] . [(meta shift +)])
395 ([(control shift left)] . [(meta shift -)]))
396 "Keys for which Org-mode and other modes compete.
397 This is an alist, cars are the default keys, second element specifies
398 the alternative to use when `org-replace-disputed-keys' is t.
400 Keys can be specified in any syntax supported by `define-key'.
401 The value of this option takes effect only at Org-mode's startup,
402 therefore you'll have to restart Emacs to apply it after changing."
403 :group 'org-startup
404 :type 'alist)
406 (defun org-key (key)
407 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
408 Or return the original if not disputed."
409 (if org-replace-disputed-keys
410 (let* ((nkey (key-description key))
411 (x (org-find-if (lambda (x)
412 (equal (key-description (car x)) nkey))
413 org-disputed-keys)))
414 (if x (cdr x) key))
415 key))
417 (defun org-find-if (predicate seq)
418 (catch 'exit
419 (while seq
420 (if (funcall predicate (car seq))
421 (throw 'exit (car seq))
422 (pop seq)))))
424 (defun org-defkey (keymap key def)
425 "Define a key, possibly translated, as returned by `org-key'."
426 (define-key keymap (org-key key) def))
428 (defcustom org-ellipsis nil
429 "The ellipsis to use in the Org-mode outline.
430 When nil, just use the standard three dots. When a string, use that instead,
431 When a face, use the standard 3 dots, but with the specified face.
432 The change affects only Org-mode (which will then use its own display table).
433 Changing this requires executing `M-x org-mode' in a buffer to become
434 effective."
435 :group 'org-startup
436 :type '(choice (const :tag "Default" nil)
437 (face :tag "Face" :value org-warning)
438 (string :tag "String" :value "...#")))
440 (defvar org-display-table nil
441 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
443 (defgroup org-keywords nil
444 "Keywords in Org-mode."
445 :tag "Org Keywords"
446 :group 'org)
448 (defcustom org-deadline-string "DEADLINE:"
449 "String to mark deadline entries.
450 A deadline is this string, followed by a time stamp. Should be a word,
451 terminated by a colon. You can insert a schedule keyword and
452 a timestamp with \\[org-deadline].
453 Changes become only effective after restarting Emacs."
454 :group 'org-keywords
455 :type 'string)
457 (defcustom org-scheduled-string "SCHEDULED:"
458 "String to mark scheduled TODO entries.
459 A schedule is this string, followed by a time stamp. Should be a word,
460 terminated by a colon. You can insert a schedule keyword and
461 a timestamp with \\[org-schedule].
462 Changes become only effective after restarting Emacs."
463 :group 'org-keywords
464 :type 'string)
466 (defcustom org-closed-string "CLOSED:"
467 "String used as the prefix for timestamps logging closing a TODO entry."
468 :group 'org-keywords
469 :type 'string)
471 (defcustom org-clock-string "CLOCK:"
472 "String used as prefix for timestamps clocking work hours on an item."
473 :group 'org-keywords
474 :type 'string)
476 (defcustom org-comment-string "COMMENT"
477 "Entries starting with this keyword will never be exported.
478 An entry can be toggled between COMMENT and normal with
479 \\[org-toggle-comment].
480 Changes become only effective after restarting Emacs."
481 :group 'org-keywords
482 :type 'string)
484 (defcustom org-quote-string "QUOTE"
485 "Entries starting with this keyword will be exported in fixed-width font.
486 Quoting applies only to the text in the entry following the headline, and does
487 not extend beyond the next headline, even if that is lower level.
488 An entry can be toggled between QUOTE and normal with
489 \\[org-toggle-fixed-width-section]."
490 :group 'org-keywords
491 :type 'string)
493 (defconst org-repeat-re
494 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
495 "Regular expression for specifying repeated events.
496 After a match, group 1 contains the repeat expression.")
498 (defgroup org-structure nil
499 "Options concerning the general structure of Org-mode files."
500 :tag "Org Structure"
501 :group 'org)
503 (defgroup org-reveal-location nil
504 "Options about how to make context of a location visible."
505 :tag "Org Reveal Location"
506 :group 'org-structure)
508 (defconst org-context-choice
509 '(choice
510 (const :tag "Always" t)
511 (const :tag "Never" nil)
512 (repeat :greedy t :tag "Individual contexts"
513 (cons
514 (choice :tag "Context"
515 (const agenda)
516 (const org-goto)
517 (const occur-tree)
518 (const tags-tree)
519 (const link-search)
520 (const mark-goto)
521 (const bookmark-jump)
522 (const isearch)
523 (const default))
524 (boolean))))
525 "Contexts for the reveal options.")
527 (defcustom org-show-hierarchy-above '((default . t))
528 "Non-nil means, show full hierarchy when revealing a location.
529 Org-mode often shows locations in an org-mode file which might have
530 been invisible before. When this is set, the hierarchy of headings
531 above the exposed location is shown.
532 Turning this off for example for sparse trees makes them very compact.
533 Instead of t, this can also be an alist specifying this option for different
534 contexts. Valid contexts are
535 agenda when exposing an entry from the agenda
536 org-goto when using the command `org-goto' on key C-c C-j
537 occur-tree when using the command `org-occur' on key C-c /
538 tags-tree when constructing a sparse tree based on tags matches
539 link-search when exposing search matches associated with a link
540 mark-goto when exposing the jump goal of a mark
541 bookmark-jump when exposing a bookmark location
542 isearch when exiting from an incremental search
543 default default for all contexts not set explicitly"
544 :group 'org-reveal-location
545 :type org-context-choice)
547 (defcustom org-show-following-heading '((default . nil))
548 "Non-nil means, show following heading when revealing a location.
549 Org-mode often shows locations in an org-mode file which might have
550 been invisible before. When this is set, the heading following the
551 match is shown.
552 Turning this off for example for sparse trees makes them very compact,
553 but makes it harder to edit the location of the match. In such a case,
554 use the command \\[org-reveal] to show more context.
555 Instead of t, this can also be an alist specifying this option for different
556 contexts. See `org-show-hierarchy-above' for valid contexts."
557 :group 'org-reveal-location
558 :type org-context-choice)
560 (defcustom org-show-siblings '((default . nil) (isearch t))
561 "Non-nil means, show all sibling heading when revealing a location.
562 Org-mode often shows locations in an org-mode file which might have
563 been invisible before. When this is set, the sibling of the current entry
564 heading are all made visible. If `org-show-hierarchy-above' is t,
565 the same happens on each level of the hierarchy above the current entry.
567 By default this is on for the isearch context, off for all other contexts.
568 Turning this off for example for sparse trees makes them very compact,
569 but makes it harder to edit the location of the match. In such a case,
570 use the command \\[org-reveal] to show more context.
571 Instead of t, this can also be an alist specifying this option for different
572 contexts. See `org-show-hierarchy-above' for valid contexts."
573 :group 'org-reveal-location
574 :type org-context-choice)
576 (defcustom org-show-entry-below '((default . nil))
577 "Non-nil means, show the entry below a headline when revealing a location.
578 Org-mode often shows locations in an org-mode file which might have
579 been invisible before. When this is set, the text below the headline that is
580 exposed is also shown.
582 By default this is off for all contexts.
583 Instead of t, this can also be an alist specifying this option for different
584 contexts. See `org-show-hierarchy-above' for valid contexts."
585 :group 'org-reveal-location
586 :type org-context-choice)
588 (defcustom org-indirect-buffer-display 'other-window
589 "How should indirect tree buffers be displayed?
590 This applies to indirect buffers created with the commands
591 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
592 Valid values are:
593 current-window Display in the current window
594 other-window Just display in another window.
595 dedicated-frame Create one new frame, and re-use it each time.
596 new-frame Make a new frame each time. Note that in this case
597 previously-made indirect buffers are kept, and you need to
598 kill these buffers yourself."
599 :group 'org-structure
600 :group 'org-agenda-windows
601 :type '(choice
602 (const :tag "In current window" current-window)
603 (const :tag "In current frame, other window" other-window)
604 (const :tag "Each time a new frame" new-frame)
605 (const :tag "One dedicated frame" dedicated-frame)))
607 (defcustom org-use-speed-commands nil
608 "Non-nil means, activate single letter commands at beginning of a headline.
609 This may also be a function to test for appropriate locations where speed
610 commands should be active."
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Never" nil)
614 (const :tag "At beginning of headline stars" t)
615 (function)))
617 (defcustom org-speed-commands-user nil
618 "Alist of additional speed commands.
619 This list will be checked before `org-speed-commands-default'
620 when the variable `org-use-speed-commands' is non-nil
621 and when the cursor is at the beginning of a headline.
622 The car if each entry is a string with a single letter, which must
623 be assigned to `self-insert-command' in the global map.
624 The cdr is either a command to be called interactively, a function
625 to be called, or a form to be evaluated.
626 An entry that is just a list with a single string will be interpreted
627 as a descriptive headline that will be added when listing the speed
628 copmmands in the Help buffer using the `?' speed command."
629 :group 'org-structure
630 :type '(repeat :value ("k" . ignore)
631 (choice :value ("k" . ignore)
632 (list :tag "Descriptive Headline" (string :tag "Headline"))
633 (cons :tag "Letter and Command"
634 (string :tag "Command letter")
635 (choice
636 (function)
637 (sexp))))))
639 (defgroup org-cycle nil
640 "Options concerning visibility cycling in Org-mode."
641 :tag "Org Cycle"
642 :group 'org-structure)
644 (defcustom org-cycle-skip-children-state-if-no-children t
645 "Non-nil means, skip CHILDREN state in entries that don't have any."
646 :group 'org-cycle
647 :type 'boolean)
649 (defcustom org-cycle-max-level nil
650 "Maximum level which should still be subject to visibility cycling.
651 Levels higher than this will, for cycling, be treated as text, not a headline.
652 When `org-odd-levels-only' is set, a value of N in this variable actually
653 means 2N-1 stars as the limiting headline.
654 When nil, cycle all levels.
655 Note that the limiting level of cycling is also influenced by
656 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
657 `org-inlinetask-min-level' is, cycling will be limited to levels one less
658 than its value."
659 :group 'org-cycle
660 :type '(choice
661 (const :tag "No limit" nil)
662 (integer :tag "Maximum level")))
664 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
665 "Names of drawers. Drawers are not opened by cycling on the headline above.
666 Drawers only open with a TAB on the drawer line itself. A drawer looks like
667 this:
668 :DRAWERNAME:
669 .....
670 :END:
671 The drawer \"PROPERTIES\" is special for capturing properties through
672 the property API.
674 Drawers can be defined on the per-file basis with a line like:
676 #+DRAWERS: HIDDEN STATE PROPERTIES"
677 :group 'org-structure
678 :group 'org-cycle
679 :type '(repeat (string :tag "Drawer Name")))
681 (defcustom org-hide-block-startup nil
682 "Non-nil means, , entering Org-mode will fold all blocks.
683 This can also be set in on a per-file basis with
685 #+STARTUP: hideblocks
686 #+STARTUP: showblocks"
687 :group 'org-startup
688 :group 'org-cycle
689 :type 'boolean)
691 (defcustom org-cycle-global-at-bob nil
692 "Cycle globally if cursor is at beginning of buffer and not at a headline.
693 This makes it possible to do global cycling without having to use S-TAB or
694 C-u TAB. For this special case to work, the first line of the buffer
695 must not be a headline - it may be empty or some other text. When used in
696 this way, `org-cycle-hook' is disables temporarily, to make sure the
697 cursor stays at the beginning of the buffer.
698 When this option is nil, don't do anything special at the beginning
699 of the buffer."
700 :group 'org-cycle
701 :type 'boolean)
703 (defcustom org-cycle-level-after-item/entry-creation t
704 "Non-nil means, cycle entry level or item indentation in new empty entries.
706 When the cursor is at the end of an empty headline, i.e with only stars
707 and maybe a TODO keyword, TAB will then switch the entry to become a child,
708 and then all possible anchestor states, before returning to the original state.
709 This makes data entry extremely fast: M-RET to create a new headline,
710 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
712 When the cursor is at the end of an empty plain list item, one TAB will
713 make it a subitem, two or more tabs will back up to make this an item
714 higher up in the item hierarchy."
715 :group 'org-cycle
716 :type 'boolean)
718 (defcustom org-cycle-emulate-tab t
719 "Where should `org-cycle' emulate TAB.
720 nil Never
721 white Only in completely white lines
722 whitestart Only at the beginning of lines, before the first non-white char
723 t Everywhere except in headlines
724 exc-hl-bol Everywhere except at the start of a headline
725 If TAB is used in a place where it does not emulate TAB, the current subtree
726 visibility is cycled."
727 :group 'org-cycle
728 :type '(choice (const :tag "Never" nil)
729 (const :tag "Only in completely white lines" white)
730 (const :tag "Before first char in a line" whitestart)
731 (const :tag "Everywhere except in headlines" t)
732 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
735 (defcustom org-cycle-separator-lines 2
736 "Number of empty lines needed to keep an empty line between collapsed trees.
737 If you leave an empty line between the end of a subtree and the following
738 headline, this empty line is hidden when the subtree is folded.
739 Org-mode will leave (exactly) one empty line visible if the number of
740 empty lines is equal or larger to the number given in this variable.
741 So the default 2 means, at least 2 empty lines after the end of a subtree
742 are needed to produce free space between a collapsed subtree and the
743 following headline.
745 If the number is negative, and the number of empty lines is at least -N,
746 all empty lines are shown.
748 Special case: when 0, never leave empty lines in collapsed view."
749 :group 'org-cycle
750 :type 'integer)
751 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
753 (defcustom org-pre-cycle-hook nil
754 "Hook that is run before visibility cycling is happening.
755 The function(s) in this hook must accept a single argument which indicates
756 the new state that will be set right after running this hook. The
757 argument is a symbol. Before a global state change, it can have the values
758 `overview', `content', or `all'. Before a local state change, it can have
759 the values `folded', `children', or `subtree'."
760 :group 'org-cycle
761 :type 'hook)
763 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
764 org-cycle-hide-drawers
765 org-cycle-show-empty-lines
766 org-optimize-window-after-visibility-change)
767 "Hook that is run after `org-cycle' has changed the buffer visibility.
768 The function(s) in this hook must accept a single argument which indicates
769 the new state that was set by the most recent `org-cycle' command. The
770 argument is a symbol. After a global state change, it can have the values
771 `overview', `content', or `all'. After a local state change, it can have
772 the values `folded', `children', or `subtree'."
773 :group 'org-cycle
774 :type 'hook)
776 (defgroup org-edit-structure nil
777 "Options concerning structure editing in Org-mode."
778 :tag "Org Edit Structure"
779 :group 'org-structure)
781 (defcustom org-odd-levels-only nil
782 "Non-nil means, skip even levels and only use odd levels for the outline.
783 This has the effect that two stars are being added/taken away in
784 promotion/demotion commands. It also influences how levels are
785 handled by the exporters.
786 Changing it requires restart of `font-lock-mode' to become effective
787 for fontification also in regions already fontified.
788 You may also set this on a per-file basis by adding one of the following
789 lines to the buffer:
791 #+STARTUP: odd
792 #+STARTUP: oddeven"
793 :group 'org-edit-structure
794 :group 'org-font-lock
795 :type 'boolean)
797 (defcustom org-adapt-indentation t
798 "Non-nil means, adapt indentation to outline node level.
800 When this variable is set, Org assumes that you write outlines by
801 indenting text in each node to align with the headline (after the stars).
802 The following issues are influenced by this variable:
804 - When this is set and the *entire* text in an entry is indented, the
805 indentation is increased by one space in a demotion command, and
806 decreased by one in a promotion command. If any line in the entry
807 body starts with text at column 0, indentation is not changed at all.
809 - Property drawers and planning information is inserted indented when
810 this variable s set. When nil, they will not be indented.
812 - TAB indents a line relative to context. The lines below a headline
813 will be indented when this variable is set.
815 Note that this is all about true indentation, by adding and removing
816 space characters. See also `org-indent.el' which does level-dependent
817 indentation in a virtual way, i.e. at display time in Emacs."
818 :group 'org-edit-structure
819 :type 'boolean)
821 (defcustom org-special-ctrl-a/e nil
822 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
824 When t, `C-a' will bring back the cursor to the beginning of the
825 headline text, i.e. after the stars and after a possible TODO keyword.
826 In an item, this will be the position after the bullet.
827 When the cursor is already at that position, another `C-a' will bring
828 it to the beginning of the line.
830 `C-e' will jump to the end of the headline, ignoring the presence of tags
831 in the headline. A second `C-e' will then jump to the true end of the
832 line, after any tags. This also means that, when this variable is
833 non-nil, `C-e' also will never jump beyond the end of the heading of a
834 folded section, i.e. not after the ellipses.
836 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
837 going to the true line boundary first. Only a directly following, identical
838 keypress will bring the cursor to the special positions.
840 This may also be a cons cell where the behavior for `C-a' and `C-e' is
841 set separately."
842 :group 'org-edit-structure
843 :type '(choice
844 (const :tag "off" nil)
845 (const :tag "on: after stars/bullet and before tags first" t)
846 (const :tag "reversed: true line boundary first" reversed)
847 (cons :tag "Set C-a and C-e separately"
848 (choice :tag "Special C-a"
849 (const :tag "off" nil)
850 (const :tag "on: after stars/bullet first" t)
851 (const :tag "reversed: before stars/bullet first" reversed))
852 (choice :tag "Special C-e"
853 (const :tag "off" nil)
854 (const :tag "on: before tags first" t)
855 (const :tag "reversed: after tags first" reversed)))))
856 (if (fboundp 'defvaralias)
857 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
859 (defcustom org-special-ctrl-k nil
860 "Non-nil means `C-k' will behave specially in headlines.
861 When nil, `C-k' will call the default `kill-line' command.
862 When t, the following will happen while the cursor is in the headline:
864 - When the cursor is at the beginning of a headline, kill the entire
865 line and possible the folded subtree below the line.
866 - When in the middle of the headline text, kill the headline up to the tags.
867 - When after the headline text, kill the tags."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defcustom org-yank-folded-subtrees t
872 "Non-nil means, when yanking subtrees, fold them.
873 If the kill is a single subtree, or a sequence of subtrees, i.e. if
874 it starts with a heading and all other headings in it are either children
875 or siblings, then fold all the subtrees. However, do this only if no
876 text after the yank would be swallowed into a folded tree by this action."
877 :group 'org-edit-structure
878 :type 'boolean)
880 (defcustom org-yank-adjusted-subtrees nil
881 "Non-nil means, when yanking subtrees, adjust the level.
882 With this setting, `org-paste-subtree' is used to insert the subtree, see
883 this function for details."
884 :group 'org-edit-structure
885 :type 'boolean)
887 (defcustom org-M-RET-may-split-line '((default . t))
888 "Non-nil means, M-RET will split the line at the cursor position.
889 When nil, it will go to the end of the line before making a
890 new line.
891 You may also set this option in a different way for different
892 contexts. Valid contexts are:
894 headline when creating a new headline
895 item when creating a new item
896 table in a table field
897 default the value to be used for all contexts not explicitly
898 customized"
899 :group 'org-structure
900 :group 'org-table
901 :type '(choice
902 (const :tag "Always" t)
903 (const :tag "Never" nil)
904 (repeat :greedy t :tag "Individual contexts"
905 (cons
906 (choice :tag "Context"
907 (const headline)
908 (const item)
909 (const table)
910 (const default))
911 (boolean)))))
914 (defcustom org-insert-heading-respect-content nil
915 "Non-nil means, insert new headings after the current subtree.
916 When nil, the new heading is created directly after the current line.
917 The commands \\[org-insert-heading-respect-content] and
918 \\[org-insert-todo-heading-respect-content] turn this variable on
919 for the duration of the command."
920 :group 'org-structure
921 :type 'boolean)
923 (defcustom org-blank-before-new-entry '((heading . auto)
924 (plain-list-item . auto))
925 "Should `org-insert-heading' leave a blank line before new heading/item?
926 The value is an alist, with `heading' and `plain-list-item' as car,
927 and a boolean flag as cdr. For plain lists, if the variable
928 `org-empty-line-terminates-plain-lists' is set, the setting here
929 is ignored and no empty line is inserted, to keep the list in tact."
930 :group 'org-edit-structure
931 :type '(list
932 (cons (const heading)
933 (choice (const :tag "Never" nil)
934 (const :tag "Always" t)
935 (const :tag "Auto" auto)))
936 (cons (const plain-list-item)
937 (choice (const :tag "Never" nil)
938 (const :tag "Always" t)
939 (const :tag "Auto" auto)))))
941 (defcustom org-insert-heading-hook nil
942 "Hook being run after inserting a new heading."
943 :group 'org-edit-structure
944 :type 'hook)
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means, lines starting with \":\" are treated as fixed-width.
948 This currently only means, they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-edit-structure
952 :type 'boolean)
955 (defcustom org-goto-auto-isearch t
956 "Non-nil means, typing characters in org-goto starts incremental search."
957 :group 'org-edit-structure
958 :type 'boolean)
960 (defgroup org-sparse-trees nil
961 "Options concerning sparse trees in Org-mode."
962 :tag "Org Sparse Trees"
963 :group 'org-structure)
965 (defcustom org-highlight-sparse-tree-matches t
966 "Non-nil means, highlight all matches that define a sparse tree.
967 The highlights will automatically disappear the next time the buffer is
968 changed by an edit command."
969 :group 'org-sparse-trees
970 :type 'boolean)
972 (defcustom org-remove-highlights-with-change t
973 "Non-nil means, any change to the buffer will remove temporary highlights.
974 Such highlights are created by `org-occur' and `org-clock-display'.
975 When nil, `C-c C-c needs to be used to get rid of the highlights.
976 The highlights created by `org-preview-latex-fragment' always need
977 `C-c C-c' to be removed."
978 :group 'org-sparse-trees
979 :group 'org-time
980 :type 'boolean)
983 (defcustom org-occur-hook '(org-first-headline-recenter)
984 "Hook that is run after `org-occur' has constructed a sparse tree.
985 This can be used to recenter the window to show as much of the structure
986 as possible."
987 :group 'org-sparse-trees
988 :type 'hook)
990 (defgroup org-imenu-and-speedbar nil
991 "Options concerning imenu and speedbar in Org-mode."
992 :tag "Org Imenu and Speedbar"
993 :group 'org-structure)
995 (defcustom org-imenu-depth 2
996 "The maximum level for Imenu access to Org-mode headlines.
997 This also applied for speedbar access."
998 :group 'org-imenu-and-speedbar
999 :type 'integer)
1001 (defgroup org-table nil
1002 "Options concerning tables in Org-mode."
1003 :tag "Org Table"
1004 :group 'org)
1006 (defcustom org-enable-table-editor 'optimized
1007 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1008 When nil, such lines will be treated like ordinary lines.
1010 When equal to the symbol `optimized', the table editor will be optimized to
1011 do the following:
1012 - Automatic overwrite mode in front of whitespace in table fields.
1013 This makes the structure of the table stay in tact as long as the edited
1014 field does not exceed the column width.
1015 - Minimize the number of realigns. Normally, the table is aligned each time
1016 TAB or RET are pressed to move to another field. With optimization this
1017 happens only if changes to a field might have changed the column width.
1018 Optimization requires replacing the functions `self-insert-command',
1019 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1020 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1021 very good at guessing when a re-align will be necessary, but you can always
1022 force one with \\[org-ctrl-c-ctrl-c].
1024 If you would like to use the optimized version in Org-mode, but the
1025 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1027 This variable can be used to turn on and off the table editor during a session,
1028 but in order to toggle optimization, a restart is required.
1030 See also the variable `org-table-auto-blank-field'."
1031 :group 'org-table
1032 :type '(choice
1033 (const :tag "off" nil)
1034 (const :tag "on" t)
1035 (const :tag "on, optimized" optimized)))
1037 (defcustom org-self-insert-cluster-for-undo t
1038 "Non-nil means cluster self-insert commands for undo when possible.
1039 If this is set, then, like in the Emacs command loop, 20 consecutive
1040 characters will be undone together.
1041 This is configurable, because there is some impact on typing performance."
1042 :group 'org-table
1043 :type 'boolean)
1045 (defcustom org-table-tab-recognizes-table.el t
1046 "Non-nil means, TAB will automatically notice a table.el table.
1047 When it sees such a table, it moves point into it and - if necessary -
1048 calls `table-recognize-table'."
1049 :group 'org-table-editing
1050 :type 'boolean)
1052 (defgroup org-link nil
1053 "Options concerning links in Org-mode."
1054 :tag "Org Link"
1055 :group 'org)
1057 (defvar org-link-abbrev-alist-local nil
1058 "Buffer-local version of `org-link-abbrev-alist', which see.
1059 The value of this is taken from the #+LINK lines.")
1060 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1062 (defcustom org-link-abbrev-alist nil
1063 "Alist of link abbreviations.
1064 The car of each element is a string, to be replaced at the start of a link.
1065 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1066 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1068 [[linkkey:tag][description]]
1070 The 'linkkey' must be a word word, starting with a letter, followed
1071 by letters, numbers, '-' or '_'.
1073 If REPLACE is a string, the tag will simply be appended to create the link.
1074 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1075 the placeholder \"%h\" will cause a url-encoded version of the tag to
1076 be inserted at that point (see the function `url-hexify-string').
1078 REPLACE may also be a function that will be called with the tag as the
1079 only argument to create the link, which should be returned as a string.
1081 See the manual for examples."
1082 :group 'org-link
1083 :type '(repeat
1084 (cons
1085 (string :tag "Protocol")
1086 (choice
1087 (string :tag "Format")
1088 (function)))))
1090 (defcustom org-descriptive-links t
1091 "Non-nil means, hide link part and only show description of bracket links.
1092 Bracket links are like [[link][description]]. This variable sets the initial
1093 state in new org-mode buffers. The setting can then be toggled on a
1094 per-buffer basis from the Org->Hyperlinks menu."
1095 :group 'org-link
1096 :type 'boolean)
1098 (defcustom org-link-file-path-type 'adaptive
1099 "How the path name in file links should be stored.
1100 Valid values are:
1102 relative Relative to the current directory, i.e. the directory of the file
1103 into which the link is being inserted.
1104 absolute Absolute path, if possible with ~ for home directory.
1105 noabbrev Absolute path, no abbreviation of home directory.
1106 adaptive Use relative path for files in the current directory and sub-
1107 directories of it. For other files, use an absolute path."
1108 :group 'org-link
1109 :type '(choice
1110 (const relative)
1111 (const absolute)
1112 (const noabbrev)
1113 (const adaptive)))
1115 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1116 "Types of links that should be activated in Org-mode files.
1117 This is a list of symbols, each leading to the activation of a certain link
1118 type. In principle, it does not hurt to turn on most link types - there may
1119 be a small gain when turning off unused link types. The types are:
1121 bracket The recommended [[link][description]] or [[link]] links with hiding.
1122 angular Links in angular brackets that may contain whitespace like
1123 <bbdb:Carsten Dominik>.
1124 plain Plain links in normal text, no whitespace, like http://google.com.
1125 radio Text that is matched by a radio target, see manual for details.
1126 tag Tag settings in a headline (link to tag search).
1127 date Time stamps (link to calendar).
1128 footnote Footnote labels.
1130 Changing this variable requires a restart of Emacs to become effective."
1131 :group 'org-link
1132 :type '(set :greedy t
1133 (const :tag "Double bracket links (new style)" bracket)
1134 (const :tag "Angular bracket links (old style)" angular)
1135 (const :tag "Plain text links" plain)
1136 (const :tag "Radio target matches" radio)
1137 (const :tag "Tags" tag)
1138 (const :tag "Timestamps" date)
1139 (const :tag "Footnotes" footnote)))
1141 (defcustom org-make-link-description-function nil
1142 "Function to use to generate link descriptions from links. If
1143 nil the link location will be used. This function must take two
1144 parameters; the first is the link and the second the description
1145 org-insert-link has generated, and should return the description
1146 to use."
1147 :group 'org-link
1148 :type 'function)
1150 (defgroup org-link-store nil
1151 "Options concerning storing links in Org-mode."
1152 :tag "Org Store Link"
1153 :group 'org-link)
1155 (defcustom org-email-link-description-format "Email %c: %.30s"
1156 "Format of the description part of a link to an email or usenet message.
1157 The following %-escapes will be replaced by corresponding information:
1159 %F full \"From\" field
1160 %f name, taken from \"From\" field, address if no name
1161 %T full \"To\" field
1162 %t first name in \"To\" field, address if no name
1163 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1164 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1165 %s subject
1166 %m message-id.
1168 You may use normal field width specification between the % and the letter.
1169 This is for example useful to limit the length of the subject.
1171 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1172 :group 'org-link-store
1173 :type 'string)
1175 (defcustom org-from-is-user-regexp
1176 (let (r1 r2)
1177 (when (and user-mail-address (not (string= user-mail-address "")))
1178 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1179 (when (and user-full-name (not (string= user-full-name "")))
1180 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1181 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1182 "Regexp matched against the \"From:\" header of an email or usenet message.
1183 It should match if the message is from the user him/herself."
1184 :group 'org-link-store
1185 :type 'regexp)
1187 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1188 "Non-nil means, storing a link to an Org file will use entry IDs.
1190 Note that before this variable is even considered, org-id must be loaded,
1191 so please customize `org-modules' and turn it on.
1193 The variable can have the following values:
1195 t Create an ID if needed to make a link to the current entry.
1197 create-if-interactive
1198 If `org-store-link' is called directly (interactively, as a user
1199 command), do create an ID to support the link. But when doing the
1200 job for remember, only use the ID if it already exists. The
1201 purpose of this setting is to avoid proliferation of unwanted
1202 IDs, just because you happen to be in an Org file when you
1203 call `org-remember' that automatically and preemptively
1204 creates a link. If you do want to get an ID link in a remember
1205 template to an entry not having an ID, create it first by
1206 explicitly creating a link to it, using `C-c C-l' first.
1208 create-if-interactive-and-no-custom-id
1209 Like create-if-interactive, but do not create an ID if there is
1210 a CUSTOM_ID property defined in the entry. This is the default.
1212 use-existing
1213 Use existing ID, do not create one.
1215 nil Never use an ID to make a link, instead link using a text search for
1216 the headline text."
1217 :group 'org-link-store
1218 :type '(choice
1219 (const :tag "Create ID to make link" t)
1220 (const :tag "Create if storing link interactively"
1221 create-if-interactive)
1222 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1223 create-if-interactive-and-no-custom-id)
1224 (const :tag "Only use existing" use-existing)
1225 (const :tag "Do not use ID to create link" nil)))
1227 (defcustom org-context-in-file-links t
1228 "Non-nil means, file links from `org-store-link' contain context.
1229 A search string will be added to the file name with :: as separator and
1230 used to find the context when the link is activated by the command
1231 `org-open-at-point'.
1232 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1233 negates this setting for the duration of the command."
1234 :group 'org-link-store
1235 :type 'boolean)
1237 (defcustom org-keep-stored-link-after-insertion nil
1238 "Non-nil means, keep link in list for entire session.
1240 The command `org-store-link' adds a link pointing to the current
1241 location to an internal list. These links accumulate during a session.
1242 The command `org-insert-link' can be used to insert links into any
1243 Org-mode file (offering completion for all stored links). When this
1244 option is nil, every link which has been inserted once using \\[org-insert-link]
1245 will be removed from the list, to make completing the unused links
1246 more efficient."
1247 :group 'org-link-store
1248 :type 'boolean)
1250 (defgroup org-link-follow nil
1251 "Options concerning following links in Org-mode."
1252 :tag "Org Follow Link"
1253 :group 'org-link)
1255 (defcustom org-link-translation-function nil
1256 "Function to translate links with different syntax to Org syntax.
1257 This can be used to translate links created for example by the Planner
1258 or emacs-wiki packages to Org syntax.
1259 The function must accept two parameters, a TYPE containing the link
1260 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1261 which is everything after the link protocol. It should return a cons
1262 with possibly modified values of type and path.
1263 Org contains a function for this, so if you set this variable to
1264 `org-translate-link-from-planner', you should be able follow many
1265 links created by planner."
1266 :group 'org-link-follow
1267 :type 'function)
1269 (defcustom org-follow-link-hook nil
1270 "Hook that is run after a link has been followed."
1271 :group 'org-link-follow
1272 :type 'hook)
1274 (defcustom org-tab-follows-link nil
1275 "Non-nil means, on links TAB will follow the link.
1276 Needs to be set before org.el is loaded.
1277 This really should not be used, it does not make sense, and the
1278 implementation is bad."
1279 :group 'org-link-follow
1280 :type 'boolean)
1282 (defcustom org-return-follows-link nil
1283 "Non-nil means, on links RET will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1288 (defcustom org-mouse-1-follows-link
1289 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1290 "Non-nil means, mouse-1 on a link will follow the link.
1291 A longer mouse click will still set point. Does not work on XEmacs.
1292 Needs to be set before org.el is loaded."
1293 :group 'org-link-follow
1294 :type 'boolean)
1296 (defcustom org-mark-ring-length 4
1297 "Number of different positions to be recorded in the ring
1298 Changing this requires a restart of Emacs to work correctly."
1299 :group 'org-link-follow
1300 :type 'integer)
1302 (defcustom org-link-frame-setup
1303 '((vm . vm-visit-folder-other-frame)
1304 (gnus . gnus-other-frame)
1305 (file . find-file-other-window))
1306 "Setup the frame configuration for following links.
1307 When following a link with Emacs, it may often be useful to display
1308 this link in another window or frame. This variable can be used to
1309 set this up for the different types of links.
1310 For VM, use any of
1311 `vm-visit-folder'
1312 `vm-visit-folder-other-frame'
1313 For Gnus, use any of
1314 `gnus'
1315 `gnus-other-frame'
1316 `org-gnus-no-new-news'
1317 For FILE, use any of
1318 `find-file'
1319 `find-file-other-window'
1320 `find-file-other-frame'
1321 For the calendar, use the variable `calendar-setup'.
1322 For BBDB, it is currently only possible to display the matches in
1323 another window."
1324 :group 'org-link-follow
1325 :type '(list
1326 (cons (const vm)
1327 (choice
1328 (const vm-visit-folder)
1329 (const vm-visit-folder-other-window)
1330 (const vm-visit-folder-other-frame)))
1331 (cons (const gnus)
1332 (choice
1333 (const gnus)
1334 (const gnus-other-frame)
1335 (const org-gnus-no-new-news)))
1336 (cons (const file)
1337 (choice
1338 (const find-file)
1339 (const find-file-other-window)
1340 (const find-file-other-frame)))))
1342 (defcustom org-display-internal-link-with-indirect-buffer nil
1343 "Non-nil means, use indirect buffer to display infile links.
1344 Activating internal links (from one location in a file to another location
1345 in the same file) normally just jumps to the location. When the link is
1346 activated with a C-u prefix (or with mouse-3), the link is displayed in
1347 another window. When this option is set, the other window actually displays
1348 an indirect buffer clone of the current buffer, to avoid any visibility
1349 changes to the current buffer."
1350 :group 'org-link-follow
1351 :type 'boolean)
1353 (defcustom org-open-non-existing-files nil
1354 "Non-nil means, `org-open-file' will open non-existing files.
1355 When nil, an error will be generated.
1356 This variable applies only to external applications because they
1357 might choke on non-existing files. If the link is to a file that
1358 will be opened in Emacs, the variable is ignored."
1359 :group 'org-link-follow
1360 :type 'boolean)
1362 (defcustom org-open-directory-means-index-dot-org nil
1363 "Non-nil means, a link to a directory really means to index.org.
1364 When nil, following a directory link will run dired or open a finder/explorer
1365 window on that directory."
1366 :group 'org-link-follow
1367 :type 'boolean)
1369 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1370 "Function and arguments to call for following mailto links.
1371 This is a list with the first element being a lisp function, and the
1372 remaining elements being arguments to the function. In string arguments,
1373 %a will be replaced by the address, and %s will be replaced by the subject
1374 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1378 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1379 (const :tag "message-mail" (message-mail "%a" "%s"))
1380 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1382 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1383 "Non-nil means, ask for confirmation before executing shell links.
1384 Shell links can be dangerous: just think about a link
1386 [[shell:rm -rf ~/*][Google Search]]
1388 This link would show up in your Org-mode document as \"Google Search\",
1389 but really it would remove your entire home directory.
1390 Therefore we advise against setting this variable to nil.
1391 Just change it to `y-or-n-p' if you want to confirm with a
1392 single keystroke rather than having to type \"yes\"."
1393 :group 'org-link-follow
1394 :type '(choice
1395 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1396 (const :tag "with y-or-n (faster)" y-or-n-p)
1397 (const :tag "no confirmation (dangerous)" nil)))
1399 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1400 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1401 Elisp links can be dangerous: just think about a link
1403 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1405 This link would show up in your Org-mode document as \"Google Search\",
1406 but really it would remove your entire home directory.
1407 Therefore we advise against setting this variable to nil.
1408 Just change it to `y-or-n-p' if you want to confirm with a
1409 single keystroke rather than having to type \"yes\"."
1410 :group 'org-link-follow
1411 :type '(choice
1412 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1413 (const :tag "with y-or-n (faster)" y-or-n-p)
1414 (const :tag "no confirmation (dangerous)" nil)))
1416 (defconst org-file-apps-defaults-gnu
1417 '((remote . emacs)
1418 (system . mailcap)
1419 (t . mailcap))
1420 "Default file applications on a UNIX or GNU/Linux system.
1421 See `org-file-apps'.")
1423 (defconst org-file-apps-defaults-macosx
1424 '((remote . emacs)
1425 (t . "open %s")
1426 (system . "open %s")
1427 ("ps.gz" . "gv %s")
1428 ("eps.gz" . "gv %s")
1429 ("dvi" . "xdvi %s")
1430 ("fig" . "xfig %s"))
1431 "Default file applications on a MacOS X system.
1432 The system \"open\" is known as a default, but we use X11 applications
1433 for some files for which the OS does not have a good default.
1434 See `org-file-apps'.")
1436 (defconst org-file-apps-defaults-windowsnt
1437 (list
1438 '(remote . emacs)
1439 (cons t
1440 (list (if (featurep 'xemacs)
1441 'mswindows-shell-execute
1442 'w32-shell-execute)
1443 "open" 'file))
1444 (cons 'system
1445 (list (if (featurep 'xemacs)
1446 'mswindows-shell-execute
1447 'w32-shell-execute)
1448 "open" 'file)))
1449 "Default file applications on a Windows NT system.
1450 The system \"open\" is used for most files.
1451 See `org-file-apps'.")
1453 (defcustom org-file-apps
1455 (auto-mode . emacs)
1456 ("\\.mm\\'" . default)
1457 ("\\.x?html?\\'" . default)
1458 ("\\.pdf\\'" . default)
1460 "External applications for opening `file:path' items in a document.
1461 Org-mode uses system defaults for different file types, but
1462 you can use this variable to set the application for a given file
1463 extension. The entries in this list are cons cells where the car identifies
1464 files and the cdr the corresponding command. Possible values for the
1465 file identifier are
1466 \"regex\" Regular expression matched against the file name. For backward
1467 compatibility, this can also be a string with only alphanumeric
1468 characters, which is then interpreted as an extension.
1469 `directory' Matches a directory
1470 `remote' Matches a remote file, accessible through tramp or efs.
1471 Remote files most likely should be visited through Emacs
1472 because external applications cannot handle such paths.
1473 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1474 so all files Emacs knows how to handle. Using this with
1475 command `emacs' will open most files in Emacs. Beware that this
1476 will also open html files inside Emacs, unless you add
1477 (\"html\" . default) to the list as well.
1478 t Default for files not matched by any of the other options.
1479 `system' The system command to open files, like `open' on Windows
1480 and Mac OS X, and mailcap under GNU/Linux. This is the command
1481 that will be selected if you call `C-c C-o' with a double
1482 `C-u C-u' prefix.
1484 Possible values for the command are:
1485 `emacs' The file will be visited by the current Emacs process.
1486 `default' Use the default application for this file type, which is the
1487 association for t in the list, most likely in the system-specific
1488 part.
1489 This can be used to overrule an unwanted setting in the
1490 system-specific variable.
1491 `system' Use the system command for opening files, like \"open\".
1492 This command is specified by the entry whose car is `system'.
1493 Most likely, the system-specific version of this variable
1494 does define this command, but you can overrule/replace it
1495 here.
1496 string A command to be executed by a shell; %s will be replaced
1497 by the path to the file.
1498 sexp A Lisp form which will be evaluated. The file path will
1499 be available in the Lisp variable `file'.
1500 For more examples, see the system specific constants
1501 `org-file-apps-defaults-macosx'
1502 `org-file-apps-defaults-windowsnt'
1503 `org-file-apps-defaults-gnu'."
1504 :group 'org-link-follow
1505 :type '(repeat
1506 (cons (choice :value ""
1507 (string :tag "Extension")
1508 (const :tag "System command to open files" system)
1509 (const :tag "Default for unrecognized files" t)
1510 (const :tag "Remote file" remote)
1511 (const :tag "Links to a directory" directory)
1512 (const :tag "Any files that have Emacs modes"
1513 auto-mode))
1514 (choice :value ""
1515 (const :tag "Visit with Emacs" emacs)
1516 (const :tag "Use default" default)
1517 (const :tag "Use the system command" system)
1518 (string :tag "Command")
1519 (sexp :tag "Lisp form")))))
1521 (defgroup org-refile nil
1522 "Options concerning refiling entries in Org-mode."
1523 :tag "Org Refile"
1524 :group 'org)
1526 (defcustom org-directory "~/org"
1527 "Directory with org files.
1528 This is just a default location to look for Org files. There is no need
1529 at all to put your files into this directory. It is only used in the
1530 following situations:
1532 1. When a remember template specifies a target file that is not an
1533 absolute path. The path will then be interpreted relative to
1534 `org-directory'
1535 2. When a remember note is filed away in an interactive way (when exiting the
1536 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1537 with `org-directory' as the default path."
1538 :group 'org-refile
1539 :group 'org-remember
1540 :type 'directory)
1542 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1543 "Default target for storing notes.
1544 Used by the hooks for remember.el. This can be a string, or nil to mean
1545 the value of `remember-data-file'.
1546 You can set this on a per-template basis with the variable
1547 `org-remember-templates'."
1548 :group 'org-refile
1549 :group 'org-remember
1550 :type '(choice
1551 (const :tag "Default from remember-data-file" nil)
1552 file))
1554 (defcustom org-goto-interface 'outline
1555 "The default interface to be used for `org-goto'.
1556 Allowed values are:
1557 outline The interface shows an outline of the relevant file
1558 and the correct heading is found by moving through
1559 the outline or by searching with incremental search.
1560 outline-path-completion Headlines in the current buffer are offered via
1561 completion. This is the interface also used by
1562 the refile command."
1563 :group 'org-refile
1564 :type '(choice
1565 (const :tag "Outline" outline)
1566 (const :tag "Outline-path-completion" outline-path-completion)))
1568 (defcustom org-goto-max-level 5
1569 "Maximum level to be considered when running org-goto with refile interface."
1570 :group 'org-refile
1571 :type 'integer)
1573 (defcustom org-reverse-note-order nil
1574 "Non-nil means, store new notes at the beginning of a file or entry.
1575 When nil, new notes will be filed to the end of a file or entry.
1576 This can also be a list with cons cells of regular expressions that
1577 are matched against file names, and values."
1578 :group 'org-remember
1579 :group 'org-refile
1580 :type '(choice
1581 (const :tag "Reverse always" t)
1582 (const :tag "Reverse never" nil)
1583 (repeat :tag "By file name regexp"
1584 (cons regexp boolean))))
1586 (defcustom org-refile-targets nil
1587 "Targets for refiling entries with \\[org-refile].
1588 This is list of cons cells. Each cell contains:
1589 - a specification of the files to be considered, either a list of files,
1590 or a symbol whose function or variable value will be used to retrieve
1591 a file name or a list of file names. If you use `org-agenda-files' for
1592 that, all agenda files will be scanned for targets. Nil means, consider
1593 headings in the current buffer.
1594 - A specification of how to find candidate refile targets. This may be
1595 any of:
1596 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1597 This tag has to be present in all target headlines, inheritance will
1598 not be considered.
1599 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1600 todo keyword.
1601 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1602 headlines that are refiling targets.
1603 - a cons cell (:level . N). Any headline of level N is considered a target.
1604 Note that, when `org-odd-levels-only' is set, level corresponds to
1605 order in hierarchy, not to the number of stars.
1606 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1607 Note that, when `org-odd-levels-only' is set, level corresponds to
1608 order in hierarchy, not to the number of stars.
1610 You can set the variable `org-refile-target-verify-function' to a function
1611 to verify each headline found by the simple critery above.
1613 When this variable is nil, all top-level headlines in the current buffer
1614 are used, equivalent to the value `((nil . (:level . 1))'."
1615 :group 'org-refile
1616 :type '(repeat
1617 (cons
1618 (choice :value org-agenda-files
1619 (const :tag "All agenda files" org-agenda-files)
1620 (const :tag "Current buffer" nil)
1621 (function) (variable) (file))
1622 (choice :tag "Identify target headline by"
1623 (cons :tag "Specific tag" (const :value :tag) (string))
1624 (cons :tag "TODO keyword" (const :value :todo) (string))
1625 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1626 (cons :tag "Level number" (const :value :level) (integer))
1627 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1629 (defcustom org-refile-target-verify-function nil
1630 "Function to verify if the headline at point should be a refile target.
1631 The function will be called without arguments, with point at the
1632 beginning of the headline. It should return t and leave point
1633 where it is if the headline is a valid target for refiling.
1635 If the target should not be selected, the function must return nil.
1636 In addition to this, it may move point to a place from where the search
1637 should be continued. For example, the function may decide that the entire
1638 subtree of the current entry should be excluded and move point to the end
1639 of the subtree."
1640 :group 'org-refile
1641 :type 'function)
1643 (defcustom org-refile-use-outline-path nil
1644 "Non-nil means, provide refile targets as paths.
1645 So a level 3 headline will be available as level1/level2/level3.
1647 When the value is `file', also include the file name (without directory)
1648 into the path. In this case, you can also stop the completion after
1649 the file name, to get entries inserted as top level in the file.
1651 When `full-file-path', include the full file path."
1652 :group 'org-refile
1653 :type '(choice
1654 (const :tag "Not" nil)
1655 (const :tag "Yes" t)
1656 (const :tag "Start with file name" file)
1657 (const :tag "Start with full file path" full-file-path)))
1659 (defcustom org-outline-path-complete-in-steps t
1660 "Non-nil means, complete the outline path in hierarchical steps.
1661 When Org-mode uses the refile interface to select an outline path
1662 \(see variable `org-refile-use-outline-path'), the completion of
1663 the path can be done is a single go, or if can be done in steps down
1664 the headline hierarchy. Going in steps is probably the best if you
1665 do not use a special completion package like `ido' or `icicles'.
1666 However, when using these packages, going in one step can be very
1667 fast, while still showing the whole path to the entry."
1668 :group 'org-refile
1669 :type 'boolean)
1671 (defcustom org-refile-allow-creating-parent-nodes nil
1672 "Non-nil means, allow to create new nodes as refile targets.
1673 New nodes are then created by adding \"/new node name\" to the completion
1674 of an existing node. When the value of this variable is `confirm',
1675 new node creation must be confirmed by the user (recommended)
1676 When nil, the completion must match an existing entry.
1678 Note that, if the new heading is not seen by the criteria
1679 listed in `org-refile-targets', multiple instances of the same
1680 heading would be created by trying again to file under the new
1681 heading."
1682 :group 'org-refile
1683 :type '(choice
1684 (const :tag "Never" nil)
1685 (const :tag "Always" t)
1686 (const :tag "Prompt for confirmation" confirm)))
1688 (defgroup org-todo nil
1689 "Options concerning TODO items in Org-mode."
1690 :tag "Org TODO"
1691 :group 'org)
1693 (defgroup org-progress nil
1694 "Options concerning Progress logging in Org-mode."
1695 :tag "Org Progress"
1696 :group 'org-time)
1698 (defvar org-todo-interpretation-widgets
1700 (:tag "Sequence (cycling hits every state)" sequence)
1701 (:tag "Type (cycling directly to DONE)" type))
1702 "The available interpretation symbols for customizing
1703 `org-todo-keywords'.
1704 Interested libraries should add to this list.")
1706 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1707 "List of TODO entry keyword sequences and their interpretation.
1708 \\<org-mode-map>This is a list of sequences.
1710 Each sequence starts with a symbol, either `sequence' or `type',
1711 indicating if the keywords should be interpreted as a sequence of
1712 action steps, or as different types of TODO items. The first
1713 keywords are states requiring action - these states will select a headline
1714 for inclusion into the global TODO list Org-mode produces. If one of
1715 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1716 signify that no further action is necessary. If \"|\" is not found,
1717 the last keyword is treated as the only DONE state of the sequence.
1719 The command \\[org-todo] cycles an entry through these states, and one
1720 additional state where no keyword is present. For details about this
1721 cycling, see the manual.
1723 TODO keywords and interpretation can also be set on a per-file basis with
1724 the special #+SEQ_TODO and #+TYP_TODO lines.
1726 Each keyword can optionally specify a character for fast state selection
1727 \(in combination with the variable `org-use-fast-todo-selection')
1728 and specifiers for state change logging, using the same syntax
1729 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1730 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1731 indicates to record a time stamp each time this state is selected.
1733 Each keyword may also specify if a timestamp or a note should be
1734 recorded when entering or leaving the state, by adding additional
1735 characters in the parenthesis after the keyword. This looks like this:
1736 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1737 record only the time of the state change. With X and Y being either
1738 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1739 Y when leaving the state if and only if the *target* state does not
1740 define X. You may omit any of the fast-selection key or X or /Y,
1741 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1743 For backward compatibility, this variable may also be just a list
1744 of keywords - in this case the interpretation (sequence or type) will be
1745 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1746 :group 'org-todo
1747 :group 'org-keywords
1748 :type '(choice
1749 (repeat :tag "Old syntax, just keywords"
1750 (string :tag "Keyword"))
1751 (repeat :tag "New syntax"
1752 (cons
1753 (choice
1754 :tag "Interpretation"
1755 ;;Quick and dirty way to see
1756 ;;`org-todo-interpretations'. This takes the
1757 ;;place of item arguments
1758 :convert-widget
1759 (lambda (widget)
1760 (widget-put widget
1761 :args (mapcar
1762 #'(lambda (x)
1763 (widget-convert
1764 (cons 'const x)))
1765 org-todo-interpretation-widgets))
1766 widget))
1767 (repeat
1768 (string :tag "Keyword"))))))
1770 (defvar org-todo-keywords-1 nil
1771 "All TODO and DONE keywords active in a buffer.")
1772 (make-variable-buffer-local 'org-todo-keywords-1)
1773 (defvar org-todo-keywords-for-agenda nil)
1774 (defvar org-done-keywords-for-agenda nil)
1775 (defvar org-drawers-for-agenda nil)
1776 (defvar org-todo-keyword-alist-for-agenda nil)
1777 (defvar org-tag-alist-for-agenda nil)
1778 (defvar org-agenda-contributing-files nil)
1779 (defvar org-not-done-keywords nil)
1780 (make-variable-buffer-local 'org-not-done-keywords)
1781 (defvar org-done-keywords nil)
1782 (make-variable-buffer-local 'org-done-keywords)
1783 (defvar org-todo-heads nil)
1784 (make-variable-buffer-local 'org-todo-heads)
1785 (defvar org-todo-sets nil)
1786 (make-variable-buffer-local 'org-todo-sets)
1787 (defvar org-todo-log-states nil)
1788 (make-variable-buffer-local 'org-todo-log-states)
1789 (defvar org-todo-kwd-alist nil)
1790 (make-variable-buffer-local 'org-todo-kwd-alist)
1791 (defvar org-todo-key-alist nil)
1792 (make-variable-buffer-local 'org-todo-key-alist)
1793 (defvar org-todo-key-trigger nil)
1794 (make-variable-buffer-local 'org-todo-key-trigger)
1796 (defcustom org-todo-interpretation 'sequence
1797 "Controls how TODO keywords are interpreted.
1798 This variable is in principle obsolete and is only used for
1799 backward compatibility, if the interpretation of todo keywords is
1800 not given already in `org-todo-keywords'. See that variable for
1801 more information."
1802 :group 'org-todo
1803 :group 'org-keywords
1804 :type '(choice (const sequence)
1805 (const type)))
1807 (defcustom org-use-fast-todo-selection t
1808 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1809 This variable describes if and under what circumstances the cycling
1810 mechanism for TODO keywords will be replaced by a single-key, direct
1811 selection scheme.
1813 When nil, fast selection is never used.
1815 When the symbol `prefix', it will be used when `org-todo' is called with
1816 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1817 in an agenda buffer.
1819 When t, fast selection is used by default. In this case, the prefix
1820 argument forces cycling instead.
1822 In all cases, the special interface is only used if access keys have actually
1823 been assigned by the user, i.e. if keywords in the configuration are followed
1824 by a letter in parenthesis, like TODO(t)."
1825 :group 'org-todo
1826 :type '(choice
1827 (const :tag "Never" nil)
1828 (const :tag "By default" t)
1829 (const :tag "Only with C-u C-c C-t" prefix)))
1831 (defcustom org-provide-todo-statistics t
1832 "Non-nil means, update todo statistics after insert and toggle.
1833 ALL-HEADLINES means update todo statistics by including headlines
1834 with no TODO keyword as well, counting them as not done.
1835 A list of TODO keywords means the same, but skip keywords that are
1836 not in this list.
1838 When this is set, todo statistics is updated in the parent of the
1839 current entry each time a todo state is changed."
1840 :group 'org-todo
1841 :type '(choice
1842 (const :tag "Yes, only for TODO entries" t)
1843 (const :tag "Yes, including all entries" 'all-headlines)
1844 (repeat :tag "Yes, for TODOs in this list"
1845 (string :tag "TODO keyword"))
1846 (other :tag "No TODO statistics" nil)))
1848 (defcustom org-hierarchical-todo-statistics t
1849 "Non-nil means, TODO statistics covers just direct children.
1850 When nil, all entries in the subtree are considered.
1851 This has only an effect if `org-provide-todo-statistics' is set.
1852 To set this to nil for only a single subtree, use a COOKIE_DATA
1853 property and include the word \"recursive\" into the value."
1854 :group 'org-todo
1855 :type 'boolean)
1857 (defcustom org-after-todo-state-change-hook nil
1858 "Hook which is run after the state of a TODO item was changed.
1859 The new state (a string with a TODO keyword, or nil) is available in the
1860 Lisp variable `state'."
1861 :group 'org-todo
1862 :type 'hook)
1864 (defvar org-blocker-hook nil
1865 "Hook for functions that are allowed to block a state change.
1867 Each function gets as its single argument a property list, see
1868 `org-trigger-hook' for more information about this list.
1870 If any of the functions in this hook returns nil, the state change
1871 is blocked.")
1873 (defvar org-trigger-hook nil
1874 "Hook for functions that are triggered by a state change.
1876 Each function gets as its single argument a property list with at least
1877 the following elements:
1879 (:type type-of-change :position pos-at-entry-start
1880 :from old-state :to new-state)
1882 Depending on the type, more properties may be present.
1884 This mechanism is currently implemented for:
1886 TODO state changes
1887 ------------------
1888 :type todo-state-change
1889 :from previous state (keyword as a string), or nil, or a symbol
1890 'todo' or 'done', to indicate the general type of state.
1891 :to new state, like in :from")
1893 (defcustom org-enforce-todo-dependencies nil
1894 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1895 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1896 be blocked if any prior sibling is not yet done.
1897 Finally, if the parent is blocked because of ordered siblings of its own,
1898 the child will also be blocked.
1899 This variable needs to be set before org.el is loaded, and you need to
1900 restart Emacs after a change to make the change effective. The only way
1901 to change is while Emacs is running is through the customize interface."
1902 :set (lambda (var val)
1903 (set var val)
1904 (if val
1905 (add-hook 'org-blocker-hook
1906 'org-block-todo-from-children-or-siblings-or-parent)
1907 (remove-hook 'org-blocker-hook
1908 'org-block-todo-from-children-or-siblings-or-parent)))
1909 :group 'org-todo
1910 :type 'boolean)
1912 (defcustom org-enforce-todo-checkbox-dependencies nil
1913 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1914 When this is nil, checkboxes have no influence on switching TODO states.
1915 When non-nil, you first need to check off all check boxes before the TODO
1916 entry can be switched to DONE.
1917 This variable needs to be set before org.el is loaded, and you need to
1918 restart Emacs after a change to make the change effective. The only way
1919 to change is while Emacs is running is through the customize interface."
1920 :set (lambda (var val)
1921 (set var val)
1922 (if val
1923 (add-hook 'org-blocker-hook
1924 'org-block-todo-from-checkboxes)
1925 (remove-hook 'org-blocker-hook
1926 'org-block-todo-from-checkboxes)))
1927 :group 'org-todo
1928 :type 'boolean)
1930 (defcustom org-treat-insert-todo-heading-as-state-change nil
1931 "Non-nil means, inserting a TODO heading is treated as state change.
1932 So when the command \\[org-insert-todo-heading] is used, state change
1933 logging will apply if appropriate. When nil, the new TODO item will
1934 be inserted directly, and no logging will take place."
1935 :group 'org-todo
1936 :type 'boolean)
1938 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1939 "Non-nil means, switching TODO states with S-cursor counts as state change.
1940 This is the default behavior. However, setting this to nil allows a
1941 convenient way to select a TODO state and bypass any logging associated
1942 with that."
1943 :group 'org-todo
1944 :type 'boolean)
1946 (defcustom org-todo-state-tags-triggers nil
1947 "Tag changes that should be triggered by TODO state changes.
1948 This is a list. Each entry is
1950 (state-change (tag . flag) .......)
1952 State-change can be a string with a state, and empty string to indicate the
1953 state that has no TODO keyword, or it can be one of the symbols `todo'
1954 or `done', meaning any not-done or done state, respectively."
1955 :group 'org-todo
1956 :group 'org-tags
1957 :type '(repeat
1958 (cons (choice :tag "When changing to"
1959 (const :tag "Not-done state" todo)
1960 (const :tag "Done state" done)
1961 (string :tag "State"))
1962 (repeat
1963 (cons :tag "Tag action"
1964 (string :tag "Tag")
1965 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1967 (defcustom org-log-done nil
1968 "Information to record when a task moves to the DONE state.
1970 Possible values are:
1972 nil Don't add anything, just change the keyword
1973 time Add a time stamp to the task
1974 note Prompt for a note and add it with template `org-log-note-headings'
1976 This option can also be set with on a per-file-basis with
1978 #+STARTUP: nologdone
1979 #+STARTUP: logdone
1980 #+STARTUP: lognotedone
1982 You can have local logging settings for a subtree by setting the LOGGING
1983 property to one or more of these keywords."
1984 :group 'org-todo
1985 :group 'org-progress
1986 :type '(choice
1987 (const :tag "No logging" nil)
1988 (const :tag "Record CLOSED timestamp" time)
1989 (const :tag "Record CLOSED timestamp with note." note)))
1991 ;; Normalize old uses of org-log-done.
1992 (cond
1993 ((eq org-log-done t) (setq org-log-done 'time))
1994 ((and (listp org-log-done) (memq 'done org-log-done))
1995 (setq org-log-done 'note)))
1997 (defcustom org-log-reschedule nil
1998 "Information to record when the scheduling date of a tasks is modified.
2000 Possible values are:
2002 nil Don't add anything, just change the date
2003 time Add a time stamp to the task
2004 note Prompt for a note and add it with template `org-log-note-headings'
2006 This option can also be set with on a per-file-basis with
2008 #+STARTUP: nologreschedule
2009 #+STARTUP: logreschedule
2010 #+STARTUP: lognotereschedule"
2011 :group 'org-todo
2012 :group 'org-progress
2013 :type '(choice
2014 (const :tag "No logging" nil)
2015 (const :tag "Record timestamp" time)
2016 (const :tag "Record timestamp with note." note)))
2018 (defcustom org-log-redeadline nil
2019 "Information to record when the deadline date of a tasks is modified.
2021 Possible values are:
2023 nil Don't add anything, just change the date
2024 time Add a time stamp to the task
2025 note Prompt for a note and add it with template `org-log-note-headings'
2027 This option can also be set with on a per-file-basis with
2029 #+STARTUP: nologredeadline
2030 #+STARTUP: logredeadline
2031 #+STARTUP: lognoteredeadline
2033 You can have local logging settings for a subtree by setting the LOGGING
2034 property to one or more of these keywords."
2035 :group 'org-todo
2036 :group 'org-progress
2037 :type '(choice
2038 (const :tag "No logging" nil)
2039 (const :tag "Record timestamp" time)
2040 (const :tag "Record timestamp with note." note)))
2042 (defcustom org-log-note-clock-out nil
2043 "Non-nil means, record a note when clocking out of an item.
2044 This can also be configured on a per-file basis by adding one of
2045 the following lines anywhere in the buffer:
2047 #+STARTUP: lognoteclock-out
2048 #+STARTUP: nolognoteclock-out"
2049 :group 'org-todo
2050 :group 'org-progress
2051 :type 'boolean)
2053 (defcustom org-log-done-with-time t
2054 "Non-nil means, the CLOSED time stamp will contain date and time.
2055 When nil, only the date will be recorded."
2056 :group 'org-progress
2057 :type 'boolean)
2059 (defcustom org-log-note-headings
2060 '((done . "CLOSING NOTE %t")
2061 (state . "State %-12s from %-12S %t")
2062 (note . "Note taken on %t")
2063 (reschedule . "Rescheduled from %S on %t")
2064 (delschedule . "Not scheduled, was %S on %t")
2065 (redeadline . "New deadline from %S on %t")
2066 (deldeadline . "Removed deadline, was %S on %t")
2067 (clock-out . ""))
2068 "Headings for notes added to entries.
2069 The value is an alist, with the car being a symbol indicating the note
2070 context, and the cdr is the heading to be used. The heading may also be the
2071 empty string.
2072 %t in the heading will be replaced by a time stamp.
2073 %s will be replaced by the new TODO state, in double quotes.
2074 %S will be replaced by the old TODO state, in double quotes.
2075 %u will be replaced by the user name.
2076 %U will be replaced by the full user name.
2078 In fact, it is not a good idea to change the `state' entry, because
2079 agenda log mode depends on the format of these entries."
2080 :group 'org-todo
2081 :group 'org-progress
2082 :type '(list :greedy t
2083 (cons (const :tag "Heading when closing an item" done) string)
2084 (cons (const :tag
2085 "Heading when changing todo state (todo sequence only)"
2086 state) string)
2087 (cons (const :tag "Heading when just taking a note" note) string)
2088 (cons (const :tag "Heading when clocking out" clock-out) string)
2089 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2090 (cons (const :tag "Heading when rescheduling" reschedule) string)
2091 (cons (const :tag "Heading when changing deadline" redeadline) string
2092 (cons (const :tag "Heading when deleting a deadline" deldeadline) string))))
2094 (unless (assq 'note org-log-note-headings)
2095 (push '(note . "%t") org-log-note-headings))
2097 (defcustom org-log-into-drawer nil
2098 "Non-nil means, insert state change notes and time stamps into a drawer.
2099 When nil, state changes notes will be inserted after the headline and
2100 any scheduling and clock lines, but not inside a drawer.
2102 The value of this variable should be the name of the drawer to use.
2103 LOGBOOK is proposed at the default drawer for this purpose, you can
2104 also set this to a string to define the drawer of your choice.
2106 A value of t is also allowed, representing \"LOGBOOK\".
2108 If this variable is set, `org-log-state-notes-insert-after-drawers'
2109 will be ignored.
2111 You can set the property LOG_INTO_DRAWER to overrule this setting for
2112 a subtree."
2113 :group 'org-todo
2114 :group 'org-progress
2115 :type '(choice
2116 (const :tag "Not into a drawer" nil)
2117 (const :tag "LOGBOOK" t)
2118 (string :tag "Other")))
2120 (if (fboundp 'defvaralias)
2121 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2123 (defun org-log-into-drawer ()
2124 "Return the value of `org-log-into-drawer', but let properties overrule.
2125 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2126 used instead of the default value."
2127 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2128 (cond
2129 ((or (not p) (equal p "nil")) org-log-into-drawer)
2130 ((equal p "t") "LOGBOOK")
2131 (t p))))
2133 (defcustom org-log-state-notes-insert-after-drawers nil
2134 "Non-nil means, insert state change notes after any drawers in entry.
2135 Only the drawers that *immediately* follow the headline and the
2136 deadline/scheduled line are skipped.
2137 When nil, insert notes right after the heading and perhaps the line
2138 with deadline/scheduling if present.
2140 This variable will have no effect if `org-log-into-drawer' is
2141 set."
2142 :group 'org-todo
2143 :group 'org-progress
2144 :type 'boolean)
2146 (defcustom org-log-states-order-reversed t
2147 "Non-nil means, the latest state change note will be directly after heading.
2148 When nil, the notes will be orderer according to time."
2149 :group 'org-todo
2150 :group 'org-progress
2151 :type 'boolean)
2153 (defcustom org-log-repeat 'time
2154 "Non-nil means, record moving through the DONE state when triggering repeat.
2155 An auto-repeating task is immediately switched back to TODO when
2156 marked DONE. If you are not logging state changes (by adding \"@\"
2157 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2158 record a closing note, there will be no record of the task moving
2159 through DONE. This variable forces taking a note anyway.
2161 nil Don't force a record
2162 time Record a time stamp
2163 note Record a note
2165 This option can also be set with on a per-file-basis with
2167 #+STARTUP: logrepeat
2168 #+STARTUP: lognoterepeat
2169 #+STARTUP: nologrepeat
2171 You can have local logging settings for a subtree by setting the LOGGING
2172 property to one or more of these keywords."
2173 :group 'org-todo
2174 :group 'org-progress
2175 :type '(choice
2176 (const :tag "Don't force a record" nil)
2177 (const :tag "Force recording the DONE state" time)
2178 (const :tag "Force recording a note with the DONE state" note)))
2181 (defgroup org-priorities nil
2182 "Priorities in Org-mode."
2183 :tag "Org Priorities"
2184 :group 'org-todo)
2186 (defcustom org-enable-priority-commands t
2187 "Non-nil means, priority commands are active.
2188 When nil, these commands will be disabled, so that you never accidentally
2189 set a priority."
2190 :group 'org-priorities
2191 :type 'boolean)
2193 (defcustom org-highest-priority ?A
2194 "The highest priority of TODO items. A character like ?A, ?B etc.
2195 Must have a smaller ASCII number than `org-lowest-priority'."
2196 :group 'org-priorities
2197 :type 'character)
2199 (defcustom org-lowest-priority ?C
2200 "The lowest priority of TODO items. A character like ?A, ?B etc.
2201 Must have a larger ASCII number than `org-highest-priority'."
2202 :group 'org-priorities
2203 :type 'character)
2205 (defcustom org-default-priority ?B
2206 "The default priority of TODO items.
2207 This is the priority an item get if no explicit priority is given."
2208 :group 'org-priorities
2209 :type 'character)
2211 (defcustom org-priority-start-cycle-with-default t
2212 "Non-nil means, start with default priority when starting to cycle.
2213 When this is nil, the first step in the cycle will be (depending on the
2214 command used) one higher or lower that the default priority."
2215 :group 'org-priorities
2216 :type 'boolean)
2218 (defgroup org-time nil
2219 "Options concerning time stamps and deadlines in Org-mode."
2220 :tag "Org Time"
2221 :group 'org)
2223 (defcustom org-insert-labeled-timestamps-at-point nil
2224 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2225 When nil, these labeled time stamps are forces into the second line of an
2226 entry, just after the headline. When scheduling from the global TODO list,
2227 the time stamp will always be forced into the second line."
2228 :group 'org-time
2229 :type 'boolean)
2231 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2232 "Formats for `format-time-string' which are used for time stamps.
2233 It is not recommended to change this constant.")
2235 (defcustom org-time-stamp-rounding-minutes '(0 5)
2236 "Number of minutes to round time stamps to.
2237 These are two values, the first applies when first creating a time stamp.
2238 The second applies when changing it with the commands `S-up' and `S-down'.
2239 When changing the time stamp, this means that it will change in steps
2240 of N minutes, as given by the second value.
2242 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2243 numbers should be factors of 60, so for example 5, 10, 15.
2245 When this is larger than 1, you can still force an exact time-stamp by using
2246 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2247 and by using a prefix arg to `S-up/down' to specify the exact number
2248 of minutes to shift."
2249 :group 'org-time
2250 :get '(lambda (var) ; Make sure all entries have 5 elements
2251 (if (integerp (default-value var))
2252 (list (default-value var) 5)
2253 (default-value var)))
2254 :type '(list
2255 (integer :tag "when inserting times")
2256 (integer :tag "when modifying times")))
2258 ;; Normalize old customizations of this variable.
2259 (when (integerp org-time-stamp-rounding-minutes)
2260 (setq org-time-stamp-rounding-minutes
2261 (list org-time-stamp-rounding-minutes
2262 org-time-stamp-rounding-minutes)))
2264 (defcustom org-display-custom-times nil
2265 "Non-nil means, overlay custom formats over all time stamps.
2266 The formats are defined through the variable `org-time-stamp-custom-formats'.
2267 To turn this on on a per-file basis, insert anywhere in the file:
2268 #+STARTUP: customtime"
2269 :group 'org-time
2270 :set 'set-default
2271 :type 'sexp)
2272 (make-variable-buffer-local 'org-display-custom-times)
2274 (defcustom org-time-stamp-custom-formats
2275 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2276 "Custom formats for time stamps. See `format-time-string' for the syntax.
2277 These are overlayed over the default ISO format if the variable
2278 `org-display-custom-times' is set. Time like %H:%M should be at the
2279 end of the second format. The custom formats are also honored by export
2280 commands, if custom time display is turned on at the time of export."
2281 :group 'org-time
2282 :type 'sexp)
2284 (defun org-time-stamp-format (&optional long inactive)
2285 "Get the right format for a time string."
2286 (let ((f (if long (cdr org-time-stamp-formats)
2287 (car org-time-stamp-formats))))
2288 (if inactive
2289 (concat "[" (substring f 1 -1) "]")
2290 f)))
2292 (defcustom org-time-clocksum-format "%d:%02d"
2293 "The format string used when creating CLOCKSUM lines, or when
2294 org-mode generates a time duration."
2295 :group 'org-time
2296 :type 'string)
2298 (defcustom org-time-clocksum-use-fractional nil
2299 "If non-nil, \\[org-clock-display] uses fractional times.
2300 org-mode generates a time duration."
2301 :group 'org-time
2302 :type 'boolean)
2304 (defcustom org-time-clocksum-fractional-format "%.2f"
2305 "The format string used when creating CLOCKSUM lines, or when
2306 org-mode generates a time duration."
2307 :group 'org-time
2308 :type 'string)
2310 (defcustom org-deadline-warning-days 14
2311 "No. of days before expiration during which a deadline becomes active.
2312 This variable governs the display in sparse trees and in the agenda.
2313 When 0 or negative, it means use this number (the absolute value of it)
2314 even if a deadline has a different individual lead time specified.
2316 Custom commands can set this variable in the options section."
2317 :group 'org-time
2318 :group 'org-agenda-daily/weekly
2319 :type 'integer)
2321 (defcustom org-read-date-prefer-future t
2322 "Non-nil means, assume future for incomplete date input from user.
2323 This affects the following situations:
2324 1. The user gives a month but not a year.
2325 For example, if it is april and you enter \"feb 2\", this will be read
2326 as feb 2, *next* year. \"May 5\", however, will be this year.
2327 2. The user gives a day, but no month.
2328 For example, if today is the 15th, and you enter \"3\", Org-mode will
2329 read this as the third of *next* month. However, if you enter \"17\",
2330 it will be considered as *this* month.
2332 If you set this variable to the symbol `time', then also the following
2333 will work:
2335 3. If the user gives a time, but no day. If the time is before now,
2336 to will be interpreted as tomorrow.
2338 Currently none of this works for ISO week specifications.
2340 When this option is nil, the current day, month and year will always be
2341 used as defaults."
2342 :group 'org-time
2343 :type '(choice
2344 (const :tag "Never" nil)
2345 (const :tag "Check month and day" t)
2346 (const :tag "Check month, day, and time" time)))
2348 (defcustom org-read-date-display-live t
2349 "Non-nil means, display current interpretation of date prompt live.
2350 This display will be in an overlay, in the minibuffer."
2351 :group 'org-time
2352 :type 'boolean)
2354 (defcustom org-read-date-popup-calendar t
2355 "Non-nil means, pop up a calendar when prompting for a date.
2356 In the calendar, the date can be selected with mouse-1. However, the
2357 minibuffer will also be active, and you can simply enter the date as well.
2358 When nil, only the minibuffer will be available."
2359 :group 'org-time
2360 :type 'boolean)
2361 (if (fboundp 'defvaralias)
2362 (defvaralias 'org-popup-calendar-for-date-prompt
2363 'org-read-date-popup-calendar))
2365 (defcustom org-read-date-minibuffer-setup-hook nil
2366 "Hook to be used to set up keys for the date/time interface.
2367 Add key definitions to `minibuffer-local-map', which will be a temporary
2368 copy."
2369 :group 'org-time
2370 :type 'hook)
2372 (defcustom org-extend-today-until 0
2373 "The hour when your day really ends. Must be an integer.
2374 This has influence for the following applications:
2375 - When switching the agenda to \"today\". It it is still earlier than
2376 the time given here, the day recognized as TODAY is actually yesterday.
2377 - When a date is read from the user and it is still before the time given
2378 here, the current date and time will be assumed to be yesterday, 23:59.
2379 Also, timestamps inserted in remember templates follow this rule.
2381 IMPORTANT: This is a feature whose implementation is and likely will
2382 remain incomplete. Really, it is only here because past midnight seems to
2383 be the favorite working time of John Wiegley :-)"
2384 :group 'org-time
2385 :type 'integer)
2387 (defcustom org-edit-timestamp-down-means-later nil
2388 "Non-nil means, S-down will increase the time in a time stamp.
2389 When nil, S-up will increase."
2390 :group 'org-time
2391 :type 'boolean)
2393 (defcustom org-calendar-follow-timestamp-change t
2394 "Non-nil means, make the calendar window follow timestamp changes.
2395 When a timestamp is modified and the calendar window is visible, it will be
2396 moved to the new date."
2397 :group 'org-time
2398 :type 'boolean)
2400 (defgroup org-tags nil
2401 "Options concerning tags in Org-mode."
2402 :tag "Org Tags"
2403 :group 'org)
2405 (defcustom org-tag-alist nil
2406 "List of tags allowed in Org-mode files.
2407 When this list is nil, Org-mode will base TAG input on what is already in the
2408 buffer.
2409 The value of this variable is an alist, the car of each entry must be a
2410 keyword as a string, the cdr may be a character that is used to select
2411 that tag through the fast-tag-selection interface.
2412 See the manual for details."
2413 :group 'org-tags
2414 :type '(repeat
2415 (choice
2416 (cons (string :tag "Tag name")
2417 (character :tag "Access char"))
2418 (list :tag "Start radio group"
2419 (const :startgroup)
2420 (option (string :tag "Group description")))
2421 (list :tag "End radio group"
2422 (const :endgroup)
2423 (option (string :tag "Group description")))
2424 (const :tag "New line" (:newline)))))
2426 (defcustom org-tag-persistent-alist nil
2427 "List of tags that will always appear in all Org-mode files.
2428 This is in addition to any in buffer settings or customizations
2429 of `org-tag-alist'.
2430 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2431 The value of this variable is an alist, the car of each entry must be a
2432 keyword as a string, the cdr may be a character that is used to select
2433 that tag through the fast-tag-selection interface.
2434 See the manual for details.
2435 To disable these tags on a per-file basis, insert anywhere in the file:
2436 #+STARTUP: noptag"
2437 :group 'org-tags
2438 :type '(repeat
2439 (choice
2440 (cons (string :tag "Tag name")
2441 (character :tag "Access char"))
2442 (const :tag "Start radio group" (:startgroup))
2443 (const :tag "End radio group" (:endgroup))
2444 (const :tag "New line" (:newline)))))
2446 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2447 "If non-nil, always offer completion for all tags of all agenda files.
2448 Instead of customizing this variable directly, you might want to
2449 set it locally for remember buffers, because there no list of
2450 tags in that file can be created dynamically (there are none).
2452 (add-hook 'org-remember-mode-hook
2453 (lambda ()
2454 (set (make-local-variable
2455 'org-complete-tags-always-offer-all-agenda-tags)
2456 t)))"
2457 :group 'org-tags
2458 :type 'boolean)
2460 (defvar org-file-tags nil
2461 "List of tags that can be inherited by all entries in the file.
2462 The tags will be inherited if the variable `org-use-tag-inheritance'
2463 says they should be.
2464 This variable is populated from #+FILETAGS lines.")
2466 (defcustom org-use-fast-tag-selection 'auto
2467 "Non-nil means, use fast tag selection scheme.
2468 This is a special interface to select and deselect tags with single keys.
2469 When nil, fast selection is never used.
2470 When the symbol `auto', fast selection is used if and only if selection
2471 characters for tags have been configured, either through the variable
2472 `org-tag-alist' or through a #+TAGS line in the buffer.
2473 When t, fast selection is always used and selection keys are assigned
2474 automatically if necessary."
2475 :group 'org-tags
2476 :type '(choice
2477 (const :tag "Always" t)
2478 (const :tag "Never" nil)
2479 (const :tag "When selection characters are configured" 'auto)))
2481 (defcustom org-fast-tag-selection-single-key nil
2482 "Non-nil means, fast tag selection exits after first change.
2483 When nil, you have to press RET to exit it.
2484 During fast tag selection, you can toggle this flag with `C-c'.
2485 This variable can also have the value `expert'. In this case, the window
2486 displaying the tags menu is not even shown, until you press C-c again."
2487 :group 'org-tags
2488 :type '(choice
2489 (const :tag "No" nil)
2490 (const :tag "Yes" t)
2491 (const :tag "Expert" expert)))
2493 (defvar org-fast-tag-selection-include-todo nil
2494 "Non-nil means, fast tags selection interface will also offer TODO states.
2495 This is an undocumented feature, you should not rely on it.")
2497 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2498 "The column to which tags should be indented in a headline.
2499 If this number is positive, it specifies the column. If it is negative,
2500 it means that the tags should be flushright to that column. For example,
2501 -80 works well for a normal 80 character screen."
2502 :group 'org-tags
2503 :type 'integer)
2505 (defcustom org-auto-align-tags t
2506 "Non-nil means, realign tags after pro/demotion of TODO state change.
2507 These operations change the length of a headline and therefore shift
2508 the tags around. With this options turned on, after each such operation
2509 the tags are again aligned to `org-tags-column'."
2510 :group 'org-tags
2511 :type 'boolean)
2513 (defcustom org-use-tag-inheritance t
2514 "Non-nil means, tags in levels apply also for sublevels.
2515 When nil, only the tags directly given in a specific line apply there.
2516 This may also be a list of tags that should be inherited, or a regexp that
2517 matches tags that should be inherited. Additional control is possible
2518 with the variable `org-tags-exclude-from-inheritance' which gives an
2519 explicit list of tags to be excluded from inheritance., even if the value of
2520 `org-use-tag-inheritance' would select it for inheritance.
2522 If this option is t, a match early-on in a tree can lead to a large
2523 number of matches in the subtree when constructing the agenda or creating
2524 a sparse tree. If you only want to see the first match in a tree during
2525 a search, check out the variable `org-tags-match-list-sublevels'."
2526 :group 'org-tags
2527 :type '(choice
2528 (const :tag "Not" nil)
2529 (const :tag "Always" t)
2530 (repeat :tag "Specific tags" (string :tag "Tag"))
2531 (regexp :tag "Tags matched by regexp")))
2533 (defcustom org-tags-exclude-from-inheritance nil
2534 "List of tags that should never be inherited.
2535 This is a way to exclude a few tags from inheritance. For way to do
2536 the opposite, to actively allow inheritance for selected tags,
2537 see the variable `org-use-tag-inheritance'."
2538 :group 'org-tags
2539 :type '(repeat (string :tag "Tag")))
2541 (defun org-tag-inherit-p (tag)
2542 "Check if TAG is one that should be inherited."
2543 (cond
2544 ((member tag org-tags-exclude-from-inheritance) nil)
2545 ((eq org-use-tag-inheritance t) t)
2546 ((not org-use-tag-inheritance) nil)
2547 ((stringp org-use-tag-inheritance)
2548 (string-match org-use-tag-inheritance tag))
2549 ((listp org-use-tag-inheritance)
2550 (member tag org-use-tag-inheritance))
2551 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2553 (defcustom org-tags-match-list-sublevels t
2554 "Non-nil means list also sublevels of headlines matching a search.
2555 This variable applies to tags/property searches, and also to stuck
2556 projects because this search is based on a tags match as well.
2558 When set to the symbol `indented', sublevels are indented with
2559 leading dots.
2561 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2562 the sublevels of a headline matching a tag search often also match
2563 the same search. Listing all of them can create very long lists.
2564 Setting this variable to nil causes subtrees of a match to be skipped.
2566 This variable is semi-obsolete and probably should always be true. It
2567 is better to limit inheritance to certain tags using the variables
2568 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2569 :group 'org-tags
2570 :type '(choice
2571 (const :tag "No, don't list them" nil)
2572 (const :tag "Yes, do list them" t)
2573 (const :tag "List them, indented with leading dots" indented)))
2575 (defcustom org-tags-sort-function nil
2576 "When set, tags are sorted using this function as a comparator"
2577 :group 'org-tags
2578 :type '(choice
2579 (const :tag "No sorting" nil)
2580 (const :tag "Alphabetical" string<)
2581 (const :tag "Reverse alphabetical" string>)
2582 (function :tag "Custom function" nil)))
2584 (defvar org-tags-history nil
2585 "History of minibuffer reads for tags.")
2586 (defvar org-last-tags-completion-table nil
2587 "The last used completion table for tags.")
2588 (defvar org-after-tags-change-hook nil
2589 "Hook that is run after the tags in a line have changed.")
2591 (defgroup org-properties nil
2592 "Options concerning properties in Org-mode."
2593 :tag "Org Properties"
2594 :group 'org)
2596 (defcustom org-property-format "%-10s %s"
2597 "How property key/value pairs should be formatted by `indent-line'.
2598 When `indent-line' hits a property definition, it will format the line
2599 according to this format, mainly to make sure that the values are
2600 lined-up with respect to each other."
2601 :group 'org-properties
2602 :type 'string)
2604 (defcustom org-use-property-inheritance nil
2605 "Non-nil means, properties apply also for sublevels.
2607 This setting is chiefly used during property searches. Turning it on can
2608 cause significant overhead when doing a search, which is why it is not
2609 on by default.
2611 When nil, only the properties directly given in the current entry count.
2612 When t, every property is inherited. The value may also be a list of
2613 properties that should have inheritance, or a regular expression matching
2614 properties that should be inherited.
2616 However, note that some special properties use inheritance under special
2617 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2618 and the properties ending in \"_ALL\" when they are used as descriptor
2619 for valid values of a property.
2621 Note for programmers:
2622 When querying an entry with `org-entry-get', you can control if inheritance
2623 should be used. By default, `org-entry-get' looks only at the local
2624 properties. You can request inheritance by setting the inherit argument
2625 to t (to force inheritance) or to `selective' (to respect the setting
2626 in this variable)."
2627 :group 'org-properties
2628 :type '(choice
2629 (const :tag "Not" nil)
2630 (const :tag "Always" t)
2631 (repeat :tag "Specific properties" (string :tag "Property"))
2632 (regexp :tag "Properties matched by regexp")))
2634 (defun org-property-inherit-p (property)
2635 "Check if PROPERTY is one that should be inherited."
2636 (cond
2637 ((eq org-use-property-inheritance t) t)
2638 ((not org-use-property-inheritance) nil)
2639 ((stringp org-use-property-inheritance)
2640 (string-match org-use-property-inheritance property))
2641 ((listp org-use-property-inheritance)
2642 (member property org-use-property-inheritance))
2643 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2645 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2646 "The default column format, if no other format has been defined.
2647 This variable can be set on the per-file basis by inserting a line
2649 #+COLUMNS: %25ITEM ....."
2650 :group 'org-properties
2651 :type 'string)
2653 (defcustom org-columns-ellipses ".."
2654 "The ellipses to be used when a field in column view is truncated.
2655 When this is the empty string, as many characters as possible are shown,
2656 but then there will be no visual indication that the field has been truncated.
2657 When this is a string of length N, the last N characters of a truncated
2658 field are replaced by this string. If the column is narrower than the
2659 ellipses string, only part of the ellipses string will be shown."
2660 :group 'org-properties
2661 :type 'string)
2663 (defcustom org-columns-modify-value-for-display-function nil
2664 "Function that modifies values for display in column view.
2665 For example, it can be used to cut out a certain part from a time stamp.
2666 The function must take 2 arguments:
2668 column-title The title of the column (*not* the property name)
2669 value The value that should be modified.
2671 The function should return the value that should be displayed,
2672 or nil if the normal value should be used."
2673 :group 'org-properties
2674 :type 'function)
2676 (defcustom org-effort-property "Effort"
2677 "The property that is being used to keep track of effort estimates.
2678 Effort estimates given in this property need to have the format H:MM."
2679 :group 'org-properties
2680 :group 'org-progress
2681 :type '(string :tag "Property"))
2683 (defconst org-global-properties-fixed
2684 '(("VISIBILITY_ALL" . "folded children content all")
2685 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2686 "List of property/value pairs that can be inherited by any entry.
2688 These are fixed values, for the preset properties. The user variable
2689 that can be used to add to this list is `org-global-properties'.
2691 The entries in this list are cons cells where the car is a property
2692 name and cdr is a string with the value. If the value represents
2693 multiple items like an \"_ALL\" property, separate the items by
2694 spaces.")
2696 (defcustom org-global-properties nil
2697 "List of property/value pairs that can be inherited by any entry.
2699 This list will be combined with the constant `org-global-properties-fixed'.
2701 The entries in this list are cons cells where the car is a property
2702 name and cdr is a string with the value.
2704 You can set buffer-local values for the same purpose in the variable
2705 `org-file-properties' this by adding lines like
2707 #+PROPERTY: NAME VALUE"
2708 :group 'org-properties
2709 :type '(repeat
2710 (cons (string :tag "Property")
2711 (string :tag "Value"))))
2713 (defvar org-file-properties nil
2714 "List of property/value pairs that can be inherited by any entry.
2715 Valid for the current buffer.
2716 This variable is populated from #+PROPERTY lines.")
2717 (make-variable-buffer-local 'org-file-properties)
2719 (defgroup org-agenda nil
2720 "Options concerning agenda views in Org-mode."
2721 :tag "Org Agenda"
2722 :group 'org)
2724 (defvar org-category nil
2725 "Variable used by org files to set a category for agenda display.
2726 Such files should use a file variable to set it, for example
2728 # -*- mode: org; org-category: \"ELisp\"
2730 or contain a special line
2732 #+CATEGORY: ELisp
2734 If the file does not specify a category, then file's base name
2735 is used instead.")
2736 (make-variable-buffer-local 'org-category)
2737 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2739 (defcustom org-agenda-files nil
2740 "The files to be used for agenda display.
2741 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2742 \\[org-remove-file]. You can also use customize to edit the list.
2744 If an entry is a directory, all files in that directory that are matched by
2745 `org-agenda-file-regexp' will be part of the file list.
2747 If the value of the variable is not a list but a single file name, then
2748 the list of agenda files is actually stored and maintained in that file, one
2749 agenda file per line."
2750 :group 'org-agenda
2751 :type '(choice
2752 (repeat :tag "List of files and directories" file)
2753 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2755 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2756 "Regular expression to match files for `org-agenda-files'.
2757 If any element in the list in that variable contains a directory instead
2758 of a normal file, all files in that directory that are matched by this
2759 regular expression will be included."
2760 :group 'org-agenda
2761 :type 'regexp)
2763 (defcustom org-agenda-text-search-extra-files nil
2764 "List of extra files to be searched by text search commands.
2765 These files will be search in addition to the agenda files by the
2766 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2767 Note that these files will only be searched for text search commands,
2768 not for the other agenda views like todo lists, tag searches or the weekly
2769 agenda. This variable is intended to list notes and possibly archive files
2770 that should also be searched by these two commands.
2771 In fact, if the first element in the list is the symbol `agenda-archives',
2772 than all archive files of all agenda files will be added to the search
2773 scope."
2774 :group 'org-agenda
2775 :type '(set :greedy t
2776 (const :tag "Agenda Archives" agenda-archives)
2777 (repeat :inline t (file))))
2779 (if (fboundp 'defvaralias)
2780 (defvaralias 'org-agenda-multi-occur-extra-files
2781 'org-agenda-text-search-extra-files))
2783 (defcustom org-agenda-skip-unavailable-files nil
2784 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2785 A nil value means to remove them, after a query, from the list."
2786 :group 'org-agenda
2787 :type 'boolean)
2789 (defcustom org-calendar-to-agenda-key [?c]
2790 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2791 The command `org-calendar-goto-agenda' will be bound to this key. The
2792 default is the character `c' because then `c' can be used to switch back and
2793 forth between agenda and calendar."
2794 :group 'org-agenda
2795 :type 'sexp)
2797 (defcustom org-calendar-agenda-action-key [?k]
2798 "The key to be installed in `calendar-mode-map' for agenda-action.
2799 The command `org-agenda-action' will be bound to this key. The
2800 default is the character `k' because we use the same key in the agenda."
2801 :group 'org-agenda
2802 :type 'sexp)
2804 (defcustom org-calendar-insert-diary-entry-key [?i]
2805 "The key to be installed in `calendar-mode-map' for adding diary entries.
2806 This option is irrelevant until `org-agenda-diary-file' has been configured
2807 to point to an Org-mode file. When that is the case, the command
2808 `org-agenda-diary-entry' will be bound to the key given here, by default
2809 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2810 if you want to continue doing this, you need to change this to a different
2811 key."
2812 :group 'org-agenda
2813 :type 'sexp)
2815 (defcustom org-agenda-diary-file 'diary-file
2816 "File to which to add new entries with the `i' key in agenda and calendar.
2817 When this is the symbol `diary-file', the functionality in the Emacs
2818 calendar will be used to add entries to the `diary-file'. But when this
2819 points to a file, `org-agenda-diary-entry' will be used instead."
2820 :group 'org-agenda
2821 :type '(choice
2822 (const :tag "The standard Emacs diary file" diary-file)
2823 (file :tag "Special Org file diary entries")))
2825 (eval-after-load "calendar"
2826 '(progn
2827 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2828 'org-calendar-goto-agenda)
2829 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2830 'org-agenda-action)
2831 (add-hook 'calendar-mode-hook
2832 (lambda ()
2833 (unless (eq org-agenda-diary-file 'diary-file)
2834 (define-key calendar-mode-map
2835 org-calendar-insert-diary-entry-key
2836 'org-agenda-diary-entry))))))
2838 (defgroup org-latex nil
2839 "Options for embedding LaTeX code into Org-mode."
2840 :tag "Org LaTeX"
2841 :group 'org)
2843 (defcustom org-format-latex-options
2844 '(:foreground default :background default :scale 1.0
2845 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2846 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2847 "Options for creating images from LaTeX fragments.
2848 This is a property list with the following properties:
2849 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2850 `default' means use the foreground of the default face.
2851 :background the background color, or \"Transparent\".
2852 `default' means use the background of the default face.
2853 :scale a scaling factor for the size of the images.
2854 :html-foreground, :html-background, :html-scale
2855 the same numbers for HTML export.
2856 :matchers a list indicating which matchers should be used to
2857 find LaTeX fragments. Valid members of this list are:
2858 \"begin\" find environments
2859 \"$1\" find single characters surrounded by $.$
2860 \"$\" find math expressions surrounded by $...$
2861 \"$$\" find math expressions surrounded by $$....$$
2862 \"\\(\" find math expressions surrounded by \\(...\\)
2863 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2864 :group 'org-latex
2865 :type 'plist)
2867 (defcustom org-format-latex-header "\\documentclass{article}
2868 \\usepackage{amssymb}
2869 \\usepackage[usenames]{color}
2870 \\usepackage{amsmath}
2871 \\usepackage{latexsym}
2872 \\usepackage[mathscr]{eucal}
2873 \\pagestyle{empty} % do not remove
2874 % The settings below are copied from fullpage.sty
2875 \\setlength{\\textwidth}{\\paperwidth}
2876 \\addtolength{\\textwidth}{-3cm}
2877 \\setlength{\\oddsidemargin}{1.5cm}
2878 \\addtolength{\\oddsidemargin}{-2.54cm}
2879 \\setlength{\\evensidemargin}{\\oddsidemargin}
2880 \\setlength{\\textheight}{\\paperheight}
2881 \\addtolength{\\textheight}{-\\headheight}
2882 \\addtolength{\\textheight}{-\\headsep}
2883 \\addtolength{\\textheight}{-\\footskip}
2884 \\addtolength{\\textheight}{-3cm}
2885 \\setlength{\\topmargin}{1.5cm}
2886 \\addtolength{\\topmargin}{-2.54cm}"
2887 "The document header used for processing LaTeX fragments.
2888 It is imperative that this header make sure that no page number
2889 appears on the page."
2890 :group 'org-latex
2891 :type 'string)
2893 (defvar org-format-latex-header-extra nil)
2895 ;; The following variable is defined here because is it also used
2896 ;; when formatting latex fragments. Originally it was part of the
2897 ;; LaTeX exporter, which is why the name includes "export".
2898 (defcustom org-export-latex-packages-alist nil
2899 "Alist of packages to be inserted in the header.
2900 Each cell is of the format \( \"option\" . \"package\" \)."
2901 :group 'org-export-latex
2902 :type '(repeat
2903 (list
2904 (string :tag "option")
2905 (string :tag "package"))))
2907 (defgroup org-font-lock nil
2908 "Font-lock settings for highlighting in Org-mode."
2909 :tag "Org Font Lock"
2910 :group 'org)
2912 (defcustom org-level-color-stars-only nil
2913 "Non-nil means fontify only the stars in each headline.
2914 When nil, the entire headline is fontified.
2915 Changing it requires restart of `font-lock-mode' to become effective
2916 also in regions already fontified."
2917 :group 'org-font-lock
2918 :type 'boolean)
2920 (defcustom org-hide-leading-stars nil
2921 "Non-nil means, hide the first N-1 stars in a headline.
2922 This works by using the face `org-hide' for these stars. This
2923 face is white for a light background, and black for a dark
2924 background. You may have to customize the face `org-hide' to
2925 make this work.
2926 Changing it requires restart of `font-lock-mode' to become effective
2927 also in regions already fontified.
2928 You may also set this on a per-file basis by adding one of the following
2929 lines to the buffer:
2931 #+STARTUP: hidestars
2932 #+STARTUP: showstars"
2933 :group 'org-font-lock
2934 :type 'boolean)
2936 (defcustom org-fontify-done-headline nil
2937 "Non-nil means, change the face of a headline if it is marked DONE.
2938 Normally, only the TODO/DONE keyword indicates the state of a headline.
2939 When this is non-nil, the headline after the keyword is set to the
2940 `org-headline-done' as an additional indication."
2941 :group 'org-font-lock
2942 :type 'boolean)
2944 (defcustom org-fontify-emphasized-text t
2945 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2946 Changing this variable requires a restart of Emacs to take effect."
2947 :group 'org-font-lock
2948 :type 'boolean)
2950 (defcustom org-fontify-whole-heading-line nil
2951 "Non-nil means fontify the whole line for headings.
2952 This is useful when setting a background color for the
2953 org-level-* faces."
2954 :group 'org-font-lock
2955 :type 'boolean)
2957 (defcustom org-highlight-latex-fragments-and-specials nil
2958 "Non-nil means, fontify what is treated specially by the exporters."
2959 :group 'org-font-lock
2960 :type 'boolean)
2962 (defcustom org-hide-emphasis-markers nil
2963 "Non-nil mean font-lock should hide the emphasis marker characters."
2964 :group 'org-font-lock
2965 :type 'boolean)
2967 (defvar org-emph-re nil
2968 "Regular expression for matching emphasis.")
2969 (defvar org-verbatim-re nil
2970 "Regular expression for matching verbatim text.")
2971 (defvar org-emphasis-regexp-components) ; defined just below
2972 (defvar org-emphasis-alist) ; defined just below
2973 (defun org-set-emph-re (var val)
2974 "Set variable and compute the emphasis regular expression."
2975 (set var val)
2976 (when (and (boundp 'org-emphasis-alist)
2977 (boundp 'org-emphasis-regexp-components)
2978 org-emphasis-alist org-emphasis-regexp-components)
2979 (let* ((e org-emphasis-regexp-components)
2980 (pre (car e))
2981 (post (nth 1 e))
2982 (border (nth 2 e))
2983 (body (nth 3 e))
2984 (nl (nth 4 e))
2985 (body1 (concat body "*?"))
2986 (markers (mapconcat 'car org-emphasis-alist ""))
2987 (vmarkers (mapconcat
2988 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2989 org-emphasis-alist "")))
2990 ;; make sure special characters appear at the right position in the class
2991 (if (string-match "\\^" markers)
2992 (setq markers (concat (replace-match "" t t markers) "^")))
2993 (if (string-match "-" markers)
2994 (setq markers (concat (replace-match "" t t markers) "-")))
2995 (if (string-match "\\^" vmarkers)
2996 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2997 (if (string-match "-" vmarkers)
2998 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2999 (if (> nl 0)
3000 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3001 (int-to-string nl) "\\}")))
3002 ;; Make the regexp
3003 (setq org-emph-re
3004 (concat "\\([" pre "]\\|^\\)"
3005 "\\("
3006 "\\([" markers "]\\)"
3007 "\\("
3008 "[^" border "]\\|"
3009 "[^" border "]"
3010 body1
3011 "[^" border "]"
3012 "\\)"
3013 "\\3\\)"
3014 "\\([" post "]\\|$\\)"))
3015 (setq org-verbatim-re
3016 (concat "\\([" pre "]\\|^\\)"
3017 "\\("
3018 "\\([" vmarkers "]\\)"
3019 "\\("
3020 "[^" border "]\\|"
3021 "[^" border "]"
3022 body1
3023 "[^" border "]"
3024 "\\)"
3025 "\\3\\)"
3026 "\\([" post "]\\|$\\)")))))
3028 (defcustom org-emphasis-regexp-components
3029 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3030 "Components used to build the regular expression for emphasis.
3031 This is a list with 6 entries. Terminology: In an emphasis string
3032 like \" *strong word* \", we call the initial space PREMATCH, the final
3033 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3034 and \"trong wor\" is the body. The different components in this variable
3035 specify what is allowed/forbidden in each part:
3037 pre Chars allowed as prematch. Beginning of line will be allowed too.
3038 post Chars allowed as postmatch. End of line will be allowed too.
3039 border The chars *forbidden* as border characters.
3040 body-regexp A regexp like \".\" to match a body character. Don't use
3041 non-shy groups here, and don't allow newline here.
3042 newline The maximum number of newlines allowed in an emphasis exp.
3044 Use customize to modify this, or restart Emacs after changing it."
3045 :group 'org-font-lock
3046 :set 'org-set-emph-re
3047 :type '(list
3048 (sexp :tag "Allowed chars in pre ")
3049 (sexp :tag "Allowed chars in post ")
3050 (sexp :tag "Forbidden chars in border ")
3051 (sexp :tag "Regexp for body ")
3052 (integer :tag "number of newlines allowed")
3053 (option (boolean :tag "Please ignore this button"))))
3055 (defcustom org-emphasis-alist
3056 `(("*" bold "<b>" "</b>")
3057 ("/" italic "<i>" "</i>")
3058 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3059 ("=" org-code "<code>" "</code>" verbatim)
3060 ("~" org-verbatim "<code>" "</code>" verbatim)
3061 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3062 "<del>" "</del>")
3064 "Special syntax for emphasized text.
3065 Text starting and ending with a special character will be emphasized, for
3066 example *bold*, _underlined_ and /italic/. This variable sets the marker
3067 characters, the face to be used by font-lock for highlighting in Org-mode
3068 Emacs buffers, and the HTML tags to be used for this.
3069 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3070 Use customize to modify this, or restart Emacs after changing it."
3071 :group 'org-font-lock
3072 :set 'org-set-emph-re
3073 :type '(repeat
3074 (list
3075 (string :tag "Marker character")
3076 (choice
3077 (face :tag "Font-lock-face")
3078 (plist :tag "Face property list"))
3079 (string :tag "HTML start tag")
3080 (string :tag "HTML end tag")
3081 (option (const verbatim)))))
3083 (defvar org-protecting-blocks
3084 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3085 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3086 This is needed for font-lock setup.")
3088 ;;; Miscellaneous options
3090 (defgroup org-completion nil
3091 "Completion in Org-mode."
3092 :tag "Org Completion"
3093 :group 'org)
3095 (defcustom org-completion-use-ido nil
3096 "Non-nil means, use ido completion wherever possible.
3097 Note that `ido-mode' must be active for this variable to be relevant.
3098 If you decide to turn this variable on, you might well want to turn off
3099 `org-outline-path-complete-in-steps'.
3100 See also `org-completion-use-iswitchb'."
3101 :group 'org-completion
3102 :type 'boolean)
3104 (defcustom org-completion-use-iswitchb nil
3105 "Non-nil means, use iswitchb completion wherever possible.
3106 Note that `iswitchb-mode' must be active for this variable to be relevant.
3107 If you decide to turn this variable on, you might well want to turn off
3108 `org-outline-path-complete-in-steps'.
3109 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3110 :group 'org-completion
3111 :type 'boolean)
3113 (defcustom org-completion-fallback-command 'hippie-expand
3114 "The expansion command called by \\[org-complete] in normal context.
3115 Normal means, no org-mode-specific context."
3116 :group 'org-completion
3117 :type 'function)
3119 ;;; Functions and variables from their packages
3120 ;; Declared here to avoid compiler warnings
3122 ;; XEmacs only
3123 (defvar outline-mode-menu-heading)
3124 (defvar outline-mode-menu-show)
3125 (defvar outline-mode-menu-hide)
3126 (defvar zmacs-regions) ; XEmacs regions
3128 ;; Emacs only
3129 (defvar mark-active)
3131 ;; Various packages
3132 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3133 (declare-function calendar-forward-day "cal-move" (arg))
3134 (declare-function calendar-goto-date "cal-move" (date))
3135 (declare-function calendar-goto-today "cal-move" ())
3136 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3137 (defvar calc-embedded-close-formula)
3138 (defvar calc-embedded-open-formula)
3139 (declare-function cdlatex-tab "ext:cdlatex" ())
3140 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3141 (defvar font-lock-unfontify-region-function)
3142 (declare-function iswitchb-read-buffer "iswitchb"
3143 (prompt &optional default require-match start matches-set))
3144 (defvar iswitchb-temp-buflist)
3145 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3146 (defvar org-agenda-tags-todo-honor-ignore-options)
3147 (declare-function org-agenda-skip "org-agenda" ())
3148 (declare-function
3149 org-format-agenda-item "org-agenda"
3150 (extra txt &optional category tags dotime noprefix remove-re habitp))
3151 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3152 (declare-function org-agenda-change-all-lines "org-agenda"
3153 (newhead hdmarker &optional fixface just-this))
3154 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3155 (declare-function org-agenda-maybe-redo "org-agenda" ())
3156 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3157 (beg end))
3158 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3159 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3160 "org-agenda" (&optional end))
3161 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3162 (declare-function org-indent-mode "org-indent" (&optional arg))
3163 (declare-function parse-time-string "parse-time" (string))
3164 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3165 (defvar remember-data-file)
3166 (defvar texmathp-why)
3167 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3168 (declare-function table--at-cell-p "table" (position &optional object at-column))
3170 (defvar w3m-current-url)
3171 (defvar w3m-current-title)
3173 (defvar org-latex-regexps)
3175 ;;; Autoload and prepare some org modules
3177 ;; Some table stuff that needs to be defined here, because it is used
3178 ;; by the functions setting up org-mode or checking for table context.
3180 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3181 "Detects an org-type or table-type table.")
3182 (defconst org-table-line-regexp "^[ \t]*|"
3183 "Detects an org-type table line.")
3184 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3185 "Detects an org-type table line.")
3186 (defconst org-table-hline-regexp "^[ \t]*|-"
3187 "Detects an org-type table hline.")
3188 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3189 "Detects a table-type table hline.")
3190 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3191 "Searching from within a table (any type) this finds the first line
3192 outside the table.")
3194 ;; Autoload the functions in org-table.el that are needed by functions here.
3196 (eval-and-compile
3197 (org-autoload "org-table"
3198 '(org-table-align org-table-begin org-table-blank-field
3199 org-table-convert org-table-convert-region org-table-copy-down
3200 org-table-copy-region org-table-create
3201 org-table-create-or-convert-from-region
3202 org-table-create-with-table.el org-table-current-dline
3203 org-table-cut-region org-table-delete-column org-table-edit-field
3204 org-table-edit-formulas org-table-end org-table-eval-formula
3205 org-table-export org-table-field-info
3206 org-table-get-stored-formulas org-table-goto-column
3207 org-table-hline-and-move org-table-import org-table-insert-column
3208 org-table-insert-hline org-table-insert-row org-table-iterate
3209 org-table-justify-field-maybe org-table-kill-row
3210 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3211 org-table-move-column org-table-move-column-left
3212 org-table-move-column-right org-table-move-row
3213 org-table-move-row-down org-table-move-row-up
3214 org-table-next-field org-table-next-row org-table-paste-rectangle
3215 org-table-previous-field org-table-recalculate
3216 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3217 org-table-toggle-coordinate-overlays
3218 org-table-toggle-formula-debugger org-table-wrap-region
3219 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3221 (defun org-at-table-p (&optional table-type)
3222 "Return t if the cursor is inside an org-type table.
3223 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3224 (if org-enable-table-editor
3225 (save-excursion
3226 (beginning-of-line 1)
3227 (looking-at (if table-type org-table-any-line-regexp
3228 org-table-line-regexp)))
3229 nil))
3230 (defsubst org-table-p () (org-at-table-p))
3232 (defun org-at-table.el-p ()
3233 "Return t if and only if we are at a table.el table."
3234 (and (org-at-table-p 'any)
3235 (save-excursion
3236 (goto-char (org-table-begin 'any))
3237 (looking-at org-table1-hline-regexp))))
3238 (defun org-table-recognize-table.el ()
3239 "If there is a table.el table nearby, recognize it and move into it."
3240 (if org-table-tab-recognizes-table.el
3241 (if (org-at-table.el-p)
3242 (progn
3243 (beginning-of-line 1)
3244 (if (looking-at org-table-dataline-regexp)
3246 (if (looking-at org-table1-hline-regexp)
3247 (progn
3248 (beginning-of-line 2)
3249 (if (looking-at org-table-any-border-regexp)
3250 (beginning-of-line -1)))))
3251 (if (re-search-forward "|" (org-table-end t) t)
3252 (progn
3253 (require 'table)
3254 (if (table--at-cell-p (point))
3256 (message "recognizing table.el table...")
3257 (table-recognize-table)
3258 (message "recognizing table.el table...done")))
3259 (error "This should not happen..."))
3261 nil)
3262 nil))
3264 (defun org-at-table-hline-p ()
3265 "Return t if the cursor is inside a hline in a table."
3266 (if org-enable-table-editor
3267 (save-excursion
3268 (beginning-of-line 1)
3269 (looking-at org-table-hline-regexp))
3270 nil))
3272 (defvar org-table-clean-did-remove-column nil)
3274 (defun org-table-map-tables (function)
3275 "Apply FUNCTION to the start of all tables in the buffer."
3276 (save-excursion
3277 (save-restriction
3278 (widen)
3279 (goto-char (point-min))
3280 (while (re-search-forward org-table-any-line-regexp nil t)
3281 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3282 (beginning-of-line 1)
3283 (when (looking-at org-table-line-regexp)
3284 (save-excursion (funcall function))
3285 (or (looking-at org-table-line-regexp)
3286 (forward-char 1)))
3287 (re-search-forward org-table-any-border-regexp nil 1))))
3288 (message "Mapping tables: done"))
3290 ;; Declare and autoload functions from org-exp.el & Co
3292 (declare-function org-default-export-plist "org-exp")
3293 (declare-function org-infile-export-plist "org-exp")
3294 (declare-function org-get-current-options "org-exp")
3295 (eval-and-compile
3296 (org-autoload "org-exp"
3297 '(org-export org-export-visible
3298 org-insert-export-options-template
3299 org-table-clean-before-export))
3300 (org-autoload "org-ascii"
3301 '(org-export-as-ascii org-export-ascii-preprocess
3302 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3303 org-export-region-as-ascii))
3304 (org-autoload "org-latex"
3305 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3306 org-replace-region-by-latex org-export-region-as-latex
3307 org-export-as-latex org-export-as-pdf
3308 org-export-as-pdf-and-open))
3309 (org-autoload "org-html"
3310 '(org-export-as-html-and-open
3311 org-export-as-html-batch org-export-as-html-to-buffer
3312 org-replace-region-by-html org-export-region-as-html
3313 org-export-as-html))
3314 (org-autoload "org-docbook"
3315 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3316 org-replace-region-by-docbook org-export-region-as-docbook
3317 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3318 org-export-as-docbook))
3319 (org-autoload "org-icalendar"
3320 '(org-export-icalendar-this-file
3321 org-export-icalendar-all-agenda-files
3322 org-export-icalendar-combine-agenda-files))
3323 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3324 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3326 ;; Declare and autoload functions from org-agenda.el
3328 (eval-and-compile
3329 (org-autoload "org-agenda"
3330 '(org-agenda org-agenda-list org-search-view
3331 org-todo-list org-tags-view org-agenda-list-stuck-projects
3332 org-diary org-agenda-to-appt
3333 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3335 ;; Autoload org-remember
3337 (eval-and-compile
3338 (org-autoload "org-remember"
3339 '(org-remember-insinuate org-remember-annotation
3340 org-remember-apply-template org-remember org-remember-handler)))
3342 ;; Autoload org-clock.el
3345 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3346 (beg end))
3347 (declare-function org-clock-update-mode-line "org-clock" ())
3348 (declare-function org-resolve-clocks "org-clock"
3349 (&optional also-non-dangling-p prompt last-valid))
3350 (defvar org-clock-start-time)
3351 (defvar org-clock-marker (make-marker)
3352 "Marker recording the last clock-in.")
3353 (defvar org-clock-hd-marker (make-marker)
3354 "Marker recording the last clock-in, but the headline position.")
3355 (defvar org-clock-heading ""
3356 "The heading of the current clock entry.")
3357 (defun org-clock-is-active ()
3358 "Return non-nil if clock is currently running.
3359 The return value is actually the clock marker."
3360 (marker-buffer org-clock-marker))
3362 (eval-and-compile
3363 (org-autoload
3364 "org-clock"
3365 '(org-clock-in org-clock-out org-clock-cancel
3366 org-clock-goto org-clock-sum org-clock-display
3367 org-clock-remove-overlays org-clock-report
3368 org-clocktable-shift org-dblock-write:clocktable
3369 org-get-clocktable org-resolve-clocks)))
3371 (defun org-clock-update-time-maybe ()
3372 "If this is a CLOCK line, update it and return t.
3373 Otherwise, return nil."
3374 (interactive)
3375 (save-excursion
3376 (beginning-of-line 1)
3377 (skip-chars-forward " \t")
3378 (when (looking-at org-clock-string)
3379 (let ((re (concat "[ \t]*" org-clock-string
3380 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3381 "\\([ \t]*=>.*\\)?\\)?"))
3382 ts te h m s neg)
3383 (cond
3384 ((not (looking-at re))
3385 nil)
3386 ((not (match-end 2))
3387 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3388 (> org-clock-marker (point))
3389 (<= org-clock-marker (point-at-eol)))
3390 ;; The clock is running here
3391 (setq org-clock-start-time
3392 (apply 'encode-time
3393 (org-parse-time-string (match-string 1))))
3394 (org-clock-update-mode-line)))
3396 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3397 (end-of-line 1)
3398 (setq ts (match-string 1)
3399 te (match-string 3))
3400 (setq s (- (org-float-time
3401 (apply 'encode-time (org-parse-time-string te)))
3402 (org-float-time
3403 (apply 'encode-time (org-parse-time-string ts))))
3404 neg (< s 0)
3405 s (abs s)
3406 h (floor (/ s 3600))
3407 s (- s (* 3600 h))
3408 m (floor (/ s 60))
3409 s (- s (* 60 s)))
3410 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3411 t))))))
3413 (defun org-check-running-clock ()
3414 "Check if the current buffer contains the running clock.
3415 If yes, offer to stop it and to save the buffer with the changes."
3416 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3417 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3418 (buffer-name))))
3419 (org-clock-out)
3420 (when (y-or-n-p "Save changed buffer?")
3421 (save-buffer))))
3423 (defun org-clocktable-try-shift (dir n)
3424 "Check if this line starts a clock table, if yes, shift the time block."
3425 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3426 (org-clocktable-shift dir n)))
3428 ;; Autoload org-timer.el
3430 (eval-and-compile
3431 (org-autoload
3432 "org-timer"
3433 '(org-timer-start org-timer org-timer-item
3434 org-timer-change-times-in-region
3435 org-timer-set-timer
3436 org-timer-reset-timers
3437 org-timer-show-remaining-time)))
3439 ;; Autoload org-feed.el
3441 (eval-and-compile
3442 (org-autoload
3443 "org-feed"
3444 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3447 ;; Autoload org-indent.el
3449 ;; Define the variable already here, to make sure we have it.
3450 (defvar org-indent-mode nil
3451 "Non-nil if Org-Indent mode is enabled.
3452 Use the command `org-indent-mode' to change this variable.")
3454 (eval-and-compile
3455 (org-autoload
3456 "org-indent"
3457 '(org-indent-mode)))
3459 ;; Autoload org-mobile.el
3461 (eval-and-compile
3462 (org-autoload
3463 "org-mobile"
3464 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3466 ;; Autoload archiving code
3467 ;; The stuff that is needed for cycling and tags has to be defined here.
3469 (defgroup org-archive nil
3470 "Options concerning archiving in Org-mode."
3471 :tag "Org Archive"
3472 :group 'org-structure)
3474 (defcustom org-archive-location "%s_archive::"
3475 "The location where subtrees should be archived.
3477 The value of this variable is a string, consisting of two parts,
3478 separated by a double-colon. The first part is a filename and
3479 the second part is a headline.
3481 When the filename is omitted, archiving happens in the same file.
3482 %s in the filename will be replaced by the current file
3483 name (without the directory part). Archiving to a different file
3484 is useful to keep archived entries from contributing to the
3485 Org-mode Agenda.
3487 The archived entries will be filed as subtrees of the specified
3488 headline. When the headline is omitted, the subtrees are simply
3489 filed away at the end of the file, as top-level entries. Also in
3490 the heading you can use %s to represent the file name, this can be
3491 useful when using the same archive for a number of different files.
3493 Here are a few examples:
3494 \"%s_archive::\"
3495 If the current file is Projects.org, archive in file
3496 Projects.org_archive, as top-level trees. This is the default.
3498 \"::* Archived Tasks\"
3499 Archive in the current file, under the top-level headline
3500 \"* Archived Tasks\".
3502 \"~/org/archive.org::\"
3503 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3505 \"~/org/archive.org::From %s\"
3506 Archive in file ~/org/archive.org (absolute path), under headlines
3507 \"From FILENAME\" where file name is the current file name.
3509 \"basement::** Finished Tasks\"
3510 Archive in file ./basement (relative path), as level 3 trees
3511 below the level 2 heading \"** Finished Tasks\".
3513 You may set this option on a per-file basis by adding to the buffer a
3514 line like
3516 #+ARCHIVE: basement::** Finished Tasks
3518 You may also define it locally for a subtree by setting an ARCHIVE property
3519 in the entry. If such a property is found in an entry, or anywhere up
3520 the hierarchy, it will be used."
3521 :group 'org-archive
3522 :type 'string)
3524 (defcustom org-archive-tag "ARCHIVE"
3525 "The tag that marks a subtree as archived.
3526 An archived subtree does not open during visibility cycling, and does
3527 not contribute to the agenda listings.
3528 After changing this, font-lock must be restarted in the relevant buffers to
3529 get the proper fontification."
3530 :group 'org-archive
3531 :group 'org-keywords
3532 :type 'string)
3534 (defcustom org-agenda-skip-archived-trees t
3535 "Non-nil means, the agenda will skip any items located in archived trees.
3536 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3537 variable is no longer recommended, you should leave it at the value t.
3538 Instead, use the key `v' to cycle the archives-mode in the agenda."
3539 :group 'org-archive
3540 :group 'org-agenda-skip
3541 :type 'boolean)
3543 (defcustom org-columns-skip-archived-trees t
3544 "Non-nil means, ignore archived trees when creating column view."
3545 :group 'org-archive
3546 :group 'org-properties
3547 :type 'boolean)
3549 (defcustom org-cycle-open-archived-trees nil
3550 "Non-nil means, `org-cycle' will open archived trees.
3551 An archived tree is a tree marked with the tag ARCHIVE.
3552 When nil, archived trees will stay folded. You can still open them with
3553 normal outline commands like `show-all', but not with the cycling commands."
3554 :group 'org-archive
3555 :group 'org-cycle
3556 :type 'boolean)
3558 (defcustom org-sparse-tree-open-archived-trees nil
3559 "Non-nil means sparse tree construction shows matches in archived trees.
3560 When nil, matches in these trees are highlighted, but the trees are kept in
3561 collapsed state."
3562 :group 'org-archive
3563 :group 'org-sparse-trees
3564 :type 'boolean)
3566 (defun org-cycle-hide-archived-subtrees (state)
3567 "Re-hide all archived subtrees after a visibility state change."
3568 (when (and (not org-cycle-open-archived-trees)
3569 (not (memq state '(overview folded))))
3570 (save-excursion
3571 (let* ((globalp (memq state '(contents all)))
3572 (beg (if globalp (point-min) (point)))
3573 (end (if globalp (point-max) (org-end-of-subtree t))))
3574 (org-hide-archived-subtrees beg end)
3575 (goto-char beg)
3576 (if (looking-at (concat ".*:" org-archive-tag ":"))
3577 (message "%s" (substitute-command-keys
3578 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3580 (defun org-force-cycle-archived ()
3581 "Cycle subtree even if it is archived."
3582 (interactive)
3583 (setq this-command 'org-cycle)
3584 (let ((org-cycle-open-archived-trees t))
3585 (call-interactively 'org-cycle)))
3587 (defun org-hide-archived-subtrees (beg end)
3588 "Re-hide all archived subtrees after a visibility state change."
3589 (save-excursion
3590 (let* ((re (concat ":" org-archive-tag ":")))
3591 (goto-char beg)
3592 (while (re-search-forward re end t)
3593 (and (org-on-heading-p) (org-flag-subtree t))
3594 (org-end-of-subtree t)))))
3596 (defun org-flag-subtree (flag)
3597 (save-excursion
3598 (org-back-to-heading t)
3599 (outline-end-of-heading)
3600 (outline-flag-region (point)
3601 (progn (org-end-of-subtree t) (point))
3602 flag)))
3604 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3606 (eval-and-compile
3607 (org-autoload "org-archive"
3608 '(org-add-archive-files org-archive-subtree
3609 org-archive-to-archive-sibling org-toggle-archive-tag
3610 org-archive-subtree-default
3611 org-archive-subtree-default-with-confirmation)))
3613 ;; Autoload Column View Code
3615 (declare-function org-columns-number-to-string "org-colview")
3616 (declare-function org-columns-get-format-and-top-level "org-colview")
3617 (declare-function org-columns-compute "org-colview")
3619 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3620 '(org-columns-number-to-string org-columns-get-format-and-top-level
3621 org-columns-compute org-agenda-columns org-columns-remove-overlays
3622 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3624 ;; Autoload ID code
3626 (declare-function org-id-store-link "org-id")
3627 (declare-function org-id-locations-load "org-id")
3628 (declare-function org-id-locations-save "org-id")
3629 (defvar org-id-track-globally)
3630 (org-autoload "org-id"
3631 '(org-id-get-create org-id-new org-id-copy org-id-get
3632 org-id-get-with-outline-path-completion
3633 org-id-get-with-outline-drilling
3634 org-id-goto org-id-find org-id-store-link))
3636 ;; Autoload Plotting Code
3638 (org-autoload "org-plot"
3639 '(org-plot/gnuplot))
3641 ;;; Variables for pre-computed regular expressions, all buffer local
3643 (defvar org-drawer-regexp nil
3644 "Matches first line of a hidden block.")
3645 (make-variable-buffer-local 'org-drawer-regexp)
3646 (defvar org-todo-regexp nil
3647 "Matches any of the TODO state keywords.")
3648 (make-variable-buffer-local 'org-todo-regexp)
3649 (defvar org-not-done-regexp nil
3650 "Matches any of the TODO state keywords except the last one.")
3651 (make-variable-buffer-local 'org-not-done-regexp)
3652 (defvar org-not-done-heading-regexp nil
3653 "Matches a TODO headline that is not done.")
3654 (make-variable-buffer-local 'org-not-done-regexp)
3655 (defvar org-todo-line-regexp nil
3656 "Matches a headline and puts TODO state into group 2 if present.")
3657 (make-variable-buffer-local 'org-todo-line-regexp)
3658 (defvar org-complex-heading-regexp nil
3659 "Matches a headline and puts everything into groups:
3660 group 1: the stars
3661 group 2: The todo keyword, maybe
3662 group 3: Priority cookie
3663 group 4: True headline
3664 group 5: Tags")
3665 (make-variable-buffer-local 'org-complex-heading-regexp)
3666 (defvar org-complex-heading-regexp-format nil)
3667 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3668 (defvar org-todo-line-tags-regexp nil
3669 "Matches a headline and puts TODO state into group 2 if present.
3670 Also put tags into group 4 if tags are present.")
3671 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3672 (defvar org-nl-done-regexp nil
3673 "Matches newline followed by a headline with the DONE keyword.")
3674 (make-variable-buffer-local 'org-nl-done-regexp)
3675 (defvar org-looking-at-done-regexp nil
3676 "Matches the DONE keyword a point.")
3677 (make-variable-buffer-local 'org-looking-at-done-regexp)
3678 (defvar org-ds-keyword-length 12
3679 "Maximum length of the Deadline and SCHEDULED keywords.")
3680 (make-variable-buffer-local 'org-ds-keyword-length)
3681 (defvar org-deadline-regexp nil
3682 "Matches the DEADLINE keyword.")
3683 (make-variable-buffer-local 'org-deadline-regexp)
3684 (defvar org-deadline-time-regexp nil
3685 "Matches the DEADLINE keyword together with a time stamp.")
3686 (make-variable-buffer-local 'org-deadline-time-regexp)
3687 (defvar org-deadline-line-regexp nil
3688 "Matches the DEADLINE keyword and the rest of the line.")
3689 (make-variable-buffer-local 'org-deadline-line-regexp)
3690 (defvar org-scheduled-regexp nil
3691 "Matches the SCHEDULED keyword.")
3692 (make-variable-buffer-local 'org-scheduled-regexp)
3693 (defvar org-scheduled-time-regexp nil
3694 "Matches the SCHEDULED keyword together with a time stamp.")
3695 (make-variable-buffer-local 'org-scheduled-time-regexp)
3696 (defvar org-closed-time-regexp nil
3697 "Matches the CLOSED keyword together with a time stamp.")
3698 (make-variable-buffer-local 'org-closed-time-regexp)
3700 (defvar org-keyword-time-regexp nil
3701 "Matches any of the 4 keywords, together with the time stamp.")
3702 (make-variable-buffer-local 'org-keyword-time-regexp)
3703 (defvar org-keyword-time-not-clock-regexp nil
3704 "Matches any of the 3 keywords, together with the time stamp.")
3705 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3706 (defvar org-maybe-keyword-time-regexp nil
3707 "Matches a timestamp, possibly preceeded by a keyword.")
3708 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3709 (defvar org-planning-or-clock-line-re nil
3710 "Matches a line with planning or clock info.")
3711 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3712 (defvar org-all-time-keywords nil
3713 "List of time keywords.")
3714 (make-variable-buffer-local 'org-all-time-keywords)
3716 (defconst org-plain-time-of-day-regexp
3717 (concat
3718 "\\(\\<[012]?[0-9]"
3719 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3720 "\\(--?"
3721 "\\(\\<[012]?[0-9]"
3722 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3723 "\\)?")
3724 "Regular expression to match a plain time or time range.
3725 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3726 groups carry important information:
3727 0 the full match
3728 1 the first time, range or not
3729 8 the second time, if it is a range.")
3731 (defconst org-plain-time-extension-regexp
3732 (concat
3733 "\\(\\<[012]?[0-9]"
3734 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3735 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3736 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3737 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3738 groups carry important information:
3739 0 the full match
3740 7 hours of duration
3741 9 minutes of duration")
3743 (defconst org-stamp-time-of-day-regexp
3744 (concat
3745 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3746 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3747 "\\(--?"
3748 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3749 "Regular expression to match a timestamp time or time range.
3750 After a match, the following groups carry important information:
3751 0 the full match
3752 1 date plus weekday, for back referencing to make sure both times are on the same day
3753 2 the first time, range or not
3754 4 the second time, if it is a range.")
3756 (defconst org-startup-options
3757 '(("fold" org-startup-folded t)
3758 ("overview" org-startup-folded t)
3759 ("nofold" org-startup-folded nil)
3760 ("showall" org-startup-folded nil)
3761 ("showeverything" org-startup-folded showeverything)
3762 ("content" org-startup-folded content)
3763 ("indent" org-startup-indented t)
3764 ("noindent" org-startup-indented nil)
3765 ("hidestars" org-hide-leading-stars t)
3766 ("showstars" org-hide-leading-stars nil)
3767 ("odd" org-odd-levels-only t)
3768 ("oddeven" org-odd-levels-only nil)
3769 ("align" org-startup-align-all-tables t)
3770 ("noalign" org-startup-align-all-tables nil)
3771 ("customtime" org-display-custom-times t)
3772 ("logdone" org-log-done time)
3773 ("lognotedone" org-log-done note)
3774 ("nologdone" org-log-done nil)
3775 ("lognoteclock-out" org-log-note-clock-out t)
3776 ("nolognoteclock-out" org-log-note-clock-out nil)
3777 ("logrepeat" org-log-repeat state)
3778 ("lognoterepeat" org-log-repeat note)
3779 ("nologrepeat" org-log-repeat nil)
3780 ("logreschedule" org-log-reschedule time)
3781 ("lognotereschedule" org-log-reschedule note)
3782 ("nologreschedule" org-log-reschedule nil)
3783 ("logredeadline" org-log-redeadline time)
3784 ("lognoteredeadline" org-log-redeadline note)
3785 ("nologredeadline" org-log-redeadline nil)
3786 ("fninline" org-footnote-define-inline t)
3787 ("nofninline" org-footnote-define-inline nil)
3788 ("fnlocal" org-footnote-section nil)
3789 ("fnauto" org-footnote-auto-label t)
3790 ("fnprompt" org-footnote-auto-label nil)
3791 ("fnconfirm" org-footnote-auto-label confirm)
3792 ("fnplain" org-footnote-auto-label plain)
3793 ("fnadjust" org-footnote-auto-adjust t)
3794 ("nofnadjust" org-footnote-auto-adjust nil)
3795 ("constcgs" constants-unit-system cgs)
3796 ("constSI" constants-unit-system SI)
3797 ("noptag" org-tag-persistent-alist nil)
3798 ("hideblocks" org-hide-block-startup t)
3799 ("nohideblocks" org-hide-block-startup nil)
3800 ("beamer" org-startup-with-beamer-mode t))
3801 "Variable associated with STARTUP options for org-mode.
3802 Each element is a list of three items: The startup options as written
3803 in the #+STARTUP line, the corresponding variable, and the value to
3804 set this variable to if the option is found. An optional forth element PUSH
3805 means to push this value onto the list in the variable.")
3807 (defun org-set-regexps-and-options ()
3808 "Precompute regular expressions for current buffer."
3809 (when (org-mode-p)
3810 (org-set-local 'org-todo-kwd-alist nil)
3811 (org-set-local 'org-todo-key-alist nil)
3812 (org-set-local 'org-todo-key-trigger nil)
3813 (org-set-local 'org-todo-keywords-1 nil)
3814 (org-set-local 'org-done-keywords nil)
3815 (org-set-local 'org-todo-heads nil)
3816 (org-set-local 'org-todo-sets nil)
3817 (org-set-local 'org-todo-log-states nil)
3818 (org-set-local 'org-file-properties nil)
3819 (org-set-local 'org-file-tags nil)
3820 (let ((re (org-make-options-regexp
3821 '("CATEGORY" "TODO" "COLUMNS"
3822 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3823 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3824 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3825 (splitre "[ \t]+")
3826 kwds kws0 kwsa key log value cat arch tags const links hw dws
3827 tail sep kws1 prio props ftags drawers beamer-p
3828 ext-setup-or-nil setup-contents (start 0))
3829 (save-excursion
3830 (save-restriction
3831 (widen)
3832 (goto-char (point-min))
3833 (while (or (and ext-setup-or-nil
3834 (string-match re ext-setup-or-nil start)
3835 (setq start (match-end 0)))
3836 (and (setq ext-setup-or-nil nil start 0)
3837 (re-search-forward re nil t)))
3838 (setq key (upcase (match-string 1 ext-setup-or-nil))
3839 value (org-match-string-no-properties 2 ext-setup-or-nil))
3840 (cond
3841 ((equal key "CATEGORY")
3842 (if (string-match "[ \t]+$" value)
3843 (setq value (replace-match "" t t value)))
3844 (setq cat value))
3845 ((member key '("SEQ_TODO" "TODO"))
3846 (push (cons 'sequence (org-split-string value splitre)) kwds))
3847 ((equal key "TYP_TODO")
3848 (push (cons 'type (org-split-string value splitre)) kwds))
3849 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3850 ;; general TODO-like setup
3851 (push (cons (intern (downcase (match-string 1 key)))
3852 (org-split-string value splitre)) kwds))
3853 ((equal key "TAGS")
3854 (setq tags (append tags (if tags '("\\n") nil)
3855 (org-split-string value splitre))))
3856 ((equal key "COLUMNS")
3857 (org-set-local 'org-columns-default-format value))
3858 ((equal key "LINK")
3859 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3860 (push (cons (match-string 1 value)
3861 (org-trim (match-string 2 value)))
3862 links)))
3863 ((equal key "PRIORITIES")
3864 (setq prio (org-split-string value " +")))
3865 ((equal key "PROPERTY")
3866 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3867 (push (cons (match-string 1 value) (match-string 2 value))
3868 props)))
3869 ((equal key "FILETAGS")
3870 (when (string-match "\\S-" value)
3871 (setq ftags
3872 (append
3873 ftags
3874 (apply 'append
3875 (mapcar (lambda (x) (org-split-string x ":"))
3876 (org-split-string value)))))))
3877 ((equal key "DRAWERS")
3878 (setq drawers (org-split-string value splitre)))
3879 ((equal key "CONSTANTS")
3880 (setq const (append const (org-split-string value splitre))))
3881 ((equal key "STARTUP")
3882 (let ((opts (org-split-string value splitre))
3883 l var val)
3884 (while (setq l (pop opts))
3885 (when (setq l (assoc l org-startup-options))
3886 (setq var (nth 1 l) val (nth 2 l))
3887 (if (not (nth 3 l))
3888 (set (make-local-variable var) val)
3889 (if (not (listp (symbol-value var)))
3890 (set (make-local-variable var) nil))
3891 (set (make-local-variable var) (symbol-value var))
3892 (add-to-list var val))))))
3893 ((equal key "ARCHIVE")
3894 (string-match " *$" value)
3895 (setq arch (replace-match "" t t value))
3896 (remove-text-properties 0 (length arch)
3897 '(face t fontified t) arch))
3898 ((equal key "LATEX_CLASS")
3899 (setq beamer-p (equal value "beamer")))
3900 ((equal key "SETUPFILE")
3901 (setq setup-contents (org-file-contents
3902 (expand-file-name
3903 (org-remove-double-quotes value))
3904 'noerror))
3905 (if (not ext-setup-or-nil)
3906 (setq ext-setup-or-nil setup-contents start 0)
3907 (setq ext-setup-or-nil
3908 (concat (substring ext-setup-or-nil 0 start)
3909 "\n" setup-contents "\n"
3910 (substring ext-setup-or-nil start)))))
3911 ))))
3912 (when cat
3913 (org-set-local 'org-category (intern cat))
3914 (push (cons "CATEGORY" cat) props))
3915 (when prio
3916 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3917 (setq prio (mapcar 'string-to-char prio))
3918 (org-set-local 'org-highest-priority (nth 0 prio))
3919 (org-set-local 'org-lowest-priority (nth 1 prio))
3920 (org-set-local 'org-default-priority (nth 2 prio)))
3921 (and props (org-set-local 'org-file-properties (nreverse props)))
3922 (and ftags (org-set-local 'org-file-tags
3923 (mapcar 'org-add-prop-inherited ftags)))
3924 (and drawers (org-set-local 'org-drawers drawers))
3925 (and arch (org-set-local 'org-archive-location arch))
3926 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3927 ;; Process the TODO keywords
3928 (unless kwds
3929 ;; Use the global values as if they had been given locally.
3930 (setq kwds (default-value 'org-todo-keywords))
3931 (if (stringp (car kwds))
3932 (setq kwds (list (cons org-todo-interpretation
3933 (default-value 'org-todo-keywords)))))
3934 (setq kwds (reverse kwds)))
3935 (setq kwds (nreverse kwds))
3936 (let (inter kws kw)
3937 (while (setq kws (pop kwds))
3938 (let ((kws (or
3939 (run-hook-with-args-until-success
3940 'org-todo-setup-filter-hook kws)
3941 kws)))
3942 (setq inter (pop kws) sep (member "|" kws)
3943 kws0 (delete "|" (copy-sequence kws))
3944 kwsa nil
3945 kws1 (mapcar
3946 (lambda (x)
3947 ;; 1 2
3948 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3949 (progn
3950 (setq kw (match-string 1 x)
3951 key (and (match-end 2) (match-string 2 x))
3952 log (org-extract-log-state-settings x))
3953 (push (cons kw (and key (string-to-char key))) kwsa)
3954 (and log (push log org-todo-log-states))
3956 (error "Invalid TODO keyword %s" x)))
3957 kws0)
3958 kwsa (if kwsa (append '((:startgroup))
3959 (nreverse kwsa)
3960 '((:endgroup))))
3961 hw (car kws1)
3962 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3963 tail (list inter hw (car dws) (org-last dws))))
3964 (add-to-list 'org-todo-heads hw 'append)
3965 (push kws1 org-todo-sets)
3966 (setq org-done-keywords (append org-done-keywords dws nil))
3967 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3968 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3969 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3970 (setq org-todo-sets (nreverse org-todo-sets)
3971 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3972 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3973 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3974 ;; Process the constants
3975 (when const
3976 (let (e cst)
3977 (while (setq e (pop const))
3978 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3979 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3980 (setq org-table-formula-constants-local cst)))
3982 ;; Process the tags.
3983 (when tags
3984 (let (e tgs)
3985 (while (setq e (pop tags))
3986 (cond
3987 ((equal e "{") (push '(:startgroup) tgs))
3988 ((equal e "}") (push '(:endgroup) tgs))
3989 ((equal e "\\n") (push '(:newline) tgs))
3990 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3991 (push (cons (match-string 1 e)
3992 (string-to-char (match-string 2 e)))
3993 tgs))
3994 (t (push (list e) tgs))))
3995 (org-set-local 'org-tag-alist nil)
3996 (while (setq e (pop tgs))
3997 (or (and (stringp (car e))
3998 (assoc (car e) org-tag-alist))
3999 (push e org-tag-alist)))))
4001 ;; Compute the regular expressions and other local variables
4002 (if (not org-done-keywords)
4003 (setq org-done-keywords (and org-todo-keywords-1
4004 (list (org-last org-todo-keywords-1)))))
4005 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4006 (length org-scheduled-string)
4007 (length org-clock-string)
4008 (length org-closed-string)))
4009 org-drawer-regexp
4010 (concat "^[ \t]*:\\("
4011 (mapconcat 'regexp-quote org-drawers "\\|")
4012 "\\):[ \t]*$")
4013 org-not-done-keywords
4014 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4015 org-todo-regexp
4016 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4017 "\\|") "\\)\\>")
4018 org-not-done-regexp
4019 (concat "\\<\\("
4020 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4021 "\\)\\>")
4022 org-not-done-heading-regexp
4023 (concat "^\\(\\*+\\)[ \t]+\\("
4024 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4025 "\\)\\>")
4026 org-todo-line-regexp
4027 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4028 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4029 "\\)\\>\\)?[ \t]*\\(.*\\)")
4030 org-complex-heading-regexp
4031 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4032 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4033 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4034 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4035 org-complex-heading-regexp-format
4036 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4037 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4038 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4039 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4040 org-nl-done-regexp
4041 (concat "\n\\*+[ \t]+"
4042 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4043 "\\)" "\\>")
4044 org-todo-line-tags-regexp
4045 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4046 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4047 (org-re
4048 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4049 org-looking-at-done-regexp
4050 (concat "^" "\\(?:"
4051 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4052 "\\>")
4053 org-deadline-regexp (concat "\\<" org-deadline-string)
4054 org-deadline-time-regexp
4055 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4056 org-deadline-line-regexp
4057 (concat "\\<\\(" org-deadline-string "\\).*")
4058 org-scheduled-regexp
4059 (concat "\\<" org-scheduled-string)
4060 org-scheduled-time-regexp
4061 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4062 org-closed-time-regexp
4063 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4064 org-keyword-time-regexp
4065 (concat "\\<\\(" org-scheduled-string
4066 "\\|" org-deadline-string
4067 "\\|" org-closed-string
4068 "\\|" org-clock-string "\\)"
4069 " *[[<]\\([^]>]+\\)[]>]")
4070 org-keyword-time-not-clock-regexp
4071 (concat "\\<\\(" org-scheduled-string
4072 "\\|" org-deadline-string
4073 "\\|" org-closed-string
4074 "\\)"
4075 " *[[<]\\([^]>]+\\)[]>]")
4076 org-maybe-keyword-time-regexp
4077 (concat "\\(\\<\\(" org-scheduled-string
4078 "\\|" org-deadline-string
4079 "\\|" org-closed-string
4080 "\\|" org-clock-string "\\)\\)?"
4081 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4082 org-planning-or-clock-line-re
4083 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4084 "\\|" org-deadline-string
4085 "\\|" org-closed-string "\\|" org-clock-string
4086 "\\)\\>\\)")
4087 org-all-time-keywords
4088 (mapcar (lambda (w) (substring w 0 -1))
4089 (list org-scheduled-string org-deadline-string
4090 org-clock-string org-closed-string))
4092 (org-compute-latex-and-specials-regexp)
4093 (org-set-font-lock-defaults))))
4095 (defun org-file-contents (file &optional noerror)
4096 "Return the contents of FILE, as a string."
4097 (if (or (not file)
4098 (not (file-readable-p file)))
4099 (if noerror
4100 (progn
4101 (message "Cannot read file %s" file)
4102 (ding) (sit-for 2)
4104 (error "Cannot read file %s" file))
4105 (with-temp-buffer
4106 (insert-file-contents file)
4107 (buffer-string))))
4109 (defun org-extract-log-state-settings (x)
4110 "Extract the log state setting from a TODO keyword string.
4111 This will extract info from a string like \"WAIT(w@/!)\"."
4112 (let (kw key log1 log2)
4113 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4114 (setq kw (match-string 1 x)
4115 key (and (match-end 2) (match-string 2 x))
4116 log1 (and (match-end 3) (match-string 3 x))
4117 log2 (and (match-end 4) (match-string 4 x)))
4118 (and (or log1 log2)
4119 (list kw
4120 (and log1 (if (equal log1 "!") 'time 'note))
4121 (and log2 (if (equal log2 "!") 'time 'note)))))))
4123 (defun org-remove-keyword-keys (list)
4124 "Remove a pair of parenthesis at the end of each string in LIST."
4125 (mapcar (lambda (x)
4126 (if (string-match "(.*)$" x)
4127 (substring x 0 (match-beginning 0))
4129 list))
4131 ;; FIXME: this could be done much better, using second characters etc.
4132 (defun org-assign-fast-keys (alist)
4133 "Assign fast keys to a keyword-key alist.
4134 Respect keys that are already there."
4135 (let (new e k c c1 c2 (char ?a))
4136 (while (setq e (pop alist))
4137 (cond
4138 ((equal e '(:startgroup)) (push e new))
4139 ((equal e '(:endgroup)) (push e new))
4140 ((equal e '(:newline)) (push e new))
4142 (setq k (car e) c2 nil)
4143 (if (cdr e)
4144 (setq c (cdr e))
4145 ;; automatically assign a character.
4146 (setq c1 (string-to-char
4147 (downcase (substring
4148 k (if (= (string-to-char k) ?@) 1 0)))))
4149 (if (or (rassoc c1 new) (rassoc c1 alist))
4150 (while (or (rassoc char new) (rassoc char alist))
4151 (setq char (1+ char)))
4152 (setq c2 c1))
4153 (setq c (or c2 char)))
4154 (push (cons k c) new))))
4155 (nreverse new)))
4157 ;;; Some variables used in various places
4159 (defvar org-window-configuration nil
4160 "Used in various places to store a window configuration.")
4161 (defvar org-selected-window nil
4162 "Used in various places to store a window configuration.")
4163 (defvar org-finish-function nil
4164 "Function to be called when `C-c C-c' is used.
4165 This is for getting out of special buffers like remember.")
4168 ;; FIXME: Occasionally check by commenting these, to make sure
4169 ;; no other functions uses these, forgetting to let-bind them.
4170 (defvar entry)
4171 (defvar last-state)
4172 (defvar date)
4174 ;; Defined somewhere in this file, but used before definition.
4175 (defvar org-html-entities)
4176 (defvar org-struct-menu)
4177 (defvar org-org-menu)
4178 (defvar org-tbl-menu)
4180 ;;;; Define the Org-mode
4182 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4183 (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."))
4186 ;; We use a before-change function to check if a table might need
4187 ;; an update.
4188 (defvar org-table-may-need-update t
4189 "Indicates that a table might need an update.
4190 This variable is set by `org-before-change-function'.
4191 `org-table-align' sets it back to nil.")
4192 (defun org-before-change-function (beg end)
4193 "Every change indicates that a table might need an update."
4194 (setq org-table-may-need-update t))
4195 (defvar org-mode-map)
4196 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4197 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4198 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4199 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4200 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4201 (defvar org-table-buffer-is-an nil)
4202 (defconst org-outline-regexp "\\*+ ")
4204 ;;;###autoload
4205 (define-derived-mode org-mode outline-mode "Org"
4206 "Outline-based notes management and organizer, alias
4207 \"Carsten's outline-mode for keeping track of everything.\"
4209 Org-mode develops organizational tasks around a NOTES file which
4210 contains information about projects as plain text. Org-mode is
4211 implemented on top of outline-mode, which is ideal to keep the content
4212 of large files well structured. It supports ToDo items, deadlines and
4213 time stamps, which magically appear in the diary listing of the Emacs
4214 calendar. Tables are easily created with a built-in table editor.
4215 Plain text URL-like links connect to websites, emails (VM), Usenet
4216 messages (Gnus), BBDB entries, and any files related to the project.
4217 For printing and sharing of notes, an Org-mode file (or a part of it)
4218 can be exported as a structured ASCII or HTML file.
4220 The following commands are available:
4222 \\{org-mode-map}"
4224 ;; Get rid of Outline menus, they are not needed
4225 ;; Need to do this here because define-derived-mode sets up
4226 ;; the keymap so late. Still, it is a waste to call this each time
4227 ;; we switch another buffer into org-mode.
4228 (if (featurep 'xemacs)
4229 (when (boundp 'outline-mode-menu-heading)
4230 ;; Assume this is Greg's port, it used easymenu
4231 (easy-menu-remove outline-mode-menu-heading)
4232 (easy-menu-remove outline-mode-menu-show)
4233 (easy-menu-remove outline-mode-menu-hide))
4234 (define-key org-mode-map [menu-bar headings] 'undefined)
4235 (define-key org-mode-map [menu-bar hide] 'undefined)
4236 (define-key org-mode-map [menu-bar show] 'undefined))
4238 (org-load-modules-maybe)
4239 (easy-menu-add org-org-menu)
4240 (easy-menu-add org-tbl-menu)
4241 (org-install-agenda-files-menu)
4242 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4243 (org-add-to-invisibility-spec '(org-cwidth))
4244 (org-add-to-invisibility-spec '(org-hide-block . t))
4245 (when (featurep 'xemacs)
4246 (org-set-local 'line-move-ignore-invisible t))
4247 (org-set-local 'outline-regexp org-outline-regexp)
4248 (org-set-local 'outline-level 'org-outline-level)
4249 (when (and org-ellipsis
4250 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4251 (fboundp 'make-glyph-code))
4252 (unless org-display-table
4253 (setq org-display-table (make-display-table)))
4254 (set-display-table-slot
4255 org-display-table 4
4256 (vconcat (mapcar
4257 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4258 org-ellipsis)))
4259 (if (stringp org-ellipsis) org-ellipsis "..."))))
4260 (setq buffer-display-table org-display-table))
4261 (org-set-regexps-and-options)
4262 (when (and org-tag-faces (not org-tags-special-faces-re))
4263 ;; tag faces set outside customize.... force initialization.
4264 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4265 ;; Calc embedded
4266 (org-set-local 'calc-embedded-open-mode "# ")
4267 (modify-syntax-entry ?# "<")
4268 (modify-syntax-entry ?@ "w")
4269 (if org-startup-truncated (setq truncate-lines t))
4270 (org-set-local 'font-lock-unfontify-region-function
4271 'org-unfontify-region)
4272 ;; Activate before-change-function
4273 (org-set-local 'org-table-may-need-update t)
4274 (org-add-hook 'before-change-functions 'org-before-change-function nil
4275 'local)
4276 ;; Check for running clock before killing a buffer
4277 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4278 ;; Paragraphs and auto-filling
4279 (org-set-autofill-regexps)
4280 (setq indent-line-function 'org-indent-line-function)
4281 (org-update-radio-target-regexp)
4282 ;; Make sure dependence stuff works reliably, even for users who set it
4283 ;; too late :-(
4284 (if org-enforce-todo-dependencies
4285 (add-hook 'org-blocker-hook
4286 'org-block-todo-from-children-or-siblings-or-parent)
4287 (remove-hook 'org-blocker-hook
4288 'org-block-todo-from-children-or-siblings-or-parent))
4289 (if org-enforce-todo-checkbox-dependencies
4290 (add-hook 'org-blocker-hook
4291 'org-block-todo-from-checkboxes)
4292 (remove-hook 'org-blocker-hook
4293 'org-block-todo-from-checkboxes))
4295 ;; Comment characters
4296 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4297 (org-set-local 'comment-padding " ")
4299 ;; Align options lines
4300 (org-set-local
4301 'align-mode-rules-list
4302 '((org-in-buffer-settings
4303 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4304 (modes . '(org-mode)))))
4306 ;; Imenu
4307 (org-set-local 'imenu-create-index-function
4308 'org-imenu-get-tree)
4310 ;; Make isearch reveal context
4311 (if (or (featurep 'xemacs)
4312 (not (boundp 'outline-isearch-open-invisible-function)))
4313 ;; Emacs 21 and XEmacs make use of the hook
4314 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4315 ;; Emacs 22 deals with this through a special variable
4316 (org-set-local 'outline-isearch-open-invisible-function
4317 (lambda (&rest ignore) (org-show-context 'isearch))))
4319 ;; Turn on org-beamer-mode?
4320 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4322 ;; If empty file that did not turn on org-mode automatically, make it to.
4323 (if (and org-insert-mode-line-in-empty-file
4324 (interactive-p)
4325 (= (point-min) (point-max)))
4326 (insert "# -*- mode: org -*-\n\n"))
4327 (unless org-inhibit-startup
4328 (when org-startup-align-all-tables
4329 (let ((bmp (buffer-modified-p)))
4330 (org-table-map-tables 'org-table-align)
4331 (set-buffer-modified-p bmp)))
4332 (when org-startup-indented
4333 (require 'org-indent)
4334 (org-indent-mode 1))
4335 (unless org-inhibit-startup-visibility-stuff
4336 (org-set-startup-visibility))))
4338 (when (fboundp 'abbrev-table-put)
4339 (abbrev-table-put org-mode-abbrev-table
4340 :parents (list text-mode-abbrev-table)))
4342 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4344 (defun org-current-time ()
4345 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4346 (if (> (car org-time-stamp-rounding-minutes) 1)
4347 (let ((r (car org-time-stamp-rounding-minutes))
4348 (time (decode-time)))
4349 (apply 'encode-time
4350 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4351 (nthcdr 2 time))))
4352 (current-time)))
4354 ;;;; Font-Lock stuff, including the activators
4356 (defvar org-mouse-map (make-sparse-keymap))
4357 (org-defkey org-mouse-map
4358 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4359 (org-defkey org-mouse-map
4360 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4361 (when org-mouse-1-follows-link
4362 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4363 (when org-tab-follows-link
4364 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4365 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4367 (require 'font-lock)
4369 (defconst org-non-link-chars "]\t\n\r<>")
4370 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4371 "shell" "elisp"))
4372 (defvar org-link-types-re nil
4373 "Matches a link that has a url-like prefix like \"http:\"")
4374 (defvar org-link-re-with-space nil
4375 "Matches a link with spaces, optional angular brackets around it.")
4376 (defvar org-link-re-with-space2 nil
4377 "Matches a link with spaces, optional angular brackets around it.")
4378 (defvar org-link-re-with-space3 nil
4379 "Matches a link with spaces, only for internal part in bracket links.")
4380 (defvar org-angle-link-re nil
4381 "Matches link with angular brackets, spaces are allowed.")
4382 (defvar org-plain-link-re nil
4383 "Matches plain link, without spaces.")
4384 (defvar org-bracket-link-regexp nil
4385 "Matches a link in double brackets.")
4386 (defvar org-bracket-link-analytic-regexp nil
4387 "Regular expression used to analyze links.
4388 Here is what the match groups contain after a match:
4389 1: http:
4390 2: http
4391 3: path
4392 4: [desc]
4393 5: desc")
4394 (defvar org-bracket-link-analytic-regexp++ nil
4395 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4396 (defvar org-any-link-re nil
4397 "Regular expression matching any link.")
4399 (defun org-make-link-regexps ()
4400 "Update the link regular expressions.
4401 This should be called after the variable `org-link-types' has changed."
4402 (setq org-link-types-re
4403 (concat
4404 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4405 org-link-re-with-space
4406 (concat
4407 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4408 "\\([^" org-non-link-chars " ]"
4409 "[^" org-non-link-chars "]*"
4410 "[^" org-non-link-chars " ]\\)>?")
4411 org-link-re-with-space2
4412 (concat
4413 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4414 "\\([^" org-non-link-chars " ]"
4415 "[^\t\n\r]*"
4416 "[^" org-non-link-chars " ]\\)>?")
4417 org-link-re-with-space3
4418 (concat
4419 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4420 "\\([^" org-non-link-chars " ]"
4421 "[^\t\n\r]*\\)")
4422 org-angle-link-re
4423 (concat
4424 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4425 "\\([^" org-non-link-chars " ]"
4426 "[^" org-non-link-chars "]*"
4427 "\\)>")
4428 org-plain-link-re
4429 (concat
4430 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4431 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4432 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4433 org-bracket-link-regexp
4434 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4435 org-bracket-link-analytic-regexp
4436 (concat
4437 "\\[\\["
4438 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4439 "\\([^]]+\\)"
4440 "\\]"
4441 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4442 "\\]")
4443 org-bracket-link-analytic-regexp++
4444 (concat
4445 "\\[\\["
4446 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4447 "\\([^]]+\\)"
4448 "\\]"
4449 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4450 "\\]")
4451 org-any-link-re
4452 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4453 org-angle-link-re "\\)\\|\\("
4454 org-plain-link-re "\\)")))
4456 (org-make-link-regexps)
4458 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4459 "Regular expression for fast time stamp matching.")
4460 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4461 "Regular expression for fast time stamp matching.")
4462 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4463 "Regular expression matching time strings for analysis.
4464 This one does not require the space after the date, so it can be used
4465 on a string that terminates immediately after the date.")
4466 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4467 "Regular expression matching time strings for analysis.")
4468 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4469 "Regular expression matching time stamps, with groups.")
4470 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4471 "Regular expression matching time stamps (also [..]), with groups.")
4472 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4473 "Regular expression matching a time stamp range.")
4474 (defconst org-tr-regexp-both
4475 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4476 "Regular expression matching a time stamp range.")
4477 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4478 org-ts-regexp "\\)?")
4479 "Regular expression matching a time stamp or time stamp range.")
4480 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4481 org-ts-regexp-both "\\)?")
4482 "Regular expression matching a time stamp or time stamp range.
4483 The time stamps may be either active or inactive.")
4485 (defvar org-emph-face nil)
4487 (defun org-do-emphasis-faces (limit)
4488 "Run through the buffer and add overlays to links."
4489 (let (rtn a)
4490 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4491 (if (not (= (char-after (match-beginning 3))
4492 (char-after (match-beginning 4))))
4493 (progn
4494 (setq rtn t)
4495 (setq a (assoc (match-string 3) org-emphasis-alist))
4496 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4497 'face
4498 (nth 1 a))
4499 (and (nth 4 a)
4500 (org-remove-flyspell-overlays-in
4501 (match-beginning 0) (match-end 0)))
4502 (add-text-properties (match-beginning 2) (match-end 2)
4503 '(font-lock-multiline t))
4504 (when org-hide-emphasis-markers
4505 (add-text-properties (match-end 4) (match-beginning 5)
4506 '(invisible org-link))
4507 (add-text-properties (match-beginning 3) (match-end 3)
4508 '(invisible org-link)))))
4509 (backward-char 1))
4510 rtn))
4512 (defun org-emphasize (&optional char)
4513 "Insert or change an emphasis, i.e. a font like bold or italic.
4514 If there is an active region, change that region to a new emphasis.
4515 If there is no region, just insert the marker characters and position
4516 the cursor between them.
4517 CHAR should be either the marker character, or the first character of the
4518 HTML tag associated with that emphasis. If CHAR is a space, the means
4519 to remove the emphasis of the selected region.
4520 If char is not given (for example in an interactive call) it
4521 will be prompted for."
4522 (interactive)
4523 (let ((eal org-emphasis-alist) e det
4524 (erc org-emphasis-regexp-components)
4525 (prompt "")
4526 (string "") beg end move tag c s)
4527 (if (org-region-active-p)
4528 (setq beg (region-beginning) end (region-end)
4529 string (buffer-substring beg end))
4530 (setq move t))
4532 (while (setq e (pop eal))
4533 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4534 c (aref tag 0))
4535 (push (cons c (string-to-char (car e))) det)
4536 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4537 (substring tag 1)))))
4538 (setq det (nreverse det))
4539 (unless char
4540 (message "%s" (concat "Emphasis marker or tag:" prompt))
4541 (setq char (read-char-exclusive)))
4542 (setq char (or (cdr (assoc char det)) char))
4543 (if (equal char ?\ )
4544 (setq s "" move nil)
4545 (unless (assoc (char-to-string char) org-emphasis-alist)
4546 (error "No such emphasis marker: \"%c\"" char))
4547 (setq s (char-to-string char)))
4548 (while (and (> (length string) 1)
4549 (equal (substring string 0 1) (substring string -1))
4550 (assoc (substring string 0 1) org-emphasis-alist))
4551 (setq string (substring string 1 -1)))
4552 (setq string (concat s string s))
4553 (if beg (delete-region beg end))
4554 (unless (or (bolp)
4555 (string-match (concat "[" (nth 0 erc) "\n]")
4556 (char-to-string (char-before (point)))))
4557 (insert " "))
4558 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4559 (char-to-string (char-after (point))))
4560 (insert " ") (backward-char 1))
4561 (insert string)
4562 (and move (backward-char 1))))
4564 (defconst org-nonsticky-props
4565 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4567 (defsubst org-rear-nonsticky-at (pos)
4568 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4570 (defun org-activate-plain-links (limit)
4571 "Run through the buffer and add overlays to links."
4572 (catch 'exit
4573 (let (f)
4574 (if (re-search-forward org-plain-link-re limit t)
4575 (progn
4576 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4577 (setq f (get-text-property (match-beginning 0) 'face))
4578 (if (or (eq f 'org-tag)
4579 (and (listp f) (memq 'org-tag f)))
4581 (add-text-properties (match-beginning 0) (match-end 0)
4582 (list 'mouse-face 'highlight
4583 'face 'org-link
4584 'keymap org-mouse-map))
4585 (org-rear-nonsticky-at (match-end 0)))
4586 t)))))
4588 (defun org-activate-code (limit)
4589 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4590 (progn
4591 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4592 (remove-text-properties (match-beginning 0) (match-end 0)
4593 '(display t invisible t intangible t))
4594 t)))
4596 (defun org-fontify-meta-lines-and-blocks (limit)
4597 "Fontify #+ lines and blocks, in the correct ways."
4598 (let ((case-fold-search t))
4599 (if (re-search-forward
4600 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4601 limit t)
4602 (let ((beg (match-beginning 0))
4603 (beg1 (line-beginning-position 2))
4604 (dc1 (downcase (match-string 2)))
4605 (dc3 (downcase (match-string 3)))
4606 end end1 quoting block-type)
4607 (cond
4608 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4609 ;; a single line of backend-specific content
4610 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4611 (remove-text-properties (match-beginning 0) (match-end 0)
4612 '(display t invisible t intangible t))
4613 (add-text-properties (match-beginning 1) (match-end 3)
4614 '(font-lock-fontified t face org-meta-line))
4615 (add-text-properties (match-beginning 6) (match-end 6)
4616 '(font-lock-fontified t face org-block))
4618 ((and (match-end 4) (equal dc3 "begin"))
4619 ;; Truely a block
4620 (setq block-type (downcase (match-string 5))
4621 quoting (member block-type org-protecting-blocks))
4622 (when (re-search-forward
4623 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4624 nil t) ;; on purpose, we look further than LIMIT
4625 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4626 (when quoting
4627 (remove-text-properties beg end
4628 '(display t invisible t intangible t)))
4629 (add-text-properties
4630 beg end
4631 '(font-lock-fontified t font-lock-multiline t))
4632 (add-text-properties beg beg1 '(face org-meta-line))
4633 (add-text-properties end1 end '(face org-meta-line))
4634 (cond
4635 (quoting
4636 (add-text-properties beg1 end1 '(face org-block)))
4637 ((string= block-type "quote")
4638 (add-text-properties beg1 end1 '(face org-quote)))
4639 ((string= block-type "verse")
4640 (add-text-properties beg1 end1 '(face org-verse))))
4642 ((not (member (char-after beg) '(?\ ?\t)))
4643 ;; just any other in-buffer setting, but not indented
4644 (add-text-properties
4645 beg (match-end 0)
4646 '(font-lock-fontified t face org-meta-line))
4648 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4649 "orgtbl:" "tblfm:" "tblname:"))
4650 (and (match-end 4) (equal dc3 "attr")))
4651 (add-text-properties
4652 beg (match-end 0)
4653 '(font-lock-fontified t face org-meta-line))
4655 ((member dc3 '(" " ""))
4656 (add-text-properties
4657 beg (match-end 0)
4658 '(font-lock-fontified t face font-lock-comment-face)))
4659 (t nil))))))
4661 (defun org-activate-angle-links (limit)
4662 "Run through the buffer and add overlays to links."
4663 (if (re-search-forward org-angle-link-re limit t)
4664 (progn
4665 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4666 (add-text-properties (match-beginning 0) (match-end 0)
4667 (list 'mouse-face 'highlight
4668 'keymap org-mouse-map))
4669 (org-rear-nonsticky-at (match-end 0))
4670 t)))
4672 (defun org-activate-footnote-links (limit)
4673 "Run through the buffer and add overlays to links."
4674 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4675 limit t)
4676 (progn
4677 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4678 (add-text-properties (match-beginning 2) (match-end 2)
4679 (list 'mouse-face 'highlight
4680 'keymap org-mouse-map
4681 'help-echo
4682 (if (= (point-at-bol) (match-beginning 2))
4683 "Footnote definition"
4684 "Footnote reference")
4686 (org-rear-nonsticky-at (match-end 2))
4687 t)))
4689 (defun org-activate-bracket-links (limit)
4690 "Run through the buffer and add overlays to bracketed links."
4691 (if (re-search-forward org-bracket-link-regexp limit t)
4692 (let* ((help (concat "LINK: "
4693 (org-match-string-no-properties 1)))
4694 ;; FIXME: above we should remove the escapes.
4695 ;; but that requires another match, protecting match data,
4696 ;; a lot of overhead for font-lock.
4697 (ip (org-maybe-intangible
4698 (list 'invisible 'org-link
4699 'keymap org-mouse-map 'mouse-face 'highlight
4700 'font-lock-multiline t 'help-echo help)))
4701 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4702 'font-lock-multiline t 'help-echo help)))
4703 ;; We need to remove the invisible property here. Table narrowing
4704 ;; may have made some of this invisible.
4705 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4706 (remove-text-properties (match-beginning 0) (match-end 0)
4707 '(invisible nil))
4708 (if (match-end 3)
4709 (progn
4710 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4711 (org-rear-nonsticky-at (match-beginning 3))
4712 (add-text-properties (match-beginning 3) (match-end 3) vp)
4713 (org-rear-nonsticky-at (match-end 3))
4714 (add-text-properties (match-end 3) (match-end 0) ip)
4715 (org-rear-nonsticky-at (match-end 0)))
4716 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4717 (org-rear-nonsticky-at (match-beginning 1))
4718 (add-text-properties (match-beginning 1) (match-end 1) vp)
4719 (org-rear-nonsticky-at (match-end 1))
4720 (add-text-properties (match-end 1) (match-end 0) ip)
4721 (org-rear-nonsticky-at (match-end 0)))
4722 t)))
4724 (defun org-activate-dates (limit)
4725 "Run through the buffer and add overlays to dates."
4726 (if (re-search-forward org-tsr-regexp-both limit t)
4727 (progn
4728 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4729 (add-text-properties (match-beginning 0) (match-end 0)
4730 (list 'mouse-face 'highlight
4731 'keymap org-mouse-map))
4732 (org-rear-nonsticky-at (match-end 0))
4733 (when org-display-custom-times
4734 (if (match-end 3)
4735 (org-display-custom-time (match-beginning 3) (match-end 3)))
4736 (org-display-custom-time (match-beginning 1) (match-end 1)))
4737 t)))
4739 (defvar org-target-link-regexp nil
4740 "Regular expression matching radio targets in plain text.")
4741 (make-variable-buffer-local 'org-target-link-regexp)
4742 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4743 "Regular expression matching a link target.")
4744 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4745 "Regular expression matching a radio target.")
4746 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4747 "Regular expression matching any target.")
4749 (defun org-activate-target-links (limit)
4750 "Run through the buffer and add overlays to target matches."
4751 (when org-target-link-regexp
4752 (let ((case-fold-search t))
4753 (if (re-search-forward org-target-link-regexp limit t)
4754 (progn
4755 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4756 (add-text-properties (match-beginning 0) (match-end 0)
4757 (list 'mouse-face 'highlight
4758 'keymap org-mouse-map
4759 'help-echo "Radio target link"
4760 'org-linked-text t))
4761 (org-rear-nonsticky-at (match-end 0))
4762 t)))))
4764 (defun org-update-radio-target-regexp ()
4765 "Find all radio targets in this file and update the regular expression."
4766 (interactive)
4767 (when (memq 'radio org-activate-links)
4768 (setq org-target-link-regexp
4769 (org-make-target-link-regexp (org-all-targets 'radio)))
4770 (org-restart-font-lock)))
4772 (defun org-hide-wide-columns (limit)
4773 (let (s e)
4774 (setq s (text-property-any (point) (or limit (point-max))
4775 'org-cwidth t))
4776 (when s
4777 (setq e (next-single-property-change s 'org-cwidth))
4778 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4779 (goto-char e)
4780 t)))
4782 (defvar org-latex-and-specials-regexp nil
4783 "Regular expression for highlighting export special stuff.")
4784 (defvar org-match-substring-regexp)
4785 (defvar org-match-substring-with-braces-regexp)
4787 ;; This should be with the exporter code, but we also use if for font-locking
4788 (defconst org-export-html-special-string-regexps
4789 '(("\\\\-" . "&shy;")
4790 ("---\\([^-]\\)" . "&mdash;\\1")
4791 ("--\\([^-]\\)" . "&ndash;\\1")
4792 ("\\.\\.\\." . "&hellip;"))
4793 "Regular expressions for special string conversion.")
4796 (defun org-compute-latex-and-specials-regexp ()
4797 "Compute regular expression for stuff treated specially by exporters."
4798 (if (not org-highlight-latex-fragments-and-specials)
4799 (org-set-local 'org-latex-and-specials-regexp nil)
4800 (require 'org-exp)
4801 (let*
4802 ((matchers (plist-get org-format-latex-options :matchers))
4803 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4804 org-latex-regexps)))
4805 (org-export-allow-BIND nil)
4806 (options (org-combine-plists (org-default-export-plist)
4807 (org-infile-export-plist)))
4808 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4809 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4810 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4811 (org-export-html-expand (plist-get options :expand-quoted-html))
4812 (org-export-with-special-strings (plist-get options :special-strings))
4813 (re-sub
4814 (cond
4815 ((equal org-export-with-sub-superscripts '{})
4816 (list org-match-substring-with-braces-regexp))
4817 (org-export-with-sub-superscripts
4818 (list org-match-substring-regexp))
4819 (t nil)))
4820 (re-latex
4821 (if org-export-with-LaTeX-fragments
4822 (mapcar (lambda (x) (nth 1 x)) latexs)))
4823 (re-macros
4824 (if org-export-with-TeX-macros
4825 (list (concat "\\\\"
4826 (regexp-opt
4827 (append (mapcar 'car org-html-entities)
4828 (if (boundp 'org-latex-entities)
4829 (mapcar (lambda (x)
4830 (or (car-safe x) x))
4831 org-latex-entities)
4832 nil))
4833 'words))) ; FIXME
4835 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4836 (re-special (if org-export-with-special-strings
4837 (mapcar (lambda (x) (car x))
4838 org-export-html-special-string-regexps)))
4839 (re-rest
4840 (delq nil
4841 (list
4842 (if org-export-html-expand "@<[^>\n]+>")
4843 ))))
4844 (org-set-local
4845 'org-latex-and-specials-regexp
4846 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4847 re-rest) "\\|")))))
4849 (defun org-do-latex-and-special-faces (limit)
4850 "Run through the buffer and add overlays to links."
4851 (when org-latex-and-specials-regexp
4852 (let (rtn d)
4853 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4854 limit t))
4855 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4856 'face))
4857 '(org-code org-verbatim underline)))
4858 (progn
4859 (setq rtn t
4860 d (cond ((member (char-after (1+ (match-beginning 0)))
4861 '(?_ ?^)) 1)
4862 (t 0)))
4863 (font-lock-prepend-text-property
4864 (+ d (match-beginning 0)) (match-end 0)
4865 'face 'org-latex-and-export-specials)
4866 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4867 '(font-lock-multiline t)))))
4868 rtn)))
4870 (defun org-restart-font-lock ()
4871 "Restart font-lock-mode, to force refontification."
4872 (when (and (boundp 'font-lock-mode) font-lock-mode)
4873 (font-lock-mode -1)
4874 (font-lock-mode 1)))
4876 (defun org-all-targets (&optional radio)
4877 "Return a list of all targets in this file.
4878 With optional argument RADIO, only find radio targets."
4879 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4880 rtn)
4881 (save-excursion
4882 (goto-char (point-min))
4883 (while (re-search-forward re nil t)
4884 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4885 rtn)))
4887 (defun org-make-target-link-regexp (targets)
4888 "Make regular expression matching all strings in TARGETS.
4889 The regular expression finds the targets also if there is a line break
4890 between words."
4891 (and targets
4892 (concat
4893 "\\<\\("
4894 (mapconcat
4895 (lambda (x)
4896 (while (string-match " +" x)
4897 (setq x (replace-match "\\s-+" t t x)))
4899 targets
4900 "\\|")
4901 "\\)\\>")))
4903 (defun org-activate-tags (limit)
4904 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4905 (progn
4906 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4907 (add-text-properties (match-beginning 1) (match-end 1)
4908 (list 'mouse-face 'highlight
4909 'keymap org-mouse-map))
4910 (org-rear-nonsticky-at (match-end 1))
4911 t)))
4913 (defun org-outline-level ()
4914 "Compute the outline level of the heading at point.
4915 This function assumes that the cursor is at the beginning of a line matched
4916 by outline-regexp. Otherwise it returns garbage.
4917 If this is called at a normal headline, the level is the number of stars.
4918 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4919 For plain list items, if they are matched by `outline-regexp', this returns
4920 1000 plus the line indentation."
4921 (save-excursion
4922 (looking-at outline-regexp)
4923 (if (match-beginning 1)
4924 (+ (org-get-string-indentation (match-string 1)) 1000)
4925 (1- (- (match-end 0) (match-beginning 0))))))
4927 (defvar org-font-lock-keywords nil)
4929 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4930 "Regular expression matching a property line.")
4932 (defvar org-font-lock-hook nil
4933 "Functions to be called for special font lock stuff.")
4935 (defun org-font-lock-hook (limit)
4936 (run-hook-with-args 'org-font-lock-hook limit))
4938 (defun org-set-font-lock-defaults ()
4939 (let* ((em org-fontify-emphasized-text)
4940 (lk org-activate-links)
4941 (org-font-lock-extra-keywords
4942 (list
4943 ;; Call the hook
4944 '(org-font-lock-hook)
4945 ;; Headlines
4946 `(,(if org-fontify-whole-heading-line
4947 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4948 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4949 (1 (org-get-level-face 1))
4950 (2 (org-get-level-face 2))
4951 (3 (org-get-level-face 3)))
4952 ;; Table lines
4953 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4954 (1 'org-table t))
4955 ;; Table internals
4956 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4957 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4958 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4959 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4960 ;; Drawers
4961 (list org-drawer-regexp '(0 'org-special-keyword t))
4962 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4963 ;; Properties
4964 (list org-property-re
4965 '(1 'org-special-keyword t)
4966 '(3 'org-property-value t))
4967 ;; Links
4968 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4969 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4970 (if (memq 'plain lk) '(org-activate-plain-links))
4971 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4972 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4973 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4974 (if (memq 'footnote lk) '(org-activate-footnote-links
4975 (2 'org-footnote t)))
4976 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4977 '(org-hide-wide-columns (0 nil append))
4978 ;; TODO lines
4979 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4980 '(1 (org-get-todo-face 1) t))
4981 ;; DONE
4982 (if org-fontify-done-headline
4983 (list (concat "^[*]+ +\\<\\("
4984 (mapconcat 'regexp-quote org-done-keywords "\\|")
4985 "\\)\\(.*\\)")
4986 '(2 'org-headline-done t))
4987 nil)
4988 ;; Priorities
4989 '(org-font-lock-add-priority-faces)
4990 ;; Tags
4991 '(org-font-lock-add-tag-faces)
4992 ;; Special keywords
4993 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4994 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4995 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4996 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4997 ;; Emphasis
4998 (if em
4999 (if (featurep 'xemacs)
5000 '(org-do-emphasis-faces (0 nil append))
5001 '(org-do-emphasis-faces)))
5002 ;; Checkboxes
5003 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5004 2 'org-checkbox prepend)
5005 (if org-provide-checkbox-statistics
5006 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5007 (0 (org-get-checkbox-statistics-face) t)))
5008 ;; Description list items
5009 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5010 2 'bold prepend)
5011 ;; ARCHIVEd headings
5012 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5013 '(1 'org-archived prepend))
5014 ;; Specials
5015 '(org-do-latex-and-special-faces)
5016 ;; Code
5017 '(org-activate-code (1 'org-code t))
5018 ;; COMMENT
5019 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5020 "\\|" org-quote-string "\\)\\>")
5021 '(1 'org-special-keyword t))
5022 '("^#.*" (0 'font-lock-comment-face t))
5023 ;; Blocks and meta lines
5024 '(org-fontify-meta-lines-and-blocks)
5026 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5027 ;; Now set the full font-lock-keywords
5028 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5029 (org-set-local 'font-lock-defaults
5030 '(org-font-lock-keywords t nil nil backward-paragraph))
5031 (kill-local-variable 'font-lock-keywords) nil))
5033 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5034 "Fontify string S like in Org-mode"
5035 (with-temp-buffer
5036 (insert s)
5037 (let ((org-odd-levels-only odd-levels))
5038 (org-mode)
5039 (font-lock-fontify-buffer)
5040 (buffer-string))))
5042 (defvar org-m nil)
5043 (defvar org-l nil)
5044 (defvar org-f nil)
5045 (defun org-get-level-face (n)
5046 "Get the right face for match N in font-lock matching of headlines."
5047 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5048 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5049 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5050 (cond
5051 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5052 ((eq n 2) org-f)
5053 (t (if org-level-color-stars-only nil org-f))))
5055 (defun org-get-todo-face (kwd)
5056 "Get the right face for a TODO keyword KWD.
5057 If KWD is a number, get the corresponding match group."
5058 (if (numberp kwd) (setq kwd (match-string kwd)))
5059 (or (cdr (assoc kwd org-todo-keyword-faces))
5060 (and (member kwd org-done-keywords) 'org-done)
5061 'org-todo))
5063 (defun org-font-lock-add-tag-faces (limit)
5064 "Add the special tag faces."
5065 (when (and org-tag-faces org-tags-special-faces-re)
5066 (while (re-search-forward org-tags-special-faces-re limit t)
5067 (add-text-properties (match-beginning 1) (match-end 1)
5068 (list 'face (org-get-tag-face 1)
5069 'font-lock-fontified t))
5070 (backward-char 1))))
5072 (defun org-font-lock-add-priority-faces (limit)
5073 "Add the special priority faces."
5074 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5075 (add-text-properties
5076 (match-beginning 0) (match-end 0)
5077 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5078 org-priority-faces))
5079 'org-special-keyword)
5080 'font-lock-fontified t))))
5082 (defun org-get-tag-face (kwd)
5083 "Get the right face for a TODO keyword KWD.
5084 If KWD is a number, get the corresponding match group."
5085 (if (numberp kwd) (setq kwd (match-string kwd)))
5086 (or (cdr (assoc kwd org-tag-faces))
5087 'org-tag))
5089 (defun org-unfontify-region (beg end &optional maybe_loudly)
5090 "Remove fontification and activation overlays from links."
5091 (font-lock-default-unfontify-region beg end)
5092 (let* ((buffer-undo-list t)
5093 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5094 (inhibit-modification-hooks t)
5095 deactivate-mark buffer-file-name buffer-file-truename)
5096 (remove-text-properties
5097 beg end
5098 (if org-indent-mode
5099 ;; also remove line-prefix and wrap-prefix properties
5100 '(mouse-face t keymap t org-linked-text t
5101 invisible t intangible t
5102 line-prefix t wrap-prefix t
5103 org-no-flyspell t)
5104 '(mouse-face t keymap t org-linked-text t
5105 invisible t intangible t
5106 org-no-flyspell t)))))
5108 ;;;; Visibility cycling, including org-goto and indirect buffer
5110 ;;; Cycling
5112 (defvar org-cycle-global-status nil)
5113 (make-variable-buffer-local 'org-cycle-global-status)
5114 (defvar org-cycle-subtree-status nil)
5115 (make-variable-buffer-local 'org-cycle-subtree-status)
5117 ;;;###autoload
5119 (defvar org-inlinetask-min-level)
5121 (defun org-cycle (&optional arg)
5122 "TAB-action and visibility cycling for Org-mode.
5124 This is the command invoked in Org-mode by the TAB key. Its main purpose
5125 is outline visibility cycling, but it also invokes other actions
5126 in special contexts.
5128 - When this function is called with a prefix argument, rotate the entire
5129 buffer through 3 states (global cycling)
5130 1. OVERVIEW: Show only top-level headlines.
5131 2. CONTENTS: Show all headlines of all levels, but no body text.
5132 3. SHOW ALL: Show everything.
5133 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5134 determined by the variable `org-startup-folded', and by any VISIBILITY
5135 properties in the buffer.
5136 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5137 including any drawers.
5139 - When inside a table, re-align the table and move to the next field.
5141 - When point is at the beginning of a headline, rotate the subtree started
5142 by this line through 3 different states (local cycling)
5143 1. FOLDED: Only the main headline is shown.
5144 2. CHILDREN: The main headline and the direct children are shown.
5145 From this state, you can move to one of the children
5146 and zoom in further.
5147 3. SUBTREE: Show the entire subtree, including body text.
5148 If there is no subtree, switch directly from CHILDREN to FOLDED.
5150 - When there is a numeric prefix, go up to a heading with level ARG, do
5151 a `show-subtree' and return to the previous cursor position. If ARG
5152 is negative, go up that many levels.
5154 - When point is not at the beginning of a headline, execute the global
5155 binding for TAB, which is re-indenting the line. See the option
5156 `org-cycle-emulate-tab' for details.
5158 - Special case: if point is at the beginning of the buffer and there is
5159 no headline in line 1, this function will act as if called with prefix arg.
5160 But only if also the variable `org-cycle-global-at-bob' is t."
5161 (interactive "P")
5162 (org-load-modules-maybe)
5163 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5164 (and org-cycle-level-after-item/entry-creation
5165 (or (org-cycle-level)
5166 (org-cycle-item-indentation))))
5167 (let* ((limit-level
5168 (or org-cycle-max-level
5169 (and (boundp 'org-inlinetask-min-level)
5170 org-inlinetask-min-level
5171 (1- org-inlinetask-min-level))))
5172 (nstars (and limit-level
5173 (if org-odd-levels-only
5174 (and limit-level (1- (* limit-level 2)))
5175 limit-level)))
5176 (outline-regexp
5177 (cond
5178 ((not (org-mode-p)) outline-regexp)
5179 ((or (eq org-cycle-include-plain-lists 'integrate)
5180 (and org-cycle-include-plain-lists (org-at-item-p)))
5181 (concat "\\(?:\\*"
5182 (if nstars (format "\\{1,%d\\}" nstars) "+")
5183 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5184 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5185 (bob-special (and org-cycle-global-at-bob (bobp)
5186 (not (looking-at outline-regexp))))
5187 (org-cycle-hook
5188 (if bob-special
5189 (delq 'org-optimize-window-after-visibility-change
5190 (copy-sequence org-cycle-hook))
5191 org-cycle-hook))
5192 (pos (point)))
5194 (if (or bob-special (equal arg '(4)))
5195 ;; special case: use global cycling
5196 (setq arg t))
5198 (cond
5200 ((equal arg '(16))
5201 (org-set-startup-visibility)
5202 (message "Startup visibility, plus VISIBILITY properties"))
5204 ((equal arg '(64))
5205 (show-all)
5206 (message "Entire buffer visible, including drawers"))
5208 ((org-at-table-p 'any)
5209 ;; Enter the table or move to the next field in the table
5210 (or (org-table-recognize-table.el)
5211 (progn
5212 (if arg (org-table-edit-field t)
5213 (org-table-justify-field-maybe)
5214 (call-interactively 'org-table-next-field)))))
5216 ((run-hook-with-args-until-success
5217 'org-tab-after-check-for-table-hook))
5219 ((eq arg t) ;; Global cycling
5220 (org-cycle-internal-global))
5222 ((and org-drawers org-drawer-regexp
5223 (save-excursion
5224 (beginning-of-line 1)
5225 (looking-at org-drawer-regexp)))
5226 ;; Toggle block visibility
5227 (org-flag-drawer
5228 (not (get-char-property (match-end 0) 'invisible))))
5230 ((integerp arg)
5231 ;; Show-subtree, ARG levels up from here.
5232 (save-excursion
5233 (org-back-to-heading)
5234 (outline-up-heading (if (< arg 0) (- arg)
5235 (- (funcall outline-level) arg)))
5236 (org-show-subtree)))
5238 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5239 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5241 (org-cycle-internal-local))
5243 ;; TAB emulation and template completion
5244 (buffer-read-only (org-back-to-heading))
5246 ((run-hook-with-args-until-success
5247 'org-tab-after-check-for-cycling-hook))
5249 ((org-try-structure-completion))
5251 ((org-try-cdlatex-tab))
5253 ((run-hook-with-args-until-success
5254 'org-tab-before-tab-emulation-hook))
5256 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5257 (or (not (bolp))
5258 (not (looking-at outline-regexp))))
5259 (call-interactively (global-key-binding "\t")))
5261 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5262 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5263 (or (and (eq org-cycle-emulate-tab 'white)
5264 (= (match-end 0) (point-at-eol)))
5265 (and (eq org-cycle-emulate-tab 'whitestart)
5266 (>= (match-end 0) pos))))
5268 (eq org-cycle-emulate-tab t))
5269 (call-interactively (global-key-binding "\t")))
5271 (t (save-excursion
5272 (org-back-to-heading)
5273 (org-cycle)))))))
5275 (defun org-cycle-internal-global ()
5276 "Do the global cycling action."
5277 (cond
5278 ((and (eq last-command this-command)
5279 (eq org-cycle-global-status 'overview))
5280 ;; We just created the overview - now do table of contents
5281 ;; This can be slow in very large buffers, so indicate action
5282 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5283 (message "CONTENTS...")
5284 (org-content)
5285 (message "CONTENTS...done")
5286 (setq org-cycle-global-status 'contents)
5287 (run-hook-with-args 'org-cycle-hook 'contents))
5289 ((and (eq last-command this-command)
5290 (eq org-cycle-global-status 'contents))
5291 ;; We just showed the table of contents - now show everything
5292 (run-hook-with-args 'org-pre-cycle-hook 'all)
5293 (show-all)
5294 (message "SHOW ALL")
5295 (setq org-cycle-global-status 'all)
5296 (run-hook-with-args 'org-cycle-hook 'all))
5299 ;; Default action: go to overview
5300 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5301 (org-overview)
5302 (message "OVERVIEW")
5303 (setq org-cycle-global-status 'overview)
5304 (run-hook-with-args 'org-cycle-hook 'overview))))
5306 (defun org-cycle-internal-local ()
5307 "Do the local cycling action."
5308 (org-back-to-heading)
5309 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5310 ;; First, some boundaries
5311 (save-excursion
5312 (org-back-to-heading)
5313 (setq level (funcall outline-level))
5314 (save-excursion
5315 (beginning-of-line 2)
5316 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5317 ; XEmacs does not have `next-single-char-property-change'
5318 ; I'm not sure about Emacs 21.
5319 (while (and (not (eobp)) ;; this is like `next-line'
5320 (get-char-property (1- (point)) 'invisible))
5321 (beginning-of-line 2))
5322 (while (and (not (eobp)) ;; this is like `next-line'
5323 (get-char-property (1- (point)) 'invisible))
5324 (goto-char (next-single-char-property-change (point) 'invisible))
5325 ;;;??? (or (bolp) (beginning-of-line 2))))
5326 (and (eolp) (beginning-of-line 2))))
5327 (setq eol (point)))
5328 (outline-end-of-heading) (setq eoh (point))
5329 (save-excursion
5330 (outline-next-heading)
5331 (setq has-children (and (org-at-heading-p t)
5332 (> (funcall outline-level) level))))
5333 (org-end-of-subtree t)
5334 (unless (eobp)
5335 (skip-chars-forward " \t\n")
5336 (beginning-of-line 1) ; in case this is an item
5338 (setq eos (if (eobp) (point) (1- (point)))))
5339 ;; Find out what to do next and set `this-command'
5340 (cond
5341 ((= eos eoh)
5342 ;; Nothing is hidden behind this heading
5343 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5344 (message "EMPTY ENTRY")
5345 (setq org-cycle-subtree-status nil)
5346 (save-excursion
5347 (goto-char eos)
5348 (outline-next-heading)
5349 (if (org-invisible-p) (org-flag-heading nil))))
5350 ((and (or (>= eol eos)
5351 (not (string-match "\\S-" (buffer-substring eol eos))))
5352 (or has-children
5353 (not (setq children-skipped
5354 org-cycle-skip-children-state-if-no-children))))
5355 ;; Entire subtree is hidden in one line: children view
5356 (run-hook-with-args 'org-pre-cycle-hook 'children)
5357 (org-show-entry)
5358 (show-children)
5359 (message "CHILDREN")
5360 (save-excursion
5361 (goto-char eos)
5362 (outline-next-heading)
5363 (if (org-invisible-p) (org-flag-heading nil)))
5364 (setq org-cycle-subtree-status 'children)
5365 (run-hook-with-args 'org-cycle-hook 'children))
5366 ((or children-skipped
5367 (and (eq last-command this-command)
5368 (eq org-cycle-subtree-status 'children)))
5369 ;; We just showed the children, or no children are there,
5370 ;; now show everything.
5371 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5372 (org-show-subtree)
5373 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5374 (setq org-cycle-subtree-status 'subtree)
5375 (run-hook-with-args 'org-cycle-hook 'subtree))
5377 ;; Default action: hide the subtree.
5378 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5379 (hide-subtree)
5380 (message "FOLDED")
5381 (setq org-cycle-subtree-status 'folded)
5382 (run-hook-with-args 'org-cycle-hook 'folded)))))
5384 ;;;###autoload
5385 (defun org-global-cycle (&optional arg)
5386 "Cycle the global visibility. For details see `org-cycle'.
5387 With C-u prefix arg, switch to startup visibility.
5388 With a numeric prefix, show all headlines up to that level."
5389 (interactive "P")
5390 (let ((org-cycle-include-plain-lists
5391 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5392 (cond
5393 ((integerp arg)
5394 (show-all)
5395 (hide-sublevels arg)
5396 (setq org-cycle-global-status 'contents))
5397 ((equal arg '(4))
5398 (org-set-startup-visibility)
5399 (message "Startup visibility, plus VISIBILITY properties."))
5401 (org-cycle '(4))))))
5403 (defun org-set-startup-visibility ()
5404 "Set the visibility required by startup options and properties."
5405 (cond
5406 ((eq org-startup-folded t)
5407 (org-cycle '(4)))
5408 ((eq org-startup-folded 'content)
5409 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5410 (org-cycle '(4)) (org-cycle '(4)))))
5411 (unless (eq org-startup-folded 'showeverything)
5412 (if org-hide-block-startup (org-hide-block-all))
5413 (org-set-visibility-according-to-property 'no-cleanup)
5414 (org-cycle-hide-archived-subtrees 'all)
5415 (org-cycle-hide-drawers 'all)
5416 (org-cycle-show-empty-lines 'all)))
5418 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5419 "Switch subtree visibilities according to :VISIBILITY: property."
5420 (interactive)
5421 (let (org-show-entry-below state)
5422 (save-excursion
5423 (goto-char (point-min))
5424 (while (re-search-forward
5425 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5426 nil t)
5427 (setq state (match-string 1))
5428 (save-excursion
5429 (org-back-to-heading t)
5430 (hide-subtree)
5431 (org-reveal)
5432 (cond
5433 ((equal state '("fold" "folded"))
5434 (hide-subtree))
5435 ((equal state "children")
5436 (org-show-hidden-entry)
5437 (show-children))
5438 ((equal state "content")
5439 (save-excursion
5440 (save-restriction
5441 (org-narrow-to-subtree)
5442 (org-content))))
5443 ((member state '("all" "showall"))
5444 (show-subtree)))))
5445 (unless no-cleanup
5446 (org-cycle-hide-archived-subtrees 'all)
5447 (org-cycle-hide-drawers 'all)
5448 (org-cycle-show-empty-lines 'all)))))
5450 (defun org-overview ()
5451 "Switch to overview mode, showing only top-level headlines.
5452 Really, this shows all headlines with level equal or greater than the level
5453 of the first headline in the buffer. This is important, because if the
5454 first headline is not level one, then (hide-sublevels 1) gives confusing
5455 results."
5456 (interactive)
5457 (let ((level (save-excursion
5458 (goto-char (point-min))
5459 (if (re-search-forward (concat "^" outline-regexp) nil t)
5460 (progn
5461 (goto-char (match-beginning 0))
5462 (funcall outline-level))))))
5463 (and level (hide-sublevels level))))
5465 (defun org-content (&optional arg)
5466 "Show all headlines in the buffer, like a table of contents.
5467 With numerical argument N, show content up to level N."
5468 (interactive "P")
5469 (save-excursion
5470 ;; Visit all headings and show their offspring
5471 (and (integerp arg) (org-overview))
5472 (goto-char (point-max))
5473 (catch 'exit
5474 (while (and (progn (condition-case nil
5475 (outline-previous-visible-heading 1)
5476 (error (goto-char (point-min))))
5478 (looking-at outline-regexp))
5479 (if (integerp arg)
5480 (show-children (1- arg))
5481 (show-branches))
5482 (if (bobp) (throw 'exit nil))))))
5485 (defun org-optimize-window-after-visibility-change (state)
5486 "Adjust the window after a change in outline visibility.
5487 This function is the default value of the hook `org-cycle-hook'."
5488 (when (get-buffer-window (current-buffer))
5489 (cond
5490 ((eq state 'content) nil)
5491 ((eq state 'all) nil)
5492 ((eq state 'folded) nil)
5493 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5494 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5496 (defun org-remove-empty-overlays-at (pos)
5497 "Remove outline overlays that do not contain non-white stuff."
5498 (mapc
5499 (lambda (o)
5500 (and (eq 'outline (org-overlay-get o 'invisible))
5501 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5502 (org-overlay-end o))))
5503 (org-delete-overlay o)))
5504 (org-overlays-at pos)))
5506 (defun org-clean-visibility-after-subtree-move ()
5507 "Fix visibility issues after moving a subtree."
5508 ;; First, find a reasonable region to look at:
5509 ;; Start two siblings above, end three below
5510 (let* ((beg (save-excursion
5511 (and (org-get-last-sibling)
5512 (org-get-last-sibling))
5513 (point)))
5514 (end (save-excursion
5515 (and (org-get-next-sibling)
5516 (org-get-next-sibling)
5517 (org-get-next-sibling))
5518 (if (org-at-heading-p)
5519 (point-at-eol)
5520 (point))))
5521 (level (looking-at "\\*+"))
5522 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5523 (save-excursion
5524 (save-restriction
5525 (narrow-to-region beg end)
5526 (when re
5527 ;; Properly fold already folded siblings
5528 (goto-char (point-min))
5529 (while (re-search-forward re nil t)
5530 (if (and (not (org-invisible-p))
5531 (save-excursion
5532 (goto-char (point-at-eol)) (org-invisible-p)))
5533 (hide-entry))))
5534 (org-cycle-show-empty-lines 'overview)
5535 (org-cycle-hide-drawers 'overview)))))
5537 (defun org-cycle-show-empty-lines (state)
5538 "Show empty lines above all visible headlines.
5539 The region to be covered depends on STATE when called through
5540 `org-cycle-hook'. Lisp program can use t for STATE to get the
5541 entire buffer covered. Note that an empty line is only shown if there
5542 are at least `org-cycle-separator-lines' empty lines before the headline."
5543 (when (not (= org-cycle-separator-lines 0))
5544 (save-excursion
5545 (let* ((n (abs org-cycle-separator-lines))
5546 (re (cond
5547 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5548 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5549 (t (let ((ns (number-to-string (- n 2))))
5550 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5551 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5552 beg end b e)
5553 (cond
5554 ((memq state '(overview contents t))
5555 (setq beg (point-min) end (point-max)))
5556 ((memq state '(children folded))
5557 (setq beg (point) end (progn (org-end-of-subtree t t)
5558 (beginning-of-line 2)
5559 (point)))))
5560 (when beg
5561 (goto-char beg)
5562 (while (re-search-forward re end t)
5563 (unless (get-char-property (match-end 1) 'invisible)
5564 (setq e (match-end 1))
5565 (if (< org-cycle-separator-lines 0)
5566 (setq b (save-excursion
5567 (goto-char (match-beginning 0))
5568 (org-back-over-empty-lines)
5569 (if (save-excursion
5570 (goto-char (max (point-min) (1- (point))))
5571 (org-on-heading-p))
5572 (1- (point))
5573 (point))))
5574 (setq b (match-beginning 1)))
5575 (outline-flag-region b e nil)))))))
5576 ;; Never hide empty lines at the end of the file.
5577 (save-excursion
5578 (goto-char (point-max))
5579 (outline-previous-heading)
5580 (outline-end-of-heading)
5581 (if (and (looking-at "[ \t\n]+")
5582 (= (match-end 0) (point-max)))
5583 (outline-flag-region (point) (match-end 0) nil))))
5585 (defun org-show-empty-lines-in-parent ()
5586 "Move to the parent and re-show empty lines before visible headlines."
5587 (save-excursion
5588 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5589 (org-cycle-show-empty-lines context))))
5591 (defun org-files-list ()
5592 "Return `org-agenda-files' list, plus all open org-mode files.
5593 This is useful for operations that need to scan all of a user's
5594 open and agenda-wise Org files."
5595 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5596 (dolist (buf (buffer-list))
5597 (with-current-buffer buf
5598 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5599 (let ((file (expand-file-name (buffer-file-name))))
5600 (unless (member file files)
5601 (push file files))))))
5602 files))
5604 (defsubst org-entry-beginning-position ()
5605 "Return the beginning position of the current entry."
5606 (save-excursion (outline-back-to-heading t) (point)))
5608 (defsubst org-entry-end-position ()
5609 "Return the end position of the current entry."
5610 (save-excursion (outline-next-heading) (point)))
5612 (defun org-cycle-hide-drawers (state)
5613 "Re-hide all drawers after a visibility state change."
5614 (when (and (org-mode-p)
5615 (not (memq state '(overview folded contents))))
5616 (save-excursion
5617 (let* ((globalp (memq state '(contents all)))
5618 (beg (if globalp (point-min) (point)))
5619 (end (if globalp (point-max)
5620 (if (eq state 'children)
5621 (save-excursion (outline-next-heading) (point))
5622 (org-end-of-subtree t)))))
5623 (goto-char beg)
5624 (while (re-search-forward org-drawer-regexp end t)
5625 (org-flag-drawer t))))))
5627 (defun org-flag-drawer (flag)
5628 (save-excursion
5629 (beginning-of-line 1)
5630 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5631 (let ((b (match-end 0))
5632 (outline-regexp org-outline-regexp))
5633 (if (re-search-forward
5634 "^[ \t]*:END:"
5635 (save-excursion (outline-next-heading) (point)) t)
5636 (outline-flag-region b (point-at-eol) flag)
5637 (error ":END: line missing at position %s" b))))))
5639 (defun org-subtree-end-visible-p ()
5640 "Is the end of the current subtree visible?"
5641 (pos-visible-in-window-p
5642 (save-excursion (org-end-of-subtree t) (point))))
5644 (defun org-first-headline-recenter (&optional N)
5645 "Move cursor to the first headline and recenter the headline.
5646 Optional argument N means, put the headline into the Nth line of the window."
5647 (goto-char (point-min))
5648 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5649 (beginning-of-line)
5650 (recenter (prefix-numeric-value N))))
5652 ;;; Saving and restoring visibility
5654 (defun org-outline-overlay-data (&optional use-markers)
5655 "Return a list of the locations of all outline overlays.
5656 The are overlays with the `invisible' property value `outline'.
5657 The return valus is a list of cons cells, with start and stop
5658 positions for each overlay.
5659 If USE-MARKERS is set, return the positions as markers."
5660 (let (beg end)
5661 (save-excursion
5662 (save-restriction
5663 (widen)
5664 (delq nil
5665 (mapcar (lambda (o)
5666 (when (eq (org-overlay-get o 'invisible) 'outline)
5667 (setq beg (org-overlay-start o)
5668 end (org-overlay-end o))
5669 (and beg end (> end beg)
5670 (if use-markers
5671 (cons (move-marker (make-marker) beg)
5672 (move-marker (make-marker) end))
5673 (cons beg end)))))
5674 (org-overlays-in (point-min) (point-max))))))))
5676 (defun org-set-outline-overlay-data (data)
5677 "Create visibility overlays for all positions in DATA.
5678 DATA should have been made by `org-outline-overlay-data'."
5679 (let (o)
5680 (save-excursion
5681 (save-restriction
5682 (widen)
5683 (show-all)
5684 (mapc (lambda (c)
5685 (setq o (org-make-overlay (car c) (cdr c)))
5686 (org-overlay-put o 'invisible 'outline))
5687 data)))))
5689 (defmacro org-save-outline-visibility (use-markers &rest body)
5690 "Save and restore outline visibility around BODY.
5691 If USE-MARKERS is non-nil, use markers for the positions.
5692 This means that the buffer may change while running BODY,
5693 but it also means that the buffer should stay alive
5694 during the operation, because otherwise all these markers will
5695 point nowhere."
5696 `(let ((data (org-outline-overlay-data ,use-markers)))
5697 (unwind-protect
5698 (progn
5699 ,@body
5700 (org-set-outline-overlay-data data))
5701 (when ,use-markers
5702 (mapc (lambda (c)
5703 (and (markerp (car c)) (move-marker (car c) nil))
5704 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5705 data)))))
5708 ;;; Folding of blocks
5710 (defconst org-block-regexp
5712 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5713 "Regular expression for hiding blocks.")
5715 (defvar org-hide-block-overlays nil
5716 "Overlays hiding blocks.")
5717 (make-variable-buffer-local 'org-hide-block-overlays)
5719 (defun org-block-map (function &optional start end)
5720 "Call func at the head of all source blocks in the current
5721 buffer. Optional arguments START and END can be used to limit
5722 the range."
5723 (let ((start (or start (point-min)))
5724 (end (or end (point-max))))
5725 (save-excursion
5726 (goto-char start)
5727 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5728 (save-excursion
5729 (save-match-data
5730 (goto-char (match-beginning 0))
5731 (funcall function)))))))
5733 (defun org-hide-block-toggle-all ()
5734 "Toggle the visibility of all blocks in the current buffer."
5735 (org-block-map #'org-hide-block-toggle))
5737 (defun org-hide-block-all ()
5738 "Fold all blocks in the current buffer."
5739 (interactive)
5740 (org-show-block-all)
5741 (org-block-map #'org-hide-block-toggle-maybe))
5743 (defun org-show-block-all ()
5744 "Unfold all blocks in the current buffer."
5745 (mapc 'org-delete-overlay org-hide-block-overlays)
5746 (setq org-hide-block-overlays nil))
5748 (defun org-hide-block-toggle-maybe ()
5749 "Toggle visibility of block at point."
5750 (interactive)
5751 (let ((case-fold-search t))
5752 (if (save-excursion
5753 (beginning-of-line 1)
5754 (looking-at org-block-regexp))
5755 (progn (org-hide-block-toggle)
5756 t) ;; to signal that we took action
5757 nil))) ;; to signal that we did not
5759 (defun org-hide-block-toggle (&optional force)
5760 "Toggle the visibility of the current block."
5761 (interactive)
5762 (save-excursion
5763 (beginning-of-line)
5764 (if (re-search-forward org-block-regexp nil t)
5765 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5766 (end (match-end 0)) ;; end of entire body
5768 (if (memq t (mapcar (lambda (overlay)
5769 (eq (org-overlay-get overlay 'invisible)
5770 'org-hide-block))
5771 (org-overlays-at start)))
5772 (if (or (not force) (eq force 'off))
5773 (mapc (lambda (ov)
5774 (when (member ov org-hide-block-overlays)
5775 (setq org-hide-block-overlays
5776 (delq ov org-hide-block-overlays)))
5777 (when (eq (org-overlay-get ov 'invisible)
5778 'org-hide-block)
5779 (org-delete-overlay ov)))
5780 (org-overlays-at start)))
5781 (setq ov (org-make-overlay start end))
5782 (org-overlay-put ov 'invisible 'org-hide-block)
5783 ;; make the block accessible to isearch
5784 (org-overlay-put
5785 ov 'isearch-open-invisible
5786 (lambda (ov)
5787 (when (member ov org-hide-block-overlays)
5788 (setq org-hide-block-overlays
5789 (delq ov org-hide-block-overlays)))
5790 (when (eq (org-overlay-get ov 'invisible)
5791 'org-hide-block)
5792 (org-delete-overlay ov))))
5793 (push ov org-hide-block-overlays)))
5794 (error "Not looking at a source block"))))
5796 ;; org-tab-after-check-for-cycling-hook
5797 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5798 ;; Remove overlays when changing major mode
5799 (add-hook 'org-mode-hook
5800 (lambda () (org-add-hook 'change-major-mode-hook
5801 'org-show-block-all 'append 'local)))
5803 ;;; Org-goto
5805 (defvar org-goto-window-configuration nil)
5806 (defvar org-goto-marker nil)
5807 (defvar org-goto-map
5808 (let ((map (make-sparse-keymap)))
5809 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5810 (while (setq cmd (pop cmds))
5811 (substitute-key-definition cmd cmd map global-map)))
5812 (suppress-keymap map)
5813 (org-defkey map "\C-m" 'org-goto-ret)
5814 (org-defkey map [(return)] 'org-goto-ret)
5815 (org-defkey map [(left)] 'org-goto-left)
5816 (org-defkey map [(right)] 'org-goto-right)
5817 (org-defkey map [(control ?g)] 'org-goto-quit)
5818 (org-defkey map "\C-i" 'org-cycle)
5819 (org-defkey map [(tab)] 'org-cycle)
5820 (org-defkey map [(down)] 'outline-next-visible-heading)
5821 (org-defkey map [(up)] 'outline-previous-visible-heading)
5822 (if org-goto-auto-isearch
5823 (if (fboundp 'define-key-after)
5824 (define-key-after map [t] 'org-goto-local-auto-isearch)
5825 nil)
5826 (org-defkey map "q" 'org-goto-quit)
5827 (org-defkey map "n" 'outline-next-visible-heading)
5828 (org-defkey map "p" 'outline-previous-visible-heading)
5829 (org-defkey map "f" 'outline-forward-same-level)
5830 (org-defkey map "b" 'outline-backward-same-level)
5831 (org-defkey map "u" 'outline-up-heading))
5832 (org-defkey map "/" 'org-occur)
5833 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5834 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5835 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5836 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5837 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5838 map))
5840 (defconst org-goto-help
5841 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5842 RET=jump to location [Q]uit and return to previous location
5843 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5845 (defvar org-goto-start-pos) ; dynamically scoped parameter
5847 ;; FIXME: Docstring does not mention both interfaces
5848 (defun org-goto (&optional alternative-interface)
5849 "Look up a different location in the current file, keeping current visibility.
5851 When you want look-up or go to a different location in a document, the
5852 fastest way is often to fold the entire buffer and then dive into the tree.
5853 This method has the disadvantage, that the previous location will be folded,
5854 which may not be what you want.
5856 This command works around this by showing a copy of the current buffer
5857 in an indirect buffer, in overview mode. You can dive into the tree in
5858 that copy, use org-occur and incremental search to find a location.
5859 When pressing RET or `Q', the command returns to the original buffer in
5860 which the visibility is still unchanged. After RET is will also jump to
5861 the location selected in the indirect buffer and expose the
5862 the headline hierarchy above."
5863 (interactive "P")
5864 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5865 (org-refile-use-outline-path t)
5866 (org-refile-target-verify-function nil)
5867 (interface
5868 (if (not alternative-interface)
5869 org-goto-interface
5870 (if (eq org-goto-interface 'outline)
5871 'outline-path-completion
5872 'outline)))
5873 (org-goto-start-pos (point))
5874 (selected-point
5875 (if (eq interface 'outline)
5876 (car (org-get-location (current-buffer) org-goto-help))
5877 (nth 3 (org-refile-get-location "Goto: ")))))
5878 (if selected-point
5879 (progn
5880 (org-mark-ring-push org-goto-start-pos)
5881 (goto-char selected-point)
5882 (if (or (org-invisible-p) (org-invisible-p2))
5883 (org-show-context 'org-goto)))
5884 (message "Quit"))))
5886 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5887 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5888 (defvar org-goto-local-auto-isearch-map) ; defined below
5890 (defun org-get-location (buf help)
5891 "Let the user select a location in the Org-mode buffer BUF.
5892 This function uses a recursive edit. It returns the selected position
5893 or nil."
5894 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5895 (isearch-hide-immediately nil)
5896 (isearch-search-fun-function
5897 (lambda () 'org-goto-local-search-headings))
5898 (org-goto-selected-point org-goto-exit-command))
5899 (save-excursion
5900 (save-window-excursion
5901 (delete-other-windows)
5902 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5903 (switch-to-buffer
5904 (condition-case nil
5905 (make-indirect-buffer (current-buffer) "*org-goto*")
5906 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5907 (with-output-to-temp-buffer "*Help*"
5908 (princ help))
5909 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5910 (setq buffer-read-only nil)
5911 (let ((org-startup-truncated t)
5912 (org-startup-folded nil)
5913 (org-startup-align-all-tables nil))
5914 (org-mode)
5915 (org-overview))
5916 (setq buffer-read-only t)
5917 (if (and (boundp 'org-goto-start-pos)
5918 (integer-or-marker-p org-goto-start-pos))
5919 (let ((org-show-hierarchy-above t)
5920 (org-show-siblings t)
5921 (org-show-following-heading t))
5922 (goto-char org-goto-start-pos)
5923 (and (org-invisible-p) (org-show-context)))
5924 (goto-char (point-min)))
5925 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5926 (message "Select location and press RET")
5927 (use-local-map org-goto-map)
5928 (recursive-edit)
5930 (kill-buffer "*org-goto*")
5931 (cons org-goto-selected-point org-goto-exit-command)))
5933 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5934 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5935 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5936 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5938 (defun org-goto-local-search-headings (string bound noerror)
5939 "Search and make sure that any matches are in headlines."
5940 (catch 'return
5941 (while (if isearch-forward
5942 (search-forward string bound noerror)
5943 (search-backward string bound noerror))
5944 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5945 (and (member :headline context)
5946 (not (member :tags context))))
5947 (throw 'return (point))))))
5949 (defun org-goto-local-auto-isearch ()
5950 "Start isearch."
5951 (interactive)
5952 (goto-char (point-min))
5953 (let ((keys (this-command-keys)))
5954 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5955 (isearch-mode t)
5956 (isearch-process-search-char (string-to-char keys)))))
5958 (defun org-goto-ret (&optional arg)
5959 "Finish `org-goto' by going to the new location."
5960 (interactive "P")
5961 (setq org-goto-selected-point (point)
5962 org-goto-exit-command 'return)
5963 (throw 'exit nil))
5965 (defun org-goto-left ()
5966 "Finish `org-goto' by going to the new location."
5967 (interactive)
5968 (if (org-on-heading-p)
5969 (progn
5970 (beginning-of-line 1)
5971 (setq org-goto-selected-point (point)
5972 org-goto-exit-command 'left)
5973 (throw 'exit nil))
5974 (error "Not on a heading")))
5976 (defun org-goto-right ()
5977 "Finish `org-goto' by going to the new location."
5978 (interactive)
5979 (if (org-on-heading-p)
5980 (progn
5981 (setq org-goto-selected-point (point)
5982 org-goto-exit-command 'right)
5983 (throw 'exit nil))
5984 (error "Not on a heading")))
5986 (defun org-goto-quit ()
5987 "Finish `org-goto' without cursor motion."
5988 (interactive)
5989 (setq org-goto-selected-point nil)
5990 (setq org-goto-exit-command 'quit)
5991 (throw 'exit nil))
5993 ;;; Indirect buffer display of subtrees
5995 (defvar org-indirect-dedicated-frame nil
5996 "This is the frame being used for indirect tree display.")
5997 (defvar org-last-indirect-buffer nil)
5999 (defun org-tree-to-indirect-buffer (&optional arg)
6000 "Create indirect buffer and narrow it to current subtree.
6001 With numerical prefix ARG, go up to this level and then take that tree.
6002 If ARG is negative, go up that many levels.
6003 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6004 indirect buffer previously made with this command, to avoid proliferation of
6005 indirect buffers. However, when you call the command with a `C-u' prefix, or
6006 when `org-indirect-buffer-display' is `new-frame', the last buffer
6007 is kept so that you can work with several indirect buffers at the same time.
6008 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6009 requests that a new frame be made for the new buffer, so that the dedicated
6010 frame is not changed."
6011 (interactive "P")
6012 (let ((cbuf (current-buffer))
6013 (cwin (selected-window))
6014 (pos (point))
6015 beg end level heading ibuf)
6016 (save-excursion
6017 (org-back-to-heading t)
6018 (when (numberp arg)
6019 (setq level (org-outline-level))
6020 (if (< arg 0) (setq arg (+ level arg)))
6021 (while (> (setq level (org-outline-level)) arg)
6022 (outline-up-heading 1 t)))
6023 (setq beg (point)
6024 heading (org-get-heading))
6025 (org-end-of-subtree t t) (setq end (point)))
6026 (if (and (buffer-live-p org-last-indirect-buffer)
6027 (not (eq org-indirect-buffer-display 'new-frame))
6028 (not arg))
6029 (kill-buffer org-last-indirect-buffer))
6030 (setq ibuf (org-get-indirect-buffer cbuf)
6031 org-last-indirect-buffer ibuf)
6032 (cond
6033 ((or (eq org-indirect-buffer-display 'new-frame)
6034 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6035 (select-frame (make-frame))
6036 (delete-other-windows)
6037 (switch-to-buffer ibuf)
6038 (org-set-frame-title heading))
6039 ((eq org-indirect-buffer-display 'dedicated-frame)
6040 (raise-frame
6041 (select-frame (or (and org-indirect-dedicated-frame
6042 (frame-live-p org-indirect-dedicated-frame)
6043 org-indirect-dedicated-frame)
6044 (setq org-indirect-dedicated-frame (make-frame)))))
6045 (delete-other-windows)
6046 (switch-to-buffer ibuf)
6047 (org-set-frame-title (concat "Indirect: " heading)))
6048 ((eq org-indirect-buffer-display 'current-window)
6049 (switch-to-buffer ibuf))
6050 ((eq org-indirect-buffer-display 'other-window)
6051 (pop-to-buffer ibuf))
6052 (t (error "Invalid value")))
6053 (if (featurep 'xemacs)
6054 (save-excursion (org-mode) (turn-on-font-lock)))
6055 (narrow-to-region beg end)
6056 (show-all)
6057 (goto-char pos)
6058 (and (window-live-p cwin) (select-window cwin))))
6060 (defun org-get-indirect-buffer (&optional buffer)
6061 (setq buffer (or buffer (current-buffer)))
6062 (let ((n 1) (base (buffer-name buffer)) bname)
6063 (while (buffer-live-p
6064 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6065 (setq n (1+ n)))
6066 (condition-case nil
6067 (make-indirect-buffer buffer bname 'clone)
6068 (error (make-indirect-buffer buffer bname)))))
6070 (defun org-set-frame-title (title)
6071 "Set the title of the current frame to the string TITLE."
6072 ;; FIXME: how to name a single frame in XEmacs???
6073 (unless (featurep 'xemacs)
6074 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6076 ;;;; Structure editing
6078 ;;; Inserting headlines
6080 (defun org-previous-line-empty-p ()
6081 (save-excursion
6082 (and (not (bobp))
6083 (or (beginning-of-line 0) t)
6084 (save-match-data
6085 (looking-at "[ \t]*$")))))
6087 (defun org-insert-heading (&optional force-heading)
6088 "Insert a new heading or item with same depth at point.
6089 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6090 If point is at the beginning of a headline, insert a sibling before the
6091 current headline. If point is not at the beginning, do not split the line,
6092 but create the new headline after the current line."
6093 (interactive "P")
6094 (if (or (= (buffer-size) 0)
6095 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
6096 (org-on-heading-p))))
6097 (not (org-in-item-p))))
6098 (insert "\n* ")
6099 (when (or force-heading (not (org-insert-item)))
6100 (let* ((empty-line-p nil)
6101 (head (save-excursion
6102 (condition-case nil
6103 (progn
6104 (org-back-to-heading)
6105 (setq empty-line-p (org-previous-line-empty-p))
6106 (match-string 0))
6107 (error "*"))))
6108 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6109 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6110 pos hide-previous previous-pos)
6111 (cond
6112 ((and (org-on-heading-p) (bolp)
6113 (or (bobp)
6114 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6115 ;; insert before the current line
6116 (open-line (if blank 2 1)))
6117 ((and (bolp)
6118 (not org-insert-heading-respect-content)
6119 (or (bobp)
6120 (save-excursion
6121 (backward-char 1) (not (org-invisible-p)))))
6122 ;; insert right here
6123 nil)
6125 ;; somewhere in the line
6126 (save-excursion
6127 (setq previous-pos (point-at-bol))
6128 (end-of-line)
6129 (setq hide-previous (org-invisible-p)))
6130 (and org-insert-heading-respect-content (org-show-subtree))
6131 (let ((split
6132 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6133 (save-excursion
6134 (let ((p (point)))
6135 (goto-char (point-at-bol))
6136 (and (looking-at org-complex-heading-regexp)
6137 (> p (match-beginning 4)))))))
6138 tags pos)
6139 (cond
6140 (org-insert-heading-respect-content
6141 (org-end-of-subtree nil t)
6142 (or (bolp) (newline))
6143 (or (org-previous-line-empty-p)
6144 (and blank (newline)))
6145 (open-line 1))
6146 ((org-on-heading-p)
6147 (when hide-previous
6148 (show-children)
6149 (org-show-entry))
6150 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6151 (setq tags (and (match-end 2) (match-string 2)))
6152 (and (match-end 1)
6153 (delete-region (match-beginning 1) (match-end 1)))
6154 (setq pos (point-at-bol))
6155 (or split (end-of-line 1))
6156 (delete-horizontal-space)
6157 (newline (if blank 2 1))
6158 (when tags
6159 (save-excursion
6160 (goto-char pos)
6161 (end-of-line 1)
6162 (insert " " tags)
6163 (org-set-tags nil 'align))))
6165 (or split (end-of-line 1))
6166 (newline (if blank 2 1)))))))
6167 (insert head) (just-one-space)
6168 (setq pos (point))
6169 (end-of-line 1)
6170 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6171 (when (and org-insert-heading-respect-content hide-previous)
6172 (save-excursion
6173 (goto-char previous-pos)
6174 (hide-subtree)))
6175 (run-hooks 'org-insert-heading-hook)))))
6177 (defun org-get-heading (&optional no-tags)
6178 "Return the heading of the current entry, without the stars."
6179 (save-excursion
6180 (org-back-to-heading t)
6181 (if (looking-at
6182 (if no-tags
6183 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6184 "\\*+[ \t]+\\([^\r\n]*\\)"))
6185 (match-string 1) "")))
6187 (defun org-heading-components ()
6188 "Return the components of the current heading.
6189 This is a list with the following elements:
6190 - the level as an integer
6191 - the reduced level, different if `org-odd-levels-only' is set.
6192 - the TODO keyword, or nil
6193 - the priority character, like ?A, or nil if no priority is given
6194 - the headline text itself, or the tags string if no headline text
6195 - the tags string, or nil."
6196 (save-excursion
6197 (org-back-to-heading t)
6198 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6199 (list (length (match-string 1))
6200 (org-reduced-level (length (match-string 1)))
6201 (org-match-string-no-properties 2)
6202 (and (match-end 3) (aref (match-string 3) 2))
6203 (org-match-string-no-properties 4)
6204 (org-match-string-no-properties 5)))))
6206 (defun org-get-entry ()
6207 "Get the entry text, after heading, entire subtree."
6208 (save-excursion
6209 (org-back-to-heading t)
6210 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6212 (defun org-insert-heading-after-current ()
6213 "Insert a new heading with same level as current, after current subtree."
6214 (interactive)
6215 (org-back-to-heading)
6216 (org-insert-heading)
6217 (org-move-subtree-down)
6218 (end-of-line 1))
6220 (defun org-insert-heading-respect-content ()
6221 (interactive)
6222 (let ((org-insert-heading-respect-content t))
6223 (org-insert-heading t)))
6225 (defun org-insert-todo-heading-respect-content (&optional force-state)
6226 (interactive "P")
6227 (let ((org-insert-heading-respect-content t))
6228 (org-insert-todo-heading force-state t)))
6230 (defun org-insert-todo-heading (arg &optional force-heading)
6231 "Insert a new heading with the same level and TODO state as current heading.
6232 If the heading has no TODO state, or if the state is DONE, use the first
6233 state (TODO by default). Also with prefix arg, force first state."
6234 (interactive "P")
6235 (when (or force-heading (not (org-insert-item 'checkbox)))
6236 (org-insert-heading force-heading)
6237 (save-excursion
6238 (org-back-to-heading)
6239 (outline-previous-heading)
6240 (looking-at org-todo-line-regexp))
6241 (let*
6242 ((new-mark-x
6243 (if (or arg
6244 (not (match-beginning 2))
6245 (member (match-string 2) org-done-keywords))
6246 (car org-todo-keywords-1)
6247 (match-string 2)))
6248 (new-mark
6250 (run-hook-with-args-until-success
6251 'org-todo-get-default-hook new-mark-x nil)
6252 new-mark-x)))
6253 (beginning-of-line 1)
6254 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6255 (if org-treat-insert-todo-heading-as-state-change
6256 (org-todo new-mark)
6257 (insert new-mark " "))))
6258 (when org-provide-todo-statistics
6259 (org-update-parent-todo-statistics))))
6261 (defun org-insert-subheading (arg)
6262 "Insert a new subheading and demote it.
6263 Works for outline headings and for plain lists alike."
6264 (interactive "P")
6265 (org-insert-heading arg)
6266 (cond
6267 ((org-on-heading-p) (org-do-demote))
6268 ((org-at-item-p) (org-indent-item 1))))
6270 (defun org-insert-todo-subheading (arg)
6271 "Insert a new subheading with TODO keyword or checkbox and demote it.
6272 Works for outline headings and for plain lists alike."
6273 (interactive "P")
6274 (org-insert-todo-heading arg)
6275 (cond
6276 ((org-on-heading-p) (org-do-demote))
6277 ((org-at-item-p) (org-indent-item 1))))
6279 ;;; Promotion and Demotion
6281 (defvar org-after-demote-entry-hook nil
6282 "Hook run after an entry has been demoted.
6283 The cursor will be at the beginning of the entry.
6284 When a subtree is being demoted, the hook will be called for each node.")
6286 (defvar org-after-promote-entry-hook nil
6287 "Hook run after an entry has been promoted.
6288 The cursor will be at the beginning of the entry.
6289 When a subtree is being promoted, the hook will be called for each node.")
6291 (defun org-promote-subtree ()
6292 "Promote the entire subtree.
6293 See also `org-promote'."
6294 (interactive)
6295 (save-excursion
6296 (org-map-tree 'org-promote))
6297 (org-fix-position-after-promote))
6299 (defun org-demote-subtree ()
6300 "Demote the entire subtree. See `org-demote'.
6301 See also `org-promote'."
6302 (interactive)
6303 (save-excursion
6304 (org-map-tree 'org-demote))
6305 (org-fix-position-after-promote))
6308 (defun org-do-promote ()
6309 "Promote the current heading higher up the tree.
6310 If the region is active in `transient-mark-mode', promote all headings
6311 in the region."
6312 (interactive)
6313 (save-excursion
6314 (if (org-region-active-p)
6315 (org-map-region 'org-promote (region-beginning) (region-end))
6316 (org-promote)))
6317 (org-fix-position-after-promote))
6319 (defun org-do-demote ()
6320 "Demote the current heading lower down the tree.
6321 If the region is active in `transient-mark-mode', demote all headings
6322 in the region."
6323 (interactive)
6324 (save-excursion
6325 (if (org-region-active-p)
6326 (org-map-region 'org-demote (region-beginning) (region-end))
6327 (org-demote)))
6328 (org-fix-position-after-promote))
6330 (defun org-fix-position-after-promote ()
6331 "Make sure that after pro/demotion cursor position is right."
6332 (let ((pos (point)))
6333 (when (save-excursion
6334 (beginning-of-line 1)
6335 (looking-at org-todo-line-regexp)
6336 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6337 (cond ((eobp) (insert " "))
6338 ((eolp) (insert " "))
6339 ((equal (char-after) ?\ ) (forward-char 1))))))
6341 (defun org-current-level ()
6342 "Return the level of the current entry, or nil if before the first headline.
6343 The level is the number of stars at the beginning of the headline."
6344 (save-excursion
6345 (condition-case nil
6346 (progn
6347 (org-back-to-heading t)
6348 (funcall outline-level))
6349 (error nil))))
6351 (defun org-reduced-level (l)
6352 "Compute the effective level of a heading.
6353 This takes into account the setting of `org-odd-levels-only'."
6354 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6356 (defun org-get-valid-level (level &optional change)
6357 "Rectify a level change under the influence of `org-odd-levels-only'
6358 LEVEL is a current level, CHANGE is by how much the level should be
6359 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6360 even level numbers will become the next higher odd number."
6361 (if org-odd-levels-only
6362 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6363 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6364 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6365 (max 1 (+ level (or change 0)))))
6367 (if (boundp 'define-obsolete-function-alias)
6368 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6369 (define-obsolete-function-alias 'org-get-legal-level
6370 'org-get-valid-level)
6371 (define-obsolete-function-alias 'org-get-legal-level
6372 'org-get-valid-level "23.1")))
6374 (defun org-promote ()
6375 "Promote the current heading higher up the tree.
6376 If the region is active in `transient-mark-mode', promote all headings
6377 in the region."
6378 (org-back-to-heading t)
6379 (let* ((level (save-match-data (funcall outline-level)))
6380 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6381 (diff (abs (- level (length up-head) -1))))
6382 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6383 (replace-match up-head nil t)
6384 ;; Fixup tag positioning
6385 (and org-auto-align-tags (org-set-tags nil t))
6386 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6387 (run-hooks 'org-after-promote-entry-hook)))
6389 (defun org-demote ()
6390 "Demote the current heading lower down the tree.
6391 If the region is active in `transient-mark-mode', demote all headings
6392 in the region."
6393 (org-back-to-heading t)
6394 (let* ((level (save-match-data (funcall outline-level)))
6395 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6396 (diff (abs (- level (length down-head) -1))))
6397 (replace-match down-head nil t)
6398 ;; Fixup tag positioning
6399 (and org-auto-align-tags (org-set-tags nil t))
6400 (if org-adapt-indentation (org-fixup-indentation diff))
6401 (run-hooks 'org-after-demote-entry-hook)))
6403 (defvar org-tab-ind-state nil)
6405 (defun org-cycle-level ()
6406 (let ((org-adapt-indentation nil))
6407 (when (and (looking-at "[ \t]*$")
6408 (org-looking-back
6409 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6410 (setq this-command 'org-cycle-level)
6411 (if (eq last-command 'org-cycle-level)
6412 (condition-case nil
6413 (progn (org-do-promote)
6414 (if (equal org-tab-ind-state (org-current-level))
6415 (org-do-promote)))
6416 (error
6417 (progn
6418 (save-excursion
6419 (beginning-of-line 1)
6420 (and (looking-at "\\*+")
6421 (replace-match
6422 (make-string org-tab-ind-state ?*))))
6423 (setq this-command 'org-cycle))))
6424 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6425 (org-do-demote))
6426 t)))
6428 (defun org-map-tree (fun)
6429 "Call FUN for every heading underneath the current one."
6430 (org-back-to-heading)
6431 (let ((level (funcall outline-level)))
6432 (save-excursion
6433 (funcall fun)
6434 (while (and (progn
6435 (outline-next-heading)
6436 (> (funcall outline-level) level))
6437 (not (eobp)))
6438 (funcall fun)))))
6440 (defun org-map-region (fun beg end)
6441 "Call FUN for every heading between BEG and END."
6442 (let ((org-ignore-region t))
6443 (save-excursion
6444 (setq end (copy-marker end))
6445 (goto-char beg)
6446 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6447 (< (point) end))
6448 (funcall fun))
6449 (while (and (progn
6450 (outline-next-heading)
6451 (< (point) end))
6452 (not (eobp)))
6453 (funcall fun)))))
6455 (defun org-fixup-indentation (diff)
6456 "Change the indentation in the current entry by DIFF
6457 However, if any line in the current entry has no indentation, or if it
6458 would end up with no indentation after the change, nothing at all is done."
6459 (save-excursion
6460 (let ((end (save-excursion (outline-next-heading)
6461 (point-marker)))
6462 (prohibit (if (> diff 0)
6463 "^\\S-"
6464 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6465 col)
6466 (unless (save-excursion (end-of-line 1)
6467 (re-search-forward prohibit end t))
6468 (while (and (< (point) end)
6469 (re-search-forward "^[ \t]+" end t))
6470 (goto-char (match-end 0))
6471 (setq col (current-column))
6472 (if (< diff 0) (replace-match ""))
6473 (org-indent-to-column (+ diff col))))
6474 (move-marker end nil))))
6476 (defun org-convert-to-odd-levels ()
6477 "Convert an org-mode file with all levels allowed to one with odd levels.
6478 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6479 level 5 etc."
6480 (interactive)
6481 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6482 (let ((outline-regexp org-outline-regexp)
6483 (outline-level 'org-outline-level)
6484 (org-odd-levels-only nil) n)
6485 (save-excursion
6486 (goto-char (point-min))
6487 (while (re-search-forward "^\\*\\*+ " nil t)
6488 (setq n (- (length (match-string 0)) 2))
6489 (while (>= (setq n (1- n)) 0)
6490 (org-demote))
6491 (end-of-line 1))))))
6493 (defun org-convert-to-oddeven-levels ()
6494 "Convert an org-mode file with only odd levels to one with odd and even levels.
6495 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6496 section with an even level, conversion would destroy the structure of the file. An error
6497 is signaled in this case."
6498 (interactive)
6499 (goto-char (point-min))
6500 ;; First check if there are no even levels
6501 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6502 (org-show-context t)
6503 (error "Not all levels are odd in this file. Conversion not possible"))
6504 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6505 (let ((outline-regexp org-outline-regexp)
6506 (outline-level 'org-outline-level)
6507 (org-odd-levels-only nil) n)
6508 (save-excursion
6509 (goto-char (point-min))
6510 (while (re-search-forward "^\\*\\*+ " nil t)
6511 (setq n (/ (1- (length (match-string 0))) 2))
6512 (while (>= (setq n (1- n)) 0)
6513 (org-promote))
6514 (end-of-line 1))))))
6516 (defun org-tr-level (n)
6517 "Make N odd if required."
6518 (if org-odd-levels-only (1+ (/ n 2)) n))
6520 ;;; Vertical tree motion, cutting and pasting of subtrees
6522 (defun org-move-subtree-up (&optional arg)
6523 "Move the current subtree up past ARG headlines of the same level."
6524 (interactive "p")
6525 (org-move-subtree-down (- (prefix-numeric-value arg))))
6527 (defun org-move-subtree-down (&optional arg)
6528 "Move the current subtree down past ARG headlines of the same level."
6529 (interactive "p")
6530 (setq arg (prefix-numeric-value arg))
6531 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6532 'org-get-last-sibling))
6533 (ins-point (make-marker))
6534 (cnt (abs arg))
6535 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6536 ;; Select the tree
6537 (org-back-to-heading)
6538 (setq beg0 (point))
6539 (save-excursion
6540 (setq ne-beg (org-back-over-empty-lines))
6541 (setq beg (point)))
6542 (save-match-data
6543 (save-excursion (outline-end-of-heading)
6544 (setq folded (org-invisible-p)))
6545 (outline-end-of-subtree))
6546 (outline-next-heading)
6547 (setq ne-end (org-back-over-empty-lines))
6548 (setq end (point))
6549 (goto-char beg0)
6550 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6551 ;; include less whitespace
6552 (save-excursion
6553 (goto-char beg)
6554 (forward-line (- ne-beg ne-end))
6555 (setq beg (point))))
6556 ;; Find insertion point, with error handling
6557 (while (> cnt 0)
6558 (or (and (funcall movfunc) (looking-at outline-regexp))
6559 (progn (goto-char beg0)
6560 (error "Cannot move past superior level or buffer limit")))
6561 (setq cnt (1- cnt)))
6562 (if (> arg 0)
6563 ;; Moving forward - still need to move over subtree
6564 (progn (org-end-of-subtree t t)
6565 (save-excursion
6566 (org-back-over-empty-lines)
6567 (or (bolp) (newline)))))
6568 (setq ne-ins (org-back-over-empty-lines))
6569 (move-marker ins-point (point))
6570 (setq txt (buffer-substring beg end))
6571 (org-save-markers-in-region beg end)
6572 (delete-region beg end)
6573 (org-remove-empty-overlays-at beg)
6574 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6575 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6576 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6577 (let ((bbb (point)))
6578 (insert-before-markers txt)
6579 (org-reinstall-markers-in-region bbb)
6580 (move-marker ins-point bbb))
6581 (or (bolp) (insert "\n"))
6582 (setq ins-end (point))
6583 (goto-char ins-point)
6584 (org-skip-whitespace)
6585 (when (and (< arg 0)
6586 (org-first-sibling-p)
6587 (> ne-ins ne-beg))
6588 ;; Move whitespace back to beginning
6589 (save-excursion
6590 (goto-char ins-end)
6591 (let ((kill-whole-line t))
6592 (kill-line (- ne-ins ne-beg)) (point)))
6593 (insert (make-string (- ne-ins ne-beg) ?\n)))
6594 (move-marker ins-point nil)
6595 (if folded
6596 (hide-subtree)
6597 (org-show-entry)
6598 (show-children)
6599 (org-cycle-hide-drawers 'children))
6600 (org-clean-visibility-after-subtree-move)))
6602 (defvar org-subtree-clip ""
6603 "Clipboard for cut and paste of subtrees.
6604 This is actually only a copy of the kill, because we use the normal kill
6605 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6607 (defvar org-subtree-clip-folded nil
6608 "Was the last copied subtree folded?
6609 This is used to fold the tree back after pasting.")
6611 (defun org-cut-subtree (&optional n)
6612 "Cut the current subtree into the clipboard.
6613 With prefix arg N, cut this many sequential subtrees.
6614 This is a short-hand for marking the subtree and then cutting it."
6615 (interactive "p")
6616 (org-copy-subtree n 'cut))
6618 (defun org-copy-subtree (&optional n cut force-store-markers)
6619 "Cut the current subtree into the clipboard.
6620 With prefix arg N, cut this many sequential subtrees.
6621 This is a short-hand for marking the subtree and then copying it.
6622 If CUT is non-nil, actually cut the subtree.
6623 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6624 of some markers in the region, even if CUT is non-nil. This is
6625 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6626 (interactive "p")
6627 (let (beg end folded (beg0 (point)))
6628 (if (interactive-p)
6629 (org-back-to-heading nil) ; take what looks like a subtree
6630 (org-back-to-heading t)) ; take what is really there
6631 (org-back-over-empty-lines)
6632 (setq beg (point))
6633 (skip-chars-forward " \t\r\n")
6634 (save-match-data
6635 (save-excursion (outline-end-of-heading)
6636 (setq folded (org-invisible-p)))
6637 (condition-case nil
6638 (org-forward-same-level (1- n) t)
6639 (error nil))
6640 (org-end-of-subtree t t))
6641 (org-back-over-empty-lines)
6642 (setq end (point))
6643 (goto-char beg0)
6644 (when (> end beg)
6645 (setq org-subtree-clip-folded folded)
6646 (when (or cut force-store-markers)
6647 (org-save-markers-in-region beg end))
6648 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6649 (setq org-subtree-clip (current-kill 0))
6650 (message "%s: Subtree(s) with %d characters"
6651 (if cut "Cut" "Copied")
6652 (length org-subtree-clip)))))
6654 (defun org-paste-subtree (&optional level tree for-yank)
6655 "Paste the clipboard as a subtree, with modification of headline level.
6656 The entire subtree is promoted or demoted in order to match a new headline
6657 level.
6659 If the cursor is at the beginning of a headline, the same level as
6660 that headline is used to paste the tree
6662 If not, the new level is derived from the *visible* headings
6663 before and after the insertion point, and taken to be the inferior headline
6664 level of the two. So if the previous visible heading is level 3 and the
6665 next is level 4 (or vice versa), level 4 will be used for insertion.
6666 This makes sure that the subtree remains an independent subtree and does
6667 not swallow low level entries.
6669 You can also force a different level, either by using a numeric prefix
6670 argument, or by inserting the heading marker by hand. For example, if the
6671 cursor is after \"*****\", then the tree will be shifted to level 5.
6673 If optional TREE is given, use this text instead of the kill ring.
6675 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6676 move back over whitespace before inserting, and move point to the end of
6677 the inserted text when done."
6678 (interactive "P")
6679 (setq tree (or tree (and kill-ring (current-kill 0))))
6680 (unless (org-kill-is-subtree-p tree)
6681 (error "%s"
6682 (substitute-command-keys
6683 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6684 (let* ((visp (not (org-invisible-p)))
6685 (txt tree)
6686 (^re (concat "^\\(" outline-regexp "\\)"))
6687 (re (concat "\\(" outline-regexp "\\)"))
6688 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6690 (old-level (if (string-match ^re txt)
6691 (- (match-end 0) (match-beginning 0) 1)
6692 -1))
6693 (force-level (cond (level (prefix-numeric-value level))
6694 ((and (looking-at "[ \t]*$")
6695 (string-match
6696 ^re_ (buffer-substring
6697 (point-at-bol) (point))))
6698 (- (match-end 1) (match-beginning 1)))
6699 ((and (bolp)
6700 (looking-at org-outline-regexp))
6701 (- (match-end 0) (point) 1))
6702 (t nil)))
6703 (previous-level (save-excursion
6704 (condition-case nil
6705 (progn
6706 (outline-previous-visible-heading 1)
6707 (if (looking-at re)
6708 (- (match-end 0) (match-beginning 0) 1)
6710 (error 1))))
6711 (next-level (save-excursion
6712 (condition-case nil
6713 (progn
6714 (or (looking-at outline-regexp)
6715 (outline-next-visible-heading 1))
6716 (if (looking-at re)
6717 (- (match-end 0) (match-beginning 0) 1)
6719 (error 1))))
6720 (new-level (or force-level (max previous-level next-level)))
6721 (shift (if (or (= old-level -1)
6722 (= new-level -1)
6723 (= old-level new-level))
6725 (- new-level old-level)))
6726 (delta (if (> shift 0) -1 1))
6727 (func (if (> shift 0) 'org-demote 'org-promote))
6728 (org-odd-levels-only nil)
6729 beg end newend)
6730 ;; Remove the forced level indicator
6731 (if force-level
6732 (delete-region (point-at-bol) (point)))
6733 ;; Paste
6734 (beginning-of-line 1)
6735 (unless for-yank (org-back-over-empty-lines))
6736 (setq beg (point))
6737 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6738 (insert-before-markers txt)
6739 (unless (string-match "\n\\'" txt) (insert "\n"))
6740 (setq newend (point))
6741 (org-reinstall-markers-in-region beg)
6742 (setq end (point))
6743 (goto-char beg)
6744 (skip-chars-forward " \t\n\r")
6745 (setq beg (point))
6746 (if (and (org-invisible-p) visp)
6747 (save-excursion (outline-show-heading)))
6748 ;; Shift if necessary
6749 (unless (= shift 0)
6750 (save-restriction
6751 (narrow-to-region beg end)
6752 (while (not (= shift 0))
6753 (org-map-region func (point-min) (point-max))
6754 (setq shift (+ delta shift)))
6755 (goto-char (point-min))
6756 (setq newend (point-max))))
6757 (when (or (interactive-p) for-yank)
6758 (message "Clipboard pasted as level %d subtree" new-level))
6759 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6760 kill-ring
6761 (eq org-subtree-clip (current-kill 0))
6762 org-subtree-clip-folded)
6763 ;; The tree was folded before it was killed/copied
6764 (hide-subtree))
6765 (and for-yank (goto-char newend))))
6767 (defun org-kill-is-subtree-p (&optional txt)
6768 "Check if the current kill is an outline subtree, or a set of trees.
6769 Returns nil if kill does not start with a headline, or if the first
6770 headline level is not the largest headline level in the tree.
6771 So this will actually accept several entries of equal levels as well,
6772 which is OK for `org-paste-subtree'.
6773 If optional TXT is given, check this string instead of the current kill."
6774 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6775 (start-level (and kill
6776 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6777 org-outline-regexp "\\)")
6778 kill)
6779 (- (match-end 2) (match-beginning 2) 1)))
6780 (re (concat "^" org-outline-regexp))
6781 (start (1+ (or (match-beginning 2) -1))))
6782 (if (not start-level)
6783 (progn
6784 nil) ;; does not even start with a heading
6785 (catch 'exit
6786 (while (setq start (string-match re kill (1+ start)))
6787 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6788 (throw 'exit nil)))
6789 t))))
6791 (defvar org-markers-to-move nil
6792 "Markers that should be moved with a cut-and-paste operation.
6793 Those markers are stored together with their positions relative to
6794 the start of the region.")
6796 (defun org-save-markers-in-region (beg end)
6797 "Check markers in region.
6798 If these markers are between BEG and END, record their position relative
6799 to BEG, so that after moving the block of text, we can put the markers back
6800 into place.
6801 This function gets called just before an entry or tree gets cut from the
6802 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6803 called immediately, to move the markers with the entries."
6804 (setq org-markers-to-move nil)
6805 (when (featurep 'org-clock)
6806 (org-clock-save-markers-for-cut-and-paste beg end))
6807 (when (featurep 'org-agenda)
6808 (org-agenda-save-markers-for-cut-and-paste beg end)))
6810 (defun org-check-and-save-marker (marker beg end)
6811 "Check if MARKER is between BEG and END.
6812 If yes, remember the marker and the distance to BEG."
6813 (when (and (marker-buffer marker)
6814 (equal (marker-buffer marker) (current-buffer)))
6815 (if (and (>= marker beg) (< marker end))
6816 (push (cons marker (- marker beg)) org-markers-to-move))))
6818 (defun org-reinstall-markers-in-region (beg)
6819 "Move all remembered markers to their position relative to BEG."
6820 (mapc (lambda (x)
6821 (move-marker (car x) (+ beg (cdr x))))
6822 org-markers-to-move)
6823 (setq org-markers-to-move nil))
6825 (defun org-narrow-to-subtree ()
6826 "Narrow buffer to the current subtree."
6827 (interactive)
6828 (save-excursion
6829 (save-match-data
6830 (narrow-to-region
6831 (progn (org-back-to-heading t) (point))
6832 (progn (org-end-of-subtree t t) (point))))))
6834 (defun org-clone-subtree-with-time-shift (n &optional shift)
6835 "Clone the task (subtree) at point N times.
6836 The clones will be inserted as siblings.
6838 In interactive use, the user will be prompted for the number of clones
6839 to be produced, and for a time SHIFT, which may be a repeater as used
6840 in time stamps, for example `+3d'.
6842 When a valid repeater is given and the entry contains any time stamps,
6843 the clones will become a sequence in time, with time stamps in the
6844 subtree shifted for each clone produced. If SHIFT is nil or the
6845 empty string, time stamps will be left alone.
6847 If the original subtree did contain time stamps with a repeater,
6848 the following will happen:
6849 - the repeater will be removed in each clone
6850 - an additional clone will be produced, with the current, unshifted
6851 date(s) in the entry.
6852 - the original entry will be placed *after* all the clones, with
6853 repeater intact.
6854 - the start days in the repeater in the original entry will be shifted
6855 to past the last clone.
6856 I this way you can spell out a number of instances of a repeating task,
6857 and still retain the repeater to cover future instances of the task."
6858 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6859 (let (beg end template task
6860 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6861 (if (not (and (integerp n) (> n 0)))
6862 (error "Invalid number of replications %s" n))
6863 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6864 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6865 shift)))
6866 (error "Invalid shift specification %s" shift))
6867 (when doshift
6868 (setq shift-n (string-to-number (match-string 1 shift))
6869 shift-what (cdr (assoc (match-string 2 shift)
6870 '(("d" . day) ("w" . week)
6871 ("m" . month) ("y" . year))))))
6872 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6873 (setq nmin 1 nmax n)
6874 (org-back-to-heading t)
6875 (setq beg (point))
6876 (org-end-of-subtree t t)
6877 (or (bolp) (insert "\n"))
6878 (setq end (point))
6879 (setq template (buffer-substring beg end))
6880 (when (and doshift
6881 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6882 (delete-region beg end)
6883 (setq end beg)
6884 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6885 (goto-char end)
6886 (loop for n from nmin to nmax do
6887 (if (not doshift)
6888 (setq task template)
6889 (with-temp-buffer
6890 (insert template)
6891 (org-mode)
6892 (goto-char (point-min))
6893 (while (re-search-forward org-ts-regexp-both nil t)
6894 (org-timestamp-change (* n shift-n) shift-what))
6895 (unless (= n n-no-remove)
6896 (goto-char (point-min))
6897 (while (re-search-forward org-ts-regexp nil t)
6898 (save-excursion
6899 (goto-char (match-beginning 0))
6900 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6901 (delete-region (match-beginning 1) (match-end 1))))))
6902 (setq task (buffer-string))))
6903 (insert task))
6904 (goto-char beg)))
6906 ;;; Outline Sorting
6908 (defun org-sort (with-case)
6909 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6910 Optional argument WITH-CASE means sort case-sensitively.
6911 With a double prefix argument, also remove duplicate entries."
6912 (interactive "P")
6913 (if (org-at-table-p)
6914 (org-call-with-arg 'org-table-sort-lines with-case)
6915 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6917 (defun org-sort-remove-invisible (s)
6918 (remove-text-properties 0 (length s) org-rm-props s)
6919 (while (string-match org-bracket-link-regexp s)
6920 (setq s (replace-match (if (match-end 2)
6921 (match-string 3 s)
6922 (match-string 1 s)) t t s)))
6925 (defvar org-priority-regexp) ; defined later in the file
6927 (defvar org-after-sorting-entries-or-items-hook nil
6928 "Hook that is run after a bunch of entries or items have been sorted.
6929 When children are sorted, the cursor is in the parent line when this
6930 hook gets called. When a region or a plain list is sorted, the cursor
6931 will be in the first entry of the sorted region/list.")
6933 (defun org-sort-entries-or-items
6934 (&optional with-case sorting-type getkey-func compare-func property)
6935 "Sort entries on a certain level of an outline tree, or plain list items.
6936 If there is an active region, the entries in the region are sorted.
6937 Else, if the cursor is before the first entry, sort the top-level items.
6938 Else, the children of the entry at point are sorted.
6939 If the cursor is at the first item in a plain list, the list items will be
6940 sorted.
6942 Sorting can be alphabetically, numerically, by date/time as given by
6943 a time stamp, by a property or by priority.
6945 The command prompts for the sorting type unless it has been given to the
6946 function through the SORTING-TYPE argument, which needs to a character,
6947 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6948 precise meaning of each character:
6950 n Numerically, by converting the beginning of the entry/item to a number.
6951 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6952 t By date/time, either the first active time stamp in the entry, or, if
6953 none exist, by the first inactive one.
6954 In items, only the first line will be checked.
6955 s By the scheduled date/time.
6956 d By deadline date/time.
6957 c By creation time, which is assumed to be the first inactive time stamp
6958 at the beginning of a line.
6959 p By priority according to the cookie.
6960 r By the value of a property.
6962 Capital letters will reverse the sort order.
6964 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6965 called with point at the beginning of the record. It must return either
6966 a string or a number that should serve as the sorting key for that record.
6968 Comparing entries ignores case by default. However, with an optional argument
6969 WITH-CASE, the sorting considers case as well."
6970 (interactive "P")
6971 (let ((case-func (if with-case 'identity 'downcase))
6972 start beg end stars re re2
6973 txt what tmp plain-list-p)
6974 ;; Find beginning and end of region to sort
6975 (cond
6976 ((org-region-active-p)
6977 ;; we will sort the region
6978 (setq end (region-end)
6979 what "region")
6980 (goto-char (region-beginning))
6981 (if (not (org-on-heading-p)) (outline-next-heading))
6982 (setq start (point)))
6983 ((org-at-item-p)
6984 ;; we will sort this plain list
6985 (org-beginning-of-item-list) (setq start (point))
6986 (org-end-of-item-list)
6987 (or (bolp) (insert "\n"))
6988 (setq end (point))
6989 (goto-char start)
6990 (setq plain-list-p t
6991 what "plain list"))
6992 ((or (org-on-heading-p)
6993 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6994 ;; we will sort the children of the current headline
6995 (org-back-to-heading)
6996 (setq start (point)
6997 end (progn (org-end-of-subtree t t)
6998 (or (bolp) (insert "\n"))
6999 (org-back-over-empty-lines)
7000 (point))
7001 what "children")
7002 (goto-char start)
7003 (show-subtree)
7004 (outline-next-heading))
7006 ;; we will sort the top-level entries in this file
7007 (goto-char (point-min))
7008 (or (org-on-heading-p) (outline-next-heading))
7009 (setq start (point))
7010 (goto-char (point-max))
7011 (beginning-of-line 1)
7012 (when (looking-at ".*?\\S-")
7013 ;; File ends in a non-white line
7014 (end-of-line 1)
7015 (insert "\n"))
7016 (setq end (point-max))
7017 (setq what "top-level")
7018 (goto-char start)
7019 (show-all)))
7021 (setq beg (point))
7022 (if (>= beg end) (error "Nothing to sort"))
7024 (unless plain-list-p
7025 (looking-at "\\(\\*+\\)")
7026 (setq stars (match-string 1)
7027 re (concat "^" (regexp-quote stars) " +")
7028 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7029 txt (buffer-substring beg end))
7030 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7031 (if (and (not (equal stars "*")) (string-match re2 txt))
7032 (error "Region to sort contains a level above the first entry")))
7034 (unless sorting-type
7035 (message
7036 (if plain-list-p
7037 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7038 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7039 [t]ime [s]cheduled [d]eadline [c]reated
7040 A/N/T/S/D/C/P/O/F means reversed:")
7041 what)
7042 (setq sorting-type (read-char-exclusive))
7044 (and (= (downcase sorting-type) ?f)
7045 (setq getkey-func
7046 (org-icompleting-read "Sort using function: "
7047 obarray 'fboundp t nil nil))
7048 (setq getkey-func (intern getkey-func)))
7050 (and (= (downcase sorting-type) ?r)
7051 (setq property
7052 (org-icompleting-read "Property: "
7053 (mapcar 'list (org-buffer-property-keys t))
7054 nil t))))
7056 (message "Sorting entries...")
7058 (save-restriction
7059 (narrow-to-region start end)
7061 (let ((dcst (downcase sorting-type))
7062 (case-fold-search nil)
7063 (now (current-time)))
7064 (sort-subr
7065 (/= dcst sorting-type)
7066 ;; This function moves to the beginning character of the "record" to
7067 ;; be sorted.
7068 (if plain-list-p
7069 (lambda nil
7070 (if (org-at-item-p) t (goto-char (point-max))))
7071 (lambda nil
7072 (if (re-search-forward re nil t)
7073 (goto-char (match-beginning 0))
7074 (goto-char (point-max)))))
7075 ;; This function moves to the last character of the "record" being
7076 ;; sorted.
7077 (if plain-list-p
7078 'org-end-of-item
7079 (lambda nil
7080 (save-match-data
7081 (condition-case nil
7082 (outline-forward-same-level 1)
7083 (error
7084 (goto-char (point-max)))))))
7086 ;; This function returns the value that gets sorted against.
7087 (if plain-list-p
7088 (lambda nil
7089 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7090 (cond
7091 ((= dcst ?n)
7092 (string-to-number (buffer-substring (match-end 0)
7093 (point-at-eol))))
7094 ((= dcst ?a)
7095 (buffer-substring (match-end 0) (point-at-eol)))
7096 ((= dcst ?t)
7097 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7098 (re-search-forward org-ts-regexp-both
7099 (point-at-eol) t))
7100 (org-time-string-to-seconds (match-string 0))
7101 (org-float-time now)))
7102 ((= dcst ?f)
7103 (if getkey-func
7104 (progn
7105 (setq tmp (funcall getkey-func))
7106 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7107 tmp)
7108 (error "Invalid key function `%s'" getkey-func)))
7109 (t (error "Invalid sorting type `%c'" sorting-type)))))
7110 (lambda nil
7111 (cond
7112 ((= dcst ?n)
7113 (if (looking-at org-complex-heading-regexp)
7114 (string-to-number (match-string 4))
7115 nil))
7116 ((= dcst ?a)
7117 (if (looking-at org-complex-heading-regexp)
7118 (funcall case-func (match-string 4))
7119 nil))
7120 ((= dcst ?t)
7121 (let ((end (save-excursion (outline-next-heading) (point))))
7122 (if (or (re-search-forward org-ts-regexp end t)
7123 (re-search-forward org-ts-regexp-both end t))
7124 (org-time-string-to-seconds (match-string 0))
7125 (org-float-time now))))
7126 ((= dcst ?c)
7127 (let ((end (save-excursion (outline-next-heading) (point))))
7128 (if (re-search-forward
7129 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7130 end t)
7131 (org-time-string-to-seconds (match-string 0))
7132 (org-float-time now))))
7133 ((= dcst ?s)
7134 (let ((end (save-excursion (outline-next-heading) (point))))
7135 (if (re-search-forward org-scheduled-time-regexp end t)
7136 (org-time-string-to-seconds (match-string 1))
7137 (org-float-time now))))
7138 ((= dcst ?d)
7139 (let ((end (save-excursion (outline-next-heading) (point))))
7140 (if (re-search-forward org-deadline-time-regexp end t)
7141 (org-time-string-to-seconds (match-string 1))
7142 (org-float-time now))))
7143 ((= dcst ?p)
7144 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7145 (string-to-char (match-string 2))
7146 org-default-priority))
7147 ((= dcst ?r)
7148 (or (org-entry-get nil property) ""))
7149 ((= dcst ?o)
7150 (if (looking-at org-complex-heading-regexp)
7151 (- 9999 (length (member (match-string 2)
7152 org-todo-keywords-1)))))
7153 ((= dcst ?f)
7154 (if getkey-func
7155 (progn
7156 (setq tmp (funcall getkey-func))
7157 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7158 tmp)
7159 (error "Invalid key function `%s'" getkey-func)))
7160 (t (error "Invalid sorting type `%c'" sorting-type)))))
7162 (cond
7163 ((= dcst ?a) 'string<)
7164 ((= dcst ?f) compare-func)
7165 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7166 (t nil)))))
7167 (run-hooks 'org-after-sorting-entries-or-items-hook)
7168 (message "Sorting entries...done")))
7170 (defun org-do-sort (table what &optional with-case sorting-type)
7171 "Sort TABLE of WHAT according to SORTING-TYPE.
7172 The user will be prompted for the SORTING-TYPE if the call to this
7173 function does not specify it. WHAT is only for the prompt, to indicate
7174 what is being sorted. The sorting key will be extracted from
7175 the car of the elements of the table.
7176 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7177 (unless sorting-type
7178 (message
7179 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7180 what)
7181 (setq sorting-type (read-char-exclusive)))
7182 (let ((dcst (downcase sorting-type))
7183 extractfun comparefun)
7184 ;; Define the appropriate functions
7185 (cond
7186 ((= dcst ?n)
7187 (setq extractfun 'string-to-number
7188 comparefun (if (= dcst sorting-type) '< '>)))
7189 ((= dcst ?a)
7190 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7191 (lambda(x) (downcase (org-sort-remove-invisible x))))
7192 comparefun (if (= dcst sorting-type)
7193 'string<
7194 (lambda (a b) (and (not (string< a b))
7195 (not (string= a b)))))))
7196 ((= dcst ?t)
7197 (setq extractfun
7198 (lambda (x)
7199 (if (or (string-match org-ts-regexp x)
7200 (string-match org-ts-regexp-both x))
7201 (org-float-time
7202 (org-time-string-to-time (match-string 0 x)))
7204 comparefun (if (= dcst sorting-type) '< '>)))
7205 (t (error "Invalid sorting type `%c'" sorting-type)))
7207 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7208 table)
7209 (lambda (a b) (funcall comparefun (car a) (car b))))))
7212 ;;; The orgstruct minor mode
7214 ;; Define a minor mode which can be used in other modes in order to
7215 ;; integrate the org-mode structure editing commands.
7217 ;; This is really a hack, because the org-mode structure commands use
7218 ;; keys which normally belong to the major mode. Here is how it
7219 ;; works: The minor mode defines all the keys necessary to operate the
7220 ;; structure commands, but wraps the commands into a function which
7221 ;; tests if the cursor is currently at a headline or a plain list
7222 ;; item. If that is the case, the structure command is used,
7223 ;; temporarily setting many Org-mode variables like regular
7224 ;; expressions for filling etc. However, when any of those keys is
7225 ;; used at a different location, function uses `key-binding' to look
7226 ;; up if the key has an associated command in another currently active
7227 ;; keymap (minor modes, major mode, global), and executes that
7228 ;; command. There might be problems if any of the keys is otherwise
7229 ;; used as a prefix key.
7231 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7232 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7233 ;; addresses this by checking explicitly for both bindings.
7235 (defvar orgstruct-mode-map (make-sparse-keymap)
7236 "Keymap for the minor `orgstruct-mode'.")
7238 (defvar org-local-vars nil
7239 "List of local variables, for use by `orgstruct-mode'")
7241 ;;;###autoload
7242 (define-minor-mode orgstruct-mode
7243 "Toggle the minor more `orgstruct-mode'.
7244 This mode is for using Org-mode structure commands in other modes.
7245 The following key behave as if Org-mode was active, if the cursor
7246 is on a headline, or on a plain list item (both in the definition
7247 of Org-mode).
7249 M-up Move entry/item up
7250 M-down Move entry/item down
7251 M-left Promote
7252 M-right Demote
7253 M-S-up Move entry/item up
7254 M-S-down Move entry/item down
7255 M-S-left Promote subtree
7256 M-S-right Demote subtree
7257 M-q Fill paragraph and items like in Org-mode
7258 C-c ^ Sort entries
7259 C-c - Cycle list bullet
7260 TAB Cycle item visibility
7261 M-RET Insert new heading/item
7262 S-M-RET Insert new TODO heading / Checkbox item
7263 C-c C-c Set tags / toggle checkbox"
7264 nil " OrgStruct" nil
7265 (org-load-modules-maybe)
7266 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7268 ;;;###autoload
7269 (defun turn-on-orgstruct ()
7270 "Unconditionally turn on `orgstruct-mode'."
7271 (orgstruct-mode 1))
7273 (defun orgstruct++-mode (&optional arg)
7274 "Toggle `orgstruct-mode', the enhanced version of it.
7275 In addition to setting orgstruct-mode, this also exports all indentation
7276 and autofilling variables from org-mode into the buffer. It will also
7277 recognize item context in multiline items.
7278 Note that turning off orgstruct-mode will *not* remove the
7279 indentation/paragraph settings. This can only be done by refreshing the
7280 major mode, for example with \\[normal-mode]."
7281 (interactive "P")
7282 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7283 (if (< arg 1)
7284 (orgstruct-mode -1)
7285 (orgstruct-mode 1)
7286 (let (var val)
7287 (mapc
7288 (lambda (x)
7289 (when (string-match
7290 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7291 (symbol-name (car x)))
7292 (setq var (car x) val (nth 1 x))
7293 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7294 org-local-vars)
7295 (org-set-local 'orgstruct-is-++ t))))
7297 (defvar orgstruct-is-++ nil
7298 "Is orgstruct-mode in ++ version in the current-buffer?")
7299 (make-variable-buffer-local 'orgstruct-is-++)
7301 ;;;###autoload
7302 (defun turn-on-orgstruct++ ()
7303 "Unconditionally turn on `orgstruct++-mode'."
7304 (orgstruct++-mode 1))
7306 (defun orgstruct-error ()
7307 "Error when there is no default binding for a structure key."
7308 (interactive)
7309 (error "This key has no function outside structure elements"))
7311 (defun orgstruct-setup ()
7312 "Setup orgstruct keymaps."
7313 (let ((nfunc 0)
7314 (bindings
7315 (list
7316 '([(meta up)] org-metaup)
7317 '([(meta down)] org-metadown)
7318 '([(meta left)] org-metaleft)
7319 '([(meta right)] org-metaright)
7320 '([(meta shift up)] org-shiftmetaup)
7321 '([(meta shift down)] org-shiftmetadown)
7322 '([(meta shift left)] org-shiftmetaleft)
7323 '([(meta shift right)] org-shiftmetaright)
7324 '([?\e (up)] org-metaup)
7325 '([?\e (down)] org-metadown)
7326 '([?\e (left)] org-metaleft)
7327 '([?\e (right)] org-metaright)
7328 '([?\e (shift up)] org-shiftmetaup)
7329 '([?\e (shift down)] org-shiftmetadown)
7330 '([?\e (shift left)] org-shiftmetaleft)
7331 '([?\e (shift right)] org-shiftmetaright)
7332 '([(shift up)] org-shiftup)
7333 '([(shift down)] org-shiftdown)
7334 '([(shift left)] org-shiftleft)
7335 '([(shift right)] org-shiftright)
7336 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7337 '("\M-q" fill-paragraph)
7338 '("\C-c^" org-sort)
7339 '("\C-c-" org-cycle-list-bullet)))
7340 elt key fun cmd)
7341 (while (setq elt (pop bindings))
7342 (setq nfunc (1+ nfunc))
7343 (setq key (org-key (car elt))
7344 fun (nth 1 elt)
7345 cmd (orgstruct-make-binding fun nfunc key))
7346 (org-defkey orgstruct-mode-map key cmd))
7348 ;; Special treatment needed for TAB and RET
7349 (org-defkey orgstruct-mode-map [(tab)]
7350 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7351 (org-defkey orgstruct-mode-map "\C-i"
7352 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7354 (org-defkey orgstruct-mode-map "\M-\C-m"
7355 (orgstruct-make-binding 'org-insert-heading 105
7356 "\M-\C-m" [(meta return)]))
7357 (org-defkey orgstruct-mode-map [(meta return)]
7358 (orgstruct-make-binding 'org-insert-heading 106
7359 [(meta return)] "\M-\C-m"))
7361 (org-defkey orgstruct-mode-map [(shift meta return)]
7362 (orgstruct-make-binding 'org-insert-todo-heading 107
7363 [(meta return)] "\M-\C-m"))
7365 (org-defkey orgstruct-mode-map "\e\C-m"
7366 (orgstruct-make-binding 'org-insert-heading 108
7367 "\e\C-m" [?\e (return)]))
7368 (org-defkey orgstruct-mode-map [?\e (return)]
7369 (orgstruct-make-binding 'org-insert-heading 109
7370 [?\e (return)] "\e\C-m"))
7371 (org-defkey orgstruct-mode-map [?\e (shift return)]
7372 (orgstruct-make-binding 'org-insert-todo-heading 110
7373 [?\e (return)] "\e\C-m"))
7375 (unless org-local-vars
7376 (setq org-local-vars (org-get-local-variables)))
7380 (defun orgstruct-make-binding (fun n &rest keys)
7381 "Create a function for binding in the structure minor mode.
7382 FUN is the command to call inside a table. N is used to create a unique
7383 command name. KEYS are keys that should be checked in for a command
7384 to execute outside of tables."
7385 (eval
7386 (list 'defun
7387 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7388 '(arg)
7389 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7390 "Outside of structure, run the binding of `"
7391 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7392 "'.")
7393 '(interactive "p")
7394 (list 'if
7395 `(org-context-p 'headline 'item
7396 (and orgstruct-is-++
7397 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7398 'item-body))
7399 (list 'org-run-like-in-org-mode (list 'quote fun))
7400 (list 'let '(orgstruct-mode)
7401 (list 'call-interactively
7402 (append '(or)
7403 (mapcar (lambda (k)
7404 (list 'key-binding k))
7405 keys)
7406 '('orgstruct-error))))))))
7408 (defun org-context-p (&rest contexts)
7409 "Check if local context is any of CONTEXTS.
7410 Possible values in the list of contexts are `table', `headline', and `item'."
7411 (let ((pos (point)))
7412 (goto-char (point-at-bol))
7413 (prog1 (or (and (memq 'table contexts)
7414 (looking-at "[ \t]*|"))
7415 (and (memq 'headline contexts)
7416 ;;????????? (looking-at "\\*+"))
7417 (looking-at outline-regexp))
7418 (and (memq 'item contexts)
7419 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7420 (and (memq 'item-body contexts)
7421 (org-in-item-p)))
7422 (goto-char pos))))
7424 (defun org-get-local-variables ()
7425 "Return a list of all local variables in an org-mode buffer."
7426 (let (varlist)
7427 (with-current-buffer (get-buffer-create "*Org tmp*")
7428 (erase-buffer)
7429 (org-mode)
7430 (setq varlist (buffer-local-variables)))
7431 (kill-buffer "*Org tmp*")
7432 (delq nil
7433 (mapcar
7434 (lambda (x)
7435 (setq x
7436 (if (symbolp x)
7437 (list x)
7438 (list (car x) (list 'quote (cdr x)))))
7439 (if (string-match
7440 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7441 (symbol-name (car x)))
7442 x nil))
7443 varlist))))
7445 ;;;###autoload
7446 (defun org-run-like-in-org-mode (cmd)
7447 "Run a command, pretending that the current buffer is in Org-mode.
7448 This will temporarily bind local variables that are typically bound in
7449 Org-mode to the values they have in Org-mode, and then interactively
7450 call CMD."
7451 (org-load-modules-maybe)
7452 (unless org-local-vars
7453 (setq org-local-vars (org-get-local-variables)))
7454 (eval (list 'let org-local-vars
7455 (list 'call-interactively (list 'quote cmd)))))
7457 ;;;; Archiving
7459 (defun org-get-category (&optional pos)
7460 "Get the category applying to position POS."
7461 (get-text-property (or pos (point)) 'org-category))
7463 (defun org-refresh-category-properties ()
7464 "Refresh category text properties in the buffer."
7465 (let ((def-cat (cond
7466 ((null org-category)
7467 (if buffer-file-name
7468 (file-name-sans-extension
7469 (file-name-nondirectory buffer-file-name))
7470 "???"))
7471 ((symbolp org-category) (symbol-name org-category))
7472 (t org-category)))
7473 beg end cat pos optionp)
7474 (org-unmodified
7475 (save-excursion
7476 (save-restriction
7477 (widen)
7478 (goto-char (point-min))
7479 (put-text-property (point) (point-max) 'org-category def-cat)
7480 (while (re-search-forward
7481 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7482 (setq pos (match-end 0)
7483 optionp (equal (char-after (match-beginning 0)) ?#)
7484 cat (org-trim (match-string 2)))
7485 (if optionp
7486 (setq beg (point-at-bol) end (point-max))
7487 (org-back-to-heading t)
7488 (setq beg (point) end (org-end-of-subtree t t)))
7489 (put-text-property beg end 'org-category cat)
7490 (goto-char pos)))))))
7493 ;;;; Link Stuff
7495 ;;; Link abbreviations
7497 (defun org-link-expand-abbrev (link)
7498 "Apply replacements as defined in `org-link-abbrev-alist."
7499 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7500 (let* ((key (match-string 1 link))
7501 (as (or (assoc key org-link-abbrev-alist-local)
7502 (assoc key org-link-abbrev-alist)))
7503 (tag (and (match-end 2) (match-string 3 link)))
7504 rpl)
7505 (if (not as)
7506 link
7507 (setq rpl (cdr as))
7508 (cond
7509 ((symbolp rpl) (funcall rpl tag))
7510 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7511 ((string-match "%h" rpl)
7512 (replace-match (url-hexify-string (or tag "")) t t rpl))
7513 (t (concat rpl tag)))))
7514 link))
7516 ;;; Storing and inserting links
7518 (defvar org-insert-link-history nil
7519 "Minibuffer history for links inserted with `org-insert-link'.")
7521 (defvar org-stored-links nil
7522 "Contains the links stored with `org-store-link'.")
7524 (defvar org-store-link-plist nil
7525 "Plist with info about the most recently link created with `org-store-link'.")
7527 (defvar org-link-protocols nil
7528 "Link protocols added to Org-mode using `org-add-link-type'.")
7530 (defvar org-store-link-functions nil
7531 "List of functions that are called to create and store a link.
7532 Each function will be called in turn until one returns a non-nil
7533 value. Each function should check if it is responsible for creating
7534 this link (for example by looking at the major mode).
7535 If not, it must exit and return nil.
7536 If yes, it should return a non-nil value after a calling
7537 `org-store-link-props' with a list of properties and values.
7538 Special properties are:
7540 :type The link prefix. like \"http\". This must be given.
7541 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7542 This is obligatory as well.
7543 :description Optional default description for the second pair
7544 of brackets in an Org-mode link. The user can still change
7545 this when inserting this link into an Org-mode buffer.
7547 In addition to these, any additional properties can be specified
7548 and then used in remember templates.")
7550 (defun org-add-link-type (type &optional follow export)
7551 "Add TYPE to the list of `org-link-types'.
7552 Re-compute all regular expressions depending on `org-link-types'
7554 FOLLOW and EXPORT are two functions.
7556 FOLLOW should take the link path as the single argument and do whatever
7557 is necessary to follow the link, for example find a file or display
7558 a mail message.
7560 EXPORT should format the link path for export to one of the export formats.
7561 It should be a function accepting three arguments:
7563 path the path of the link, the text after the prefix (like \"http:\")
7564 desc the description of the link, if any, nil if there was no description
7565 format the export format, a symbol like `html' or `latex'.
7567 The function may use the FORMAT information to return different values
7568 depending on the format. The return value will be put literally into
7569 the exported file.
7570 Org-mode has a built-in default for exporting links. If you are happy with
7571 this default, there is no need to define an export function for the link
7572 type. For a simple example of an export function, see `org-bbdb.el'."
7573 (add-to-list 'org-link-types type t)
7574 (org-make-link-regexps)
7575 (if (assoc type org-link-protocols)
7576 (setcdr (assoc type org-link-protocols) (list follow export))
7577 (push (list type follow export) org-link-protocols)))
7579 (defvar org-agenda-buffer-name)
7581 ;;;###autoload
7582 (defun org-store-link (arg)
7583 "\\<org-mode-map>Store an org-link to the current location.
7584 This link is added to `org-stored-links' and can later be inserted
7585 into an org-buffer with \\[org-insert-link].
7587 For some link types, a prefix arg is interpreted:
7588 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7589 For file links, arg negates `org-context-in-file-links'."
7590 (interactive "P")
7591 (org-load-modules-maybe)
7592 (setq org-store-link-plist nil) ; reset
7593 (let ((outline-regexp (org-get-limited-outline-regexp))
7594 link cpltxt desc description search txt custom-id)
7595 (cond
7597 ((run-hook-with-args-until-success 'org-store-link-functions)
7598 (setq link (plist-get org-store-link-plist :link)
7599 desc (or (plist-get org-store-link-plist :description) link)))
7601 ((equal (buffer-name) "*Org Edit Src Example*")
7602 (let (label gc)
7603 (while (or (not label)
7604 (save-excursion
7605 (save-restriction
7606 (widen)
7607 (goto-char (point-min))
7608 (re-search-forward
7609 (regexp-quote (format org-coderef-label-format label))
7610 nil t))))
7611 (when label (message "Label exists already") (sit-for 2))
7612 (setq label (read-string "Code line label: " label)))
7613 (end-of-line 1)
7614 (setq link (format org-coderef-label-format label))
7615 (setq gc (- 79 (length link)))
7616 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7617 (insert link)
7618 (setq link (concat "(" label ")") desc nil)))
7620 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7621 ;; We are in the agenda, link to referenced location
7622 (let ((m (or (get-text-property (point) 'org-hd-marker)
7623 (get-text-property (point) 'org-marker))))
7624 (when m
7625 (org-with-point-at m
7626 (call-interactively 'org-store-link)))))
7628 ((eq major-mode 'calendar-mode)
7629 (let ((cd (calendar-cursor-to-date)))
7630 (setq link
7631 (format-time-string
7632 (car org-time-stamp-formats)
7633 (apply 'encode-time
7634 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7635 nil nil nil))))
7636 (org-store-link-props :type "calendar" :date cd)))
7638 ((eq major-mode 'w3-mode)
7639 (setq cpltxt (if (and (buffer-name)
7640 (not (string-match "Untitled" (buffer-name))))
7641 (buffer-name)
7642 (url-view-url t))
7643 link (org-make-link (url-view-url t)))
7644 (org-store-link-props :type "w3" :url (url-view-url t)))
7646 ((eq major-mode 'w3m-mode)
7647 (setq cpltxt (or w3m-current-title w3m-current-url)
7648 link (org-make-link w3m-current-url))
7649 (org-store-link-props :type "w3m" :url (url-view-url t)))
7651 ((setq search (run-hook-with-args-until-success
7652 'org-create-file-search-functions))
7653 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7654 "::" search))
7655 (setq cpltxt (or description link)))
7657 ((eq major-mode 'image-mode)
7658 (setq cpltxt (concat "file:"
7659 (abbreviate-file-name buffer-file-name))
7660 link (org-make-link cpltxt))
7661 (org-store-link-props :type "image" :file buffer-file-name))
7663 ((eq major-mode 'dired-mode)
7664 ;; link to the file in the current line
7665 (setq cpltxt (concat "file:"
7666 (abbreviate-file-name
7667 (expand-file-name
7668 (dired-get-filename nil t))))
7669 link (org-make-link cpltxt)))
7671 ((and buffer-file-name (org-mode-p))
7672 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7673 (cond
7674 ((org-in-regexp "<<\\(.*?\\)>>")
7675 (setq cpltxt
7676 (concat "file:"
7677 (abbreviate-file-name buffer-file-name)
7678 "::" (match-string 1))
7679 link (org-make-link cpltxt)))
7680 ((and (featurep 'org-id)
7681 (or (eq org-link-to-org-use-id t)
7682 (and (eq org-link-to-org-use-id 'create-if-interactive)
7683 (interactive-p))
7684 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7685 (interactive-p)
7686 (not custom-id))
7687 (and org-link-to-org-use-id
7688 (condition-case nil
7689 (org-entry-get nil "ID")
7690 (error nil)))))
7691 ;; We can make a link using the ID.
7692 (setq link (condition-case nil
7693 (prog1 (org-id-store-link)
7694 (setq desc (plist-get org-store-link-plist
7695 :description)))
7696 (error
7697 ;; probably before first headline, link to file only
7698 (concat "file:"
7699 (abbreviate-file-name buffer-file-name))))))
7701 ;; Just link to current headline
7702 (setq cpltxt (concat "file:"
7703 (abbreviate-file-name buffer-file-name)))
7704 ;; Add a context search string
7705 (when (org-xor org-context-in-file-links arg)
7706 (setq txt (cond
7707 ((org-on-heading-p) nil)
7708 ((org-region-active-p)
7709 (buffer-substring (region-beginning) (region-end)))
7710 (t nil)))
7711 (when (or (null txt) (string-match "\\S-" txt))
7712 (setq cpltxt
7713 (concat cpltxt "::"
7714 (condition-case nil
7715 (org-make-org-heading-search-string txt)
7716 (error "")))
7717 desc (or (nth 4 (ignore-errors
7718 (org-heading-components))) "NONE"))))
7719 (if (string-match "::\\'" cpltxt)
7720 (setq cpltxt (substring cpltxt 0 -2)))
7721 (setq link (org-make-link cpltxt)))))
7723 ((buffer-file-name (buffer-base-buffer))
7724 ;; Just link to this file here.
7725 (setq cpltxt (concat "file:"
7726 (abbreviate-file-name
7727 (buffer-file-name (buffer-base-buffer)))))
7728 ;; Add a context string
7729 (when (org-xor org-context-in-file-links arg)
7730 (setq txt (if (org-region-active-p)
7731 (buffer-substring (region-beginning) (region-end))
7732 (buffer-substring (point-at-bol) (point-at-eol))))
7733 ;; Only use search option if there is some text.
7734 (when (string-match "\\S-" txt)
7735 (setq cpltxt
7736 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7737 desc "NONE")))
7738 (setq link (org-make-link cpltxt)))
7740 ((interactive-p)
7741 (error "Cannot link to a buffer which is not visiting a file"))
7743 (t (setq link nil)))
7745 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7746 (setq link (or link cpltxt)
7747 desc (or desc cpltxt))
7748 (if (equal desc "NONE") (setq desc nil))
7750 (if (and (or (interactive-p) executing-kbd-macro) link)
7751 (progn
7752 (setq org-stored-links
7753 (cons (list link desc) org-stored-links))
7754 (message "Stored: %s" (or desc link))
7755 (when custom-id
7756 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7757 "::#" custom-id))
7758 (setq org-stored-links
7759 (cons (list link desc) org-stored-links))))
7760 (and link (org-make-link-string link desc)))))
7762 (defun org-store-link-props (&rest plist)
7763 "Store link properties, extract names and addresses."
7764 (let (x adr)
7765 (when (setq x (plist-get plist :from))
7766 (setq adr (mail-extract-address-components x))
7767 (setq plist (plist-put plist :fromname (car adr)))
7768 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7769 (when (setq x (plist-get plist :to))
7770 (setq adr (mail-extract-address-components x))
7771 (setq plist (plist-put plist :toname (car adr)))
7772 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7773 (let ((from (plist-get plist :from))
7774 (to (plist-get plist :to)))
7775 (when (and from to org-from-is-user-regexp)
7776 (setq plist
7777 (plist-put plist :fromto
7778 (if (string-match org-from-is-user-regexp from)
7779 (concat "to %t")
7780 (concat "from %f"))))))
7781 (setq org-store-link-plist plist))
7783 (defun org-add-link-props (&rest plist)
7784 "Add these properties to the link property list."
7785 (let (key value)
7786 (while plist
7787 (setq key (pop plist) value (pop plist))
7788 (setq org-store-link-plist
7789 (plist-put org-store-link-plist key value)))))
7791 (defun org-email-link-description (&optional fmt)
7792 "Return the description part of an email link.
7793 This takes information from `org-store-link-plist' and formats it
7794 according to FMT (default from `org-email-link-description-format')."
7795 (setq fmt (or fmt org-email-link-description-format))
7796 (let* ((p org-store-link-plist)
7797 (to (plist-get p :toaddress))
7798 (from (plist-get p :fromaddress))
7799 (table
7800 (list
7801 (cons "%c" (plist-get p :fromto))
7802 (cons "%F" (plist-get p :from))
7803 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7804 (cons "%T" (plist-get p :to))
7805 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7806 (cons "%s" (plist-get p :subject))
7807 (cons "%m" (plist-get p :message-id)))))
7808 (when (string-match "%c" fmt)
7809 ;; Check if the user wrote this message
7810 (if (and org-from-is-user-regexp from to
7811 (save-match-data (string-match org-from-is-user-regexp from)))
7812 (setq fmt (replace-match "to %t" t t fmt))
7813 (setq fmt (replace-match "from %f" t t fmt))))
7814 (org-replace-escapes fmt table)))
7816 (defun org-make-org-heading-search-string (&optional string heading)
7817 "Make search string for STRING or current headline."
7818 (interactive)
7819 (let ((s (or string (org-get-heading))))
7820 (unless (and string (not heading))
7821 ;; We are using a headline, clean up garbage in there.
7822 (if (string-match org-todo-regexp s)
7823 (setq s (replace-match "" t t s)))
7824 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7825 (setq s (replace-match "" t t s)))
7826 (setq s (org-trim s))
7827 (if (string-match (concat "^\\(" org-quote-string "\\|"
7828 org-comment-string "\\)") s)
7829 (setq s (replace-match "" t t s)))
7830 (while (string-match org-ts-regexp s)
7831 (setq s (replace-match "" t t s))))
7832 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7833 (setq s (replace-match " " t t s)))
7834 (or string (setq s (concat "*" s))) ; Add * for headlines
7835 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7837 (defun org-make-link (&rest strings)
7838 "Concatenate STRINGS."
7839 (apply 'concat strings))
7841 (defun org-make-link-string (link &optional description)
7842 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7843 (unless (string-match "\\S-" link)
7844 (error "Empty link"))
7845 (when (and description
7846 (stringp description)
7847 (not (string-match "\\S-" description)))
7848 (setq description nil))
7849 (when (stringp description)
7850 ;; Remove brackets from the description, they are fatal.
7851 (while (string-match "\\[" description)
7852 (setq description (replace-match "{" t t description)))
7853 (while (string-match "\\]" description)
7854 (setq description (replace-match "}" t t description))))
7855 (when (equal (org-link-escape link) description)
7856 ;; No description needed, it is identical
7857 (setq description nil))
7858 (when (and (not description)
7859 (not (equal link (org-link-escape link))))
7860 (setq description (org-extract-attributes link)))
7861 (concat "[[" (org-link-escape link) "]"
7862 (if description (concat "[" description "]") "")
7863 "]"))
7865 (defconst org-link-escape-chars
7866 '((?\ . "%20")
7867 (?\[ . "%5B")
7868 (?\] . "%5D")
7869 (?\340 . "%E0") ; `a
7870 (?\342 . "%E2") ; ^a
7871 (?\347 . "%E7") ; ,c
7872 (?\350 . "%E8") ; `e
7873 (?\351 . "%E9") ; 'e
7874 (?\352 . "%EA") ; ^e
7875 (?\356 . "%EE") ; ^i
7876 (?\364 . "%F4") ; ^o
7877 (?\371 . "%F9") ; `u
7878 (?\373 . "%FB") ; ^u
7879 (?\; . "%3B")
7880 (?? . "%3F")
7881 (?= . "%3D")
7882 (?+ . "%2B")
7884 "Association list of escapes for some characters problematic in links.
7885 This is the list that is used for internal purposes.")
7887 (defvar org-url-encoding-use-url-hexify nil)
7889 (defconst org-link-escape-chars-browser
7890 '((?\ . "%20")) ; 32 for the SPC char
7891 "Association list of escapes for some characters problematic in links.
7892 This is the list that is used before handing over to the browser.")
7894 (defun org-link-escape (text &optional table)
7895 "Escape characters in TEXT that are problematic for links."
7896 (if org-url-encoding-use-url-hexify
7897 (url-hexify-string text)
7898 (setq table (or table org-link-escape-chars))
7899 (when text
7900 (let ((re (mapconcat (lambda (x) (regexp-quote
7901 (char-to-string (car x))))
7902 table "\\|")))
7903 (while (string-match re text)
7904 (setq text
7905 (replace-match
7906 (cdr (assoc (string-to-char (match-string 0 text))
7907 table))
7908 t t text)))
7909 text))))
7911 (defun org-link-unescape (text &optional table)
7912 "Reverse the action of `org-link-escape'."
7913 (if org-url-encoding-use-url-hexify
7914 (url-unhex-string text)
7915 (setq table (or table org-link-escape-chars))
7916 (when text
7917 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7918 table "\\|")))
7919 (while (string-match re text)
7920 (setq text
7921 (replace-match
7922 (char-to-string (car (rassoc (match-string 0 text) table)))
7923 t t text)))
7924 text))))
7926 (defun org-xor (a b)
7927 "Exclusive or."
7928 (if a (not b) b))
7930 (defun org-fixup-message-id-for-http (s)
7931 "Replace special characters in a message id, so it can be used in an http query."
7932 (while (string-match "<" s)
7933 (setq s (replace-match "%3C" t t s)))
7934 (while (string-match ">" s)
7935 (setq s (replace-match "%3E" t t s)))
7936 (while (string-match "@" s)
7937 (setq s (replace-match "%40" t t s)))
7940 ;;;###autoload
7941 (defun org-insert-link-global ()
7942 "Insert a link like Org-mode does.
7943 This command can be called in any mode to insert a link in Org-mode syntax."
7944 (interactive)
7945 (org-load-modules-maybe)
7946 (org-run-like-in-org-mode 'org-insert-link))
7948 (defun org-insert-link (&optional complete-file link-location)
7949 "Insert a link. At the prompt, enter the link.
7951 Completion can be used to insert any of the link protocol prefixes like
7952 http or ftp in use.
7954 The history can be used to select a link previously stored with
7955 `org-store-link'. When the empty string is entered (i.e. if you just
7956 press RET at the prompt), the link defaults to the most recently
7957 stored link. As SPC triggers completion in the minibuffer, you need to
7958 use M-SPC or C-q SPC to force the insertion of a space character.
7960 You will also be prompted for a description, and if one is given, it will
7961 be displayed in the buffer instead of the link.
7963 If there is already a link at point, this command will allow you to edit link
7964 and description parts.
7966 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7967 be selected using completion. The path to the file will be relative to the
7968 current directory if the file is in the current directory or a subdirectory.
7969 Otherwise, the link will be the absolute path as completed in the minibuffer
7970 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7971 option `org-link-file-path-type'.
7973 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7974 the current directory or below.
7976 With three \\[universal-argument] prefixes, negate the meaning of
7977 `org-keep-stored-link-after-insertion'.
7979 If `org-make-link-description-function' is non-nil, this function will be
7980 called with the link target, and the result will be the default
7981 link description.
7983 If the LINK-LOCATION parameter is non-nil, this value will be
7984 used as the link location instead of reading one interactively."
7985 (interactive "P")
7986 (let* ((wcf (current-window-configuration))
7987 (region (if (org-region-active-p)
7988 (buffer-substring (region-beginning) (region-end))))
7989 (remove (and region (list (region-beginning) (region-end))))
7990 (desc region)
7991 tmphist ; byte-compile incorrectly complains about this
7992 (link link-location)
7993 entry file all-prefixes)
7994 (cond
7995 (link-location) ; specified by arg, just use it.
7996 ((org-in-regexp org-bracket-link-regexp 1)
7997 ;; We do have a link at point, and we are going to edit it.
7998 (setq remove (list (match-beginning 0) (match-end 0)))
7999 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8000 (setq link (read-string "Link: "
8001 (org-link-unescape
8002 (org-match-string-no-properties 1)))))
8003 ((or (org-in-regexp org-angle-link-re)
8004 (org-in-regexp org-plain-link-re))
8005 ;; Convert to bracket link
8006 (setq remove (list (match-beginning 0) (match-end 0))
8007 link (read-string "Link: "
8008 (org-remove-angle-brackets (match-string 0)))))
8009 ((member complete-file '((4) (16)))
8010 ;; Completing read for file names.
8011 (setq link (org-file-complete-link complete-file)))
8013 ;; Read link, with completion for stored links.
8014 (with-output-to-temp-buffer "*Org Links*"
8015 (princ "Insert a link.
8016 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8017 (when org-stored-links
8018 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8019 (princ (mapconcat
8020 (lambda (x)
8021 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8022 (reverse org-stored-links) "\n"))))
8023 (let ((cw (selected-window)))
8024 (select-window (get-buffer-window "*Org Links*"))
8025 (setq truncate-lines t)
8026 (unless (pos-visible-in-window-p (point-max))
8027 (org-fit-window-to-buffer))
8028 (and (window-live-p cw) (select-window cw)))
8029 ;; Fake a link history, containing the stored links.
8030 (setq tmphist (append (mapcar 'car org-stored-links)
8031 org-insert-link-history))
8032 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8033 (mapcar 'car org-link-abbrev-alist)
8034 org-link-types))
8035 (unwind-protect
8036 (progn
8037 (setq link
8038 (let ((org-completion-use-ido nil)
8039 (org-completion-use-iswitchb nil))
8040 (org-completing-read
8041 "Link: "
8042 (append
8043 (mapcar (lambda (x) (list (concat x ":")))
8044 all-prefixes)
8045 (mapcar 'car org-stored-links))
8046 nil nil nil
8047 'tmphist
8048 (car (car org-stored-links)))))
8049 (if (not (string-match "\\S-" link))
8050 (error "No link selected"))
8051 (if (or (member link all-prefixes)
8052 (and (equal ":" (substring link -1))
8053 (member (substring link 0 -1) all-prefixes)
8054 (setq link (substring link 0 -1))))
8055 (setq link (org-link-try-special-completion link))))
8056 (set-window-configuration wcf)
8057 (kill-buffer "*Org Links*"))
8058 (setq entry (assoc link org-stored-links))
8059 (or entry (push link org-insert-link-history))
8060 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8061 (not org-keep-stored-link-after-insertion))
8062 (setq org-stored-links (delq (assoc link org-stored-links)
8063 org-stored-links)))
8064 (setq desc (or desc (nth 1 entry)))))
8066 (if (string-match org-plain-link-re link)
8067 ;; URL-like link, normalize the use of angular brackets.
8068 (setq link (org-make-link (org-remove-angle-brackets link))))
8070 ;; Check if we are linking to the current file with a search option
8071 ;; If yes, simplify the link by using only the search option.
8072 (when (and buffer-file-name
8073 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8074 (let* ((path (match-string 1 link))
8075 (case-fold-search nil)
8076 (search (match-string 2 link)))
8077 (save-match-data
8078 (if (equal (file-truename buffer-file-name) (file-truename path))
8079 ;; We are linking to this same file, with a search option
8080 (setq link search)))))
8082 ;; Check if we can/should use a relative path. If yes, simplify the link
8083 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8084 (let* ((type (match-string 1 link))
8085 (path (match-string 2 link))
8086 (origpath path)
8087 (case-fold-search nil))
8088 (cond
8089 ((or (eq org-link-file-path-type 'absolute)
8090 (equal complete-file '(16)))
8091 (setq path (abbreviate-file-name (expand-file-name path))))
8092 ((eq org-link-file-path-type 'noabbrev)
8093 (setq path (expand-file-name path)))
8094 ((eq org-link-file-path-type 'relative)
8095 (setq path (file-relative-name path)))
8097 (save-match-data
8098 (if (string-match (concat "^" (regexp-quote
8099 (file-name-as-directory
8100 (expand-file-name "."))))
8101 (expand-file-name path))
8102 ;; We are linking a file with relative path name.
8103 (setq path (substring (expand-file-name path)
8104 (match-end 0)))
8105 (setq path (abbreviate-file-name (expand-file-name path)))))))
8106 (setq link (concat type path))
8107 (if (equal desc origpath)
8108 (setq desc path))))
8110 (if org-make-link-description-function
8111 (setq desc (funcall org-make-link-description-function link desc)))
8113 (setq desc (read-string "Description: " desc))
8114 (unless (string-match "\\S-" desc) (setq desc nil))
8115 (if remove (apply 'delete-region remove))
8116 (insert (org-make-link-string link desc))))
8118 (defun org-link-try-special-completion (type)
8119 "If there is completion support for link type TYPE, offer it."
8120 (let ((fun (intern (concat "org-" type "-complete-link"))))
8121 (if (functionp fun)
8122 (funcall fun)
8123 (read-string "Link (no completion support): " (concat type ":")))))
8125 (defun org-file-complete-link (&optional arg)
8126 "Create a file link using completion."
8127 (let (file link)
8128 (setq file (read-file-name "File: "))
8129 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8130 (pwd1 (file-name-as-directory (abbreviate-file-name
8131 (expand-file-name ".")))))
8132 (cond
8133 ((equal arg '(16))
8134 (setq link (org-make-link
8135 "file:"
8136 (abbreviate-file-name (expand-file-name file)))))
8137 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8138 (setq link (org-make-link "file:" (match-string 1 file))))
8139 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8140 (expand-file-name file))
8141 (setq link (org-make-link
8142 "file:" (match-string 1 (expand-file-name file)))))
8143 (t (setq link (org-make-link "file:" file)))))
8144 link))
8146 (defun org-completing-read (&rest args)
8147 "Completing-read with SPACE being a normal character."
8148 (let ((minibuffer-local-completion-map
8149 (copy-keymap minibuffer-local-completion-map)))
8150 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8151 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8152 (apply 'org-icompleting-read args)))
8154 (defun org-completing-read-no-i (&rest args)
8155 (let (org-completion-use-ido org-completion-use-iswitchb)
8156 (apply 'org-completing-read args)))
8158 (defun org-iswitchb-completing-read (prompt choices &rest args)
8159 "Use iswitch as a completing-read replacement to choose from choices.
8160 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8161 from."
8162 (let* ((iswitchb-use-virtual-buffers nil)
8163 (iswitchb-make-buflist-hook
8164 (lambda ()
8165 (setq iswitchb-temp-buflist choices))))
8166 (iswitchb-read-buffer prompt)))
8168 (defun org-icompleting-read (&rest args)
8169 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8170 (org-without-partial-completion
8171 (if (and org-completion-use-ido
8172 (fboundp 'ido-completing-read)
8173 (boundp 'ido-mode) ido-mode
8174 (listp (second args)))
8175 (let ((ido-enter-matching-directory nil))
8176 (apply 'ido-completing-read (concat (car args))
8177 (if (consp (car (nth 1 args)))
8178 (mapcar (lambda (x) (car x)) (nth 1 args))
8179 (nth 1 args))
8180 (cddr args)))
8181 (if (and org-completion-use-iswitchb
8182 (boundp 'iswitchb-mode) iswitchb-mode
8183 (listp (second args)))
8184 (apply 'org-iswitchb-completing-read (concat (car args))
8185 (if (consp (car (nth 1 args)))
8186 (mapcar (lambda (x) (car x)) (nth 1 args))
8187 (nth 1 args))
8188 (cddr args))
8189 (apply 'completing-read args)))))
8191 (defun org-extract-attributes (s)
8192 "Extract the attributes cookie from a string and set as text property."
8193 (let (a attr (start 0) key value)
8194 (save-match-data
8195 (when (string-match "{{\\([^}]+\\)}}$" s)
8196 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8197 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8198 (setq key (match-string 1 a) value (match-string 2 a)
8199 start (match-end 0)
8200 attr (plist-put attr (intern key) value))))
8201 (org-add-props s nil 'org-attr attr))
8204 (defun org-extract-attributes-from-string (tag)
8205 (let (key value attr)
8206 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8207 (setq key (match-string 1 tag) value (match-string 2 tag)
8208 tag (replace-match "" t t tag)
8209 attr (plist-put attr (intern key) value)))
8210 (cons tag attr)))
8212 (defun org-attributes-to-string (plist)
8213 "Format a property list into an HTML attribute list."
8214 (let ((s "") key value)
8215 (while plist
8216 (setq key (pop plist) value (pop plist))
8217 (and value
8218 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8221 ;;; Opening/following a link
8223 (defvar org-link-search-failed nil)
8225 (defvar org-open-link-functions nil
8226 "Hook for functions finding a plain text link.
8227 These functions must take a single argument, the link content.
8228 They will be called for links that look like [[link text][description]]
8229 when LINK TEXT does not have a protocol like \"http:\" and does not look
8230 like a filename (e.g. \"./blue.png\").
8232 These functions will be called *before* Org attempts to resolve the
8233 link by doing text searches in the current buffer - so if you want a
8234 link \"[[target]]\" to still find \"<<target>>\", your function should
8235 handle this as a special case.
8237 When the function does handle the link, it must return a non-nil value.
8238 If it decides that it is not responsible for this link, it must return
8239 nil to indicate that that Org-mode can continue with other options
8240 like exact and fuzzy text search.")
8242 (defun org-next-link ()
8243 "Move forward to the next link.
8244 If the link is in hidden text, expose it."
8245 (interactive)
8246 (when (and org-link-search-failed (eq this-command last-command))
8247 (goto-char (point-min))
8248 (message "Link search wrapped back to beginning of buffer"))
8249 (setq org-link-search-failed nil)
8250 (let* ((pos (point))
8251 (ct (org-context))
8252 (a (assoc :link ct)))
8253 (if a (goto-char (nth 2 a)))
8254 (if (re-search-forward org-any-link-re nil t)
8255 (progn
8256 (goto-char (match-beginning 0))
8257 (if (org-invisible-p) (org-show-context)))
8258 (goto-char pos)
8259 (setq org-link-search-failed t)
8260 (error "No further link found"))))
8262 (defun org-previous-link ()
8263 "Move backward to the previous link.
8264 If the link is in hidden text, expose it."
8265 (interactive)
8266 (when (and org-link-search-failed (eq this-command last-command))
8267 (goto-char (point-max))
8268 (message "Link search wrapped back to end of buffer"))
8269 (setq org-link-search-failed nil)
8270 (let* ((pos (point))
8271 (ct (org-context))
8272 (a (assoc :link ct)))
8273 (if a (goto-char (nth 1 a)))
8274 (if (re-search-backward org-any-link-re nil t)
8275 (progn
8276 (goto-char (match-beginning 0))
8277 (if (org-invisible-p) (org-show-context)))
8278 (goto-char pos)
8279 (setq org-link-search-failed t)
8280 (error "No further link found"))))
8282 (defun org-translate-link (s)
8283 "Translate a link string if a translation function has been defined."
8284 (if (and org-link-translation-function
8285 (fboundp org-link-translation-function)
8286 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8287 (progn
8288 (setq s (funcall org-link-translation-function
8289 (match-string 1) (match-string 2)))
8290 (concat (car s) ":" (cdr s)))
8293 (defun org-translate-link-from-planner (type path)
8294 "Translate a link from Emacs Planner syntax so that Org can follow it.
8295 This is still an experimental function, your mileage may vary."
8296 (cond
8297 ((member type '("http" "https" "news" "ftp"))
8298 ;; standard Internet links are the same.
8299 nil)
8300 ((and (equal type "irc") (string-match "^//" path))
8301 ;; Planner has two / at the beginning of an irc link, we have 1.
8302 ;; We should have zero, actually....
8303 (setq path (substring path 1)))
8304 ((and (equal type "lisp") (string-match "^/" path))
8305 ;; Planner has a slash, we do not.
8306 (setq type "elisp" path (substring path 1)))
8307 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8308 ;; A typical message link. Planner has the id after the final slash,
8309 ;; we separate it with a hash mark
8310 (setq path (concat (match-string 1 path) "#"
8311 (org-remove-angle-brackets (match-string 2 path)))))
8313 (cons type path))
8315 (defun org-find-file-at-mouse (ev)
8316 "Open file link or URL at mouse."
8317 (interactive "e")
8318 (mouse-set-point ev)
8319 (org-open-at-point 'in-emacs))
8321 (defun org-open-at-mouse (ev)
8322 "Open file link or URL at mouse."
8323 (interactive "e")
8324 (mouse-set-point ev)
8325 (if (eq major-mode 'org-agenda-mode)
8326 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8327 (org-open-at-point))
8329 (defvar org-window-config-before-follow-link nil
8330 "The window configuration before following a link.
8331 This is saved in case the need arises to restore it.")
8333 (defvar org-open-link-marker (make-marker)
8334 "Marker pointing to the location where `org-open-at-point; was called.")
8336 ;;;###autoload
8337 (defun org-open-at-point-global ()
8338 "Follow a link like Org-mode does.
8339 This command can be called in any mode to follow a link that has
8340 Org-mode syntax."
8341 (interactive)
8342 (org-run-like-in-org-mode 'org-open-at-point))
8344 ;;;###autoload
8345 (defun org-open-link-from-string (s &optional arg reference-buffer)
8346 "Open a link in the string S, as if it was in Org-mode."
8347 (interactive "sLink: \nP")
8348 (let ((reference-buffer (or reference-buffer (current-buffer))))
8349 (with-temp-buffer
8350 (let ((org-inhibit-startup t))
8351 (org-mode)
8352 (insert s)
8353 (goto-char (point-min))
8354 (org-open-at-point arg reference-buffer)))))
8356 (defun org-open-at-point (&optional in-emacs reference-buffer)
8357 "Open link at or after point.
8358 If there is no link at point, this function will search forward up to
8359 the end of the current line.
8360 Normally, files will be opened by an appropriate application. If the
8361 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8362 With a double prefix argument, try to open outside of Emacs, in the
8363 application the system uses for this file type."
8364 (interactive "P")
8365 (org-load-modules-maybe)
8366 (move-marker org-open-link-marker (point))
8367 (setq org-window-config-before-follow-link (current-window-configuration))
8368 (org-remove-occur-highlights nil nil t)
8369 (cond
8370 ((and (org-on-heading-p)
8371 (not (org-in-regexp
8372 (concat org-plain-link-re "\\|"
8373 org-bracket-link-regexp "\\|"
8374 org-angle-link-re "\\|"
8375 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8376 (or (org-offer-links-in-entry in-emacs)
8377 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8378 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8379 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8380 (org-footnote-action))
8382 (let (type path link line search (pos (point)))
8383 (catch 'match
8384 (save-excursion
8385 (skip-chars-forward "^]\n\r")
8386 (when (org-in-regexp org-bracket-link-regexp 1)
8387 (setq link (org-extract-attributes
8388 (org-link-unescape (org-match-string-no-properties 1))))
8389 (while (string-match " *\n *" link)
8390 (setq link (replace-match " " t t link)))
8391 (setq link (org-link-expand-abbrev link))
8392 (cond
8393 ((or (file-name-absolute-p link)
8394 (string-match "^\\.\\.?/" link))
8395 (setq type "file" path link))
8396 ((string-match org-link-re-with-space3 link)
8397 (setq type (match-string 1 link) path (match-string 2 link)))
8398 (t (setq type "thisfile" path link)))
8399 (throw 'match t)))
8401 (when (get-text-property (point) 'org-linked-text)
8402 (setq type "thisfile"
8403 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8404 (1+ (point)) (point))
8405 path (buffer-substring
8406 (previous-single-property-change pos 'org-linked-text)
8407 (next-single-property-change pos 'org-linked-text)))
8408 (throw 'match t))
8410 (save-excursion
8411 (when (or (org-in-regexp org-angle-link-re)
8412 (org-in-regexp org-plain-link-re))
8413 (setq type (match-string 1) path (match-string 2))
8414 (throw 'match t)))
8415 (save-excursion
8416 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8417 (setq type "tags"
8418 path (match-string 1))
8419 (while (string-match ":" path)
8420 (setq path (replace-match "+" t t path)))
8421 (throw 'match t)))
8422 (when (org-in-regexp "<\\([^><\n]+\\)>")
8423 (setq type "tree-match"
8424 path (match-string 1))
8425 (throw 'match t)))
8426 (unless path
8427 (error "No link found"))
8429 ;; switch back to reference buffer
8430 ;; needed when if called in a temporary buffer through
8431 ;; org-open-link-from-string
8432 (with-current-buffer (or reference-buffer (current-buffer))
8434 ;; Remove any trailing spaces in path
8435 (if (string-match " +\\'" path)
8436 (setq path (replace-match "" t t path)))
8437 (if (and org-link-translation-function
8438 (fboundp org-link-translation-function))
8439 ;; Check if we need to translate the link
8440 (let ((tmp (funcall org-link-translation-function type path)))
8441 (setq type (car tmp) path (cdr tmp))))
8443 (cond
8445 ((assoc type org-link-protocols)
8446 (funcall (nth 1 (assoc type org-link-protocols)) path))
8448 ((equal type "mailto")
8449 (let ((cmd (car org-link-mailto-program))
8450 (args (cdr org-link-mailto-program)) args1
8451 (address path) (subject "") a)
8452 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8453 (setq address (match-string 1 path)
8454 subject (org-link-escape (match-string 2 path))))
8455 (while args
8456 (cond
8457 ((not (stringp (car args))) (push (pop args) args1))
8458 (t (setq a (pop args))
8459 (if (string-match "%a" a)
8460 (setq a (replace-match address t t a)))
8461 (if (string-match "%s" a)
8462 (setq a (replace-match subject t t a)))
8463 (push a args1))))
8464 (apply cmd (nreverse args1))))
8466 ((member type '("http" "https" "ftp" "news"))
8467 (browse-url (concat type ":" (org-link-escape
8468 path org-link-escape-chars-browser))))
8470 ((member type '("message"))
8471 (browse-url (concat type ":" path)))
8473 ((string= type "tags")
8474 (org-tags-view in-emacs path))
8476 ((string= type "tree-match")
8477 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8479 ((string= type "file")
8480 (if (string-match "::\\([0-9]+\\)\\'" path)
8481 (setq line (string-to-number (match-string 1 path))
8482 path (substring path 0 (match-beginning 0)))
8483 (if (string-match "::\\(.+\\)\\'" path)
8484 (setq search (match-string 1 path)
8485 path (substring path 0 (match-beginning 0)))))
8486 (if (string-match "[*?{]" (file-name-nondirectory path))
8487 (dired path)
8488 (org-open-file path in-emacs line search)))
8490 ((string= type "news")
8491 (require 'org-gnus)
8492 (org-gnus-follow-link path))
8494 ((string= type "shell")
8495 (let ((cmd path))
8496 (if (or (not org-confirm-shell-link-function)
8497 (funcall org-confirm-shell-link-function
8498 (format "Execute \"%s\" in shell? "
8499 (org-add-props cmd nil
8500 'face 'org-warning))))
8501 (progn
8502 (message "Executing %s" cmd)
8503 (shell-command cmd))
8504 (error "Abort"))))
8506 ((string= type "elisp")
8507 (let ((cmd path))
8508 (if (or (not org-confirm-elisp-link-function)
8509 (funcall org-confirm-elisp-link-function
8510 (format "Execute \"%s\" as elisp? "
8511 (org-add-props cmd nil
8512 'face 'org-warning))))
8513 (message "%s => %s" cmd
8514 (if (equal (string-to-char cmd) ?\()
8515 (eval (read cmd))
8516 (call-interactively (read cmd))))
8517 (error "Abort"))))
8519 ((and (string= type "thisfile")
8520 (run-hook-with-args-until-success
8521 'org-open-link-functions path)))
8523 ((string= type "thisfile")
8524 (if in-emacs
8525 (switch-to-buffer-other-window
8526 (org-get-buffer-for-internal-link (current-buffer)))
8527 (org-mark-ring-push))
8528 (let ((cmd `(org-link-search
8529 ,path
8530 ,(cond ((equal in-emacs '(4)) 'occur)
8531 ((equal in-emacs '(16)) 'org-occur)
8532 (t nil))
8533 ,pos)))
8534 (condition-case nil (eval cmd)
8535 (error (progn (widen) (eval cmd))))))
8538 (browse-url-at-point)))))))
8539 (move-marker org-open-link-marker nil)
8540 (run-hook-with-args 'org-follow-link-hook))
8542 (defun org-offer-links-in-entry (&optional nth zero)
8543 "Offer links in the current entry and follow the selected link.
8544 If there is only one link, follow it immediately as well.
8545 If NTH is an integer, immediately pick the NTH link found.
8546 If ZERO is a string, check also this string for a link, and if
8547 there is one, offer it as link number zero."
8548 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8549 "\\(" org-angle-link-re "\\)\\|"
8550 "\\(" org-plain-link-re "\\)"))
8551 (cnt ?0)
8552 (in-emacs (if (integerp nth) nil nth))
8553 have-zero end links link c)
8554 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8555 (push (match-string 0 zero) links)
8556 (setq cnt (1- cnt) have-zero t))
8557 (save-excursion
8558 (org-back-to-heading t)
8559 (setq end (save-excursion (outline-next-heading) (point)))
8560 (while (re-search-forward re end t)
8561 (push (match-string 0) links))
8562 (setq links (org-uniquify (reverse links))))
8564 (cond
8565 ((null links)
8566 (message "No links"))
8567 ((equal (length links) 1)
8568 (setq link (list (car links))))
8569 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8570 (setq link (nth (if have-zero nth (1- nth)) links)))
8571 (t ; we have to select a link
8572 (save-excursion
8573 (save-window-excursion
8574 (delete-other-windows)
8575 (with-output-to-temp-buffer "*Select Link*"
8576 (mapc (lambda (l)
8577 (if (not (string-match org-bracket-link-regexp l))
8578 (princ (format "[%c] %s\n" (incf cnt)
8579 (org-remove-angle-brackets l)))
8580 (if (match-end 3)
8581 (princ (format "[%c] %s (%s)\n" (incf cnt)
8582 (match-string 3 l) (match-string 1 l)))
8583 (princ (format "[%c] %s\n" (incf cnt)
8584 (match-string 1 l))))))
8585 links))
8586 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8587 (message "Select link to open, RET to open all:")
8588 (setq c (read-char-exclusive))
8589 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8590 (when (equal c ?q) (error "Abort"))
8591 (if (equal c ?\C-m)
8592 (setq link links)
8593 (setq nth (- c ?0))
8594 (if have-zero (setq nth (1+ nth)))
8595 (unless (and (integerp nth) (>= (length links) nth))
8596 (error "Invalid link selection"))
8597 (setq link (list (nth (1- nth) links))))))
8598 (if link
8599 (let ((buf (current-buffer)))
8600 (dolist (l link)
8601 (org-open-link-from-string l in-emacs buf))
8603 nil)))
8605 ;; Add special file links that specify the way of opening
8607 (org-add-link-type "file+sys" 'org-open-file-with-system)
8608 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8609 (defun org-open-file-with-system (path)
8610 "Open file at PATH using the system way of opeing it."
8611 (org-open-file path 'system))
8612 (defun org-open-file-with-emacs (path)
8613 "Open file at PATH in emacs."
8614 (org-open-file path 'emacs))
8615 (defun org-remove-file-link-modifiers ()
8616 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8617 (goto-char (point-min))
8618 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8619 (org-if-unprotected
8620 (replace-match "file:" t t))))
8621 (eval-after-load "org-exp"
8622 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8623 'org-remove-file-link-modifiers))
8625 ;;;; Time estimates
8627 (defun org-get-effort (&optional pom)
8628 "Get the effort estimate for the current entry."
8629 (org-entry-get pom org-effort-property))
8631 ;;; File search
8633 (defvar org-create-file-search-functions nil
8634 "List of functions to construct the right search string for a file link.
8635 These functions are called in turn with point at the location to
8636 which the link should point.
8638 A function in the hook should first test if it would like to
8639 handle this file type, for example by checking the major-mode or
8640 the file extension. If it decides not to handle this file, it
8641 should just return nil to give other functions a chance. If it
8642 does handle the file, it must return the search string to be used
8643 when following the link. The search string will be part of the
8644 file link, given after a double colon, and `org-open-at-point'
8645 will automatically search for it. If special measures must be
8646 taken to make the search successful, another function should be
8647 added to the companion hook `org-execute-file-search-functions',
8648 which see.
8650 A function in this hook may also use `setq' to set the variable
8651 `description' to provide a suggestion for the descriptive text to
8652 be used for this link when it gets inserted into an Org-mode
8653 buffer with \\[org-insert-link].")
8655 (defvar org-execute-file-search-functions nil
8656 "List of functions to execute a file search triggered by a link.
8658 Functions added to this hook must accept a single argument, the
8659 search string that was part of the file link, the part after the
8660 double colon. The function must first check if it would like to
8661 handle this search, for example by checking the major-mode or the
8662 file extension. If it decides not to handle this search, it
8663 should just return nil to give other functions a chance. If it
8664 does handle the search, it must return a non-nil value to keep
8665 other functions from trying.
8667 Each function can access the current prefix argument through the
8668 variable `current-prefix-argument'. Note that a single prefix is
8669 used to force opening a link in Emacs, so it may be good to only
8670 use a numeric or double prefix to guide the search function.
8672 In case this is needed, a function in this hook can also restore
8673 the window configuration before `org-open-at-point' was called using:
8675 (set-window-configuration org-window-config-before-follow-link)")
8677 (defun org-link-search (s &optional type avoid-pos)
8678 "Search for a link search option.
8679 If S is surrounded by forward slashes, it is interpreted as a
8680 regular expression. In org-mode files, this will create an `org-occur'
8681 sparse tree. In ordinary files, `occur' will be used to list matches.
8682 If the current buffer is in `dired-mode', grep will be used to search
8683 in all files. If AVOID-POS is given, ignore matches near that position."
8684 (let ((case-fold-search t)
8685 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8686 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8687 (append '(("") (" ") ("\t") ("\n"))
8688 org-emphasis-alist)
8689 "\\|") "\\)"))
8690 (pos (point))
8691 (pre nil) (post nil)
8692 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8693 (cond
8694 ;; First check if there are any special
8695 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8696 ;; Now try the builtin stuff
8697 ((and (equal (string-to-char s0) ?#)
8698 (> (length s0) 1)
8699 (save-excursion
8700 (goto-char (point-min))
8701 (and
8702 (re-search-forward
8703 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8704 (setq type 'dedicated
8705 pos (match-beginning 0))))
8706 ;; There is an exact target for this
8707 (goto-char pos)
8708 (org-back-to-heading t)))
8709 ((save-excursion
8710 (goto-char (point-min))
8711 (and
8712 (re-search-forward
8713 (concat "<<" (regexp-quote s0) ">>") nil t)
8714 (setq type 'dedicated
8715 pos (match-beginning 0))))
8716 ;; There is an exact target for this
8717 (goto-char pos))
8718 ((and (string-match "^(\\(.*\\))$" s0)
8719 (save-excursion
8720 (goto-char (point-min))
8721 (and
8722 (re-search-forward
8723 (concat "[^[]" (regexp-quote
8724 (format org-coderef-label-format
8725 (match-string 1 s0))))
8726 nil t)
8727 (setq type 'dedicated
8728 pos (1+ (match-beginning 0))))))
8729 ;; There is a coderef target for this
8730 (goto-char pos))
8731 ((string-match "^/\\(.*\\)/$" s)
8732 ;; A regular expression
8733 (cond
8734 ((org-mode-p)
8735 (org-occur (match-string 1 s)))
8736 ;;((eq major-mode 'dired-mode)
8737 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8738 (t (org-do-occur (match-string 1 s)))))
8740 ;; A normal search strings
8741 (when (equal (string-to-char s) ?*)
8742 ;; Anchor on headlines, post may include tags.
8743 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8744 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8745 s (substring s 1)))
8746 (remove-text-properties
8747 0 (length s)
8748 '(face nil mouse-face nil keymap nil fontified nil) s)
8749 ;; Make a series of regular expressions to find a match
8750 (setq words (org-split-string s "[ \n\r\t]+")
8752 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8753 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8754 "\\)" markers)
8755 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8756 re2a (concat "[ \t\r\n]" re2a_)
8757 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8758 re4 (concat "[^a-zA-Z_]" re4_)
8760 re1 (concat pre re2 post)
8761 re3 (concat pre (if pre re4_ re4) post)
8762 re5 (concat pre ".*" re4)
8763 re2 (concat pre re2)
8764 re2a (concat pre (if pre re2a_ re2a))
8765 re4 (concat pre (if pre re4_ re4))
8766 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8767 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8768 re5 "\\)"
8770 (cond
8771 ((eq type 'org-occur) (org-occur reall))
8772 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8773 (t (goto-char (point-min))
8774 (setq type 'fuzzy)
8775 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8776 (org-search-not-self 1 re1 nil t)
8777 (org-search-not-self 1 re2 nil t)
8778 (org-search-not-self 1 re2a nil t)
8779 (org-search-not-self 1 re3 nil t)
8780 (org-search-not-self 1 re4 nil t)
8781 (org-search-not-self 1 re5 nil t)
8783 (goto-char (match-beginning 1))
8784 (goto-char pos)
8785 (error "No match")))))
8787 ;; Normal string-search
8788 (goto-char (point-min))
8789 (if (search-forward s nil t)
8790 (goto-char (match-beginning 0))
8791 (error "No match"))))
8792 (and (org-mode-p) (org-show-context 'link-search))
8793 type))
8795 (defun org-search-not-self (group &rest args)
8796 "Execute `re-search-forward', but only accept matches that do not
8797 enclose the position of `org-open-link-marker'."
8798 (let ((m org-open-link-marker))
8799 (catch 'exit
8800 (while (apply 're-search-forward args)
8801 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8802 (goto-char (match-end group))
8803 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8804 (> (match-beginning 0) (marker-position m))
8805 (< (match-end 0) (marker-position m)))
8806 (save-match-data
8807 (or (not (org-in-regexp
8808 org-bracket-link-analytic-regexp 1))
8809 (not (match-end 4)) ; no description
8810 (and (<= (match-beginning 4) (point))
8811 (>= (match-end 4) (point))))))
8812 (throw 'exit (point))))))))
8814 (defun org-get-buffer-for-internal-link (buffer)
8815 "Return a buffer to be used for displaying the link target of internal links."
8816 (cond
8817 ((not org-display-internal-link-with-indirect-buffer)
8818 buffer)
8819 ((string-match "(Clone)$" (buffer-name buffer))
8820 (message "Buffer is already a clone, not making another one")
8821 ;; we also do not modify visibility in this case
8822 buffer)
8823 (t ; make a new indirect buffer for displaying the link
8824 (let* ((bn (buffer-name buffer))
8825 (ibn (concat bn "(Clone)"))
8826 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8827 (with-current-buffer ib (org-overview))
8828 ib))))
8830 (defun org-do-occur (regexp &optional cleanup)
8831 "Call the Emacs command `occur'.
8832 If CLEANUP is non-nil, remove the printout of the regular expression
8833 in the *Occur* buffer. This is useful if the regex is long and not useful
8834 to read."
8835 (occur regexp)
8836 (when cleanup
8837 (let ((cwin (selected-window)) win beg end)
8838 (when (setq win (get-buffer-window "*Occur*"))
8839 (select-window win))
8840 (goto-char (point-min))
8841 (when (re-search-forward "match[a-z]+" nil t)
8842 (setq beg (match-end 0))
8843 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8844 (setq end (1- (match-beginning 0)))))
8845 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8846 (goto-char (point-min))
8847 (select-window cwin))))
8849 ;;; The mark ring for links jumps
8851 (defvar org-mark-ring nil
8852 "Mark ring for positions before jumps in Org-mode.")
8853 (defvar org-mark-ring-last-goto nil
8854 "Last position in the mark ring used to go back.")
8855 ;; Fill and close the ring
8856 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8857 (loop for i from 1 to org-mark-ring-length do
8858 (push (make-marker) org-mark-ring))
8859 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8860 org-mark-ring)
8862 (defun org-mark-ring-push (&optional pos buffer)
8863 "Put the current position or POS into the mark ring and rotate it."
8864 (interactive)
8865 (setq pos (or pos (point)))
8866 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8867 (move-marker (car org-mark-ring)
8868 (or pos (point))
8869 (or buffer (current-buffer)))
8870 (message "%s"
8871 (substitute-command-keys
8872 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8874 (defun org-mark-ring-goto (&optional n)
8875 "Jump to the previous position in the mark ring.
8876 With prefix arg N, jump back that many stored positions. When
8877 called several times in succession, walk through the entire ring.
8878 Org-mode commands jumping to a different position in the current file,
8879 or to another Org-mode file, automatically push the old position
8880 onto the ring."
8881 (interactive "p")
8882 (let (p m)
8883 (if (eq last-command this-command)
8884 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8885 (setq p org-mark-ring))
8886 (setq org-mark-ring-last-goto p)
8887 (setq m (car p))
8888 (switch-to-buffer (marker-buffer m))
8889 (goto-char m)
8890 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8892 (defun org-remove-angle-brackets (s)
8893 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8894 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8896 (defun org-add-angle-brackets (s)
8897 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8898 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8900 (defun org-remove-double-quotes (s)
8901 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8902 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8905 ;;; Following specific links
8907 (defun org-follow-timestamp-link ()
8908 (cond
8909 ((org-at-date-range-p t)
8910 (let ((org-agenda-start-on-weekday)
8911 (t1 (match-string 1))
8912 (t2 (match-string 2)))
8913 (setq t1 (time-to-days (org-time-string-to-time t1))
8914 t2 (time-to-days (org-time-string-to-time t2)))
8915 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8916 ((org-at-timestamp-p t)
8917 (org-agenda-list nil (time-to-days (org-time-string-to-time
8918 (substring (match-string 1) 0 10)))
8920 (t (error "This should not happen"))))
8923 ;;; Following file links
8924 (defvar org-wait nil)
8925 (defun org-open-file (path &optional in-emacs line search)
8926 "Open the file at PATH.
8927 First, this expands any special file name abbreviations. Then the
8928 configuration variable `org-file-apps' is checked if it contains an
8929 entry for this file type, and if yes, the corresponding command is launched.
8931 If no application is found, Emacs simply visits the file.
8933 With optional prefix argument IN-EMACS, Emacs will visit the file.
8934 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8935 and to use an external application to visit the file.
8937 Optional LINE specifies a line to go to, optional SEARCH a string to
8938 search for. If LINE or SEARCH is given, the file will always be
8939 opened in Emacs.
8940 If the file does not exist, an error is thrown."
8941 (setq in-emacs (or in-emacs line search))
8942 (let* ((file (if (equal path "")
8943 buffer-file-name
8944 (substitute-in-file-name (expand-file-name path))))
8945 (apps (append org-file-apps (org-default-apps)))
8946 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8947 (dirp (if remp nil (file-directory-p file)))
8948 (file (if (and dirp org-open-directory-means-index-dot-org)
8949 (concat (file-name-as-directory file) "index.org")
8950 file))
8951 (a-m-a-p (assq 'auto-mode apps))
8952 (dfile (downcase file))
8953 (old-buffer (current-buffer))
8954 (old-pos (point))
8955 (old-mode major-mode)
8956 ext cmd)
8957 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8958 (setq ext (match-string 1 dfile))
8959 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8960 (setq ext (match-string 1 dfile))))
8961 (cond
8962 ((member in-emacs '((16) system))
8963 (setq cmd (cdr (assoc 'system apps))))
8964 (in-emacs (setq cmd 'emacs))
8966 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8967 (and dirp (cdr (assoc 'directory apps)))
8968 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8969 'string-match)
8970 (cdr (assoc ext apps))
8971 (cdr (assoc t apps))))))
8972 (when (eq cmd 'system)
8973 (setq cmd (cdr (assoc 'system apps))))
8974 (when (eq cmd 'default)
8975 (setq cmd (cdr (assoc t apps))))
8976 (when (eq cmd 'mailcap)
8977 (require 'mailcap)
8978 (mailcap-parse-mailcaps)
8979 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8980 (command (mailcap-mime-info mime-type)))
8981 (if (stringp command)
8982 (setq cmd command)
8983 (setq cmd 'emacs))))
8984 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8985 (not (file-exists-p file))
8986 (not org-open-non-existing-files))
8987 (error "No such file: %s" file))
8988 (cond
8989 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8990 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8991 (while (string-match "['\"]%s['\"]" cmd)
8992 (setq cmd (replace-match "%s" t t cmd)))
8993 (while (string-match "%s" cmd)
8994 (setq cmd (replace-match
8995 (save-match-data
8996 (shell-quote-argument
8997 (convert-standard-filename file)))
8998 t t cmd)))
8999 (save-window-excursion
9000 (start-process-shell-command cmd nil cmd)
9001 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9003 ((or (stringp cmd)
9004 (eq cmd 'emacs))
9005 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9006 (widen)
9007 (if line (org-goto-line line)
9008 (if search (org-link-search search))))
9009 ((consp cmd)
9010 (let ((file (convert-standard-filename file)))
9011 (eval cmd)))
9012 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9013 (and (org-mode-p) (eq old-mode 'org-mode)
9014 (or (not (equal old-buffer (current-buffer)))
9015 (not (equal old-pos (point))))
9016 (org-mark-ring-push old-pos old-buffer))))
9018 (defun org-default-apps ()
9019 "Return the default applications for this operating system."
9020 (cond
9021 ((eq system-type 'darwin)
9022 org-file-apps-defaults-macosx)
9023 ((eq system-type 'windows-nt)
9024 org-file-apps-defaults-windowsnt)
9025 (t org-file-apps-defaults-gnu)))
9027 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9028 "Convert extensions to regular expressions in the cars of LIST.
9029 Also, weed out any non-string entries, because the return value is used
9030 only for regexp matching.
9031 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9032 point to the symbol `emacs', indicating that the file should
9033 be opened in Emacs."
9034 (append
9035 (delq nil
9036 (mapcar (lambda (x)
9037 (if (not (stringp (car x)))
9039 (if (string-match "\\W" (car x))
9041 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9042 list))
9043 (if add-auto-mode
9044 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9046 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9047 (defun org-file-remote-p (file)
9048 "Test whether FILE specifies a location on a remote system.
9049 Return non-nil if the location is indeed remote.
9051 For example, the filename \"/user@host:/foo\" specifies a location
9052 on the system \"/user@host:\"."
9053 (cond ((fboundp 'file-remote-p)
9054 (file-remote-p file))
9055 ((fboundp 'tramp-handle-file-remote-p)
9056 (tramp-handle-file-remote-p file))
9057 ((and (boundp 'ange-ftp-name-format)
9058 (string-match (car ange-ftp-name-format) file))
9060 (t nil)))
9063 ;;;; Refiling
9065 (defun org-get-org-file ()
9066 "Read a filename, with default directory `org-directory'."
9067 (let ((default (or org-default-notes-file remember-data-file)))
9068 (read-file-name (format "File name [%s]: " default)
9069 (file-name-as-directory org-directory)
9070 default)))
9072 (defun org-notes-order-reversed-p ()
9073 "Check if the current file should receive notes in reversed order."
9074 (cond
9075 ((not org-reverse-note-order) nil)
9076 ((eq t org-reverse-note-order) t)
9077 ((not (listp org-reverse-note-order)) nil)
9078 (t (catch 'exit
9079 (let ((all org-reverse-note-order)
9080 entry)
9081 (while (setq entry (pop all))
9082 (if (string-match (car entry) buffer-file-name)
9083 (throw 'exit (cdr entry))))
9084 nil)))))
9086 (defvar org-refile-target-table nil
9087 "The list of refile targets, created by `org-refile'.")
9089 (defvar org-agenda-new-buffers nil
9090 "Buffers created to visit agenda files.")
9092 (defun org-get-refile-targets (&optional default-buffer)
9093 "Produce a table with refile targets."
9094 (let ((case-fold-search nil)
9095 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9096 (entries (or org-refile-targets '((nil . (:level . 1)))))
9097 targets txt re files f desc descre fast-path-p level pos0)
9098 (message "Getting targets...")
9099 (with-current-buffer (or default-buffer (current-buffer))
9100 (while (setq entry (pop entries))
9101 (setq files (car entry) desc (cdr entry))
9102 (setq fast-path-p nil)
9103 (cond
9104 ((null files) (setq files (list (current-buffer))))
9105 ((eq files 'org-agenda-files)
9106 (setq files (org-agenda-files 'unrestricted)))
9107 ((and (symbolp files) (fboundp files))
9108 (setq files (funcall files)))
9109 ((and (symbolp files) (boundp files))
9110 (setq files (symbol-value files))))
9111 (if (stringp files) (setq files (list files)))
9112 (cond
9113 ((eq (car desc) :tag)
9114 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9115 ((eq (car desc) :todo)
9116 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9117 ((eq (car desc) :regexp)
9118 (setq descre (cdr desc)))
9119 ((eq (car desc) :level)
9120 (setq descre (concat "^\\*\\{" (number-to-string
9121 (if org-odd-levels-only
9122 (1- (* 2 (cdr desc)))
9123 (cdr desc)))
9124 "\\}[ \t]")))
9125 ((eq (car desc) :maxlevel)
9126 (setq fast-path-p t)
9127 (setq descre (concat "^\\*\\{1," (number-to-string
9128 (if org-odd-levels-only
9129 (1- (* 2 (cdr desc)))
9130 (cdr desc)))
9131 "\\}[ \t]")))
9132 (t (error "Bad refiling target description %s" desc)))
9133 (while (setq f (pop files))
9134 (with-current-buffer
9135 (if (bufferp f) f (org-get-agenda-file-buffer f))
9136 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9137 (setq f (and f (expand-file-name f)))
9138 (if (eq org-refile-use-outline-path 'file)
9139 (push (list (file-name-nondirectory f) f nil nil) targets))
9140 (save-excursion
9141 (save-restriction
9142 (widen)
9143 (goto-char (point-min))
9144 (while (re-search-forward descre nil t)
9145 (goto-char (setq pos0 (point-at-bol)))
9146 (catch 'next
9147 (when org-refile-target-verify-function
9148 (save-match-data
9149 (or (funcall org-refile-target-verify-function)
9150 (throw 'next t))))
9151 (when (looking-at org-complex-heading-regexp)
9152 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9153 txt (org-link-display-format (match-string 4))
9154 re (concat "^" (regexp-quote
9155 (buffer-substring (match-beginning 1)
9156 (match-end 4)))))
9157 (if (match-end 5) (setq re (concat re "[ \t]+"
9158 (regexp-quote
9159 (match-string 5)))))
9160 (setq re (concat re "[ \t]*$"))
9161 (when org-refile-use-outline-path
9162 (setq txt (mapconcat 'org-protect-slash
9163 (append
9164 (if (eq org-refile-use-outline-path 'file)
9165 (list (file-name-nondirectory
9166 (buffer-file-name (buffer-base-buffer))))
9167 (if (eq org-refile-use-outline-path 'full-file-path)
9168 (list (buffer-file-name (buffer-base-buffer)))))
9169 (org-get-outline-path fast-path-p level txt)
9170 (list txt))
9171 "/")))
9172 (push (list txt f re (point)) targets)))
9173 (when (= (point) pos0)
9174 ;; verification function has not moved point
9175 (goto-char (point-at-eol))))))))))
9176 (message "Getting targets...done")
9177 (nreverse targets)))
9179 (defun org-protect-slash (s)
9180 (while (string-match "/" s)
9181 (setq s (replace-match "\\" t t s)))
9184 (defvar org-olpa (make-vector 20 nil))
9186 (defun org-get-outline-path (&optional fastp level heading)
9187 "Return the outline path to the current entry, as a list.
9188 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9189 routine which makes outline path derivations for an entire file,
9190 avoiding backtracing."
9191 (if fastp
9192 (progn
9193 (if (> level 19)
9194 (error "Outline path failure, more than 19 levels."))
9195 (loop for i from level upto 19 do
9196 (aset org-olpa i nil))
9197 (prog1
9198 (delq nil (append org-olpa nil))
9199 (aset org-olpa level heading)))
9200 (let (rtn case-fold-search)
9201 (save-excursion
9202 (save-restriction
9203 (widen)
9204 (while (org-up-heading-safe)
9205 (when (looking-at org-complex-heading-regexp)
9206 (push (org-match-string-no-properties 4) rtn)))
9207 rtn)))))
9209 (defun org-format-outline-path (path &optional width prefix)
9210 "Format the outlie path PATH for display.
9211 Width is the maximum number of characters that is available.
9212 Prefix is a prefix to be included in the returned string,
9213 such as the file name."
9214 (setq width (or width 79))
9215 (if prefix (setq width (- width (length prefix))))
9216 (if (not path)
9217 (or prefix "")
9218 (let* ((nsteps (length path))
9219 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9220 (maxwidth (if (<= total-width width)
9221 10000 ;; everything fits
9222 ;; we need to shorten the level headings
9223 (/ (- width nsteps) nsteps)))
9224 (org-odd-levels-only nil)
9225 (n 0)
9226 (total (1+ (length prefix))))
9227 (setq maxwidth (max maxwidth 10))
9228 (concat prefix
9229 (mapconcat
9230 (lambda (h)
9231 (setq n (1+ n))
9232 (if (and (= n nsteps) (< maxwidth 10000))
9233 (setq maxwidth (- total-width total)))
9234 (if (< (length h) maxwidth)
9235 (progn (setq total (+ total (length h) 1)) h)
9236 (setq h (substring h 0 (- maxwidth 2))
9237 total (+ total maxwidth 1))
9238 (if (string-match "[ \t]+\\'" h)
9239 (setq h (substring h 0 (match-beginning 0))))
9240 (setq h (concat h "..")))
9241 (org-add-props h nil 'face
9242 (nth (% (1- n) org-n-level-faces)
9243 org-level-faces))
9245 path "/")))))
9247 (defun org-display-outline-path (&optional file current)
9248 "Display the current outline path in the echo area."
9249 (interactive "P")
9250 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9251 (case-fold-search nil)
9252 (path (and (org-mode-p) (org-get-outline-path))))
9253 (if current (setq path (append path
9254 (save-excursion
9255 (org-back-to-heading t)
9256 (if (looking-at org-complex-heading-regexp)
9257 (list (match-string 4)))))))
9258 (message "%s"
9259 (org-format-outline-path
9260 path
9261 (1- (frame-width))
9262 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9264 (defvar org-refile-history nil
9265 "History for refiling operations.")
9267 (defvar org-after-refile-insert-hook nil
9268 "Hook run after `org-refile' has inserted its stuff at the new location.
9269 Note that this is still *before* the stuff will be removed from
9270 the *old* location.")
9272 (defun org-refile (&optional goto default-buffer rfloc)
9273 "Move the entry at point to another heading.
9274 The list of target headings is compiled using the information in
9275 `org-refile-targets', which see. This list is created before each use
9276 and will therefore always be up-to-date.
9278 At the target location, the entry is filed as a subitem of the target heading.
9279 Depending on `org-reverse-note-order', the new subitem will either be the
9280 first or the last subitem.
9282 If there is an active region, all entries in that region will be moved.
9283 However, the region must fulfil the requirement that the first heading
9284 is the first one sets the top-level of the moved text - at most siblings
9285 below it are allowed.
9287 With prefix arg GOTO, the command will only visit the target location,
9288 not actually move anything.
9289 With a double prefix `C-u C-u', go to the location where the last refiling
9290 operation has put the subtree.
9291 With a prefix argument of `2', refile to the running clock.
9293 RFLOC can be a refile location obtained in a different way.
9295 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9296 (interactive "P")
9297 (let* ((cbuf (current-buffer))
9298 (regionp (org-region-active-p))
9299 (region-start (and regionp (region-beginning)))
9300 (region-end (and regionp (region-end)))
9301 (region-length (and regionp (- region-end region-start)))
9302 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9303 pos it nbuf file re level reversed)
9304 (setq last-command nil)
9305 (when regionp
9306 (goto-char region-start)
9307 (or (bolp) (goto-char (point-at-bol)))
9308 (setq region-start (point))
9309 (unless (org-kill-is-subtree-p
9310 (buffer-substring region-start region-end))
9311 (error "The region is not a (sequence of) subtree(s)")))
9312 (if (equal goto '(16))
9313 (org-refile-goto-last-stored)
9314 (when (or
9315 (and (equal goto 2)
9316 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9317 (prog1
9318 (setq it (list (or org-clock-heading "running clock")
9319 (buffer-file-name
9320 (marker-buffer org-clock-hd-marker))
9322 (marker-position org-clock-hd-marker)))
9323 (setq goto nil)))
9324 (setq it (or rfloc
9325 (save-excursion
9326 (org-refile-get-location
9327 (if goto "Goto: " "Refile to: ") default-buffer
9328 org-refile-allow-creating-parent-nodes)))))
9329 (setq file (nth 1 it)
9330 re (nth 2 it)
9331 pos (nth 3 it))
9332 (if (and (not goto)
9334 (equal (buffer-file-name) file)
9335 (if regionp
9336 (and (>= pos region-start)
9337 (<= pos region-end))
9338 (and (>= pos (point))
9339 (< pos (save-excursion
9340 (org-end-of-subtree t t))))))
9341 (error "Cannot refile to position inside the tree or region"))
9343 (setq nbuf (or (find-buffer-visiting file)
9344 (find-file-noselect file)))
9345 (if goto
9346 (progn
9347 (switch-to-buffer nbuf)
9348 (goto-char pos)
9349 (org-show-context 'org-goto))
9350 (if regionp
9351 (progn
9352 (org-kill-new (buffer-substring region-start region-end))
9353 (org-save-markers-in-region region-start region-end))
9354 (org-copy-subtree 1 nil t))
9355 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9356 (find-file-noselect file)))
9357 (setq reversed (org-notes-order-reversed-p))
9358 (save-excursion
9359 (save-restriction
9360 (widen)
9361 (if pos
9362 (progn
9363 (goto-char pos)
9364 (looking-at outline-regexp)
9365 (setq level (org-get-valid-level (funcall outline-level) 1))
9366 (goto-char
9367 (if reversed
9368 (or (outline-next-heading) (point-max))
9369 (or (save-excursion (org-get-next-sibling))
9370 (org-end-of-subtree t t)
9371 (point-max)))))
9372 (setq level 1)
9373 (if (not reversed)
9374 (goto-char (point-max))
9375 (goto-char (point-min))
9376 (or (outline-next-heading) (goto-char (point-max)))))
9377 (if (not (bolp)) (newline))
9378 (bookmark-set "org-refile-last-stored")
9379 (org-paste-subtree level)
9380 (if (fboundp 'deactivate-mark) (deactivate-mark))
9381 (run-hooks 'org-after-refile-insert-hook))))
9382 (if regionp
9383 (delete-region (point) (+ (point) region-length))
9384 (org-cut-subtree))
9385 (when (featurep 'org-inlinetask)
9386 (org-inlinetask-remove-END-maybe))
9387 (setq org-markers-to-move nil)
9388 (message "Refiled to \"%s\"" (car it))))))
9389 (org-reveal))
9391 (defun org-refile-goto-last-stored ()
9392 "Go to the location where the last refile was stored."
9393 (interactive)
9394 (bookmark-jump "org-refile-last-stored")
9395 (message "This is the location of the last refile"))
9397 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9398 "Prompt the user for a refile location, using PROMPT."
9399 (let ((org-refile-targets org-refile-targets)
9400 (org-refile-use-outline-path org-refile-use-outline-path))
9401 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9402 (unless org-refile-target-table
9403 (error "No refile targets"))
9404 (let* ((cbuf (current-buffer))
9405 (partial-completion-mode nil)
9406 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9407 (cfunc (if (and org-refile-use-outline-path
9408 org-outline-path-complete-in-steps)
9409 'org-olpath-completing-read
9410 'org-icompleting-read))
9411 (extra (if org-refile-use-outline-path "/" ""))
9412 (filename (and cfn (expand-file-name cfn)))
9413 (tbl (mapcar
9414 (lambda (x)
9415 (if (and (not (member org-refile-use-outline-path
9416 '(file full-file-path)))
9417 (not (equal filename (nth 1 x))))
9418 (cons (concat (car x) extra " ("
9419 (file-name-nondirectory (nth 1 x)) ")")
9420 (cdr x))
9421 (cons (concat (car x) extra) (cdr x))))
9422 org-refile-target-table))
9423 (completion-ignore-case t)
9424 pa answ parent-target child parent old-hist)
9425 (setq old-hist org-refile-history)
9426 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9427 nil 'org-refile-history))
9428 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9429 (if pa
9430 (progn
9431 (when (or (not org-refile-history)
9432 (not (eq old-hist org-refile-history))
9433 (not (equal (car pa) (car org-refile-history))))
9434 (setq org-refile-history
9435 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9436 org-refile-history
9437 (cdr org-refile-history))))
9438 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9439 (pop org-refile-history)))
9441 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9442 (setq parent (match-string 1 answ)
9443 child (match-string 2 answ))
9444 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9445 (when (and parent-target
9446 (or (eq new-nodes t)
9447 (and (eq new-nodes 'confirm)
9448 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9449 (org-refile-new-child parent-target child))))))
9451 (defun org-refile-new-child (parent-target child)
9452 "Use refile target PARENT-TARGET to add new CHILD below it."
9453 (unless parent-target
9454 (error "Cannot find parent for new node"))
9455 (let ((file (nth 1 parent-target))
9456 (pos (nth 3 parent-target))
9457 level)
9458 (with-current-buffer (or (find-buffer-visiting file)
9459 (find-file-noselect file))
9460 (save-excursion
9461 (save-restriction
9462 (widen)
9463 (if pos
9464 (goto-char pos)
9465 (goto-char (point-max))
9466 (if (not (bolp)) (newline)))
9467 (when (looking-at outline-regexp)
9468 (setq level (funcall outline-level))
9469 (org-end-of-subtree t t))
9470 (org-back-over-empty-lines)
9471 (insert "\n" (make-string
9472 (if pos (org-get-valid-level level 1) 1) ?*)
9473 " " child "\n")
9474 (beginning-of-line 0)
9475 (list (concat (car parent-target) "/" child) file "" (point)))))))
9477 (defun org-olpath-completing-read (prompt collection &rest args)
9478 "Read an outline path like a file name."
9479 (let ((thetable collection)
9480 (org-completion-use-ido nil) ; does not work with ido.
9481 (org-completion-use-iswitchb nil)) ; or iswitchb
9482 (apply
9483 'org-icompleting-read prompt
9484 (lambda (string predicate &optional flag)
9485 (let (rtn r f (l (length string)))
9486 (cond
9487 ((eq flag nil)
9488 ;; try completion
9489 (try-completion string thetable))
9490 ((eq flag t)
9491 ;; all-completions
9492 (setq rtn (all-completions string thetable predicate))
9493 (mapcar
9494 (lambda (x)
9495 (setq r (substring x l))
9496 (if (string-match " ([^)]*)$" x)
9497 (setq f (match-string 0 x))
9498 (setq f ""))
9499 (if (string-match "/" r)
9500 (concat string (substring r 0 (match-end 0)) f)
9502 rtn))
9503 ((eq flag 'lambda)
9504 ;; exact match?
9505 (assoc string thetable)))
9507 args)))
9509 ;;;; Dynamic blocks
9511 (defun org-find-dblock (name)
9512 "Find the first dynamic block with name NAME in the buffer.
9513 If not found, stay at current position and return nil."
9514 (let (pos)
9515 (save-excursion
9516 (goto-char (point-min))
9517 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9518 nil t)
9519 (match-beginning 0))))
9520 (if pos (goto-char pos))
9521 pos))
9523 (defconst org-dblock-start-re
9524 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9525 "Matches the start line of a dynamic block, with parameters.")
9527 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9528 "Matches the end of a dynamic block.")
9530 (defun org-create-dblock (plist)
9531 "Create a dynamic block section, with parameters taken from PLIST.
9532 PLIST must contain a :name entry which is used as name of the block."
9533 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9534 (end-of-line 1)
9535 (newline))
9536 (let ((col (current-column))
9537 (name (plist-get plist :name)))
9538 (insert "#+BEGIN: " name)
9539 (while plist
9540 (if (eq (car plist) :name)
9541 (setq plist (cddr plist))
9542 (insert " " (prin1-to-string (pop plist)))))
9543 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9544 (beginning-of-line -2)))
9546 (defun org-prepare-dblock ()
9547 "Prepare dynamic block for refresh.
9548 This empties the block, puts the cursor at the insert position and returns
9549 the property list including an extra property :name with the block name."
9550 (unless (looking-at org-dblock-start-re)
9551 (error "Not at a dynamic block"))
9552 (let* ((begdel (1+ (match-end 0)))
9553 (name (org-no-properties (match-string 1)))
9554 (params (append (list :name name)
9555 (read (concat "(" (match-string 3) ")")))))
9556 (save-excursion
9557 (beginning-of-line 1)
9558 (skip-chars-forward " \t")
9559 (setq params (plist-put params :indentation-column (current-column))))
9560 (unless (re-search-forward org-dblock-end-re nil t)
9561 (error "Dynamic block not terminated"))
9562 (setq params
9563 (append params
9564 (list :content (buffer-substring
9565 begdel (match-beginning 0)))))
9566 (delete-region begdel (match-beginning 0))
9567 (goto-char begdel)
9568 (open-line 1)
9569 params))
9571 (defun org-map-dblocks (&optional command)
9572 "Apply COMMAND to all dynamic blocks in the current buffer.
9573 If COMMAND is not given, use `org-update-dblock'."
9574 (let ((cmd (or command 'org-update-dblock))
9575 pos)
9576 (save-excursion
9577 (goto-char (point-min))
9578 (while (re-search-forward org-dblock-start-re nil t)
9579 (goto-char (setq pos (match-beginning 0)))
9580 (condition-case nil
9581 (funcall cmd)
9582 (error (message "Error during update of dynamic block")))
9583 (goto-char pos)
9584 (unless (re-search-forward org-dblock-end-re nil t)
9585 (error "Dynamic block not terminated"))))))
9587 (defun org-dblock-update (&optional arg)
9588 "User command for updating dynamic blocks.
9589 Update the dynamic block at point. With prefix ARG, update all dynamic
9590 blocks in the buffer."
9591 (interactive "P")
9592 (if arg
9593 (org-update-all-dblocks)
9594 (or (looking-at org-dblock-start-re)
9595 (org-beginning-of-dblock))
9596 (org-update-dblock)))
9598 (defun org-update-dblock ()
9599 "Update the dynamic block at point
9600 This means to empty the block, parse for parameters and then call
9601 the correct writing function."
9602 (save-window-excursion
9603 (let* ((pos (point))
9604 (line (org-current-line))
9605 (params (org-prepare-dblock))
9606 (name (plist-get params :name))
9607 (indent (plist-get params :indentation-column))
9608 (cmd (intern (concat "org-dblock-write:" name))))
9609 (message "Updating dynamic block `%s' at line %d..." name line)
9610 (funcall cmd params)
9611 (message "Updating dynamic block `%s' at line %d...done" name line)
9612 (goto-char pos)
9613 (when (and indent (> indent 0))
9614 (setq indent (make-string indent ?\ ))
9615 (save-excursion
9616 (org-beginning-of-dblock)
9617 (forward-line 1)
9618 (while (not (looking-at org-dblock-end-re))
9619 (insert indent)
9620 (beginning-of-line 2))
9621 (when (looking-at org-dblock-end-re)
9622 (and (looking-at "[ \t]+")
9623 (replace-match ""))
9624 (insert indent)))))))
9626 (defun org-beginning-of-dblock ()
9627 "Find the beginning of the dynamic block at point.
9628 Error if there is no such block at point."
9629 (let ((pos (point))
9630 beg)
9631 (end-of-line 1)
9632 (if (and (re-search-backward org-dblock-start-re nil t)
9633 (setq beg (match-beginning 0))
9634 (re-search-forward org-dblock-end-re nil t)
9635 (> (match-end 0) pos))
9636 (goto-char beg)
9637 (goto-char pos)
9638 (error "Not in a dynamic block"))))
9640 (defun org-update-all-dblocks ()
9641 "Update all dynamic blocks in the buffer.
9642 This function can be used in a hook."
9643 (when (org-mode-p)
9644 (org-map-dblocks 'org-update-dblock)))
9647 ;;;; Completion
9649 (defconst org-additional-option-like-keywords
9650 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9651 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9652 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9653 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9654 "BEGIN:" "END:"
9655 "ORGTBL" "TBLFM:" "TBLNAME:"
9656 "BEGIN_EXAMPLE" "END_EXAMPLE"
9657 "BEGIN_QUOTE" "END_QUOTE"
9658 "BEGIN_VERSE" "END_VERSE"
9659 "BEGIN_CENTER" "END_CENTER"
9660 "BEGIN_SRC" "END_SRC"
9661 "CATEGORY" "COLUMNS"
9662 "CAPTION" "LABEL"
9663 "SETUPFILE"
9664 "BIND"
9665 "MACRO"))
9667 (defcustom org-structure-template-alist
9669 ("s" "#+begin_src ?\n\n#+end_src"
9670 "<src lang=\"?\">\n\n</src>")
9671 ("e" "#+begin_example\n?\n#+end_example"
9672 "<example>\n?\n</example>")
9673 ("q" "#+begin_quote\n?\n#+end_quote"
9674 "<quote>\n?\n</quote>")
9675 ("v" "#+begin_verse\n?\n#+end_verse"
9676 "<verse>\n?\n/verse>")
9677 ("c" "#+begin_center\n?\n#+end_center"
9678 "<center>\n?\n/center>")
9679 ("l" "#+begin_latex\n?\n#+end_latex"
9680 "<literal style=\"latex\">\n?\n</literal>")
9681 ("L" "#+latex: "
9682 "<literal style=\"latex\">?</literal>")
9683 ("h" "#+begin_html\n?\n#+end_html"
9684 "<literal style=\"html\">\n?\n</literal>")
9685 ("H" "#+html: "
9686 "<literal style=\"html\">?</literal>")
9687 ("a" "#+begin_ascii\n?\n#+end_ascii")
9688 ("A" "#+ascii: ")
9689 ("i" "#+include %file ?"
9690 "<include file=%file markup=\"?\">")
9692 "Structure completion elements.
9693 This is a list of abbreviation keys and values. The value gets inserted
9694 it you type @samp{.} followed by the key and then the completion key,
9695 usually `M-TAB'. %file will be replaced by a file name after prompting
9696 for the file using completion.
9697 There are two templates for each key, the first uses the original Org syntax,
9698 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9699 the default when the /org-mtags.el/ module has been loaded. See also the
9700 variable `org-mtags-prefer-muse-templates'.
9701 This is an experimental feature, it is undecided if it is going to stay in."
9702 :group 'org-completion
9703 :type '(repeat
9704 (string :tag "Key")
9705 (string :tag "Template")
9706 (string :tag "Muse Template")))
9708 (defun org-try-structure-completion ()
9709 "Try to complete a structure template before point.
9710 This looks for strings like \"<e\" on an otherwise empty line and
9711 expands them."
9712 (let ((l (buffer-substring (point-at-bol) (point)))
9714 (when (and (looking-at "[ \t]*$")
9715 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9716 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9717 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9718 (match-beginning 1)) a)
9719 t)))
9721 (defun org-complete-expand-structure-template (start cell)
9722 "Expand a structure template."
9723 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9724 (rpl (nth (if musep 2 1) cell))
9725 (ind ""))
9726 (delete-region start (point))
9727 (when (string-match "\\`#\\+" rpl)
9728 (cond
9729 ((bolp))
9730 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9731 (setq ind (buffer-substring (point-at-bol) (point))))
9732 (t (newline))))
9733 (setq start (point))
9734 (if (string-match "%file" rpl)
9735 (setq rpl (replace-match
9736 (concat
9737 "\""
9738 (save-match-data
9739 (abbreviate-file-name (read-file-name "Include file: ")))
9740 "\"")
9741 t t rpl)))
9742 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9743 (concat "\n" ind)))
9744 (insert rpl)
9745 (if (re-search-backward "\\?" start t) (delete-char 1))))
9748 (defun org-complete (&optional arg)
9749 "Perform completion on word at point.
9750 At the beginning of a headline, this completes TODO keywords as given in
9751 `org-todo-keywords'.
9752 If the current word is preceded by a backslash, completes the TeX symbols
9753 that are supported for HTML support.
9754 If the current word is preceded by \"#+\", completes special words for
9755 setting file options.
9756 In the line after \"#+STARTUP:, complete valid keywords.\"
9757 At all other locations, this simply calls the value of
9758 `org-completion-fallback-command'."
9759 (interactive "P")
9760 (org-without-partial-completion
9761 (catch 'exit
9762 (let* ((a nil)
9763 (end (point))
9764 (beg1 (save-excursion
9765 (skip-chars-backward (org-re "[:alnum:]_@"))
9766 (point)))
9767 (beg (save-excursion
9768 (skip-chars-backward "a-zA-Z0-9_:$")
9769 (point)))
9770 (confirm (lambda (x) (stringp (car x))))
9771 (searchhead (equal (char-before beg) ?*))
9772 (struct
9773 (when (and (member (char-before beg1) '(?. ?<))
9774 (setq a (assoc (buffer-substring beg1 (point))
9775 org-structure-template-alist)))
9776 (org-complete-expand-structure-template (1- beg1) a)
9777 (throw 'exit t)))
9778 (tag (and (equal (char-before beg1) ?:)
9779 (equal (char-after (point-at-bol)) ?*)))
9780 (prop (and (equal (char-before beg1) ?:)
9781 (not (equal (char-after (point-at-bol)) ?*))))
9782 (texp (equal (char-before beg) ?\\))
9783 (link (equal (char-before beg) ?\[))
9784 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9785 beg)
9786 "#+"))
9787 (startup (string-match "^#\\+STARTUP:.*"
9788 (buffer-substring (point-at-bol) (point))))
9789 (completion-ignore-case opt)
9790 (type nil)
9791 (tbl nil)
9792 (table (cond
9793 (opt
9794 (setq type :opt)
9795 (require 'org-exp)
9796 (append
9797 (delq nil
9798 (mapcar
9799 (lambda (x)
9800 (if (string-match
9801 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9802 (cons (match-string 2 x)
9803 (match-string 1 x))))
9804 (org-split-string (org-get-current-options) "\n")))
9805 (mapcar 'list org-additional-option-like-keywords)))
9806 (startup
9807 (setq type :startup)
9808 org-startup-options)
9809 (link (append org-link-abbrev-alist-local
9810 org-link-abbrev-alist))
9811 (texp
9812 (setq type :tex)
9813 org-html-entities)
9814 ((string-match "\\`\\*+[ \t]+\\'"
9815 (buffer-substring (point-at-bol) beg))
9816 (setq type :todo)
9817 (mapcar 'list org-todo-keywords-1))
9818 (searchhead
9819 (setq type :searchhead)
9820 (save-excursion
9821 (goto-char (point-min))
9822 (while (re-search-forward org-todo-line-regexp nil t)
9823 (push (list
9824 (org-make-org-heading-search-string
9825 (match-string 3) t))
9826 tbl)))
9827 tbl)
9828 (tag (setq type :tag beg beg1)
9829 (or org-tag-alist (org-get-buffer-tags)))
9830 (prop (setq type :prop beg beg1)
9831 (mapcar 'list (org-buffer-property-keys nil t t)))
9832 (t (progn
9833 (call-interactively org-completion-fallback-command)
9834 (throw 'exit nil)))))
9835 (pattern (buffer-substring-no-properties beg end))
9836 (completion (try-completion pattern table confirm)))
9837 (cond ((eq completion t)
9838 (if (not (assoc (upcase pattern) table))
9839 (message "Already complete")
9840 (if (and (equal type :opt)
9841 (not (member (car (assoc (upcase pattern) table))
9842 org-additional-option-like-keywords)))
9843 (insert (substring (cdr (assoc (upcase pattern) table))
9844 (length pattern)))
9845 (if (memq type '(:tag :prop)) (insert ":")))))
9846 ((null completion)
9847 (message "Can't find completion for \"%s\"" pattern)
9848 (ding))
9849 ((not (string= pattern completion))
9850 (delete-region beg end)
9851 (if (string-match " +$" completion)
9852 (setq completion (replace-match "" t t completion)))
9853 (insert completion)
9854 (if (get-buffer-window "*Completions*")
9855 (delete-window (get-buffer-window "*Completions*")))
9856 (if (assoc completion table)
9857 (if (eq type :todo) (insert " ")
9858 (if (memq type '(:tag :prop)) (insert ":"))))
9859 (if (and (equal type :opt) (assoc completion table))
9860 (message "%s" (substitute-command-keys
9861 "Press \\[org-complete] again to insert example settings"))))
9863 (message "Making completion list...")
9864 (let ((list (sort (all-completions pattern table confirm)
9865 'string<)))
9866 (with-output-to-temp-buffer "*Completions*"
9867 (condition-case nil
9868 ;; Protection needed for XEmacs and emacs 21
9869 (display-completion-list list pattern)
9870 (error (display-completion-list list)))))
9871 (message "Making completion list...%s" "done")))))))
9873 ;;;; TODO, DEADLINE, Comments
9875 (defun org-toggle-comment ()
9876 "Change the COMMENT state of an entry."
9877 (interactive)
9878 (save-excursion
9879 (org-back-to-heading)
9880 (let (case-fold-search)
9881 (if (looking-at (concat outline-regexp
9882 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9883 (replace-match "" t t nil 1)
9884 (if (looking-at outline-regexp)
9885 (progn
9886 (goto-char (match-end 0))
9887 (insert org-comment-string " ")))))))
9889 (defvar org-last-todo-state-is-todo nil
9890 "This is non-nil when the last TODO state change led to a TODO state.
9891 If the last change removed the TODO tag or switched to DONE, then
9892 this is nil.")
9894 (defvar org-setting-tags nil) ; dynamically skipped
9896 (defun org-parse-local-options (string var)
9897 "Parse STRING for startup setting relevant for variable VAR."
9898 (let ((rtn (symbol-value var))
9899 e opts)
9900 (save-match-data
9901 (if (or (not string) (not (string-match "\\S-" string)))
9903 (setq opts (delq nil (mapcar (lambda (x)
9904 (setq e (assoc x org-startup-options))
9905 (if (eq (nth 1 e) var) e nil))
9906 (org-split-string string "[ \t]+"))))
9907 (if (not opts)
9909 (setq rtn nil)
9910 (while (setq e (pop opts))
9911 (if (not (nth 3 e))
9912 (setq rtn (nth 2 e))
9913 (if (not (listp rtn)) (setq rtn nil))
9914 (push (nth 2 e) rtn)))
9915 rtn)))))
9917 (defvar org-todo-setup-filter-hook nil
9918 "Hook for functions that pre-filter todo specs.
9920 Each function takes a todo spec and returns either `nil' or the spec
9921 transformed into canonical form." )
9923 (defvar org-todo-get-default-hook nil
9924 "Hook for functions that get a default item for todo.
9926 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9927 `nil' or a string to be used for the todo mark." )
9929 (defvar org-agenda-headline-snapshot-before-repeat)
9931 (defun org-todo (&optional arg)
9932 "Change the TODO state of an item.
9933 The state of an item is given by a keyword at the start of the heading,
9934 like
9935 *** TODO Write paper
9936 *** DONE Call mom
9938 The different keywords are specified in the variable `org-todo-keywords'.
9939 By default the available states are \"TODO\" and \"DONE\".
9940 So for this example: when the item starts with TODO, it is changed to DONE.
9941 When it starts with DONE, the DONE is removed. And when neither TODO nor
9942 DONE are present, add TODO at the beginning of the heading.
9944 With C-u prefix arg, use completion to determine the new state.
9945 With numeric prefix arg, switch to that state.
9946 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9947 With a triple C-u prefix, circumvent any state blocking.
9949 For calling through lisp, arg is also interpreted in the following way:
9950 'none -> empty state
9951 \"\"(empty string) -> switch to empty state
9952 'done -> switch to DONE
9953 'nextset -> switch to the next set of keywords
9954 'previousset -> switch to the previous set of keywords
9955 \"WAITING\" -> switch to the specified keyword, but only if it
9956 really is a member of `org-todo-keywords'."
9957 (interactive "P")
9958 (if (equal arg '(16)) (setq arg 'nextset))
9959 (let ((org-blocker-hook org-blocker-hook)
9960 (case-fold-search nil))
9961 (when (equal arg '(64))
9962 (setq arg nil org-blocker-hook nil))
9963 (when (and org-blocker-hook
9964 (or org-inhibit-blocking
9965 (org-entry-get nil "NOBLOCKING")))
9966 (setq org-blocker-hook nil))
9967 (save-excursion
9968 (catch 'exit
9969 (org-back-to-heading t)
9970 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9971 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9972 (looking-at " *"))
9973 (let* ((match-data (match-data))
9974 (startpos (point-at-bol))
9975 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9976 (org-log-done org-log-done)
9977 (org-log-repeat org-log-repeat)
9978 (org-todo-log-states org-todo-log-states)
9979 (this (match-string 1))
9980 (hl-pos (match-beginning 0))
9981 (head (org-get-todo-sequence-head this))
9982 (ass (assoc head org-todo-kwd-alist))
9983 (interpret (nth 1 ass))
9984 (done-word (nth 3 ass))
9985 (final-done-word (nth 4 ass))
9986 (last-state (or this ""))
9987 (completion-ignore-case t)
9988 (member (member this org-todo-keywords-1))
9989 (tail (cdr member))
9990 (state (cond
9991 ((and org-todo-key-trigger
9992 (or (and (equal arg '(4))
9993 (eq org-use-fast-todo-selection 'prefix))
9994 (and (not arg) org-use-fast-todo-selection
9995 (not (eq org-use-fast-todo-selection
9996 'prefix)))))
9997 ;; Use fast selection
9998 (org-fast-todo-selection))
9999 ((and (equal arg '(4))
10000 (or (not org-use-fast-todo-selection)
10001 (not org-todo-key-trigger)))
10002 ;; Read a state with completion
10003 (org-icompleting-read
10004 "State: " (mapcar (lambda(x) (list x))
10005 org-todo-keywords-1)
10006 nil t))
10007 ((eq arg 'right)
10008 (if this
10009 (if tail (car tail) nil)
10010 (car org-todo-keywords-1)))
10011 ((eq arg 'left)
10012 (if (equal member org-todo-keywords-1)
10014 (if this
10015 (nth (- (length org-todo-keywords-1)
10016 (length tail) 2)
10017 org-todo-keywords-1)
10018 (org-last org-todo-keywords-1))))
10019 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10020 (setq arg nil))) ; hack to fall back to cycling
10021 (arg
10022 ;; user or caller requests a specific state
10023 (cond
10024 ((equal arg "") nil)
10025 ((eq arg 'none) nil)
10026 ((eq arg 'done) (or done-word (car org-done-keywords)))
10027 ((eq arg 'nextset)
10028 (or (car (cdr (member head org-todo-heads)))
10029 (car org-todo-heads)))
10030 ((eq arg 'previousset)
10031 (let ((org-todo-heads (reverse org-todo-heads)))
10032 (or (car (cdr (member head org-todo-heads)))
10033 (car org-todo-heads))))
10034 ((car (member arg org-todo-keywords-1)))
10035 ((stringp arg)
10036 (error "State `%s' not valid in this file" arg))
10037 ((nth (1- (prefix-numeric-value arg))
10038 org-todo-keywords-1))))
10039 ((null member) (or head (car org-todo-keywords-1)))
10040 ((equal this final-done-word) nil) ;; -> make empty
10041 ((null tail) nil) ;; -> first entry
10042 ((memq interpret '(type priority))
10043 (if (eq this-command last-command)
10044 (car tail)
10045 (if (> (length tail) 0)
10046 (or done-word (car org-done-keywords))
10047 nil)))
10049 (car tail))))
10050 (state (or
10051 (run-hook-with-args-until-success
10052 'org-todo-get-default-hook state last-state)
10053 state))
10054 (next (if state (concat " " state " ") " "))
10055 (change-plist (list :type 'todo-state-change :from this :to state
10056 :position startpos))
10057 dolog now-done-p)
10058 (when org-blocker-hook
10059 (setq org-last-todo-state-is-todo
10060 (not (member this org-done-keywords)))
10061 (unless (save-excursion
10062 (save-match-data
10063 (run-hook-with-args-until-failure
10064 'org-blocker-hook change-plist)))
10065 (if (interactive-p)
10066 (error "TODO state change from %s to %s blocked" this state)
10067 ;; fail silently
10068 (message "TODO state change from %s to %s blocked" this state)
10069 (throw 'exit nil))))
10070 (store-match-data match-data)
10071 (replace-match next t t)
10072 (unless (pos-visible-in-window-p hl-pos)
10073 (message "TODO state changed to %s" (org-trim next)))
10074 (unless head
10075 (setq head (org-get-todo-sequence-head state)
10076 ass (assoc head org-todo-kwd-alist)
10077 interpret (nth 1 ass)
10078 done-word (nth 3 ass)
10079 final-done-word (nth 4 ass)))
10080 (when (memq arg '(nextset previousset))
10081 (message "Keyword-Set %d/%d: %s"
10082 (- (length org-todo-sets) -1
10083 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10084 (length org-todo-sets)
10085 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10086 (setq org-last-todo-state-is-todo
10087 (not (member state org-done-keywords)))
10088 (setq now-done-p (and (member state org-done-keywords)
10089 (not (member this org-done-keywords))))
10090 (and logging (org-local-logging logging))
10091 (when (and (or org-todo-log-states org-log-done)
10092 (not (eq org-inhibit-logging t))
10093 (not (memq arg '(nextset previousset))))
10094 ;; we need to look at recording a time and note
10095 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10096 (nth 2 (assoc this org-todo-log-states))))
10097 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10098 (setq dolog 'time))
10099 (when (and state
10100 (member state org-not-done-keywords)
10101 (not (member this org-not-done-keywords)))
10102 ;; This is now a todo state and was not one before
10103 ;; If there was a CLOSED time stamp, get rid of it.
10104 (org-add-planning-info nil nil 'closed))
10105 (when (and now-done-p org-log-done)
10106 ;; It is now done, and it was not done before
10107 (org-add-planning-info 'closed (org-current-time))
10108 (if (and (not dolog) (eq 'note org-log-done))
10109 (org-add-log-setup 'done state this 'findpos 'note)))
10110 (when (and state dolog)
10111 ;; This is a non-nil state, and we need to log it
10112 (org-add-log-setup 'state state this 'findpos dolog)))
10113 ;; Fixup tag positioning
10114 (org-todo-trigger-tag-changes state)
10115 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10116 (when org-provide-todo-statistics
10117 (org-update-parent-todo-statistics))
10118 (run-hooks 'org-after-todo-state-change-hook)
10119 (if (and arg (not (member state org-done-keywords)))
10120 (setq head (org-get-todo-sequence-head state)))
10121 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10122 ;; Do we need to trigger a repeat?
10123 (when now-done-p
10124 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10125 ;; This is for the agenda, take a snapshot of the headline.
10126 (save-match-data
10127 (setq org-agenda-headline-snapshot-before-repeat
10128 (org-get-heading))))
10129 (org-auto-repeat-maybe state))
10130 ;; Fixup cursor location if close to the keyword
10131 (if (and (outline-on-heading-p)
10132 (not (bolp))
10133 (save-excursion (beginning-of-line 1)
10134 (looking-at org-todo-line-regexp))
10135 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10136 (progn
10137 (goto-char (or (match-end 2) (match-end 1)))
10138 (and (looking-at " ") (just-one-space))))
10139 (when org-trigger-hook
10140 (save-excursion
10141 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10143 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10144 "Block turning an entry into a TODO, using the hierarchy.
10145 This checks whether the current task should be blocked from state
10146 changes. Such blocking occurs when:
10148 1. The task has children which are not all in a completed state.
10150 2. A task has a parent with the property :ORDERED:, and there
10151 are siblings prior to the current task with incomplete
10152 status.
10154 3. The parent of the task is blocked because it has siblings that should
10155 be done first, or is child of a block grandparent TODO entry."
10157 (catch 'dont-block
10158 ;; If this is not a todo state change, or if this entry is already DONE,
10159 ;; do not block
10160 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10161 (member (plist-get change-plist :from)
10162 (cons 'done org-done-keywords))
10163 (member (plist-get change-plist :to)
10164 (cons 'todo org-not-done-keywords))
10165 (not (plist-get change-plist :to)))
10166 (throw 'dont-block t))
10167 ;; If this task has children, and any are undone, it's blocked
10168 (save-excursion
10169 (org-back-to-heading t)
10170 (let ((this-level (funcall outline-level)))
10171 (outline-next-heading)
10172 (let ((child-level (funcall outline-level)))
10173 (while (and (not (eobp))
10174 (> child-level this-level))
10175 ;; this todo has children, check whether they are all
10176 ;; completed
10177 (if (and (not (org-entry-is-done-p))
10178 (org-entry-is-todo-p))
10179 (throw 'dont-block nil))
10180 (outline-next-heading)
10181 (setq child-level (funcall outline-level))))))
10182 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10183 ;; any previous siblings are undone, it's blocked
10184 (save-excursion
10185 (org-back-to-heading t)
10186 (let* ((pos (point))
10187 (parent-pos (and (org-up-heading-safe) (point))))
10188 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10189 (when (and (org-entry-get (point) "ORDERED")
10190 (forward-line 1)
10191 (re-search-forward org-not-done-heading-regexp pos t))
10192 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10193 ;; Search further up the hierarchy, to see if an anchestor is blocked
10194 (while t
10195 (goto-char parent-pos)
10196 (if (not (looking-at org-not-done-heading-regexp))
10197 (throw 'dont-block t)) ; do not block, parent is not a TODO
10198 (setq pos (point))
10199 (setq parent-pos (and (org-up-heading-safe) (point)))
10200 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10201 (when (and (org-entry-get (point) "ORDERED")
10202 (forward-line 1)
10203 (re-search-forward org-not-done-heading-regexp pos t))
10204 (throw 'dont-block nil))))))) ; block, older sibling not done.
10206 (defcustom org-track-ordered-property-with-tag nil
10207 "Should the ORDERED property also be shown as a tag?
10208 The ORDERED property decides if an entry should require subtasks to be
10209 completed in sequence. Since a property is not very visible, setting
10210 this option means that toggling the ORDERED property with the command
10211 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10212 not relevant for the behavior, but it makes things more visible.
10214 Note that toggling the tag with tags commands will not change the property
10215 and therefore not influence behavior!
10217 This can be t, meaning the tag ORDERED should be used, It can also be a
10218 string to select a different tag for this task."
10219 :group 'org-todo
10220 :type '(choice
10221 (const :tag "No tracking" nil)
10222 (const :tag "Track with ORDERED tag" t)
10223 (string :tag "Use other tag")))
10225 (defun org-toggle-ordered-property ()
10226 "Toggle the ORDERED property of the current entry.
10227 For better visibility, you can track the value of this property with a tag.
10228 See variable `org-track-ordered-property-with-tag'."
10229 (interactive)
10230 (let* ((t1 org-track-ordered-property-with-tag)
10231 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10232 (save-excursion
10233 (org-back-to-heading)
10234 (if (org-entry-get nil "ORDERED")
10235 (progn
10236 (org-delete-property "ORDERED")
10237 (and tag (org-toggle-tag tag 'off))
10238 (message "Subtasks can be completed in arbitrary order"))
10239 (org-entry-put nil "ORDERED" "t")
10240 (and tag (org-toggle-tag tag 'on))
10241 (message "Subtasks must be completed in sequence")))))
10243 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10244 (defun org-block-todo-from-checkboxes (change-plist)
10245 "Block turning an entry into a TODO, using checkboxes.
10246 This checks whether the current task should be blocked from state
10247 changes because there are unchecked boxes in this entry."
10248 (catch 'dont-block
10249 ;; If this is not a todo state change, or if this entry is already DONE,
10250 ;; do not block
10251 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10252 (member (plist-get change-plist :from)
10253 (cons 'done org-done-keywords))
10254 (member (plist-get change-plist :to)
10255 (cons 'todo org-not-done-keywords))
10256 (not (plist-get change-plist :to)))
10257 (throw 'dont-block t))
10258 ;; If this task has checkboxes that are not checked, it's blocked
10259 (save-excursion
10260 (org-back-to-heading t)
10261 (let ((beg (point)) end)
10262 (outline-next-heading)
10263 (setq end (point))
10264 (goto-char beg)
10265 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10266 end t)
10267 (progn
10268 (if (boundp 'org-blocked-by-checkboxes)
10269 (setq org-blocked-by-checkboxes t))
10270 (throw 'dont-block nil)))))
10271 t)) ; do not block
10273 (defun org-entry-blocked-p ()
10274 "Is the current entry blocked?"
10275 (if (org-entry-get nil "NOBLOCKING")
10276 nil ;; Never block this entry
10277 (not
10278 (run-hook-with-args-until-failure
10279 'org-blocker-hook
10280 (list :type 'todo-state-change
10281 :position (point)
10282 :from 'todo
10283 :to 'done)))))
10285 (defun org-update-statistics-cookies (all)
10286 "Update the statistics cookie, either from TODO or from checkboxes.
10287 This should be called with the cursor in a line with a statistics cookie."
10288 (interactive "P")
10289 (if all
10290 (progn
10291 (org-update-checkbox-count 'all)
10292 (org-map-entries 'org-update-parent-todo-statistics))
10293 (if (not (org-on-heading-p))
10294 (org-update-checkbox-count)
10295 (let ((pos (move-marker (make-marker) (point)))
10296 end l1 l2)
10297 (ignore-errors (org-back-to-heading t))
10298 (if (not (org-on-heading-p))
10299 (org-update-checkbox-count)
10300 (setq l1 (org-outline-level))
10301 (setq end (save-excursion
10302 (outline-next-heading)
10303 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10304 (point)))
10305 (if (and (save-excursion
10306 (re-search-forward
10307 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10308 (not (save-excursion (re-search-forward
10309 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10310 (org-update-checkbox-count)
10311 (if (and l2 (> l2 l1))
10312 (progn
10313 (goto-char end)
10314 (org-update-parent-todo-statistics))
10315 (goto-char pos)
10316 (beginning-of-line 1)
10317 (while (re-search-forward
10318 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10319 (point-at-eol) t)
10320 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10321 (goto-char pos)
10322 (move-marker pos nil)))))
10324 (defvar org-entry-property-inherited-from) ;; defined below
10325 (defun org-update-parent-todo-statistics ()
10326 "Update any statistics cookie in the parent of the current headline.
10327 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10328 the entire subtree and this will travel up the hierarchy and update
10329 statistics everywhere."
10330 (interactive)
10331 (let* ((lim 0) prop
10332 (recursive (or (not org-hierarchical-todo-statistics)
10333 (string-match
10334 "\\<recursive\\>"
10335 (or (setq prop (org-entry-get
10336 nil "COOKIE_DATA" 'inherit)) ""))))
10337 (lim (or (and prop (marker-position
10338 org-entry-property-inherited-from))
10339 lim))
10340 (first t)
10341 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10342 level ltoggle l1 new ndel
10343 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10344 (catch 'exit
10345 (save-excursion
10346 (beginning-of-line 1)
10347 (if (org-at-heading-p)
10348 (setq ltoggle (funcall outline-level))
10349 (error "This should not happen"))
10350 (while (and (setq level (org-up-heading-safe))
10351 (or recursive first)
10352 (>= (point) lim))
10353 (setq first nil cookie-present nil)
10354 (unless (and level
10355 (not (string-match
10356 "\\<checkbox\\>"
10357 (downcase
10358 (or (org-entry-get
10359 nil "COOKIE_DATA")
10360 "")))))
10361 (throw 'exit nil))
10362 (while (re-search-forward box-re (point-at-eol) t)
10363 (setq cnt-all 0 cnt-done 0 cookie-present t)
10364 (setq is-percent (match-end 2))
10365 (save-match-data
10366 (unless (outline-next-heading) (throw 'exit nil))
10367 (while (and (looking-at org-complex-heading-regexp)
10368 (> (setq l1 (length (match-string 1))) level))
10369 (setq kwd (and (or recursive (= l1 ltoggle))
10370 (match-string 2)))
10371 (if (or (eq org-provide-todo-statistics 'all-headlines)
10372 (and (listp org-provide-todo-statistics)
10373 (or (member kwd org-provide-todo-statistics)
10374 (member kwd org-done-keywords))))
10375 (setq cnt-all (1+ cnt-all))
10376 (if (eq org-provide-todo-statistics t)
10377 (and kwd (setq cnt-all (1+ cnt-all)))))
10378 (and (member kwd org-done-keywords)
10379 (setq cnt-done (1+ cnt-done)))
10380 (outline-next-heading)))
10381 (setq new
10382 (if is-percent
10383 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10384 (format "[%d/%d]" cnt-done cnt-all))
10385 ndel (- (match-end 0) (match-beginning 0)))
10386 (goto-char (match-beginning 0))
10387 (insert new)
10388 (delete-region (point) (+ (point) ndel)))
10389 (when cookie-present
10390 (run-hook-with-args 'org-after-todo-statistics-hook
10391 cnt-done (- cnt-all cnt-done))))))
10392 (run-hooks 'org-todo-statistics-hook)))
10394 (defvar org-after-todo-statistics-hook nil
10395 "Hook that is called after a TODO statistics cookie has been updated.
10396 Each function is called with two arguments: the number of not-done entries
10397 and the number of done entries.
10399 For example, the following function, when added to this hook, will switch
10400 an entry to DONE when all children are done, and back to TODO when new
10401 entries are set to a TODO status. Note that this hook is only called
10402 when there is a statistics cookie in the headline!
10404 (defun org-summary-todo (n-done n-not-done)
10405 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10406 (let (org-log-done org-log-states) ; turn off logging
10407 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10410 (defvar org-todo-statistics-hook nil
10411 "Hook that is run whenever Org thinks TODO statistics should be updated.
10412 This hook runs even if there is no statistics cookie present, in which case
10413 `org-after-todo-statistics-hook' would not run.")
10415 (defun org-todo-trigger-tag-changes (state)
10416 "Apply the changes defined in `org-todo-state-tags-triggers'."
10417 (let ((l org-todo-state-tags-triggers)
10418 changes)
10419 (when (or (not state) (equal state ""))
10420 (setq changes (append changes (cdr (assoc "" l)))))
10421 (when (and (stringp state) (> (length state) 0))
10422 (setq changes (append changes (cdr (assoc state l)))))
10423 (when (member state org-not-done-keywords)
10424 (setq changes (append changes (cdr (assoc 'todo l)))))
10425 (when (member state org-done-keywords)
10426 (setq changes (append changes (cdr (assoc 'done l)))))
10427 (dolist (c changes)
10428 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10430 (defun org-local-logging (value)
10431 "Get logging settings from a property VALUE."
10432 (let* (words w a)
10433 ;; directly set the variables, they are already local.
10434 (setq org-log-done nil
10435 org-log-repeat nil
10436 org-todo-log-states nil)
10437 (setq words (org-split-string value))
10438 (while (setq w (pop words))
10439 (cond
10440 ((setq a (assoc w org-startup-options))
10441 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10442 (set (nth 1 a) (nth 2 a))))
10443 ((setq a (org-extract-log-state-settings w))
10444 (and (member (car a) org-todo-keywords-1)
10445 (push a org-todo-log-states)))))))
10447 (defun org-get-todo-sequence-head (kwd)
10448 "Return the head of the TODO sequence to which KWD belongs.
10449 If KWD is not set, check if there is a text property remembering the
10450 right sequence."
10451 (let (p)
10452 (cond
10453 ((not kwd)
10454 (or (get-text-property (point-at-bol) 'org-todo-head)
10455 (progn
10456 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10457 nil (point-at-eol)))
10458 (get-text-property p 'org-todo-head))))
10459 ((not (member kwd org-todo-keywords-1))
10460 (car org-todo-keywords-1))
10461 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10463 (defun org-fast-todo-selection ()
10464 "Fast TODO keyword selection with single keys.
10465 Returns the new TODO keyword, or nil if no state change should occur."
10466 (let* ((fulltable org-todo-key-alist)
10467 (done-keywords org-done-keywords) ;; needed for the faces.
10468 (maxlen (apply 'max (mapcar
10469 (lambda (x)
10470 (if (stringp (car x)) (string-width (car x)) 0))
10471 fulltable)))
10472 (expert nil)
10473 (fwidth (+ maxlen 3 1 3))
10474 (ncol (/ (- (window-width) 4) fwidth))
10475 tg cnt e c tbl
10476 groups ingroup)
10477 (save-excursion
10478 (save-window-excursion
10479 (if expert
10480 (set-buffer (get-buffer-create " *Org todo*"))
10481 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10482 (erase-buffer)
10483 (org-set-local 'org-done-keywords done-keywords)
10484 (setq tbl fulltable cnt 0)
10485 (while (setq e (pop tbl))
10486 (cond
10487 ((equal e '(:startgroup))
10488 (push '() groups) (setq ingroup t)
10489 (when (not (= cnt 0))
10490 (setq cnt 0)
10491 (insert "\n"))
10492 (insert "{ "))
10493 ((equal e '(:endgroup))
10494 (setq ingroup nil cnt 0)
10495 (insert "}\n"))
10496 ((equal e '(:newline))
10497 (when (not (= cnt 0))
10498 (setq cnt 0)
10499 (insert "\n")
10500 (setq e (car tbl))
10501 (while (equal (car tbl) '(:newline))
10502 (insert "\n")
10503 (setq tbl (cdr tbl)))))
10505 (setq tg (car e) c (cdr e))
10506 (if ingroup (push tg (car groups)))
10507 (setq tg (org-add-props tg nil 'face
10508 (org-get-todo-face tg)))
10509 (if (and (= cnt 0) (not ingroup)) (insert " "))
10510 (insert "[" c "] " tg (make-string
10511 (- fwidth 4 (length tg)) ?\ ))
10512 (when (= (setq cnt (1+ cnt)) ncol)
10513 (insert "\n")
10514 (if ingroup (insert " "))
10515 (setq cnt 0)))))
10516 (insert "\n")
10517 (goto-char (point-min))
10518 (if (not expert) (org-fit-window-to-buffer))
10519 (message "[a-z..]:Set [SPC]:clear")
10520 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10521 (cond
10522 ((or (= c ?\C-g)
10523 (and (= c ?q) (not (rassoc c fulltable))))
10524 (setq quit-flag t))
10525 ((= c ?\ ) nil)
10526 ((setq e (rassoc c fulltable) tg (car e))
10528 (t (setq quit-flag t)))))))
10530 (defun org-entry-is-todo-p ()
10531 (member (org-get-todo-state) org-not-done-keywords))
10533 (defun org-entry-is-done-p ()
10534 (member (org-get-todo-state) org-done-keywords))
10536 (defun org-get-todo-state ()
10537 (save-excursion
10538 (org-back-to-heading t)
10539 (and (looking-at org-todo-line-regexp)
10540 (match-end 2)
10541 (match-string 2))))
10543 (defun org-at-date-range-p (&optional inactive-ok)
10544 "Is the cursor inside a date range?"
10545 (interactive)
10546 (save-excursion
10547 (catch 'exit
10548 (let ((pos (point)))
10549 (skip-chars-backward "^[<\r\n")
10550 (skip-chars-backward "<[")
10551 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10552 (>= (match-end 0) pos)
10553 (throw 'exit t))
10554 (skip-chars-backward "^<[\r\n")
10555 (skip-chars-backward "<[")
10556 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10557 (>= (match-end 0) pos)
10558 (throw 'exit t)))
10559 nil)))
10561 (defun org-get-repeat (&optional tagline)
10562 "Check if there is a deadline/schedule with repeater in this entry."
10563 (save-match-data
10564 (save-excursion
10565 (org-back-to-heading t)
10566 (and (re-search-forward (if tagline
10567 (concat tagline "\\s-*" org-repeat-re)
10568 org-repeat-re)
10569 (org-entry-end-position) t)
10570 (match-string-no-properties 1)))))
10572 (defvar org-last-changed-timestamp)
10573 (defvar org-last-inserted-timestamp)
10574 (defvar org-log-post-message)
10575 (defvar org-log-note-purpose)
10576 (defvar org-log-note-how)
10577 (defvar org-log-note-extra)
10578 (defun org-auto-repeat-maybe (done-word)
10579 "Check if the current headline contains a repeated deadline/schedule.
10580 If yes, set TODO state back to what it was and change the base date
10581 of repeating deadline/scheduled time stamps to new date.
10582 This function is run automatically after each state change to a DONE state."
10583 ;; last-state is dynamically scoped into this function
10584 (let* ((repeat (org-get-repeat))
10585 (aa (assoc last-state org-todo-kwd-alist))
10586 (interpret (nth 1 aa))
10587 (head (nth 2 aa))
10588 (whata '(("d" . day) ("m" . month) ("y" . year)))
10589 (msg "Entry repeats: ")
10590 (org-log-done nil)
10591 (org-todo-log-states nil)
10592 (nshiftmax 10) (nshift 0)
10593 re type n what ts time)
10594 (when repeat
10595 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10596 (org-todo (if (eq interpret 'type) last-state head))
10597 (org-entry-put nil "LAST_REPEAT" (format-time-string
10598 (org-time-stamp-format t t)))
10599 (when org-log-repeat
10600 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10601 (memq 'org-add-log-note post-command-hook))
10602 ;; OK, we are already setup for some record
10603 (if (eq org-log-repeat 'note)
10604 ;; make sure we take a note, not only a time stamp
10605 (setq org-log-note-how 'note))
10606 ;; Set up for taking a record
10607 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10608 last-state
10609 'findpos org-log-repeat)))
10610 (org-back-to-heading t)
10611 (org-add-planning-info nil nil 'closed)
10612 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10613 org-deadline-time-regexp "\\)\\|\\("
10614 org-ts-regexp "\\)"))
10615 (while (re-search-forward
10616 re (save-excursion (outline-next-heading) (point)) t)
10617 (setq type (if (match-end 1) org-scheduled-string
10618 (if (match-end 3) org-deadline-string "Plain:"))
10619 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10620 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10621 (setq n (string-to-number (match-string 2 ts))
10622 what (match-string 3 ts))
10623 (if (equal what "w") (setq n (* n 7) what "d"))
10624 ;; Preparation, see if we need to modify the start date for the change
10625 (when (match-end 1)
10626 (setq time (save-match-data (org-time-string-to-time ts)))
10627 (cond
10628 ((equal (match-string 1 ts) ".")
10629 ;; Shift starting date to today
10630 (org-timestamp-change
10631 (- (time-to-days (current-time)) (time-to-days time))
10632 'day))
10633 ((equal (match-string 1 ts) "+")
10634 (while (or (= nshift 0)
10635 (<= (time-to-days time) (time-to-days (current-time))))
10636 (when (= (incf nshift) nshiftmax)
10637 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10638 (error "Abort")))
10639 (org-timestamp-change n (cdr (assoc what whata)))
10640 (org-at-timestamp-p t)
10641 (setq ts (match-string 1))
10642 (setq time (save-match-data (org-time-string-to-time ts))))
10643 (org-timestamp-change (- n) (cdr (assoc what whata)))
10644 ;; rematch, so that we have everything in place for the real shift
10645 (org-at-timestamp-p t)
10646 (setq ts (match-string 1))
10647 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10648 (org-timestamp-change n (cdr (assoc what whata)))
10649 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10650 (setq org-log-post-message msg)
10651 (message "%s" msg))))
10653 (defun org-show-todo-tree (arg)
10654 "Make a compact tree which shows all headlines marked with TODO.
10655 The tree will show the lines where the regexp matches, and all higher
10656 headlines above the match.
10657 With a \\[universal-argument] prefix, prompt for a regexp to match.
10658 With a numeric prefix N, construct a sparse tree for the Nth element
10659 of `org-todo-keywords-1'."
10660 (interactive "P")
10661 (let ((case-fold-search nil)
10662 (kwd-re
10663 (cond ((null arg) org-not-done-regexp)
10664 ((equal arg '(4))
10665 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10666 (mapcar 'list org-todo-keywords-1))))
10667 (concat "\\("
10668 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10669 "\\)\\>")))
10670 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10671 (regexp-quote (nth (1- (prefix-numeric-value arg))
10672 org-todo-keywords-1)))
10673 (t (error "Invalid prefix argument: %s" arg)))))
10674 (message "%d TODO entries found"
10675 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10677 (defun org-deadline (&optional remove time)
10678 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10679 With argument REMOVE, remove any deadline from the item.
10680 When TIME is set, it should be an internal time specification, and the
10681 scheduling will use the corresponding date."
10682 (interactive "P")
10683 (let ((old-date (org-entry-get nil "DEADLINE")))
10684 (if remove
10685 (progn
10686 (when (and old-date org-log-redeadline)
10687 (org-add-log-setup 'deldeadline nil old-date 'findpos
10688 org-log-redeadline))
10689 (org-remove-timestamp-with-keyword org-deadline-string)
10690 (message "Item no longer has a deadline."))
10691 (if (org-get-repeat)
10692 (error "Cannot change deadline on task with repeater, please do that by hand")
10693 (org-add-planning-info 'deadline time 'closed)
10694 (when (and old-date org-log-redeadline
10695 (not (equal old-date
10696 (substring org-last-inserted-timestamp 1 -1))))
10697 (org-add-log-setup 'redeadline nil old-date 'findpos
10698 org-log-redeadline))
10699 (message "Deadline on %s" org-last-inserted-timestamp)))))
10701 (defun org-schedule (&optional remove time)
10702 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10703 With argument REMOVE, remove any scheduling date from the item.
10704 When TIME is set, it should be an internal time specification, and the
10705 scheduling will use the corresponding date."
10706 (interactive "P")
10707 (let ((old-date (org-entry-get nil "SCHEDULED")))
10708 (if remove
10709 (progn
10710 (when (and old-date org-log-reschedule)
10711 (org-add-log-setup 'delschedule nil old-date 'findpos
10712 org-log-reschedule))
10713 (org-remove-timestamp-with-keyword org-scheduled-string)
10714 (message "Item is no longer scheduled."))
10715 (if (org-get-repeat)
10716 (error "Cannot reschedule task with repeater, please do that by hand")
10717 (org-add-planning-info 'scheduled time 'closed)
10718 (when (and old-date org-log-reschedule
10719 (not (equal old-date
10720 (substring org-last-inserted-timestamp 1 -1))))
10721 (org-add-log-setup 'reschedule nil old-date 'findpos
10722 org-log-reschedule))
10723 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10725 (defun org-get-scheduled-time (pom &optional inherit)
10726 "Get the scheduled time as a time tuple, of a format suitable
10727 for calling org-schedule with, or if there is no scheduling,
10728 returns nil."
10729 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10730 (when time
10731 (apply 'encode-time (org-parse-time-string time)))))
10733 (defun org-get-deadline-time (pom &optional inherit)
10734 "Get the deadine as a time tuple, of a format suitable for
10735 calling org-deadline with, or if there is no scheduling, returns
10736 nil."
10737 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10738 (when time
10739 (apply 'encode-time (org-parse-time-string time)))))
10741 (defun org-remove-timestamp-with-keyword (keyword)
10742 "Remove all time stamps with KEYWORD in the current entry."
10743 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10744 beg)
10745 (save-excursion
10746 (org-back-to-heading t)
10747 (setq beg (point))
10748 (outline-next-heading)
10749 (while (re-search-backward re beg t)
10750 (replace-match "")
10751 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10752 (equal (char-before) ?\ ))
10753 (backward-delete-char 1)
10754 (if (string-match "^[ \t]*$" (buffer-substring
10755 (point-at-bol) (point-at-eol)))
10756 (delete-region (point-at-bol)
10757 (min (point-max) (1+ (point-at-eol))))))))))
10759 (defun org-add-planning-info (what &optional time &rest remove)
10760 "Insert new timestamp with keyword in the line directly after the headline.
10761 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10762 If non is given, the user is prompted for a date.
10763 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10764 be removed."
10765 (interactive)
10766 (let (org-time-was-given org-end-time-was-given ts
10767 end default-time default-input)
10769 (catch 'exit
10770 (when (and (not time) (memq what '(scheduled deadline)))
10771 ;; Try to get a default date/time from existing timestamp
10772 (save-excursion
10773 (org-back-to-heading t)
10774 (setq end (save-excursion (outline-next-heading) (point)))
10775 (when (re-search-forward (if (eq what 'scheduled)
10776 org-scheduled-time-regexp
10777 org-deadline-time-regexp)
10778 end t)
10779 (setq ts (match-string 1)
10780 default-time
10781 (apply 'encode-time (org-parse-time-string ts))
10782 default-input (and ts (org-get-compact-tod ts))))))
10783 (when what
10784 ;; If necessary, get the time from the user
10785 (setq time (or time (org-read-date nil 'to-time nil nil
10786 default-time default-input))))
10788 (when (and org-insert-labeled-timestamps-at-point
10789 (member what '(scheduled deadline)))
10790 (insert
10791 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10792 (org-insert-time-stamp time org-time-was-given
10793 nil nil nil (list org-end-time-was-given))
10794 (setq what nil))
10795 (save-excursion
10796 (save-restriction
10797 (let (col list elt ts buffer-invisibility-spec)
10798 (org-back-to-heading t)
10799 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10800 (goto-char (match-end 1))
10801 (setq col (current-column))
10802 (goto-char (match-end 0))
10803 (if (eobp) (insert "\n") (forward-char 1))
10804 (when (and (not what)
10805 (not (looking-at
10806 (concat "[ \t]*"
10807 org-keyword-time-not-clock-regexp))))
10808 ;; Nothing to add, nothing to remove...... :-)
10809 (throw 'exit nil))
10810 (if (and (not (looking-at outline-regexp))
10811 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10812 "[^\r\n]*"))
10813 (not (equal (match-string 1) org-clock-string)))
10814 (narrow-to-region (match-beginning 0) (match-end 0))
10815 (insert-before-markers "\n")
10816 (backward-char 1)
10817 (narrow-to-region (point) (point))
10818 (and org-adapt-indentation (org-indent-to-column col)))
10819 ;; Check if we have to remove something.
10820 (setq list (cons what remove))
10821 (while list
10822 (setq elt (pop list))
10823 (goto-char (point-min))
10824 (when (or (and (eq elt 'scheduled)
10825 (re-search-forward org-scheduled-time-regexp nil t))
10826 (and (eq elt 'deadline)
10827 (re-search-forward org-deadline-time-regexp nil t))
10828 (and (eq elt 'closed)
10829 (re-search-forward org-closed-time-regexp nil t)))
10830 (replace-match "")
10831 (if (looking-at "--+<[^>]+>") (replace-match ""))
10832 (skip-chars-backward " ")
10833 (if (looking-at " +") (replace-match ""))))
10834 (goto-char (point-max))
10835 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10836 (when what
10837 (insert
10838 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10839 (cond ((eq what 'scheduled) org-scheduled-string)
10840 ((eq what 'deadline) org-deadline-string)
10841 ((eq what 'closed) org-closed-string))
10842 " ")
10843 (setq ts (org-insert-time-stamp
10844 time
10845 (or org-time-was-given
10846 (and (eq what 'closed) org-log-done-with-time))
10847 (eq what 'closed)
10848 nil nil (list org-end-time-was-given)))
10849 (end-of-line 1))
10850 (goto-char (point-min))
10851 (widen)
10852 (if (and (looking-at "[ \t]+\n")
10853 (equal (char-before) ?\n))
10854 (delete-region (1- (point)) (point-at-eol)))
10855 ts))))))
10857 (defvar org-log-note-marker (make-marker))
10858 (defvar org-log-note-purpose nil)
10859 (defvar org-log-note-state nil)
10860 (defvar org-log-note-previous-state nil)
10861 (defvar org-log-note-how nil)
10862 (defvar org-log-note-extra nil)
10863 (defvar org-log-note-window-configuration nil)
10864 (defvar org-log-note-return-to (make-marker))
10865 (defvar org-log-post-message nil
10866 "Message to be displayed after a log note has been stored.
10867 The auto-repeater uses this.")
10869 (defun org-add-note ()
10870 "Add a note to the current entry.
10871 This is done in the same way as adding a state change note."
10872 (interactive)
10873 (org-add-log-setup 'note nil nil 'findpos nil))
10875 (defvar org-property-end-re)
10876 (defun org-add-log-setup (&optional purpose state prev-state
10877 findpos how &optional extra)
10878 "Set up the post command hook to take a note.
10879 If this is about to TODO state change, the new state is expected in STATE.
10880 When FINDPOS is non-nil, find the correct position for the note in
10881 the current entry. If not, assume that it can be inserted at point.
10882 HOW is an indicator what kind of note should be created.
10883 EXTRA is additional text that will be inserted into the notes buffer."
10884 (let* ((org-log-into-drawer (org-log-into-drawer))
10885 (drawer (cond ((stringp org-log-into-drawer)
10886 org-log-into-drawer)
10887 (org-log-into-drawer "LOGBOOK")
10888 (t nil))))
10889 (save-restriction
10890 (save-excursion
10891 (when findpos
10892 (org-back-to-heading t)
10893 (narrow-to-region (point) (save-excursion
10894 (outline-next-heading) (point)))
10895 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10896 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10897 "[^\r\n]*\\)?"))
10898 (goto-char (match-end 0))
10899 (cond
10900 (drawer
10901 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10902 nil t)
10903 (progn
10904 (goto-char (match-end 0))
10905 (or org-log-states-order-reversed
10906 (and (re-search-forward org-property-end-re nil t)
10907 (goto-char (1- (match-beginning 0))))))
10908 (insert "\n:" drawer ":\n:END:")
10909 (beginning-of-line 0)
10910 (org-indent-line-function)
10911 (beginning-of-line 2)
10912 (org-indent-line-function)
10913 (end-of-line 0)))
10914 ((and org-log-state-notes-insert-after-drawers
10915 (save-excursion
10916 (forward-line) (looking-at org-drawer-regexp)))
10917 (forward-line)
10918 (while (looking-at org-drawer-regexp)
10919 (goto-char (match-end 0))
10920 (re-search-forward org-property-end-re (point-max) t)
10921 (forward-line))
10922 (forward-line -1)))
10923 (unless org-log-states-order-reversed
10924 (and (= (char-after) ?\n) (forward-char 1))
10925 (org-skip-over-state-notes)
10926 (skip-chars-backward " \t\n\r")))
10927 (move-marker org-log-note-marker (point))
10928 (setq org-log-note-purpose purpose
10929 org-log-note-state state
10930 org-log-note-previous-state prev-state
10931 org-log-note-how how
10932 org-log-note-extra extra)
10933 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10935 (defun org-skip-over-state-notes ()
10936 "Skip past the list of State notes in an entry."
10937 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10938 (while (looking-at "[ \t]*- State")
10939 (condition-case nil
10940 (org-next-item)
10941 (error (org-end-of-item)))))
10943 (defun org-add-log-note (&optional purpose)
10944 "Pop up a window for taking a note, and add this note later at point."
10945 (remove-hook 'post-command-hook 'org-add-log-note)
10946 (setq org-log-note-window-configuration (current-window-configuration))
10947 (delete-other-windows)
10948 (move-marker org-log-note-return-to (point))
10949 (switch-to-buffer (marker-buffer org-log-note-marker))
10950 (goto-char org-log-note-marker)
10951 (org-switch-to-buffer-other-window "*Org Note*")
10952 (erase-buffer)
10953 (if (memq org-log-note-how '(time state))
10954 (let (current-prefix-arg) (org-store-log-note))
10955 (let ((org-inhibit-startup t)) (org-mode))
10956 (insert (format "# Insert note for %s.
10957 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10958 (cond
10959 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10960 ((eq org-log-note-purpose 'done) "closed todo item")
10961 ((eq org-log-note-purpose 'state)
10962 (format "state change from \"%s\" to \"%s\""
10963 (or org-log-note-previous-state "")
10964 (or org-log-note-state "")))
10965 ((eq org-log-note-purpose 'reschedule)
10966 "rescheduling")
10967 ((eq org-log-note-purpose 'delschedule)
10968 "no longer scheduled")
10969 ((eq org-log-note-purpose 'redeadline)
10970 "changing deadline")
10971 ((eq org-log-note-purpose 'deldeadline)
10972 "removing deadline")
10973 ((eq org-log-note-purpose 'note)
10974 "this entry")
10975 (t (error "This should not happen")))))
10976 (if org-log-note-extra (insert org-log-note-extra))
10977 (org-set-local 'org-finish-function 'org-store-log-note)))
10979 (defvar org-note-abort nil) ; dynamically scoped
10980 (defun org-store-log-note ()
10981 "Finish taking a log note, and insert it to where it belongs."
10982 (let ((txt (buffer-string))
10983 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10984 lines ind)
10985 (kill-buffer (current-buffer))
10986 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10987 (setq txt (replace-match "" t t txt)))
10988 (if (string-match "\\s-+\\'" txt)
10989 (setq txt (replace-match "" t t txt)))
10990 (setq lines (org-split-string txt "\n"))
10991 (when (and note (string-match "\\S-" note))
10992 (setq note
10993 (org-replace-escapes
10994 note
10995 (list (cons "%u" (user-login-name))
10996 (cons "%U" user-full-name)
10997 (cons "%t" (format-time-string
10998 (org-time-stamp-format 'long 'inactive)
10999 (current-time)))
11000 (cons "%s" (if org-log-note-state
11001 (concat "\"" org-log-note-state "\"")
11002 ""))
11003 (cons "%S" (if org-log-note-previous-state
11004 (concat "\"" org-log-note-previous-state "\"")
11005 "\"\"")))))
11006 (if lines (setq note (concat note " \\\\")))
11007 (push note lines))
11008 (when (or current-prefix-arg org-note-abort)
11009 (when org-log-into-drawer
11010 (org-remove-empty-drawer-at
11011 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11012 org-log-note-marker))
11013 (setq lines nil))
11014 (when lines
11015 (with-current-buffer (marker-buffer org-log-note-marker)
11016 (save-excursion
11017 (goto-char org-log-note-marker)
11018 (move-marker org-log-note-marker nil)
11019 (end-of-line 1)
11020 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11021 (insert "- " (pop lines))
11022 (org-indent-line-function)
11023 (beginning-of-line 1)
11024 (looking-at "[ \t]*")
11025 (setq ind (concat (match-string 0) " "))
11026 (end-of-line 1)
11027 (while lines (insert "\n" ind (pop lines)))
11028 (message "Note stored")
11029 (org-back-to-heading t)
11030 (org-cycle-hide-drawers 'children)))))
11031 (set-window-configuration org-log-note-window-configuration)
11032 (with-current-buffer (marker-buffer org-log-note-return-to)
11033 (goto-char org-log-note-return-to))
11034 (move-marker org-log-note-return-to nil)
11035 (and org-log-post-message (message "%s" org-log-post-message)))
11037 (defun org-remove-empty-drawer-at (drawer pos)
11038 "Remove an empty drawer DRAWER at position POS.
11039 POS may also be a marker."
11040 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11041 (save-excursion
11042 (save-restriction
11043 (widen)
11044 (goto-char pos)
11045 (if (org-in-regexp
11046 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11047 (replace-match ""))))))
11049 (defun org-sparse-tree (&optional arg)
11050 "Create a sparse tree, prompt for the details.
11051 This command can create sparse trees. You first need to select the type
11052 of match used to create the tree:
11054 t Show entries with a specific TODO keyword.
11055 m Show entries selected by a tags/property match.
11056 p Enter a property name and its value (both with completion on existing
11057 names/values) and show entries with that property.
11058 / Show entries matching a regular expression (`r' can be used as well)
11059 d Show deadlines due within `org-deadline-warning-days'.
11060 b Show deadlines and scheduled items before a date.
11061 a Show deadlines and scheduled items after a date."
11062 (interactive "P")
11063 (let (ans kwd value)
11064 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11065 (setq ans (read-char-exclusive))
11066 (cond
11067 ((equal ans ?d)
11068 (call-interactively 'org-check-deadlines))
11069 ((equal ans ?b)
11070 (call-interactively 'org-check-before-date))
11071 ((equal ans ?a)
11072 (call-interactively 'org-check-after-date))
11073 ((equal ans ?t)
11074 (org-show-todo-tree '(4)))
11075 ((member ans '(?T ?m))
11076 (call-interactively 'org-match-sparse-tree))
11077 ((member ans '(?p ?P))
11078 (setq kwd (org-icompleting-read "Property: "
11079 (mapcar 'list (org-buffer-property-keys))))
11080 (setq value (org-icompleting-read "Value: "
11081 (mapcar 'list (org-property-values kwd))))
11082 (unless (string-match "\\`{.*}\\'" value)
11083 (setq value (concat "\"" value "\"")))
11084 (org-match-sparse-tree arg (concat kwd "=" value)))
11085 ((member ans '(?r ?R ?/))
11086 (call-interactively 'org-occur))
11087 (t (error "No such sparse tree command \"%c\"" ans)))))
11089 (defvar org-occur-highlights nil
11090 "List of overlays used for occur matches.")
11091 (make-variable-buffer-local 'org-occur-highlights)
11092 (defvar org-occur-parameters nil
11093 "Parameters of the active org-occur calls.
11094 This is a list, each call to org-occur pushes as cons cell,
11095 containing the regular expression and the callback, onto the list.
11096 The list can contain several entries if `org-occur' has been called
11097 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11098 will only contain one set of parameters. When the highlights are
11099 removed (for example with `C-c C-c', or with the next edit (depending
11100 on `org-remove-highlights-with-change'), this variable is emptied
11101 as well.")
11102 (make-variable-buffer-local 'org-occur-parameters)
11104 (defun org-occur (regexp &optional keep-previous callback)
11105 "Make a compact tree which shows all matches of REGEXP.
11106 The tree will show the lines where the regexp matches, and all higher
11107 headlines above the match. It will also show the heading after the match,
11108 to make sure editing the matching entry is easy.
11109 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11110 call to `org-occur' will be kept, to allow stacking of calls to this
11111 command.
11112 If CALLBACK is non-nil, it is a function which is called to confirm
11113 that the match should indeed be shown."
11114 (interactive "sRegexp: \nP")
11115 (when (equal regexp "")
11116 (error "Regexp cannot be empty"))
11117 (unless keep-previous
11118 (org-remove-occur-highlights nil nil t))
11119 (push (cons regexp callback) org-occur-parameters)
11120 (let ((cnt 0))
11121 (save-excursion
11122 (goto-char (point-min))
11123 (if (or (not keep-previous) ; do not want to keep
11124 (not org-occur-highlights)) ; no previous matches
11125 ;; hide everything
11126 (org-overview))
11127 (while (re-search-forward regexp nil t)
11128 (when (or (not callback)
11129 (save-match-data (funcall callback)))
11130 (setq cnt (1+ cnt))
11131 (when org-highlight-sparse-tree-matches
11132 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11133 (org-show-context 'occur-tree))))
11134 (when org-remove-highlights-with-change
11135 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11136 nil 'local))
11137 (unless org-sparse-tree-open-archived-trees
11138 (org-hide-archived-subtrees (point-min) (point-max)))
11139 (run-hooks 'org-occur-hook)
11140 (if (interactive-p)
11141 (message "%d match(es) for regexp %s" cnt regexp))
11142 cnt))
11144 (defun org-show-context (&optional key)
11145 "Make sure point and context and visible.
11146 How much context is shown depends upon the variables
11147 `org-show-hierarchy-above', `org-show-following-heading'. and
11148 `org-show-siblings'."
11149 (let ((heading-p (org-on-heading-p t))
11150 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11151 (following-p (org-get-alist-option org-show-following-heading key))
11152 (entry-p (org-get-alist-option org-show-entry-below key))
11153 (siblings-p (org-get-alist-option org-show-siblings key)))
11154 (catch 'exit
11155 ;; Show heading or entry text
11156 (if (and heading-p (not entry-p))
11157 (org-flag-heading nil) ; only show the heading
11158 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11159 (org-show-hidden-entry))) ; show entire entry
11160 (when following-p
11161 ;; Show next sibling, or heading below text
11162 (save-excursion
11163 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11164 (org-flag-heading nil))))
11165 (when siblings-p (org-show-siblings))
11166 (when hierarchy-p
11167 ;; show all higher headings, possibly with siblings
11168 (save-excursion
11169 (while (and (condition-case nil
11170 (progn (org-up-heading-all 1) t)
11171 (error nil))
11172 (not (bobp)))
11173 (org-flag-heading nil)
11174 (when siblings-p (org-show-siblings))))))))
11176 (defun org-reveal (&optional siblings)
11177 "Show current entry, hierarchy above it, and the following headline.
11178 This can be used to show a consistent set of context around locations
11179 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11180 not t for the search context.
11182 With optional argument SIBLINGS, on each level of the hierarchy all
11183 siblings are shown. This repairs the tree structure to what it would
11184 look like when opened with hierarchical calls to `org-cycle'."
11185 (interactive "P")
11186 (let ((org-show-hierarchy-above t)
11187 (org-show-following-heading t)
11188 (org-show-siblings (if siblings t org-show-siblings)))
11189 (org-show-context nil)))
11191 (defun org-highlight-new-match (beg end)
11192 "Highlight from BEG to END and mark the highlight is an occur headline."
11193 (let ((ov (org-make-overlay beg end)))
11194 (org-overlay-put ov 'face 'secondary-selection)
11195 (push ov org-occur-highlights)))
11197 (defun org-remove-occur-highlights (&optional beg end noremove)
11198 "Remove the occur highlights from the buffer.
11199 BEG and END are ignored. If NOREMOVE is nil, remove this function
11200 from the `before-change-functions' in the current buffer."
11201 (interactive)
11202 (unless org-inhibit-highlight-removal
11203 (mapc 'org-delete-overlay org-occur-highlights)
11204 (setq org-occur-highlights nil)
11205 (setq org-occur-parameters nil)
11206 (unless noremove
11207 (remove-hook 'before-change-functions
11208 'org-remove-occur-highlights 'local))))
11210 ;;;; Priorities
11212 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11213 "Regular expression matching the priority indicator.")
11215 (defvar org-remove-priority-next-time nil)
11217 (defun org-priority-up ()
11218 "Increase the priority of the current item."
11219 (interactive)
11220 (org-priority 'up))
11222 (defun org-priority-down ()
11223 "Decrease the priority of the current item."
11224 (interactive)
11225 (org-priority 'down))
11227 (defun org-priority (&optional action)
11228 "Change the priority of an item by ARG.
11229 ACTION can be `set', `up', `down', or a character."
11230 (interactive)
11231 (unless org-enable-priority-commands
11232 (error "Priority commands are disabled"))
11233 (setq action (or action 'set))
11234 (let (current new news have remove)
11235 (save-excursion
11236 (org-back-to-heading t)
11237 (if (looking-at org-priority-regexp)
11238 (setq current (string-to-char (match-string 2))
11239 have t)
11240 (setq current org-default-priority))
11241 (cond
11242 ((eq action 'remove)
11243 (setq remove t new ?\ ))
11244 ((or (eq action 'set)
11245 (if (featurep 'xemacs) (characterp action) (integerp action)))
11246 (if (not (eq action 'set))
11247 (setq new action)
11248 (message "Priority %c-%c, SPC to remove: "
11249 org-highest-priority org-lowest-priority)
11250 (setq new (read-char-exclusive)))
11251 (if (and (= (upcase org-highest-priority) org-highest-priority)
11252 (= (upcase org-lowest-priority) org-lowest-priority))
11253 (setq new (upcase new)))
11254 (cond ((equal new ?\ ) (setq remove t))
11255 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11256 (error "Priority must be between `%c' and `%c'"
11257 org-highest-priority org-lowest-priority))))
11258 ((eq action 'up)
11259 (if (and (not have) (eq last-command this-command))
11260 (setq new org-lowest-priority)
11261 (setq new (if (and org-priority-start-cycle-with-default (not have))
11262 org-default-priority (1- current)))))
11263 ((eq action 'down)
11264 (if (and (not have) (eq last-command this-command))
11265 (setq new org-highest-priority)
11266 (setq new (if (and org-priority-start-cycle-with-default (not have))
11267 org-default-priority (1+ current)))))
11268 (t (error "Invalid action")))
11269 (if (or (< (upcase new) org-highest-priority)
11270 (> (upcase new) org-lowest-priority))
11271 (setq remove t))
11272 (setq news (format "%c" new))
11273 (if have
11274 (if remove
11275 (replace-match "" t t nil 1)
11276 (replace-match news t t nil 2))
11277 (if remove
11278 (error "No priority cookie found in line")
11279 (let ((case-fold-search nil))
11280 (looking-at org-todo-line-regexp))
11281 (if (match-end 2)
11282 (progn
11283 (goto-char (match-end 2))
11284 (insert " [#" news "]"))
11285 (goto-char (match-beginning 3))
11286 (insert "[#" news "] "))))
11287 (org-preserve-lc (org-set-tags nil 'align)))
11288 (if remove
11289 (message "Priority removed")
11290 (message "Priority of current item set to %s" news))))
11292 (defun org-get-priority (s)
11293 "Find priority cookie and return priority."
11294 (save-match-data
11295 (if (not (string-match org-priority-regexp s))
11296 (* 1000 (- org-lowest-priority org-default-priority))
11297 (* 1000 (- org-lowest-priority
11298 (string-to-char (match-string 2 s)))))))
11300 ;;;; Tags
11302 (defvar org-agenda-archives-mode)
11303 (defvar org-map-continue-from nil
11304 "Position from where mapping should continue.
11305 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11307 (defvar org-scanner-tags nil
11308 "The current tag list while the tags scanner is running.")
11309 (defvar org-trust-scanner-tags nil
11310 "Should `org-get-tags-at' use the tags fro the scanner.
11311 This is for internal dynamical scoping only.
11312 When this is non-nil, the function `org-get-tags-at' will return the value
11313 of `org-scanner-tags' instead of building the list by itself. This
11314 can lead to large speed-ups when the tags scanner is used in a file with
11315 many entries, and when the list of tags is retrieved, for example to
11316 obtain a list of properties. Building the tags list for each entry in such
11317 a file becomes an N^2 operation - but with this variable set, it scales
11318 as N.")
11320 (defun org-scan-tags (action matcher &optional todo-only)
11321 "Scan headline tags with inheritance and produce output ACTION.
11323 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11324 or `agenda' to produce an entry list for an agenda view. It can also be
11325 a Lisp form or a function that should be called at each matched headline, in
11326 this case the return value is a list of all return values from these calls.
11328 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11329 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11330 only lines with a TODO keyword are included in the output."
11331 (require 'org-agenda)
11332 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11333 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11334 (org-re
11335 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11336 (props (list 'face 'default
11337 'done-face 'org-agenda-done
11338 'undone-face 'default
11339 'mouse-face 'highlight
11340 'org-not-done-regexp org-not-done-regexp
11341 'org-todo-regexp org-todo-regexp
11342 'help-echo
11343 (format "mouse-2 or RET jump to org file %s"
11344 (abbreviate-file-name
11345 (or (buffer-file-name (buffer-base-buffer))
11346 (buffer-name (buffer-base-buffer)))))))
11347 (case-fold-search nil)
11348 (org-map-continue-from nil)
11349 lspos tags tags-list
11350 (tags-alist (list (cons 0 org-file-tags)))
11351 (llast 0) rtn rtn1 level category i txt
11352 todo marker entry priority)
11353 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11354 (setq action (list 'lambda nil action)))
11355 (save-excursion
11356 (goto-char (point-min))
11357 (when (eq action 'sparse-tree)
11358 (org-overview)
11359 (org-remove-occur-highlights))
11360 (while (re-search-forward re nil t)
11361 (catch :skip
11362 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11363 tags (if (match-end 4) (org-match-string-no-properties 4)))
11364 (goto-char (setq lspos (match-beginning 0)))
11365 (setq level (org-reduced-level (funcall outline-level))
11366 category (org-get-category))
11367 (setq i llast llast level)
11368 ;; remove tag lists from same and sublevels
11369 (while (>= i level)
11370 (when (setq entry (assoc i tags-alist))
11371 (setq tags-alist (delete entry tags-alist)))
11372 (setq i (1- i)))
11373 ;; add the next tags
11374 (when tags
11375 (setq tags (org-split-string tags ":")
11376 tags-alist
11377 (cons (cons level tags) tags-alist)))
11378 ;; compile tags for current headline
11379 (setq tags-list
11380 (if org-use-tag-inheritance
11381 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11382 tags)
11383 org-scanner-tags tags-list)
11384 (when org-use-tag-inheritance
11385 (setcdr (car tags-alist)
11386 (mapcar (lambda (x)
11387 (setq x (copy-sequence x))
11388 (org-add-prop-inherited x))
11389 (cdar tags-alist))))
11390 (when (and tags org-use-tag-inheritance
11391 (or (not (eq t org-use-tag-inheritance))
11392 org-tags-exclude-from-inheritance))
11393 ;; selective inheritance, remove uninherited ones
11394 (setcdr (car tags-alist)
11395 (org-remove-uniherited-tags (cdar tags-alist))))
11396 (when (and (or (not todo-only)
11397 (and (member todo org-not-done-keywords)
11398 (or (not org-agenda-tags-todo-honor-ignore-options)
11399 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11400 (let ((case-fold-search t)) (eval matcher))
11402 (not (member org-archive-tag tags-list))
11403 ;; we have an archive tag, should we use this anyway?
11404 (or (not org-agenda-skip-archived-trees)
11405 (and (eq action 'agenda) org-agenda-archives-mode))))
11406 (unless (eq action 'sparse-tree) (org-agenda-skip))
11408 ;; select this headline
11410 (cond
11411 ((eq action 'sparse-tree)
11412 (and org-highlight-sparse-tree-matches
11413 (org-get-heading) (match-end 0)
11414 (org-highlight-new-match
11415 (match-beginning 0) (match-beginning 1)))
11416 (org-show-context 'tags-tree))
11417 ((eq action 'agenda)
11418 (setq txt (org-format-agenda-item
11420 (concat
11421 (if (eq org-tags-match-list-sublevels 'indented)
11422 (make-string (1- level) ?.) "")
11423 (org-get-heading))
11424 category
11425 tags-list
11427 priority (org-get-priority txt))
11428 (goto-char lspos)
11429 (setq marker (org-agenda-new-marker))
11430 (org-add-props txt props
11431 'org-marker marker 'org-hd-marker marker 'org-category category
11432 'todo-state todo
11433 'priority priority 'type "tagsmatch")
11434 (push txt rtn))
11435 ((functionp action)
11436 (setq org-map-continue-from nil)
11437 (save-excursion
11438 (setq rtn1 (funcall action))
11439 (push rtn1 rtn)))
11440 (t (error "Invalid action")))
11442 ;; if we are to skip sublevels, jump to end of subtree
11443 (unless org-tags-match-list-sublevels
11444 (org-end-of-subtree t)
11445 (backward-char 1))))
11446 ;; Get the correct position from where to continue
11447 (if org-map-continue-from
11448 (goto-char org-map-continue-from)
11449 (and (= (point) lspos) (end-of-line 1)))))
11450 (when (and (eq action 'sparse-tree)
11451 (not org-sparse-tree-open-archived-trees))
11452 (org-hide-archived-subtrees (point-min) (point-max)))
11453 (nreverse rtn)))
11455 (defun org-remove-uniherited-tags (tags)
11456 "Remove all tags that are not inherited from the list TAGS."
11457 (cond
11458 ((eq org-use-tag-inheritance t)
11459 (if org-tags-exclude-from-inheritance
11460 (org-delete-all org-tags-exclude-from-inheritance tags)
11461 tags))
11462 ((not org-use-tag-inheritance) nil)
11463 ((stringp org-use-tag-inheritance)
11464 (delq nil (mapcar
11465 (lambda (x)
11466 (if (and (string-match org-use-tag-inheritance x)
11467 (not (member x org-tags-exclude-from-inheritance)))
11468 x nil))
11469 tags)))
11470 ((listp org-use-tag-inheritance)
11471 (delq nil (mapcar
11472 (lambda (x)
11473 (if (member x org-use-tag-inheritance) x nil))
11474 tags)))))
11476 (defvar todo-only) ;; dynamically scoped
11478 (defun org-match-sparse-tree (&optional todo-only match)
11479 "Create a sparse tree according to tags string MATCH.
11480 MATCH can contain positive and negative selection of tags, like
11481 \"+WORK+URGENT-WITHBOSS\".
11482 If optional argument TODO-ONLY is non-nil, only select lines that are
11483 also TODO lines."
11484 (interactive "P")
11485 (org-prepare-agenda-buffers (list (current-buffer)))
11486 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11488 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11490 (defvar org-cached-props nil)
11491 (defun org-cached-entry-get (pom property)
11492 (if (or (eq t org-use-property-inheritance)
11493 (and (stringp org-use-property-inheritance)
11494 (string-match org-use-property-inheritance property))
11495 (and (listp org-use-property-inheritance)
11496 (member property org-use-property-inheritance)))
11497 ;; Caching is not possible, check it directly
11498 (org-entry-get pom property 'inherit)
11499 ;; Get all properties, so that we can do complicated checks easily
11500 (cdr (assoc property (or org-cached-props
11501 (setq org-cached-props
11502 (org-entry-properties pom)))))))
11504 (defun org-global-tags-completion-table (&optional files)
11505 "Return the list of all tags in all agenda buffer/files."
11506 (save-excursion
11507 (org-uniquify
11508 (delq nil
11509 (apply 'append
11510 (mapcar
11511 (lambda (file)
11512 (set-buffer (find-file-noselect file))
11513 (append (org-get-buffer-tags)
11514 (mapcar (lambda (x) (if (stringp (car-safe x))
11515 (list (car-safe x)) nil))
11516 org-tag-alist)))
11517 (if (and files (car files))
11518 files
11519 (org-agenda-files))))))))
11521 (defun org-make-tags-matcher (match)
11522 "Create the TAGS//TODO matcher form for the selection string MATCH."
11523 ;; todo-only is scoped dynamically into this function, and the function
11524 ;; may change it if the matcher asks for it.
11525 (unless match
11526 ;; Get a new match request, with completion
11527 (let ((org-last-tags-completion-table
11528 (org-global-tags-completion-table)))
11529 (setq match (org-completing-read-no-i
11530 "Match: " 'org-tags-completion-function nil nil nil
11531 'org-tags-history))))
11533 ;; Parse the string and create a lisp form
11534 (let ((match0 match)
11535 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11536 minus tag mm
11537 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11538 orterms term orlist re-p str-p level-p level-op time-p
11539 prop-p pn pv po cat-p gv rest)
11540 (if (string-match "/+" match)
11541 ;; match contains also a todo-matching request
11542 (progn
11543 (setq tagsmatch (substring match 0 (match-beginning 0))
11544 todomatch (substring match (match-end 0)))
11545 (if (string-match "^!" todomatch)
11546 (setq todo-only t todomatch (substring todomatch 1)))
11547 (if (string-match "^\\s-*$" todomatch)
11548 (setq todomatch nil)))
11549 ;; only matching tags
11550 (setq tagsmatch match todomatch nil))
11552 ;; Make the tags matcher
11553 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11554 (setq tagsmatcher t)
11555 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11556 (while (setq term (pop orterms))
11557 (while (and (equal (substring term -1) "\\") orterms)
11558 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11559 (while (string-match re term)
11560 (setq rest (substring term (match-end 0))
11561 minus (and (match-end 1)
11562 (equal (match-string 1 term) "-"))
11563 tag (match-string 2 term)
11564 re-p (equal (string-to-char tag) ?{)
11565 level-p (match-end 4)
11566 prop-p (match-end 5)
11567 mm (cond
11568 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11569 (level-p
11570 (setq level-op (org-op-to-function (match-string 3 term)))
11571 `(,level-op level ,(string-to-number
11572 (match-string 4 term))))
11573 (prop-p
11574 (setq pn (match-string 5 term)
11575 po (match-string 6 term)
11576 pv (match-string 7 term)
11577 cat-p (equal pn "CATEGORY")
11578 re-p (equal (string-to-char pv) ?{)
11579 str-p (equal (string-to-char pv) ?\")
11580 time-p (save-match-data
11581 (string-match "^\"[[<].*[]>]\"$" pv))
11582 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11583 (if time-p (setq pv (org-matcher-time pv)))
11584 (setq po (org-op-to-function po (if time-p 'time str-p)))
11585 (cond
11586 ((equal pn "CATEGORY")
11587 (setq gv '(get-text-property (point) 'org-category)))
11588 ((equal pn "TODO")
11589 (setq gv 'todo))
11591 (setq gv `(org-cached-entry-get nil ,pn))))
11592 (if re-p
11593 (if (eq po 'org<>)
11594 `(not (string-match ,pv (or ,gv "")))
11595 `(string-match ,pv (or ,gv "")))
11596 (if str-p
11597 `(,po (or ,gv "") ,pv)
11598 `(,po (string-to-number (or ,gv ""))
11599 ,(string-to-number pv) ))))
11600 (t `(member ,tag tags-list)))
11601 mm (if minus (list 'not mm) mm)
11602 term rest)
11603 (push mm tagsmatcher))
11604 (push (if (> (length tagsmatcher) 1)
11605 (cons 'and tagsmatcher)
11606 (car tagsmatcher))
11607 orlist)
11608 (setq tagsmatcher nil))
11609 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11610 (setq tagsmatcher
11611 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11612 ;; Make the todo matcher
11613 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11614 (setq todomatcher t)
11615 (setq orterms (org-split-string todomatch "|") orlist nil)
11616 (while (setq term (pop orterms))
11617 (while (string-match re term)
11618 (setq minus (and (match-end 1)
11619 (equal (match-string 1 term) "-"))
11620 kwd (match-string 2 term)
11621 re-p (equal (string-to-char kwd) ?{)
11622 term (substring term (match-end 0))
11623 mm (if re-p
11624 `(string-match ,(substring kwd 1 -1) todo)
11625 (list 'equal 'todo kwd))
11626 mm (if minus (list 'not mm) mm))
11627 (push mm todomatcher))
11628 (push (if (> (length todomatcher) 1)
11629 (cons 'and todomatcher)
11630 (car todomatcher))
11631 orlist)
11632 (setq todomatcher nil))
11633 (setq todomatcher (if (> (length orlist) 1)
11634 (cons 'or orlist) (car orlist))))
11636 ;; Return the string and lisp forms of the matcher
11637 (setq matcher (if todomatcher
11638 (list 'and tagsmatcher todomatcher)
11639 tagsmatcher))
11640 (cons match0 matcher)))
11642 (defun org-op-to-function (op &optional stringp)
11643 "Turn an operator into the appropriate function."
11644 (setq op
11645 (cond
11646 ((equal op "<" ) '(< string< org-time<))
11647 ((equal op ">" ) '(> org-string> org-time>))
11648 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11649 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11650 ((member op '("=" "==")) '(= string= org-time=))
11651 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11652 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11654 (defun org<> (a b) (not (= a b)))
11655 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11656 (defun org-string>= (a b) (not (string< a b)))
11657 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11658 (defun org-string<> (a b) (not (string= a b)))
11659 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11660 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11661 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11662 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11663 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11664 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11665 (defun org-2ft (s)
11666 "Convert S to a floating point time.
11667 If S is already a number, just return it. If it is a string, parse
11668 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11669 (cond
11670 ((numberp s) s)
11671 ((stringp s)
11672 (condition-case nil
11673 (float-time (apply 'encode-time (org-parse-time-string s)))
11674 (error 0.)))
11675 (t 0.)))
11677 (defun org-time-today ()
11678 "Time in seconds today at 0:00.
11679 Returns the float number of seconds since the beginning of the
11680 epoch to the beginning of today (00:00)."
11681 (float-time (apply 'encode-time
11682 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11684 (defun org-matcher-time (s)
11685 "Interpret a time comparison value."
11686 (save-match-data
11687 (cond
11688 ((string= s "<now>") (float-time))
11689 ((string= s "<today>") (org-time-today))
11690 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11691 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11692 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11693 (+ (org-time-today)
11694 (* (string-to-number (match-string 1 s))
11695 (cdr (assoc (match-string 2 s)
11696 '(("d" . 86400.0) ("w" . 604800.0)
11697 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11698 (t (org-2ft s)))))
11700 (defun org-match-any-p (re list)
11701 "Does re match any element of list?"
11702 (setq list (mapcar (lambda (x) (string-match re x)) list))
11703 (delq nil list))
11705 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11706 (defvar org-tags-overlay (org-make-overlay 1 1))
11707 (org-detach-overlay org-tags-overlay)
11709 (defun org-get-local-tags-at (&optional pos)
11710 "Get a list of tags defined in the current headline."
11711 (org-get-tags-at pos 'local))
11713 (defun org-get-local-tags ()
11714 "Get a list of tags defined in the current headline."
11715 (org-get-tags-at nil 'local))
11717 (defun org-get-tags-at (&optional pos local)
11718 "Get a list of all headline tags applicable at POS.
11719 POS defaults to point. If tags are inherited, the list contains
11720 the targets in the same sequence as the headlines appear, i.e.
11721 the tags of the current headline come last.
11722 When LOCAL is non-nil, only return tags from the current headline,
11723 ignore inherited ones."
11724 (interactive)
11725 (if (and org-trust-scanner-tags
11726 (or (not pos) (equal pos (point)))
11727 (not local))
11728 org-scanner-tags
11729 (let (tags ltags lastpos parent)
11730 (save-excursion
11731 (save-restriction
11732 (widen)
11733 (goto-char (or pos (point)))
11734 (save-match-data
11735 (catch 'done
11736 (condition-case nil
11737 (progn
11738 (org-back-to-heading t)
11739 (while (not (equal lastpos (point)))
11740 (setq lastpos (point))
11741 (when (looking-at
11742 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11743 (setq ltags (org-split-string
11744 (org-match-string-no-properties 1) ":"))
11745 (when parent
11746 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11747 (setq tags (append
11748 (if parent
11749 (org-remove-uniherited-tags ltags)
11750 ltags)
11751 tags)))
11752 (or org-use-tag-inheritance (throw 'done t))
11753 (if local (throw 'done t))
11754 (or (org-up-heading-safe) (error nil))
11755 (setq parent t)))
11756 (error nil)))))
11757 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11759 (defun org-add-prop-inherited (s)
11760 (add-text-properties 0 (length s) '(inherited t) s)
11763 (defun org-toggle-tag (tag &optional onoff)
11764 "Toggle the tag TAG for the current line.
11765 If ONOFF is `on' or `off', don't toggle but set to this state."
11766 (let (res current)
11767 (save-excursion
11768 (org-back-to-heading t)
11769 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11770 (point-at-eol) t)
11771 (progn
11772 (setq current (match-string 1))
11773 (replace-match ""))
11774 (setq current ""))
11775 (setq current (nreverse (org-split-string current ":")))
11776 (cond
11777 ((eq onoff 'on)
11778 (setq res t)
11779 (or (member tag current) (push tag current)))
11780 ((eq onoff 'off)
11781 (or (not (member tag current)) (setq current (delete tag current))))
11782 (t (if (member tag current)
11783 (setq current (delete tag current))
11784 (setq res t)
11785 (push tag current))))
11786 (end-of-line 1)
11787 (if current
11788 (progn
11789 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11790 (org-set-tags nil t))
11791 (delete-horizontal-space))
11792 (run-hooks 'org-after-tags-change-hook))
11793 res))
11795 (defun org-align-tags-here (to-col)
11796 ;; Assumes that this is a headline
11797 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11798 (beginning-of-line 1)
11799 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11800 (< pos (match-beginning 2)))
11801 (progn
11802 (setq tags-l (- (match-end 2) (match-beginning 2)))
11803 (goto-char (match-beginning 1))
11804 (insert " ")
11805 (delete-region (point) (1+ (match-beginning 2)))
11806 (setq ncol (max (1+ (current-column))
11807 (1+ col)
11808 (if (> to-col 0)
11809 to-col
11810 (- (abs to-col) tags-l))))
11811 (setq p (point))
11812 (insert (make-string (- ncol (current-column)) ?\ ))
11813 (setq ncol (current-column))
11814 (when indent-tabs-mode (tabify p (point-at-eol)))
11815 (org-move-to-column (min ncol col) t))
11816 (goto-char pos))))
11818 (defun org-set-tags-command (&optional arg just-align)
11819 "Call the set-tags command for the current entry."
11820 (interactive "P")
11821 (if (org-on-heading-p)
11822 (org-set-tags arg just-align)
11823 (save-excursion
11824 (org-back-to-heading t)
11825 (org-set-tags arg just-align))))
11827 (defun org-set-tags-to (data)
11828 "Set the tags of the current entry to DATA, replacing the current tags.
11829 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11830 If DATA is nil or the empty string, any tags will be removed."
11831 (interactive "sTags: ")
11832 (setq data
11833 (cond
11834 ((eq data nil) "")
11835 ((equal data "") "")
11836 ((stringp data)
11837 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11838 ":"))
11839 ((listp data)
11840 (concat ":" (mapconcat 'identity data ":") ":"))
11841 (t nil)))
11842 (when data
11843 (save-excursion
11844 (org-back-to-heading t)
11845 (when (looking-at org-complex-heading-regexp)
11846 (if (match-end 5)
11847 (progn
11848 (goto-char (match-beginning 5))
11849 (insert data)
11850 (delete-region (point) (point-at-eol))
11851 (org-set-tags nil 'align))
11852 (goto-char (point-at-eol))
11853 (insert " " data)
11854 (org-set-tags nil 'align)))
11855 (beginning-of-line 1)
11856 (if (looking-at ".*?\\([ \t]+\\)$")
11857 (delete-region (match-beginning 1) (match-end 1))))))
11859 (defun org-set-tags (&optional arg just-align)
11860 "Set the tags for the current headline.
11861 With prefix ARG, realign all tags in headings in the current buffer."
11862 (interactive "P")
11863 (let* ((re (concat "^" outline-regexp))
11864 (current (org-get-tags-string))
11865 (col (current-column))
11866 (org-setting-tags t)
11867 table current-tags inherited-tags ; computed below when needed
11868 tags p0 c0 c1 rpl)
11869 (if arg
11870 (save-excursion
11871 (goto-char (point-min))
11872 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11873 (while (re-search-forward re nil t)
11874 (org-set-tags nil t)
11875 (end-of-line 1)))
11876 (message "All tags realigned to column %d" org-tags-column))
11877 (if just-align
11878 (setq tags current)
11879 ;; Get a new set of tags from the user
11880 (save-excursion
11881 (setq table (append org-tag-persistent-alist
11882 (or org-tag-alist (org-get-buffer-tags))
11883 (and org-complete-tags-always-offer-all-agenda-tags
11884 (org-global-tags-completion-table (org-agenda-files))))
11885 org-last-tags-completion-table table
11886 current-tags (org-split-string current ":")
11887 inherited-tags (nreverse
11888 (nthcdr (length current-tags)
11889 (nreverse (org-get-tags-at))))
11890 tags
11891 (if (or (eq t org-use-fast-tag-selection)
11892 (and org-use-fast-tag-selection
11893 (delq nil (mapcar 'cdr table))))
11894 (org-fast-tag-selection
11895 current-tags inherited-tags table
11896 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11897 (let ((org-add-colon-after-tag-completion t))
11898 (org-trim
11899 (org-without-partial-completion
11900 (org-icompleting-read "Tags: " 'org-tags-completion-function
11901 nil nil current 'org-tags-history)))))))
11902 (while (string-match "[-+&]+" tags)
11903 ;; No boolean logic, just a list
11904 (setq tags (replace-match ":" t t tags))))
11906 (if org-tags-sort-function
11907 (setq tags (mapconcat 'identity
11908 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11909 org-tags-sort-function) ":")))
11911 (if (string-match "\\`[\t ]*\\'" tags)
11912 (setq tags "")
11913 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11914 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11916 ;; Insert new tags at the correct column
11917 (beginning-of-line 1)
11918 (cond
11919 ((and (equal current "") (equal tags "")))
11920 ((re-search-forward
11921 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11922 (point-at-eol) t)
11923 (if (equal tags "")
11924 (setq rpl "")
11925 (goto-char (match-beginning 0))
11926 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11927 (1+ (point)) (point))
11928 c1 (max (1+ c0) (if (> org-tags-column 0)
11929 org-tags-column
11930 (- (- org-tags-column) (length tags))))
11931 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11932 (replace-match rpl t t)
11933 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11934 tags)
11935 (t (error "Tags alignment failed")))
11936 (org-move-to-column col)
11937 (unless just-align
11938 (run-hooks 'org-after-tags-change-hook)))))
11940 (defun org-change-tag-in-region (beg end tag off)
11941 "Add or remove TAG for each entry in the region.
11942 This works in the agenda, and also in an org-mode buffer."
11943 (interactive
11944 (list (region-beginning) (region-end)
11945 (let ((org-last-tags-completion-table
11946 (if (org-mode-p)
11947 (org-get-buffer-tags)
11948 (org-global-tags-completion-table))))
11949 (org-icompleting-read
11950 "Tag: " 'org-tags-completion-function nil nil nil
11951 'org-tags-history))
11952 (progn
11953 (message "[s]et or [r]emove? ")
11954 (equal (read-char-exclusive) ?r))))
11955 (if (fboundp 'deactivate-mark) (deactivate-mark))
11956 (let ((agendap (equal major-mode 'org-agenda-mode))
11957 l1 l2 m buf pos newhead (cnt 0))
11958 (goto-char end)
11959 (setq l2 (1- (org-current-line)))
11960 (goto-char beg)
11961 (setq l1 (org-current-line))
11962 (loop for l from l1 to l2 do
11963 (org-goto-line l)
11964 (setq m (get-text-property (point) 'org-hd-marker))
11965 (when (or (and (org-mode-p) (org-on-heading-p))
11966 (and agendap m))
11967 (setq buf (if agendap (marker-buffer m) (current-buffer))
11968 pos (if agendap m (point)))
11969 (with-current-buffer buf
11970 (save-excursion
11971 (save-restriction
11972 (goto-char pos)
11973 (setq cnt (1+ cnt))
11974 (org-toggle-tag tag (if off 'off 'on))
11975 (setq newhead (org-get-heading)))))
11976 (and agendap (org-agenda-change-all-lines newhead m))))
11977 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11979 (defun org-tags-completion-function (string predicate &optional flag)
11980 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11981 (confirm (lambda (x) (stringp (car x)))))
11982 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11983 (setq s1 (match-string 1 string)
11984 s2 (match-string 2 string))
11985 (setq s1 "" s2 string))
11986 (cond
11987 ((eq flag nil)
11988 ;; try completion
11989 (setq rtn (try-completion s2 ctable confirm))
11990 (if (stringp rtn)
11991 (setq rtn
11992 (concat s1 s2 (substring rtn (length s2))
11993 (if (and org-add-colon-after-tag-completion
11994 (assoc rtn ctable))
11995 ":" ""))))
11996 rtn)
11997 ((eq flag t)
11998 ;; all-completions
11999 (all-completions s2 ctable confirm)
12001 ((eq flag 'lambda)
12002 ;; exact match?
12003 (assoc s2 ctable)))
12006 (defun org-fast-tag-insert (kwd tags face &optional end)
12007 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12008 (insert (format "%-12s" (concat kwd ":"))
12009 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12010 (or end "")))
12012 (defun org-fast-tag-show-exit (flag)
12013 (save-excursion
12014 (org-goto-line 3)
12015 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12016 (replace-match ""))
12017 (when flag
12018 (end-of-line 1)
12019 (org-move-to-column (- (window-width) 19) t)
12020 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12022 (defun org-set-current-tags-overlay (current prefix)
12023 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12024 (if (featurep 'xemacs)
12025 (org-overlay-display org-tags-overlay (concat prefix s)
12026 'secondary-selection)
12027 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12028 (org-overlay-display org-tags-overlay (concat prefix s)))))
12030 (defvar org-last-tag-selection-key nil)
12031 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12032 "Fast tag selection with single keys.
12033 CURRENT is the current list of tags in the headline, INHERITED is the
12034 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12035 possibly with grouping information. TODO-TABLE is a similar table with
12036 TODO keywords, should these have keys assigned to them.
12037 If the keys are nil, a-z are automatically assigned.
12038 Returns the new tags string, or nil to not change the current settings."
12039 (let* ((fulltable (append table todo-table))
12040 (maxlen (apply 'max (mapcar
12041 (lambda (x)
12042 (if (stringp (car x)) (string-width (car x)) 0))
12043 fulltable)))
12044 (buf (current-buffer))
12045 (expert (eq org-fast-tag-selection-single-key 'expert))
12046 (buffer-tags nil)
12047 (fwidth (+ maxlen 3 1 3))
12048 (ncol (/ (- (window-width) 4) fwidth))
12049 (i-face 'org-done)
12050 (c-face 'org-todo)
12051 tg cnt e c char c1 c2 ntable tbl rtn
12052 ov-start ov-end ov-prefix
12053 (exit-after-next org-fast-tag-selection-single-key)
12054 (done-keywords org-done-keywords)
12055 groups ingroup)
12056 (save-excursion
12057 (beginning-of-line 1)
12058 (if (looking-at
12059 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12060 (setq ov-start (match-beginning 1)
12061 ov-end (match-end 1)
12062 ov-prefix "")
12063 (setq ov-start (1- (point-at-eol))
12064 ov-end (1+ ov-start))
12065 (skip-chars-forward "^\n\r")
12066 (setq ov-prefix
12067 (concat
12068 (buffer-substring (1- (point)) (point))
12069 (if (> (current-column) org-tags-column)
12071 (make-string (- org-tags-column (current-column)) ?\ ))))))
12072 (org-move-overlay org-tags-overlay ov-start ov-end)
12073 (save-window-excursion
12074 (if expert
12075 (set-buffer (get-buffer-create " *Org tags*"))
12076 (delete-other-windows)
12077 (split-window-vertically)
12078 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12079 (erase-buffer)
12080 (org-set-local 'org-done-keywords done-keywords)
12081 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12082 (org-fast-tag-insert "Current" current c-face "\n\n")
12083 (org-fast-tag-show-exit exit-after-next)
12084 (org-set-current-tags-overlay current ov-prefix)
12085 (setq tbl fulltable char ?a cnt 0)
12086 (while (setq e (pop tbl))
12087 (cond
12088 ((equal (car e) :startgroup)
12089 (push '() groups) (setq ingroup t)
12090 (when (not (= cnt 0))
12091 (setq cnt 0)
12092 (insert "\n"))
12093 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12094 ((equal (car e) :endgroup)
12095 (setq ingroup nil cnt 0)
12096 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12097 ((equal e '(:newline))
12098 (when (not (= cnt 0))
12099 (setq cnt 0)
12100 (insert "\n")
12101 (setq e (car tbl))
12102 (while (equal (car tbl) '(:newline))
12103 (insert "\n")
12104 (setq tbl (cdr tbl)))))
12106 (setq tg (copy-sequence (car e)) c2 nil)
12107 (if (cdr e)
12108 (setq c (cdr e))
12109 ;; automatically assign a character.
12110 (setq c1 (string-to-char
12111 (downcase (substring
12112 tg (if (= (string-to-char tg) ?@) 1 0)))))
12113 (if (or (rassoc c1 ntable) (rassoc c1 table))
12114 (while (or (rassoc char ntable) (rassoc char table))
12115 (setq char (1+ char)))
12116 (setq c2 c1))
12117 (setq c (or c2 char)))
12118 (if ingroup (push tg (car groups)))
12119 (setq tg (org-add-props tg nil 'face
12120 (cond
12121 ((not (assoc tg table))
12122 (org-get-todo-face tg))
12123 ((member tg current) c-face)
12124 ((member tg inherited) i-face)
12125 (t nil))))
12126 (if (and (= cnt 0) (not ingroup)) (insert " "))
12127 (insert "[" c "] " tg (make-string
12128 (- fwidth 4 (length tg)) ?\ ))
12129 (push (cons tg c) ntable)
12130 (when (= (setq cnt (1+ cnt)) ncol)
12131 (insert "\n")
12132 (if ingroup (insert " "))
12133 (setq cnt 0)))))
12134 (setq ntable (nreverse ntable))
12135 (insert "\n")
12136 (goto-char (point-min))
12137 (if (not expert) (org-fit-window-to-buffer))
12138 (setq rtn
12139 (catch 'exit
12140 (while t
12141 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12142 (if (not groups) "no " "")
12143 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12144 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12145 (setq org-last-tag-selection-key c)
12146 (cond
12147 ((= c ?\r) (throw 'exit t))
12148 ((= c ?!)
12149 (setq groups (not groups))
12150 (goto-char (point-min))
12151 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12152 ((= c ?\C-c)
12153 (if (not expert)
12154 (org-fast-tag-show-exit
12155 (setq exit-after-next (not exit-after-next)))
12156 (setq expert nil)
12157 (delete-other-windows)
12158 (split-window-vertically)
12159 (org-switch-to-buffer-other-window " *Org tags*")
12160 (org-fit-window-to-buffer)))
12161 ((or (= c ?\C-g)
12162 (and (= c ?q) (not (rassoc c ntable))))
12163 (org-detach-overlay org-tags-overlay)
12164 (setq quit-flag t))
12165 ((= c ?\ )
12166 (setq current nil)
12167 (if exit-after-next (setq exit-after-next 'now)))
12168 ((= c ?\t)
12169 (condition-case nil
12170 (setq tg (org-icompleting-read
12171 "Tag: "
12172 (or buffer-tags
12173 (with-current-buffer buf
12174 (org-get-buffer-tags)))))
12175 (quit (setq tg "")))
12176 (when (string-match "\\S-" tg)
12177 (add-to-list 'buffer-tags (list tg))
12178 (if (member tg current)
12179 (setq current (delete tg current))
12180 (push tg current)))
12181 (if exit-after-next (setq exit-after-next 'now)))
12182 ((setq e (rassoc c todo-table) tg (car e))
12183 (with-current-buffer buf
12184 (save-excursion (org-todo tg)))
12185 (if exit-after-next (setq exit-after-next 'now)))
12186 ((setq e (rassoc c ntable) tg (car e))
12187 (if (member tg current)
12188 (setq current (delete tg current))
12189 (loop for g in groups do
12190 (if (member tg g)
12191 (mapc (lambda (x)
12192 (setq current (delete x current)))
12193 g)))
12194 (push tg current))
12195 (if exit-after-next (setq exit-after-next 'now))))
12197 ;; Create a sorted list
12198 (setq current
12199 (sort current
12200 (lambda (a b)
12201 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12202 (if (eq exit-after-next 'now) (throw 'exit t))
12203 (goto-char (point-min))
12204 (beginning-of-line 2)
12205 (delete-region (point) (point-at-eol))
12206 (org-fast-tag-insert "Current" current c-face)
12207 (org-set-current-tags-overlay current ov-prefix)
12208 (while (re-search-forward
12209 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12210 (setq tg (match-string 1))
12211 (add-text-properties
12212 (match-beginning 1) (match-end 1)
12213 (list 'face
12214 (cond
12215 ((member tg current) c-face)
12216 ((member tg inherited) i-face)
12217 (t (get-text-property (match-beginning 1) 'face))))))
12218 (goto-char (point-min)))))
12219 (org-detach-overlay org-tags-overlay)
12220 (if rtn
12221 (mapconcat 'identity current ":")
12222 nil))))
12224 (defun org-get-tags-string ()
12225 "Get the TAGS string in the current headline."
12226 (unless (org-on-heading-p t)
12227 (error "Not on a heading"))
12228 (save-excursion
12229 (beginning-of-line 1)
12230 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12231 (org-match-string-no-properties 1)
12232 "")))
12234 (defun org-get-tags ()
12235 "Get the list of tags specified in the current headline."
12236 (org-split-string (org-get-tags-string) ":"))
12238 (defun org-get-buffer-tags ()
12239 "Get a table of all tags used in the buffer, for completion."
12240 (let (tags)
12241 (save-excursion
12242 (goto-char (point-min))
12243 (while (re-search-forward
12244 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12245 (when (equal (char-after (point-at-bol 0)) ?*)
12246 (mapc (lambda (x) (add-to-list 'tags x))
12247 (org-split-string (org-match-string-no-properties 1) ":")))))
12248 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12249 (mapcar 'list tags)))
12251 ;;;; The mapping API
12253 ;;;###autoload
12254 (defun org-map-entries (func &optional match scope &rest skip)
12255 "Call FUNC at each headline selected by MATCH in SCOPE.
12257 FUNC is a function or a lisp form. The function will be called without
12258 arguments, with the cursor positioned at the beginning of the headline.
12259 The return values of all calls to the function will be collected and
12260 returned as a list.
12262 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12263 does not need to preserve point. After evaluation, the cursor will be
12264 moved to the end of the line (presumably of the headline of the
12265 processed entry) and search continues from there. Under some
12266 circumstances, this may not produce the wanted results. For example,
12267 if you have removed (e.g. archived) the current (sub)tree it could
12268 mean that the next entry will be skipped entirely. In such cases, you
12269 can specify the position from where search should continue by making
12270 FUNC set the variable `org-map-continue-from' to the desired buffer
12271 position.
12273 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12274 Only headlines that are matched by this query will be considered during
12275 the iteration. When MATCH is nil or t, all headlines will be
12276 visited by the iteration.
12278 SCOPE determines the scope of this command. It can be any of:
12280 nil The current buffer, respecting the restriction if any
12281 tree The subtree started with the entry at point
12282 file The current buffer, without restriction
12283 file-with-archives
12284 The current buffer, and any archives associated with it
12285 agenda All agenda files
12286 agenda-with-archives
12287 All agenda files with any archive files associated with them
12288 \(file1 file2 ...)
12289 If this is a list, all files in the list will be scanned
12291 The remaining args are treated as settings for the skipping facilities of
12292 the scanner. The following items can be given here:
12294 archive skip trees with the archive tag.
12295 comment skip trees with the COMMENT keyword
12296 function or Emacs Lisp form:
12297 will be used as value for `org-agenda-skip-function', so whenever
12298 the function returns t, FUNC will not be called for that
12299 entry and search will continue from the point where the
12300 function leaves it.
12302 If your function needs to retrieve the tags including inherited tags
12303 at the *current* entry, you can use the value of the variable
12304 `org-scanner-tags' which will be much faster than getting the value
12305 with `org-get-tags-at'. If your function gets properties with
12306 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12307 to t around the call to `org-entry-properties' to get the same speedup.
12308 Note that if your function moves around to retrieve tags and properties at
12309 a *different* entry, you cannot use these techniques."
12310 (let* ((org-agenda-archives-mode nil) ; just to make sure
12311 (org-agenda-skip-archived-trees (memq 'archive skip))
12312 (org-agenda-skip-comment-trees (memq 'comment skip))
12313 (org-agenda-skip-function
12314 (car (org-delete-all '(comment archive) skip)))
12315 (org-tags-match-list-sublevels t)
12316 matcher file res
12317 org-todo-keywords-for-agenda
12318 org-done-keywords-for-agenda
12319 org-todo-keyword-alist-for-agenda
12320 org-drawers-for-agenda
12321 org-tag-alist-for-agenda)
12323 (cond
12324 ((eq match t) (setq matcher t))
12325 ((eq match nil) (setq matcher t))
12326 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12328 (save-excursion
12329 (save-restriction
12330 (when (eq scope 'tree)
12331 (org-back-to-heading t)
12332 (org-narrow-to-subtree)
12333 (setq scope nil))
12335 (if (not scope)
12336 (progn
12337 (org-prepare-agenda-buffers
12338 (list (buffer-file-name (current-buffer))))
12339 (setq res (org-scan-tags func matcher)))
12340 ;; Get the right scope
12341 (cond
12342 ((and scope (listp scope) (symbolp (car scope)))
12343 (setq scope (eval scope)))
12344 ((eq scope 'agenda)
12345 (setq scope (org-agenda-files t)))
12346 ((eq scope 'agenda-with-archives)
12347 (setq scope (org-agenda-files t))
12348 (setq scope (org-add-archive-files scope)))
12349 ((eq scope 'file)
12350 (setq scope (list (buffer-file-name))))
12351 ((eq scope 'file-with-archives)
12352 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12353 (org-prepare-agenda-buffers scope)
12354 (while (setq file (pop scope))
12355 (with-current-buffer (org-find-base-buffer-visiting file)
12356 (save-excursion
12357 (save-restriction
12358 (widen)
12359 (goto-char (point-min))
12360 (setq res (append res (org-scan-tags func matcher))))))))))
12361 res))
12363 ;;;; Properties
12365 ;;; Setting and retrieving properties
12367 (defconst org-special-properties
12368 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12369 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12370 "The special properties valid in Org-mode.
12372 These are properties that are not defined in the property drawer,
12373 but in some other way.")
12375 (defconst org-default-properties
12376 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12377 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12378 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12379 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12380 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12381 "CLOCK_MODELINE_TOTAL" "STYLE")
12382 "Some properties that are used by Org-mode for various purposes.
12383 Being in this list makes sure that they are offered for completion.")
12385 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12386 "Regular expression matching the first line of a property drawer.")
12388 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12389 "Regular expression matching the first line of a property drawer.")
12391 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12392 "Regular expression matching the first line of a property drawer.")
12394 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12395 "Regular expression matching the first line of a property drawer.")
12397 (defconst org-property-drawer-re
12398 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12399 org-property-end-re "\\)\n?")
12400 "Matches an entire property drawer.")
12402 (defconst org-clock-drawer-re
12403 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12404 org-property-end-re "\\)\n?")
12405 "Matches an entire clock drawer.")
12407 (defun org-property-action ()
12408 "Do an action on properties."
12409 (interactive)
12410 (let (c)
12411 (org-at-property-p)
12412 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12413 (setq c (read-char-exclusive))
12414 (cond
12415 ((equal c ?s)
12416 (call-interactively 'org-set-property))
12417 ((equal c ?d)
12418 (call-interactively 'org-delete-property))
12419 ((equal c ?D)
12420 (call-interactively 'org-delete-property-globally))
12421 ((equal c ?c)
12422 (call-interactively 'org-compute-property-at-point))
12423 (t (error "No such property action %c" c)))))
12425 (defun org-set-effort (&optional value)
12426 "Set the effort property of the current entry.
12427 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12428 allowed value."
12429 (interactive "P")
12430 (if (equal value 0) (setq value 10))
12431 (let* ((completion-ignore-case t)
12432 (prop org-effort-property)
12433 (cur (org-entry-get nil prop))
12434 (allowed (org-property-get-allowed-values nil prop 'table))
12435 (existing (mapcar 'list (org-property-values prop)))
12437 (val (cond
12438 ((stringp value) value)
12439 ((and allowed (integerp value))
12440 (or (car (nth (1- value) allowed))
12441 (car (org-last allowed))))
12442 (allowed
12443 (message "Select 1-9,0, [RET%s]: %s"
12444 (if cur (concat "=" cur) "")
12445 (mapconcat 'car allowed " "))
12446 (setq rpl (read-char-exclusive))
12447 (if (equal rpl ?\r)
12449 (setq rpl (- rpl ?0))
12450 (if (equal rpl 0) (setq rpl 10))
12451 (if (and (> rpl 0) (<= rpl (length allowed)))
12452 (car (nth (1- rpl) allowed))
12453 (org-completing-read "Effort: " allowed nil))))
12455 (let (org-completion-use-ido org-completion-use-iswitchb)
12456 (org-completing-read
12457 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12458 (concat "[" cur "]") "")
12459 ": ")
12460 existing nil nil "" nil cur))))))
12461 (unless (equal (org-entry-get nil prop) val)
12462 (org-entry-put nil prop val))
12463 (message "%s is now %s" prop val)))
12465 (defun org-at-property-p ()
12466 "Is the cursor in a property line?"
12467 ;; FIXME: Does not check if we are actually in the drawer.
12468 ;; FIXME: also returns true on any drawers.....
12469 ;; This is used by C-c C-c for property action.
12470 (save-excursion
12471 (beginning-of-line 1)
12472 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12474 (defun org-get-property-block (&optional beg end force)
12475 "Return the (beg . end) range of the body of the property drawer.
12476 BEG and END can be beginning and end of subtree, if not given
12477 they will be found.
12478 If the drawer does not exist and FORCE is non-nil, create the drawer."
12479 (catch 'exit
12480 (save-excursion
12481 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12482 (end (or end (progn (outline-next-heading) (point)))))
12483 (goto-char beg)
12484 (if (re-search-forward org-property-start-re end t)
12485 (setq beg (1+ (match-end 0)))
12486 (if force
12487 (save-excursion
12488 (org-insert-property-drawer)
12489 (setq end (progn (outline-next-heading) (point))))
12490 (throw 'exit nil))
12491 (goto-char beg)
12492 (if (re-search-forward org-property-start-re end t)
12493 (setq beg (1+ (match-end 0)))))
12494 (if (re-search-forward org-property-end-re end t)
12495 (setq end (match-beginning 0))
12496 (or force (throw 'exit nil))
12497 (goto-char beg)
12498 (setq end beg)
12499 (org-indent-line-function)
12500 (insert ":END:\n"))
12501 (cons beg end)))))
12503 (defun org-entry-properties (&optional pom which specific)
12504 "Get all properties of the entry at point-or-marker POM.
12505 This includes the TODO keyword, the tags, time strings for deadline,
12506 scheduled, and clocking, and any additional properties defined in the
12507 entry. The return value is an alist, keys may occur multiple times
12508 if the property key was used several times.
12509 POM may also be nil, in which case the current entry is used.
12510 If WHICH is nil or `all', get all properties. If WHICH is
12511 `special' or `standard', only get that subclass. If WHICH
12512 is a string only get exactly this property. Specific can be a sting, the
12513 specific property we are interested in. Specifying it can speed
12514 things up because then unnecessary parsing is avoided."
12515 (setq which (or which 'all))
12516 (org-with-point-at pom
12517 (let ((clockstr (substring org-clock-string 0 -1))
12518 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12519 beg end range props sum-props key value string clocksum)
12520 (save-excursion
12521 (when (condition-case nil
12522 (and (org-mode-p) (org-back-to-heading t))
12523 (error nil))
12524 (setq beg (point))
12525 (setq sum-props (get-text-property (point) 'org-summaries))
12526 (setq clocksum (get-text-property (point) :org-clock-minutes))
12527 (outline-next-heading)
12528 (setq end (point))
12529 (when (memq which '(all special))
12530 ;; Get the special properties, like TODO and tags
12531 (goto-char beg)
12532 (when (and (or (not specific) (string= specific "TODO"))
12533 (looking-at org-todo-line-regexp) (match-end 2))
12534 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12535 (when (and (or (not specific) (string= specific "PRIORITY"))
12536 (looking-at org-priority-regexp))
12537 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12538 (when (and (or (not specific) (string= specific "TAGS"))
12539 (setq value (org-get-tags-string))
12540 (string-match "\\S-" value))
12541 (push (cons "TAGS" value) props))
12542 (when (and (or (not specific) (string= specific "TAGS"))
12543 (setq value (org-get-tags-at)))
12544 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12545 ":"))
12546 props))
12547 (when (or (not specific) (string= specific "TAGS"))
12548 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12549 (when (or (not specific)
12550 (member specific org-all-time-keywords)
12551 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12552 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12553 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12554 string (if (equal key clockstr)
12555 (org-no-properties
12556 (org-trim
12557 (buffer-substring
12558 (match-beginning 3) (goto-char (point-at-eol)))))
12559 (substring (org-match-string-no-properties 3) 1 -1)))
12560 (unless key
12561 (if (= (char-after (match-beginning 3)) ?\[)
12562 (setq key "TIMESTAMP_IA")
12563 (setq key "TIMESTAMP")))
12564 (when (or (equal key clockstr) (not (assoc key props)))
12565 (push (cons key string) props))))
12569 (when (memq which '(all standard))
12570 ;; Get the standard properties, like :PROP: ...
12571 (setq range (org-get-property-block beg end))
12572 (when range
12573 (goto-char (car range))
12574 (while (re-search-forward
12575 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12576 (cdr range) t)
12577 (setq key (org-match-string-no-properties 1)
12578 value (org-trim (or (org-match-string-no-properties 2) "")))
12579 (unless (member key excluded)
12580 (push (cons key (or value "")) props)))))
12581 (if clocksum
12582 (push (cons "CLOCKSUM"
12583 (org-columns-number-to-string (/ (float clocksum) 60.)
12584 'add_times))
12585 props))
12586 (unless (assoc "CATEGORY" props)
12587 (setq value (or (org-get-category)
12588 (progn (org-refresh-category-properties)
12589 (org-get-category))))
12590 (push (cons "CATEGORY" value) props))
12591 (append sum-props (nreverse props)))))))
12593 (defun org-entry-get (pom property &optional inherit)
12594 "Get value of PROPERTY for entry at point-or-marker POM.
12595 If INHERIT is non-nil and the entry does not have the property,
12596 then also check higher levels of the hierarchy.
12597 If INHERIT is the symbol `selective', use inheritance only if the setting
12598 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12599 If the property is present but empty, the return value is the empty string.
12600 If the property is not present at all, nil is returned."
12601 (org-with-point-at pom
12602 (if (and inherit (if (eq inherit 'selective)
12603 (org-property-inherit-p property)
12605 (org-entry-get-with-inheritance property)
12606 (if (member property org-special-properties)
12607 ;; We need a special property. Use `org-entry-properties' to
12608 ;; retrieve it, but specify the wanted property
12609 (cdr (assoc property (org-entry-properties nil 'special property)))
12610 (let ((range (org-get-property-block)))
12611 (if (and range
12612 (goto-char (car range))
12613 (re-search-forward
12614 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12615 (cdr range) t))
12616 ;; Found the property, return it.
12617 (if (match-end 1)
12618 (org-match-string-no-properties 1)
12619 "")))))))
12621 (defun org-property-or-variable-value (var &optional inherit)
12622 "Check if there is a property fixing the value of VAR.
12623 If yes, return this value. If not, return the current value of the variable."
12624 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12625 (if (and prop (stringp prop) (string-match "\\S-" prop))
12626 (read prop)
12627 (symbol-value var))))
12629 (defun org-entry-delete (pom property)
12630 "Delete the property PROPERTY from entry at point-or-marker POM."
12631 (org-with-point-at pom
12632 (if (member property org-special-properties)
12633 nil ; cannot delete these properties.
12634 (let ((range (org-get-property-block)))
12635 (if (and range
12636 (goto-char (car range))
12637 (re-search-forward
12638 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12639 (cdr range) t))
12640 (progn
12641 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12643 nil)))))
12645 ;; Multi-values properties are properties that contain multiple values
12646 ;; These values are assumed to be single words, separated by whitespace.
12647 (defun org-entry-add-to-multivalued-property (pom property value)
12648 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12649 (let* ((old (org-entry-get pom property))
12650 (values (and old (org-split-string old "[ \t]"))))
12651 (setq value (org-entry-protect-space value))
12652 (unless (member value values)
12653 (setq values (cons value values))
12654 (org-entry-put pom property
12655 (mapconcat 'identity values " ")))))
12657 (defun org-entry-remove-from-multivalued-property (pom property value)
12658 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12659 (let* ((old (org-entry-get pom property))
12660 (values (and old (org-split-string old "[ \t]"))))
12661 (setq value (org-entry-protect-space value))
12662 (when (member value values)
12663 (setq values (delete value values))
12664 (org-entry-put pom property
12665 (mapconcat 'identity values " ")))))
12667 (defun org-entry-member-in-multivalued-property (pom property value)
12668 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12669 (let* ((old (org-entry-get pom property))
12670 (values (and old (org-split-string old "[ \t]"))))
12671 (setq value (org-entry-protect-space value))
12672 (member value values)))
12674 (defun org-entry-get-multivalued-property (pom property)
12675 "Return a list of values in a multivalued property."
12676 (let* ((value (org-entry-get pom property))
12677 (values (and value (org-split-string value "[ \t]"))))
12678 (mapcar 'org-entry-restore-space values)))
12680 (defun org-entry-put-multivalued-property (pom property &rest values)
12681 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12682 VALUES should be a list of strings. Spaces will be protected."
12683 (org-entry-put pom property
12684 (mapconcat 'org-entry-protect-space values " "))
12685 (let* ((value (org-entry-get pom property))
12686 (values (and value (org-split-string value "[ \t]"))))
12687 (mapcar 'org-entry-restore-space values)))
12689 (defun org-entry-protect-space (s)
12690 "Protect spaces and newline in string S."
12691 (while (string-match " " s)
12692 (setq s (replace-match "%20" t t s)))
12693 (while (string-match "\n" s)
12694 (setq s (replace-match "%0A" t t s)))
12697 (defun org-entry-restore-space (s)
12698 "Restore spaces and newline in string S."
12699 (while (string-match "%20" s)
12700 (setq s (replace-match " " t t s)))
12701 (while (string-match "%0A" s)
12702 (setq s (replace-match "\n" t t s)))
12705 (defvar org-entry-property-inherited-from (make-marker)
12706 "Marker pointing to the entry from where a property was inherited.
12707 Each call to `org-entry-get-with-inheritance' will set this marker to the
12708 location of the entry where the inheritance search matched. If there was
12709 no match, the marker will point nowhere.
12710 Note that also `org-entry-get' calls this function, if the INHERIT flag
12711 is set.")
12713 (defun org-entry-get-with-inheritance (property)
12714 "Get entry property, and search higher levels if not present."
12715 (move-marker org-entry-property-inherited-from nil)
12716 (let (tmp)
12717 (save-excursion
12718 (save-restriction
12719 (widen)
12720 (catch 'ex
12721 (while t
12722 (when (setq tmp (org-entry-get nil property))
12723 (org-back-to-heading t)
12724 (move-marker org-entry-property-inherited-from (point))
12725 (throw 'ex tmp))
12726 (or (org-up-heading-safe) (throw 'ex nil)))))
12727 (or tmp
12728 (cdr (assoc property org-file-properties))
12729 (cdr (assoc property org-global-properties))
12730 (cdr (assoc property org-global-properties-fixed))))))
12732 (defvar org-property-changed-functions nil
12733 "Hook called when the value of a property has changed.
12734 Each hook function should accept two arguments, the name of the property
12735 and the new value.")
12737 (defun org-entry-put (pom property value)
12738 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12739 (org-with-point-at pom
12740 (org-back-to-heading t)
12741 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12742 range)
12743 (cond
12744 ((equal property "TODO")
12745 (when (and (stringp value) (string-match "\\S-" value)
12746 (not (member value org-todo-keywords-1)))
12747 (error "\"%s\" is not a valid TODO state" value))
12748 (if (or (not value)
12749 (not (string-match "\\S-" value)))
12750 (setq value 'none))
12751 (org-todo value)
12752 (org-set-tags nil 'align))
12753 ((equal property "PRIORITY")
12754 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12755 (string-to-char value) ?\ ))
12756 (org-set-tags nil 'align))
12757 ((equal property "SCHEDULED")
12758 (if (re-search-forward org-scheduled-time-regexp end t)
12759 (cond
12760 ((eq value 'earlier) (org-timestamp-change -1 'day))
12761 ((eq value 'later) (org-timestamp-change 1 'day))
12762 (t (call-interactively 'org-schedule)))
12763 (call-interactively 'org-schedule)))
12764 ((equal property "DEADLINE")
12765 (if (re-search-forward org-deadline-time-regexp end t)
12766 (cond
12767 ((eq value 'earlier) (org-timestamp-change -1 'day))
12768 ((eq value 'later) (org-timestamp-change 1 'day))
12769 (t (call-interactively 'org-deadline)))
12770 (call-interactively 'org-deadline)))
12771 ((member property org-special-properties)
12772 (error "The %s property can not yet be set with `org-entry-put'"
12773 property))
12774 (t ; a non-special property
12775 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12776 (setq range (org-get-property-block beg end 'force))
12777 (goto-char (car range))
12778 (if (re-search-forward
12779 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12780 (progn
12781 (delete-region (match-beginning 1) (match-end 1))
12782 (goto-char (match-beginning 1)))
12783 (goto-char (cdr range))
12784 (insert "\n")
12785 (backward-char 1)
12786 (org-indent-line-function)
12787 (insert ":" property ":"))
12788 (and value (insert " " value))
12789 (org-indent-line-function)))))
12790 (run-hook-with-args 'org-property-changed-functions property value)))
12792 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12793 "Get all property keys in the current buffer.
12794 With INCLUDE-SPECIALS, also list the special properties that reflect things
12795 like tags and TODO state.
12796 With INCLUDE-DEFAULTS, also include properties that has special meaning
12797 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12798 With INCLUDE-COLUMNS, also include property names given in COLUMN
12799 formats in the current buffer."
12800 (let (rtn range cfmt s p)
12801 (save-excursion
12802 (save-restriction
12803 (widen)
12804 (goto-char (point-min))
12805 (while (re-search-forward org-property-start-re nil t)
12806 (setq range (org-get-property-block))
12807 (goto-char (car range))
12808 (while (re-search-forward
12809 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12810 (cdr range) t)
12811 (add-to-list 'rtn (org-match-string-no-properties 1)))
12812 (outline-next-heading))))
12814 (when include-specials
12815 (setq rtn (append org-special-properties rtn)))
12817 (when include-defaults
12818 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12819 (add-to-list 'rtn org-effort-property))
12821 (when include-columns
12822 (save-excursion
12823 (save-restriction
12824 (widen)
12825 (goto-char (point-min))
12826 (while (re-search-forward
12827 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12828 nil t)
12829 (setq cfmt (match-string 2) s 0)
12830 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12831 cfmt s)
12832 (setq s (match-end 0)
12833 p (match-string 1 cfmt))
12834 (unless (or (equal p "ITEM")
12835 (member p org-special-properties))
12836 (add-to-list 'rtn (match-string 1 cfmt))))))))
12838 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12840 (defun org-property-values (key)
12841 "Return a list of all values of property KEY."
12842 (save-excursion
12843 (save-restriction
12844 (widen)
12845 (goto-char (point-min))
12846 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12847 values)
12848 (while (re-search-forward re nil t)
12849 (add-to-list 'values (org-trim (match-string 1))))
12850 (delete "" values)))))
12852 (defun org-insert-property-drawer ()
12853 "Insert a property drawer into the current entry."
12854 (interactive)
12855 (org-back-to-heading t)
12856 (looking-at outline-regexp)
12857 (let ((indent (if org-adapt-indentation
12858 (- (match-end 0)(match-beginning 0))
12860 (beg (point))
12861 (re (concat "^[ \t]*" org-keyword-time-regexp))
12862 end hiddenp)
12863 (outline-next-heading)
12864 (setq end (point))
12865 (goto-char beg)
12866 (while (re-search-forward re end t))
12867 (setq hiddenp (org-invisible-p))
12868 (end-of-line 1)
12869 (and (equal (char-after) ?\n) (forward-char 1))
12870 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12871 (if (member (match-string 1) '("CLOCK:" ":END:"))
12872 ;; just skip this line
12873 (beginning-of-line 2)
12874 ;; Drawer start, find the end
12875 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12876 (beginning-of-line 1)))
12877 (org-skip-over-state-notes)
12878 (skip-chars-backward " \t\n\r")
12879 (if (eq (char-before) ?*) (forward-char 1))
12880 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12881 (beginning-of-line 0)
12882 (org-indent-to-column indent)
12883 (beginning-of-line 2)
12884 (org-indent-to-column indent)
12885 (beginning-of-line 0)
12886 (if hiddenp
12887 (save-excursion
12888 (org-back-to-heading t)
12889 (hide-entry))
12890 (org-flag-drawer t))))
12892 (defun org-set-property (property value)
12893 "In the current entry, set PROPERTY to VALUE.
12894 When called interactively, this will prompt for a property name, offering
12895 completion on existing and default properties. And then it will prompt
12896 for a value, offering completion either on allowed values (via an inherited
12897 xxx_ALL property) or on existing values in other instances of this property
12898 in the current file."
12899 (interactive
12900 (let* ((completion-ignore-case t)
12901 (keys (org-buffer-property-keys nil t t))
12902 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12903 (prop (if (member prop0 keys)
12904 prop0
12905 (or (cdr (assoc (downcase prop0)
12906 (mapcar (lambda (x) (cons (downcase x) x))
12907 keys)))
12908 prop0)))
12909 (cur (org-entry-get nil prop))
12910 (allowed (org-property-get-allowed-values nil prop 'table))
12911 (existing (mapcar 'list (org-property-values prop)))
12912 (val (if allowed
12913 (org-completing-read "Value: " allowed nil
12914 (not (get-text-property 0 'org-unrestricted
12915 (caar allowed))))
12916 (let (org-completion-use-ido org-completion-use-iswitchb)
12917 (org-completing-read
12918 (concat "Value " (if (and cur (string-match "\\S-" cur))
12919 (concat "[" cur "]") "")
12920 ": ")
12921 existing nil nil "" nil cur)))))
12922 (list prop (if (equal val "") cur val))))
12923 (unless (equal (org-entry-get nil property) value)
12924 (org-entry-put nil property value)))
12926 (defun org-delete-property (property)
12927 "In the current entry, delete PROPERTY."
12928 (interactive
12929 (let* ((completion-ignore-case t)
12930 (prop (org-icompleting-read
12931 "Property: " (org-entry-properties nil 'standard))))
12932 (list prop)))
12933 (message "Property %s %s" property
12934 (if (org-entry-delete nil property)
12935 "deleted"
12936 "was not present in the entry")))
12938 (defun org-delete-property-globally (property)
12939 "Remove PROPERTY globally, from all entries."
12940 (interactive
12941 (let* ((completion-ignore-case t)
12942 (prop (org-icompleting-read
12943 "Globally remove property: "
12944 (mapcar 'list (org-buffer-property-keys)))))
12945 (list prop)))
12946 (save-excursion
12947 (save-restriction
12948 (widen)
12949 (goto-char (point-min))
12950 (let ((cnt 0))
12951 (while (re-search-forward
12952 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12953 nil t)
12954 (setq cnt (1+ cnt))
12955 (replace-match ""))
12956 (message "Property \"%s\" removed from %d entries" property cnt)))))
12958 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12960 (defun org-compute-property-at-point ()
12961 "Compute the property at point.
12962 This looks for an enclosing column format, extracts the operator and
12963 then applies it to the property in the column format's scope."
12964 (interactive)
12965 (unless (org-at-property-p)
12966 (error "Not at a property"))
12967 (let ((prop (org-match-string-no-properties 2)))
12968 (org-columns-get-format-and-top-level)
12969 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12970 (error "No operator defined for property %s" prop))
12971 (org-columns-compute prop)))
12973 (defvar org-property-allowed-value-functions nil
12974 "Hook for functions supplying allowed values for a specific property.
12975 The functions must take a single argument, the name of the property, and
12976 return a flat list of allowed values. If \":ETC\" is one of
12977 the values, this means that these values are intended as defaults for
12978 completion, but that other values should be allowed too.
12979 The functions must return nil if they are not responsible for this
12980 property.")
12982 (defun org-property-get-allowed-values (pom property &optional table)
12983 "Get allowed values for the property PROPERTY.
12984 When TABLE is non-nil, return an alist that can directly be used for
12985 completion."
12986 (let (vals)
12987 (cond
12988 ((equal property "TODO")
12989 (setq vals (org-with-point-at pom
12990 (append org-todo-keywords-1 '("")))))
12991 ((equal property "PRIORITY")
12992 (let ((n org-lowest-priority))
12993 (while (>= n org-highest-priority)
12994 (push (char-to-string n) vals)
12995 (setq n (1- n)))))
12996 ((member property org-special-properties))
12997 ((setq vals (run-hook-with-args-until-success
12998 'org-property-allowed-value-functions property)))
13000 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13001 (when (and vals (string-match "\\S-" vals))
13002 (setq vals (car (read-from-string (concat "(" vals ")"))))
13003 (setq vals (mapcar (lambda (x)
13004 (cond ((stringp x) x)
13005 ((numberp x) (number-to-string x))
13006 ((symbolp x) (symbol-name x))
13007 (t "???")))
13008 vals)))))
13009 (when (member ":ETC" vals)
13010 (setq vals (remove ":ETC" vals))
13011 (org-add-props (car vals) '(org-unrestricted t)))
13012 (if table (mapcar 'list vals) vals)))
13014 (defun org-property-previous-allowed-value (&optional previous)
13015 "Switch to the next allowed value for this property."
13016 (interactive)
13017 (org-property-next-allowed-value t))
13019 (defun org-property-next-allowed-value (&optional previous)
13020 "Switch to the next allowed value for this property."
13021 (interactive)
13022 (unless (org-at-property-p)
13023 (error "Not at a property"))
13024 (let* ((key (match-string 2))
13025 (value (match-string 3))
13026 (allowed (or (org-property-get-allowed-values (point) key)
13027 (and (member value '("[ ]" "[-]" "[X]"))
13028 '("[ ]" "[X]"))))
13029 nval)
13030 (unless allowed
13031 (error "Allowed values for this property have not been defined"))
13032 (if previous (setq allowed (reverse allowed)))
13033 (if (member value allowed)
13034 (setq nval (car (cdr (member value allowed)))))
13035 (setq nval (or nval (car allowed)))
13036 (if (equal nval value)
13037 (error "Only one allowed value for this property"))
13038 (org-at-property-p)
13039 (replace-match (concat " :" key ": " nval) t t)
13040 (org-indent-line-function)
13041 (beginning-of-line 1)
13042 (skip-chars-forward " \t")
13043 (run-hook-with-args 'org-property-changed-functions key nval)))
13045 (defun org-find-entry-with-id (ident)
13046 "Locate the entry that contains the ID property with exact value IDENT.
13047 IDENT can be a string, a symbol or a number, this function will search for
13048 the string representation of it.
13049 Return the position where this entry starts, or nil if there is no such entry."
13050 (interactive "sID: ")
13051 (let ((id (cond
13052 ((stringp ident) ident)
13053 ((symbol-name ident) (symbol-name ident))
13054 ((numberp ident) (number-to-string ident))
13055 (t (error "IDENT %s must be a string, symbol or number" ident))))
13056 (case-fold-search nil))
13057 (save-excursion
13058 (save-restriction
13059 (widen)
13060 (goto-char (point-min))
13061 (when (re-search-forward
13062 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13063 nil t)
13064 (org-back-to-heading t)
13065 (point))))))
13067 ;;;; Timestamps
13069 (defvar org-last-changed-timestamp nil)
13070 (defvar org-last-inserted-timestamp nil
13071 "The last time stamp inserted with `org-insert-time-stamp'.")
13072 (defvar org-time-was-given) ; dynamically scoped parameter
13073 (defvar org-end-time-was-given) ; dynamically scoped parameter
13074 (defvar org-ts-what) ; dynamically scoped parameter
13076 (defun org-time-stamp (arg &optional inactive)
13077 "Prompt for a date/time and insert a time stamp.
13078 If the user specifies a time like HH:MM, or if this command is called
13079 with a prefix argument, the time stamp will contain date and time.
13080 Otherwise, only the date will be included. All parts of a date not
13081 specified by the user will be filled in from the current date/time.
13082 So if you press just return without typing anything, the time stamp
13083 will represent the current date/time. If there is already a timestamp
13084 at the cursor, it will be modified."
13085 (interactive "P")
13086 (let* ((ts nil)
13087 (default-time
13088 ;; Default time is either today, or, when entering a range,
13089 ;; the range start.
13090 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13091 (save-excursion
13092 (re-search-backward
13093 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13094 (- (point) 20) t)))
13095 (apply 'encode-time (org-parse-time-string (match-string 1)))
13096 (current-time)))
13097 (default-input (and ts (org-get-compact-tod ts)))
13098 org-time-was-given org-end-time-was-given time)
13099 (cond
13100 ((and (org-at-timestamp-p t)
13101 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13102 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13103 (insert "--")
13104 (setq time (let ((this-command this-command))
13105 (org-read-date arg 'totime nil nil
13106 default-time default-input)))
13107 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13108 ((org-at-timestamp-p t)
13109 (setq time (let ((this-command this-command))
13110 (org-read-date arg 'totime nil nil default-time default-input)))
13111 (when (org-at-timestamp-p t) ; just to get the match data
13112 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13113 (replace-match "")
13114 (setq org-last-changed-timestamp
13115 (org-insert-time-stamp
13116 time (or org-time-was-given arg)
13117 inactive nil nil (list org-end-time-was-given))))
13118 (message "Timestamp updated"))
13120 (setq time (let ((this-command this-command))
13121 (org-read-date arg 'totime nil nil default-time default-input)))
13122 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13123 nil nil (list org-end-time-was-given))))))
13125 ;; FIXME: can we use this for something else, like computing time differences?
13126 (defun org-get-compact-tod (s)
13127 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13128 (let* ((t1 (match-string 1 s))
13129 (h1 (string-to-number (match-string 2 s)))
13130 (m1 (string-to-number (match-string 3 s)))
13131 (t2 (and (match-end 4) (match-string 5 s)))
13132 (h2 (and t2 (string-to-number (match-string 6 s))))
13133 (m2 (and t2 (string-to-number (match-string 7 s))))
13134 dh dm)
13135 (if (not t2)
13137 (setq dh (- h2 h1) dm (- m2 m1))
13138 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13139 (concat t1 "+" (number-to-string dh)
13140 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13142 (defun org-time-stamp-inactive (&optional arg)
13143 "Insert an inactive time stamp.
13144 An inactive time stamp is enclosed in square brackets instead of angle
13145 brackets. It is inactive in the sense that it does not trigger agenda entries,
13146 does not link to the calendar and cannot be changed with the S-cursor keys.
13147 So these are more for recording a certain time/date."
13148 (interactive "P")
13149 (org-time-stamp arg 'inactive))
13151 (defvar org-date-ovl (org-make-overlay 1 1))
13152 (org-overlay-put org-date-ovl 'face 'org-warning)
13153 (org-detach-overlay org-date-ovl)
13155 (defvar org-ans1) ; dynamically scoped parameter
13156 (defvar org-ans2) ; dynamically scoped parameter
13158 (defvar org-plain-time-of-day-regexp) ; defined below
13160 (defvar org-overriding-default-time nil) ; dynamically scoped
13161 (defvar org-read-date-overlay nil)
13162 (defvar org-dcst nil) ; dynamically scoped
13163 (defvar org-read-date-history nil)
13164 (defvar org-read-date-final-answer nil)
13166 (defun org-read-date (&optional with-time to-time from-string prompt
13167 default-time default-input)
13168 "Read a date, possibly a time, and make things smooth for the user.
13169 The prompt will suggest to enter an ISO date, but you can also enter anything
13170 which will at least partially be understood by `parse-time-string'.
13171 Unrecognized parts of the date will default to the current day, month, year,
13172 hour and minute. If this command is called to replace a timestamp at point,
13173 of to enter the second timestamp of a range, the default time is taken from the
13174 existing stamp. For example,
13175 3-2-5 --> 2003-02-05
13176 feb 15 --> currentyear-02-15
13177 sep 12 9 --> 2009-09-12
13178 12:45 --> today 12:45
13179 22 sept 0:34 --> currentyear-09-22 0:34
13180 12 --> currentyear-currentmonth-12
13181 Fri --> nearest Friday (today or later)
13182 etc.
13184 Furthermore you can specify a relative date by giving, as the *first* thing
13185 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13186 change in days weeks, months, years.
13187 With a single plus or minus, the date is relative to today. With a double
13188 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13189 +4d --> four days from today
13190 +4 --> same as above
13191 +2w --> two weeks from today
13192 ++5 --> five days from default date
13194 The function understands only English month and weekday abbreviations,
13195 but this can be configured with the variables `parse-time-months' and
13196 `parse-time-weekdays'.
13198 While prompting, a calendar is popped up - you can also select the
13199 date with the mouse (button 1). The calendar shows a period of three
13200 months. To scroll it to other months, use the keys `>' and `<'.
13201 If you don't like the calendar, turn it off with
13202 \(setq org-read-date-popup-calendar nil)
13204 With optional argument TO-TIME, the date will immediately be converted
13205 to an internal time.
13206 With an optional argument WITH-TIME, the prompt will suggest to also
13207 insert a time. Note that when WITH-TIME is not set, you can still
13208 enter a time, and this function will inform the calling routine about
13209 this change. The calling routine may then choose to change the format
13210 used to insert the time stamp into the buffer to include the time.
13211 With optional argument FROM-STRING, read from this string instead from
13212 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13213 the time/date that is used for everything that is not specified by the
13214 user."
13215 (require 'parse-time)
13216 (let* ((org-time-stamp-rounding-minutes
13217 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13218 (org-dcst org-display-custom-times)
13219 (ct (org-current-time))
13220 (def (or org-overriding-default-time default-time ct))
13221 (defdecode (decode-time def))
13222 (dummy (progn
13223 (when (< (nth 2 defdecode) org-extend-today-until)
13224 (setcar (nthcdr 2 defdecode) -1)
13225 (setcar (nthcdr 1 defdecode) 59)
13226 (setq def (apply 'encode-time defdecode)
13227 defdecode (decode-time def)))))
13228 (calendar-frame-setup nil)
13229 (calendar-move-hook nil)
13230 (calendar-view-diary-initially-flag nil)
13231 (view-diary-entries-initially nil)
13232 (calendar-view-holidays-initially-flag nil)
13233 (view-calendar-holidays-initially nil)
13234 (timestr (format-time-string
13235 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13236 (prompt (concat (if prompt (concat prompt " ") "")
13237 (format "Date+time [%s]: " timestr)))
13238 ans (org-ans0 "") org-ans1 org-ans2 final)
13240 (cond
13241 (from-string (setq ans from-string))
13242 (org-read-date-popup-calendar
13243 (save-excursion
13244 (save-window-excursion
13245 (calendar)
13246 (calendar-forward-day (- (time-to-days def)
13247 (calendar-absolute-from-gregorian
13248 (calendar-current-date))))
13249 (org-eval-in-calendar nil t)
13250 (let* ((old-map (current-local-map))
13251 (map (copy-keymap calendar-mode-map))
13252 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13253 (org-defkey map (kbd "RET") 'org-calendar-select)
13254 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13255 'org-calendar-select-mouse)
13256 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13257 'org-calendar-select-mouse)
13258 (org-defkey minibuffer-local-map [(meta shift left)]
13259 (lambda () (interactive)
13260 (org-eval-in-calendar '(calendar-backward-month 1))))
13261 (org-defkey minibuffer-local-map [(meta shift right)]
13262 (lambda () (interactive)
13263 (org-eval-in-calendar '(calendar-forward-month 1))))
13264 (org-defkey minibuffer-local-map [(meta shift up)]
13265 (lambda () (interactive)
13266 (org-eval-in-calendar '(calendar-backward-year 1))))
13267 (org-defkey minibuffer-local-map [(meta shift down)]
13268 (lambda () (interactive)
13269 (org-eval-in-calendar '(calendar-forward-year 1))))
13270 (org-defkey minibuffer-local-map [?\e (shift left)]
13271 (lambda () (interactive)
13272 (org-eval-in-calendar '(calendar-backward-month 1))))
13273 (org-defkey minibuffer-local-map [?\e (shift right)]
13274 (lambda () (interactive)
13275 (org-eval-in-calendar '(calendar-forward-month 1))))
13276 (org-defkey minibuffer-local-map [?\e (shift up)]
13277 (lambda () (interactive)
13278 (org-eval-in-calendar '(calendar-backward-year 1))))
13279 (org-defkey minibuffer-local-map [?\e (shift down)]
13280 (lambda () (interactive)
13281 (org-eval-in-calendar '(calendar-forward-year 1))))
13282 (org-defkey minibuffer-local-map [(shift up)]
13283 (lambda () (interactive)
13284 (org-eval-in-calendar '(calendar-backward-week 1))))
13285 (org-defkey minibuffer-local-map [(shift down)]
13286 (lambda () (interactive)
13287 (org-eval-in-calendar '(calendar-forward-week 1))))
13288 (org-defkey minibuffer-local-map [(shift left)]
13289 (lambda () (interactive)
13290 (org-eval-in-calendar '(calendar-backward-day 1))))
13291 (org-defkey minibuffer-local-map [(shift right)]
13292 (lambda () (interactive)
13293 (org-eval-in-calendar '(calendar-forward-day 1))))
13294 (org-defkey minibuffer-local-map ">"
13295 (lambda () (interactive)
13296 (org-eval-in-calendar '(scroll-calendar-left 1))))
13297 (org-defkey minibuffer-local-map "<"
13298 (lambda () (interactive)
13299 (org-eval-in-calendar '(scroll-calendar-right 1))))
13300 (run-hooks 'org-read-date-minibuffer-setup-hook)
13301 (unwind-protect
13302 (progn
13303 (use-local-map map)
13304 (add-hook 'post-command-hook 'org-read-date-display)
13305 (setq org-ans0 (read-string prompt default-input
13306 'org-read-date-history nil))
13307 ;; org-ans0: from prompt
13308 ;; org-ans1: from mouse click
13309 ;; org-ans2: from calendar motion
13310 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13311 (remove-hook 'post-command-hook 'org-read-date-display)
13312 (use-local-map old-map)
13313 (when org-read-date-overlay
13314 (org-delete-overlay org-read-date-overlay)
13315 (setq org-read-date-overlay nil)))))))
13317 (t ; Naked prompt only
13318 (unwind-protect
13319 (setq ans (read-string prompt default-input
13320 'org-read-date-history timestr))
13321 (when org-read-date-overlay
13322 (org-delete-overlay org-read-date-overlay)
13323 (setq org-read-date-overlay nil)))))
13325 (setq final (org-read-date-analyze ans def defdecode))
13326 (setq org-read-date-final-answer ans)
13328 (if to-time
13329 (apply 'encode-time final)
13330 (if (and (boundp 'org-time-was-given) org-time-was-given)
13331 (format "%04d-%02d-%02d %02d:%02d"
13332 (nth 5 final) (nth 4 final) (nth 3 final)
13333 (nth 2 final) (nth 1 final))
13334 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13336 (defvar def)
13337 (defvar defdecode)
13338 (defvar with-time)
13339 (defvar org-read-date-analyze-futurep nil)
13340 (defun org-read-date-display ()
13341 "Display the current date prompt interpretation in the minibuffer."
13342 (when org-read-date-display-live
13343 (when org-read-date-overlay
13344 (org-delete-overlay org-read-date-overlay))
13345 (let ((p (point)))
13346 (end-of-line 1)
13347 (while (not (equal (buffer-substring
13348 (max (point-min) (- (point) 4)) (point))
13349 " "))
13350 (insert " "))
13351 (goto-char p))
13352 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13353 " " (or org-ans1 org-ans2)))
13354 (org-end-time-was-given nil)
13355 (f (org-read-date-analyze ans def defdecode))
13356 (fmts (if org-dcst
13357 org-time-stamp-custom-formats
13358 org-time-stamp-formats))
13359 (fmt (if (or with-time
13360 (and (boundp 'org-time-was-given) org-time-was-given))
13361 (cdr fmts)
13362 (car fmts)))
13363 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13364 (when (and org-end-time-was-given
13365 (string-match org-plain-time-of-day-regexp txt))
13366 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13367 org-end-time-was-given
13368 (substring txt (match-end 0)))))
13369 (when org-read-date-analyze-futurep
13370 (setq txt (concat txt " (=>F)")))
13371 (setq org-read-date-overlay
13372 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13373 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13375 (defun org-read-date-analyze (ans def defdecode)
13376 "Analyse the combined answer of the date prompt."
13377 ;; FIXME: cleanup and comment
13378 (let ((nowdecode (decode-time (current-time)))
13379 delta deltan deltaw deltadef year month day
13380 hour minute second wday pm h2 m2 tl wday1
13381 iso-year iso-weekday iso-week iso-year iso-date futurep)
13382 (setq org-read-date-analyze-futurep nil)
13383 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13384 (setq ans "+0"))
13386 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13387 (setq ans (replace-match "" t t ans)
13388 deltan (car delta)
13389 deltaw (nth 1 delta)
13390 deltadef (nth 2 delta)))
13392 ;; Check if there is an iso week date in there
13393 ;; If yes, store the info and postpone interpreting it until the rest
13394 ;; of the parsing is done
13395 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13396 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13397 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13398 iso-week (string-to-number (match-string 2 ans)))
13399 (setq ans (replace-match "" t t ans)))
13401 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13402 (when (string-match
13403 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13404 (setq year (if (match-end 2)
13405 (string-to-number (match-string 2 ans))
13406 (string-to-number (format-time-string "%Y")))
13407 month (string-to-number (match-string 3 ans))
13408 day (string-to-number (match-string 4 ans)))
13409 (if (< year 100) (setq year (+ 2000 year)))
13410 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13411 t nil ans)))
13412 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13413 ;; If there is a time with am/pm, and *no* time without it, we convert
13414 ;; so that matching will be successful.
13415 (loop for i from 1 to 2 do ; twice, for end time as well
13416 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13417 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13418 (setq hour (string-to-number (match-string 1 ans))
13419 minute (if (match-end 3)
13420 (string-to-number (match-string 3 ans))
13422 pm (equal ?p
13423 (string-to-char (downcase (match-string 4 ans)))))
13424 (if (and (= hour 12) (not pm))
13425 (setq hour 0)
13426 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13427 (setq ans (replace-match (format "%02d:%02d" hour minute)
13428 t t ans))))
13430 ;; Check if a time range is given as a duration
13431 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13432 (setq hour (string-to-number (match-string 1 ans))
13433 h2 (+ hour (string-to-number (match-string 3 ans)))
13434 minute (string-to-number (match-string 2 ans))
13435 m2 (+ minute (if (match-end 5) (string-to-number
13436 (match-string 5 ans))0)))
13437 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13438 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13439 t t ans)))
13441 ;; Check if there is a time range
13442 (when (boundp 'org-end-time-was-given)
13443 (setq org-time-was-given nil)
13444 (when (and (string-match org-plain-time-of-day-regexp ans)
13445 (match-end 8))
13446 (setq org-end-time-was-given (match-string 8 ans))
13447 (setq ans (concat (substring ans 0 (match-beginning 7))
13448 (substring ans (match-end 7))))))
13450 (setq tl (parse-time-string ans)
13451 day (or (nth 3 tl) (nth 3 defdecode))
13452 month (or (nth 4 tl)
13453 (if (and org-read-date-prefer-future
13454 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13455 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13456 (nth 4 defdecode)))
13457 year (or (nth 5 tl)
13458 (if (and org-read-date-prefer-future
13459 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13460 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13461 (nth 5 defdecode)))
13462 hour (or (nth 2 tl) (nth 2 defdecode))
13463 minute (or (nth 1 tl) (nth 1 defdecode))
13464 second (or (nth 0 tl) 0)
13465 wday (nth 6 tl))
13467 (when (and (eq org-read-date-prefer-future 'time)
13468 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13469 (equal day (nth 3 nowdecode))
13470 (equal month (nth 4 nowdecode))
13471 (equal year (nth 5 nowdecode))
13472 (nth 2 tl)
13473 (or (< (nth 2 tl) (nth 2 nowdecode))
13474 (and (= (nth 2 tl) (nth 2 nowdecode))
13475 (nth 1 tl)
13476 (< (nth 1 tl) (nth 1 nowdecode)))))
13477 (setq day (1+ day)
13478 futurep t))
13480 ;; Special date definitions below
13481 (cond
13482 (iso-week
13483 ;; There was an iso week
13484 (setq futurep nil)
13485 (setq year (or iso-year year)
13486 day (or iso-weekday wday 1)
13487 wday nil ; to make sure that the trigger below does not match
13488 iso-date (calendar-gregorian-from-absolute
13489 (calendar-absolute-from-iso
13490 (list iso-week day year))))
13491 ; FIXME: Should we also push ISO weeks into the future?
13492 ; (when (and org-read-date-prefer-future
13493 ; (not iso-year)
13494 ; (< (calendar-absolute-from-gregorian iso-date)
13495 ; (time-to-days (current-time))))
13496 ; (setq year (1+ year)
13497 ; iso-date (calendar-gregorian-from-absolute
13498 ; (calendar-absolute-from-iso
13499 ; (list iso-week day year)))))
13500 (setq month (car iso-date)
13501 year (nth 2 iso-date)
13502 day (nth 1 iso-date)))
13503 (deltan
13504 (setq futurep nil)
13505 (unless deltadef
13506 (let ((now (decode-time (current-time))))
13507 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13508 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13509 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13510 ((equal deltaw "m") (setq month (+ month deltan)))
13511 ((equal deltaw "y") (setq year (+ year deltan)))))
13512 ((and wday (not (nth 3 tl)))
13513 (setq futurep nil)
13514 ;; Weekday was given, but no day, so pick that day in the week
13515 ;; on or after the derived date.
13516 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13517 (unless (equal wday wday1)
13518 (setq day (+ day (% (- wday wday1 -7) 7))))))
13519 (if (and (boundp 'org-time-was-given)
13520 (nth 2 tl))
13521 (setq org-time-was-given t))
13522 (if (< year 100) (setq year (+ 2000 year)))
13523 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13524 (setq org-read-date-analyze-futurep futurep)
13525 (list second minute hour day month year)))
13527 (defvar parse-time-weekdays)
13529 (defun org-read-date-get-relative (s today default)
13530 "Check string S for special relative date string.
13531 TODAY and DEFAULT are internal times, for today and for a default.
13532 Return shift list (N what def-flag)
13533 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13534 N is the number of WHATs to shift.
13535 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13536 the DEFAULT date rather than TODAY."
13537 (when (and
13538 (string-match
13539 (concat
13540 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13541 "\\([0-9]+\\)?"
13542 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13543 "\\([ \t]\\|$\\)") s)
13544 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13545 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13546 (string-to-char (substring (match-string 1 s) -1))
13547 ?+))
13548 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13549 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13550 (what (if (match-end 3) (match-string 3 s) "d"))
13551 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13552 (date (if rel default today))
13553 (wday (nth 6 (decode-time date)))
13554 delta)
13555 (if wday1
13556 (progn
13557 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13558 (if (= dir ?-) (setq delta (- delta 7)))
13559 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13560 (list delta "d" rel))
13561 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13563 (defun org-eval-in-calendar (form &optional keepdate)
13564 "Eval FORM in the calendar window and return to current window.
13565 Also, store the cursor date in variable org-ans2."
13566 (let ((sf (selected-frame))
13567 (sw (selected-window)))
13568 (select-window (get-buffer-window "*Calendar*" t))
13569 (eval form)
13570 (when (and (not keepdate) (calendar-cursor-to-date))
13571 (let* ((date (calendar-cursor-to-date))
13572 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13573 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13574 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13575 (select-window sw)
13576 (org-select-frame-set-input-focus sf)))
13578 (defun org-calendar-select ()
13579 "Return to `org-read-date' with the date currently selected.
13580 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13581 (interactive)
13582 (when (calendar-cursor-to-date)
13583 (let* ((date (calendar-cursor-to-date))
13584 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13585 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13586 (if (active-minibuffer-window) (exit-minibuffer))))
13588 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13589 "Insert a date stamp for the date given by the internal TIME.
13590 WITH-HM means, use the stamp format that includes the time of the day.
13591 INACTIVE means use square brackets instead of angular ones, so that the
13592 stamp will not contribute to the agenda.
13593 PRE and POST are optional strings to be inserted before and after the
13594 stamp.
13595 The command returns the inserted time stamp."
13596 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13597 stamp)
13598 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13599 (insert-before-markers (or pre ""))
13600 (insert-before-markers (setq stamp (format-time-string fmt time)))
13601 (when (listp extra)
13602 (setq extra (car extra))
13603 (if (and (stringp extra)
13604 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13605 (setq extra (format "-%02d:%02d"
13606 (string-to-number (match-string 1 extra))
13607 (string-to-number (match-string 2 extra))))
13608 (setq extra nil)))
13609 (when extra
13610 (backward-char 1)
13611 (insert-before-markers extra)
13612 (forward-char 1))
13613 (insert-before-markers (or post ""))
13614 (setq org-last-inserted-timestamp stamp)))
13616 (defun org-toggle-time-stamp-overlays ()
13617 "Toggle the use of custom time stamp formats."
13618 (interactive)
13619 (setq org-display-custom-times (not org-display-custom-times))
13620 (unless org-display-custom-times
13621 (let ((p (point-min)) (bmp (buffer-modified-p)))
13622 (while (setq p (next-single-property-change p 'display))
13623 (if (and (get-text-property p 'display)
13624 (eq (get-text-property p 'face) 'org-date))
13625 (remove-text-properties
13626 p (setq p (next-single-property-change p 'display))
13627 '(display t))))
13628 (set-buffer-modified-p bmp)))
13629 (if (featurep 'xemacs)
13630 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13631 (org-restart-font-lock)
13632 (setq org-table-may-need-update t)
13633 (if org-display-custom-times
13634 (message "Time stamps are overlayed with custom format")
13635 (message "Time stamp overlays removed")))
13637 (defun org-display-custom-time (beg end)
13638 "Overlay modified time stamp format over timestamp between BEG and END."
13639 (let* ((ts (buffer-substring beg end))
13640 t1 w1 with-hm tf time str w2 (off 0))
13641 (save-match-data
13642 (setq t1 (org-parse-time-string ts t))
13643 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13644 (setq off (- (match-end 0) (match-beginning 0)))))
13645 (setq end (- end off))
13646 (setq w1 (- end beg)
13647 with-hm (and (nth 1 t1) (nth 2 t1))
13648 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13649 time (org-fix-decoded-time t1)
13650 str (org-add-props
13651 (format-time-string
13652 (substring tf 1 -1) (apply 'encode-time time))
13653 nil 'mouse-face 'highlight)
13654 w2 (length str))
13655 (if (not (= w2 w1))
13656 (add-text-properties (1+ beg) (+ 2 beg)
13657 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13658 (if (featurep 'xemacs)
13659 (progn
13660 (put-text-property beg end 'invisible t)
13661 (put-text-property beg end 'end-glyph (make-glyph str)))
13662 (put-text-property beg end 'display str))))
13664 (defun org-translate-time (string)
13665 "Translate all timestamps in STRING to custom format.
13666 But do this only if the variable `org-display-custom-times' is set."
13667 (when org-display-custom-times
13668 (save-match-data
13669 (let* ((start 0)
13670 (re org-ts-regexp-both)
13671 t1 with-hm inactive tf time str beg end)
13672 (while (setq start (string-match re string start))
13673 (setq beg (match-beginning 0)
13674 end (match-end 0)
13675 t1 (save-match-data
13676 (org-parse-time-string (substring string beg end) t))
13677 with-hm (and (nth 1 t1) (nth 2 t1))
13678 inactive (equal (substring string beg (1+ beg)) "[")
13679 tf (funcall (if with-hm 'cdr 'car)
13680 org-time-stamp-custom-formats)
13681 time (org-fix-decoded-time t1)
13682 str (format-time-string
13683 (concat
13684 (if inactive "[" "<") (substring tf 1 -1)
13685 (if inactive "]" ">"))
13686 (apply 'encode-time time))
13687 string (replace-match str t t string)
13688 start (+ start (length str)))))))
13689 string)
13691 (defun org-fix-decoded-time (time)
13692 "Set 0 instead of nil for the first 6 elements of time.
13693 Don't touch the rest."
13694 (let ((n 0))
13695 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13697 (defun org-days-to-time (timestamp-string)
13698 "Difference between TIMESTAMP-STRING and now in days."
13699 (- (time-to-days (org-time-string-to-time timestamp-string))
13700 (time-to-days (current-time))))
13702 (defun org-deadline-close (timestamp-string &optional ndays)
13703 "Is the time in TIMESTAMP-STRING close to the current date?"
13704 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13705 (and (< (org-days-to-time timestamp-string) ndays)
13706 (not (org-entry-is-done-p))))
13708 (defun org-get-wdays (ts)
13709 "Get the deadline lead time appropriate for timestring TS."
13710 (cond
13711 ((<= org-deadline-warning-days 0)
13712 ;; 0 or negative, enforce this value no matter what
13713 (- org-deadline-warning-days))
13714 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13715 ;; lead time is specified.
13716 (floor (* (string-to-number (match-string 1 ts))
13717 (cdr (assoc (match-string 2 ts)
13718 '(("d" . 1) ("w" . 7)
13719 ("m" . 30.4) ("y" . 365.25)))))))
13720 ;; go for the default.
13721 (t org-deadline-warning-days)))
13723 (defun org-calendar-select-mouse (ev)
13724 "Return to `org-read-date' with the date currently selected.
13725 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13726 (interactive "e")
13727 (mouse-set-point ev)
13728 (when (calendar-cursor-to-date)
13729 (let* ((date (calendar-cursor-to-date))
13730 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13731 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13732 (if (active-minibuffer-window) (exit-minibuffer))))
13734 (defun org-check-deadlines (ndays)
13735 "Check if there are any deadlines due or past due.
13736 A deadline is considered due if it happens within `org-deadline-warning-days'
13737 days from today's date. If the deadline appears in an entry marked DONE,
13738 it is not shown. The prefix arg NDAYS can be used to test that many
13739 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13740 (interactive "P")
13741 (let* ((org-warn-days
13742 (cond
13743 ((equal ndays '(4)) 100000)
13744 (ndays (prefix-numeric-value ndays))
13745 (t (abs org-deadline-warning-days))))
13746 (case-fold-search nil)
13747 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13748 (callback
13749 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13751 (message "%d deadlines past-due or due within %d days"
13752 (org-occur regexp nil callback)
13753 org-warn-days)))
13755 (defun org-check-before-date (date)
13756 "Check if there are deadlines or scheduled entries before DATE."
13757 (interactive (list (org-read-date)))
13758 (let ((case-fold-search nil)
13759 (regexp (concat "\\<\\(" org-deadline-string
13760 "\\|" org-scheduled-string
13761 "\\) *<\\([^>]+\\)>"))
13762 (callback
13763 (lambda () (time-less-p
13764 (org-time-string-to-time (match-string 2))
13765 (org-time-string-to-time date)))))
13766 (message "%d entries before %s"
13767 (org-occur regexp nil callback) date)))
13769 (defun org-check-after-date (date)
13770 "Check if there are deadlines or scheduled entries after DATE."
13771 (interactive (list (org-read-date)))
13772 (let ((case-fold-search nil)
13773 (regexp (concat "\\<\\(" org-deadline-string
13774 "\\|" org-scheduled-string
13775 "\\) *<\\([^>]+\\)>"))
13776 (callback
13777 (lambda () (not
13778 (time-less-p
13779 (org-time-string-to-time (match-string 2))
13780 (org-time-string-to-time date))))))
13781 (message "%d entries after %s"
13782 (org-occur regexp nil callback) date)))
13784 (defun org-evaluate-time-range (&optional to-buffer)
13785 "Evaluate a time range by computing the difference between start and end.
13786 Normally the result is just printed in the echo area, but with prefix arg
13787 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13788 If the time range is actually in a table, the result is inserted into the
13789 next column.
13790 For time difference computation, a year is assumed to be exactly 365
13791 days in order to avoid rounding problems."
13792 (interactive "P")
13794 (org-clock-update-time-maybe)
13795 (save-excursion
13796 (unless (org-at-date-range-p t)
13797 (goto-char (point-at-bol))
13798 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13799 (if (not (org-at-date-range-p t))
13800 (error "Not at a time-stamp range, and none found in current line")))
13801 (let* ((ts1 (match-string 1))
13802 (ts2 (match-string 2))
13803 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13804 (match-end (match-end 0))
13805 (time1 (org-time-string-to-time ts1))
13806 (time2 (org-time-string-to-time ts2))
13807 (t1 (org-float-time time1))
13808 (t2 (org-float-time time2))
13809 (diff (abs (- t2 t1)))
13810 (negative (< (- t2 t1) 0))
13811 ;; (ys (floor (* 365 24 60 60)))
13812 (ds (* 24 60 60))
13813 (hs (* 60 60))
13814 (fy "%dy %dd %02d:%02d")
13815 (fy1 "%dy %dd")
13816 (fd "%dd %02d:%02d")
13817 (fd1 "%dd")
13818 (fh "%02d:%02d")
13819 y d h m align)
13820 (if havetime
13821 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13823 d (floor (/ diff ds)) diff (mod diff ds)
13824 h (floor (/ diff hs)) diff (mod diff hs)
13825 m (floor (/ diff 60)))
13826 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13828 d (floor (+ (/ diff ds) 0.5))
13829 h 0 m 0))
13830 (if (not to-buffer)
13831 (message "%s" (org-make-tdiff-string y d h m))
13832 (if (org-at-table-p)
13833 (progn
13834 (goto-char match-end)
13835 (setq align t)
13836 (and (looking-at " *|") (goto-char (match-end 0))))
13837 (goto-char match-end))
13838 (if (looking-at
13839 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13840 (replace-match ""))
13841 (if negative (insert " -"))
13842 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13843 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13844 (insert " " (format fh h m))))
13845 (if align (org-table-align))
13846 (message "Time difference inserted")))))
13848 (defun org-make-tdiff-string (y d h m)
13849 (let ((fmt "")
13850 (l nil))
13851 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13852 l (push y l)))
13853 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13854 l (push d l)))
13855 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13856 l (push h l)))
13857 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13858 l (push m l)))
13859 (apply 'format fmt (nreverse l))))
13861 (defun org-time-string-to-time (s)
13862 (apply 'encode-time (org-parse-time-string s)))
13863 (defun org-time-string-to-seconds (s)
13864 (org-float-time (org-time-string-to-time s)))
13866 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13867 "Convert a time stamp to an absolute day number.
13868 If there is a specifyer for a cyclic time stamp, get the closest date to
13869 DAYNR.
13870 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13871 the variable date is bound by the calendar when this is called."
13872 (cond
13873 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13874 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13875 daynr
13876 (+ daynr 1000)))
13877 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13878 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13879 (time-to-days (current-time))) (match-string 0 s)
13880 prefer show-all))
13881 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13883 (defun org-days-to-iso-week (days)
13884 "Return the iso week number."
13885 (require 'cal-iso)
13886 (car (calendar-iso-from-absolute days)))
13888 (defun org-small-year-to-year (year)
13889 "Convert 2-digit years into 4-digit years.
13890 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13891 The year 2000 cannot be abbreviated. Any year larger than 99
13892 is returned unchanged."
13893 (if (< year 38)
13894 (setq year (+ 2000 year))
13895 (if (< year 100)
13896 (setq year (+ 1900 year))))
13897 year)
13899 (defun org-time-from-absolute (d)
13900 "Return the time corresponding to date D.
13901 D may be an absolute day number, or a calendar-type list (month day year)."
13902 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13903 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13905 (defun org-calendar-holiday ()
13906 "List of holidays, for Diary display in Org-mode."
13907 (require 'holidays)
13908 (let ((hl (funcall
13909 (if (fboundp 'calendar-check-holidays)
13910 'calendar-check-holidays 'check-calendar-holidays) date)))
13911 (if hl (mapconcat 'identity hl "; "))))
13913 (defun org-diary-sexp-entry (sexp entry date)
13914 "Process a SEXP diary ENTRY for DATE."
13915 (require 'diary-lib)
13916 (let ((result (if calendar-debug-sexp
13917 (let ((stack-trace-on-error t))
13918 (eval (car (read-from-string sexp))))
13919 (condition-case nil
13920 (eval (car (read-from-string sexp)))
13921 (error
13922 (beep)
13923 (message "Bad sexp at line %d in %s: %s"
13924 (org-current-line)
13925 (buffer-file-name) sexp)
13926 (sleep-for 2))))))
13927 (cond ((stringp result) result)
13928 ((and (consp result)
13929 (stringp (cdr result))) (cdr result))
13930 (result entry)
13931 (t nil))))
13933 (defun org-diary-to-ical-string (frombuf)
13934 "Get iCalendar entries from diary entries in buffer FROMBUF.
13935 This uses the icalendar.el library."
13936 (let* ((tmpdir (if (featurep 'xemacs)
13937 (temp-directory)
13938 temporary-file-directory))
13939 (tmpfile (make-temp-name
13940 (expand-file-name "orgics" tmpdir)))
13941 buf rtn b e)
13942 (with-current-buffer frombuf
13943 (icalendar-export-region (point-min) (point-max) tmpfile)
13944 (setq buf (find-buffer-visiting tmpfile))
13945 (set-buffer buf)
13946 (goto-char (point-min))
13947 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13948 (setq b (match-beginning 0)))
13949 (goto-char (point-max))
13950 (if (re-search-backward "^END:VEVENT" nil t)
13951 (setq e (match-end 0)))
13952 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13953 (kill-buffer buf)
13954 (delete-file tmpfile)
13955 rtn))
13957 (defun org-closest-date (start current change prefer show-all)
13958 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13959 When PREFER is `past' return a date that is either CURRENT or past.
13960 When PREFER is `future', return a date that is either CURRENT or future.
13961 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13962 ;; Make the proper lists from the dates
13963 (catch 'exit
13964 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13965 dn dw sday cday n1 n2 n0
13966 d m y y1 y2 date1 date2 nmonths nm ny m2)
13968 (setq start (org-date-to-gregorian start)
13969 current (org-date-to-gregorian
13970 (if show-all
13971 current
13972 (time-to-days (current-time))))
13973 sday (calendar-absolute-from-gregorian start)
13974 cday (calendar-absolute-from-gregorian current))
13976 (if (<= cday sday) (throw 'exit sday))
13978 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13979 (setq dn (string-to-number (match-string 1 change))
13980 dw (cdr (assoc (match-string 2 change) a1)))
13981 (error "Invalid change specifyer: %s" change))
13982 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13983 (cond
13984 ((eq dw 'day)
13985 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13986 n2 (+ n1 dn)))
13987 ((eq dw 'year)
13988 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13989 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13990 (setq date1 (list m d y1)
13991 n1 (calendar-absolute-from-gregorian date1)
13992 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13993 n2 (calendar-absolute-from-gregorian date2)))
13994 ((eq dw 'month)
13995 ;; approx number of month between the two dates
13996 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13997 ;; How often does dn fit in there?
13998 (setq d (nth 1 start) m (car start) y (nth 2 start)
13999 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14000 m (+ m nm)
14001 ny (floor (/ m 12))
14002 y (+ y ny)
14003 m (- m (* ny 12)))
14004 (while (> m 12) (setq m (- m 12) y (1+ y)))
14005 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14006 (setq m2 (+ m dn) y2 y)
14007 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14008 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14009 (while (<= n2 cday)
14010 (setq n1 n2 m m2 y y2)
14011 (setq m2 (+ m dn) y2 y)
14012 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14013 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14014 ;; Make sure n1 is the earlier date
14015 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14016 (if show-all
14017 (cond
14018 ((eq prefer 'past) (if (= cday n2) n2 n1))
14019 ((eq prefer 'future) (if (= cday n1) n1 n2))
14020 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14021 (cond
14022 ((eq prefer 'past) (if (= cday n2) n2 n1))
14023 ((eq prefer 'future) (if (= cday n1) n1 n2))
14024 (t (if (= cday n1) n1 n2)))))))
14026 (defun org-date-to-gregorian (date)
14027 "Turn any specification of DATE into a gregorian date for the calendar."
14028 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14029 ((and (listp date) (= (length date) 3)) date)
14030 ((stringp date)
14031 (setq date (org-parse-time-string date))
14032 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14033 ((listp date)
14034 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14036 (defun org-parse-time-string (s &optional nodefault)
14037 "Parse the standard Org-mode time string.
14038 This should be a lot faster than the normal `parse-time-string'.
14039 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14040 hour and minute fields will be nil if not given."
14041 (if (string-match org-ts-regexp0 s)
14042 (list 0
14043 (if (or (match-beginning 8) (not nodefault))
14044 (string-to-number (or (match-string 8 s) "0")))
14045 (if (or (match-beginning 7) (not nodefault))
14046 (string-to-number (or (match-string 7 s) "0")))
14047 (string-to-number (match-string 4 s))
14048 (string-to-number (match-string 3 s))
14049 (string-to-number (match-string 2 s))
14050 nil nil nil)
14051 (error "Not a standard Org-mode time string: %s" s)))
14053 (defun org-timestamp-up (&optional arg)
14054 "Increase the date item at the cursor by one.
14055 If the cursor is on the year, change the year. If it is on the month or
14056 the day, change that.
14057 With prefix ARG, change by that many units."
14058 (interactive "p")
14059 (org-timestamp-change (prefix-numeric-value arg)))
14061 (defun org-timestamp-down (&optional arg)
14062 "Decrease the date item at the cursor by one.
14063 If the cursor is on the year, change the year. If it is on the month or
14064 the day, change that.
14065 With prefix ARG, change by that many units."
14066 (interactive "p")
14067 (org-timestamp-change (- (prefix-numeric-value arg))))
14069 (defun org-timestamp-up-day (&optional arg)
14070 "Increase the date in the time stamp by one day.
14071 With prefix ARG, change that many days."
14072 (interactive "p")
14073 (if (and (not (org-at-timestamp-p t))
14074 (org-on-heading-p))
14075 (org-todo 'up)
14076 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14078 (defun org-timestamp-down-day (&optional arg)
14079 "Decrease the date in the time stamp by one day.
14080 With prefix ARG, change that many days."
14081 (interactive "p")
14082 (if (and (not (org-at-timestamp-p t))
14083 (org-on-heading-p))
14084 (org-todo 'down)
14085 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14087 (defun org-at-timestamp-p (&optional inactive-ok)
14088 "Determine if the cursor is in or at a timestamp."
14089 (interactive)
14090 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14091 (pos (point))
14092 (ans (or (looking-at tsr)
14093 (save-excursion
14094 (skip-chars-backward "^[<\n\r\t")
14095 (if (> (point) (point-min)) (backward-char 1))
14096 (and (looking-at tsr)
14097 (> (- (match-end 0) pos) -1))))))
14098 (and ans
14099 (boundp 'org-ts-what)
14100 (setq org-ts-what
14101 (cond
14102 ((= pos (match-beginning 0)) 'bracket)
14103 ((= pos (1- (match-end 0))) 'bracket)
14104 ((org-pos-in-match-range pos 2) 'year)
14105 ((org-pos-in-match-range pos 3) 'month)
14106 ((org-pos-in-match-range pos 7) 'hour)
14107 ((org-pos-in-match-range pos 8) 'minute)
14108 ((or (org-pos-in-match-range pos 4)
14109 (org-pos-in-match-range pos 5)) 'day)
14110 ((and (> pos (or (match-end 8) (match-end 5)))
14111 (< pos (match-end 0)))
14112 (- pos (or (match-end 8) (match-end 5))))
14113 (t 'day))))
14114 ans))
14116 (defun org-toggle-timestamp-type ()
14117 "Toggle the type (<active> or [inactive]) of a time stamp."
14118 (interactive)
14119 (when (org-at-timestamp-p t)
14120 (let ((beg (match-beginning 0)) (end (match-end 0))
14121 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14122 (save-excursion
14123 (goto-char beg)
14124 (while (re-search-forward "[][<>]" end t)
14125 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14126 t t)))
14127 (message "Timestamp is now %sactive"
14128 (if (equal (char-after beg) ?<) "" "in")))))
14130 (defun org-timestamp-change (n &optional what)
14131 "Change the date in the time stamp at point.
14132 The date will be changed by N times WHAT. WHAT can be `day', `month',
14133 `year', `minute', `second'. If WHAT is not given, the cursor position
14134 in the timestamp determines what will be changed."
14135 (let ((pos (point))
14136 with-hm inactive
14137 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14138 org-ts-what
14139 extra rem
14140 ts time time0)
14141 (if (not (org-at-timestamp-p t))
14142 (error "Not at a timestamp"))
14143 (if (and (not what) (eq org-ts-what 'bracket))
14144 (org-toggle-timestamp-type)
14145 (if (and (not what) (not (eq org-ts-what 'day))
14146 org-display-custom-times
14147 (get-text-property (point) 'display)
14148 (not (get-text-property (1- (point)) 'display)))
14149 (setq org-ts-what 'day))
14150 (setq org-ts-what (or what org-ts-what)
14151 inactive (= (char-after (match-beginning 0)) ?\[)
14152 ts (match-string 0))
14153 (replace-match "")
14154 (if (string-match
14155 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14157 (setq extra (match-string 1 ts)))
14158 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14159 (setq with-hm t))
14160 (setq time0 (org-parse-time-string ts))
14161 (when (and (eq org-ts-what 'minute)
14162 (eq current-prefix-arg nil))
14163 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14164 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14165 (setcar (cdr time0) (+ (nth 1 time0)
14166 (if (> n 0) (- rem) (- dm rem))))))
14167 (setq time
14168 (encode-time (or (car time0) 0)
14169 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14170 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14171 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14172 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14173 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14174 (nthcdr 6 time0)))
14175 (when (and (member org-ts-what '(hour minute))
14176 extra
14177 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14178 (setq extra (org-modify-ts-extra
14179 extra
14180 (if (eq org-ts-what 'hour) 2 5)
14181 n dm)))
14182 (when (integerp org-ts-what)
14183 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14184 (if (eq what 'calendar)
14185 (let ((cal-date (org-get-date-from-calendar)))
14186 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14187 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14188 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14189 (setcar time0 (or (car time0) 0))
14190 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14191 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14192 (setq time (apply 'encode-time time0))))
14193 (setq org-last-changed-timestamp
14194 (org-insert-time-stamp time with-hm inactive nil nil extra))
14195 (org-clock-update-time-maybe)
14196 (goto-char pos)
14197 ;; Try to recenter the calendar window, if any
14198 (if (and org-calendar-follow-timestamp-change
14199 (get-buffer-window "*Calendar*" t)
14200 (memq org-ts-what '(day month year)))
14201 (org-recenter-calendar (time-to-days time))))))
14203 (defun org-modify-ts-extra (s pos n dm)
14204 "Change the different parts of the lead-time and repeat fields in timestamp."
14205 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14206 ng h m new rem)
14207 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14208 (cond
14209 ((or (org-pos-in-match-range pos 2)
14210 (org-pos-in-match-range pos 3))
14211 (setq m (string-to-number (match-string 3 s))
14212 h (string-to-number (match-string 2 s)))
14213 (if (org-pos-in-match-range pos 2)
14214 (setq h (+ h n))
14215 (setq n (* dm (org-no-warnings (signum n))))
14216 (when (not (= 0 (setq rem (% m dm))))
14217 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14218 (setq m (+ m n)))
14219 (if (< m 0) (setq m (+ m 60) h (1- h)))
14220 (if (> m 59) (setq m (- m 60) h (1+ h)))
14221 (setq h (min 24 (max 0 h)))
14222 (setq ng 1 new (format "-%02d:%02d" h m)))
14223 ((org-pos-in-match-range pos 6)
14224 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14225 ((org-pos-in-match-range pos 5)
14226 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14228 ((org-pos-in-match-range pos 9)
14229 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14230 ((org-pos-in-match-range pos 8)
14231 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14233 (when ng
14234 (setq s (concat
14235 (substring s 0 (match-beginning ng))
14237 (substring s (match-end ng))))))
14240 (defun org-recenter-calendar (date)
14241 "If the calendar is visible, recenter it to DATE."
14242 (let* ((win (selected-window))
14243 (cwin (get-buffer-window "*Calendar*" t))
14244 (calendar-move-hook nil))
14245 (when cwin
14246 (select-window cwin)
14247 (calendar-goto-date (if (listp date) date
14248 (calendar-gregorian-from-absolute date)))
14249 (select-window win))))
14251 (defun org-goto-calendar (&optional arg)
14252 "Go to the Emacs calendar at the current date.
14253 If there is a time stamp in the current line, go to that date.
14254 A prefix ARG can be used to force the current date."
14255 (interactive "P")
14256 (let ((tsr org-ts-regexp) diff
14257 (calendar-move-hook nil)
14258 (calendar-view-holidays-initially-flag nil)
14259 (view-calendar-holidays-initially nil)
14260 (calendar-view-diary-initially-flag nil)
14261 (view-diary-entries-initially nil))
14262 (if (or (org-at-timestamp-p)
14263 (save-excursion
14264 (beginning-of-line 1)
14265 (looking-at (concat ".*" tsr))))
14266 (let ((d1 (time-to-days (current-time)))
14267 (d2 (time-to-days
14268 (org-time-string-to-time (match-string 1)))))
14269 (setq diff (- d2 d1))))
14270 (calendar)
14271 (calendar-goto-today)
14272 (if (and diff (not arg)) (calendar-forward-day diff))))
14274 (defun org-get-date-from-calendar ()
14275 "Return a list (month day year) of date at point in calendar."
14276 (with-current-buffer "*Calendar*"
14277 (save-match-data
14278 (calendar-cursor-to-date))))
14280 (defun org-date-from-calendar ()
14281 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14282 If there is already a time stamp at the cursor position, update it."
14283 (interactive)
14284 (if (org-at-timestamp-p t)
14285 (org-timestamp-change 0 'calendar)
14286 (let ((cal-date (org-get-date-from-calendar)))
14287 (org-insert-time-stamp
14288 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14290 (defun org-minutes-to-hh:mm-string (m)
14291 "Compute H:MM from a number of minutes."
14292 (let ((h (/ m 60)))
14293 (setq m (- m (* 60 h)))
14294 (format org-time-clocksum-format h m)))
14296 (defun org-hh:mm-string-to-minutes (s)
14297 "Convert a string H:MM to a number of minutes.
14298 If the string is just a number, interpret it as minutes.
14299 In fact, the first hh:mm or number in the string will be taken,
14300 there can be extra stuff in the string.
14301 If no number is found, the return value is 0."
14302 (cond
14303 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14304 (+ (* (string-to-number (match-string 1 s)) 60)
14305 (string-to-number (match-string 2 s))))
14306 ((string-match "\\([0-9]+\\)" s)
14307 (string-to-number (match-string 1 s)))
14308 (t 0)))
14310 ;;;; Files
14312 (defun org-save-all-org-buffers ()
14313 "Save all Org-mode buffers without user confirmation."
14314 (interactive)
14315 (message "Saving all Org-mode buffers...")
14316 (save-some-buffers t 'org-mode-p)
14317 (when (featurep 'org-id) (org-id-locations-save))
14318 (message "Saving all Org-mode buffers... done"))
14320 (defun org-revert-all-org-buffers ()
14321 "Revert all Org-mode buffers.
14322 Prompt for confirmation when there are unsaved changes.
14323 Be sure you know what you are doing before letting this function
14324 overwrite your changes.
14326 This function is useful in a setup where one tracks org files
14327 with a version control system, to revert on one machine after pulling
14328 changes from another. I believe the procedure must be like this:
14330 1. M-x org-save-all-org-buffers
14331 2. Pull changes from the other machine, resolve conflicts
14332 3. M-x org-revert-all-org-buffers"
14333 (interactive)
14334 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14335 (error "Abort"))
14336 (save-excursion
14337 (save-window-excursion
14338 (mapc
14339 (lambda (b)
14340 (when (and (with-current-buffer b (org-mode-p))
14341 (with-current-buffer b buffer-file-name))
14342 (switch-to-buffer b)
14343 (revert-buffer t 'no-confirm)))
14344 (buffer-list))
14345 (when (and (featurep 'org-id) org-id-track-globally)
14346 (org-id-locations-load)))))
14348 ;;;; Agenda files
14350 ;;;###autoload
14351 (defun org-iswitchb (&optional arg)
14352 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14353 With a prefix argument, restrict available to files.
14354 With two prefix arguments, restrict available buffers to agenda files."
14355 (interactive "P")
14356 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14357 ((equal arg '(16)) (org-buffer-list 'agenda))
14358 (t (org-buffer-list)))))
14359 (switch-to-buffer
14360 (org-icompleting-read "Org buffer: "
14361 (mapcar 'list (mapcar 'buffer-name blist))
14362 nil t))))
14364 ;;;###autoload
14365 (defalias 'org-ido-switchb 'org-iswitchb)
14367 (defun org-buffer-list (&optional predicate exclude-tmp)
14368 "Return a list of Org buffers.
14369 PREDICATE can be `export', `files' or `agenda'.
14371 export restrict the list to Export buffers.
14372 files restrict the list to buffers visiting Org files.
14373 agenda restrict the list to buffers visiting agenda files.
14375 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14376 (let* ((bfn nil)
14377 (agenda-files (and (eq predicate 'agenda)
14378 (mapcar 'file-truename (org-agenda-files t))))
14379 (filter
14380 (cond
14381 ((eq predicate 'files)
14382 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14383 ((eq predicate 'export)
14384 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14385 ((eq predicate 'agenda)
14386 (lambda (b)
14387 (with-current-buffer b
14388 (and (eq major-mode 'org-mode)
14389 (setq bfn (buffer-file-name b))
14390 (member (file-truename bfn) agenda-files)))))
14391 (t (lambda (b) (with-current-buffer b
14392 (or (eq major-mode 'org-mode)
14393 (string-match "\*Org .*Export"
14394 (buffer-name b)))))))))
14395 (delq nil
14396 (mapcar
14397 (lambda(b)
14398 (if (and (funcall filter b)
14399 (or (not exclude-tmp)
14400 (not (string-match "tmp" (buffer-name b)))))
14402 nil))
14403 (buffer-list)))))
14405 (defun org-agenda-files (&optional unrestricted archives)
14406 "Get the list of agenda files.
14407 Optional UNRESTRICTED means return the full list even if a restriction
14408 is currently in place.
14409 When ARCHIVES is t, include all archive files hat are really being
14410 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14411 `org-agenda-archives-mode' is t."
14412 (let ((files
14413 (cond
14414 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14415 ((stringp org-agenda-files) (org-read-agenda-file-list))
14416 ((listp org-agenda-files) org-agenda-files)
14417 (t (error "Invalid value of `org-agenda-files'")))))
14418 (setq files (apply 'append
14419 (mapcar (lambda (f)
14420 (if (file-directory-p f)
14421 (directory-files
14422 f t org-agenda-file-regexp)
14423 (list f)))
14424 files)))
14425 (when org-agenda-skip-unavailable-files
14426 (setq files (delq nil
14427 (mapcar (function
14428 (lambda (file)
14429 (and (file-readable-p file) file)))
14430 files))))
14431 (when (or (eq archives t)
14432 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14433 (setq files (org-add-archive-files files)))
14434 files))
14436 (defun org-edit-agenda-file-list ()
14437 "Edit the list of agenda files.
14438 Depending on setup, this either uses customize to edit the variable
14439 `org-agenda-files', or it visits the file that is holding the list. In the
14440 latter case, the buffer is set up in a way that saving it automatically kills
14441 the buffer and restores the previous window configuration."
14442 (interactive)
14443 (if (stringp org-agenda-files)
14444 (let ((cw (current-window-configuration)))
14445 (find-file org-agenda-files)
14446 (org-set-local 'org-window-configuration cw)
14447 (org-add-hook 'after-save-hook
14448 (lambda ()
14449 (set-window-configuration
14450 (prog1 org-window-configuration
14451 (kill-buffer (current-buffer))))
14452 (org-install-agenda-files-menu)
14453 (message "New agenda file list installed"))
14454 nil 'local)
14455 (message "%s" (substitute-command-keys
14456 "Edit list and finish with \\[save-buffer]")))
14457 (customize-variable 'org-agenda-files)))
14459 (defun org-store-new-agenda-file-list (list)
14460 "Set new value for the agenda file list and save it correctly."
14461 (if (stringp org-agenda-files)
14462 (let ((f org-agenda-files) b)
14463 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14464 (with-temp-file f
14465 (insert (mapconcat 'identity list "\n") "\n")))
14466 (let ((org-mode-hook nil) (org-inhibit-startup t)
14467 (org-insert-mode-line-in-empty-file nil))
14468 (setq org-agenda-files list)
14469 (customize-save-variable 'org-agenda-files org-agenda-files))))
14471 (defun org-read-agenda-file-list ()
14472 "Read the list of agenda files from a file."
14473 (when (file-directory-p org-agenda-files)
14474 (error "`org-agenda-files' cannot be a single directory"))
14475 (when (stringp org-agenda-files)
14476 (with-temp-buffer
14477 (insert-file-contents org-agenda-files)
14478 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14481 ;;;###autoload
14482 (defun org-cycle-agenda-files ()
14483 "Cycle through the files in `org-agenda-files'.
14484 If the current buffer visits an agenda file, find the next one in the list.
14485 If the current buffer does not, find the first agenda file."
14486 (interactive)
14487 (let* ((fs (org-agenda-files t))
14488 (files (append fs (list (car fs))))
14489 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14490 file)
14491 (unless files (error "No agenda files"))
14492 (catch 'exit
14493 (while (setq file (pop files))
14494 (if (equal (file-truename file) tcf)
14495 (when (car files)
14496 (find-file (car files))
14497 (throw 'exit t))))
14498 (find-file (car fs)))
14499 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14501 (defun org-agenda-file-to-front (&optional to-end)
14502 "Move/add the current file to the top of the agenda file list.
14503 If the file is not present in the list, it is added to the front. If it is
14504 present, it is moved there. With optional argument TO-END, add/move to the
14505 end of the list."
14506 (interactive "P")
14507 (let ((org-agenda-skip-unavailable-files nil)
14508 (file-alist (mapcar (lambda (x)
14509 (cons (file-truename x) x))
14510 (org-agenda-files t)))
14511 (ctf (file-truename buffer-file-name))
14512 x had)
14513 (setq x (assoc ctf file-alist) had x)
14515 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14516 (if to-end
14517 (setq file-alist (append (delq x file-alist) (list x)))
14518 (setq file-alist (cons x (delq x file-alist))))
14519 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14520 (org-install-agenda-files-menu)
14521 (message "File %s to %s of agenda file list"
14522 (if had "moved" "added") (if to-end "end" "front"))))
14524 (defun org-remove-file (&optional file)
14525 "Remove current file from the list of files in variable `org-agenda-files'.
14526 These are the files which are being checked for agenda entries.
14527 Optional argument FILE means, use this file instead of the current."
14528 (interactive)
14529 (let* ((org-agenda-skip-unavailable-files nil)
14530 (file (or file buffer-file-name))
14531 (true-file (file-truename file))
14532 (afile (abbreviate-file-name file))
14533 (files (delq nil (mapcar
14534 (lambda (x)
14535 (if (equal true-file
14536 (file-truename x))
14537 nil x))
14538 (org-agenda-files t)))))
14539 (if (not (= (length files) (length (org-agenda-files t))))
14540 (progn
14541 (org-store-new-agenda-file-list files)
14542 (org-install-agenda-files-menu)
14543 (message "Removed file: %s" afile))
14544 (message "File was not in list: %s (not removed)" afile))))
14546 (defun org-file-menu-entry (file)
14547 (vector file (list 'find-file file) t))
14549 (defun org-check-agenda-file (file)
14550 "Make sure FILE exists. If not, ask user what to do."
14551 (when (not (file-exists-p file))
14552 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14553 (abbreviate-file-name file))
14554 (let ((r (downcase (read-char-exclusive))))
14555 (cond
14556 ((equal r ?r)
14557 (org-remove-file file)
14558 (throw 'nextfile t))
14559 (t (error "Abort"))))))
14561 (defun org-get-agenda-file-buffer (file)
14562 "Get a buffer visiting FILE. If the buffer needs to be created, add
14563 it to the list of buffers which might be released later."
14564 (let ((buf (org-find-base-buffer-visiting file)))
14565 (if buf
14566 buf ; just return it
14567 ;; Make a new buffer and remember it
14568 (setq buf (find-file-noselect file))
14569 (if buf (push buf org-agenda-new-buffers))
14570 buf)))
14572 (defun org-release-buffers (blist)
14573 "Release all buffers in list, asking the user for confirmation when needed.
14574 When a buffer is unmodified, it is just killed. When modified, it is saved
14575 \(if the user agrees) and then killed."
14576 (let (buf file)
14577 (while (setq buf (pop blist))
14578 (setq file (buffer-file-name buf))
14579 (when (and (buffer-modified-p buf)
14580 file
14581 (y-or-n-p (format "Save file %s? " file)))
14582 (with-current-buffer buf (save-buffer)))
14583 (kill-buffer buf))))
14585 (defun org-prepare-agenda-buffers (files)
14586 "Create buffers for all agenda files, protect archived trees and comments."
14587 (interactive)
14588 (let ((pa '(:org-archived t))
14589 (pc '(:org-comment t))
14590 (pall '(:org-archived t :org-comment t))
14591 (inhibit-read-only t)
14592 (rea (concat ":" org-archive-tag ":"))
14593 bmp file re)
14594 (save-excursion
14595 (save-restriction
14596 (while (setq file (pop files))
14597 (catch 'nextfile
14598 (if (bufferp file)
14599 (set-buffer file)
14600 (org-check-agenda-file file)
14601 (set-buffer (org-get-agenda-file-buffer file)))
14602 (widen)
14603 (setq bmp (buffer-modified-p))
14604 (org-refresh-category-properties)
14605 (setq org-todo-keywords-for-agenda
14606 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14607 (setq org-done-keywords-for-agenda
14608 (append org-done-keywords-for-agenda org-done-keywords))
14609 (setq org-todo-keyword-alist-for-agenda
14610 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14611 (setq org-drawers-for-agenda
14612 (append org-drawers-for-agenda org-drawers))
14613 (setq org-tag-alist-for-agenda
14614 (append org-tag-alist-for-agenda org-tag-alist))
14616 (save-excursion
14617 (remove-text-properties (point-min) (point-max) pall)
14618 (when org-agenda-skip-archived-trees
14619 (goto-char (point-min))
14620 (while (re-search-forward rea nil t)
14621 (if (org-on-heading-p t)
14622 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14623 (goto-char (point-min))
14624 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14625 (while (re-search-forward re nil t)
14626 (add-text-properties
14627 (match-beginning 0) (org-end-of-subtree t) pc)))
14628 (set-buffer-modified-p bmp)))))
14629 (setq org-todo-keyword-alist-for-agenda
14630 (org-uniquify org-todo-keyword-alist-for-agenda)
14631 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14633 ;;;; Embedded LaTeX
14635 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14636 "Keymap for the minor `org-cdlatex-mode'.")
14638 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14639 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14640 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14641 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14642 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14644 (defvar org-cdlatex-texmathp-advice-is-done nil
14645 "Flag remembering if we have applied the advice to texmathp already.")
14647 (define-minor-mode org-cdlatex-mode
14648 "Toggle the minor `org-cdlatex-mode'.
14649 This mode supports entering LaTeX environment and math in LaTeX fragments
14650 in Org-mode.
14651 \\{org-cdlatex-mode-map}"
14652 nil " OCDL" nil
14653 (when org-cdlatex-mode (require 'cdlatex))
14654 (unless org-cdlatex-texmathp-advice-is-done
14655 (setq org-cdlatex-texmathp-advice-is-done t)
14656 (defadvice texmathp (around org-math-always-on activate)
14657 "Always return t in org-mode buffers.
14658 This is because we want to insert math symbols without dollars even outside
14659 the LaTeX math segments. If Orgmode thinks that point is actually inside
14660 an embedded LaTeX fragment, let texmathp do its job.
14661 \\[org-cdlatex-mode-map]"
14662 (interactive)
14663 (let (p)
14664 (cond
14665 ((not (org-mode-p)) ad-do-it)
14666 ((eq this-command 'cdlatex-math-symbol)
14667 (setq ad-return-value t
14668 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14670 (let ((p (org-inside-LaTeX-fragment-p)))
14671 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14672 (setq ad-return-value t
14673 texmathp-why '("Org-mode embedded math" . 0))
14674 (if p ad-do-it)))))))))
14676 (defun turn-on-org-cdlatex ()
14677 "Unconditionally turn on `org-cdlatex-mode'."
14678 (org-cdlatex-mode 1))
14680 (defun org-inside-LaTeX-fragment-p ()
14681 "Test if point is inside a LaTeX fragment.
14682 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14683 sequence appearing also before point.
14684 Even though the matchers for math are configurable, this function assumes
14685 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14686 delimiters are skipped when they have been removed by customization.
14687 The return value is nil, or a cons cell with the delimiter and
14688 and the position of this delimiter.
14690 This function does a reasonably good job, but can locally be fooled by
14691 for example currency specifications. For example it will assume being in
14692 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14693 fragments that are properly closed, but during editing, we have to live
14694 with the uncertainty caused by missing closing delimiters. This function
14695 looks only before point, not after."
14696 (catch 'exit
14697 (let ((pos (point))
14698 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14699 (lim (progn
14700 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14701 (point)))
14702 dd-on str (start 0) m re)
14703 (goto-char pos)
14704 (when dodollar
14705 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14706 re (nth 1 (assoc "$" org-latex-regexps)))
14707 (while (string-match re str start)
14708 (cond
14709 ((= (match-end 0) (length str))
14710 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14711 ((= (match-end 0) (- (length str) 5))
14712 (throw 'exit nil))
14713 (t (setq start (match-end 0))))))
14714 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14715 (goto-char pos)
14716 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14717 (and (match-beginning 2) (throw 'exit nil))
14718 ;; count $$
14719 (while (re-search-backward "\\$\\$" lim t)
14720 (setq dd-on (not dd-on)))
14721 (goto-char pos)
14722 (if dd-on (cons "$$" m))))))
14724 (defun org-inside-latex-macro-p ()
14725 "Is point inside a LaTeX macro or its arguments?"
14726 (save-match-data
14727 (org-in-regexp
14728 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14730 (defun org-try-cdlatex-tab ()
14731 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14732 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14733 - inside a LaTeX fragment, or
14734 - after the first word in a line, where an abbreviation expansion could
14735 insert a LaTeX environment."
14736 (when org-cdlatex-mode
14737 (cond
14738 ((save-excursion
14739 (skip-chars-backward "a-zA-Z0-9*")
14740 (skip-chars-backward " \t")
14741 (bolp))
14742 (cdlatex-tab) t)
14743 ((org-inside-LaTeX-fragment-p)
14744 (cdlatex-tab) t)
14745 (t nil))))
14747 (defun org-cdlatex-underscore-caret (&optional arg)
14748 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14749 Revert to the normal definition outside of these fragments."
14750 (interactive "P")
14751 (if (org-inside-LaTeX-fragment-p)
14752 (call-interactively 'cdlatex-sub-superscript)
14753 (let (org-cdlatex-mode)
14754 (call-interactively (key-binding (vector last-input-event))))))
14756 (defun org-cdlatex-math-modify (&optional arg)
14757 "Execute `cdlatex-math-modify' in LaTeX fragments.
14758 Revert to the normal definition outside of these fragments."
14759 (interactive "P")
14760 (if (org-inside-LaTeX-fragment-p)
14761 (call-interactively 'cdlatex-math-modify)
14762 (let (org-cdlatex-mode)
14763 (call-interactively (key-binding (vector last-input-event))))))
14765 (defvar org-latex-fragment-image-overlays nil
14766 "List of overlays carrying the images of latex fragments.")
14767 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14769 (defun org-remove-latex-fragment-image-overlays ()
14770 "Remove all overlays with LaTeX fragment images in current buffer."
14771 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14772 (setq org-latex-fragment-image-overlays nil))
14774 (defun org-preview-latex-fragment (&optional subtree)
14775 "Preview the LaTeX fragment at point, or all locally or globally.
14776 If the cursor is in a LaTeX fragment, create the image and overlay
14777 it over the source code. If there is no fragment at point, display
14778 all fragments in the current text, from one headline to the next. With
14779 prefix SUBTREE, display all fragments in the current subtree. With a
14780 double prefix `C-u C-u', or when the cursor is before the first headline,
14781 display all fragments in the buffer.
14782 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14783 (interactive "P")
14784 (org-remove-latex-fragment-image-overlays)
14785 (save-excursion
14786 (save-restriction
14787 (let (beg end at msg)
14788 (cond
14789 ((or (equal subtree '(16))
14790 (not (save-excursion
14791 (re-search-backward (concat "^" outline-regexp) nil t))))
14792 (setq beg (point-min) end (point-max)
14793 msg "Creating images for buffer...%s"))
14794 ((equal subtree '(4))
14795 (org-back-to-heading)
14796 (setq beg (point) end (org-end-of-subtree t)
14797 msg "Creating images for subtree...%s"))
14799 (if (setq at (org-inside-LaTeX-fragment-p))
14800 (goto-char (max (point-min) (- (cdr at) 2)))
14801 (org-back-to-heading))
14802 (setq beg (point) end (progn (outline-next-heading) (point))
14803 msg (if at "Creating image...%s"
14804 "Creating images for entry...%s"))))
14805 (message msg "")
14806 (narrow-to-region beg end)
14807 (goto-char beg)
14808 (org-format-latex
14809 (concat "ltxpng/" (file-name-sans-extension
14810 (file-name-nondirectory
14811 buffer-file-name)))
14812 default-directory 'overlays msg at 'forbuffer)
14813 (message msg "done. Use `C-c C-c' to remove images.")))))
14815 (defvar org-latex-regexps
14816 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14817 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14818 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14819 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14820 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14821 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14822 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14823 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14824 "Regular expressions for matching embedded LaTeX.")
14826 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14827 "Replace LaTeX fragments with links to an image, and produce images.
14828 Some of the options can be changed using the variable
14829 `org-format-latex-options'."
14830 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14831 (let* ((prefixnodir (file-name-nondirectory prefix))
14832 (absprefix (expand-file-name prefix dir))
14833 (todir (file-name-directory absprefix))
14834 (opt org-format-latex-options)
14835 (matchers (plist-get opt :matchers))
14836 (re-list org-latex-regexps)
14837 (org-format-latex-header-extra
14838 (plist-get (org-infile-export-plist) :latex-header-extra))
14839 (cnt 0) txt hash link beg end re e checkdir
14840 executables-checked
14841 m n block linkfile movefile ov)
14842 ;; Check the different regular expressions
14843 (while (setq e (pop re-list))
14844 (setq m (car e) re (nth 1 e) n (nth 2 e)
14845 block (if (nth 3 e) "\n\n" ""))
14846 (when (member m matchers)
14847 (goto-char (point-min))
14848 (while (re-search-forward re nil t)
14849 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14850 (not (get-text-property (match-beginning n)
14851 'org-protected))
14852 (or (not overlays)
14853 (not (eq (get-char-property (match-beginning n)
14854 'org-overlay-type)
14855 'org-latex-overlay))))
14856 (setq txt (match-string n)
14857 beg (match-beginning n) end (match-end n)
14858 cnt (1+ cnt))
14859 (let (print-length print-level) ; make sure full list is printed
14860 (setq hash (sha1 (prin1-to-string
14861 (list org-format-latex-header
14862 org-format-latex-header-extra
14863 org-export-latex-packages-alist
14864 org-format-latex-options
14865 forbuffer txt)))
14866 linkfile (format "%s_%s.png" prefix hash)
14867 movefile (format "%s_%s.png" absprefix hash)))
14868 (setq link (concat block "[[file:" linkfile "]]" block))
14869 (if msg (message msg cnt))
14870 (goto-char beg)
14871 (unless checkdir ; make sure the directory exists
14872 (setq checkdir t)
14873 (or (file-directory-p todir) (make-directory todir)))
14875 (unless executables-checked
14876 (org-check-external-command
14877 "latex" "needed to convert LaTeX fragments to images")
14878 (org-check-external-command
14879 "dvipng" "needed to convert LaTeX fragments to images")
14880 (setq executables-checked t))
14882 (unless (file-exists-p movefile)
14883 (org-create-formula-image
14884 txt movefile opt forbuffer))
14885 (if overlays
14886 (progn
14887 (mapc (lambda (o)
14888 (if (eq (org-overlay-get o 'org-overlay-type)
14889 'org-latex-overlay)
14890 (org-delete-overlay o)))
14891 (org-overlays-in beg end))
14892 (setq ov (org-make-overlay beg end))
14893 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14894 (if (featurep 'xemacs)
14895 (progn
14896 (org-overlay-put ov 'invisible t)
14897 (org-overlay-put
14898 ov 'end-glyph
14899 (make-glyph (vector 'png :file movefile))))
14900 (org-overlay-put
14901 ov 'display
14902 (list 'image :type 'png :file movefile :ascent 'center)))
14903 (push ov org-latex-fragment-image-overlays)
14904 (goto-char end))
14905 (delete-region beg end)
14906 (insert link))))))))
14908 ;; This function borrows from Ganesh Swami's latex2png.el
14909 (defun org-create-formula-image (string tofile options buffer)
14910 "This calls dvipng."
14911 (require 'org-latex)
14912 (let* ((tmpdir (if (featurep 'xemacs)
14913 (temp-directory)
14914 temporary-file-directory))
14915 (texfilebase (make-temp-name
14916 (expand-file-name "orgtex" tmpdir)))
14917 (texfile (concat texfilebase ".tex"))
14918 (dvifile (concat texfilebase ".dvi"))
14919 (pngfile (concat texfilebase ".png"))
14920 (fnh (if (featurep 'xemacs)
14921 (font-height (get-face-font 'default))
14922 (face-attribute 'default :height nil)))
14923 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14924 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14925 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14926 "Black"))
14927 (bg (or (plist-get options (if buffer :background :html-background))
14928 "Transparent")))
14929 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14930 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14931 (with-temp-file texfile
14932 (insert org-format-latex-header
14933 (if org-export-latex-packages-alist
14934 (concat "\n"
14935 (mapconcat (lambda(p)
14936 (if (equal "" (car p))
14937 (format "\\usepackage{%s}" (cadr p))
14938 (format "\\usepackage[%s]{%s}"
14939 (car p) (cadr p))))
14940 org-export-latex-packages-alist "\n"))
14942 (if org-format-latex-header-extra
14943 (concat "\n" org-format-latex-header-extra)
14945 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14946 (let ((dir default-directory))
14947 (condition-case nil
14948 (progn
14949 (cd tmpdir)
14950 (call-process "latex" nil nil nil texfile))
14951 (error nil))
14952 (cd dir))
14953 (if (not (file-exists-p dvifile))
14954 (progn (message "Failed to create dvi file from %s" texfile) nil)
14955 (condition-case nil
14956 (call-process "dvipng" nil nil nil
14957 "-fg" fg "-bg" bg
14958 "-D" dpi
14959 ;;"-x" scale "-y" scale
14960 "-T" "tight"
14961 "-o" pngfile
14962 dvifile)
14963 (error nil))
14964 (if (not (file-exists-p pngfile))
14965 (progn (message "Failed to create png file from %s" texfile) nil)
14966 ;; Use the requested file name and clean up
14967 (copy-file pngfile tofile 'replace)
14968 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14969 (delete-file (concat texfilebase e)))
14970 pngfile))))
14972 (defun org-dvipng-color (attr)
14973 "Return an rgb color specification for dvipng."
14974 (apply 'format "rgb %s %s %s"
14975 (mapcar 'org-normalize-color
14976 (color-values (face-attribute 'default attr nil)))))
14978 (defun org-normalize-color (value)
14979 "Return string to be used as color value for an RGB component."
14980 (format "%g" (/ value 65535.0)))
14982 ;;;; Key bindings
14984 ;; Make `C-c C-x' a prefix key
14985 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14987 ;; TAB key with modifiers
14988 (org-defkey org-mode-map "\C-i" 'org-cycle)
14989 (org-defkey org-mode-map [(tab)] 'org-cycle)
14990 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14991 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14992 (org-defkey org-mode-map "\M-\t" 'org-complete)
14993 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14994 ;; The following line is necessary under Suse GNU/Linux
14995 (unless (featurep 'xemacs)
14996 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14997 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14998 (define-key org-mode-map [backtab] 'org-shifttab)
15000 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15001 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15002 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15004 ;; Cursor keys with modifiers
15005 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15006 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15007 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15008 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15010 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15011 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15012 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15013 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15015 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15016 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15017 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15018 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15020 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15021 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15023 ;;; Extra keys for tty access.
15024 ;; We only set them when really needed because otherwise the
15025 ;; menus don't show the simple keys
15027 (when (or org-use-extra-keys
15028 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15029 (not window-system))
15030 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15031 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15032 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15033 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15034 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15035 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15036 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15037 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15038 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15039 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15040 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15041 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15042 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15043 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15044 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15045 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15046 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15047 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15048 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15049 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15050 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15051 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15052 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15053 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15054 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15055 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15056 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15057 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15059 ;; All the other keys
15061 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15062 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15063 (if (boundp 'narrow-map)
15064 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15065 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15066 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15067 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15068 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15069 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15070 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15071 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15072 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15073 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15074 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15075 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15076 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15077 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15078 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15079 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15080 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15081 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15082 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15083 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15084 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15085 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15086 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15087 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15088 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15089 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15090 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15091 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15092 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15093 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15094 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15095 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15096 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15097 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15098 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15099 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15100 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15101 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15102 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15103 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15104 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15105 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15106 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15107 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15108 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15109 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15110 (org-defkey org-mode-map "\C-c^" 'org-sort)
15111 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15112 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15113 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15114 (org-defkey org-mode-map "\C-m" 'org-return)
15115 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15116 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15117 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15118 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15119 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15120 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15121 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15122 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15123 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15124 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15125 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15126 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15127 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15128 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15129 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15130 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15131 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15132 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15133 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15134 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15135 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15137 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15138 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15139 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15140 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15142 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15143 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15144 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15145 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15146 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15147 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15148 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15149 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15150 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15151 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15152 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15153 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15154 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15155 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15156 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15158 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15159 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15160 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15161 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15163 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15165 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15167 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15168 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15170 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15173 (when (featurep 'xemacs)
15174 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15177 (defconst org-speed-commands-default
15179 ("Outline Navigation")
15180 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15181 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15182 ("f" . (org-speed-move-safe 'org-forward-same-level))
15183 ("b" . (org-speed-move-safe 'org-backward-same-level))
15184 ("u" . (org-speed-move-safe 'outline-up-heading))
15185 ("j" . org-goto)
15186 ("g" . (org-refile t))
15187 ("Outline Visibility")
15188 ("c" . org-cycle)
15189 ("C" . org-shifttab)
15190 (" " . org-display-outline-path)
15191 ("Outline Structure Editing")
15192 ("U" . org-shiftmetaup)
15193 ("D" . org-shiftmetadown)
15194 ("r" . org-metaright)
15195 ("l" . org-metaleft)
15196 ("R" . org-shiftmetaright)
15197 ("L" . org-shiftmetaleft)
15198 ("i" . (progn (forward-char 1) (call-interactively
15199 'org-insert-heading-respect-content)))
15200 ("^" . org-sort)
15201 ("w" . org-refile)
15202 ("a" . org-archive-subtree-default-with-confirmation)
15203 ("." . outline-mark-subtree)
15204 ("Clock Commands")
15205 ("I" . org-clock-in)
15206 ("O" . org-clock-out)
15207 ("Meta Data Editing")
15208 ("t" . org-todo)
15209 ("0" . (org-priority ?\ ))
15210 ("1" . (org-priority ?A))
15211 ("2" . (org-priority ?B))
15212 ("3" . (org-priority ?C))
15213 (";" . org-set-tags-command)
15214 ("e" . org-set-effort)
15215 ("Agenda Views etc")
15216 ("v" . org-agenda)
15217 ("/" . org-sparse-tree)
15218 ("Misc")
15219 ("o" . org-open-at-point)
15220 ("?" . org-speed-command-help)
15222 "The default speed commands.")
15224 (defun org-print-speed-command (e)
15225 (if (> (length (car e)) 1)
15226 (progn
15227 (princ "\n")
15228 (princ (car e))
15229 (princ "\n")
15230 (princ (make-string (length (car e)) ?-))
15231 (princ "\n"))
15232 (princ (car e))
15233 (princ " ")
15234 (if (symbolp (cdr e))
15235 (princ (symbol-name (cdr e)))
15236 (prin1 (cdr e)))
15237 (princ "\n")))
15239 (defun org-speed-command-help ()
15240 "Show the available speed commands."
15241 (interactive)
15242 (if (not org-use-speed-commands)
15243 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15244 (with-output-to-temp-buffer "*Help*"
15245 (princ "User-defined Speed commands\n===========================\n")
15246 (mapc 'org-print-speed-command org-speed-commands-user)
15247 (princ "\n")
15248 (princ "Built-in Speed commands\n=======================\n")
15249 (mapc 'org-print-speed-command org-speed-commands-default))
15250 (with-current-buffer "*Help*"
15251 (setq truncate-lines t))))
15253 (defun org-speed-move-safe (cmd)
15254 "Execute CMD, but make sure that the cursor always ends up in a headline.
15255 If not, return to the original position and throw an error."
15256 (interactive)
15257 (let ((pos (point)))
15258 (call-interactively cmd)
15259 (unless (and (bolp) (org-on-heading-p))
15260 (goto-char pos)
15261 (error "Boundary reached while executing %s" cmd))))
15263 (defvar org-self-insert-command-undo-counter 0)
15265 (defvar org-table-auto-blank-field) ; defined in org-table.el
15266 (defvar org-speed-command nil)
15267 (defun org-self-insert-command (N)
15268 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15269 If the cursor is in a table looking at whitespace, the whitespace is
15270 overwritten, and the table is not marked as requiring realignment."
15271 (interactive "p")
15272 (cond
15273 ((and org-use-speed-commands
15274 (or (and (bolp) (looking-at outline-regexp))
15275 (and (functionp org-use-speed-commands)
15276 (funcall org-use-speed-commands)))
15277 (setq
15278 org-speed-command
15279 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15280 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15281 (cond
15282 ((commandp org-speed-command)
15283 (setq this-command org-speed-command)
15284 (call-interactively org-speed-command))
15285 ((functionp org-speed-command)
15286 (funcall org-speed-command))
15287 ((and org-speed-command (listp org-speed-command))
15288 (eval org-speed-command))
15289 (t (let (org-use-speed-commands)
15290 (call-interactively 'org-self-insert-command)))))
15291 ((and
15292 (org-table-p)
15293 (progn
15294 ;; check if we blank the field, and if that triggers align
15295 (and (featurep 'org-table) org-table-auto-blank-field
15296 (member last-command
15297 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15298 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15299 ;; got extra space, this field does not determine column width
15300 (let (org-table-may-need-update) (org-table-blank-field))
15301 ;; no extra space, this field may determine column width
15302 (org-table-blank-field)))
15304 (eq N 1)
15305 (looking-at "[^|\n]* |"))
15306 (let (org-table-may-need-update)
15307 (goto-char (1- (match-end 0)))
15308 (delete-backward-char 1)
15309 (goto-char (match-beginning 0))
15310 (self-insert-command N)))
15312 (setq org-table-may-need-update t)
15313 (self-insert-command N)
15314 (org-fix-tags-on-the-fly)
15315 (if org-self-insert-cluster-for-undo
15316 (if (not (eq last-command 'org-self-insert-command))
15317 (setq org-self-insert-command-undo-counter 1)
15318 (if (>= org-self-insert-command-undo-counter 20)
15319 (setq org-self-insert-command-undo-counter 1)
15320 (and (> org-self-insert-command-undo-counter 0)
15321 buffer-undo-list
15322 (not (cadr buffer-undo-list)) ; remove nil entry
15323 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15324 (setq org-self-insert-command-undo-counter
15325 (1+ org-self-insert-command-undo-counter))))))))
15327 (defun org-fix-tags-on-the-fly ()
15328 (when (and (equal (char-after (point-at-bol)) ?*)
15329 (org-on-heading-p))
15330 (org-align-tags-here org-tags-column)))
15332 (defun org-delete-backward-char (N)
15333 "Like `delete-backward-char', insert whitespace at field end in tables.
15334 When deleting backwards, in tables this function will insert whitespace in
15335 front of the next \"|\" separator, to keep the table aligned. The table will
15336 still be marked for re-alignment if the field did fill the entire column,
15337 because, in this case the deletion might narrow the column."
15338 (interactive "p")
15339 (if (and (org-table-p)
15340 (eq N 1)
15341 (string-match "|" (buffer-substring (point-at-bol) (point)))
15342 (looking-at ".*?|"))
15343 (let ((pos (point))
15344 (noalign (looking-at "[^|\n\r]* |"))
15345 (c org-table-may-need-update))
15346 (backward-delete-char N)
15347 (skip-chars-forward "^|")
15348 (insert " ")
15349 (goto-char (1- pos))
15350 ;; noalign: if there were two spaces at the end, this field
15351 ;; does not determine the width of the column.
15352 (if noalign (setq org-table-may-need-update c)))
15353 (backward-delete-char N)
15354 (org-fix-tags-on-the-fly)))
15356 (defun org-delete-char (N)
15357 "Like `delete-char', but insert whitespace at field end in tables.
15358 When deleting characters, in tables this function will insert whitespace in
15359 front of the next \"|\" separator, to keep the table aligned. The table will
15360 still be marked for re-alignment if the field did fill the entire column,
15361 because, in this case the deletion might narrow the column."
15362 (interactive "p")
15363 (if (and (org-table-p)
15364 (not (bolp))
15365 (not (= (char-after) ?|))
15366 (eq N 1))
15367 (if (looking-at ".*?|")
15368 (let ((pos (point))
15369 (noalign (looking-at "[^|\n\r]* |"))
15370 (c org-table-may-need-update))
15371 (replace-match (concat
15372 (substring (match-string 0) 1 -1)
15373 " |"))
15374 (goto-char pos)
15375 ;; noalign: if there were two spaces at the end, this field
15376 ;; does not determine the width of the column.
15377 (if noalign (setq org-table-may-need-update c)))
15378 (delete-char N))
15379 (delete-char N)
15380 (org-fix-tags-on-the-fly)))
15382 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15383 (put 'org-self-insert-command 'delete-selection t)
15384 (put 'orgtbl-self-insert-command 'delete-selection t)
15385 (put 'org-delete-char 'delete-selection 'supersede)
15386 (put 'org-delete-backward-char 'delete-selection 'supersede)
15387 (put 'org-yank 'delete-selection 'yank)
15389 ;; Make `flyspell-mode' delay after some commands
15390 (put 'org-self-insert-command 'flyspell-delayed t)
15391 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15392 (put 'org-delete-char 'flyspell-delayed t)
15393 (put 'org-delete-backward-char 'flyspell-delayed t)
15395 ;; Make pabbrev-mode expand after org-mode commands
15396 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15397 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15399 ;; How to do this: Measure non-white length of current string
15400 ;; If equal to column width, we should realign.
15402 (defun org-remap (map &rest commands)
15403 "In MAP, remap the functions given in COMMANDS.
15404 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15405 (let (new old)
15406 (while commands
15407 (setq old (pop commands) new (pop commands))
15408 (if (fboundp 'command-remapping)
15409 (org-defkey map (vector 'remap old) new)
15410 (substitute-key-definition old new map global-map)))))
15412 (when (eq org-enable-table-editor 'optimized)
15413 ;; If the user wants maximum table support, we need to hijack
15414 ;; some standard editing functions
15415 (org-remap org-mode-map
15416 'self-insert-command 'org-self-insert-command
15417 'delete-char 'org-delete-char
15418 'delete-backward-char 'org-delete-backward-char)
15419 (org-defkey org-mode-map "|" 'org-force-self-insert))
15421 (defvar org-ctrl-c-ctrl-c-hook nil
15422 "Hook for functions attaching themselves to `C-c C-c'.
15423 This can be used to add additional functionality to the C-c C-c key which
15424 executes context-dependent commands.
15425 Each function will be called with no arguments. The function must check
15426 if the context is appropriate for it to act. If yes, it should do its
15427 thing and then return a non-nil value. If the context is wrong,
15428 just do nothing and return nil.")
15430 (defvar org-tab-first-hook nil
15431 "Hook for functions to attach themselves to TAB.
15432 See `org-ctrl-c-ctrl-c-hook' for more information.
15433 This hook runs as the first action when TAB is pressed, even before
15434 `org-cycle' messes around with the `outline-regexp' to cater for
15435 inline tasks and plain list item folding.
15436 If any function in this hook returns t, not other actions like table
15437 field motion visibility cycling will be done.")
15439 (defvar org-tab-after-check-for-table-hook nil
15440 "Hook for functions to attach themselves to TAB.
15441 See `org-ctrl-c-ctrl-c-hook' for more information.
15442 This hook runs after it has been established that the cursor is not in a
15443 table, but before checking if the cursor is in a headline or if global cycling
15444 should be done.
15445 If any function in this hook returns t, not other actions like visibility
15446 cycling will be done.")
15448 (defvar org-tab-after-check-for-cycling-hook nil
15449 "Hook for functions to attach themselves to TAB.
15450 See `org-ctrl-c-ctrl-c-hook' for more information.
15451 This hook runs after it has been established that not table field motion and
15452 not visibility should be done because of current context. This is probably
15453 the place where a package like yasnippets can hook in.")
15455 (defvar org-tab-before-tab-emulation-hook nil
15456 "Hook for functions to attach themselves to TAB.
15457 See `org-ctrl-c-ctrl-c-hook' for more information.
15458 This hook runs after every other options for TAB have been exhausted, but
15459 before indentation and \t insertion takes place.")
15461 (defvar org-metaleft-hook nil
15462 "Hook for functions attaching themselves to `M-left'.
15463 See `org-ctrl-c-ctrl-c-hook' for more information.")
15464 (defvar org-metaright-hook nil
15465 "Hook for functions attaching themselves to `M-right'.
15466 See `org-ctrl-c-ctrl-c-hook' for more information.")
15467 (defvar org-metaup-hook nil
15468 "Hook for functions attaching themselves to `M-up'.
15469 See `org-ctrl-c-ctrl-c-hook' for more information.")
15470 (defvar org-metadown-hook nil
15471 "Hook for functions attaching themselves to `M-down'.
15472 See `org-ctrl-c-ctrl-c-hook' for more information.")
15473 (defvar org-shiftmetaleft-hook nil
15474 "Hook for functions attaching themselves to `M-S-left'.
15475 See `org-ctrl-c-ctrl-c-hook' for more information.")
15476 (defvar org-shiftmetaright-hook nil
15477 "Hook for functions attaching themselves to `M-S-right'.
15478 See `org-ctrl-c-ctrl-c-hook' for more information.")
15479 (defvar org-shiftmetaup-hook nil
15480 "Hook for functions attaching themselves to `M-S-up'.
15481 See `org-ctrl-c-ctrl-c-hook' for more information.")
15482 (defvar org-shiftmetadown-hook nil
15483 "Hook for functions attaching themselves to `M-S-down'.
15484 See `org-ctrl-c-ctrl-c-hook' for more information.")
15485 (defvar org-metareturn-hook nil
15486 "Hook for functions attaching themselves to `M-RET'.
15487 See `org-ctrl-c-ctrl-c-hook' for more information.")
15489 (defun org-modifier-cursor-error ()
15490 "Throw an error, a modified cursor command was applied in wrong context."
15491 (error "This command is active in special context like tables, headlines or items"))
15493 (defun org-shiftselect-error ()
15494 "Throw an error because Shift-Cursor command was applied in wrong context."
15495 (if (and (boundp 'shift-select-mode) shift-select-mode)
15496 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15497 (error "This command works only in special context like headlines or timestamps")))
15499 (defun org-call-for-shift-select (cmd)
15500 (let ((this-command-keys-shift-translated t))
15501 (call-interactively cmd)))
15503 (defun org-shifttab (&optional arg)
15504 "Global visibility cycling or move to previous table field.
15505 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15506 on context.
15507 See the individual commands for more information."
15508 (interactive "P")
15509 (cond
15510 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15511 ((integerp arg)
15512 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15513 (message "Content view to level: %d" arg)
15514 (org-content (prefix-numeric-value arg2))
15515 (setq org-cycle-global-status 'overview)))
15516 (t (call-interactively 'org-global-cycle))))
15518 (defun org-shiftmetaleft ()
15519 "Promote subtree or delete table column.
15520 Calls `org-promote-subtree', `org-outdent-item',
15521 or `org-table-delete-column', depending on context.
15522 See the individual commands for more information."
15523 (interactive)
15524 (cond
15525 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15526 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15527 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15528 ((org-at-item-p) (call-interactively 'org-outdent-item))
15529 (t (org-modifier-cursor-error))))
15531 (defun org-shiftmetaright ()
15532 "Demote subtree or insert table column.
15533 Calls `org-demote-subtree', `org-indent-item',
15534 or `org-table-insert-column', depending on context.
15535 See the individual commands for more information."
15536 (interactive)
15537 (cond
15538 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15539 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15540 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15541 ((org-at-item-p) (call-interactively 'org-indent-item))
15542 (t (org-modifier-cursor-error))))
15544 (defun org-shiftmetaup (&optional arg)
15545 "Move subtree up or kill table row.
15546 Calls `org-move-subtree-up' or `org-table-kill-row' or
15547 `org-move-item-up' depending on context. See the individual commands
15548 for more information."
15549 (interactive "P")
15550 (cond
15551 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15552 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15553 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15554 ((org-at-item-p) (call-interactively 'org-move-item-up))
15555 (t (org-modifier-cursor-error))))
15557 (defun org-shiftmetadown (&optional arg)
15558 "Move subtree down or insert table row.
15559 Calls `org-move-subtree-down' or `org-table-insert-row' or
15560 `org-move-item-down', depending on context. See the individual
15561 commands for more information."
15562 (interactive "P")
15563 (cond
15564 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15565 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15566 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15567 ((org-at-item-p) (call-interactively 'org-move-item-down))
15568 (t (org-modifier-cursor-error))))
15570 (defun org-metaleft (&optional arg)
15571 "Promote heading or move table column to left.
15572 Calls `org-do-promote' or `org-table-move-column', depending on context.
15573 With no specific context, calls the Emacs default `backward-word'.
15574 See the individual commands for more information."
15575 (interactive "P")
15576 (cond
15577 ((run-hook-with-args-until-success 'org-metaleft-hook))
15578 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15579 ((or (org-on-heading-p)
15580 (and (org-region-active-p)
15581 (save-excursion
15582 (goto-char (region-beginning))
15583 (org-on-heading-p))))
15584 (call-interactively 'org-do-promote))
15585 ((or (org-at-item-p)
15586 (and (org-region-active-p)
15587 (save-excursion
15588 (goto-char (region-beginning))
15589 (org-at-item-p))))
15590 (call-interactively 'org-outdent-item))
15591 (t (call-interactively 'backward-word))))
15593 (defun org-metaright (&optional arg)
15594 "Demote subtree or move table column to right.
15595 Calls `org-do-demote' or `org-table-move-column', depending on context.
15596 With no specific context, calls the Emacs default `forward-word'.
15597 See the individual commands for more information."
15598 (interactive "P")
15599 (cond
15600 ((run-hook-with-args-until-success 'org-metaright-hook))
15601 ((org-at-table-p) (call-interactively 'org-table-move-column))
15602 ((or (org-on-heading-p)
15603 (and (org-region-active-p)
15604 (save-excursion
15605 (goto-char (region-beginning))
15606 (org-on-heading-p))))
15607 (call-interactively 'org-do-demote))
15608 ((or (org-at-item-p)
15609 (and (org-region-active-p)
15610 (save-excursion
15611 (goto-char (region-beginning))
15612 (org-at-item-p))))
15613 (call-interactively 'org-indent-item))
15614 (t (call-interactively 'forward-word))))
15616 (defun org-metaup (&optional arg)
15617 "Move subtree up or move table row up.
15618 Calls `org-move-subtree-up' or `org-table-move-row' or
15619 `org-move-item-up', depending on context. See the individual commands
15620 for more information."
15621 (interactive "P")
15622 (cond
15623 ((run-hook-with-args-until-success 'org-metaup-hook))
15624 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15625 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15626 ((org-at-item-p) (call-interactively 'org-move-item-up))
15627 (t (transpose-lines 1) (beginning-of-line -1))))
15629 (defun org-metadown (&optional arg)
15630 "Move subtree down or move table row down.
15631 Calls `org-move-subtree-down' or `org-table-move-row' or
15632 `org-move-item-down', depending on context. See the individual
15633 commands for more information."
15634 (interactive "P")
15635 (cond
15636 ((run-hook-with-args-until-success 'org-metadown-hook))
15637 ((org-at-table-p) (call-interactively 'org-table-move-row))
15638 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15639 ((org-at-item-p) (call-interactively 'org-move-item-down))
15640 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15642 (defun org-shiftup (&optional arg)
15643 "Increase item in timestamp or increase priority of current headline.
15644 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15645 depending on context. See the individual commands for more information."
15646 (interactive "P")
15647 (cond
15648 ((and org-support-shift-select (org-region-active-p))
15649 (org-call-for-shift-select 'previous-line))
15650 ((org-at-timestamp-p t)
15651 (call-interactively (if org-edit-timestamp-down-means-later
15652 'org-timestamp-down 'org-timestamp-up)))
15653 ((and (not (eq org-support-shift-select 'always))
15654 org-enable-priority-commands
15655 (org-on-heading-p))
15656 (call-interactively 'org-priority-up))
15657 ((and (not org-support-shift-select) (org-at-item-p))
15658 (call-interactively 'org-previous-item))
15659 ((org-clocktable-try-shift 'up arg))
15660 (org-support-shift-select
15661 (org-call-for-shift-select 'previous-line))
15662 (t (org-shiftselect-error))))
15664 (defun org-shiftdown (&optional arg)
15665 "Decrease item in timestamp or decrease priority of current headline.
15666 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15667 depending on context. See the individual commands for more information."
15668 (interactive "P")
15669 (cond
15670 ((and org-support-shift-select (org-region-active-p))
15671 (org-call-for-shift-select 'next-line))
15672 ((org-at-timestamp-p t)
15673 (call-interactively (if org-edit-timestamp-down-means-later
15674 'org-timestamp-up 'org-timestamp-down)))
15675 ((and (not (eq org-support-shift-select 'always))
15676 org-enable-priority-commands
15677 (org-on-heading-p))
15678 (call-interactively 'org-priority-down))
15679 ((and (not org-support-shift-select) (org-at-item-p))
15680 (call-interactively 'org-next-item))
15681 ((org-clocktable-try-shift 'down arg))
15682 (org-support-shift-select
15683 (org-call-for-shift-select 'next-line))
15684 (t (org-shiftselect-error))))
15686 (defun org-shiftright (&optional arg)
15687 "Cycle the thing at point or in the current line, depending on context.
15688 Depending on context, this does one of the following:
15690 - switch a timestamp at point one day into the future
15691 - on a headline, switch to the next TODO keyword.
15692 - on an item, switch entire list to the next bullet type
15693 - on a property line, switch to the next allowed value
15694 - on a clocktable definition line, move time block into the future"
15695 (interactive "P")
15696 (cond
15697 ((and org-support-shift-select (org-region-active-p))
15698 (org-call-for-shift-select 'forward-char))
15699 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15700 ((and (not (eq org-support-shift-select 'always))
15701 (org-on-heading-p))
15702 (let ((org-inhibit-logging
15703 (not org-treat-S-cursor-todo-selection-as-state-change))
15704 (org-inhibit-blocking
15705 (not org-treat-S-cursor-todo-selection-as-state-change)))
15706 (org-call-with-arg 'org-todo 'right)))
15707 ((or (and org-support-shift-select
15708 (not (eq org-support-shift-select 'always))
15709 (org-at-item-bullet-p))
15710 (and (not org-support-shift-select) (org-at-item-p)))
15711 (org-call-with-arg 'org-cycle-list-bullet nil))
15712 ((and (not (eq org-support-shift-select 'always))
15713 (org-at-property-p))
15714 (call-interactively 'org-property-next-allowed-value))
15715 ((org-clocktable-try-shift 'right arg))
15716 (org-support-shift-select
15717 (org-call-for-shift-select 'forward-char))
15718 (t (org-shiftselect-error))))
15720 (defun org-shiftleft (&optional arg)
15721 "Cycle the thing at point or in the current line, depending on context.
15722 Depending on context, this does one of the following:
15724 - switch a timestamp at point one day into the past
15725 - on a headline, switch to the previous TODO keyword.
15726 - on an item, switch entire list to the previous bullet type
15727 - on a property line, switch to the previous allowed value
15728 - on a clocktable definition line, move time block into the past"
15729 (interactive "P")
15730 (cond
15731 ((and org-support-shift-select (org-region-active-p))
15732 (org-call-for-shift-select 'backward-char))
15733 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15734 ((and (not (eq org-support-shift-select 'always))
15735 (org-on-heading-p))
15736 (let ((org-inhibit-logging
15737 (not org-treat-S-cursor-todo-selection-as-state-change))
15738 (org-inhibit-blocking
15739 (not org-treat-S-cursor-todo-selection-as-state-change)))
15740 (org-call-with-arg 'org-todo 'left)))
15741 ((or (and org-support-shift-select
15742 (not (eq org-support-shift-select 'always))
15743 (org-at-item-bullet-p))
15744 (and (not org-support-shift-select) (org-at-item-p)))
15745 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15746 ((and (not (eq org-support-shift-select 'always))
15747 (org-at-property-p))
15748 (call-interactively 'org-property-previous-allowed-value))
15749 ((org-clocktable-try-shift 'left arg))
15750 (org-support-shift-select
15751 (org-call-for-shift-select 'backward-char))
15752 (t (org-shiftselect-error))))
15754 (defun org-shiftcontrolright ()
15755 "Switch to next TODO set."
15756 (interactive)
15757 (cond
15758 ((and org-support-shift-select (org-region-active-p))
15759 (org-call-for-shift-select 'forward-word))
15760 ((and (not (eq org-support-shift-select 'always))
15761 (org-on-heading-p))
15762 (org-call-with-arg 'org-todo 'nextset))
15763 (org-support-shift-select
15764 (org-call-for-shift-select 'forward-word))
15765 (t (org-shiftselect-error))))
15767 (defun org-shiftcontrolleft ()
15768 "Switch to previous TODO set."
15769 (interactive)
15770 (cond
15771 ((and org-support-shift-select (org-region-active-p))
15772 (org-call-for-shift-select 'backward-word))
15773 ((and (not (eq org-support-shift-select 'always))
15774 (org-on-heading-p))
15775 (org-call-with-arg 'org-todo 'previousset))
15776 (org-support-shift-select
15777 (org-call-for-shift-select 'backward-word))
15778 (t (org-shiftselect-error))))
15780 (defun org-ctrl-c-ret ()
15781 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15782 (interactive)
15783 (cond
15784 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15785 (t (call-interactively 'org-insert-heading))))
15787 (defun org-copy-special ()
15788 "Copy region in table or copy current subtree.
15789 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15790 See the individual commands for more information."
15791 (interactive)
15792 (call-interactively
15793 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15795 (defun org-cut-special ()
15796 "Cut region in table or cut current subtree.
15797 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15798 See the individual commands for more information."
15799 (interactive)
15800 (call-interactively
15801 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15803 (defun org-paste-special (arg)
15804 "Paste rectangular region into table, or past subtree relative to level.
15805 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15806 See the individual commands for more information."
15807 (interactive "P")
15808 (if (org-at-table-p)
15809 (org-table-paste-rectangle)
15810 (org-paste-subtree arg)))
15812 (defun org-edit-special ()
15813 "Call a special editor for the stuff at point.
15814 When at a table, call the formula editor with `org-table-edit-formulas'.
15815 When at the first line of an src example, call `org-edit-src-code'.
15816 When in an #+include line, visit the include file. Otherwise call
15817 `ffap' to visit the file at point."
15818 (interactive)
15819 (cond
15820 ((org-at-table-p)
15821 (call-interactively 'org-table-edit-formulas))
15822 ((save-excursion
15823 (beginning-of-line 1)
15824 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15825 (find-file (org-trim (match-string 1))))
15826 ((org-edit-src-code))
15827 ((org-edit-fixed-width-region))
15828 (t (call-interactively 'ffap))))
15831 (defun org-ctrl-c-ctrl-c (&optional arg)
15832 "Set tags in headline, or update according to changed information at point.
15834 This command does many different things, depending on context:
15836 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15837 this is what we do.
15839 - If the cursor is on a statistics cookie, update it.
15841 - If the cursor is in a headline, prompt for tags and insert them
15842 into the current line, aligned to `org-tags-column'. When called
15843 with prefix arg, realign all tags in the current buffer.
15845 - If the cursor is in one of the special #+KEYWORD lines, this
15846 triggers scanning the buffer for these lines and updating the
15847 information.
15849 - If the cursor is inside a table, realign the table. This command
15850 works even if the automatic table editor has been turned off.
15852 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15853 the entire table.
15855 - If the cursor is at a footnote reference or definition, jump to
15856 the corresponding definition or references, respectively.
15858 - If the cursor is a the beginning of a dynamic block, update it.
15860 - If the cursor is inside a table created by the table.el package,
15861 activate that table.
15863 - If the current buffer is a remember buffer, close note and file
15864 it. A prefix argument of 1 files to the default location
15865 without further interaction. A prefix argument of 2 files to
15866 the currently clocking task.
15868 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15869 links in this buffer.
15871 - If the cursor is on a numbered item in a plain list, renumber the
15872 ordered list.
15874 - If the cursor is on a checkbox, toggle it."
15875 (interactive "P")
15876 (let ((org-enable-table-editor t))
15877 (cond
15878 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15879 org-occur-highlights
15880 org-latex-fragment-image-overlays)
15881 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15882 (org-remove-occur-highlights)
15883 (org-remove-latex-fragment-image-overlays)
15884 (message "Temporary highlights/overlays removed from current buffer"))
15885 ((and (local-variable-p 'org-finish-function (current-buffer))
15886 (fboundp org-finish-function))
15887 (funcall org-finish-function))
15888 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15889 ((org-at-property-p)
15890 (call-interactively 'org-property-action))
15891 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15892 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15893 (or (org-on-heading-p) (org-at-item-p)))
15894 (call-interactively 'org-update-statistics-cookies))
15895 ((org-on-heading-p) (call-interactively 'org-set-tags))
15896 ((org-at-table.el-p)
15897 (require 'table)
15898 (beginning-of-line 1)
15899 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15900 (call-interactively 'table-recognize-table))
15901 ((org-at-table-p)
15902 (org-table-maybe-eval-formula)
15903 (if arg
15904 (call-interactively 'org-table-recalculate)
15905 (org-table-maybe-recalculate-line))
15906 (call-interactively 'org-table-align))
15907 ((or (org-footnote-at-reference-p)
15908 (org-footnote-at-definition-p))
15909 (call-interactively 'org-footnote-action))
15910 ((org-at-item-checkbox-p)
15911 (call-interactively 'org-toggle-checkbox))
15912 ((org-at-item-p)
15913 (if arg
15914 (call-interactively 'org-toggle-checkbox)
15915 (call-interactively 'org-maybe-renumber-ordered-list)))
15916 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15917 ;; Dynamic block
15918 (beginning-of-line 1)
15919 (save-excursion (org-update-dblock)))
15920 ((save-excursion
15921 (beginning-of-line 1)
15922 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15923 (cond
15924 ((equal (match-string 1) "TBLFM")
15925 ;; Recalculate the table before this line
15926 (save-excursion
15927 (beginning-of-line 1)
15928 (skip-chars-backward " \r\n\t")
15929 (if (org-at-table-p)
15930 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15932 (let ((org-inhibit-startup-visibility-stuff t)
15933 (org-startup-align-all-tables nil))
15934 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15935 (message "Local setup has been refreshed"))))
15936 ((org-clock-update-time-maybe))
15937 (t (error "C-c C-c can do nothing useful at this location")))))
15939 (defun org-mode-restart ()
15940 "Restart Org-mode, to scan again for special lines.
15941 Also updates the keyword regular expressions."
15942 (interactive)
15943 (org-mode)
15944 (message "Org-mode restarted"))
15946 (defun org-kill-note-or-show-branches ()
15947 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15948 (interactive)
15949 (if (not org-finish-function)
15950 (call-interactively 'show-branches)
15951 (let ((org-note-abort t))
15952 (funcall org-finish-function))))
15954 (defun org-return (&optional indent)
15955 "Goto next table row or insert a newline.
15956 Calls `org-table-next-row' or `newline', depending on context.
15957 See the individual commands for more information."
15958 (interactive)
15959 (cond
15960 ((bobp) (if indent (newline-and-indent) (newline)))
15961 ((org-at-table-p)
15962 (org-table-justify-field-maybe)
15963 (call-interactively 'org-table-next-row))
15964 ((and org-return-follows-link
15965 (eq (get-text-property (point) 'face) 'org-link))
15966 (call-interactively 'org-open-at-point))
15967 ((and (org-at-heading-p)
15968 (looking-at
15969 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15970 (org-show-entry)
15971 (end-of-line 1)
15972 (newline))
15973 (t (if indent (newline-and-indent) (newline)))))
15975 (defun org-return-indent ()
15976 "Goto next table row or insert a newline and indent.
15977 Calls `org-table-next-row' or `newline-and-indent', depending on
15978 context. See the individual commands for more information."
15979 (interactive)
15980 (org-return t))
15982 (defun org-ctrl-c-star ()
15983 "Compute table, or change heading status of lines.
15984 Calls `org-table-recalculate' or `org-toggle-heading',
15985 depending on context."
15986 (interactive)
15987 (cond
15988 ((org-at-table-p)
15989 (call-interactively 'org-table-recalculate))
15991 ;; Convert all lines in region to list items
15992 (call-interactively 'org-toggle-heading))))
15994 (defun org-ctrl-c-minus ()
15995 "Insert separator line in table or modify bullet status of line.
15996 Also turns a plain line or a region of lines into list items.
15997 Calls `org-table-insert-hline', `org-toggle-item', or
15998 `org-cycle-list-bullet', depending on context."
15999 (interactive)
16000 (cond
16001 ((org-at-table-p)
16002 (call-interactively 'org-table-insert-hline))
16003 ((org-region-active-p)
16004 (call-interactively 'org-toggle-item))
16005 ((org-in-item-p)
16006 (call-interactively 'org-cycle-list-bullet))
16008 (call-interactively 'org-toggle-item))))
16010 (defun org-toggle-item ()
16011 "Convert headings or normal lines to items, items to normal lines.
16012 If there is no active region, only the current line is considered.
16014 If the first line in the region is a headline, convert all headlines to items.
16016 If the first line in the region is an item, convert all items to normal lines.
16018 If the first line is normal text, add an item bullet to each line."
16019 (interactive)
16020 (let (l2 l beg end)
16021 (if (org-region-active-p)
16022 (setq beg (region-beginning) end (region-end))
16023 (setq beg (point-at-bol)
16024 end (min (1+ (point-at-eol)) (point-max))))
16025 (save-excursion
16026 (goto-char end)
16027 (setq l2 (org-current-line))
16028 (goto-char beg)
16029 (beginning-of-line 1)
16030 (setq l (1- (org-current-line)))
16031 (if (org-at-item-p)
16032 ;; We already have items, de-itemize
16033 (while (< (setq l (1+ l)) l2)
16034 (when (org-at-item-p)
16035 (goto-char (match-beginning 2))
16036 (delete-region (match-beginning 2) (match-end 2))
16037 (and (looking-at "[ \t]+") (replace-match "")))
16038 (beginning-of-line 2))
16039 (if (org-on-heading-p)
16040 ;; Headings, convert to items
16041 (while (< (setq l (1+ l)) l2)
16042 (if (looking-at org-outline-regexp)
16043 (replace-match "- " t t))
16044 (beginning-of-line 2))
16045 ;; normal lines, turn them into items
16046 (while (< (setq l (1+ l)) l2)
16047 (unless (org-at-item-p)
16048 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16049 (replace-match "\\1- \\2")))
16050 (beginning-of-line 2)))))))
16052 (defun org-toggle-heading (&optional nstars)
16053 "Convert headings to normal text, or items or text to headings.
16054 If there is no active region, only the current line is considered.
16056 If the first line is a heading, remove the stars from all headlines
16057 in the region.
16059 If the first line is a plain list item, turn all plain list items
16060 into headings.
16062 If the first line is a normal line, turn each and every line in the
16063 region into a heading.
16065 When converting a line into a heading, the number of stars is chosen
16066 such that the lines become children of the current entry. However,
16067 when a prefix argument is given, its value determines the number of
16068 stars to add."
16069 (interactive "P")
16070 (let (l2 l itemp beg end)
16071 (if (org-region-active-p)
16072 (setq beg (region-beginning) end (region-end))
16073 (setq beg (point-at-bol)
16074 end (min (1+ (point-at-eol)) (point-max))))
16075 (save-excursion
16076 (goto-char end)
16077 (setq l2 (org-current-line))
16078 (goto-char beg)
16079 (beginning-of-line 1)
16080 (setq l (1- (org-current-line)))
16081 (if (org-on-heading-p)
16082 ;; We already have headlines, de-star them
16083 (while (< (setq l (1+ l)) l2)
16084 (when (org-on-heading-p t)
16085 (and (looking-at outline-regexp) (replace-match "")))
16086 (beginning-of-line 2))
16087 (setq itemp (org-at-item-p))
16088 (let* ((stars
16089 (if nstars
16090 (make-string (prefix-numeric-value current-prefix-arg)
16092 (save-excursion
16093 (if (re-search-backward org-complex-heading-regexp nil t)
16094 (match-string 1) ""))))
16095 (add-stars (cond (nstars "")
16096 ((equal stars "") "*")
16097 (org-odd-levels-only "**")
16098 (t "*")))
16099 (rpl (concat stars add-stars " ")))
16100 (while (< (setq l (1+ l)) l2)
16101 (if itemp
16102 (and (org-at-item-p) (replace-match rpl t t))
16103 (unless (org-on-heading-p)
16104 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16105 (replace-match (concat rpl (match-string 2))))))
16106 (beginning-of-line 2)))))))
16108 (defun org-meta-return (&optional arg)
16109 "Insert a new heading or wrap a region in a table.
16110 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16111 See the individual commands for more information."
16112 (interactive "P")
16113 (cond
16114 ((run-hook-with-args-until-success 'org-metareturn-hook))
16115 ((org-at-table-p)
16116 (call-interactively 'org-table-wrap-region))
16117 (t (call-interactively 'org-insert-heading))))
16119 ;;; Menu entries
16121 ;; Define the Org-mode menus
16122 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16123 '("Tbl"
16124 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16125 ["Next Field" org-cycle (org-at-table-p)]
16126 ["Previous Field" org-shifttab (org-at-table-p)]
16127 ["Next Row" org-return (org-at-table-p)]
16128 "--"
16129 ["Blank Field" org-table-blank-field (org-at-table-p)]
16130 ["Edit Field" org-table-edit-field (org-at-table-p)]
16131 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16132 "--"
16133 ("Column"
16134 ["Move Column Left" org-metaleft (org-at-table-p)]
16135 ["Move Column Right" org-metaright (org-at-table-p)]
16136 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16137 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16138 ("Row"
16139 ["Move Row Up" org-metaup (org-at-table-p)]
16140 ["Move Row Down" org-metadown (org-at-table-p)]
16141 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16142 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16143 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16144 "--"
16145 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16146 ("Rectangle"
16147 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16148 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16149 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16150 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16151 "--"
16152 ("Calculate"
16153 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16154 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16155 ["Edit Formulas" org-edit-special (org-at-table-p)]
16156 "--"
16157 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16158 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16159 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16160 "--"
16161 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16162 "--"
16163 ["Sum Column/Rectangle" org-table-sum
16164 (or (org-at-table-p) (org-region-active-p))]
16165 ["Which Column?" org-table-current-column (org-at-table-p)])
16166 ["Debug Formulas"
16167 org-table-toggle-formula-debugger
16168 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16169 ["Show Col/Row Numbers"
16170 org-table-toggle-coordinate-overlays
16171 :style toggle
16172 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16173 "--"
16174 ["Create" org-table-create (and (not (org-at-table-p))
16175 org-enable-table-editor)]
16176 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16177 ["Import from File" org-table-import (not (org-at-table-p))]
16178 ["Export to File" org-table-export (org-at-table-p)]
16179 "--"
16180 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16182 (easy-menu-define org-org-menu org-mode-map "Org menu"
16183 '("Org"
16184 ("Show/Hide"
16185 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16186 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16187 ["Sparse Tree..." org-sparse-tree t]
16188 ["Reveal Context" org-reveal t]
16189 ["Show All" show-all t]
16190 "--"
16191 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16192 "--"
16193 ["New Heading" org-insert-heading t]
16194 ("Navigate Headings"
16195 ["Up" outline-up-heading t]
16196 ["Next" outline-next-visible-heading t]
16197 ["Previous" outline-previous-visible-heading t]
16198 ["Next Same Level" outline-forward-same-level t]
16199 ["Previous Same Level" outline-backward-same-level t]
16200 "--"
16201 ["Jump" org-goto t])
16202 ("Edit Structure"
16203 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16204 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16205 "--"
16206 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16207 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16208 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16209 "--"
16210 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16211 "--"
16212 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16213 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16214 ["Demote Heading" org-metaright (not (org-at-table-p))]
16215 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16216 "--"
16217 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16218 "--"
16219 ["Convert to odd levels" org-convert-to-odd-levels t]
16220 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16221 ("Editing"
16222 ["Emphasis..." org-emphasize t]
16223 ["Edit Source Example" org-edit-special t]
16224 "--"
16225 ["Footnote new/jump" org-footnote-action t]
16226 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16227 ("Archive"
16228 ["Archive (default method)" org-archive-subtree-default t]
16229 "--"
16230 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16231 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16232 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16234 "--"
16235 ("Hyperlinks"
16236 ["Store Link (Global)" org-store-link t]
16237 ["Find existing link to here" org-occur-link-in-agenda-files t]
16238 ["Insert Link" org-insert-link t]
16239 ["Follow Link" org-open-at-point t]
16240 "--"
16241 ["Next link" org-next-link t]
16242 ["Previous link" org-previous-link t]
16243 "--"
16244 ["Descriptive Links"
16245 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16246 :style radio
16247 :selected (member '(org-link) buffer-invisibility-spec)]
16248 ["Literal Links"
16249 (progn
16250 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16251 :style radio
16252 :selected (not (member '(org-link) buffer-invisibility-spec))])
16253 "--"
16254 ("TODO Lists"
16255 ["TODO/DONE/-" org-todo t]
16256 ("Select keyword"
16257 ["Next keyword" org-shiftright (org-on-heading-p)]
16258 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16259 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16260 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16261 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16262 ["Show TODO Tree" org-show-todo-tree t]
16263 ["Global TODO list" org-todo-list t]
16264 "--"
16265 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16266 :selected org-enforce-todo-dependencies :style toggle :active t]
16267 "Settings for tree at point"
16268 ["Do Children sequentially" org-toggle-ordered-property :style radio
16269 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16270 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16271 ["Do Children parallel" org-toggle-ordered-property :style radio
16272 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16273 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16274 "--"
16275 ["Set Priority" org-priority t]
16276 ["Priority Up" org-shiftup t]
16277 ["Priority Down" org-shiftdown t]
16278 "--"
16279 ["Get news from all feeds" org-feed-update-all t]
16280 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16281 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16282 ("TAGS and Properties"
16283 ["Set Tags" org-set-tags-command t]
16284 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16285 "--"
16286 ["Set property" org-set-property t]
16287 ["Column view of properties" org-columns t]
16288 ["Insert Column View DBlock" org-insert-columns-dblock t])
16289 ("Dates and Scheduling"
16290 ["Timestamp" org-time-stamp t]
16291 ["Timestamp (inactive)" org-time-stamp-inactive t]
16292 ("Change Date"
16293 ["1 Day Later" org-shiftright t]
16294 ["1 Day Earlier" org-shiftleft t]
16295 ["1 ... Later" org-shiftup t]
16296 ["1 ... Earlier" org-shiftdown t])
16297 ["Compute Time Range" org-evaluate-time-range t]
16298 ["Schedule Item" org-schedule t]
16299 ["Deadline" org-deadline t]
16300 "--"
16301 ["Custom time format" org-toggle-time-stamp-overlays
16302 :style radio :selected org-display-custom-times]
16303 "--"
16304 ["Goto Calendar" org-goto-calendar t]
16305 ["Date from Calendar" org-date-from-calendar t]
16306 "--"
16307 ["Start/Restart Timer" org-timer-start t]
16308 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16309 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16310 ["Insert Timer String" org-timer t]
16311 ["Insert Timer Item" org-timer-item t])
16312 ("Logging work"
16313 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16314 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16315 ["Clock out" org-clock-out t]
16316 ["Clock cancel" org-clock-cancel t]
16317 "--"
16318 ["Mark as default task" org-clock-mark-default-task t]
16319 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16320 ["Goto running clock" org-clock-goto t]
16321 "--"
16322 ["Display times" org-clock-display t]
16323 ["Create clock table" org-clock-report t]
16324 "--"
16325 ["Record DONE time"
16326 (progn (setq org-log-done (not org-log-done))
16327 (message "Switching to %s will %s record a timestamp"
16328 (car org-done-keywords)
16329 (if org-log-done "automatically" "not")))
16330 :style toggle :selected org-log-done])
16331 "--"
16332 ["Agenda Command..." org-agenda t]
16333 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16334 ("File List for Agenda")
16335 ("Special views current file"
16336 ["TODO Tree" org-show-todo-tree t]
16337 ["Check Deadlines" org-check-deadlines t]
16338 ["Timeline" org-timeline t]
16339 ["Tags/Property tree" org-match-sparse-tree t])
16340 "--"
16341 ["Export/Publish..." org-export t]
16342 ("LaTeX"
16343 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16344 :selected org-cdlatex-mode]
16345 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16346 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16347 ["Modify math symbol" org-cdlatex-math-modify
16348 (org-inside-LaTeX-fragment-p)]
16349 ["Insert citation" org-reftex-citation t]
16350 "--"
16351 ["Export LaTeX fragments as images"
16352 (if (featurep 'org-exp)
16353 (setq org-export-with-LaTeX-fragments
16354 (not org-export-with-LaTeX-fragments))
16355 (require 'org-exp))
16356 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16357 org-export-with-LaTeX-fragments)]
16358 "--"
16359 ["Template for BEAMER" org-beamer-settings-template t])
16360 "--"
16361 ("MobileOrg"
16362 ["Push Files and Views" org-mobile-push t]
16363 ["Get Captured and Flagged" org-mobile-pull t]
16364 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16365 "--"
16366 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16367 "--"
16368 ("Documentation"
16369 ["Show Version" org-version t]
16370 ["Info Documentation" org-info t])
16371 ("Customize"
16372 ["Browse Org Group" org-customize t]
16373 "--"
16374 ["Expand This Menu" org-create-customize-menu
16375 (fboundp 'customize-menu-create)])
16376 ["Send bug report" org-submit-bug-report t]
16377 "--"
16378 ("Refresh/Reload"
16379 ["Refresh setup current buffer" org-mode-restart t]
16380 ["Reload Org (after update)" org-reload t]
16381 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16384 (defun org-info (&optional node)
16385 "Read documentation for Org-mode in the info system.
16386 With optional NODE, go directly to that node."
16387 (interactive)
16388 (info (format "(org)%s" (or node ""))))
16390 ;;;###autoload
16391 (defun org-submit-bug-report ()
16392 "Submit a bug report on Org-mode via mail.
16394 Don't hesitate to report any problems or inaccurate documentation.
16396 If you don't have setup sending mail from (X)Emacs, please copy the
16397 output buffer into your mail program, as it gives us important
16398 information about your Org-mode version and configuration."
16399 (interactive)
16400 (require 'reporter)
16401 (org-load-modules-maybe)
16402 (org-require-autoloaded-modules)
16403 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16404 (reporter-submit-bug-report
16405 "emacs-orgmode@gnu.org"
16406 (org-version)
16407 (let (list)
16408 (save-window-excursion
16409 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16410 (delete-other-windows)
16411 (erase-buffer)
16412 (insert "You are about to submit a bug report to the Org-mode mailing list.
16414 We would like to add your full Org-mode and Outline configuration to the
16415 bug report. This greatly simplifies the work of the maintainer and
16416 other experts on the mailing list.
16418 HOWEVER, some variables you have customized may contain private
16419 information. The names of customers, colleagues, or friends, might
16420 appear in the form of file names, tags, todo states, or search strings.
16421 If you answer yes to the prompt, you might want to check and remove
16422 such private information before sending the email.")
16423 (add-text-properties (point-min) (point-max) '(face org-warning))
16424 (when (yes-or-no-p "Include your Org-mode configuration ")
16425 (mapatoms
16426 (lambda (v)
16427 (and (boundp v)
16428 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16429 (or (and (symbol-value v)
16430 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16431 (and
16432 (get v 'custom-type) (get v 'standard-value)
16433 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16434 (push v list)))))
16435 (kill-buffer (get-buffer "*Warn about privacy*"))
16436 list))
16437 nil nil
16438 "Remember to cover the basics, that is, what you expected to happen and
16439 what in fact did happen. You don't know how to make a good report? See
16441 http://orgmode.org/manual/Feedback.html#Feedback
16443 Your bug report will be posted to the Org-mode mailing list.
16444 ------------------------------------------------------------------------")
16445 (save-excursion
16446 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16447 (replace-match "\\1Bug: \\3 [\\2]")))))
16450 (defun org-install-agenda-files-menu ()
16451 (let ((bl (buffer-list)))
16452 (save-excursion
16453 (while bl
16454 (set-buffer (pop bl))
16455 (if (org-mode-p) (setq bl nil)))
16456 (when (org-mode-p)
16457 (easy-menu-change
16458 '("Org") "File List for Agenda"
16459 (append
16460 (list
16461 ["Edit File List" (org-edit-agenda-file-list) t]
16462 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16463 ["Remove Current File from List" org-remove-file t]
16464 ["Cycle through agenda files" org-cycle-agenda-files t]
16465 ["Occur in all agenda files" org-occur-in-agenda-files t]
16466 "--")
16467 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16469 ;;;; Documentation
16471 ;;;###autoload
16472 (defun org-require-autoloaded-modules ()
16473 (interactive)
16474 (mapc 'require
16475 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16476 org-docbook org-exp org-html org-icalendar
16477 org-id org-latex
16478 org-publish org-remember org-table
16479 org-timer org-xoxo)))
16481 ;;;###autoload
16482 (defun org-reload (&optional uncompiled)
16483 "Reload all org lisp files.
16484 With prefix arg UNCOMPILED, load the uncompiled versions."
16485 (interactive "P")
16486 (require 'find-func)
16487 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16488 (dir-org (file-name-directory (org-find-library-name "org")))
16489 (dir-org-contrib (ignore-errors
16490 (file-name-directory
16491 (org-find-library-name "org-contribdir"))))
16492 (files
16493 (append (directory-files dir-org t file-re)
16494 (and dir-org-contrib
16495 (directory-files dir-org-contrib t file-re))))
16496 (remove-re (concat (if (featurep 'xemacs)
16497 "org-colview" "org-colview-xemacs")
16498 "\\'")))
16499 (setq files (mapcar 'file-name-sans-extension files))
16500 (setq files (mapcar
16501 (lambda (x) (if (string-match remove-re x) nil x))
16502 files))
16503 (setq files (delq nil files))
16504 (mapc
16505 (lambda (f)
16506 (when (featurep (intern (file-name-nondirectory f)))
16507 (if (and (not uncompiled)
16508 (file-exists-p (concat f ".elc")))
16509 (load (concat f ".elc") nil nil t)
16510 (load (concat f ".el") nil nil t))))
16511 files))
16512 (org-version))
16514 ;;;###autoload
16515 (defun org-customize ()
16516 "Call the customize function with org as argument."
16517 (interactive)
16518 (org-load-modules-maybe)
16519 (org-require-autoloaded-modules)
16520 (customize-browse 'org))
16522 (defun org-create-customize-menu ()
16523 "Create a full customization menu for Org-mode, insert it into the menu."
16524 (interactive)
16525 (org-load-modules-maybe)
16526 (org-require-autoloaded-modules)
16527 (if (fboundp 'customize-menu-create)
16528 (progn
16529 (easy-menu-change
16530 '("Org") "Customize"
16531 `(["Browse Org group" org-customize t]
16532 "--"
16533 ,(customize-menu-create 'org)
16534 ["Set" Custom-set t]
16535 ["Save" Custom-save t]
16536 ["Reset to Current" Custom-reset-current t]
16537 ["Reset to Saved" Custom-reset-saved t]
16538 ["Reset to Standard Settings" Custom-reset-standard t]))
16539 (message "\"Org\"-menu now contains full customization menu"))
16540 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16542 ;;;; Miscellaneous stuff
16544 ;;; Generally useful functions
16546 (defun org-get-at-bol (property)
16547 "Get text property PROPERTY at beginning of line."
16548 (get-text-property (point-at-bol) property))
16550 (defun org-find-text-property-in-string (prop s)
16551 "Return the first non-nil value of property PROP in string S."
16552 (or (get-text-property 0 prop s)
16553 (get-text-property (or (next-single-property-change 0 prop s) 0)
16554 prop s)))
16556 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16557 "Display the given MESSAGE as a warning."
16558 (if (fboundp 'display-warning)
16559 (display-warning 'org message
16560 (if (featurep 'xemacs)
16561 'warning
16562 :warning))
16563 (let ((buf (get-buffer-create "*Org warnings*")))
16564 (with-current-buffer buf
16565 (goto-char (point-max))
16566 (insert "Warning (Org): " message)
16567 (unless (bolp)
16568 (newline)))
16569 (display-buffer buf)
16570 (sit-for 0))))
16572 (defun org-in-commented-line ()
16573 "Is point in a line starting with `#'?"
16574 (equal (char-after (point-at-bol)) ?#))
16576 (defun org-in-verbatim-emphasis ()
16577 (save-match-data
16578 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16580 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16581 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16582 (if (and marker (marker-buffer marker)
16583 (buffer-live-p (marker-buffer marker)))
16584 (progn
16585 (switch-to-buffer (marker-buffer marker))
16586 (if (or (> marker (point-max)) (< marker (point-min)))
16587 (widen))
16588 (goto-char marker)
16589 (org-show-context 'org-goto))
16590 (if bookmark
16591 (bookmark-jump bookmark)
16592 (error "Cannot find location"))))
16594 (defun org-quote-csv-field (s)
16595 "Quote field for inclusion in CSV material."
16596 (if (string-match "[\",]" s)
16597 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16600 (defun org-plist-delete (plist property)
16601 "Delete PROPERTY from PLIST.
16602 This is in contrast to merely setting it to 0."
16603 (let (p)
16604 (while plist
16605 (if (not (eq property (car plist)))
16606 (setq p (plist-put p (car plist) (nth 1 plist))))
16607 (setq plist (cddr plist)))
16610 (defun org-force-self-insert (N)
16611 "Needed to enforce self-insert under remapping."
16612 (interactive "p")
16613 (self-insert-command N))
16615 (defun org-string-width (s)
16616 "Compute width of string, ignoring invisible characters.
16617 This ignores character with invisibility property `org-link', and also
16618 characters with property `org-cwidth', because these will become invisible
16619 upon the next fontification round."
16620 (let (b l)
16621 (when (or (eq t buffer-invisibility-spec)
16622 (assq 'org-link buffer-invisibility-spec))
16623 (while (setq b (text-property-any 0 (length s)
16624 'invisible 'org-link s))
16625 (setq s (concat (substring s 0 b)
16626 (substring s (or (next-single-property-change
16627 b 'invisible s) (length s)))))))
16628 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16629 (setq s (concat (substring s 0 b)
16630 (substring s (or (next-single-property-change
16631 b 'org-cwidth s) (length s))))))
16632 (setq l (string-width s) b -1)
16633 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16634 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16637 (defun org-get-indentation (&optional line)
16638 "Get the indentation of the current line, interpreting tabs.
16639 When LINE is given, assume it represents a line and compute its indentation."
16640 (if line
16641 (if (string-match "^ *" (org-remove-tabs line))
16642 (match-end 0))
16643 (save-excursion
16644 (beginning-of-line 1)
16645 (skip-chars-forward " \t")
16646 (current-column))))
16648 (defun org-remove-tabs (s &optional width)
16649 "Replace tabulators in S with spaces.
16650 Assumes that s is a single line, starting in column 0."
16651 (setq width (or width tab-width))
16652 (while (string-match "\t" s)
16653 (setq s (replace-match
16654 (make-string
16655 (- (* width (/ (+ (match-beginning 0) width) width))
16656 (match-beginning 0)) ?\ )
16657 t t s)))
16660 (defun org-fix-indentation (line ind)
16661 "Fix indentation in LINE.
16662 IND is a cons cell with target and minimum indentation.
16663 If the current indentation in LINE is smaller than the minimum,
16664 leave it alone. If it is larger than ind, set it to the target."
16665 (let* ((l (org-remove-tabs line))
16666 (i (org-get-indentation l))
16667 (i1 (car ind)) (i2 (cdr ind)))
16668 (if (>= i i2) (setq l (substring line i2)))
16669 (if (> i1 0)
16670 (concat (make-string i1 ?\ ) l)
16671 l)))
16673 (defun org-remove-indentation (code &optional n)
16674 "Remove the maximum common indentation from the lines in CODE.
16675 N may optionally be the number of spaces to remove."
16676 (with-temp-buffer
16677 (insert code)
16678 (org-do-remove-indentation n)
16679 (buffer-string)))
16681 (defun org-do-remove-indentation (&optional n)
16682 "Remove the maximum common indentation from the buffer."
16683 (untabify (point-min) (point-max))
16684 (let ((min 10000) re)
16685 (if n
16686 (setq min n)
16687 (goto-char (point-min))
16688 (while (re-search-forward "^ *[^ \n]" nil t)
16689 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16690 (unless (or (= min 0) (= min 10000))
16691 (setq re (format "^ \\{%d\\}" min))
16692 (goto-char (point-min))
16693 (while (re-search-forward re nil t)
16694 (replace-match "")
16695 (end-of-line 1))
16696 min)))
16698 (defun org-fill-template (template alist)
16699 "Find each %key of ALIST in TEMPLATE and replace it."
16700 (let ((case-fold-search nil)
16701 entry key value)
16702 (setq alist (sort (copy-sequence alist)
16703 (lambda (a b) (< (length (car a)) (length (car b))))))
16704 (while (setq entry (pop alist))
16705 (setq template
16706 (replace-regexp-in-string
16707 (concat "%" (regexp-quote (car entry)))
16708 (cdr entry) template t t)))
16709 template))
16711 (defun org-base-buffer (buffer)
16712 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16713 (if (not buffer)
16714 buffer
16715 (or (buffer-base-buffer buffer)
16716 buffer)))
16718 (defun org-trim (s)
16719 "Remove whitespace at beginning and end of string."
16720 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16721 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16724 (defun org-wrap (string &optional width lines)
16725 "Wrap string to either a number of lines, or a width in characters.
16726 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16727 that costs. If there is a word longer than WIDTH, the text is actually
16728 wrapped to the length of that word.
16729 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16730 many lines, whatever width that takes.
16731 The return value is a list of lines, without newlines at the end."
16732 (let* ((words (org-split-string string "[ \t\n]+"))
16733 (maxword (apply 'max (mapcar 'org-string-width words)))
16734 w ll)
16735 (cond (width
16736 (org-do-wrap words (max maxword width)))
16737 (lines
16738 (setq w maxword)
16739 (setq ll (org-do-wrap words maxword))
16740 (if (<= (length ll) lines)
16742 (setq ll words)
16743 (while (> (length ll) lines)
16744 (setq w (1+ w))
16745 (setq ll (org-do-wrap words w)))
16746 ll))
16747 (t (error "Cannot wrap this")))))
16749 (defun org-do-wrap (words width)
16750 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16751 (let (lines line)
16752 (while words
16753 (setq line (pop words))
16754 (while (and words (< (+ (length line) (length (car words))) width))
16755 (setq line (concat line " " (pop words))))
16756 (setq lines (push line lines)))
16757 (nreverse lines)))
16759 (defun org-split-string (string &optional separators)
16760 "Splits STRING into substrings at SEPARATORS.
16761 No empty strings are returned if there are matches at the beginning
16762 and end of string."
16763 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16764 (start 0)
16765 notfirst
16766 (list nil))
16767 (while (and (string-match rexp string
16768 (if (and notfirst
16769 (= start (match-beginning 0))
16770 (< start (length string)))
16771 (1+ start) start))
16772 (< (match-beginning 0) (length string)))
16773 (setq notfirst t)
16774 (or (eq (match-beginning 0) 0)
16775 (and (eq (match-beginning 0) (match-end 0))
16776 (eq (match-beginning 0) start))
16777 (setq list
16778 (cons (substring string start (match-beginning 0))
16779 list)))
16780 (setq start (match-end 0)))
16781 (or (eq start (length string))
16782 (setq list
16783 (cons (substring string start)
16784 list)))
16785 (nreverse list)))
16787 (defun org-quote-vert (s)
16788 "Replace \"|\" with \"\\vert\"."
16789 (while (string-match "|" s)
16790 (setq s (replace-match "\\vert" t t s)))
16793 (defun org-uuidgen-p (s)
16794 "Is S an ID created by UUIDGEN?"
16795 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16797 (defun org-context ()
16798 "Return a list of contexts of the current cursor position.
16799 If several contexts apply, all are returned.
16800 Each context entry is a list with a symbol naming the context, and
16801 two positions indicating start and end of the context. Possible
16802 contexts are:
16804 :headline anywhere in a headline
16805 :headline-stars on the leading stars in a headline
16806 :todo-keyword on a TODO keyword (including DONE) in a headline
16807 :tags on the TAGS in a headline
16808 :priority on the priority cookie in a headline
16809 :item on the first line of a plain list item
16810 :item-bullet on the bullet/number of a plain list item
16811 :checkbox on the checkbox in a plain list item
16812 :table in an org-mode table
16813 :table-special on a special filed in a table
16814 :table-table in a table.el table
16815 :link on a hyperlink
16816 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16817 :target on a <<target>>
16818 :radio-target on a <<<radio-target>>>
16819 :latex-fragment on a LaTeX fragment
16820 :latex-preview on a LaTeX fragment with overlayed preview image
16822 This function expects the position to be visible because it uses font-lock
16823 faces as a help to recognize the following contexts: :table-special, :link,
16824 and :keyword."
16825 (let* ((f (get-text-property (point) 'face))
16826 (faces (if (listp f) f (list f)))
16827 (p (point)) clist o)
16828 ;; First the large context
16829 (cond
16830 ((org-on-heading-p t)
16831 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16832 (when (progn
16833 (beginning-of-line 1)
16834 (looking-at org-todo-line-tags-regexp))
16835 (push (org-point-in-group p 1 :headline-stars) clist)
16836 (push (org-point-in-group p 2 :todo-keyword) clist)
16837 (push (org-point-in-group p 4 :tags) clist))
16838 (goto-char p)
16839 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16840 (if (looking-at "\\[#[A-Z0-9]\\]")
16841 (push (org-point-in-group p 0 :priority) clist)))
16843 ((org-at-item-p)
16844 (push (org-point-in-group p 2 :item-bullet) clist)
16845 (push (list :item (point-at-bol)
16846 (save-excursion (org-end-of-item) (point)))
16847 clist)
16848 (and (org-at-item-checkbox-p)
16849 (push (org-point-in-group p 0 :checkbox) clist)))
16851 ((org-at-table-p)
16852 (push (list :table (org-table-begin) (org-table-end)) clist)
16853 (if (memq 'org-formula faces)
16854 (push (list :table-special
16855 (previous-single-property-change p 'face)
16856 (next-single-property-change p 'face)) clist)))
16857 ((org-at-table-p 'any)
16858 (push (list :table-table) clist)))
16859 (goto-char p)
16861 ;; Now the small context
16862 (cond
16863 ((org-at-timestamp-p)
16864 (push (org-point-in-group p 0 :timestamp) clist))
16865 ((memq 'org-link faces)
16866 (push (list :link
16867 (previous-single-property-change p 'face)
16868 (next-single-property-change p 'face)) clist))
16869 ((memq 'org-special-keyword faces)
16870 (push (list :keyword
16871 (previous-single-property-change p 'face)
16872 (next-single-property-change p 'face)) clist))
16873 ((org-on-target-p)
16874 (push (org-point-in-group p 0 :target) clist)
16875 (goto-char (1- (match-beginning 0)))
16876 (if (looking-at org-radio-target-regexp)
16877 (push (org-point-in-group p 0 :radio-target) clist))
16878 (goto-char p))
16879 ((setq o (car (delq nil
16880 (mapcar
16881 (lambda (x)
16882 (if (memq x org-latex-fragment-image-overlays) x))
16883 (org-overlays-at (point))))))
16884 (push (list :latex-fragment
16885 (org-overlay-start o) (org-overlay-end o)) clist)
16886 (push (list :latex-preview
16887 (org-overlay-start o) (org-overlay-end o)) clist))
16888 ((org-inside-LaTeX-fragment-p)
16889 ;; FIXME: positions wrong.
16890 (push (list :latex-fragment (point) (point)) clist)))
16892 (setq clist (nreverse (delq nil clist)))
16893 clist))
16895 ;; FIXME: Compare with at-regexp-p Do we need both?
16896 (defun org-in-regexp (re &optional nlines visually)
16897 "Check if point is inside a match of regexp.
16898 Normally only the current line is checked, but you can include NLINES extra
16899 lines both before and after point into the search.
16900 If VISUALLY is set, require that the cursor is not after the match but
16901 really on, so that the block visually is on the match."
16902 (catch 'exit
16903 (let ((pos (point))
16904 (eol (point-at-eol (+ 1 (or nlines 0))))
16905 (inc (if visually 1 0)))
16906 (save-excursion
16907 (beginning-of-line (- 1 (or nlines 0)))
16908 (while (re-search-forward re eol t)
16909 (if (and (<= (match-beginning 0) pos)
16910 (>= (+ inc (match-end 0)) pos))
16911 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16913 (defun org-at-regexp-p (regexp)
16914 "Is point inside a match of REGEXP in the current line?"
16915 (catch 'exit
16916 (save-excursion
16917 (let ((pos (point)) (end (point-at-eol)))
16918 (beginning-of-line 1)
16919 (while (re-search-forward regexp end t)
16920 (if (and (<= (match-beginning 0) pos)
16921 (>= (match-end 0) pos))
16922 (throw 'exit t)))
16923 nil))))
16925 (defun org-occur-in-agenda-files (regexp &optional nlines)
16926 "Call `multi-occur' with buffers for all agenda files."
16927 (interactive "sOrg-files matching: \np")
16928 (let* ((files (org-agenda-files))
16929 (tnames (mapcar 'file-truename files))
16930 (extra org-agenda-text-search-extra-files)
16932 (when (eq (car extra) 'agenda-archives)
16933 (setq extra (cdr extra))
16934 (setq files (org-add-archive-files files)))
16935 (while (setq f (pop extra))
16936 (unless (member (file-truename f) tnames)
16937 (add-to-list 'files f 'append)
16938 (add-to-list 'tnames (file-truename f) 'append)))
16939 (multi-occur
16940 (mapcar (lambda (x)
16941 (with-current-buffer
16942 (or (get-file-buffer x) (find-file-noselect x))
16943 (widen)
16944 (current-buffer)))
16945 files)
16946 regexp)))
16948 (if (boundp 'occur-mode-find-occurrence-hook)
16949 ;; Emacs 23
16950 (add-hook 'occur-mode-find-occurrence-hook
16951 (lambda ()
16952 (when (org-mode-p)
16953 (org-reveal))))
16954 ;; Emacs 22
16955 (defadvice occur-mode-goto-occurrence
16956 (after org-occur-reveal activate)
16957 (and (org-mode-p) (org-reveal)))
16958 (defadvice occur-mode-goto-occurrence-other-window
16959 (after org-occur-reveal activate)
16960 (and (org-mode-p) (org-reveal)))
16961 (defadvice occur-mode-display-occurrence
16962 (after org-occur-reveal activate)
16963 (when (org-mode-p)
16964 (let ((pos (occur-mode-find-occurrence)))
16965 (with-current-buffer (marker-buffer pos)
16966 (save-excursion
16967 (goto-char pos)
16968 (org-reveal)))))))
16970 (defun org-occur-link-in-agenda-files ()
16971 "Create a link and search for it in the agendas.
16972 The link is not stored in `org-stored-links', it is just created
16973 for the search purpose."
16974 (interactive)
16975 (let ((link (condition-case nil
16976 (org-store-link nil)
16977 (error "Unable to create a link to here"))))
16978 (org-occur-in-agenda-files (regexp-quote link))))
16980 (defun org-uniquify (list)
16981 "Remove duplicate elements from LIST."
16982 (let (res)
16983 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16984 res))
16986 (defun org-delete-all (elts list)
16987 "Remove all elements in ELTS from LIST."
16988 (while elts
16989 (setq list (delete (pop elts) list)))
16990 list)
16992 (defun org-back-over-empty-lines ()
16993 "Move backwards over whitespace, to the beginning of the first empty line.
16994 Returns the number of empty lines passed."
16995 (let ((pos (point)))
16996 (skip-chars-backward " \t\n\r")
16997 (beginning-of-line 2)
16998 (goto-char (min (point) pos))
16999 (count-lines (point) pos)))
17001 (defun org-skip-whitespace ()
17002 (skip-chars-forward " \t\n\r"))
17004 (defun org-point-in-group (point group &optional context)
17005 "Check if POINT is in match-group GROUP.
17006 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17007 match. If the match group does ot exist or point is not inside it,
17008 return nil."
17009 (and (match-beginning group)
17010 (>= point (match-beginning group))
17011 (<= point (match-end group))
17012 (if context
17013 (list context (match-beginning group) (match-end group))
17014 t)))
17016 (defun org-switch-to-buffer-other-window (&rest args)
17017 "Switch to buffer in a second window on the current frame.
17018 In particular, do not allow pop-up frames."
17019 (let (pop-up-frames special-display-buffer-names special-display-regexps
17020 special-display-function)
17021 (apply 'switch-to-buffer-other-window args)))
17023 (defun org-combine-plists (&rest plists)
17024 "Create a single property list from all plists in PLISTS.
17025 The process starts by copying the first list, and then setting properties
17026 from the other lists. Settings in the last list are the most significant
17027 ones and overrule settings in the other lists."
17028 (let ((rtn (copy-sequence (pop plists)))
17029 p v ls)
17030 (while plists
17031 (setq ls (pop plists))
17032 (while ls
17033 (setq p (pop ls) v (pop ls))
17034 (setq rtn (plist-put rtn p v))))
17035 rtn))
17037 (defun org-move-line-down (arg)
17038 "Move the current line down. With prefix argument, move it past ARG lines."
17039 (interactive "p")
17040 (let ((col (current-column))
17041 beg end pos)
17042 (beginning-of-line 1) (setq beg (point))
17043 (beginning-of-line 2) (setq end (point))
17044 (beginning-of-line (+ 1 arg))
17045 (setq pos (move-marker (make-marker) (point)))
17046 (insert (delete-and-extract-region beg end))
17047 (goto-char pos)
17048 (org-move-to-column col)))
17050 (defun org-move-line-up (arg)
17051 "Move the current line up. With prefix argument, move it past ARG lines."
17052 (interactive "p")
17053 (let ((col (current-column))
17054 beg end pos)
17055 (beginning-of-line 1) (setq beg (point))
17056 (beginning-of-line 2) (setq end (point))
17057 (beginning-of-line (- arg))
17058 (setq pos (move-marker (make-marker) (point)))
17059 (insert (delete-and-extract-region beg end))
17060 (goto-char pos)
17061 (org-move-to-column col)))
17063 (defun org-replace-escapes (string table)
17064 "Replace %-escapes in STRING with values in TABLE.
17065 TABLE is an association list with keys like \"%a\" and string values.
17066 The sequences in STRING may contain normal field width and padding information,
17067 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17068 so values can contain further %-escapes if they are define later in TABLE."
17069 (let ((case-fold-search nil)
17070 e re rpl)
17071 (while (setq e (pop table))
17072 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17073 (while (string-match re string)
17074 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17075 (cdr e)))
17076 (setq string (replace-match rpl t t string))))
17077 string))
17080 (defun org-sublist (list start end)
17081 "Return a section of LIST, from START to END.
17082 Counting starts at 1."
17083 (let (rtn (c start))
17084 (setq list (nthcdr (1- start) list))
17085 (while (and list (<= c end))
17086 (push (pop list) rtn)
17087 (setq c (1+ c)))
17088 (nreverse rtn)))
17090 (defun org-find-base-buffer-visiting (file)
17091 "Like `find-buffer-visiting' but always return the base buffer and
17092 not an indirect buffer."
17093 (let ((buf (or (get-file-buffer file)
17094 (find-buffer-visiting file))))
17095 (if buf
17096 (or (buffer-base-buffer buf) buf)
17097 nil)))
17099 (defun org-image-file-name-regexp (&optional extensions)
17100 "Return regexp matching the file names of images.
17101 If EXTENSIONS is given, only match these."
17102 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17103 (image-file-name-regexp)
17104 (let ((image-file-name-extensions
17105 (or extensions
17106 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17107 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17108 (concat "\\."
17109 (regexp-opt (nconc (mapcar 'upcase
17110 image-file-name-extensions)
17111 image-file-name-extensions)
17113 "\\'"))))
17115 (defun org-file-image-p (file &optional extensions)
17116 "Return non-nil if FILE is an image."
17117 (save-match-data
17118 (string-match (org-image-file-name-regexp extensions) file)))
17120 (defun org-get-cursor-date ()
17121 "Return the date at cursor in as a time.
17122 This works in the calendar and in the agenda, anywhere else it just
17123 returns the current time."
17124 (let (date day defd)
17125 (cond
17126 ((eq major-mode 'calendar-mode)
17127 (setq date (calendar-cursor-to-date)
17128 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17129 ((eq major-mode 'org-agenda-mode)
17130 (setq day (get-text-property (point) 'day))
17131 (if day
17132 (setq date (calendar-gregorian-from-absolute day)
17133 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17134 (nth 2 date))))))
17135 (or defd (current-time))))
17137 (defvar org-agenda-action-marker (make-marker)
17138 "Marker pointing to the entry for the next agenda action.")
17140 (defun org-mark-entry-for-agenda-action ()
17141 "Mark the current entry as target of an agenda action.
17142 Agenda actions are actions executed from the agenda with the key `k',
17143 which make use of the date at the cursor."
17144 (interactive)
17145 (move-marker org-agenda-action-marker
17146 (save-excursion (org-back-to-heading t) (point))
17147 (current-buffer))
17148 (message
17149 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17151 ;;; Paragraph filling stuff.
17152 ;; We want this to be just right, so use the full arsenal.
17154 (defun org-indent-line-function ()
17155 "Indent line like previous, but further if previous was headline or item."
17156 (interactive)
17157 (let* ((pos (point))
17158 (itemp (org-at-item-p))
17159 (case-fold-search t)
17160 (org-drawer-regexp (or org-drawer-regexp "\000"))
17161 column bpos bcol tpos tcol bullet btype bullet-type)
17162 ;; Find the previous relevant line
17163 (beginning-of-line 1)
17164 (cond
17165 ((looking-at "#") (setq column 0))
17166 ((looking-at "\\*+ ") (setq column 0))
17167 ((and (looking-at "[ \t]*:END:")
17168 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17169 (save-excursion
17170 (goto-char (1- (match-beginning 1)))
17171 (setq column (current-column))))
17172 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17173 (save-excursion
17174 (re-search-backward
17175 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17176 (setq column (org-get-indentation (match-string 0))))
17178 (beginning-of-line 0)
17179 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17180 (not (looking-at "[ \t]*:END:"))
17181 (not (looking-at org-drawer-regexp)))
17182 (beginning-of-line 0))
17183 (cond
17184 ((looking-at "\\*+[ \t]+")
17185 (if (not org-adapt-indentation)
17186 (setq column 0)
17187 (goto-char (match-end 0))
17188 (setq column (current-column))))
17189 ((looking-at org-drawer-regexp)
17190 (goto-char (1- (match-beginning 1)))
17191 (setq column (current-column)))
17192 ((looking-at "\\([ \t]*\\):END:")
17193 (goto-char (match-end 1))
17194 (setq column (current-column)))
17195 ((org-in-item-p)
17196 (org-beginning-of-item)
17197 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17198 (setq bpos (match-beginning 1) tpos (match-end 0)
17199 bcol (progn (goto-char bpos) (current-column))
17200 tcol (progn (goto-char tpos) (current-column))
17201 bullet (match-string 1)
17202 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17203 (if (> tcol (+ bcol org-description-max-indent))
17204 (setq tcol (+ bcol 5)))
17205 (if (not itemp)
17206 (setq column tcol)
17207 (goto-char pos)
17208 (beginning-of-line 1)
17209 (if (looking-at "\\S-")
17210 (progn
17211 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17212 (setq bullet (match-string 1)
17213 btype (if (string-match "[0-9]" bullet) "n" bullet))
17214 (setq column (if (equal btype bullet-type) bcol tcol)))
17215 (setq column (org-get-indentation)))))
17216 (t (setq column (org-get-indentation))))))
17217 (goto-char pos)
17218 (if (<= (current-column) (current-indentation))
17219 (org-indent-line-to column)
17220 (save-excursion (org-indent-line-to column)))
17221 (setq column (current-column))
17222 (beginning-of-line 1)
17223 (if (looking-at
17224 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17225 (replace-match (concat (match-string 1)
17226 (format org-property-format
17227 (match-string 2) (match-string 3)))
17228 t t))
17229 (org-move-to-column column)))
17231 (defun org-set-autofill-regexps ()
17232 (interactive)
17233 ;; In the paragraph separator we include headlines, because filling
17234 ;; text in a line directly attached to a headline would otherwise
17235 ;; fill the headline as well.
17236 (org-set-local 'comment-start-skip "^#+[ \t]*")
17237 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17238 ;; The paragraph starter includes hand-formatted lists.
17239 (org-set-local
17240 'paragraph-start
17241 (concat
17242 "\f" "\\|"
17243 "[ ]*$" "\\|"
17244 "\\*+ " "\\|"
17245 "[ \t]*#" "\\|"
17246 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17247 "[ \t]*[:|]" "\\|"
17248 "\\$\\$" "\\|"
17249 "\\\\\\(begin\\|end\\|[][]\\)"))
17250 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17251 ;; But only if the user has not turned off tables or fixed-width regions
17252 (org-set-local
17253 'auto-fill-inhibit-regexp
17254 (concat "\\*+ \\|#\\+"
17255 "\\|[ \t]*" org-keyword-time-regexp
17256 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17257 (concat
17258 "\\|[ \t]*["
17259 (if org-enable-table-editor "|" "")
17260 (if org-enable-fixed-width-editor ":" "")
17261 "]"))))
17262 ;; We use our own fill-paragraph function, to make sure that tables
17263 ;; and fixed-width regions are not wrapped. That function will pass
17264 ;; through to `fill-paragraph' when appropriate.
17265 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17266 ; Adaptive filling: To get full control, first make sure that
17267 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17268 (org-set-local 'adaptive-fill-regexp "\000")
17269 (org-set-local 'adaptive-fill-function
17270 'org-adaptive-fill-function)
17271 (org-set-local
17272 'align-mode-rules-list
17273 '((org-in-buffer-settings
17274 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17275 (modes . '(org-mode))))))
17277 (defun org-fill-paragraph (&optional justify)
17278 "Re-align a table, pass through to fill-paragraph if no table."
17279 (let ((table-p (org-at-table-p))
17280 (table.el-p (org-at-table.el-p)))
17281 (cond ((and (equal (char-after (point-at-bol)) ?*)
17282 (save-excursion (goto-char (point-at-bol))
17283 (looking-at outline-regexp)))
17284 t) ; skip headlines
17285 (table.el-p t) ; skip table.el tables
17286 (table-p (org-table-align) t) ; align org-mode tables
17287 (t nil)))) ; call paragraph-fill
17289 ;; For reference, this is the default value of adaptive-fill-regexp
17290 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17292 (defun org-adaptive-fill-function ()
17293 "Return a fill prefix for org-mode files.
17294 In particular, this makes sure hanging paragraphs for hand-formatted lists
17295 work correctly."
17296 (cond ((looking-at "#[ \t]+")
17297 (match-string 0))
17298 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17299 (save-excursion
17300 (if (> (match-end 1) (+ (match-beginning 1)
17301 org-description-max-indent))
17302 (goto-char (+ (match-beginning 1) 5))
17303 (goto-char (match-end 0)))
17304 (make-string (current-column) ?\ )))
17305 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17306 (save-excursion
17307 (goto-char (match-end 0))
17308 (make-string (current-column) ?\ )))
17309 (t nil)))
17311 ;;; Other stuff.
17313 (defun org-toggle-fixed-width-section (arg)
17314 "Toggle the fixed-width export.
17315 If there is no active region, the QUOTE keyword at the current headline is
17316 inserted or removed. When present, it causes the text between this headline
17317 and the next to be exported as fixed-width text, and unmodified.
17318 If there is an active region, this command adds or removes a colon as the
17319 first character of this line. If the first character of a line is a colon,
17320 this line is also exported in fixed-width font."
17321 (interactive "P")
17322 (let* ((cc 0)
17323 (regionp (org-region-active-p))
17324 (beg (if regionp (region-beginning) (point)))
17325 (end (if regionp (region-end)))
17326 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17327 (case-fold-search nil)
17328 (re "[ \t]*\\(: \\)")
17329 off)
17330 (if regionp
17331 (save-excursion
17332 (goto-char beg)
17333 (setq cc (current-column))
17334 (beginning-of-line 1)
17335 (setq off (looking-at re))
17336 (while (> nlines 0)
17337 (setq nlines (1- nlines))
17338 (beginning-of-line 1)
17339 (cond
17340 (arg
17341 (org-move-to-column cc t)
17342 (insert ": \n")
17343 (forward-line -1))
17344 ((and off (looking-at re))
17345 (replace-match "" t t nil 1))
17346 ((not off) (org-move-to-column cc t) (insert ": ")))
17347 (forward-line 1)))
17348 (save-excursion
17349 (org-back-to-heading)
17350 (if (looking-at (concat outline-regexp
17351 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17352 (replace-match "" t t nil 1)
17353 (if (looking-at outline-regexp)
17354 (progn
17355 (goto-char (match-end 0))
17356 (insert org-quote-string " "))))))))
17358 (defun org-reftex-citation ()
17359 "Use reftex-citation to insert a citation into the buffer.
17360 This looks for a line like
17362 #+BIBLIOGRAPHY: foo plain option:-d
17364 and derives from it that foo.bib is the bibliography file relevant
17365 for this document. It then installs the necessary environment for RefTeX
17366 to work in this buffer and calls `reftex-citation' to insert a citation
17367 into the buffer.
17369 Export of such citations to both LaTeX and HTML is handled by the contributed
17370 package org-exp-bibtex by Taru Karttunen."
17371 (interactive)
17372 (let ((reftex-docstruct-symbol 'rds)
17373 (reftex-cite-format "\\cite{%l}")
17374 rds bib)
17375 (save-excursion
17376 (save-restriction
17377 (widen)
17378 (let ((case-fold-search t)
17379 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17380 (if (not (save-excursion
17381 (or (re-search-forward re nil t)
17382 (re-search-backward re nil t))))
17383 (error "No bibliography defined in file")
17384 (setq bib (concat (match-string 1) ".bib")
17385 rds (list (list 'bib bib)))))))
17386 (call-interactively 'reftex-citation)))
17388 ;;;; Functions extending outline functionality
17390 (defun org-beginning-of-line (&optional arg)
17391 "Go to the beginning of the current line. If that is invisible, continue
17392 to a visible line beginning. This makes the function of C-a more intuitive.
17393 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17394 first attempt, and only move to after the tags when the cursor is already
17395 beyond the end of the headline."
17396 (interactive "P")
17397 (let ((pos (point))
17398 (special (if (consp org-special-ctrl-a/e)
17399 (car org-special-ctrl-a/e)
17400 org-special-ctrl-a/e))
17401 refpos)
17402 (if (org-bound-and-true-p line-move-visual)
17403 (beginning-of-visual-line 1)
17404 (beginning-of-line 1))
17405 (if (and arg (fboundp 'move-beginning-of-line))
17406 (call-interactively 'move-beginning-of-line)
17407 (if (bobp)
17409 (backward-char 1)
17410 (if (org-invisible-p)
17411 (while (and (not (bobp)) (org-invisible-p))
17412 (backward-char 1)
17413 (beginning-of-line 1))
17414 (forward-char 1))))
17415 (when special
17416 (cond
17417 ((and (looking-at org-complex-heading-regexp)
17418 (= (char-after (match-end 1)) ?\ ))
17419 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17420 (point-at-eol)))
17421 (goto-char
17422 (if (eq special t)
17423 (cond ((> pos refpos) refpos)
17424 ((= pos (point)) refpos)
17425 (t (point)))
17426 (cond ((> pos (point)) (point))
17427 ((not (eq last-command this-command)) (point))
17428 (t refpos)))))
17429 ((org-at-item-p)
17430 (goto-char
17431 (if (eq special t)
17432 (cond ((> pos (match-end 4)) (match-end 4))
17433 ((= pos (point)) (match-end 4))
17434 (t (point)))
17435 (cond ((> pos (point)) (point))
17436 ((not (eq last-command this-command)) (point))
17437 (t (match-end 4))))))))
17438 (org-no-warnings
17439 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17441 (defun org-end-of-line (&optional arg)
17442 "Go to the end of the line.
17443 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17444 first attempt, and only move to after the tags when the cursor is already
17445 beyond the end of the headline."
17446 (interactive "P")
17447 (let ((special (if (consp org-special-ctrl-a/e)
17448 (cdr org-special-ctrl-a/e)
17449 org-special-ctrl-a/e)))
17450 (if (or (not special)
17451 (not (org-on-heading-p))
17452 arg)
17453 (call-interactively
17454 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17455 ((fboundp 'move-end-of-line) 'move-end-of-line)
17456 (t 'end-of-line)))
17457 (let ((pos (point)))
17458 (beginning-of-line 1)
17459 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17460 (if (eq special t)
17461 (if (or (< pos (match-beginning 1))
17462 (= pos (match-end 0)))
17463 (goto-char (match-beginning 1))
17464 (goto-char (match-end 0)))
17465 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17466 (goto-char (match-end 0))
17467 (goto-char (match-beginning 1))))
17468 (call-interactively (if (fboundp 'move-end-of-line)
17469 'move-end-of-line
17470 'end-of-line)))))
17471 (org-no-warnings
17472 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17474 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17475 (define-key org-mode-map "\C-e" 'org-end-of-line)
17476 (define-key org-mode-map [home] 'org-beginning-of-line)
17477 (define-key org-mode-map [end] 'org-end-of-line)
17479 (defun org-backward-sentence (&optional arg)
17480 "Go to beginning of sentence, or beginning of table field.
17481 This will call `backward-sentence' or `org-table-beginning-of-field',
17482 depending on context."
17483 (interactive "P")
17484 (cond
17485 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17486 (t (call-interactively 'backward-sentence))))
17488 (defun org-forward-sentence (&optional arg)
17489 "Go to end of sentence, or end of table field.
17490 This will call `forward-sentence' or `org-table-end-of-field',
17491 depending on context."
17492 (interactive "P")
17493 (cond
17494 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17495 (t (call-interactively 'forward-sentence))))
17497 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17498 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17500 (defun org-kill-line (&optional arg)
17501 "Kill line, to tags or end of line."
17502 (interactive "P")
17503 (cond
17504 ((or (not org-special-ctrl-k)
17505 (bolp)
17506 (not (org-on-heading-p)))
17507 (call-interactively 'kill-line))
17508 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17509 (kill-region (point) (match-beginning 1))
17510 (org-set-tags nil t))
17511 (t (kill-region (point) (point-at-eol)))))
17513 (define-key org-mode-map "\C-k" 'org-kill-line)
17515 (defun org-yank (&optional arg)
17516 "Yank. If the kill is a subtree, treat it specially.
17517 This command will look at the current kill and check if is a single
17518 subtree, or a series of subtrees[1]. If it passes the test, and if the
17519 cursor is at the beginning of a line or after the stars of a currently
17520 empty headline, then the yank is handled specially. How exactly depends
17521 on the value of the following variables, both set by default.
17523 org-yank-folded-subtrees
17524 When set, the subtree(s) will be folded after insertion, but only
17525 if doing so would now swallow text after the yanked text.
17527 org-yank-adjusted-subtrees
17528 When set, the subtree will be promoted or demoted in order to
17529 fit into the local outline tree structure, which means that the level
17530 will be adjusted so that it becomes the smaller one of the two
17531 *visible* surrounding headings.
17533 Any prefix to this command will cause `yank' to be called directly with
17534 no special treatment. In particular, a simple `C-u' prefix will just
17535 plainly yank the text as it is.
17537 \[1] The test checks if the first non-white line is a heading
17538 and if there are no other headings with fewer stars."
17539 (interactive "P")
17540 (org-yank-generic 'yank arg))
17542 (defun org-yank-generic (command arg)
17543 "Perform some yank-like command.
17545 This function implements the behavior described in the `org-yank'
17546 documentation. However, it has been generalized to work for any
17547 interactive command with similar behavior."
17549 ;; pretend to be command COMMAND
17550 (setq this-command command)
17552 (if arg
17553 (call-interactively command)
17555 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17556 (and (org-kill-is-subtree-p)
17557 (or (bolp)
17558 (and (looking-at "[ \t]*$")
17559 (string-match
17560 "\\`\\*+\\'"
17561 (buffer-substring (point-at-bol) (point)))))))
17562 swallowp)
17563 (cond
17564 ((and subtreep org-yank-folded-subtrees)
17565 (let ((beg (point))
17566 end)
17567 (if (and subtreep org-yank-adjusted-subtrees)
17568 (org-paste-subtree nil nil 'for-yank)
17569 (call-interactively command))
17571 (setq end (point))
17572 (goto-char beg)
17573 (when (and (bolp) subtreep
17574 (not (setq swallowp
17575 (org-yank-folding-would-swallow-text beg end))))
17576 (or (looking-at outline-regexp)
17577 (re-search-forward (concat "^" outline-regexp) end t))
17578 (while (and (< (point) end) (looking-at outline-regexp))
17579 (hide-subtree)
17580 (org-cycle-show-empty-lines 'folded)
17581 (condition-case nil
17582 (outline-forward-same-level 1)
17583 (error (goto-char end)))))
17584 (when swallowp
17585 (message
17586 "Inserted text not folded because that would swallow text"))
17588 (goto-char end)
17589 (skip-chars-forward " \t\n\r")
17590 (beginning-of-line 1)
17591 (push-mark beg 'nomsg)))
17592 ((and subtreep org-yank-adjusted-subtrees)
17593 (let ((beg (point-at-bol)))
17594 (org-paste-subtree nil nil 'for-yank)
17595 (push-mark beg 'nomsg)))
17597 (call-interactively command))))))
17599 (defun org-yank-folding-would-swallow-text (beg end)
17600 "Would hide-subtree at BEG swallow any text after END?"
17601 (let (level)
17602 (save-excursion
17603 (goto-char beg)
17604 (when (or (looking-at outline-regexp)
17605 (re-search-forward (concat "^" outline-regexp) end t))
17606 (setq level (org-outline-level)))
17607 (goto-char end)
17608 (skip-chars-forward " \t\r\n\v\f")
17609 (if (or (eobp)
17610 (and (bolp) (looking-at org-outline-regexp)
17611 (<= (org-outline-level) level)))
17612 nil ; Nothing would be swallowed
17613 t)))) ; something would swallow
17615 (define-key org-mode-map "\C-y" 'org-yank)
17617 (defun org-invisible-p ()
17618 "Check if point is at a character currently not visible."
17619 ;; Early versions of noutline don't have `outline-invisible-p'.
17620 (if (fboundp 'outline-invisible-p)
17621 (outline-invisible-p)
17622 (get-char-property (point) 'invisible)))
17624 (defun org-invisible-p2 ()
17625 "Check if point is at a character currently not visible."
17626 (save-excursion
17627 (if (and (eolp) (not (bobp))) (backward-char 1))
17628 ;; Early versions of noutline don't have `outline-invisible-p'.
17629 (if (fboundp 'outline-invisible-p)
17630 (outline-invisible-p)
17631 (get-char-property (point) 'invisible))))
17633 (defun org-back-to-heading (&optional invisible-ok)
17634 "Call `outline-back-to-heading', but provide a better error message."
17635 (condition-case nil
17636 (outline-back-to-heading invisible-ok)
17637 (error (error "Before first headline at position %d in buffer %s"
17638 (point) (current-buffer)))))
17640 (defun org-before-first-heading-p ()
17641 "Before first heading?"
17642 (save-excursion
17643 (null (re-search-backward "^\\*+ " nil t))))
17645 (defun org-on-heading-p (&optional ignored)
17646 (outline-on-heading-p t))
17647 (defun org-at-heading-p (&optional ignored)
17648 (outline-on-heading-p t))
17650 (defun org-at-heading-or-item-p ()
17651 (or (org-on-heading-p) (org-at-item-p)))
17653 (defun org-on-target-p ()
17654 (or (org-in-regexp org-radio-target-regexp)
17655 (org-in-regexp org-target-regexp)))
17657 (defun org-up-heading-all (arg)
17658 "Move to the heading line of which the present line is a subheading.
17659 This function considers both visible and invisible heading lines.
17660 With argument, move up ARG levels."
17661 (if (fboundp 'outline-up-heading-all)
17662 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17663 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17665 (defun org-up-heading-safe ()
17666 "Move to the heading line of which the present line is a subheading.
17667 This version will not throw an error. It will return the level of the
17668 headline found, or nil if no higher level is found.
17670 Also, this function will be a lot faster than `outline-up-heading',
17671 because it relies on stars being the outline starters. This can really
17672 make a significant difference in outlines with very many siblings."
17673 (let (start-level re)
17674 (org-back-to-heading t)
17675 (setq start-level (funcall outline-level))
17676 (if (equal start-level 1)
17678 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17679 (if (re-search-backward re nil t)
17680 (funcall outline-level)))))
17682 (defun org-first-sibling-p ()
17683 "Is this heading the first child of its parents?"
17684 (interactive)
17685 (let ((re (concat "^" outline-regexp))
17686 level l)
17687 (unless (org-at-heading-p t)
17688 (error "Not at a heading"))
17689 (setq level (funcall outline-level))
17690 (save-excursion
17691 (if (not (re-search-backward re nil t))
17693 (setq l (funcall outline-level))
17694 (< l level)))))
17696 (defun org-goto-sibling (&optional previous)
17697 "Goto the next sibling, even if it is invisible.
17698 When PREVIOUS is set, go to the previous sibling instead. Returns t
17699 when a sibling was found. When none is found, return nil and don't
17700 move point."
17701 (let ((fun (if previous 're-search-backward 're-search-forward))
17702 (pos (point))
17703 (re (concat "^" outline-regexp))
17704 level l)
17705 (when (condition-case nil (org-back-to-heading t) (error nil))
17706 (setq level (funcall outline-level))
17707 (catch 'exit
17708 (or previous (forward-char 1))
17709 (while (funcall fun re nil t)
17710 (setq l (funcall outline-level))
17711 (when (< l level) (goto-char pos) (throw 'exit nil))
17712 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17713 (goto-char pos)
17714 nil))))
17716 (defun org-show-siblings ()
17717 "Show all siblings of the current headline."
17718 (save-excursion
17719 (while (org-goto-sibling) (org-flag-heading nil)))
17720 (save-excursion
17721 (while (org-goto-sibling 'previous)
17722 (org-flag-heading nil))))
17724 (defun org-show-hidden-entry ()
17725 "Show an entry where even the heading is hidden."
17726 (save-excursion
17727 (org-show-entry)))
17729 (defun org-flag-heading (flag &optional entry)
17730 "Flag the current heading. FLAG non-nil means make invisible.
17731 When ENTRY is non-nil, show the entire entry."
17732 (save-excursion
17733 (org-back-to-heading t)
17734 ;; Check if we should show the entire entry
17735 (if entry
17736 (progn
17737 (org-show-entry)
17738 (save-excursion
17739 (and (outline-next-heading)
17740 (org-flag-heading nil))))
17741 (outline-flag-region (max (point-min) (1- (point)))
17742 (save-excursion (outline-end-of-heading) (point))
17743 flag))))
17745 (defun org-get-next-sibling ()
17746 "Move to next heading of the same level, and return point.
17747 If there is no such heading, return nil.
17748 This is like outline-next-sibling, but invisible headings are ok."
17749 (let ((level (funcall outline-level)))
17750 (outline-next-heading)
17751 (while (and (not (eobp)) (> (funcall outline-level) level))
17752 (outline-next-heading))
17753 (if (or (eobp) (< (funcall outline-level) level))
17755 (point))))
17757 (defun org-get-last-sibling ()
17758 "Move to previous heading of the same level, and return point.
17759 If there is no such heading, return nil."
17760 (let ((opoint (point))
17761 (level (funcall outline-level)))
17762 (outline-previous-heading)
17763 (when (and (/= (point) opoint) (outline-on-heading-p t))
17764 (while (and (> (funcall outline-level) level)
17765 (not (bobp)))
17766 (outline-previous-heading))
17767 (if (< (funcall outline-level) level)
17769 (point)))))
17771 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17772 ;; This contains an exact copy of the original function, but it uses
17773 ;; `org-back-to-heading', to make it work also in invisible
17774 ;; trees. And is uses an invisible-OK argument.
17775 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17776 ;; Furthermore, when used inside Org, finding the end of a large subtree
17777 ;; with many children and grandchildren etc, this can be much faster
17778 ;; than the outline version.
17779 (org-back-to-heading invisible-OK)
17780 (let ((first t)
17781 (level (funcall outline-level)))
17782 (if (and (org-mode-p) (< level 1000))
17783 ;; A true heading (not a plain list item), in Org-mode
17784 ;; This means we can easily find the end by looking
17785 ;; only for the right number of stars. Using a regexp to do
17786 ;; this is so much faster than using a Lisp loop.
17787 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17788 (forward-char 1)
17789 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17790 ;; something else, do it the slow way
17791 (while (and (not (eobp))
17792 (or first (> (funcall outline-level) level)))
17793 (setq first nil)
17794 (outline-next-heading)))
17795 (unless to-heading
17796 (if (memq (preceding-char) '(?\n ?\^M))
17797 (progn
17798 ;; Go to end of line before heading
17799 (forward-char -1)
17800 (if (memq (preceding-char) '(?\n ?\^M))
17801 ;; leave blank line before heading
17802 (forward-char -1))))))
17803 (point))
17805 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17806 "Use Org version in org-mode, for dramatic speed-up."
17807 (if (eq major-mode 'org-mode)
17808 (progn
17809 (org-end-of-subtree nil t)
17810 (unless (eobp) (backward-char 1)))
17811 ad-do-it))
17813 (defun org-forward-same-level (arg &optional invisible-ok)
17814 "Move forward to the arg'th subheading at same level as this one.
17815 Stop at the first and last subheadings of a superior heading."
17816 (interactive "p")
17817 (org-back-to-heading invisible-ok)
17818 (org-on-heading-p)
17819 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17820 (re (format "^\\*\\{1,%d\\} " level))
17822 (forward-char 1)
17823 (while (> arg 0)
17824 (while (and (re-search-forward re nil 'move)
17825 (setq l (- (match-end 0) (match-beginning 0) 1))
17826 (= l level)
17827 (not invisible-ok)
17828 (progn (backward-char 1) (org-invisible-p)))
17829 (if (< l level) (setq arg 1)))
17830 (setq arg (1- arg)))
17831 (beginning-of-line 1)))
17833 (defun org-backward-same-level (arg &optional invisible-ok)
17834 "Move backward to the arg'th subheading at same level as this one.
17835 Stop at the first and last subheadings of a superior heading."
17836 (interactive "p")
17837 (org-back-to-heading)
17838 (org-on-heading-p)
17839 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17840 (re (format "^\\*\\{1,%d\\} " level))
17842 (while (> arg 0)
17843 (while (and (re-search-backward re nil 'move)
17844 (setq l (- (match-end 0) (match-beginning 0) 1))
17845 (= l level)
17846 (not invisible-ok)
17847 (org-invisible-p))
17848 (if (< l level) (setq arg 1)))
17849 (setq arg (1- arg)))))
17851 (defun org-show-subtree ()
17852 "Show everything after this heading at deeper levels."
17853 (outline-flag-region
17854 (point)
17855 (save-excursion
17856 (org-end-of-subtree t t))
17857 nil))
17859 (defun org-show-entry ()
17860 "Show the body directly following this heading.
17861 Show the heading too, if it is currently invisible."
17862 (interactive)
17863 (save-excursion
17864 (condition-case nil
17865 (progn
17866 (org-back-to-heading t)
17867 (outline-flag-region
17868 (max (point-min) (1- (point)))
17869 (save-excursion
17870 (if (re-search-forward
17871 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17872 (match-beginning 1)
17873 (point-max)))
17874 nil)
17875 (org-cycle-hide-drawers 'children))
17876 (error nil))))
17878 (defun org-make-options-regexp (kwds &optional extra)
17879 "Make a regular expression for keyword lines."
17880 (concat
17882 "#?[ \t]*\\+\\("
17883 (mapconcat 'regexp-quote kwds "\\|")
17884 (if extra (concat "\\|" extra))
17885 "\\):[ \t]*"
17886 "\\(.*\\)"))
17888 ;; Make isearch reveal the necessary context
17889 (defun org-isearch-end ()
17890 "Reveal context after isearch exits."
17891 (when isearch-success ; only if search was successful
17892 (if (featurep 'xemacs)
17893 ;; Under XEmacs, the hook is run in the correct place,
17894 ;; we directly show the context.
17895 (org-show-context 'isearch)
17896 ;; In Emacs the hook runs *before* restoring the overlays.
17897 ;; So we have to use a one-time post-command-hook to do this.
17898 ;; (Emacs 22 has a special variable, see function `org-mode')
17899 (unless (and (boundp 'isearch-mode-end-hook-quit)
17900 isearch-mode-end-hook-quit)
17901 ;; Only when the isearch was not quitted.
17902 (org-add-hook 'post-command-hook 'org-isearch-post-command
17903 'append 'local)))))
17905 (defun org-isearch-post-command ()
17906 "Remove self from hook, and show context."
17907 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17908 (org-show-context 'isearch))
17911 ;;;; Integration with and fixes for other packages
17913 ;;; Imenu support
17915 (defvar org-imenu-markers nil
17916 "All markers currently used by Imenu.")
17917 (make-variable-buffer-local 'org-imenu-markers)
17919 (defun org-imenu-new-marker (&optional pos)
17920 "Return a new marker for use by Imenu, and remember the marker."
17921 (let ((m (make-marker)))
17922 (move-marker m (or pos (point)))
17923 (push m org-imenu-markers)
17926 (defun org-imenu-get-tree ()
17927 "Produce the index for Imenu."
17928 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17929 (setq org-imenu-markers nil)
17930 (let* ((n org-imenu-depth)
17931 (re (concat "^" outline-regexp))
17932 (subs (make-vector (1+ n) nil))
17933 (last-level 0)
17934 m level head)
17935 (save-excursion
17936 (save-restriction
17937 (widen)
17938 (goto-char (point-max))
17939 (while (re-search-backward re nil t)
17940 (setq level (org-reduced-level (funcall outline-level)))
17941 (when (<= level n)
17942 (looking-at org-complex-heading-regexp)
17943 (setq head (org-link-display-format
17944 (org-match-string-no-properties 4))
17945 m (org-imenu-new-marker))
17946 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17947 (if (>= level last-level)
17948 (push (cons head m) (aref subs level))
17949 (push (cons head (aref subs (1+ level))) (aref subs level))
17950 (loop for i from (1+ level) to n do (aset subs i nil)))
17951 (setq last-level level)))))
17952 (aref subs 1)))
17954 (eval-after-load "imenu"
17955 '(progn
17956 (add-hook 'imenu-after-jump-hook
17957 (lambda ()
17958 (if (eq major-mode 'org-mode)
17959 (org-show-context 'org-goto))))))
17961 (defun org-link-display-format (link)
17962 "Replace a link with either the description, or the link target
17963 if no description is present"
17964 (save-match-data
17965 (if (string-match org-bracket-link-analytic-regexp link)
17966 (replace-match (if (match-end 5)
17967 (match-string 5 link)
17968 (concat (match-string 1 link)
17969 (match-string 3 link)))
17970 nil t link)
17971 link)))
17973 ;; Speedbar support
17975 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17976 "Overlay marking the agenda restriction line in speedbar.")
17977 (org-overlay-put org-speedbar-restriction-lock-overlay
17978 'face 'org-agenda-restriction-lock)
17979 (org-overlay-put org-speedbar-restriction-lock-overlay
17980 'help-echo "Agendas are currently limited to this item.")
17981 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17983 (defun org-speedbar-set-agenda-restriction ()
17984 "Restrict future agenda commands to the location at point in speedbar.
17985 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17986 (interactive)
17987 (require 'org-agenda)
17988 (let (p m tp np dir txt)
17989 (cond
17990 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17991 'org-imenu t))
17992 (setq m (get-text-property p 'org-imenu-marker))
17993 (with-current-buffer (marker-buffer m)
17994 (goto-char m)
17995 (org-agenda-set-restriction-lock 'subtree)))
17996 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17997 'speedbar-function 'speedbar-find-file))
17998 (setq tp (previous-single-property-change
17999 (1+ p) 'speedbar-function)
18000 np (next-single-property-change
18001 tp 'speedbar-function)
18002 dir (speedbar-line-directory)
18003 txt (buffer-substring-no-properties (or tp (point-min))
18004 (or np (point-max))))
18005 (with-current-buffer (find-file-noselect
18006 (let ((default-directory dir))
18007 (expand-file-name txt)))
18008 (unless (org-mode-p)
18009 (error "Cannot restrict to non-Org-mode file"))
18010 (org-agenda-set-restriction-lock 'file)))
18011 (t (error "Don't know how to restrict Org-mode's agenda")))
18012 (org-move-overlay org-speedbar-restriction-lock-overlay
18013 (point-at-bol) (point-at-eol))
18014 (setq current-prefix-arg nil)
18015 (org-agenda-maybe-redo)))
18017 (eval-after-load "speedbar"
18018 '(progn
18019 (speedbar-add-supported-extension ".org")
18020 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18021 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18022 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18023 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18024 (add-hook 'speedbar-visiting-tag-hook
18025 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18028 ;;; Fixes and Hacks for problems with other packages
18030 ;; Make flyspell not check words in links, to not mess up our keymap
18031 (defun org-mode-flyspell-verify ()
18032 "Don't let flyspell put overlays at active buttons."
18033 (and (not (get-text-property (point) 'keymap))
18034 (not (get-text-property (point) 'org-no-flyspell))))
18036 (defun org-remove-flyspell-overlays-in (beg end)
18037 "Remove flyspell overlays in region."
18038 (and (org-bound-and-true-p flyspell-mode)
18039 (fboundp 'flyspell-delete-region-overlays)
18040 (flyspell-delete-region-overlays beg end))
18041 (add-text-properties beg end '(org-no-flyspell t)))
18043 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18044 (eval-after-load "bookmark"
18045 '(if (boundp 'bookmark-after-jump-hook)
18046 ;; We can use the hook
18047 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18048 ;; Hook not available, use advice
18049 (defadvice bookmark-jump (after org-make-visible activate)
18050 "Make the position visible."
18051 (org-bookmark-jump-unhide))))
18053 ;; Make sure saveplace shows the location if it was hidden
18054 (eval-after-load "saveplace"
18055 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18056 "Make the position visible."
18057 (org-bookmark-jump-unhide)))
18059 ;; Make sure ecb shows the location if it was hidden
18060 (eval-after-load "ecb"
18061 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18062 "Make hierarchy visible when jumping into location from ECB tree buffer."
18063 (if (eq major-mode 'org-mode)
18064 (org-show-context))))
18066 (defun org-bookmark-jump-unhide ()
18067 "Unhide the current position, to show the bookmark location."
18068 (and (org-mode-p)
18069 (or (org-invisible-p)
18070 (save-excursion (goto-char (max (point-min) (1- (point))))
18071 (org-invisible-p)))
18072 (org-show-context 'bookmark-jump)))
18074 ;; Make session.el ignore our circular variable
18075 (eval-after-load "session"
18076 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18078 ;;;; Experimental code
18080 (defun org-closed-in-range ()
18081 "Sparse tree of items closed in a certain time range.
18082 Still experimental, may disappear in the future."
18083 (interactive)
18084 ;; Get the time interval from the user.
18085 (let* ((time1 (org-float-time
18086 (org-read-date nil 'to-time nil "Starting date: ")))
18087 (time2 (org-float-time
18088 (org-read-date nil 'to-time nil "End date:")))
18089 ;; callback function
18090 (callback (lambda ()
18091 (let ((time
18092 (org-float-time
18093 (apply 'encode-time
18094 (org-parse-time-string
18095 (match-string 1))))))
18096 ;; check if time in interval
18097 (and (>= time time1) (<= time time2))))))
18098 ;; make tree, check each match with the callback
18099 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18101 ;;;; Finish up
18103 (provide 'org)
18105 (run-hooks 'org-load-hook)
18107 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18109 ;;; org.el ends here