outline-end-of-subtree: Bugfix.
[org-mode.git] / lisp / org.el
blobb58caccb554526287b25cab82e7e5e9c85ac41a9
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.30trans
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.30trans"
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* ((version org-version)
106 (git-version)
107 (dir (concat (file-name-directory (locate-library "org")) "../" )))
108 (if (and (file-exists-p (expand-file-name ".git" dir))
109 (executable-find "git"))
110 (let ((pwd (substring (pwd) 10)))
111 (cd dir)
112 (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
113 (save-excursion
114 (set-buffer "*Shell Command Output*")
115 (goto-char (point-min))
116 (re-search-forward "[^\n]+")
117 (setq git-version (match-string 0))
118 (subst-char-in-string ?- ?. git-version t)
119 (shell-command "git diff-index --name-only HEAD --")
120 (unless (eql 1 (point-max))
121 (setq git-version (concat git-version ".dirty")))
122 (setq version (concat version " (" git-version ")")))
123 (cd pwd))))
124 (setq version (format "Org-mode version %s" version))
125 (if here (insert version))
126 (message version)
127 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-load-hook nil
141 "Hook that is run after org.el has been loaded."
142 :group 'org
143 :type 'hook)
145 (defvar org-modules) ; defined below
146 (defvar org-modules-loaded nil
147 "Have the modules been loaded already?")
149 (defun org-load-modules-maybe (&optional force)
150 "Load all extensions listed in `org-modules'."
151 (when (or force (not org-modules-loaded))
152 (mapc (lambda (ext)
153 (condition-case nil (require ext)
154 (error (message "Problems while trying to load feature `%s'" ext))))
155 org-modules)
156 (setq org-modules-loaded t)))
158 (defun org-set-modules (var value)
159 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
160 (set var value)
161 (when (featurep 'org)
162 (org-load-modules-maybe 'force)))
164 (when (org-bound-and-true-p org-modules)
165 (let ((a (member 'org-infojs org-modules)))
166 (and a (setcar a 'org-jsinfo))))
168 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
169 "Modules that should always be loaded together with org.el.
170 If a description starts with <C>, the file is not part of Emacs
171 and loading it will require that you have downloaded and properly installed
172 the org-mode distribution.
174 You can also use this system to load external packages (i.e. neither Org
175 core modules, nor modules from the CONTRIB directory). Just add symbols
176 to the end of the list. If the package is called org-xyz.el, then you need
177 to add the symbol `xyz', and the package must have a call to
179 (provide 'org-xyz)"
180 :group 'org
181 :set 'org-set-modules
182 :type
183 '(set :greedy t
184 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
185 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
186 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
187 (const :tag " id: Global IDs for identifying entries" org-id)
188 (const :tag " info: Links to Info nodes" org-info)
189 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
190 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
191 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
192 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
193 (const :tag " mew Links to Mew folders/messages" org-mew)
194 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
195 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
196 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
197 (const :tag " vm: Links to VM folders/messages" org-vm)
198 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
199 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
200 (const :tag " mouse: Additional mouse support" org-mouse)
202 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
203 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
204 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
205 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
206 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
207 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
208 (const :tag "C collector: Collect properties into tables" org-collector)
209 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
210 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
211 (const :tag "C eval: Include command output as text" org-eval)
212 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
213 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
214 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
215 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
216 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
217 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
218 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
219 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
220 (const :tag "C mtags: Support for muse-like tags" org-mtags)
221 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
222 (const :tag "C R: Computation using the R language" org-R)
223 (const :tag "C registry: A registry for Org links" org-registry)
224 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
225 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
226 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
227 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
228 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
229 (const :tag "C track: Keep up with Org development" org-track)
230 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
232 (defcustom org-support-shift-select nil
233 "Non-nil means, make shift-cursor commands select text when possible.
235 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
236 selecting a region, or enlarge thusly regions started in this way.
237 In Org-mode, in special contexts, these same keys are used for other
238 purposes, important enough to compete with shift selection. Org tries
239 to balance these needs by supporting `shift-select-mode' outside these
240 special contexts, under control of this variable.
242 The default of this variable is nil, to avoid confusing behavior. Shifted
243 cursor keys will then execute Org commands in the following contexts:
244 - on a headline, changing TODO state (left/right) and priority (up/down)
245 - on a time stamp, changing the time
246 - in a plain list item, changing the bullet type
247 - in a property definition line, switching between allowed values
248 - in the BEGIN line of a clock table (changing the time block).
249 Outside these contexts, the commands will throw an error.
251 When this variable is t and the cursor is not in a special context,
252 Org-mode will support shift-selection for making and enlarging regions.
253 To make this more effective, the bullet cycling will no longer happen
254 anywhere in an item line, but only if the cursor is exactly on the bullet.
256 If you set this variable to the symbol `always', then the keys
257 will not be special in headlines, property lines, and item lines, to make
258 shift selection work there as well. If this is what you want, you can
259 use the following alternative commands: `C-c C-t' and `C-c ,' to
260 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
261 TODO sets, `C-c -' to cycle item bullet types, and properties can be
262 edited by hand or in column view.
264 However, when the cursor is on a timestamp, shift-cursor commands
265 will still edit the time stamp - this is just too good to give up.
267 XEmacs user should have this variable set to nil, because shift-select-mode
268 is Emacs 23 only."
269 :group 'org
270 :type '(choice
271 (const :tag "Never" nil)
272 (const :tag "When outside special context" t)
273 (const :tag "Everywhere except timestamps" always)))
275 (defgroup org-startup nil
276 "Options concerning startup of Org-mode."
277 :tag "Org Startup"
278 :group 'org)
280 (defcustom org-startup-folded t
281 "Non-nil means, entering Org-mode will switch to OVERVIEW.
282 This can also be configured on a per-file basis by adding one of
283 the following lines anywhere in the buffer:
285 #+STARTUP: fold
286 #+STARTUP: nofold
287 #+STARTUP: content"
288 :group 'org-startup
289 :type '(choice
290 (const :tag "nofold: show all" nil)
291 (const :tag "fold: overview" t)
292 (const :tag "content: all headlines" content)))
294 (defcustom org-startup-truncated t
295 "Non-nil means, entering Org-mode will set `truncate-lines'.
296 This is useful since some lines containing links can be very long and
297 uninteresting. Also tables look terrible when wrapped."
298 :group 'org-startup
299 :type 'boolean)
301 (defcustom org-startup-indented nil
302 "Non-nil means, turn on `org-indent-mode' on startup.
303 This can also be configured on a per-file basis by adding one of
304 the following lines anywhere in the buffer:
306 #+STARTUP: indent
307 #+STARTUP: noindent"
308 :group 'org-structure
309 :type '(choice
310 (const :tag "Not" nil)
311 (const :tag "Globally (slow on startup in large files)" t)))
313 (defcustom org-startup-align-all-tables nil
314 "Non-nil means, align all tables when visiting a file.
315 This is useful when the column width in tables is forced with <N> cookies
316 in table fields. Such tables will look correct only after the first re-align.
317 This can also be configured on a per-file basis by adding one of
318 the following lines anywhere in the buffer:
319 #+STARTUP: align
320 #+STARTUP: noalign"
321 :group 'org-startup
322 :type 'boolean)
324 (defcustom org-insert-mode-line-in-empty-file nil
325 "Non-nil means insert the first line setting Org-mode in empty files.
326 When the function `org-mode' is called interactively in an empty file, this
327 normally means that the file name does not automatically trigger Org-mode.
328 To ensure that the file will always be in Org-mode in the future, a
329 line enforcing Org-mode will be inserted into the buffer, if this option
330 has been set."
331 :group 'org-startup
332 :type 'boolean)
334 (defcustom org-replace-disputed-keys nil
335 "Non-nil means use alternative key bindings for some keys.
336 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
337 These keys are also used by other packages like shift-selection-mode'
338 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
339 If you want to use Org-mode together with one of these other modes,
340 or more generally if you would like to move some Org-mode commands to
341 other keys, set this variable and configure the keys with the variable
342 `org-disputed-keys'.
344 This option is only relevant at load-time of Org-mode, and must be set
345 *before* org.el is loaded. Changing it requires a restart of Emacs to
346 become effective."
347 :group 'org-startup
348 :type 'boolean)
350 (defcustom org-use-extra-keys nil
351 "Non-nil means use extra key sequence definitions for certain
352 commands. This happens automatically if you run XEmacs or if
353 window-system is nil. This variable lets you do the same
354 manually. You must set it before loading org.
356 Example: on Carbon Emacs 22 running graphically, with an external
357 keyboard on a Powerbook, the default way of setting M-left might
358 not work for either Alt or ESC. Setting this variable will make
359 it work for ESC."
360 :group 'org-startup
361 :type 'boolean)
363 (if (fboundp 'defvaralias)
364 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
366 (defcustom org-disputed-keys
367 '(([(shift up)] . [(meta p)])
368 ([(shift down)] . [(meta n)])
369 ([(shift left)] . [(meta -)])
370 ([(shift right)] . [(meta +)])
371 ([(control shift right)] . [(meta shift +)])
372 ([(control shift left)] . [(meta shift -)]))
373 "Keys for which Org-mode and other modes compete.
374 This is an alist, cars are the default keys, second element specifies
375 the alternative to use when `org-replace-disputed-keys' is t.
377 Keys can be specified in any syntax supported by `define-key'.
378 The value of this option takes effect only at Org-mode's startup,
379 therefore you'll have to restart Emacs to apply it after changing."
380 :group 'org-startup
381 :type 'alist)
383 (defun org-key (key)
384 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
385 Or return the original if not disputed."
386 (if org-replace-disputed-keys
387 (let* ((nkey (key-description key))
388 (x (org-find-if (lambda (x)
389 (equal (key-description (car x)) nkey))
390 org-disputed-keys)))
391 (if x (cdr x) key))
392 key))
394 (defun org-find-if (predicate seq)
395 (catch 'exit
396 (while seq
397 (if (funcall predicate (car seq))
398 (throw 'exit (car seq))
399 (pop seq)))))
401 (defun org-defkey (keymap key def)
402 "Define a key, possibly translated, as returned by `org-key'."
403 (define-key keymap (org-key key) def))
405 (defcustom org-ellipsis nil
406 "The ellipsis to use in the Org-mode outline.
407 When nil, just use the standard three dots. When a string, use that instead,
408 When a face, use the standard 3 dots, but with the specified face.
409 The change affects only Org-mode (which will then use its own display table).
410 Changing this requires executing `M-x org-mode' in a buffer to become
411 effective."
412 :group 'org-startup
413 :type '(choice (const :tag "Default" nil)
414 (face :tag "Face" :value org-warning)
415 (string :tag "String" :value "...#")))
417 (defvar org-display-table nil
418 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
420 (defgroup org-keywords nil
421 "Keywords in Org-mode."
422 :tag "Org Keywords"
423 :group 'org)
425 (defcustom org-deadline-string "DEADLINE:"
426 "String to mark deadline entries.
427 A deadline is this string, followed by a time stamp. Should be a word,
428 terminated by a colon. You can insert a schedule keyword and
429 a timestamp with \\[org-deadline].
430 Changes become only effective after restarting Emacs."
431 :group 'org-keywords
432 :type 'string)
434 (defcustom org-scheduled-string "SCHEDULED:"
435 "String to mark scheduled TODO entries.
436 A schedule is this string, followed by a time stamp. Should be a word,
437 terminated by a colon. You can insert a schedule keyword and
438 a timestamp with \\[org-schedule].
439 Changes become only effective after restarting Emacs."
440 :group 'org-keywords
441 :type 'string)
443 (defcustom org-closed-string "CLOSED:"
444 "String used as the prefix for timestamps logging closing a TODO entry."
445 :group 'org-keywords
446 :type 'string)
448 (defcustom org-clock-string "CLOCK:"
449 "String used as prefix for timestamps clocking work hours on an item."
450 :group 'org-keywords
451 :type 'string)
453 (defcustom org-comment-string "COMMENT"
454 "Entries starting with this keyword will never be exported.
455 An entry can be toggled between COMMENT and normal with
456 \\[org-toggle-comment].
457 Changes become only effective after restarting Emacs."
458 :group 'org-keywords
459 :type 'string)
461 (defcustom org-quote-string "QUOTE"
462 "Entries starting with this keyword will be exported in fixed-width font.
463 Quoting applies only to the text in the entry following the headline, and does
464 not extend beyond the next headline, even if that is lower level.
465 An entry can be toggled between QUOTE and normal with
466 \\[org-toggle-fixed-width-section]."
467 :group 'org-keywords
468 :type 'string)
470 (defconst org-repeat-re
471 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
472 "Regular expression for specifying repeated events.
473 After a match, group 1 contains the repeat expression.")
475 (defgroup org-structure nil
476 "Options concerning the general structure of Org-mode files."
477 :tag "Org Structure"
478 :group 'org)
480 (defgroup org-reveal-location nil
481 "Options about how to make context of a location visible."
482 :tag "Org Reveal Location"
483 :group 'org-structure)
485 (defconst org-context-choice
486 '(choice
487 (const :tag "Always" t)
488 (const :tag "Never" nil)
489 (repeat :greedy t :tag "Individual contexts"
490 (cons
491 (choice :tag "Context"
492 (const agenda)
493 (const org-goto)
494 (const occur-tree)
495 (const tags-tree)
496 (const link-search)
497 (const mark-goto)
498 (const bookmark-jump)
499 (const isearch)
500 (const default))
501 (boolean))))
502 "Contexts for the reveal options.")
504 (defcustom org-show-hierarchy-above '((default . t))
505 "Non-nil means, show full hierarchy when revealing a location.
506 Org-mode often shows locations in an org-mode file which might have
507 been invisible before. When this is set, the hierarchy of headings
508 above the exposed location is shown.
509 Turning this off for example for sparse trees makes them very compact.
510 Instead of t, this can also be an alist specifying this option for different
511 contexts. Valid contexts are
512 agenda when exposing an entry from the agenda
513 org-goto when using the command `org-goto' on key C-c C-j
514 occur-tree when using the command `org-occur' on key C-c /
515 tags-tree when constructing a sparse tree based on tags matches
516 link-search when exposing search matches associated with a link
517 mark-goto when exposing the jump goal of a mark
518 bookmark-jump when exposing a bookmark location
519 isearch when exiting from an incremental search
520 default default for all contexts not set explicitly"
521 :group 'org-reveal-location
522 :type org-context-choice)
524 (defcustom org-show-following-heading '((default . nil))
525 "Non-nil means, show following heading when revealing a location.
526 Org-mode often shows locations in an org-mode file which might have
527 been invisible before. When this is set, the heading following the
528 match is shown.
529 Turning this off for example for sparse trees makes them very compact,
530 but makes it harder to edit the location of the match. In such a case,
531 use the command \\[org-reveal] to show more context.
532 Instead of t, this can also be an alist specifying this option for different
533 contexts. See `org-show-hierarchy-above' for valid contexts."
534 :group 'org-reveal-location
535 :type org-context-choice)
537 (defcustom org-show-siblings '((default . nil) (isearch t))
538 "Non-nil means, show all sibling heading when revealing a location.
539 Org-mode often shows locations in an org-mode file which might have
540 been invisible before. When this is set, the sibling of the current entry
541 heading are all made visible. If `org-show-hierarchy-above' is t,
542 the same happens on each level of the hierarchy above the current entry.
544 By default this is on for the isearch context, off for all other contexts.
545 Turning this off for example for sparse trees makes them very compact,
546 but makes it harder to edit the location of the match. In such a case,
547 use the command \\[org-reveal] to show more context.
548 Instead of t, this can also be an alist specifying this option for different
549 contexts. See `org-show-hierarchy-above' for valid contexts."
550 :group 'org-reveal-location
551 :type org-context-choice)
553 (defcustom org-show-entry-below '((default . nil))
554 "Non-nil means, show the entry below a headline when revealing a location.
555 Org-mode often shows locations in an org-mode file which might have
556 been invisible before. When this is set, the text below the headline that is
557 exposed is also shown.
559 By default this is off for all contexts.
560 Instead of t, this can also be an alist specifying this option for different
561 contexts. See `org-show-hierarchy-above' for valid contexts."
562 :group 'org-reveal-location
563 :type org-context-choice)
565 (defcustom org-indirect-buffer-display 'other-window
566 "How should indirect tree buffers be displayed?
567 This applies to indirect buffers created with the commands
568 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
569 Valid values are:
570 current-window Display in the current window
571 other-window Just display in another window.
572 dedicated-frame Create one new frame, and re-use it each time.
573 new-frame Make a new frame each time. Note that in this case
574 previously-made indirect buffers are kept, and you need to
575 kill these buffers yourself."
576 :group 'org-structure
577 :group 'org-agenda-windows
578 :type '(choice
579 (const :tag "In current window" current-window)
580 (const :tag "In current frame, other window" other-window)
581 (const :tag "Each time a new frame" new-frame)
582 (const :tag "One dedicated frame" dedicated-frame)))
584 (defgroup org-cycle nil
585 "Options concerning visibility cycling in Org-mode."
586 :tag "Org Cycle"
587 :group 'org-structure)
589 (defcustom org-cycle-skip-children-state-if-no-children t
590 "Non-nil means, skip CHILDREN state in entries that don't have any."
591 :group 'org-cycle
592 :type 'boolean)
594 (defcustom org-cycle-max-level nil
595 "Maximum level which should still be subject to visibility cycling.
596 Levels higher than this will, for cycling, be treated as text, not a headline.
597 When `org-odd-levels-only' is set, a value of N in this variable actually
598 means 2N-1 stars as the limiting headline.
599 When nil, cycle all levels.
600 Note that the limiting level of cycling is also influenced by
601 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
602 `org-inlinetask-min-level' is, cycling will be limited to levels one less
603 than its value."
604 :group 'org-cycle
605 :type '(choice
606 (const :tag "No limit" nil)
607 (integer :tag "Maximum level")))
609 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
610 "Names of drawers. Drawers are not opened by cycling on the headline above.
611 Drawers only open with a TAB on the drawer line itself. A drawer looks like
612 this:
613 :DRAWERNAME:
614 .....
615 :END:
616 The drawer \"PROPERTIES\" is special for capturing properties through
617 the property API.
619 Drawers can be defined on the per-file basis with a line like:
621 #+DRAWERS: HIDDEN STATE PROPERTIES"
622 :group 'org-structure
623 :group 'org-cycle
624 :type '(repeat (string :tag "Drawer Name")))
626 (defcustom org-hide-block-startup nil
627 "Non-nil means, , entering Org-mode will fold all blocks.
628 This can also be set in on a per-file basis with
630 #+STARTUP: hideblocks
631 #+STARTUP: showblocks"
632 :group 'org-startup
633 :group 'org-cycle
634 :type 'boolean)
636 (defcustom org-cycle-global-at-bob nil
637 "Cycle globally if cursor is at beginning of buffer and not at a headline.
638 This makes it possible to do global cycling without having to use S-TAB or
639 C-u TAB. For this special case to work, the first line of the buffer
640 must not be a headline - it may be empty or some other text. When used in
641 this way, `org-cycle-hook' is disables temporarily, to make sure the
642 cursor stays at the beginning of the buffer.
643 When this option is nil, don't do anything special at the beginning
644 of the buffer."
645 :group 'org-cycle
646 :type 'boolean)
648 (defcustom org-cycle-emulate-tab t
649 "Where should `org-cycle' emulate TAB.
650 nil Never
651 white Only in completely white lines
652 whitestart Only at the beginning of lines, before the first non-white char
653 t Everywhere except in headlines
654 exc-hl-bol Everywhere except at the start of a headline
655 If TAB is used in a place where it does not emulate TAB, the current subtree
656 visibility is cycled."
657 :group 'org-cycle
658 :type '(choice (const :tag "Never" nil)
659 (const :tag "Only in completely white lines" white)
660 (const :tag "Before first char in a line" whitestart)
661 (const :tag "Everywhere except in headlines" t)
662 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
665 (defcustom org-cycle-separator-lines 2
666 "Number of empty lines needed to keep an empty line between collapsed trees.
667 If you leave an empty line between the end of a subtree and the following
668 headline, this empty line is hidden when the subtree is folded.
669 Org-mode will leave (exactly) one empty line visible if the number of
670 empty lines is equal or larger to the number given in this variable.
671 So the default 2 means, at least 2 empty lines after the end of a subtree
672 are needed to produce free space between a collapsed subtree and the
673 following headline.
675 If the number is negative, and the number of empty lines is at least -N,
676 all empty lines are shown.
678 Special case: when 0, never leave empty lines in collapsed view."
679 :group 'org-cycle
680 :type 'integer)
681 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
683 (defcustom org-pre-cycle-hook nil
684 "Hook that is run before visibility cycling is happening.
685 The function(s) in this hook must accept a single argument which indicates
686 the new state that will be set right after running this hook. The
687 argument is a symbol. Before a global state change, it can have the values
688 `overview', `content', or `all'. Before a local state change, it can have
689 the values `folded', `children', or `subtree'."
690 :group 'org-cycle
691 :type 'hook)
693 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
694 org-cycle-hide-drawers
695 org-cycle-show-empty-lines
696 org-optimize-window-after-visibility-change)
697 "Hook that is run after `org-cycle' has changed the buffer visibility.
698 The function(s) in this hook must accept a single argument which indicates
699 the new state that was set by the most recent `org-cycle' command. The
700 argument is a symbol. After a global state change, it can have the values
701 `overview', `content', or `all'. After a local state change, it can have
702 the values `folded', `children', or `subtree'."
703 :group 'org-cycle
704 :type 'hook)
706 (defgroup org-edit-structure nil
707 "Options concerning structure editing in Org-mode."
708 :tag "Org Edit Structure"
709 :group 'org-structure)
711 (defcustom org-odd-levels-only nil
712 "Non-nil means, skip even levels and only use odd levels for the outline.
713 This has the effect that two stars are being added/taken away in
714 promotion/demotion commands. It also influences how levels are
715 handled by the exporters.
716 Changing it requires restart of `font-lock-mode' to become effective
717 for fontification also in regions already fontified.
718 You may also set this on a per-file basis by adding one of the following
719 lines to the buffer:
721 #+STARTUP: odd
722 #+STARTUP: oddeven"
723 :group 'org-edit-structure
724 :group 'org-font-lock
725 :type 'boolean)
727 (defcustom org-adapt-indentation t
728 "Non-nil means, adapt indentation to outline node level.
730 When this variable is set, Org assumes that you write outlines by
731 indenting text in each node to align with the headline (after the stars).
732 The following issues are influenced by this variable:
734 - When this is set and the *entire* text in an entry is indented, the
735 indentation is increased by one space in a demotion command, and
736 decreased by one in a promotion command. If any line in the entry
737 body starts with text at column 0, indentation is not changed at all.
739 - Property drawers and planning information is inserted indented when
740 this variable s set. When nil, they will not be indented.
742 - TAB indents a line relative to context. The lines below a headline
743 will be indented when this variable is set.
745 Note that this is all about true indentation, by adding and removing
746 space characters. See also `org-indent.el' which does level-dependent
747 indentation in a virtual way, i.e. at display time in Emacs."
748 :group 'org-edit-structure
749 :type 'boolean)
751 (defcustom org-special-ctrl-a/e nil
752 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
754 When t, `C-a' will bring back the cursor to the beginning of the
755 headline text, i.e. after the stars and after a possible TODO keyword.
756 In an item, this will be the position after the bullet.
757 When the cursor is already at that position, another `C-a' will bring
758 it to the beginning of the line.
760 `C-e' will jump to the end of the headline, ignoring the presence of tags
761 in the headline. A second `C-e' will then jump to the true end of the
762 line, after any tags.
764 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
765 going to the true line boundary first. Only a directly following, identical
766 keypress will bring the cursor to the special positions.
768 This may also be a cons cell where the behavior for `C-a' and `C-e' is
769 set separately."
770 :group 'org-edit-structure
771 :type '(choice
772 (const :tag "off" nil)
773 (const :tag "after stars/bullet and before tags first" t)
774 (const :tag "true line boundary first" reversed)
775 (cons :tag "Set C-a and C-e separately"
776 (choice :tag "Special C-a"
777 (const :tag "off" nil)
778 (const :tag "after stars/bullet first" t)
779 (const :tag "before stars/bullet first" reversed))
780 (choice :tag "Special C-e"
781 (const :tag "off" nil)
782 (const :tag "before tags first" t)
783 (const :tag "after tags first" reversed)))))
784 (if (fboundp 'defvaralias)
785 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
787 (defcustom org-special-ctrl-k nil
788 "Non-nil means `C-k' will behave specially in headlines.
789 When nil, `C-k' will call the default `kill-line' command.
790 When t, the following will happen while the cursor is in the headline:
792 - When the cursor is at the beginning of a headline, kill the entire
793 line and possible the folded subtree below the line.
794 - When in the middle of the headline text, kill the headline up to the tags.
795 - When after the headline text, kill the tags."
796 :group 'org-edit-structure
797 :type 'boolean)
799 (defcustom org-yank-folded-subtrees t
800 "Non-nil means, when yanking subtrees, fold them.
801 If the kill is a single subtree, or a sequence of subtrees, i.e. if
802 it starts with a heading and all other headings in it are either children
803 or siblings, then fold all the subtrees. However, do this only if no
804 text after the yank would be swallowed into a folded tree by this action."
805 :group 'org-edit-structure
806 :type 'boolean)
808 (defcustom org-yank-adjusted-subtrees nil
809 "Non-nil means, when yanking subtrees, adjust the level.
810 With this setting, `org-paste-subtree' is used to insert the subtree, see
811 this function for details."
812 :group 'org-edit-structure
813 :type 'boolean)
815 (defcustom org-M-RET-may-split-line '((default . t))
816 "Non-nil means, M-RET will split the line at the cursor position.
817 When nil, it will go to the end of the line before making a
818 new line.
819 You may also set this option in a different way for different
820 contexts. Valid contexts are:
822 headline when creating a new headline
823 item when creating a new item
824 table in a table field
825 default the value to be used for all contexts not explicitly
826 customized"
827 :group 'org-structure
828 :group 'org-table
829 :type '(choice
830 (const :tag "Always" t)
831 (const :tag "Never" nil)
832 (repeat :greedy t :tag "Individual contexts"
833 (cons
834 (choice :tag "Context"
835 (const headline)
836 (const item)
837 (const table)
838 (const default))
839 (boolean)))))
842 (defcustom org-insert-heading-respect-content nil
843 "Non-nil means, insert new headings after the current subtree.
844 When nil, the new heading is created directly after the current line.
845 The commands \\[org-insert-heading-respect-content] and
846 \\[org-insert-todo-heading-respect-content] turn this variable on
847 for the duration of the command."
848 :group 'org-structure
849 :type 'boolean)
851 (defcustom org-blank-before-new-entry '((heading . auto)
852 (plain-list-item . auto))
853 "Should `org-insert-heading' leave a blank line before new heading/item?
854 The value is an alist, with `heading' and `plain-list-item' as car,
855 and a boolean flag as cdr. For plain lists, if the variable
856 `org-empty-line-terminates-plain-lists' is set, the setting here
857 is ignored and no empty line is inserted, to keep the list in tact."
858 :group 'org-edit-structure
859 :type '(list
860 (cons (const heading)
861 (choice (const :tag "Never" nil)
862 (const :tag "Always" t)
863 (const :tag "Auto" auto)))
864 (cons (const plain-list-item)
865 (choice (const :tag "Never" nil)
866 (const :tag "Always" t)
867 (const :tag "Auto" auto)))))
869 (defcustom org-insert-heading-hook nil
870 "Hook being run after inserting a new heading."
871 :group 'org-edit-structure
872 :type 'hook)
874 (defcustom org-enable-fixed-width-editor t
875 "Non-nil means, lines starting with \":\" are treated as fixed-width.
876 This currently only means, they are never auto-wrapped.
877 When nil, such lines will be treated like ordinary lines.
878 See also the QUOTE keyword."
879 :group 'org-edit-structure
880 :type 'boolean)
883 (defcustom org-goto-auto-isearch t
884 "Non-nil means, typing characters in org-goto starts incremental search."
885 :group 'org-edit-structure
886 :type 'boolean)
888 (defgroup org-sparse-trees nil
889 "Options concerning sparse trees in Org-mode."
890 :tag "Org Sparse Trees"
891 :group 'org-structure)
893 (defcustom org-highlight-sparse-tree-matches t
894 "Non-nil means, highlight all matches that define a sparse tree.
895 The highlights will automatically disappear the next time the buffer is
896 changed by an edit command."
897 :group 'org-sparse-trees
898 :type 'boolean)
900 (defcustom org-remove-highlights-with-change t
901 "Non-nil means, any change to the buffer will remove temporary highlights.
902 Such highlights are created by `org-occur' and `org-clock-display'.
903 When nil, `C-c C-c needs to be used to get rid of the highlights.
904 The highlights created by `org-preview-latex-fragment' always need
905 `C-c C-c' to be removed."
906 :group 'org-sparse-trees
907 :group 'org-time
908 :type 'boolean)
911 (defcustom org-occur-hook '(org-first-headline-recenter)
912 "Hook that is run after `org-occur' has constructed a sparse tree.
913 This can be used to recenter the window to show as much of the structure
914 as possible."
915 :group 'org-sparse-trees
916 :type 'hook)
918 (defgroup org-imenu-and-speedbar nil
919 "Options concerning imenu and speedbar in Org-mode."
920 :tag "Org Imenu and Speedbar"
921 :group 'org-structure)
923 (defcustom org-imenu-depth 2
924 "The maximum level for Imenu access to Org-mode headlines.
925 This also applied for speedbar access."
926 :group 'org-imenu-and-speedbar
927 :type 'integer)
929 (defgroup org-table nil
930 "Options concerning tables in Org-mode."
931 :tag "Org Table"
932 :group 'org)
934 (defcustom org-enable-table-editor 'optimized
935 "Non-nil means, lines starting with \"|\" are handled by the table editor.
936 When nil, such lines will be treated like ordinary lines.
938 When equal to the symbol `optimized', the table editor will be optimized to
939 do the following:
940 - Automatic overwrite mode in front of whitespace in table fields.
941 This makes the structure of the table stay in tact as long as the edited
942 field does not exceed the column width.
943 - Minimize the number of realigns. Normally, the table is aligned each time
944 TAB or RET are pressed to move to another field. With optimization this
945 happens only if changes to a field might have changed the column width.
946 Optimization requires replacing the functions `self-insert-command',
947 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
948 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
949 very good at guessing when a re-align will be necessary, but you can always
950 force one with \\[org-ctrl-c-ctrl-c].
952 If you would like to use the optimized version in Org-mode, but the
953 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
955 This variable can be used to turn on and off the table editor during a session,
956 but in order to toggle optimization, a restart is required.
958 See also the variable `org-table-auto-blank-field'."
959 :group 'org-table
960 :type '(choice
961 (const :tag "off" nil)
962 (const :tag "on" t)
963 (const :tag "on, optimized" optimized)))
965 (defcustom org-self-insert-cluster-for-undo t
966 "Non-nil means cluster self-insert commands for undo when possible.
967 If this is set, then, like in the Emacs command loop, 20 consequtive
968 characters will be undone together.
969 This is configurable, because there is some impact on typing performance."
970 :group 'org-table
971 :type 'boolean)
973 (defcustom org-table-tab-recognizes-table.el t
974 "Non-nil means, TAB will automatically notice a table.el table.
975 When it sees such a table, it moves point into it and - if necessary -
976 calls `table-recognize-table'."
977 :group 'org-table-editing
978 :type 'boolean)
980 (defgroup org-link nil
981 "Options concerning links in Org-mode."
982 :tag "Org Link"
983 :group 'org)
985 (defvar org-link-abbrev-alist-local nil
986 "Buffer-local version of `org-link-abbrev-alist', which see.
987 The value of this is taken from the #+LINK lines.")
988 (make-variable-buffer-local 'org-link-abbrev-alist-local)
990 (defcustom org-link-abbrev-alist nil
991 "Alist of link abbreviations.
992 The car of each element is a string, to be replaced at the start of a link.
993 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
994 links in Org-mode buffers can have an optional tag after a double colon, e.g.
996 [[linkkey:tag][description]]
998 The 'linkkey' must be a word word, starting with a letter, followed
999 by letters, numbers, '-' or '_'.
1001 If REPLACE is a string, the tag will simply be appended to create the link.
1002 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1003 the placeholder \"%h\" will cause a url-encoded version of the tag to
1004 be inserted at that point (see the function `url-hexify-string').
1006 REPLACE may also be a function that will be called with the tag as the
1007 only argument to create the link, which should be returned as a string.
1009 See the manual for examples."
1010 :group 'org-link
1011 :type '(repeat
1012 (cons
1013 (string :tag "Protocol")
1014 (choice
1015 (string :tag "Format")
1016 (function)))))
1018 (defcustom org-descriptive-links t
1019 "Non-nil means, hide link part and only show description of bracket links.
1020 Bracket links are like [[link][description]]. This variable sets the initial
1021 state in new org-mode buffers. The setting can then be toggled on a
1022 per-buffer basis from the Org->Hyperlinks menu."
1023 :group 'org-link
1024 :type 'boolean)
1026 (defcustom org-link-file-path-type 'adaptive
1027 "How the path name in file links should be stored.
1028 Valid values are:
1030 relative Relative to the current directory, i.e. the directory of the file
1031 into which the link is being inserted.
1032 absolute Absolute path, if possible with ~ for home directory.
1033 noabbrev Absolute path, no abbreviation of home directory.
1034 adaptive Use relative path for files in the current directory and sub-
1035 directories of it. For other files, use an absolute path."
1036 :group 'org-link
1037 :type '(choice
1038 (const relative)
1039 (const absolute)
1040 (const noabbrev)
1041 (const adaptive)))
1043 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1044 "Types of links that should be activated in Org-mode files.
1045 This is a list of symbols, each leading to the activation of a certain link
1046 type. In principle, it does not hurt to turn on most link types - there may
1047 be a small gain when turning off unused link types. The types are:
1049 bracket The recommended [[link][description]] or [[link]] links with hiding.
1050 angular Links in angular brackets that may contain whitespace like
1051 <bbdb:Carsten Dominik>.
1052 plain Plain links in normal text, no whitespace, like http://google.com.
1053 radio Text that is matched by a radio target, see manual for details.
1054 tag Tag settings in a headline (link to tag search).
1055 date Time stamps (link to calendar).
1056 footnote Footnote labels.
1058 Changing this variable requires a restart of Emacs to become effective."
1059 :group 'org-link
1060 :type '(set :greedy t
1061 (const :tag "Double bracket links (new style)" bracket)
1062 (const :tag "Angular bracket links (old style)" angular)
1063 (const :tag "Plain text links" plain)
1064 (const :tag "Radio target matches" radio)
1065 (const :tag "Tags" tag)
1066 (const :tag "Timestamps" date)
1067 (const :tag "Footnotes" footnote)))
1069 (defcustom org-make-link-description-function nil
1070 "Function to use to generate link descriptions from links. If
1071 nil the link location will be used. This function must take two
1072 parameters; the first is the link and the second the description
1073 org-insert-link has generated, and should return the description
1074 to use."
1075 :group 'org-link
1076 :type 'function)
1078 (defgroup org-link-store nil
1079 "Options concerning storing links in Org-mode."
1080 :tag "Org Store Link"
1081 :group 'org-link)
1083 (defcustom org-email-link-description-format "Email %c: %.30s"
1084 "Format of the description part of a link to an email or usenet message.
1085 The following %-escapes will be replaced by corresponding information:
1087 %F full \"From\" field
1088 %f name, taken from \"From\" field, address if no name
1089 %T full \"To\" field
1090 %t first name in \"To\" field, address if no name
1091 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1092 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1093 %s subject
1094 %m message-id.
1096 You may use normal field width specification between the % and the letter.
1097 This is for example useful to limit the length of the subject.
1099 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1100 :group 'org-link-store
1101 :type 'string)
1103 (defcustom org-from-is-user-regexp
1104 (let (r1 r2)
1105 (when (and user-mail-address (not (string= user-mail-address "")))
1106 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1107 (when (and user-full-name (not (string= user-full-name "")))
1108 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1109 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1110 "Regexp matched against the \"From:\" header of an email or usenet message.
1111 It should match if the message is from the user him/herself."
1112 :group 'org-link-store
1113 :type 'regexp)
1115 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1116 "Non-nil means, storing a link to an Org file will use entry IDs.
1118 Note that before this variable is even considered, org-id must be loaded,
1119 so please customize `org-modules' and turn it on.
1121 The variable can have the following values:
1123 t Create an ID if needed to make a link to the current entry.
1125 create-if-interactive
1126 If `org-store-link' is called directly (interactively, as a user
1127 command), do create an ID to support the link. But when doing the
1128 job for remember, only use the ID if it already exists. The
1129 purpose of this setting is to avoid proliferation of unwanted
1130 IDs, just because you happen to be in an Org file when you
1131 call `org-remember' that automatically and preemptively
1132 creates a link. If you do want to get an ID link in a remember
1133 template to an entry not having an ID, create it first by
1134 explicitly creating a link to it, using `C-c C-l' first.
1136 create-if-interactive-and-no-custom-id
1137 Like create-if-interactive, but do not create an ID if there is
1138 a CUSTOM_ID property defined in the entry. This is the default.
1140 use-existing
1141 Use existing ID, do not create one.
1143 nil Never use an ID to make a link, instead link using a text search for
1144 the headline text."
1145 :group 'org-link-store
1146 :type '(choice
1147 (const :tag "Create ID to make link" t)
1148 (const :tag "Create if storing link interactively"
1149 create-if-interactive)
1150 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1151 create-if-interactive-and-no-custom-id)
1152 (const :tag "Only use existing" use-existing)
1153 (const :tag "Do not use ID to create link" nil)))
1155 (defcustom org-context-in-file-links t
1156 "Non-nil means, file links from `org-store-link' contain context.
1157 A search string will be added to the file name with :: as separator and
1158 used to find the context when the link is activated by the command
1159 `org-open-at-point'.
1160 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1161 negates this setting for the duration of the command."
1162 :group 'org-link-store
1163 :type 'boolean)
1165 (defcustom org-keep-stored-link-after-insertion nil
1166 "Non-nil means, keep link in list for entire session.
1168 The command `org-store-link' adds a link pointing to the current
1169 location to an internal list. These links accumulate during a session.
1170 The command `org-insert-link' can be used to insert links into any
1171 Org-mode file (offering completion for all stored links). When this
1172 option is nil, every link which has been inserted once using \\[org-insert-link]
1173 will be removed from the list, to make completing the unused links
1174 more efficient."
1175 :group 'org-link-store
1176 :type 'boolean)
1178 (defgroup org-link-follow nil
1179 "Options concerning following links in Org-mode."
1180 :tag "Org Follow Link"
1181 :group 'org-link)
1183 (defcustom org-link-translation-function nil
1184 "Function to translate links with different syntax to Org syntax.
1185 This can be used to translate links created for example by the Planner
1186 or emacs-wiki packages to Org syntax.
1187 The function must accept two parameters, a TYPE containing the link
1188 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1189 which is everything after the link protocol. It should return a cons
1190 with possibly modified values of type and path.
1191 Org contains a function for this, so if you set this variable to
1192 `org-translate-link-from-planner', you should be able follow many
1193 links created by planner."
1194 :group 'org-link-follow
1195 :type 'function)
1197 (defcustom org-follow-link-hook nil
1198 "Hook that is run after a link has been followed."
1199 :group 'org-link-follow
1200 :type 'hook)
1202 (defcustom org-tab-follows-link nil
1203 "Non-nil means, on links TAB will follow the link.
1204 Needs to be set before org.el is loaded.
1205 This really should not be used, it does not make sense, and the
1206 implementation is bad."
1207 :group 'org-link-follow
1208 :type 'boolean)
1210 (defcustom org-return-follows-link nil
1211 "Non-nil means, on links RET will follow the link.
1212 Needs to be set before org.el is loaded."
1213 :group 'org-link-follow
1214 :type 'boolean)
1216 (defcustom org-mouse-1-follows-link
1217 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1218 "Non-nil means, mouse-1 on a link will follow the link.
1219 A longer mouse click will still set point. Does not work on XEmacs.
1220 Needs to be set before org.el is loaded."
1221 :group 'org-link-follow
1222 :type 'boolean)
1224 (defcustom org-mark-ring-length 4
1225 "Number of different positions to be recorded in the ring
1226 Changing this requires a restart of Emacs to work correctly."
1227 :group 'org-link-follow
1228 :type 'integer)
1230 (defcustom org-link-frame-setup
1231 '((vm . vm-visit-folder-other-frame)
1232 (gnus . gnus-other-frame)
1233 (file . find-file-other-window))
1234 "Setup the frame configuration for following links.
1235 When following a link with Emacs, it may often be useful to display
1236 this link in another window or frame. This variable can be used to
1237 set this up for the different types of links.
1238 For VM, use any of
1239 `vm-visit-folder'
1240 `vm-visit-folder-other-frame'
1241 For Gnus, use any of
1242 `gnus'
1243 `gnus-other-frame'
1244 `org-gnus-no-new-news'
1245 For FILE, use any of
1246 `find-file'
1247 `find-file-other-window'
1248 `find-file-other-frame'
1249 For the calendar, use the variable `calendar-setup'.
1250 For BBDB, it is currently only possible to display the matches in
1251 another window."
1252 :group 'org-link-follow
1253 :type '(list
1254 (cons (const vm)
1255 (choice
1256 (const vm-visit-folder)
1257 (const vm-visit-folder-other-window)
1258 (const vm-visit-folder-other-frame)))
1259 (cons (const gnus)
1260 (choice
1261 (const gnus)
1262 (const gnus-other-frame)
1263 (const org-gnus-no-new-news)))
1264 (cons (const file)
1265 (choice
1266 (const find-file)
1267 (const find-file-other-window)
1268 (const find-file-other-frame)))))
1270 (defcustom org-display-internal-link-with-indirect-buffer nil
1271 "Non-nil means, use indirect buffer to display infile links.
1272 Activating internal links (from one location in a file to another location
1273 in the same file) normally just jumps to the location. When the link is
1274 activated with a C-u prefix (or with mouse-3), the link is displayed in
1275 another window. When this option is set, the other window actually displays
1276 an indirect buffer clone of the current buffer, to avoid any visibility
1277 changes to the current buffer."
1278 :group 'org-link-follow
1279 :type 'boolean)
1281 (defcustom org-open-non-existing-files nil
1282 "Non-nil means, `org-open-file' will open non-existing files.
1283 When nil, an error will be generated.
1284 This variable applies only to external applications because they
1285 might choke on non-existing files. If the link is to a file that
1286 will be openend in Emacs, the variable is ignored."
1287 :group 'org-link-follow
1288 :type 'boolean)
1290 (defcustom org-open-directory-means-index-dot-org nil
1291 "Non-nil means, a link to a directory really means to index.org.
1292 When nil, following a directory link will run dired or open a finder/explorer
1293 window on that directory."
1294 :group 'org-link-follow
1295 :type 'boolean)
1297 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1298 "Function and arguments to call for following mailto links.
1299 This is a list with the first element being a lisp function, and the
1300 remaining elements being arguments to the function. In string arguments,
1301 %a will be replaced by the address, and %s will be replaced by the subject
1302 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1303 :group 'org-link-follow
1304 :type '(choice
1305 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1306 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1307 (const :tag "message-mail" (message-mail "%a" "%s"))
1308 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1310 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1311 "Non-nil means, ask for confirmation before executing shell links.
1312 Shell links can be dangerous: just think about a link
1314 [[shell:rm -rf ~/*][Google Search]]
1316 This link would show up in your Org-mode document as \"Google Search\",
1317 but really it would remove your entire home directory.
1318 Therefore we advise against setting this variable to nil.
1319 Just change it to `y-or-n-p' if you want to confirm with a
1320 single keystroke rather than having to type \"yes\"."
1321 :group 'org-link-follow
1322 :type '(choice
1323 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1324 (const :tag "with y-or-n (faster)" y-or-n-p)
1325 (const :tag "no confirmation (dangerous)" nil)))
1327 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1328 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1329 Elisp links can be dangerous: just think about a link
1331 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1333 This link would show up in your Org-mode document as \"Google Search\",
1334 but really it would remove your entire home directory.
1335 Therefore we advise against setting this variable to nil.
1336 Just change it to `y-or-n-p' if you want to confirm with a
1337 single keystroke rather than having to type \"yes\"."
1338 :group 'org-link-follow
1339 :type '(choice
1340 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1341 (const :tag "with y-or-n (faster)" y-or-n-p)
1342 (const :tag "no confirmation (dangerous)" nil)))
1344 (defconst org-file-apps-defaults-gnu
1345 '((remote . emacs)
1346 (system . mailcap)
1347 (t . mailcap))
1348 "Default file applications on a UNIX or GNU/Linux system.
1349 See `org-file-apps'.")
1351 (defconst org-file-apps-defaults-macosx
1352 '((remote . emacs)
1353 (t . "open %s")
1354 (system . "open %s")
1355 ("ps.gz" . "gv %s")
1356 ("eps.gz" . "gv %s")
1357 ("dvi" . "xdvi %s")
1358 ("fig" . "xfig %s"))
1359 "Default file applications on a MacOS X system.
1360 The system \"open\" is known as a default, but we use X11 applications
1361 for some files for which the OS does not have a good default.
1362 See `org-file-apps'.")
1364 (defconst org-file-apps-defaults-windowsnt
1365 (list
1366 '(remote . emacs)
1367 (cons t
1368 (list (if (featurep 'xemacs)
1369 'mswindows-shell-execute
1370 'w32-shell-execute)
1371 "open" 'file))
1372 (cons 'system
1373 (list (if (featurep 'xemacs)
1374 'mswindows-shell-execute
1375 'w32-shell-execute)
1376 "open" 'file)))
1377 "Default file applications on a Windows NT system.
1378 The system \"open\" is used for most files.
1379 See `org-file-apps'.")
1381 (defcustom org-file-apps
1383 (auto-mode . emacs)
1384 ("\\.x?html?\\'" . default)
1385 ("\\.pdf\\'" . default)
1387 "External applications for opening `file:path' items in a document.
1388 Org-mode uses system defaults for different file types, but
1389 you can use this variable to set the application for a given file
1390 extension. The entries in this list are cons cells where the car identifies
1391 files and the cdr the corresponding command. Possible values for the
1392 file identifier are
1393 \"regex\" Regular expression matched against the file name. For backward
1394 compatibility, this can also be a string with only alphanumeric
1395 characters, which is then interpreted as an extension.
1396 `directory' Matches a directory
1397 `remote' Matches a remote file, accessible through tramp or efs.
1398 Remote files most likely should be visited through Emacs
1399 because external applications cannot handle such paths.
1400 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1401 so all files Emacs knows how to handle. Using this with
1402 command `emacs' will open most files in Emacs. Beware that this
1403 will also open html files inside Emacs, unless you add
1404 (\"html\" . default) to the list as well.
1405 t Default for files not matched by any of the other options.
1406 `system' The system command to open files, like `open' on Windows
1407 and Mac OS X, and mailcap under GNU/Linux. This is the command
1408 that will be selected if you call `C-c C-o' with a double
1409 `C-u C-u' prefix.
1411 Possible values for the command are:
1412 `emacs' The file will be visited by the current Emacs process.
1413 `default' Use the default application for this file type, which is the
1414 association for t in the list, most likely in the system-specific
1415 part.
1416 This can be used to overrule an unwanted setting in the
1417 system-specific variable.
1418 `system' Use the system command for opening files, like \"open\".
1419 This command is specified by the entry whose car is `system'.
1420 Most likely, the system-specific version of this variable
1421 does define this command, but you can overrule/replace it
1422 here.
1423 string A command to be executed by a shell; %s will be replaced
1424 by the path to the file.
1425 sexp A Lisp form which will be evaluated. The file path will
1426 be available in the Lisp variable `file'.
1427 For more examples, see the system specific constants
1428 `org-file-apps-defaults-macosx'
1429 `org-file-apps-defaults-windowsnt'
1430 `org-file-apps-defaults-gnu'."
1431 :group 'org-link-follow
1432 :type '(repeat
1433 (cons (choice :value ""
1434 (string :tag "Extension")
1435 (const :tag "System command to open files" system)
1436 (const :tag "Default for unrecognized files" t)
1437 (const :tag "Remote file" remote)
1438 (const :tag "Links to a directory" directory)
1439 (const :tag "Any files that have Emacs modes"
1440 auto-mode))
1441 (choice :value ""
1442 (const :tag "Visit with Emacs" emacs)
1443 (const :tag "Use default" default)
1444 (const :tag "Use the system command" system)
1445 (string :tag "Command")
1446 (sexp :tag "Lisp form")))))
1448 (defgroup org-refile nil
1449 "Options concerning refiling entries in Org-mode."
1450 :tag "Org Refile"
1451 :group 'org)
1453 (defcustom org-directory "~/org"
1454 "Directory with org files.
1455 This is just a default location to look for Org files. There is no need
1456 at all to put your files into this directory. It is only used in the
1457 following situations:
1459 1. When a remember template specifies a target file that is not an
1460 absolute path. The path will then be interpreted relative to
1461 `org-directory'
1462 2. When a remember note is filed away in an interactive way (when exiting the
1463 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1464 with `org-directory' as the default path."
1465 :group 'org-refile
1466 :group 'org-remember
1467 :type 'directory)
1469 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1470 "Default target for storing notes.
1471 Used by the hooks for remember.el. This can be a string, or nil to mean
1472 the value of `remember-data-file'.
1473 You can set this on a per-template basis with the variable
1474 `org-remember-templates'."
1475 :group 'org-refile
1476 :group 'org-remember
1477 :type '(choice
1478 (const :tag "Default from remember-data-file" nil)
1479 file))
1481 (defcustom org-goto-interface 'outline
1482 "The default interface to be used for `org-goto'.
1483 Allowed values are:
1484 outline The interface shows an outline of the relevant file
1485 and the correct heading is found by moving through
1486 the outline or by searching with incremental search.
1487 outline-path-completion Headlines in the current buffer are offered via
1488 completion. This is the interface also used by
1489 the refile command."
1490 :group 'org-refile
1491 :type '(choice
1492 (const :tag "Outline" outline)
1493 (const :tag "Outline-path-completion" outline-path-completion)))
1495 (defcustom org-goto-max-level 5
1496 "Maximum level to be considered when running org-goto with refile interface."
1497 :group 'org-refile
1498 :type 'integer)
1500 (defcustom org-reverse-note-order nil
1501 "Non-nil means, store new notes at the beginning of a file or entry.
1502 When nil, new notes will be filed to the end of a file or entry.
1503 This can also be a list with cons cells of regular expressions that
1504 are matched against file names, and values."
1505 :group 'org-remember
1506 :group 'org-refile
1507 :type '(choice
1508 (const :tag "Reverse always" t)
1509 (const :tag "Reverse never" nil)
1510 (repeat :tag "By file name regexp"
1511 (cons regexp boolean))))
1513 (defcustom org-refile-targets nil
1514 "Targets for refiling entries with \\[org-refile].
1515 This is list of cons cells. Each cell contains:
1516 - a specification of the files to be considered, either a list of files,
1517 or a symbol whose function or variable value will be used to retrieve
1518 a file name or a list of file names. If you use `org-agenda-files' for
1519 that, all agenda files will be scanned for targets. Nil means, consider
1520 headings in the current buffer.
1521 - A specification of how to find candidate refile targets. This may be
1522 any of:
1523 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1524 This tag has to be present in all target headlines, inheritance will
1525 not be considered.
1526 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1527 todo keyword.
1528 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1529 headlines that are refiling targets.
1530 - a cons cell (:level . N). Any headline of level N is considered a target.
1531 Note that, when `org-odd-levels-only' is set, level corresponds to
1532 order in hierarchy, not to the number of stars.
1533 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1534 Note that, when `org-odd-levels-only' is set, level corresponds to
1535 order in hierarchy, not to the number of stars.
1537 You can set the variable `org-refile-target-verify-function' to a function
1538 to verify each headline found by the simple critery above.
1540 When this variable is nil, all top-level headlines in the current buffer
1541 are used, equivalent to the value `((nil . (:level . 1))'."
1542 :group 'org-refile
1543 :type '(repeat
1544 (cons
1545 (choice :value org-agenda-files
1546 (const :tag "All agenda files" org-agenda-files)
1547 (const :tag "Current buffer" nil)
1548 (function) (variable) (file))
1549 (choice :tag "Identify target headline by"
1550 (cons :tag "Specific tag" (const :value :tag) (string))
1551 (cons :tag "TODO keyword" (const :value :todo) (string))
1552 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1553 (cons :tag "Level number" (const :value :level) (integer))
1554 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1556 (defcustom org-refile-target-verify-function nil
1557 "Function to verify if the headline at point should be a refile target.
1558 The function will be called without arguments, with point at the
1559 beginning of the headline. It should return t and leave point
1560 where it is if the headline is a valid target for refiling.
1562 If the target should not be selected, the function must return nil.
1563 In addition to this, it may move point to a place from where the search
1564 should be continued. For example, the function may decide that the entire
1565 subtree of the current entry should be excluded and move point to the end
1566 of the subtree."
1567 :group 'org-refile
1568 :type 'function)
1570 (defcustom org-refile-use-outline-path nil
1571 "Non-nil means, provide refile targets as paths.
1572 So a level 3 headline will be available as level1/level2/level3.
1574 When the value is `file', also include the file name (without directory)
1575 into the path. In this case, you can also stop the completion after
1576 the file name, to get entries inserted as top level in the file.
1578 When `full-file-path', include the full file path."
1579 :group 'org-refile
1580 :type '(choice
1581 (const :tag "Not" nil)
1582 (const :tag "Yes" t)
1583 (const :tag "Start with file name" file)
1584 (const :tag "Start with full file path" full-file-path)))
1586 (defcustom org-outline-path-complete-in-steps t
1587 "Non-nil means, complete the outline path in hierarchical steps.
1588 When Org-mode uses the refile interface to select an outline path
1589 \(see variable `org-refile-use-outline-path'), the completion of
1590 the path can be done is a single go, or if can be done in steps down
1591 the headline hierarchy. Going in steps is probably the best if you
1592 do not use a special completion package like `ido' or `icicles'.
1593 However, when using these packages, going in one step can be very
1594 fast, while still showing the whole path to the entry."
1595 :group 'org-refile
1596 :type 'boolean)
1598 (defcustom org-refile-allow-creating-parent-nodes nil
1599 "Non-nil means, allow to create new nodes as refile targets.
1600 New nodes are then created by adding \"/new node name\" to the completion
1601 of an existing node. When the value of this variable is `confirm',
1602 new node creation must be confirmed by the user (recommended)
1603 When nil, the completion must match an existing entry.
1605 Note that, if the new heading is not seen by the criteria
1606 listed in `org-refile-targets', multiple instances of the same
1607 heading would be created by trying again to file under the new
1608 heading."
1609 :group 'org-refile
1610 :type '(choice
1611 (const :tag "Never" nil)
1612 (const :tag "Always" t)
1613 (const :tag "Prompt for confirmation" confirm)))
1615 (defgroup org-todo nil
1616 "Options concerning TODO items in Org-mode."
1617 :tag "Org TODO"
1618 :group 'org)
1620 (defgroup org-progress nil
1621 "Options concerning Progress logging in Org-mode."
1622 :tag "Org Progress"
1623 :group 'org-time)
1625 (defvar org-todo-interpretation-widgets
1627 (:tag "Sequence (cycling hits every state)" sequence)
1628 (:tag "Type (cycling directly to DONE)" type))
1629 "The available interpretation symbols for customizing
1630 `org-todo-keywords'.
1631 Interested libraries should add to this list.")
1633 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1634 "List of TODO entry keyword sequences and their interpretation.
1635 \\<org-mode-map>This is a list of sequences.
1637 Each sequence starts with a symbol, either `sequence' or `type',
1638 indicating if the keywords should be interpreted as a sequence of
1639 action steps, or as different types of TODO items. The first
1640 keywords are states requiring action - these states will select a headline
1641 for inclusion into the global TODO list Org-mode produces. If one of
1642 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1643 signify that no further action is necessary. If \"|\" is not found,
1644 the last keyword is treated as the only DONE state of the sequence.
1646 The command \\[org-todo] cycles an entry through these states, and one
1647 additional state where no keyword is present. For details about this
1648 cycling, see the manual.
1650 TODO keywords and interpretation can also be set on a per-file basis with
1651 the special #+SEQ_TODO and #+TYP_TODO lines.
1653 Each keyword can optionally specify a character for fast state selection
1654 \(in combination with the variable `org-use-fast-todo-selection')
1655 and specifiers for state change logging, using the same syntax
1656 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1657 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1658 indicates to record a time stamp each time this state is selected.
1660 Each keyword may also specify if a timestamp or a note should be
1661 recorded when entering or leaving the state, by adding additional
1662 characters in the parenthesis after the keyword. This looks like this:
1663 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1664 record only the time of the state change. With X and Y being either
1665 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1666 Y when leaving the state if and only if the *target* state does not
1667 define X. You may omit any of the fast-selection key or X or /Y,
1668 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1670 For backward compatibility, this variable may also be just a list
1671 of keywords - in this case the interpretation (sequence or type) will be
1672 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1673 :group 'org-todo
1674 :group 'org-keywords
1675 :type '(choice
1676 (repeat :tag "Old syntax, just keywords"
1677 (string :tag "Keyword"))
1678 (repeat :tag "New syntax"
1679 (cons
1680 (choice
1681 :tag "Interpretation"
1682 ;;Quick and dirty way to see
1683 ;;`org-todo-interpretations'. This takes the
1684 ;;place of item arguments
1685 :convert-widget
1686 (lambda (widget)
1687 (widget-put widget
1688 :args (mapcar
1689 #'(lambda (x)
1690 (widget-convert
1691 (cons 'const x)))
1692 org-todo-interpretation-widgets))
1693 widget))
1694 (repeat
1695 (string :tag "Keyword"))))))
1697 (defvar org-todo-keywords-1 nil
1698 "All TODO and DONE keywords active in a buffer.")
1699 (make-variable-buffer-local 'org-todo-keywords-1)
1700 (defvar org-todo-keywords-for-agenda nil)
1701 (defvar org-done-keywords-for-agenda nil)
1702 (defvar org-todo-keyword-alist-for-agenda nil)
1703 (defvar org-tag-alist-for-agenda nil)
1704 (defvar org-agenda-contributing-files nil)
1705 (defvar org-not-done-keywords nil)
1706 (make-variable-buffer-local 'org-not-done-keywords)
1707 (defvar org-done-keywords nil)
1708 (make-variable-buffer-local 'org-done-keywords)
1709 (defvar org-todo-heads nil)
1710 (make-variable-buffer-local 'org-todo-heads)
1711 (defvar org-todo-sets nil)
1712 (make-variable-buffer-local 'org-todo-sets)
1713 (defvar org-todo-log-states nil)
1714 (make-variable-buffer-local 'org-todo-log-states)
1715 (defvar org-todo-kwd-alist nil)
1716 (make-variable-buffer-local 'org-todo-kwd-alist)
1717 (defvar org-todo-key-alist nil)
1718 (make-variable-buffer-local 'org-todo-key-alist)
1719 (defvar org-todo-key-trigger nil)
1720 (make-variable-buffer-local 'org-todo-key-trigger)
1722 (defcustom org-todo-interpretation 'sequence
1723 "Controls how TODO keywords are interpreted.
1724 This variable is in principle obsolete and is only used for
1725 backward compatibility, if the interpretation of todo keywords is
1726 not given already in `org-todo-keywords'. See that variable for
1727 more information."
1728 :group 'org-todo
1729 :group 'org-keywords
1730 :type '(choice (const sequence)
1731 (const type)))
1733 (defcustom org-use-fast-todo-selection t
1734 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1735 This variable describes if and under what circumstances the cycling
1736 mechanism for TODO keywords will be replaced by a single-key, direct
1737 selection scheme.
1739 When nil, fast selection is never used.
1741 When the symbol `prefix', it will be used when `org-todo' is called with
1742 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1743 in an agenda buffer.
1745 When t, fast selection is used by default. In this case, the prefix
1746 argument forces cycling instead.
1748 In all cases, the special interface is only used if access keys have actually
1749 been assigned by the user, i.e. if keywords in the configuration are followed
1750 by a letter in parenthesis, like TODO(t)."
1751 :group 'org-todo
1752 :type '(choice
1753 (const :tag "Never" nil)
1754 (const :tag "By default" t)
1755 (const :tag "Only with C-u C-c C-t" prefix)))
1757 (defcustom org-provide-todo-statistics t
1758 "Non-nil means, update todo statistics after insert and toggle.
1759 ALL-HEADLINES means update todo statistics by including headlines
1760 with no TODO keyword as well, counting them as not done.
1761 A list of TODO keywords means the same, but skip keywords that are
1762 not in this list.
1764 When this is set, todo statistics is updated in the parent of the
1765 current entry each time a todo state is changed."
1766 :group 'org-todo
1767 :type '(choice
1768 (const :tag "Yes, only for TODO entries" t)
1769 (const :tag "Yes, including all entries" 'all-headlines)
1770 (repeat :tag "Yes, for TODOs in this list"
1771 (string :tag "TODO keyword"))
1772 (other :tag "No TODO statistics" nil)))
1774 (defcustom org-hierarchical-todo-statistics t
1775 "Non-nil means, TODO statistics covers just direct children.
1776 When nil, all entries in the subtree are considered.
1777 This has only an effect if `org-provide-todo-statistics' is set.
1778 To set this to nil for only a single subtree, use a COOKIE_DATA
1779 property and include the word \"recursive\" into the value."
1780 :group 'org-todo
1781 :type 'boolean)
1783 (defcustom org-after-todo-state-change-hook nil
1784 "Hook which is run after the state of a TODO item was changed.
1785 The new state (a string with a TODO keyword, or nil) is available in the
1786 Lisp variable `state'."
1787 :group 'org-todo
1788 :type 'hook)
1790 (defvar org-blocker-hook nil
1791 "Hook for functions that are allowed to block a state change.
1793 Each function gets as its single argument a property list, see
1794 `org-trigger-hook' for more information about this list.
1796 If any of the functions in this hook returns nil, the state change
1797 is blocked.")
1799 (defvar org-trigger-hook nil
1800 "Hook for functions that are triggered by a state change.
1802 Each function gets as its single argument a property list with at least
1803 the following elements:
1805 (:type type-of-change :position pos-at-entry-start
1806 :from old-state :to new-state)
1808 Depending on the type, more properties may be present.
1810 This mechanism is currently implemented for:
1812 TODO state changes
1813 ------------------
1814 :type todo-state-change
1815 :from previous state (keyword as a string), or nil, or a symbol
1816 'todo' or 'done', to indicate the general type of state.
1817 :to new state, like in :from")
1819 (defcustom org-enforce-todo-dependencies nil
1820 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1821 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1822 be blocked if any prior sibling is not yet done.
1823 Finally, if the parent is blocked because of ordered siblings of its own,
1824 the child will also be blocked.
1825 This variable needs to be set before org.el is loaded, and you need to
1826 restart Emacs after a change to make the change effective. The only way
1827 to change is while Emacs is running is through the customize interface."
1828 :set (lambda (var val)
1829 (set var val)
1830 (if val
1831 (add-hook 'org-blocker-hook
1832 'org-block-todo-from-children-or-siblings-or-parent)
1833 (remove-hook 'org-blocker-hook
1834 'org-block-todo-from-children-or-siblings-or-parent)))
1835 :group 'org-todo
1836 :type 'boolean)
1838 (defcustom org-enforce-todo-checkbox-dependencies nil
1839 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1840 When this is nil, checkboxes have no influence on switching TODO states.
1841 When non-nil, you first need to check off all check boxes before the TODO
1842 entry can be switched to DONE.
1843 This variable needs to be set before org.el is loaded, and you need to
1844 restart Emacs after a change to make the change effective. The only way
1845 to change is while Emacs is running is through the customize interface."
1846 :set (lambda (var val)
1847 (set var val)
1848 (if val
1849 (add-hook 'org-blocker-hook
1850 'org-block-todo-from-checkboxes)
1851 (remove-hook 'org-blocker-hook
1852 'org-block-todo-from-checkboxes)))
1853 :group 'org-todo
1854 :type 'boolean)
1856 (defcustom org-treat-insert-todo-heading-as-state-change nil
1857 "Non-nil means, inserting a TODO heading is treated as state change.
1858 So when the command \\[org-insert-todo-heading] is used, state change
1859 logging will apply if appropriate. When nil, the new TODO item will
1860 be inserted directly, and no logging will take place."
1861 :group 'org-todo
1862 :type 'boolean)
1864 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1865 "Non-nil means, switching TODO states with S-cursor counts as state change.
1866 This is the default behavior. However, setting this to nil allows a
1867 convenient way to select a TODO state and bypass any logging associated
1868 with that."
1869 :group 'org-todo
1870 :type 'boolean)
1872 (defcustom org-todo-state-tags-triggers nil
1873 "Tag changes that should be triggered by TODO state changes.
1874 This is a list. Each entry is
1876 (state-change (tag . flag) .......)
1878 State-change can be a string with a state, and empty string to indicate the
1879 state that has no TODO keyword, or it can be one of the symbols `todo'
1880 or `done', meaning any not-done or done state, respectively."
1881 :group 'org-todo
1882 :group 'org-tags
1883 :type '(repeat
1884 (cons (choice :tag "When changing to"
1885 (const :tag "Not-done state" todo)
1886 (const :tag "Done state" done)
1887 (string :tag "State"))
1888 (repeat
1889 (cons :tag "Tag action"
1890 (string :tag "Tag")
1891 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1893 (defcustom org-log-done nil
1894 "Information to record when a task moves to the DONE state.
1896 Possible values are:
1898 nil Don't add anything, just change the keyword
1899 time Add a time stamp to the task
1900 note Prompt a closing note and add it with template `org-log-note-headings'
1902 This option can also be set with on a per-file-basis with
1904 #+STARTUP: nologdone
1905 #+STARTUP: logdone
1906 #+STARTUP: lognotedone
1908 You can have local logging settings for a subtree by setting the LOGGING
1909 property to one or more of these keywords."
1910 :group 'org-todo
1911 :group 'org-progress
1912 :type '(choice
1913 (const :tag "No logging" nil)
1914 (const :tag "Record CLOSED timestamp" time)
1915 (const :tag "Record CLOSED timestamp with closing note." note)))
1917 ;; Normalize old uses of org-log-done.
1918 (cond
1919 ((eq org-log-done t) (setq org-log-done 'time))
1920 ((and (listp org-log-done) (memq 'done org-log-done))
1921 (setq org-log-done 'note)))
1923 (defcustom org-log-note-clock-out nil
1924 "Non-nil means, record a note when clocking out of an item.
1925 This can also be configured on a per-file basis by adding one of
1926 the following lines anywhere in the buffer:
1928 #+STARTUP: lognoteclock-out
1929 #+STARTUP: nolognoteclock-out"
1930 :group 'org-todo
1931 :group 'org-progress
1932 :type 'boolean)
1934 (defcustom org-log-done-with-time t
1935 "Non-nil means, the CLOSED time stamp will contain date and time.
1936 When nil, only the date will be recorded."
1937 :group 'org-progress
1938 :type 'boolean)
1940 (defcustom org-log-note-headings
1941 '((done . "CLOSING NOTE %t")
1942 (state . "State %-12s from %-12S %t")
1943 (note . "Note taken on %t")
1944 (clock-out . ""))
1945 "Headings for notes added to entries.
1946 The value is an alist, with the car being a symbol indicating the note
1947 context, and the cdr is the heading to be used. The heading may also be the
1948 empty string.
1949 %t in the heading will be replaced by a time stamp.
1950 %s will be replaced by the new TODO state, in double quotes.
1951 %S will be replaced by the old TODO state, in double quotes.
1952 %u will be replaced by the user name.
1953 %U will be replaced by the full user name."
1954 :group 'org-todo
1955 :group 'org-progress
1956 :type '(list :greedy t
1957 (cons (const :tag "Heading when closing an item" done) string)
1958 (cons (const :tag
1959 "Heading when changing todo state (todo sequence only)"
1960 state) string)
1961 (cons (const :tag "Heading when just taking a note" note) string)
1962 (cons (const :tag "Heading when clocking out" clock-out) string)))
1964 (unless (assq 'note org-log-note-headings)
1965 (push '(note . "%t") org-log-note-headings))
1967 (defcustom org-log-into-drawer nil
1968 "Non-nil means, insert state change notes and time stamps into a drawer.
1969 When nil, state changes notes will be inserted after the headline and
1970 any scheduling and clock lines, but not inside a drawer.
1972 The value of this variable should be the name of the drawer to use.
1973 LOGBOOK is proposed at the default drawer for this purpose, you can
1974 also set this to a string to define the drawer of your choice.
1976 A value of t is also allowed, representing \"LOGBOOK\".
1978 If this variable is set, `org-log-state-notes-insert-after-drawers'
1979 will be ignored.
1981 You can set the property LOG_INTO_DRAWER to overrule this setting for
1982 a subtree."
1983 :group 'org-todo
1984 :group 'org-progress
1985 :type '(choice
1986 (const :tag "Not into a drawer" nil)
1987 (const :tag "LOGBOOK" t)
1988 (string :tag "Other")))
1990 (if (fboundp 'defvaralias)
1991 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1993 (defun org-log-into-drawer ()
1994 "Return the value of `org-log-into-drawer', but let properties overrule.
1995 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1996 used instead of the default value."
1997 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1998 (cond
1999 ((or (not p) (equal p "nil")) org-log-into-drawer)
2000 ((equal p "t") "LOGBOOK")
2001 (t p))))
2003 (defcustom org-log-state-notes-insert-after-drawers nil
2004 "Non-nil means, insert state change notes after any drawers in entry.
2005 Only the drawers that *immediately* follow the headline and the
2006 deadline/scheduled line are skipped.
2007 When nil, insert notes right after the heading and perhaps the line
2008 with deadline/scheduling if present.
2010 This variable will have no effect if `org-log-into-drawer' is
2011 set."
2012 :group 'org-todo
2013 :group 'org-progress
2014 :type 'boolean)
2016 (defcustom org-log-states-order-reversed t
2017 "Non-nil means, the latest state change note will be directly after heading.
2018 When nil, the notes will be orderer according to time."
2019 :group 'org-todo
2020 :group 'org-progress
2021 :type 'boolean)
2023 (defcustom org-log-repeat 'time
2024 "Non-nil means, record moving through the DONE state when triggering repeat.
2025 An auto-repeating task is immediately switched back to TODO when
2026 marked DONE. If you are not logging state changes (by adding \"@\"
2027 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2028 record a closing note, there will be no record of the task moving
2029 through DONE. This variable forces taking a note anyway.
2031 nil Don't force a record
2032 time Record a time stamp
2033 note Record a note
2035 This option can also be set with on a per-file-basis with
2037 #+STARTUP: logrepeat
2038 #+STARTUP: lognoterepeat
2039 #+STARTUP: nologrepeat
2041 You can have local logging settings for a subtree by setting the LOGGING
2042 property to one or more of these keywords."
2043 :group 'org-todo
2044 :group 'org-progress
2045 :type '(choice
2046 (const :tag "Don't force a record" nil)
2047 (const :tag "Force recording the DONE state" time)
2048 (const :tag "Force recording a note with the DONE state" note)))
2051 (defgroup org-priorities nil
2052 "Priorities in Org-mode."
2053 :tag "Org Priorities"
2054 :group 'org-todo)
2056 (defcustom org-enable-priority-commands t
2057 "Non-nil means, priority commands are active.
2058 When nil, these commands will be disabled, so that you never accidentally
2059 set a priority."
2060 :group 'org-priorities
2061 :type 'boolean)
2063 (defcustom org-highest-priority ?A
2064 "The highest priority of TODO items. A character like ?A, ?B etc.
2065 Must have a smaller ASCII number than `org-lowest-priority'."
2066 :group 'org-priorities
2067 :type 'character)
2069 (defcustom org-lowest-priority ?C
2070 "The lowest priority of TODO items. A character like ?A, ?B etc.
2071 Must have a larger ASCII number than `org-highest-priority'."
2072 :group 'org-priorities
2073 :type 'character)
2075 (defcustom org-default-priority ?B
2076 "The default priority of TODO items.
2077 This is the priority an item get if no explicit priority is given."
2078 :group 'org-priorities
2079 :type 'character)
2081 (defcustom org-priority-start-cycle-with-default t
2082 "Non-nil means, start with default priority when starting to cycle.
2083 When this is nil, the first step in the cycle will be (depending on the
2084 command used) one higher or lower that the default priority."
2085 :group 'org-priorities
2086 :type 'boolean)
2088 (defgroup org-time nil
2089 "Options concerning time stamps and deadlines in Org-mode."
2090 :tag "Org Time"
2091 :group 'org)
2093 (defcustom org-insert-labeled-timestamps-at-point nil
2094 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2095 When nil, these labeled time stamps are forces into the second line of an
2096 entry, just after the headline. When scheduling from the global TODO list,
2097 the time stamp will always be forced into the second line."
2098 :group 'org-time
2099 :type 'boolean)
2101 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2102 "Formats for `format-time-string' which are used for time stamps.
2103 It is not recommended to change this constant.")
2105 (defcustom org-time-stamp-rounding-minutes '(0 5)
2106 "Number of minutes to round time stamps to.
2107 These are two values, the first applies when first creating a time stamp.
2108 The second applies when changing it with the commands `S-up' and `S-down'.
2109 When changing the time stamp, this means that it will change in steps
2110 of N minutes, as given by the second value.
2112 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2113 numbers should be factors of 60, so for example 5, 10, 15.
2115 When this is larger than 1, you can still force an exact time-stamp by using
2116 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2117 and by using a prefix arg to `S-up/down' to specify the exact number
2118 of minutes to shift."
2119 :group 'org-time
2120 :get '(lambda (var) ; Make sure all entries have 5 elements
2121 (if (integerp (default-value var))
2122 (list (default-value var) 5)
2123 (default-value var)))
2124 :type '(list
2125 (integer :tag "when inserting times")
2126 (integer :tag "when modifying times")))
2128 ;; Normalize old customizations of this variable.
2129 (when (integerp org-time-stamp-rounding-minutes)
2130 (setq org-time-stamp-rounding-minutes
2131 (list org-time-stamp-rounding-minutes
2132 org-time-stamp-rounding-minutes)))
2134 (defcustom org-display-custom-times nil
2135 "Non-nil means, overlay custom formats over all time stamps.
2136 The formats are defined through the variable `org-time-stamp-custom-formats'.
2137 To turn this on on a per-file basis, insert anywhere in the file:
2138 #+STARTUP: customtime"
2139 :group 'org-time
2140 :set 'set-default
2141 :type 'sexp)
2142 (make-variable-buffer-local 'org-display-custom-times)
2144 (defcustom org-time-stamp-custom-formats
2145 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2146 "Custom formats for time stamps. See `format-time-string' for the syntax.
2147 These are overlayed over the default ISO format if the variable
2148 `org-display-custom-times' is set. Time like %H:%M should be at the
2149 end of the second format. The custom formats are also honored by export
2150 commands, if custom time display is turned on at the time of export."
2151 :group 'org-time
2152 :type 'sexp)
2154 (defun org-time-stamp-format (&optional long inactive)
2155 "Get the right format for a time string."
2156 (let ((f (if long (cdr org-time-stamp-formats)
2157 (car org-time-stamp-formats))))
2158 (if inactive
2159 (concat "[" (substring f 1 -1) "]")
2160 f)))
2162 (defcustom org-time-clocksum-format "%d:%02d"
2163 "The format string used when creating CLOCKSUM lines, or when
2164 org-mode generates a time duration."
2165 :group 'org-time
2166 :type 'string)
2168 (defcustom org-deadline-warning-days 14
2169 "No. of days before expiration during which a deadline becomes active.
2170 This variable governs the display in sparse trees and in the agenda.
2171 When 0 or negative, it means use this number (the absolute value of it)
2172 even if a deadline has a different individual lead time specified.
2174 Custom commands can set this variable in the options section."
2175 :group 'org-time
2176 :group 'org-agenda-daily/weekly
2177 :type 'integer)
2179 (defcustom org-read-date-prefer-future t
2180 "Non-nil means, assume future for incomplete date input from user.
2181 This affects the following situations:
2182 1. The user gives a day, but no month.
2183 For example, if today is the 15th, and you enter \"3\", Org-mode will
2184 read this as the third of *next* month. However, if you enter \"17\",
2185 it will be considered as *this* month.
2186 2. The user gives a month but not a year.
2187 For example, if it is april and you enter \"feb 2\", this will be read
2188 as feb 2, *next* year. \"May 5\", however, will be this year.
2190 Currently this does not work for ISO week specifications.
2192 When this option is nil, the current month and year will always be used
2193 as defaults."
2194 :group 'org-time
2195 :type 'boolean)
2197 (defcustom org-read-date-display-live t
2198 "Non-nil means, display current interpretation of date prompt live.
2199 This display will be in an overlay, in the minibuffer."
2200 :group 'org-time
2201 :type 'boolean)
2203 (defcustom org-read-date-popup-calendar t
2204 "Non-nil means, pop up a calendar when prompting for a date.
2205 In the calendar, the date can be selected with mouse-1. However, the
2206 minibuffer will also be active, and you can simply enter the date as well.
2207 When nil, only the minibuffer will be available."
2208 :group 'org-time
2209 :type 'boolean)
2210 (if (fboundp 'defvaralias)
2211 (defvaralias 'org-popup-calendar-for-date-prompt
2212 'org-read-date-popup-calendar))
2214 (defcustom org-read-date-minibuffer-setup-hook nil
2215 "Hook to be used to set up keys for the date/time interface.
2216 Add key definitions to `minibuffer-local-map', which will be a temporary
2217 copy."
2218 :group 'org-time
2219 :type 'hook)
2221 (defcustom org-extend-today-until 0
2222 "The hour when your day really ends. Must be an integer.
2223 This has influence for the following applications:
2224 - When switching the agenda to \"today\". It it is still earlier than
2225 the time given here, the day recognized as TODAY is actually yesterday.
2226 - When a date is read from the user and it is still before the time given
2227 here, the current date and time will be assumed to be yesterday, 23:59.
2228 Also, timestamps inserted in remember templates follow this rule.
2230 IMPORTANT: This is a feature whose implementation is and likely will
2231 remain incomplete. Really, it is only here because past midnight seems to
2232 be the favorite working time of John Wiegley :-)"
2233 :group 'org-time
2234 :type 'integer)
2236 (defcustom org-edit-timestamp-down-means-later nil
2237 "Non-nil means, S-down will increase the time in a time stamp.
2238 When nil, S-up will increase."
2239 :group 'org-time
2240 :type 'boolean)
2242 (defcustom org-calendar-follow-timestamp-change t
2243 "Non-nil means, make the calendar window follow timestamp changes.
2244 When a timestamp is modified and the calendar window is visible, it will be
2245 moved to the new date."
2246 :group 'org-time
2247 :type 'boolean)
2249 (defgroup org-tags nil
2250 "Options concerning tags in Org-mode."
2251 :tag "Org Tags"
2252 :group 'org)
2254 (defcustom org-tag-alist nil
2255 "List of tags allowed in Org-mode files.
2256 When this list is nil, Org-mode will base TAG input on what is already in the
2257 buffer.
2258 The value of this variable is an alist, the car of each entry must be a
2259 keyword as a string, the cdr may be a character that is used to select
2260 that tag through the fast-tag-selection interface.
2261 See the manual for details."
2262 :group 'org-tags
2263 :type '(repeat
2264 (choice
2265 (cons (string :tag "Tag name")
2266 (character :tag "Access char"))
2267 (const :tag "Start radio group" (:startgroup))
2268 (const :tag "End radio group" (:endgroup))
2269 (const :tag "New line" (:newline)))))
2271 (defcustom org-tag-persistent-alist nil
2272 "List of tags that will always appear in all Org-mode files.
2273 This is in addition to any in buffer settings or customizations
2274 of `org-tag-alist'.
2275 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2276 The value of this variable is an alist, the car of each entry must be a
2277 keyword as a string, the cdr may be a character that is used to select
2278 that tag through the fast-tag-selection interface.
2279 See the manual for details.
2280 To disable these tags on a per-file basis, insert anywhere in the file:
2281 #+STARTUP: noptag"
2282 :group 'org-tags
2283 :type '(repeat
2284 (choice
2285 (cons (string :tag "Tag name")
2286 (character :tag "Access char"))
2287 (const :tag "Start radio group" (:startgroup))
2288 (const :tag "End radio group" (:endgroup))
2289 (const :tag "New line" (:newline)))))
2291 (defvar org-file-tags nil
2292 "List of tags that can be inherited by all entries in the file.
2293 The tags will be inherited if the variable `org-use-tag-inheritance'
2294 says they should be.
2295 This variable is populated from #+TAG lines.")
2297 (defcustom org-use-fast-tag-selection 'auto
2298 "Non-nil means, use fast tag selection scheme.
2299 This is a special interface to select and deselect tags with single keys.
2300 When nil, fast selection is never used.
2301 When the symbol `auto', fast selection is used if and only if selection
2302 characters for tags have been configured, either through the variable
2303 `org-tag-alist' or through a #+TAGS line in the buffer.
2304 When t, fast selection is always used and selection keys are assigned
2305 automatically if necessary."
2306 :group 'org-tags
2307 :type '(choice
2308 (const :tag "Always" t)
2309 (const :tag "Never" nil)
2310 (const :tag "When selection characters are configured" 'auto)))
2312 (defcustom org-fast-tag-selection-single-key nil
2313 "Non-nil means, fast tag selection exits after first change.
2314 When nil, you have to press RET to exit it.
2315 During fast tag selection, you can toggle this flag with `C-c'.
2316 This variable can also have the value `expert'. In this case, the window
2317 displaying the tags menu is not even shown, until you press C-c again."
2318 :group 'org-tags
2319 :type '(choice
2320 (const :tag "No" nil)
2321 (const :tag "Yes" t)
2322 (const :tag "Expert" expert)))
2324 (defvar org-fast-tag-selection-include-todo nil
2325 "Non-nil means, fast tags selection interface will also offer TODO states.
2326 This is an undocumented feature, you should not rely on it.")
2328 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2329 "The column to which tags should be indented in a headline.
2330 If this number is positive, it specifies the column. If it is negative,
2331 it means that the tags should be flushright to that column. For example,
2332 -80 works well for a normal 80 character screen."
2333 :group 'org-tags
2334 :type 'integer)
2336 (defcustom org-auto-align-tags t
2337 "Non-nil means, realign tags after pro/demotion of TODO state change.
2338 These operations change the length of a headline and therefore shift
2339 the tags around. With this options turned on, after each such operation
2340 the tags are again aligned to `org-tags-column'."
2341 :group 'org-tags
2342 :type 'boolean)
2344 (defcustom org-use-tag-inheritance t
2345 "Non-nil means, tags in levels apply also for sublevels.
2346 When nil, only the tags directly given in a specific line apply there.
2347 This may also be a list of tags that should be inherited, or a regexp that
2348 matches tags that should be inherited. Additional control is possible
2349 with the variable `org-tags-exclude-from-inheritance' which gives an
2350 explicit list of tags to be excluded from inheritance., even if the value of
2351 `org-use-tag-inheritance' would select it for inheritance.
2353 If this option is t, a match early-on in a tree can lead to a large
2354 number of matches in the subtree when constructing the agenda or creating
2355 a sparse tree. If you only want to see the first match in a tree during
2356 a search, check out the variable `org-tags-match-list-sublevels'."
2357 :group 'org-tags
2358 :type '(choice
2359 (const :tag "Not" nil)
2360 (const :tag "Always" t)
2361 (repeat :tag "Specific tags" (string :tag "Tag"))
2362 (regexp :tag "Tags matched by regexp")))
2364 (defcustom org-tags-exclude-from-inheritance nil
2365 "List of tags that should never be inherited.
2366 This is a way to exclude a few tags from inheritance. For way to do
2367 the opposite, to actively allow inheritance for selected tags,
2368 see the variable `org-use-tag-inheritance'."
2369 :group 'org-tags
2370 :type '(repeat (string :tag "Tag")))
2372 (defun org-tag-inherit-p (tag)
2373 "Check if TAG is one that should be inherited."
2374 (cond
2375 ((member tag org-tags-exclude-from-inheritance) nil)
2376 ((eq org-use-tag-inheritance t) t)
2377 ((not org-use-tag-inheritance) nil)
2378 ((stringp org-use-tag-inheritance)
2379 (string-match org-use-tag-inheritance tag))
2380 ((listp org-use-tag-inheritance)
2381 (member tag org-use-tag-inheritance))
2382 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2384 (defcustom org-tags-match-list-sublevels t
2385 "Non-nil means list also sublevels of headlines matching a search.
2386 This variable applies to tags/property searches, and also to stuck
2387 projects because this search is based on a tags match as well.
2389 When set to the symbol `indented', sublevels are indented with
2390 leading dots.
2392 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2393 the sublevels of a headline matching a tag search often also match
2394 the same search. Listing all of them can create very long lists.
2395 Setting this variable to nil causes subtrees of a match to be skipped.
2397 This variable is semi-obsolete and probably should always be true. It
2398 is better to limit inheritance to certain tags using the variables
2399 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2400 :group 'org-tags
2401 :type '(choice
2402 (const :tag "No, don't list them" nil)
2403 (const :tag "Yes, do list them" t)
2404 (const :tag "List them, indented with leading dots" indented)))
2406 (defcustom org-tags-sort-function nil
2407 "When set, tags are sorted using this function as a comparator"
2408 :group 'org-tags
2409 :type '(choice
2410 (const :tag "No sorting" nil)
2411 (const :tag "Alphabetical" string<)
2412 (const :tag "Reverse alphabetical" string>)
2413 (function :tag "Custom function" nil)))
2415 (defvar org-tags-history nil
2416 "History of minibuffer reads for tags.")
2417 (defvar org-last-tags-completion-table nil
2418 "The last used completion table for tags.")
2419 (defvar org-after-tags-change-hook nil
2420 "Hook that is run after the tags in a line have changed.")
2422 (defgroup org-properties nil
2423 "Options concerning properties in Org-mode."
2424 :tag "Org Properties"
2425 :group 'org)
2427 (defcustom org-property-format "%-10s %s"
2428 "How property key/value pairs should be formatted by `indent-line'.
2429 When `indent-line' hits a property definition, it will format the line
2430 according to this format, mainly to make sure that the values are
2431 lined-up with respect to each other."
2432 :group 'org-properties
2433 :type 'string)
2435 (defcustom org-use-property-inheritance nil
2436 "Non-nil means, properties apply also for sublevels.
2438 This setting is chiefly used during property searches. Turning it on can
2439 cause significant overhead when doing a search, which is why it is not
2440 on by default.
2442 When nil, only the properties directly given in the current entry count.
2443 When t, every property is inherited. The value may also be a list of
2444 properties that should have inheritance, or a regular expression matching
2445 properties that should be inherited.
2447 However, note that some special properties use inheritance under special
2448 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2449 and the properties ending in \"_ALL\" when they are used as descriptor
2450 for valid values of a property.
2452 Note for programmers:
2453 When querying an entry with `org-entry-get', you can control if inheritance
2454 should be used. By default, `org-entry-get' looks only at the local
2455 properties. You can request inheritance by setting the inherit argument
2456 to t (to force inheritance) or to `selective' (to respect the setting
2457 in this variable)."
2458 :group 'org-properties
2459 :type '(choice
2460 (const :tag "Not" nil)
2461 (const :tag "Always" t)
2462 (repeat :tag "Specific properties" (string :tag "Property"))
2463 (regexp :tag "Properties matched by regexp")))
2465 (defun org-property-inherit-p (property)
2466 "Check if PROPERTY is one that should be inherited."
2467 (cond
2468 ((eq org-use-property-inheritance t) t)
2469 ((not org-use-property-inheritance) nil)
2470 ((stringp org-use-property-inheritance)
2471 (string-match org-use-property-inheritance property))
2472 ((listp org-use-property-inheritance)
2473 (member property org-use-property-inheritance))
2474 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2476 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2477 "The default column format, if no other format has been defined.
2478 This variable can be set on the per-file basis by inserting a line
2480 #+COLUMNS: %25ITEM ....."
2481 :group 'org-properties
2482 :type 'string)
2484 (defcustom org-columns-ellipses ".."
2485 "The ellipses to be used when a field in column view is truncated.
2486 When this is the empty string, as many characters as possible are shown,
2487 but then there will be no visual indication that the field has been truncated.
2488 When this is a string of length N, the last N characters of a truncated
2489 field are replaced by this string. If the column is narrower than the
2490 ellipses string, only part of the ellipses string will be shown."
2491 :group 'org-properties
2492 :type 'string)
2494 (defcustom org-columns-modify-value-for-display-function nil
2495 "Function that modifies values for display in column view.
2496 For example, it can be used to cut out a certain part from a time stamp.
2497 The function must take 2 arguments:
2499 column-title The title of the column (*not* the property name)
2500 value The value that should be modified.
2502 The function should return the value that should be displayed,
2503 or nil if the normal value should be used."
2504 :group 'org-properties
2505 :type 'function)
2507 (defcustom org-effort-property "Effort"
2508 "The property that is being used to keep track of effort estimates.
2509 Effort estimates given in this property need to have the format H:MM."
2510 :group 'org-properties
2511 :group 'org-progress
2512 :type '(string :tag "Property"))
2514 (defconst org-global-properties-fixed
2515 '(("VISIBILITY_ALL" . "folded children content all")
2516 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2517 "List of property/value pairs that can be inherited by any entry.
2519 These are fixed values, for the preset properties. The user variable
2520 that can be used to add to this list is `org-global-properties'.
2522 The entries in this list are cons cells where the car is a property
2523 name and cdr is a string with the value. If the value represents
2524 multiple items like an \"_ALL\" property, separate the items by
2525 spaces.")
2527 (defcustom org-global-properties nil
2528 "List of property/value pairs that can be inherited by any entry.
2530 This list will be combined with the constant `org-global-properties-fixed'.
2532 The entries in this list are cons cells where the car is a property
2533 name and cdr is a string with the value.
2535 You can set buffer-local values for the same purpose in the variable
2536 `org-file-properties' this by adding lines like
2538 #+PROPERTY: NAME VALUE"
2539 :group 'org-properties
2540 :type '(repeat
2541 (cons (string :tag "Property")
2542 (string :tag "Value"))))
2544 (defvar org-file-properties nil
2545 "List of property/value pairs that can be inherited by any entry.
2546 Valid for the current buffer.
2547 This variable is populated from #+PROPERTY lines.")
2548 (make-variable-buffer-local 'org-file-properties)
2550 (defgroup org-agenda nil
2551 "Options concerning agenda views in Org-mode."
2552 :tag "Org Agenda"
2553 :group 'org)
2555 (defvar org-category nil
2556 "Variable used by org files to set a category for agenda display.
2557 Such files should use a file variable to set it, for example
2559 # -*- mode: org; org-category: \"ELisp\"
2561 or contain a special line
2563 #+CATEGORY: ELisp
2565 If the file does not specify a category, then file's base name
2566 is used instead.")
2567 (make-variable-buffer-local 'org-category)
2568 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2570 (defcustom org-agenda-files nil
2571 "The files to be used for agenda display.
2572 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2573 \\[org-remove-file]. You can also use customize to edit the list.
2575 If an entry is a directory, all files in that directory that are matched by
2576 `org-agenda-file-regexp' will be part of the file list.
2578 If the value of the variable is not a list but a single file name, then
2579 the list of agenda files is actually stored and maintained in that file, one
2580 agenda file per line."
2581 :group 'org-agenda
2582 :type '(choice
2583 (repeat :tag "List of files and directories" file)
2584 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2586 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2587 "Regular expression to match files for `org-agenda-files'.
2588 If any element in the list in that variable contains a directory instead
2589 of a normal file, all files in that directory that are matched by this
2590 regular expression will be included."
2591 :group 'org-agenda
2592 :type 'regexp)
2594 (defcustom org-agenda-text-search-extra-files nil
2595 "List of extra files to be searched by text search commands.
2596 These files will be search in addition to the agenda files by the
2597 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2598 Note that these files will only be searched for text search commands,
2599 not for the other agenda views like todo lists, tag searches or the weekly
2600 agenda. This variable is intended to list notes and possibly archive files
2601 that should also be searched by these two commands.
2602 In fact, if the first element in the list is the symbol `agenda-archives',
2603 than all archive files of all agenda files will be added to the search
2604 scope."
2605 :group 'org-agenda
2606 :type '(set :greedy t
2607 (const :tag "Agenda Archives" agenda-archives)
2608 (repeat :inline t (file))))
2610 (if (fboundp 'defvaralias)
2611 (defvaralias 'org-agenda-multi-occur-extra-files
2612 'org-agenda-text-search-extra-files))
2614 (defcustom org-agenda-skip-unavailable-files nil
2615 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2616 A nil value means to remove them, after a query, from the list."
2617 :group 'org-agenda
2618 :type 'boolean)
2620 (defcustom org-calendar-to-agenda-key [?c]
2621 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2622 The command `org-calendar-goto-agenda' will be bound to this key. The
2623 default is the character `c' because then `c' can be used to switch back and
2624 forth between agenda and calendar."
2625 :group 'org-agenda
2626 :type 'sexp)
2628 (defcustom org-calendar-agenda-action-key [?k]
2629 "The key to be installed in `calendar-mode-map' for agenda-action.
2630 The command `org-agenda-action' will be bound to this key. The
2631 default is the character `k' because we use the same key in the agenda."
2632 :group 'org-agenda
2633 :type 'sexp)
2635 (eval-after-load "calendar"
2636 '(progn
2637 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2638 'org-calendar-goto-agenda)
2639 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2640 'org-agenda-action)))
2642 (defgroup org-latex nil
2643 "Options for embedding LaTeX code into Org-mode."
2644 :tag "Org LaTeX"
2645 :group 'org)
2647 (defcustom org-format-latex-options
2648 '(:foreground default :background default :scale 1.0
2649 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2650 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2651 "Options for creating images from LaTeX fragments.
2652 This is a property list with the following properties:
2653 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2654 `default' means use the foreground of the default face.
2655 :background the background color, or \"Transparent\".
2656 `default' means use the background of the default face.
2657 :scale a scaling factor for the size of the images.
2658 :html-foreground, :html-background, :html-scale
2659 the same numbers for HTML export.
2660 :matchers a list indicating which matchers should be used to
2661 find LaTeX fragments. Valid members of this list are:
2662 \"begin\" find environments
2663 \"$1\" find single characters surrounded by $.$
2664 \"$\" find math expressions surrounded by $...$
2665 \"$$\" find math expressions surrounded by $$....$$
2666 \"\\(\" find math expressions surrounded by \\(...\\)
2667 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2668 :group 'org-latex
2669 :type 'plist)
2671 (defcustom org-format-latex-header "\\documentclass{article}
2672 \\usepackage{fullpage} % do not remove
2673 \\usepackage{amssymb}
2674 \\usepackage[usenames]{color}
2675 \\usepackage{amsmath}
2676 \\usepackage{latexsym}
2677 \\usepackage[mathscr]{eucal}
2678 \\pagestyle{empty} % do not remove"
2679 "The document header used for processing LaTeX fragments."
2680 :group 'org-latex
2681 :type 'string)
2684 (defgroup org-font-lock nil
2685 "Font-lock settings for highlighting in Org-mode."
2686 :tag "Org Font Lock"
2687 :group 'org)
2689 (defcustom org-level-color-stars-only nil
2690 "Non-nil means fontify only the stars in each headline.
2691 When nil, the entire headline is fontified.
2692 Changing it requires restart of `font-lock-mode' to become effective
2693 also in regions already fontified."
2694 :group 'org-font-lock
2695 :type 'boolean)
2697 (defcustom org-hide-leading-stars nil
2698 "Non-nil means, hide the first N-1 stars in a headline.
2699 This works by using the face `org-hide' for these stars. This
2700 face is white for a light background, and black for a dark
2701 background. You may have to customize the face `org-hide' to
2702 make this work.
2703 Changing it requires restart of `font-lock-mode' to become effective
2704 also in regions already fontified.
2705 You may also set this on a per-file basis by adding one of the following
2706 lines to the buffer:
2708 #+STARTUP: hidestars
2709 #+STARTUP: showstars"
2710 :group 'org-font-lock
2711 :type 'boolean)
2713 (defcustom org-fontify-done-headline nil
2714 "Non-nil means, change the face of a headline if it is marked DONE.
2715 Normally, only the TODO/DONE keyword indicates the state of a headline.
2716 When this is non-nil, the headline after the keyword is set to the
2717 `org-headline-done' as an additional indication."
2718 :group 'org-font-lock
2719 :type 'boolean)
2721 (defcustom org-fontify-emphasized-text t
2722 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2723 Changing this variable requires a restart of Emacs to take effect."
2724 :group 'org-font-lock
2725 :type 'boolean)
2727 (defcustom org-fontify-whole-heading-line nil
2728 "Non-nil means fontify the whole line for headings.
2729 This is useful when setting a background color for the
2730 org-leve-* faces."
2731 :group 'org-font-lock
2732 :type 'boolean)
2734 (defcustom org-highlight-latex-fragments-and-specials nil
2735 "Non-nil means, fontify what is treated specially by the exporters."
2736 :group 'org-font-lock
2737 :type 'boolean)
2739 (defcustom org-hide-emphasis-markers nil
2740 "Non-nil mean font-lock should hide the emphasis marker characters."
2741 :group 'org-font-lock
2742 :type 'boolean)
2744 (defvar org-emph-re nil
2745 "Regular expression for matching emphasis.")
2746 (defvar org-verbatim-re nil
2747 "Regular expression for matching verbatim text.")
2748 (defvar org-emphasis-regexp-components) ; defined just below
2749 (defvar org-emphasis-alist) ; defined just below
2750 (defun org-set-emph-re (var val)
2751 "Set variable and compute the emphasis regular expression."
2752 (set var val)
2753 (when (and (boundp 'org-emphasis-alist)
2754 (boundp 'org-emphasis-regexp-components)
2755 org-emphasis-alist org-emphasis-regexp-components)
2756 (let* ((e org-emphasis-regexp-components)
2757 (pre (car e))
2758 (post (nth 1 e))
2759 (border (nth 2 e))
2760 (body (nth 3 e))
2761 (nl (nth 4 e))
2762 (body1 (concat body "*?"))
2763 (markers (mapconcat 'car org-emphasis-alist ""))
2764 (vmarkers (mapconcat
2765 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2766 org-emphasis-alist "")))
2767 ;; make sure special characters appear at the right position in the class
2768 (if (string-match "\\^" markers)
2769 (setq markers (concat (replace-match "" t t markers) "^")))
2770 (if (string-match "-" markers)
2771 (setq markers (concat (replace-match "" t t markers) "-")))
2772 (if (string-match "\\^" vmarkers)
2773 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2774 (if (string-match "-" vmarkers)
2775 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2776 (if (> nl 0)
2777 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2778 (int-to-string nl) "\\}")))
2779 ;; Make the regexp
2780 (setq org-emph-re
2781 (concat "\\([" pre "]\\|^\\)"
2782 "\\("
2783 "\\([" markers "]\\)"
2784 "\\("
2785 "[^" border "]\\|"
2786 "[^" border "]"
2787 body1
2788 "[^" border "]"
2789 "\\)"
2790 "\\3\\)"
2791 "\\([" post "]\\|$\\)"))
2792 (setq org-verbatim-re
2793 (concat "\\([" pre "]\\|^\\)"
2794 "\\("
2795 "\\([" vmarkers "]\\)"
2796 "\\("
2797 "[^" border "]\\|"
2798 "[^" border "]"
2799 body1
2800 "[^" border "]"
2801 "\\)"
2802 "\\3\\)"
2803 "\\([" post "]\\|$\\)")))))
2805 (defcustom org-emphasis-regexp-components
2806 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2807 "Components used to build the regular expression for emphasis.
2808 This is a list with 6 entries. Terminology: In an emphasis string
2809 like \" *strong word* \", we call the initial space PREMATCH, the final
2810 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2811 and \"trong wor\" is the body. The different components in this variable
2812 specify what is allowed/forbidden in each part:
2814 pre Chars allowed as prematch. Beginning of line will be allowed too.
2815 post Chars allowed as postmatch. End of line will be allowed too.
2816 border The chars *forbidden* as border characters.
2817 body-regexp A regexp like \".\" to match a body character. Don't use
2818 non-shy groups here, and don't allow newline here.
2819 newline The maximum number of newlines allowed in an emphasis exp.
2821 Use customize to modify this, or restart Emacs after changing it."
2822 :group 'org-font-lock
2823 :set 'org-set-emph-re
2824 :type '(list
2825 (sexp :tag "Allowed chars in pre ")
2826 (sexp :tag "Allowed chars in post ")
2827 (sexp :tag "Forbidden chars in border ")
2828 (sexp :tag "Regexp for body ")
2829 (integer :tag "number of newlines allowed")
2830 (option (boolean :tag "Please ignore this button"))))
2832 (defcustom org-emphasis-alist
2833 `(("*" bold "<b>" "</b>")
2834 ("/" italic "<i>" "</i>")
2835 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2836 ("=" org-code "<code>" "</code>" verbatim)
2837 ("~" org-verbatim "<code>" "</code>" verbatim)
2838 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2839 "<del>" "</del>")
2841 "Special syntax for emphasized text.
2842 Text starting and ending with a special character will be emphasized, for
2843 example *bold*, _underlined_ and /italic/. This variable sets the marker
2844 characters, the face to be used by font-lock for highlighting in Org-mode
2845 Emacs buffers, and the HTML tags to be used for this.
2846 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2847 Use customize to modify this, or restart Emacs after changing it."
2848 :group 'org-font-lock
2849 :set 'org-set-emph-re
2850 :type '(repeat
2851 (list
2852 (string :tag "Marker character")
2853 (choice
2854 (face :tag "Font-lock-face")
2855 (plist :tag "Face property list"))
2856 (string :tag "HTML start tag")
2857 (string :tag "HTML end tag")
2858 (option (const verbatim)))))
2860 (defvar org-protecting-blocks
2861 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2862 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2863 This is needed for font-lock setup.")
2865 ;;; Miscellaneous options
2867 (defgroup org-completion nil
2868 "Completion in Org-mode."
2869 :tag "Org Completion"
2870 :group 'org)
2872 (defcustom org-completion-use-ido nil
2873 "Non-nil means, use ido completion wherever possible.
2874 Note that `ido-mode' must be active for this variable to be relevant.
2875 If you decide to turn this variable on, you might well want to turn off
2876 `org-outline-path-complete-in-steps'.
2877 See also `org-completion-use-iswitchb'."
2878 :group 'org-completion
2879 :type 'boolean)
2881 (defcustom org-completion-use-iswitchb nil
2882 "Non-nil means, use iswitchb completion wherever possible.
2883 Note that `iswitchb-mode' must be active for this variable to be relevant.
2884 If you decide to turn this variable on, you might well want to turn off
2885 `org-outline-path-complete-in-steps'.
2886 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2887 :group 'org-completion
2888 :type 'boolean)
2890 (defcustom org-completion-fallback-command 'hippie-expand
2891 "The expansion command called by \\[org-complete] in normal context.
2892 Normal means, no org-mode-specific context."
2893 :group 'org-completion
2894 :type 'function)
2896 ;;; Functions and variables from ther packages
2897 ;; Declared here to avoid compiler warnings
2899 ;; XEmacs only
2900 (defvar outline-mode-menu-heading)
2901 (defvar outline-mode-menu-show)
2902 (defvar outline-mode-menu-hide)
2903 (defvar zmacs-regions) ; XEmacs regions
2905 ;; Emacs only
2906 (defvar mark-active)
2908 ;; Various packages
2909 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2910 (declare-function calendar-forward-day "cal-move" (arg))
2911 (declare-function calendar-goto-date "cal-move" (date))
2912 (declare-function calendar-goto-today "cal-move" ())
2913 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2914 (defvar calc-embedded-close-formula)
2915 (defvar calc-embedded-open-formula)
2916 (declare-function cdlatex-tab "ext:cdlatex" ())
2917 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2918 (defvar font-lock-unfontify-region-function)
2919 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2920 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2921 (defvar iswitchb-temp-buflist)
2922 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2923 (defvar org-agenda-tags-todo-honor-ignore-options)
2924 (declare-function org-agenda-skip "org-agenda" ())
2925 (declare-function org-format-agenda-item "org-agenda"
2926 (extra txt &optional category tags dotime noprefix remove-re))
2927 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2928 (declare-function org-agenda-change-all-lines "org-agenda"
2929 (newhead hdmarker &optional fixface just-this))
2930 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2931 (declare-function org-agenda-maybe-redo "org-agenda" ())
2932 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2933 (beg end))
2934 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2935 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2936 "org-agenda" (&optional end))
2937 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2938 (declare-function org-indent-mode "org-indent" (arg))
2939 (declare-function parse-time-string "parse-time" (string))
2940 (declare-function remember "remember" (&optional initial))
2941 (declare-function remember-buffer-desc "remember" ())
2942 (declare-function remember-finalize "remember" ())
2943 (defvar remember-save-after-remembering)
2944 (defvar remember-data-file)
2945 (defvar remember-register)
2946 (defvar remember-buffer)
2947 (defvar remember-handler-functions)
2948 (defvar remember-annotation-functions)
2949 (defvar texmathp-why)
2950 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2951 (declare-function table--at-cell-p "table" (position &optional object at-column))
2953 (defvar w3m-current-url)
2954 (defvar w3m-current-title)
2956 (defvar org-latex-regexps)
2958 ;;; Autoload and prepare some org modules
2960 ;; Some table stuff that needs to be defined here, because it is used
2961 ;; by the functions setting up org-mode or checking for table context.
2963 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2964 "Detects an org-type or table-type table.")
2965 (defconst org-table-line-regexp "^[ \t]*|"
2966 "Detects an org-type table line.")
2967 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2968 "Detects an org-type table line.")
2969 (defconst org-table-hline-regexp "^[ \t]*|-"
2970 "Detects an org-type table hline.")
2971 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2972 "Detects a table-type table hline.")
2973 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2974 "Searching from within a table (any type) this finds the first line
2975 outside the table.")
2977 ;; Autoload the functions in org-table.el that are needed by functions here.
2979 (eval-and-compile
2980 (org-autoload "org-table"
2981 '(org-table-align org-table-begin org-table-blank-field
2982 org-table-convert org-table-convert-region org-table-copy-down
2983 org-table-copy-region org-table-create
2984 org-table-create-or-convert-from-region
2985 org-table-create-with-table.el org-table-current-dline
2986 org-table-cut-region org-table-delete-column org-table-edit-field
2987 org-table-edit-formulas org-table-end org-table-eval-formula
2988 org-table-export org-table-field-info
2989 org-table-get-stored-formulas org-table-goto-column
2990 org-table-hline-and-move org-table-import org-table-insert-column
2991 org-table-insert-hline org-table-insert-row org-table-iterate
2992 org-table-justify-field-maybe org-table-kill-row
2993 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2994 org-table-move-column org-table-move-column-left
2995 org-table-move-column-right org-table-move-row
2996 org-table-move-row-down org-table-move-row-up
2997 org-table-next-field org-table-next-row org-table-paste-rectangle
2998 org-table-previous-field org-table-recalculate
2999 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3000 org-table-toggle-coordinate-overlays
3001 org-table-toggle-formula-debugger org-table-wrap-region
3002 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3004 (defun org-at-table-p (&optional table-type)
3005 "Return t if the cursor is inside an org-type table.
3006 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3007 (if org-enable-table-editor
3008 (save-excursion
3009 (beginning-of-line 1)
3010 (looking-at (if table-type org-table-any-line-regexp
3011 org-table-line-regexp)))
3012 nil))
3013 (defsubst org-table-p () (org-at-table-p))
3015 (defun org-at-table.el-p ()
3016 "Return t if and only if we are at a table.el table."
3017 (and (org-at-table-p 'any)
3018 (save-excursion
3019 (goto-char (org-table-begin 'any))
3020 (looking-at org-table1-hline-regexp))))
3021 (defun org-table-recognize-table.el ()
3022 "If there is a table.el table nearby, recognize it and move into it."
3023 (if org-table-tab-recognizes-table.el
3024 (if (org-at-table.el-p)
3025 (progn
3026 (beginning-of-line 1)
3027 (if (looking-at org-table-dataline-regexp)
3029 (if (looking-at org-table1-hline-regexp)
3030 (progn
3031 (beginning-of-line 2)
3032 (if (looking-at org-table-any-border-regexp)
3033 (beginning-of-line -1)))))
3034 (if (re-search-forward "|" (org-table-end t) t)
3035 (progn
3036 (require 'table)
3037 (if (table--at-cell-p (point))
3039 (message "recognizing table.el table...")
3040 (table-recognize-table)
3041 (message "recognizing table.el table...done")))
3042 (error "This should not happen..."))
3044 nil)
3045 nil))
3047 (defun org-at-table-hline-p ()
3048 "Return t if the cursor is inside a hline in a table."
3049 (if org-enable-table-editor
3050 (save-excursion
3051 (beginning-of-line 1)
3052 (looking-at org-table-hline-regexp))
3053 nil))
3055 (defvar org-table-clean-did-remove-column nil)
3057 (defun org-table-map-tables (function)
3058 "Apply FUNCTION to the start of all tables in the buffer."
3059 (save-excursion
3060 (save-restriction
3061 (widen)
3062 (goto-char (point-min))
3063 (while (re-search-forward org-table-any-line-regexp nil t)
3064 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3065 (beginning-of-line 1)
3066 (when (looking-at org-table-line-regexp)
3067 (save-excursion (funcall function))
3068 (or (looking-at org-table-line-regexp)
3069 (forward-char 1)))
3070 (re-search-forward org-table-any-border-regexp nil 1))))
3071 (message "Mapping tables: done"))
3073 ;; Declare and autoload functions from org-exp.el & Co
3075 (declare-function org-default-export-plist "org-exp")
3076 (declare-function org-infile-export-plist "org-exp")
3077 (declare-function org-get-current-options "org-exp")
3078 (eval-and-compile
3079 (org-autoload "org-exp"
3080 '(org-export org-export-visible
3081 org-insert-export-options-template
3082 org-table-clean-before-export))
3083 (org-autoload "org-ascii"
3084 '(org-export-as-ascii org-export-ascii-preprocess
3085 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3086 org-export-region-as-ascii))
3087 (org-autoload "org-html"
3088 '(org-export-as-html-and-open
3089 org-export-as-html-batch org-export-as-html-to-buffer
3090 org-replace-region-by-html org-export-region-as-html
3091 org-export-as-html))
3092 (org-autoload "org-icalendar"
3093 '(org-export-icalendar-this-file
3094 org-export-icalendar-all-agenda-files
3095 org-export-icalendar-combine-agenda-files))
3096 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3098 ;; Declare and autoload functions from org-agenda.el
3100 (eval-and-compile
3101 (org-autoload "org-agenda"
3102 '(org-agenda org-agenda-list org-search-view
3103 org-todo-list org-tags-view org-agenda-list-stuck-projects
3104 org-diary org-agenda-to-appt
3105 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3107 ;; Autoload org-remember
3109 (eval-and-compile
3110 (org-autoload "org-remember"
3111 '(org-remember-insinuate org-remember-annotation
3112 org-remember-apply-template org-remember org-remember-handler)))
3114 ;; Autoload org-clock.el
3117 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3118 (beg end))
3119 (declare-function org-clock-update-mode-line "org-clock" ())
3120 (defvar org-clock-start-time)
3121 (defvar org-clock-marker (make-marker)
3122 "Marker recording the last clock-in.")
3123 (defvar org-clock-hd-marker (make-marker)
3124 "Marker recording the last clock-in, but the headline position.")
3125 (defun org-clock-is-active ()
3126 "Return non-nil if clock is currently running.
3127 The return value is actually the clock marker."
3128 (marker-buffer org-clock-marker))
3130 (eval-and-compile
3131 (org-autoload
3132 "org-clock"
3133 '(org-clock-in org-clock-out org-clock-cancel
3134 org-clock-goto org-clock-sum org-clock-display
3135 org-clock-remove-overlays org-clock-report
3136 org-clocktable-shift org-dblock-write:clocktable
3137 org-get-clocktable)))
3139 (defun org-clock-update-time-maybe ()
3140 "If this is a CLOCK line, update it and return t.
3141 Otherwise, return nil."
3142 (interactive)
3143 (save-excursion
3144 (beginning-of-line 1)
3145 (skip-chars-forward " \t")
3146 (when (looking-at org-clock-string)
3147 (let ((re (concat "[ \t]*" org-clock-string
3148 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3149 "\\([ \t]*=>.*\\)?\\)?"))
3150 ts te h m s neg)
3151 (cond
3152 ((not (looking-at re))
3153 nil)
3154 ((not (match-end 2))
3155 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3156 (> org-clock-marker (point))
3157 (<= org-clock-marker (point-at-eol)))
3158 ;; The clock is running here
3159 (setq org-clock-start-time
3160 (apply 'encode-time
3161 (org-parse-time-string (match-string 1))))
3162 (org-clock-update-mode-line)))
3164 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3165 (end-of-line 1)
3166 (setq ts (match-string 1)
3167 te (match-string 3))
3168 (setq s (- (org-float-time
3169 (apply 'encode-time (org-parse-time-string te)))
3170 (org-float-time
3171 (apply 'encode-time (org-parse-time-string ts))))
3172 neg (< s 0)
3173 s (abs s)
3174 h (floor (/ s 3600))
3175 s (- s (* 3600 h))
3176 m (floor (/ s 60))
3177 s (- s (* 60 s)))
3178 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3179 t))))))
3181 (defun org-check-running-clock ()
3182 "Check if the current buffer contains the running clock.
3183 If yes, offer to stop it and to save the buffer with the changes."
3184 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3185 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3186 (buffer-name))))
3187 (org-clock-out)
3188 (when (y-or-n-p "Save changed buffer?")
3189 (save-buffer))))
3191 (defun org-clocktable-try-shift (dir n)
3192 "Check if this line starts a clock table, if yes, shift the time block."
3193 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3194 (org-clocktable-shift dir n)))
3196 ;; Autoload org-timer.el
3198 (eval-and-compile
3199 (org-autoload
3200 "org-timer"
3201 '(org-timer-start org-timer org-timer-item
3202 org-timer-change-times-in-region
3203 org-timer-set-timer
3204 org-timer-reset-timers
3205 org-timer-show-remaining-time)))
3207 ;; Autoload org-feed.el
3209 (eval-and-compile
3210 (org-autoload
3211 "org-feed"
3212 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3215 ;; Autoload org-indent.el
3217 (eval-and-compile
3218 (org-autoload
3219 "org-indent"
3220 '(org-indent-mode)))
3222 ;; Autoload archiving code
3223 ;; The stuff that is needed for cycling and tags has to be defined here.
3225 (defgroup org-archive nil
3226 "Options concerning archiving in Org-mode."
3227 :tag "Org Archive"
3228 :group 'org-structure)
3230 (defcustom org-archive-location "%s_archive::"
3231 "The location where subtrees should be archived.
3233 The value of this variable is a string, consisting of two parts,
3234 separated by a double-colon. The first part is a filename and
3235 the second part is a headline.
3237 When the filename is omitted, archiving happens in the same file.
3238 %s in the filename will be replaced by the current file
3239 name (without the directory part). Archiving to a different file
3240 is useful to keep archived entries from contributing to the
3241 Org-mode Agenda.
3243 The archived entries will be filed as subtrees of the specified
3244 headline. When the headline is omitted, the subtrees are simply
3245 filed away at the end of the file, as top-level entries. Also in
3246 the heading you can use %s to represent the file name, this can be
3247 useful when using the same archive for a number of different files.
3249 Here are a few examples:
3250 \"%s_archive::\"
3251 If the current file is Projects.org, archive in file
3252 Projects.org_archive, as top-level trees. This is the default.
3254 \"::* Archived Tasks\"
3255 Archive in the current file, under the top-level headline
3256 \"* Archived Tasks\".
3258 \"~/org/archive.org::\"
3259 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3261 \"~/org/archive.org::From %s\"
3262 Archive in file ~/org/archive.org (absolute path), und headlines
3263 \"From FILENAME\" where file name is the current file name.
3265 \"basement::** Finished Tasks\"
3266 Archive in file ./basement (relative path), as level 3 trees
3267 below the level 2 heading \"** Finished Tasks\".
3269 You may set this option on a per-file basis by adding to the buffer a
3270 line like
3272 #+ARCHIVE: basement::** Finished Tasks
3274 You may also define it locally for a subtree by setting an ARCHIVE property
3275 in the entry. If such a property is found in an entry, or anywhere up
3276 the hierarchy, it will be used."
3277 :group 'org-archive
3278 :type 'string)
3280 (defcustom org-archive-tag "ARCHIVE"
3281 "The tag that marks a subtree as archived.
3282 An archived subtree does not open during visibility cycling, and does
3283 not contribute to the agenda listings.
3284 After changing this, font-lock must be restarted in the relevant buffers to
3285 get the proper fontification."
3286 :group 'org-archive
3287 :group 'org-keywords
3288 :type 'string)
3290 (defcustom org-agenda-skip-archived-trees t
3291 "Non-nil means, the agenda will skip any items located in archived trees.
3292 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3293 variable is no longer recommended, you should leave it at the value t.
3294 Instead, use the key `v' to cycle the archives-mode in the agenda."
3295 :group 'org-archive
3296 :group 'org-agenda-skip
3297 :type 'boolean)
3299 (defcustom org-columns-skip-arrchived-trees t
3300 "Non-nil means, irgnore archived trees when creating column view."
3301 :group 'org-archive
3302 :group 'org-properties
3303 :type 'boolean)
3305 (defcustom org-cycle-open-archived-trees nil
3306 "Non-nil means, `org-cycle' will open archived trees.
3307 An archived tree is a tree marked with the tag ARCHIVE.
3308 When nil, archived trees will stay folded. You can still open them with
3309 normal outline commands like `show-all', but not with the cycling commands."
3310 :group 'org-archive
3311 :group 'org-cycle
3312 :type 'boolean)
3314 (defcustom org-sparse-tree-open-archived-trees nil
3315 "Non-nil means sparse tree construction shows matches in archived trees.
3316 When nil, matches in these trees are highlighted, but the trees are kept in
3317 collapsed state."
3318 :group 'org-archive
3319 :group 'org-sparse-trees
3320 :type 'boolean)
3322 (defun org-cycle-hide-archived-subtrees (state)
3323 "Re-hide all archived subtrees after a visibility state change."
3324 (when (and (not org-cycle-open-archived-trees)
3325 (not (memq state '(overview folded))))
3326 (save-excursion
3327 (let* ((globalp (memq state '(contents all)))
3328 (beg (if globalp (point-min) (point)))
3329 (end (if globalp (point-max) (org-end-of-subtree t))))
3330 (org-hide-archived-subtrees beg end)
3331 (goto-char beg)
3332 (if (looking-at (concat ".*:" org-archive-tag ":"))
3333 (message "%s" (substitute-command-keys
3334 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3336 (defun org-force-cycle-archived ()
3337 "Cycle subtree even if it is archived."
3338 (interactive)
3339 (setq this-command 'org-cycle)
3340 (let ((org-cycle-open-archived-trees t))
3341 (call-interactively 'org-cycle)))
3343 (defun org-hide-archived-subtrees (beg end)
3344 "Re-hide all archived subtrees after a visibility state change."
3345 (save-excursion
3346 (let* ((re (concat ":" org-archive-tag ":")))
3347 (goto-char beg)
3348 (while (re-search-forward re end t)
3349 (and (org-on-heading-p) (hide-subtree))
3350 (org-end-of-subtree t)))))
3352 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3354 (eval-and-compile
3355 (org-autoload "org-archive"
3356 '(org-add-archive-files org-archive-subtree
3357 org-archive-to-archive-sibling org-toggle-archive-tag)))
3359 ;; Autoload Column View Code
3361 (declare-function org-columns-number-to-string "org-colview")
3362 (declare-function org-columns-get-format-and-top-level "org-colview")
3363 (declare-function org-columns-compute "org-colview")
3365 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3366 '(org-columns-number-to-string org-columns-get-format-and-top-level
3367 org-columns-compute org-agenda-columns org-columns-remove-overlays
3368 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3370 ;; Autoload ID code
3372 (declare-function org-id-store-link "org-id")
3373 (declare-function org-id-locations-load "org-id")
3374 (declare-function org-id-locations-save "org-id")
3375 (defvar org-id-track-globally)
3376 (org-autoload "org-id"
3377 '(org-id-get-create org-id-new org-id-copy org-id-get
3378 org-id-get-with-outline-path-completion
3379 org-id-get-with-outline-drilling
3380 org-id-goto org-id-find org-id-store-link))
3382 ;; Autoload Plotting Code
3384 (org-autoload "org-plot"
3385 '(org-plot/gnuplot))
3387 ;;; Variables for pre-computed regular expressions, all buffer local
3389 (defvar org-drawer-regexp nil
3390 "Matches first line of a hidden block.")
3391 (make-variable-buffer-local 'org-drawer-regexp)
3392 (defvar org-todo-regexp nil
3393 "Matches any of the TODO state keywords.")
3394 (make-variable-buffer-local 'org-todo-regexp)
3395 (defvar org-not-done-regexp nil
3396 "Matches any of the TODO state keywords except the last one.")
3397 (make-variable-buffer-local 'org-not-done-regexp)
3398 (defvar org-not-done-heading-regexp nil
3399 "Matches a TODO headline that is not done.")
3400 (make-variable-buffer-local 'org-not-done-regexp)
3401 (defvar org-todo-line-regexp nil
3402 "Matches a headline and puts TODO state into group 2 if present.")
3403 (make-variable-buffer-local 'org-todo-line-regexp)
3404 (defvar org-complex-heading-regexp nil
3405 "Matches a headline and puts everything into groups:
3406 group 1: the stars
3407 group 2: The todo keyword, maybe
3408 group 3: Priority cookie
3409 group 4: True headline
3410 group 5: Tags")
3411 (make-variable-buffer-local 'org-complex-heading-regexp)
3412 (defvar org-todo-line-tags-regexp nil
3413 "Matches a headline and puts TODO state into group 2 if present.
3414 Also put tags into group 4 if tags are present.")
3415 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3416 (defvar org-nl-done-regexp nil
3417 "Matches newline followed by a headline with the DONE keyword.")
3418 (make-variable-buffer-local 'org-nl-done-regexp)
3419 (defvar org-looking-at-done-regexp nil
3420 "Matches the DONE keyword a point.")
3421 (make-variable-buffer-local 'org-looking-at-done-regexp)
3422 (defvar org-ds-keyword-length 12
3423 "Maximum length of the Deadline and SCHEDULED keywords.")
3424 (make-variable-buffer-local 'org-ds-keyword-length)
3425 (defvar org-deadline-regexp nil
3426 "Matches the DEADLINE keyword.")
3427 (make-variable-buffer-local 'org-deadline-regexp)
3428 (defvar org-deadline-time-regexp nil
3429 "Matches the DEADLINE keyword together with a time stamp.")
3430 (make-variable-buffer-local 'org-deadline-time-regexp)
3431 (defvar org-deadline-line-regexp nil
3432 "Matches the DEADLINE keyword and the rest of the line.")
3433 (make-variable-buffer-local 'org-deadline-line-regexp)
3434 (defvar org-scheduled-regexp nil
3435 "Matches the SCHEDULED keyword.")
3436 (make-variable-buffer-local 'org-scheduled-regexp)
3437 (defvar org-scheduled-time-regexp nil
3438 "Matches the SCHEDULED keyword together with a time stamp.")
3439 (make-variable-buffer-local 'org-scheduled-time-regexp)
3440 (defvar org-closed-time-regexp nil
3441 "Matches the CLOSED keyword together with a time stamp.")
3442 (make-variable-buffer-local 'org-closed-time-regexp)
3444 (defvar org-keyword-time-regexp nil
3445 "Matches any of the 4 keywords, together with the time stamp.")
3446 (make-variable-buffer-local 'org-keyword-time-regexp)
3447 (defvar org-keyword-time-not-clock-regexp nil
3448 "Matches any of the 3 keywords, together with the time stamp.")
3449 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3450 (defvar org-maybe-keyword-time-regexp nil
3451 "Matches a timestamp, possibly preceeded by a keyword.")
3452 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3453 (defvar org-planning-or-clock-line-re nil
3454 "Matches a line with planning or clock info.")
3455 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3457 (defconst org-plain-time-of-day-regexp
3458 (concat
3459 "\\(\\<[012]?[0-9]"
3460 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3461 "\\(--?"
3462 "\\(\\<[012]?[0-9]"
3463 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3464 "\\)?")
3465 "Regular expression to match a plain time or time range.
3466 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3467 groups carry important information:
3468 0 the full match
3469 1 the first time, range or not
3470 8 the second time, if it is a range.")
3472 (defconst org-plain-time-extension-regexp
3473 (concat
3474 "\\(\\<[012]?[0-9]"
3475 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3476 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3477 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3478 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3479 groups carry important information:
3480 0 the full match
3481 7 hours of duration
3482 9 minutes of duration")
3484 (defconst org-stamp-time-of-day-regexp
3485 (concat
3486 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3487 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3488 "\\(--?"
3489 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3490 "Regular expression to match a timestamp time or time range.
3491 After a match, the following groups carry important information:
3492 0 the full match
3493 1 date plus weekday, for backreferencing to make sure both times on same day
3494 2 the first time, range or not
3495 4 the second time, if it is a range.")
3497 (defconst org-startup-options
3498 '(("fold" org-startup-folded t)
3499 ("overview" org-startup-folded t)
3500 ("nofold" org-startup-folded nil)
3501 ("showall" org-startup-folded nil)
3502 ("content" org-startup-folded content)
3503 ("indent" org-startup-indented t)
3504 ("noindent" org-startup-indented nil)
3505 ("hidestars" org-hide-leading-stars t)
3506 ("showstars" org-hide-leading-stars nil)
3507 ("odd" org-odd-levels-only t)
3508 ("oddeven" org-odd-levels-only nil)
3509 ("align" org-startup-align-all-tables t)
3510 ("noalign" org-startup-align-all-tables nil)
3511 ("customtime" org-display-custom-times t)
3512 ("logdone" org-log-done time)
3513 ("lognotedone" org-log-done note)
3514 ("nologdone" org-log-done nil)
3515 ("lognoteclock-out" org-log-note-clock-out t)
3516 ("nolognoteclock-out" org-log-note-clock-out nil)
3517 ("logrepeat" org-log-repeat state)
3518 ("lognoterepeat" org-log-repeat note)
3519 ("nologrepeat" org-log-repeat nil)
3520 ("fninline" org-footnote-define-inline t)
3521 ("nofninline" org-footnote-define-inline nil)
3522 ("fnlocal" org-footnote-section nil)
3523 ("fnauto" org-footnote-auto-label t)
3524 ("fnprompt" org-footnote-auto-label nil)
3525 ("fnconfirm" org-footnote-auto-label confirm)
3526 ("fnplain" org-footnote-auto-label plain)
3527 ("fnadjust" org-footnote-auto-adjust t)
3528 ("nofnadjust" org-footnote-auto-adjust nil)
3529 ("constcgs" constants-unit-system cgs)
3530 ("constSI" constants-unit-system SI)
3531 ("noptag" org-tag-persistent-alist nil)
3532 ("hideblocks" org-hide-block-startup t)
3533 ("nohideblocks" org-hide-block-startup nil))
3534 "Variable associated with STARTUP options for org-mode.
3535 Each element is a list of three items: The startup options as written
3536 in the #+STARTUP line, the corresponding variable, and the value to
3537 set this variable to if the option is found. An optional forth element PUSH
3538 means to push this value onto the list in the variable.")
3540 (defun org-set-regexps-and-options ()
3541 "Precompute regular expressions for current buffer."
3542 (when (org-mode-p)
3543 (org-set-local 'org-todo-kwd-alist nil)
3544 (org-set-local 'org-todo-key-alist nil)
3545 (org-set-local 'org-todo-key-trigger nil)
3546 (org-set-local 'org-todo-keywords-1 nil)
3547 (org-set-local 'org-done-keywords nil)
3548 (org-set-local 'org-todo-heads nil)
3549 (org-set-local 'org-todo-sets nil)
3550 (org-set-local 'org-todo-log-states nil)
3551 (org-set-local 'org-file-properties nil)
3552 (org-set-local 'org-file-tags nil)
3553 (let ((re (org-make-options-regexp
3554 '("CATEGORY" "TODO" "COLUMNS"
3555 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3556 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3557 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3558 (splitre "[ \t]+")
3559 kwds kws0 kwsa key log value cat arch tags const links hw dws
3560 tail sep kws1 prio props ftags drawers
3561 ext-setup-or-nil setup-contents (start 0))
3562 (save-excursion
3563 (save-restriction
3564 (widen)
3565 (goto-char (point-min))
3566 (while (or (and ext-setup-or-nil
3567 (string-match re ext-setup-or-nil start)
3568 (setq start (match-end 0)))
3569 (and (setq ext-setup-or-nil nil start 0)
3570 (re-search-forward re nil t)))
3571 (setq key (upcase (match-string 1 ext-setup-or-nil))
3572 value (org-match-string-no-properties 2 ext-setup-or-nil))
3573 (cond
3574 ((equal key "CATEGORY")
3575 (if (string-match "[ \t]+$" value)
3576 (setq value (replace-match "" t t value)))
3577 (setq cat value))
3578 ((member key '("SEQ_TODO" "TODO"))
3579 (push (cons 'sequence (org-split-string value splitre)) kwds))
3580 ((equal key "TYP_TODO")
3581 (push (cons 'type (org-split-string value splitre)) kwds))
3582 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3583 ;; general TODO-like setup
3584 (push (cons (intern (downcase (match-string 1 key)))
3585 (org-split-string value splitre)) kwds))
3586 ((equal key "TAGS")
3587 (setq tags (append tags (if tags '("\\n") nil)
3588 (org-split-string value splitre))))
3589 ((equal key "COLUMNS")
3590 (org-set-local 'org-columns-default-format value))
3591 ((equal key "LINK")
3592 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3593 (push (cons (match-string 1 value)
3594 (org-trim (match-string 2 value)))
3595 links)))
3596 ((equal key "PRIORITIES")
3597 (setq prio (org-split-string value " +")))
3598 ((equal key "PROPERTY")
3599 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3600 (push (cons (match-string 1 value) (match-string 2 value))
3601 props)))
3602 ((equal key "FILETAGS")
3603 (when (string-match "\\S-" value)
3604 (setq ftags
3605 (append
3606 ftags
3607 (apply 'append
3608 (mapcar (lambda (x) (org-split-string x ":"))
3609 (org-split-string value)))))))
3610 ((equal key "DRAWERS")
3611 (setq drawers (org-split-string value splitre)))
3612 ((equal key "CONSTANTS")
3613 (setq const (append const (org-split-string value splitre))))
3614 ((equal key "STARTUP")
3615 (let ((opts (org-split-string value splitre))
3616 l var val)
3617 (while (setq l (pop opts))
3618 (when (setq l (assoc l org-startup-options))
3619 (setq var (nth 1 l) val (nth 2 l))
3620 (if (not (nth 3 l))
3621 (set (make-local-variable var) val)
3622 (if (not (listp (symbol-value var)))
3623 (set (make-local-variable var) nil))
3624 (set (make-local-variable var) (symbol-value var))
3625 (add-to-list var val))))))
3626 ((equal key "ARCHIVE")
3627 (string-match " *$" value)
3628 (setq arch (replace-match "" t t value))
3629 (remove-text-properties 0 (length arch)
3630 '(face t fontified t) arch))
3631 ((equal key "SETUPFILE")
3632 (setq setup-contents (org-file-contents
3633 (expand-file-name
3634 (org-remove-double-quotes value))
3635 'noerror))
3636 (if (not ext-setup-or-nil)
3637 (setq ext-setup-or-nil setup-contents start 0)
3638 (setq ext-setup-or-nil
3639 (concat (substring ext-setup-or-nil 0 start)
3640 "\n" setup-contents "\n"
3641 (substring ext-setup-or-nil start)))))
3642 ))))
3643 (when cat
3644 (org-set-local 'org-category (intern cat))
3645 (push (cons "CATEGORY" cat) props))
3646 (when prio
3647 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3648 (setq prio (mapcar 'string-to-char prio))
3649 (org-set-local 'org-highest-priority (nth 0 prio))
3650 (org-set-local 'org-lowest-priority (nth 1 prio))
3651 (org-set-local 'org-default-priority (nth 2 prio)))
3652 (and props (org-set-local 'org-file-properties (nreverse props)))
3653 (and ftags (org-set-local 'org-file-tags
3654 (mapcar 'org-add-prop-inherited ftags)))
3655 (and drawers (org-set-local 'org-drawers drawers))
3656 (and arch (org-set-local 'org-archive-location arch))
3657 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3658 ;; Process the TODO keywords
3659 (unless kwds
3660 ;; Use the global values as if they had been given locally.
3661 (setq kwds (default-value 'org-todo-keywords))
3662 (if (stringp (car kwds))
3663 (setq kwds (list (cons org-todo-interpretation
3664 (default-value 'org-todo-keywords)))))
3665 (setq kwds (reverse kwds)))
3666 (setq kwds (nreverse kwds))
3667 (let (inter kws kw)
3668 (while (setq kws (pop kwds))
3669 (let ((kws (or
3670 (run-hook-with-args-until-success
3671 'org-todo-setup-filter-hook kws)
3672 kws)))
3673 (setq inter (pop kws) sep (member "|" kws)
3674 kws0 (delete "|" (copy-sequence kws))
3675 kwsa nil
3676 kws1 (mapcar
3677 (lambda (x)
3678 ;; 1 2
3679 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3680 (progn
3681 (setq kw (match-string 1 x)
3682 key (and (match-end 2) (match-string 2 x))
3683 log (org-extract-log-state-settings x))
3684 (push (cons kw (and key (string-to-char key))) kwsa)
3685 (and log (push log org-todo-log-states))
3687 (error "Invalid TODO keyword %s" x)))
3688 kws0)
3689 kwsa (if kwsa (append '((:startgroup))
3690 (nreverse kwsa)
3691 '((:endgroup))))
3692 hw (car kws1)
3693 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3694 tail (list inter hw (car dws) (org-last dws))))
3695 (add-to-list 'org-todo-heads hw 'append)
3696 (push kws1 org-todo-sets)
3697 (setq org-done-keywords (append org-done-keywords dws nil))
3698 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3699 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3700 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3701 (setq org-todo-sets (nreverse org-todo-sets)
3702 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3703 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3704 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3705 ;; Process the constants
3706 (when const
3707 (let (e cst)
3708 (while (setq e (pop const))
3709 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3710 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3711 (setq org-table-formula-constants-local cst)))
3713 ;; Process the tags.
3714 (when tags
3715 (let (e tgs)
3716 (while (setq e (pop tags))
3717 (cond
3718 ((equal e "{") (push '(:startgroup) tgs))
3719 ((equal e "}") (push '(:endgroup) tgs))
3720 ((equal e "\\n") (push '(:newline) tgs))
3721 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3722 (push (cons (match-string 1 e)
3723 (string-to-char (match-string 2 e)))
3724 tgs))
3725 (t (push (list e) tgs))))
3726 (org-set-local 'org-tag-alist nil)
3727 (while (setq e (pop tgs))
3728 (or (and (stringp (car e))
3729 (assoc (car e) org-tag-alist))
3730 (push e org-tag-alist)))))
3732 ;; Compute the regular expressions and other local variables
3733 (if (not org-done-keywords)
3734 (setq org-done-keywords (and org-todo-keywords-1
3735 (list (org-last org-todo-keywords-1)))))
3736 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3737 (length org-scheduled-string)
3738 (length org-clock-string)
3739 (length org-closed-string)))
3740 org-drawer-regexp
3741 (concat "^[ \t]*:\\("
3742 (mapconcat 'regexp-quote org-drawers "\\|")
3743 "\\):[ \t]*$")
3744 org-not-done-keywords
3745 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3746 org-todo-regexp
3747 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3748 "\\|") "\\)\\>")
3749 org-not-done-regexp
3750 (concat "\\<\\("
3751 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3752 "\\)\\>")
3753 org-not-done-heading-regexp
3754 (concat "^\\(\\*+\\)[ \t]+\\("
3755 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3756 "\\)\\>")
3757 org-todo-line-regexp
3758 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3759 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3760 "\\)\\>\\)?[ \t]*\\(.*\\)")
3761 org-complex-heading-regexp
3762 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3763 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3764 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3765 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3766 org-nl-done-regexp
3767 (concat "\n\\*+[ \t]+"
3768 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3769 "\\)" "\\>")
3770 org-todo-line-tags-regexp
3771 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3772 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3773 (org-re
3774 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3775 org-looking-at-done-regexp
3776 (concat "^" "\\(?:"
3777 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3778 "\\>")
3779 org-deadline-regexp (concat "\\<" org-deadline-string)
3780 org-deadline-time-regexp
3781 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3782 org-deadline-line-regexp
3783 (concat "\\<\\(" org-deadline-string "\\).*")
3784 org-scheduled-regexp
3785 (concat "\\<" org-scheduled-string)
3786 org-scheduled-time-regexp
3787 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3788 org-closed-time-regexp
3789 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3790 org-keyword-time-regexp
3791 (concat "\\<\\(" org-scheduled-string
3792 "\\|" org-deadline-string
3793 "\\|" org-closed-string
3794 "\\|" org-clock-string "\\)"
3795 " *[[<]\\([^]>]+\\)[]>]")
3796 org-keyword-time-not-clock-regexp
3797 (concat "\\<\\(" org-scheduled-string
3798 "\\|" org-deadline-string
3799 "\\|" org-closed-string
3800 "\\)"
3801 " *[[<]\\([^]>]+\\)[]>]")
3802 org-maybe-keyword-time-regexp
3803 (concat "\\(\\<\\(" org-scheduled-string
3804 "\\|" org-deadline-string
3805 "\\|" org-closed-string
3806 "\\|" org-clock-string "\\)\\)?"
3807 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3808 org-planning-or-clock-line-re
3809 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3810 "\\|" org-deadline-string
3811 "\\|" org-closed-string "\\|" org-clock-string
3812 "\\)\\>\\)")
3814 (org-compute-latex-and-specials-regexp)
3815 (org-set-font-lock-defaults))))
3817 (defun org-file-contents (file &optional noerror)
3818 "Return the contents of FILE, as a string."
3819 (if (or (not file)
3820 (not (file-readable-p file)))
3821 (if noerror
3822 (progn
3823 (message "Cannot read file %s" file)
3824 (ding) (sit-for 2)
3826 (error "Cannot read file %s" file))
3827 (with-temp-buffer
3828 (insert-file-contents file)
3829 (buffer-string))))
3831 (defun org-extract-log-state-settings (x)
3832 "Extract the log state setting from a TODO keyword string.
3833 This will extract info from a string like \"WAIT(w@/!)\"."
3834 (let (kw key log1 log2)
3835 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3836 (setq kw (match-string 1 x)
3837 key (and (match-end 2) (match-string 2 x))
3838 log1 (and (match-end 3) (match-string 3 x))
3839 log2 (and (match-end 4) (match-string 4 x)))
3840 (and (or log1 log2)
3841 (list kw
3842 (and log1 (if (equal log1 "!") 'time 'note))
3843 (and log2 (if (equal log2 "!") 'time 'note)))))))
3845 (defun org-remove-keyword-keys (list)
3846 "Remove a pair of parenthesis at the end of each string in LIST."
3847 (mapcar (lambda (x)
3848 (if (string-match "(.*)$" x)
3849 (substring x 0 (match-beginning 0))
3851 list))
3853 ;; FIXME: this could be done much better, using second characters etc.
3854 (defun org-assign-fast-keys (alist)
3855 "Assign fast keys to a keyword-key alist.
3856 Respect keys that are already there."
3857 (let (new e k c c1 c2 (char ?a))
3858 (while (setq e (pop alist))
3859 (cond
3860 ((equal e '(:startgroup)) (push e new))
3861 ((equal e '(:endgroup)) (push e new))
3862 ((equal e '(:newline)) (push e new))
3864 (setq k (car e) c2 nil)
3865 (if (cdr e)
3866 (setq c (cdr e))
3867 ;; automatically assign a character.
3868 (setq c1 (string-to-char
3869 (downcase (substring
3870 k (if (= (string-to-char k) ?@) 1 0)))))
3871 (if (or (rassoc c1 new) (rassoc c1 alist))
3872 (while (or (rassoc char new) (rassoc char alist))
3873 (setq char (1+ char)))
3874 (setq c2 c1))
3875 (setq c (or c2 char)))
3876 (push (cons k c) new))))
3877 (nreverse new)))
3879 ;;; Some variables used in various places
3881 (defvar org-window-configuration nil
3882 "Used in various places to store a window configuration.")
3883 (defvar org-selected-window nil
3884 "Used in various places to store a window configuration.")
3885 (defvar org-finish-function nil
3886 "Function to be called when `C-c C-c' is used.
3887 This is for getting out of special buffers like remember.")
3890 ;; FIXME: Occasionally check by commenting these, to make sure
3891 ;; no other functions uses these, forgetting to let-bind them.
3892 (defvar entry)
3893 (defvar last-state)
3894 (defvar date)
3896 ;; Defined somewhere in this file, but used before definition.
3897 (defvar org-html-entities)
3898 (defvar org-struct-menu)
3899 (defvar org-org-menu)
3900 (defvar org-tbl-menu)
3901 (defvar org-agenda-keymap)
3903 ;;;; Define the Org-mode
3905 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3906 (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."))
3909 ;; We use a before-change function to check if a table might need
3910 ;; an update.
3911 (defvar org-table-may-need-update t
3912 "Indicates that a table might need an update.
3913 This variable is set by `org-before-change-function'.
3914 `org-table-align' sets it back to nil.")
3915 (defun org-before-change-function (beg end)
3916 "Every change indicates that a table might need an update."
3917 (setq org-table-may-need-update t))
3918 (defvar org-mode-map)
3919 (defvar org-mode-hook nil
3920 "Mode hook for Org-mode, run after the mode was turned on.")
3921 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3922 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3923 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3924 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3925 (defvar org-table-buffer-is-an nil)
3926 (defconst org-outline-regexp "\\*+ ")
3928 ;;;###autoload
3929 (define-derived-mode org-mode outline-mode "Org"
3930 "Outline-based notes management and organizer, alias
3931 \"Carsten's outline-mode for keeping track of everything.\"
3933 Org-mode develops organizational tasks around a NOTES file which
3934 contains information about projects as plain text. Org-mode is
3935 implemented on top of outline-mode, which is ideal to keep the content
3936 of large files well structured. It supports ToDo items, deadlines and
3937 time stamps, which magically appear in the diary listing of the Emacs
3938 calendar. Tables are easily created with a built-in table editor.
3939 Plain text URL-like links connect to websites, emails (VM), Usenet
3940 messages (Gnus), BBDB entries, and any files related to the project.
3941 For printing and sharing of notes, an Org-mode file (or a part of it)
3942 can be exported as a structured ASCII or HTML file.
3944 The following commands are available:
3946 \\{org-mode-map}"
3948 ;; Get rid of Outline menus, they are not needed
3949 ;; Need to do this here because define-derived-mode sets up
3950 ;; the keymap so late. Still, it is a waste to call this each time
3951 ;; we switch another buffer into org-mode.
3952 (if (featurep 'xemacs)
3953 (when (boundp 'outline-mode-menu-heading)
3954 ;; Assume this is Greg's port, it used easymenu
3955 (easy-menu-remove outline-mode-menu-heading)
3956 (easy-menu-remove outline-mode-menu-show)
3957 (easy-menu-remove outline-mode-menu-hide))
3958 (define-key org-mode-map [menu-bar headings] 'undefined)
3959 (define-key org-mode-map [menu-bar hide] 'undefined)
3960 (define-key org-mode-map [menu-bar show] 'undefined))
3962 (org-load-modules-maybe)
3963 (easy-menu-add org-org-menu)
3964 (easy-menu-add org-tbl-menu)
3965 (org-install-agenda-files-menu)
3966 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3967 (org-add-to-invisibility-spec '(org-cwidth))
3968 (org-add-to-invisibility-spec '(org-hide-block . t))
3969 (when (featurep 'xemacs)
3970 (org-set-local 'line-move-ignore-invisible t))
3971 (org-set-local 'outline-regexp org-outline-regexp)
3972 (org-set-local 'outline-level 'org-outline-level)
3973 (when (and org-ellipsis
3974 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3975 (fboundp 'make-glyph-code))
3976 (unless org-display-table
3977 (setq org-display-table (make-display-table)))
3978 (set-display-table-slot
3979 org-display-table 4
3980 (vconcat (mapcar
3981 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3982 org-ellipsis)))
3983 (if (stringp org-ellipsis) org-ellipsis "..."))))
3984 (setq buffer-display-table org-display-table))
3985 (org-set-regexps-and-options)
3986 (when (and org-tag-faces (not org-tags-special-faces-re))
3987 ;; tag faces set outside customize.... force initialization.
3988 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3989 ;; Calc embedded
3990 (org-set-local 'calc-embedded-open-mode "# ")
3991 (modify-syntax-entry ?# "<")
3992 (modify-syntax-entry ?@ "w")
3993 (if org-startup-truncated (setq truncate-lines t))
3994 (org-set-local 'font-lock-unfontify-region-function
3995 'org-unfontify-region)
3996 ;; Activate before-change-function
3997 (org-set-local 'org-table-may-need-update t)
3998 (org-add-hook 'before-change-functions 'org-before-change-function nil
3999 'local)
4000 ;; Check for running clock before killing a buffer
4001 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4002 ;; Paragraphs and auto-filling
4003 (org-set-autofill-regexps)
4004 (setq indent-line-function 'org-indent-line-function)
4005 (org-update-radio-target-regexp)
4006 ;; Make sure dependence stuff works reliably, even for users who set it
4007 ;; too late :-(
4008 (if org-enforce-todo-dependencies
4009 (add-hook 'org-blocker-hook
4010 'org-block-todo-from-children-or-siblings-or-parent)
4011 (remove-hook 'org-blocker-hook
4012 'org-block-todo-from-children-or-siblings-or-parent))
4013 (if org-enforce-todo-checkbox-dependencies
4014 (add-hook 'org-blocker-hook
4015 'org-block-todo-from-checkboxes)
4016 (remove-hook 'org-blocker-hook
4017 'org-block-todo-from-checkboxes))
4019 ;; Comment characters
4020 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4021 (org-set-local 'comment-padding " ")
4023 ;; Align options lines
4024 (org-set-local
4025 'align-mode-rules-list
4026 '((org-in-buffer-settings
4027 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4028 (modes . '(org-mode)))))
4030 ;; Imenu
4031 (org-set-local 'imenu-create-index-function
4032 'org-imenu-get-tree)
4034 ;; Make isearch reveal context
4035 (if (or (featurep 'xemacs)
4036 (not (boundp 'outline-isearch-open-invisible-function)))
4037 ;; Emacs 21 and XEmacs make use of the hook
4038 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4039 ;; Emacs 22 deals with this through a special variable
4040 (org-set-local 'outline-isearch-open-invisible-function
4041 (lambda (&rest ignore) (org-show-context 'isearch))))
4043 ;; If empty file that did not turn on org-mode automatically, make it to.
4044 (if (and org-insert-mode-line-in-empty-file
4045 (interactive-p)
4046 (= (point-min) (point-max)))
4047 (insert "# -*- mode: org -*-\n\n"))
4049 (unless org-inhibit-startup
4050 (when org-startup-align-all-tables
4051 (let ((bmp (buffer-modified-p)))
4052 (org-table-map-tables 'org-table-align)
4053 (set-buffer-modified-p bmp)))
4054 (when org-startup-indented
4055 (require 'org-indent)
4056 (org-indent-mode 1))
4057 (org-set-startup-visibility)))
4059 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4061 (defun org-current-time ()
4062 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4063 (if (> (car org-time-stamp-rounding-minutes) 1)
4064 (let ((r (car org-time-stamp-rounding-minutes))
4065 (time (decode-time)))
4066 (apply 'encode-time
4067 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4068 (nthcdr 2 time))))
4069 (current-time)))
4071 ;;;; Font-Lock stuff, including the activators
4073 (defvar org-mouse-map (make-sparse-keymap))
4074 (org-defkey org-mouse-map
4075 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4076 (org-defkey org-mouse-map
4077 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4078 (when org-mouse-1-follows-link
4079 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4080 (when org-tab-follows-link
4081 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4082 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4084 (require 'font-lock)
4086 (defconst org-non-link-chars "]\t\n\r<>")
4087 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4088 "shell" "elisp"))
4089 (defvar org-link-types-re nil
4090 "Matches a link that has a url-like prefix like \"http:\"")
4091 (defvar org-link-re-with-space nil
4092 "Matches a link with spaces, optional angular brackets around it.")
4093 (defvar org-link-re-with-space2 nil
4094 "Matches a link with spaces, optional angular brackets around it.")
4095 (defvar org-link-re-with-space3 nil
4096 "Matches a link with spaces, only for internal part in bracket links.")
4097 (defvar org-angle-link-re nil
4098 "Matches link with angular brackets, spaces are allowed.")
4099 (defvar org-plain-link-re nil
4100 "Matches plain link, without spaces.")
4101 (defvar org-bracket-link-regexp nil
4102 "Matches a link in double brackets.")
4103 (defvar org-bracket-link-analytic-regexp nil
4104 "Regular expression used to analyze links.
4105 Here is what the match groups contain after a match:
4106 1: http:
4107 2: http
4108 3: path
4109 4: [desc]
4110 5: desc")
4111 (defvar org-bracket-link-analytic-regexp++ nil
4112 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4113 (defvar org-any-link-re nil
4114 "Regular expression matching any link.")
4116 (defun org-make-link-regexps ()
4117 "Update the link regular expressions.
4118 This should be called after the variable `org-link-types' has changed."
4119 (setq org-link-types-re
4120 (concat
4121 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4122 org-link-re-with-space
4123 (concat
4124 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4125 "\\([^" org-non-link-chars " ]"
4126 "[^" org-non-link-chars "]*"
4127 "[^" org-non-link-chars " ]\\)>?")
4128 org-link-re-with-space2
4129 (concat
4130 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4131 "\\([^" org-non-link-chars " ]"
4132 "[^\t\n\r]*"
4133 "[^" org-non-link-chars " ]\\)>?")
4134 org-link-re-with-space3
4135 (concat
4136 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4137 "\\([^" org-non-link-chars " ]"
4138 "[^\t\n\r]*\\)")
4139 org-angle-link-re
4140 (concat
4141 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4142 "\\([^" org-non-link-chars " ]"
4143 "[^" org-non-link-chars "]*"
4144 "\\)>")
4145 org-plain-link-re
4146 (concat
4147 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4148 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4149 org-bracket-link-regexp
4150 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4151 org-bracket-link-analytic-regexp
4152 (concat
4153 "\\[\\["
4154 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4155 "\\([^]]+\\)"
4156 "\\]"
4157 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4158 "\\]")
4159 org-bracket-link-analytic-regexp++
4160 (concat
4161 "\\[\\["
4162 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4163 "\\([^]]+\\)"
4164 "\\]"
4165 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4166 "\\]")
4167 org-any-link-re
4168 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4169 org-angle-link-re "\\)\\|\\("
4170 org-plain-link-re "\\)")))
4172 (org-make-link-regexps)
4174 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4175 "Regular expression for fast time stamp matching.")
4176 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4177 "Regular expression for fast time stamp matching.")
4178 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4179 "Regular expression matching time strings for analysis.
4180 This one does not require the space after the date, so it can be used
4181 on a string that terminates immediately after the date.")
4182 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4183 "Regular expression matching time strings for analysis.")
4184 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4185 "Regular expression matching time stamps, with groups.")
4186 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4187 "Regular expression matching time stamps (also [..]), with groups.")
4188 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4189 "Regular expression matching a time stamp range.")
4190 (defconst org-tr-regexp-both
4191 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4192 "Regular expression matching a time stamp range.")
4193 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4194 org-ts-regexp "\\)?")
4195 "Regular expression matching a time stamp or time stamp range.")
4196 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4197 org-ts-regexp-both "\\)?")
4198 "Regular expression matching a time stamp or time stamp range.
4199 The time stamps may be either active or inactive.")
4201 (defvar org-emph-face nil)
4203 (defun org-do-emphasis-faces (limit)
4204 "Run through the buffer and add overlays to links."
4205 (let (rtn a)
4206 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4207 (if (not (= (char-after (match-beginning 3))
4208 (char-after (match-beginning 4))))
4209 (progn
4210 (setq rtn t)
4211 (setq a (assoc (match-string 3) org-emphasis-alist))
4212 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4213 'face
4214 (nth 1 a))
4215 (and (nth 4 a)
4216 (org-remove-flyspell-overlays-in
4217 (match-beginning 0) (match-end 0)))
4218 (add-text-properties (match-beginning 2) (match-end 2)
4219 '(font-lock-multiline t))
4220 (when org-hide-emphasis-markers
4221 (add-text-properties (match-end 4) (match-beginning 5)
4222 '(invisible org-link))
4223 (add-text-properties (match-beginning 3) (match-end 3)
4224 '(invisible org-link)))))
4225 (backward-char 1))
4226 rtn))
4228 (defun org-emphasize (&optional char)
4229 "Insert or change an emphasis, i.e. a font like bold or italic.
4230 If there is an active region, change that region to a new emphasis.
4231 If there is no region, just insert the marker characters and position
4232 the cursor between them.
4233 CHAR should be either the marker character, or the first character of the
4234 HTML tag associated with that emphasis. If CHAR is a space, the means
4235 to remove the emphasis of the selected region.
4236 If char is not given (for example in an interactive call) it
4237 will be prompted for."
4238 (interactive)
4239 (let ((eal org-emphasis-alist) e det
4240 (erc org-emphasis-regexp-components)
4241 (prompt "")
4242 (string "") beg end move tag c s)
4243 (if (org-region-active-p)
4244 (setq beg (region-beginning) end (region-end)
4245 string (buffer-substring beg end))
4246 (setq move t))
4248 (while (setq e (pop eal))
4249 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4250 c (aref tag 0))
4251 (push (cons c (string-to-char (car e))) det)
4252 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4253 (substring tag 1)))))
4254 (setq det (nreverse det))
4255 (unless char
4256 (message "%s" (concat "Emphasis marker or tag:" prompt))
4257 (setq char (read-char-exclusive)))
4258 (setq char (or (cdr (assoc char det)) char))
4259 (if (equal char ?\ )
4260 (setq s "" move nil)
4261 (unless (assoc (char-to-string char) org-emphasis-alist)
4262 (error "No such emphasis marker: \"%c\"" char))
4263 (setq s (char-to-string char)))
4264 (while (and (> (length string) 1)
4265 (equal (substring string 0 1) (substring string -1))
4266 (assoc (substring string 0 1) org-emphasis-alist))
4267 (setq string (substring string 1 -1)))
4268 (setq string (concat s string s))
4269 (if beg (delete-region beg end))
4270 (unless (or (bolp)
4271 (string-match (concat "[" (nth 0 erc) "\n]")
4272 (char-to-string (char-before (point)))))
4273 (insert " "))
4274 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4275 (char-to-string (char-after (point))))
4276 (insert " ") (backward-char 1))
4277 (insert string)
4278 (and move (backward-char 1))))
4280 (defconst org-nonsticky-props
4281 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4283 (defsubst org-rear-nonsticky-at (pos)
4284 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4286 (defun org-activate-plain-links (limit)
4287 "Run through the buffer and add overlays to links."
4288 (catch 'exit
4289 (let (f)
4290 (if (re-search-forward org-plain-link-re limit t)
4291 (progn
4292 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4293 (setq f (get-text-property (match-beginning 0) 'face))
4294 (if (or (eq f 'org-tag)
4295 (and (listp f) (memq 'org-tag f)))
4297 (add-text-properties (match-beginning 0) (match-end 0)
4298 (list 'mouse-face 'highlight
4299 'keymap org-mouse-map))
4300 (org-rear-nonsticky-at (match-end 0)))
4301 t)))))
4303 (defun org-activate-code (limit)
4304 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4305 (progn
4306 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4307 (remove-text-properties (match-beginning 0) (match-end 0)
4308 '(display t invisible t intangible t))
4309 t)))
4311 (defun org-fontify-meta-lines-and-blocks (limit)
4312 "Fontify #+ lines and blocks, in the correct ways."
4313 (let ((case-fold-search t))
4314 (if (re-search-forward
4315 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4316 limit t)
4317 (let ((beg (match-beginning 0))
4318 (beg1 (line-beginning-position 2))
4319 (dc1 (downcase (match-string 2)))
4320 (dc3 (downcase (match-string 3)))
4321 end end1 quoting)
4322 (cond
4323 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4324 ;; a single line of backend-specific content
4325 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4326 (remove-text-properties (match-beginning 0) (match-end 0)
4327 '(display t invisible t intangible t))
4328 (add-text-properties (match-beginning 1) (match-end 3)
4329 '(font-lock-fontified t face org-meta-line))
4330 (add-text-properties (match-beginning 6) (match-end 6)
4331 '(font-lock-fontified t face org-block))
4333 ((and (match-end 4) (equal dc3 "begin"))
4334 ;; Truely a block
4335 (setq quoting (member (downcase (match-string 5))
4336 org-protecting-blocks))
4337 (when (re-search-forward
4338 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4339 nil t) ;; on purpose, we look further than LIMIT
4340 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4341 (when quoting
4342 (remove-text-properties beg end
4343 '(display t invisible t intangible t)))
4344 (add-text-properties
4345 beg end
4346 '(font-lock-fontified t font-lock-multiline t))
4347 (add-text-properties beg beg1 '(face org-meta-line))
4348 (add-text-properties end1 end '(face org-meta-line))
4349 (when quoting
4350 (add-text-properties beg1 end1 '(face org-block)))
4352 ((not (member (char-after beg) '(?\ ?\t)))
4353 ;; just any other in-buffer setting, but not indented
4354 (add-text-properties
4355 beg (match-end 0)
4356 '(font-lock-fontified t face org-meta-line))
4358 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4359 (and (match-end 4) (equal dc3 "attr")))
4360 (add-text-properties
4361 beg (match-end 0)
4362 '(font-lock-fontified t face org-meta-line))
4364 (t nil))))))
4366 (defun org-activate-angle-links (limit)
4367 "Run through the buffer and add overlays to links."
4368 (if (re-search-forward org-angle-link-re limit t)
4369 (progn
4370 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4371 (add-text-properties (match-beginning 0) (match-end 0)
4372 (list 'mouse-face 'highlight
4373 'keymap org-mouse-map))
4374 (org-rear-nonsticky-at (match-end 0))
4375 t)))
4377 (defun org-activate-footnote-links (limit)
4378 "Run through the buffer and add overlays to links."
4379 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4380 limit t)
4381 (progn
4382 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4383 (add-text-properties (match-beginning 2) (match-end 2)
4384 (list 'mouse-face 'highlight
4385 'keymap org-mouse-map
4386 'help-echo
4387 (if (= (point-at-bol) (match-beginning 2))
4388 "Footnote definition"
4389 "Footnote reference")
4391 (org-rear-nonsticky-at (match-end 2))
4392 t)))
4394 (defun org-activate-bracket-links (limit)
4395 "Run through the buffer and add overlays to bracketed links."
4396 (if (re-search-forward org-bracket-link-regexp limit t)
4397 (let* ((help (concat "LINK: "
4398 (org-match-string-no-properties 1)))
4399 ;; FIXME: above we should remove the escapes.
4400 ;; but that requires another match, protecting match data,
4401 ;; a lot of overhead for font-lock.
4402 (ip (org-maybe-intangible
4403 (list 'invisible 'org-link
4404 'keymap org-mouse-map 'mouse-face 'highlight
4405 'font-lock-multiline t 'help-echo help)))
4406 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4407 'font-lock-multiline t 'help-echo help)))
4408 ;; We need to remove the invisible property here. Table narrowing
4409 ;; may have made some of this invisible.
4410 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4411 (remove-text-properties (match-beginning 0) (match-end 0)
4412 '(invisible nil))
4413 (if (match-end 3)
4414 (progn
4415 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4416 (org-rear-nonsticky-at (match-beginning 3))
4417 (add-text-properties (match-beginning 3) (match-end 3) vp)
4418 (org-rear-nonsticky-at (match-end 3))
4419 (add-text-properties (match-end 3) (match-end 0) ip)
4420 (org-rear-nonsticky-at (match-end 0)))
4421 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4422 (org-rear-nonsticky-at (match-beginning 1))
4423 (add-text-properties (match-beginning 1) (match-end 1) vp)
4424 (org-rear-nonsticky-at (match-end 1))
4425 (add-text-properties (match-end 1) (match-end 0) ip)
4426 (org-rear-nonsticky-at (match-end 0)))
4427 t)))
4429 (defun org-activate-dates (limit)
4430 "Run through the buffer and add overlays to dates."
4431 (if (re-search-forward org-tsr-regexp-both limit t)
4432 (progn
4433 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4434 (add-text-properties (match-beginning 0) (match-end 0)
4435 (list 'mouse-face 'highlight
4436 'keymap org-mouse-map))
4437 (org-rear-nonsticky-at (match-end 0))
4438 (when org-display-custom-times
4439 (if (match-end 3)
4440 (org-display-custom-time (match-beginning 3) (match-end 3)))
4441 (org-display-custom-time (match-beginning 1) (match-end 1)))
4442 t)))
4444 (defvar org-target-link-regexp nil
4445 "Regular expression matching radio targets in plain text.")
4446 (make-variable-buffer-local 'org-target-link-regexp)
4447 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4448 "Regular expression matching a link target.")
4449 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4450 "Regular expression matching a radio target.")
4451 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4452 "Regular expression matching any target.")
4454 (defun org-activate-target-links (limit)
4455 "Run through the buffer and add overlays to target matches."
4456 (when org-target-link-regexp
4457 (let ((case-fold-search t))
4458 (if (re-search-forward org-target-link-regexp limit t)
4459 (progn
4460 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4461 (add-text-properties (match-beginning 0) (match-end 0)
4462 (list 'mouse-face 'highlight
4463 'keymap org-mouse-map
4464 'help-echo "Radio target link"
4465 'org-linked-text t))
4466 (org-rear-nonsticky-at (match-end 0))
4467 t)))))
4469 (defun org-update-radio-target-regexp ()
4470 "Find all radio targets in this file and update the regular expression."
4471 (interactive)
4472 (when (memq 'radio org-activate-links)
4473 (setq org-target-link-regexp
4474 (org-make-target-link-regexp (org-all-targets 'radio)))
4475 (org-restart-font-lock)))
4477 (defun org-hide-wide-columns (limit)
4478 (let (s e)
4479 (setq s (text-property-any (point) (or limit (point-max))
4480 'org-cwidth t))
4481 (when s
4482 (setq e (next-single-property-change s 'org-cwidth))
4483 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4484 (goto-char e)
4485 t)))
4487 (defvar org-latex-and-specials-regexp nil
4488 "Regular expression for highlighting export special stuff.")
4489 (defvar org-match-substring-regexp)
4490 (defvar org-match-substring-with-braces-regexp)
4492 ;; This should be with the exporter code, but we also use if for font-locking
4493 (defconst org-export-html-special-string-regexps
4494 '(("\\\\-" . "&shy;")
4495 ("---\\([^-]\\)" . "&mdash;\\1")
4496 ("--\\([^-]\\)" . "&ndash;\\1")
4497 ("\\.\\.\\." . "&hellip;"))
4498 "Regular expressions for special string conversion.")
4501 (defun org-compute-latex-and-specials-regexp ()
4502 "Compute regular expression for stuff treated specially by exporters."
4503 (if (not org-highlight-latex-fragments-and-specials)
4504 (org-set-local 'org-latex-and-specials-regexp nil)
4505 (require 'org-exp)
4506 (let*
4507 ((matchers (plist-get org-format-latex-options :matchers))
4508 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4509 org-latex-regexps)))
4510 (options (org-combine-plists (org-default-export-plist)
4511 (org-infile-export-plist)))
4512 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4513 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4514 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4515 (org-export-html-expand (plist-get options :expand-quoted-html))
4516 (org-export-with-special-strings (plist-get options :special-strings))
4517 (re-sub
4518 (cond
4519 ((equal org-export-with-sub-superscripts '{})
4520 (list org-match-substring-with-braces-regexp))
4521 (org-export-with-sub-superscripts
4522 (list org-match-substring-regexp))
4523 (t nil)))
4524 (re-latex
4525 (if org-export-with-LaTeX-fragments
4526 (mapcar (lambda (x) (nth 1 x)) latexs)))
4527 (re-macros
4528 (if org-export-with-TeX-macros
4529 (list (concat "\\\\"
4530 (regexp-opt
4531 (append (mapcar 'car org-html-entities)
4532 (if (boundp 'org-latex-entities)
4533 (mapcar (lambda (x)
4534 (or (car-safe x) x))
4535 org-latex-entities)
4536 nil))
4537 'words))) ; FIXME
4539 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4540 (re-special (if org-export-with-special-strings
4541 (mapcar (lambda (x) (car x))
4542 org-export-html-special-string-regexps)))
4543 (re-rest
4544 (delq nil
4545 (list
4546 (if org-export-html-expand "@<[^>\n]+>")
4547 ))))
4548 (org-set-local
4549 'org-latex-and-specials-regexp
4550 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4551 re-rest) "\\|")))))
4553 (defun org-do-latex-and-special-faces (limit)
4554 "Run through the buffer and add overlays to links."
4555 (when org-latex-and-specials-regexp
4556 (let (rtn d)
4557 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4558 limit t))
4559 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4560 'face))
4561 '(org-code org-verbatim underline)))
4562 (progn
4563 (setq rtn t
4564 d (cond ((member (char-after (1+ (match-beginning 0)))
4565 '(?_ ?^)) 1)
4566 (t 0)))
4567 (font-lock-prepend-text-property
4568 (+ d (match-beginning 0)) (match-end 0)
4569 'face 'org-latex-and-export-specials)
4570 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4571 '(font-lock-multiline t)))))
4572 rtn)))
4574 (defun org-restart-font-lock ()
4575 "Restart font-lock-mode, to force refontification."
4576 (when (and (boundp 'font-lock-mode) font-lock-mode)
4577 (font-lock-mode -1)
4578 (font-lock-mode 1)))
4580 (defun org-all-targets (&optional radio)
4581 "Return a list of all targets in this file.
4582 With optional argument RADIO, only find radio targets."
4583 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4584 rtn)
4585 (save-excursion
4586 (goto-char (point-min))
4587 (while (re-search-forward re nil t)
4588 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4589 rtn)))
4591 (defun org-make-target-link-regexp (targets)
4592 "Make regular expression matching all strings in TARGETS.
4593 The regular expression finds the targets also if there is a line break
4594 between words."
4595 (and targets
4596 (concat
4597 "\\<\\("
4598 (mapconcat
4599 (lambda (x)
4600 (while (string-match " +" x)
4601 (setq x (replace-match "\\s-+" t t x)))
4603 targets
4604 "\\|")
4605 "\\)\\>")))
4607 (defun org-activate-tags (limit)
4608 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4609 (progn
4610 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4611 (add-text-properties (match-beginning 1) (match-end 1)
4612 (list 'mouse-face 'highlight
4613 'keymap org-mouse-map))
4614 (org-rear-nonsticky-at (match-end 1))
4615 t)))
4617 (defun org-outline-level ()
4618 (save-excursion
4619 (looking-at outline-regexp)
4620 (if (match-beginning 1)
4621 (+ (org-get-string-indentation (match-string 1)) 1000)
4622 (1- (- (match-end 0) (match-beginning 0))))))
4624 (defvar org-font-lock-keywords nil)
4626 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4627 "Regular expression matching a property line.")
4629 (defvar org-font-lock-hook nil
4630 "Functions to be called for special font lock stuff.")
4632 (defun org-font-lock-hook (limit)
4633 (run-hook-with-args 'org-font-lock-hook limit))
4635 (defun org-set-font-lock-defaults ()
4636 (let* ((em org-fontify-emphasized-text)
4637 (lk org-activate-links)
4638 (org-font-lock-extra-keywords
4639 (list
4640 ;; Call the hook
4641 '(org-font-lock-hook)
4642 ;; Headlines
4643 `(,(if org-fontify-whole-heading-line
4644 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4645 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4646 (1 (org-get-level-face 1))
4647 (2 (org-get-level-face 2))
4648 (3 (org-get-level-face 3)))
4649 ;; Table lines
4650 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4651 (1 'org-table t))
4652 ;; Table internals
4653 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4654 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4655 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4656 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4657 ;; Drawers
4658 (list org-drawer-regexp '(0 'org-special-keyword t))
4659 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4660 ;; Properties
4661 (list org-property-re
4662 '(1 'org-special-keyword t)
4663 '(3 'org-property-value t))
4664 ;; Links
4665 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4666 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4667 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4668 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4669 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4670 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4671 (if (memq 'footnote lk) '(org-activate-footnote-links
4672 (2 'org-footnote t)))
4673 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4674 '(org-hide-wide-columns (0 nil append))
4675 ;; TODO lines
4676 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4677 '(1 (org-get-todo-face 1) t))
4678 ;; DONE
4679 (if org-fontify-done-headline
4680 (list (concat "^[*]+ +\\<\\("
4681 (mapconcat 'regexp-quote org-done-keywords "\\|")
4682 "\\)\\(.*\\)")
4683 '(2 'org-headline-done t))
4684 nil)
4685 ;; Priorities
4686 '(org-font-lock-add-priority-faces)
4687 ;; Tags
4688 '(org-font-lock-add-tag-faces)
4689 ;; Special keywords
4690 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4691 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4692 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4693 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4694 ;; Emphasis
4695 (if em
4696 (if (featurep 'xemacs)
4697 '(org-do-emphasis-faces (0 nil append))
4698 '(org-do-emphasis-faces)))
4699 ;; Checkboxes
4700 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4701 2 'org-checkbox prepend)
4702 (if org-provide-checkbox-statistics
4703 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4704 (0 (org-get-checkbox-statistics-face) t)))
4705 ;; Description list items
4706 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4707 2 'bold prepend)
4708 ;; ARCHIVEd headings
4709 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4710 '(1 'org-archived prepend))
4711 ;; Specials
4712 '(org-do-latex-and-special-faces)
4713 ;; Code
4714 '(org-activate-code (1 'org-code t))
4715 ;; COMMENT
4716 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4717 "\\|" org-quote-string "\\)\\>")
4718 '(1 'org-special-keyword t))
4719 '("^#.*" (0 'font-lock-comment-face t))
4720 ;; Blocks and meta lines
4721 '(org-fontify-meta-lines-and-blocks)
4723 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4724 ;; Now set the full font-lock-keywords
4725 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4726 (org-set-local 'font-lock-defaults
4727 '(org-font-lock-keywords t nil nil backward-paragraph))
4728 (kill-local-variable 'font-lock-keywords) nil))
4730 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4731 "Fontify string S like in Org-mode"
4732 (with-temp-buffer
4733 (insert s)
4734 (let ((org-odd-levels-only odd-levels))
4735 (org-mode)
4736 (font-lock-fontify-buffer)
4737 (buffer-string))))
4739 (defvar org-m nil)
4740 (defvar org-l nil)
4741 (defvar org-f nil)
4742 (defun org-get-level-face (n)
4743 "Get the right face for match N in font-lock matching of headlines."
4744 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4745 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4746 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4747 (cond
4748 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4749 ((eq n 2) org-f)
4750 (t (if org-level-color-stars-only nil org-f))))
4752 (defun org-get-todo-face (kwd)
4753 "Get the right face for a TODO keyword KWD.
4754 If KWD is a number, get the corresponding match group."
4755 (if (numberp kwd) (setq kwd (match-string kwd)))
4756 (or (cdr (assoc kwd org-todo-keyword-faces))
4757 (and (member kwd org-done-keywords) 'org-done)
4758 'org-todo))
4760 (defun org-font-lock-add-tag-faces (limit)
4761 "Add the special tag faces."
4762 (when (and org-tag-faces org-tags-special-faces-re)
4763 (while (re-search-forward org-tags-special-faces-re limit t)
4764 (add-text-properties (match-beginning 1) (match-end 1)
4765 (list 'face (org-get-tag-face 1)
4766 'font-lock-fontified t))
4767 (backward-char 1))))
4769 (defun org-font-lock-add-priority-faces (limit)
4770 "Add the special priority faces."
4771 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4772 (add-text-properties
4773 (match-beginning 0) (match-end 0)
4774 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4775 org-priority-faces))
4776 'org-special-keyword)
4777 'font-lock-fontified t))))
4779 (defun org-get-tag-face (kwd)
4780 "Get the right face for a TODO keyword KWD.
4781 If KWD is a number, get the corresponding match group."
4782 (if (numberp kwd) (setq kwd (match-string kwd)))
4783 (or (cdr (assoc kwd org-tag-faces))
4784 'org-tag))
4786 (defun org-unfontify-region (beg end &optional maybe_loudly)
4787 "Remove fontification and activation overlays from links."
4788 (font-lock-default-unfontify-region beg end)
4789 (let* ((buffer-undo-list t)
4790 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4791 (inhibit-modification-hooks t)
4792 deactivate-mark buffer-file-name buffer-file-truename)
4793 (remove-text-properties beg end
4794 '(mouse-face t keymap t org-linked-text t
4795 invisible t intangible t
4796 line-prefix t wrap-prefix t
4797 org-no-flyspell t))))
4799 ;;;; Visibility cycling, including org-goto and indirect buffer
4801 ;;; Cycling
4803 (defvar org-cycle-global-status nil)
4804 (make-variable-buffer-local 'org-cycle-global-status)
4805 (defvar org-cycle-subtree-status nil)
4806 (make-variable-buffer-local 'org-cycle-subtree-status)
4808 ;;;###autoload
4810 (defvar org-inlinetask-min-level)
4812 (defun org-cycle (&optional arg)
4813 "TAB-action and visibility cycling for Org-mode.
4815 This is the command invoked in Org-mode by the TAB key. Its main purpose
4816 is outine visibility cycling, but it also invokes other actions
4817 in special contexts.
4819 - When this function is called with a prefix argument, rotate the entire
4820 buffer through 3 states (global cycling)
4821 1. OVERVIEW: Show only top-level headlines.
4822 2. CONTENTS: Show all headlines of all levels, but no body text.
4823 3. SHOW ALL: Show everything.
4824 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4825 determined by the variable `org-startup-folded', and by any VISIBILITY
4826 properties in the buffer.
4827 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4828 including any drawers.
4830 - When inside a table, re-align the table and move to the next field.
4832 - When point is at the beginning of a headline, rotate the subtree started
4833 by this line through 3 different states (local cycling)
4834 1. FOLDED: Only the main headline is shown.
4835 2. CHILDREN: The main headline and the direct children are shown.
4836 From this state, you can move to one of the children
4837 and zoom in further.
4838 3. SUBTREE: Show the entire subtree, including body text.
4839 If there is no subtree, switch directly from CHILDREN to FOLDED.
4841 - When there is a numeric prefix, go up to a heading with level ARG, do
4842 a `show-subtree' and return to the previous cursor position. If ARG
4843 is negative, go up that many levels.
4845 - When point is not at the beginning of a headline, execute the global
4846 binding for TAB, which is re-indenting the line. See the option
4847 `org-cycle-emulate-tab' for details.
4849 - Special case: if point is at the beginning of the buffer and there is
4850 no headline in line 1, this function will act as if called with prefix arg.
4851 But only if also the variable `org-cycle-global-at-bob' is t."
4852 (interactive "P")
4853 (org-load-modules-maybe)
4854 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4855 (let* ((limit-level
4856 (or org-cycle-max-level
4857 (and (boundp 'org-inlinetask-min-level)
4858 org-inlinetask-min-level
4859 (1- org-inlinetask-min-level))))
4860 (nstars (and limit-level
4861 (if org-odd-levels-only
4862 (and limit-level (1- (* limit-level 2)))
4863 limit-level)))
4864 (outline-regexp
4865 (cond
4866 ((not (org-mode-p)) outline-regexp)
4867 ((or (eq org-cycle-include-plain-lists 'integrate)
4868 (and org-cycle-include-plain-lists (org-at-item-p)))
4869 (concat "\\(?:\\*"
4870 (if nstars (format "\\{1,%d\\}" nstars) "+")
4871 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4872 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4873 (bob-special (and org-cycle-global-at-bob (bobp)
4874 (not (looking-at outline-regexp))))
4875 (org-cycle-hook
4876 (if bob-special
4877 (delq 'org-optimize-window-after-visibility-change
4878 (copy-sequence org-cycle-hook))
4879 org-cycle-hook))
4880 (pos (point)))
4882 (if (or bob-special (equal arg '(4)))
4883 ;; special case: use global cycling
4884 (setq arg t))
4886 (cond
4888 ((equal arg '(16))
4889 (org-set-startup-visibility)
4890 (message "Startup visibility, plus VISIBILITY properties"))
4892 ((equal arg '(64))
4893 (show-all)
4894 (message "Entire buffer visible, including drawers"))
4896 ((org-at-table-p 'any)
4897 ;; Enter the table or move to the next field in the table
4898 (or (org-table-recognize-table.el)
4899 (progn
4900 (if arg (org-table-edit-field t)
4901 (org-table-justify-field-maybe)
4902 (call-interactively 'org-table-next-field)))))
4904 ((run-hook-with-args-until-success
4905 'org-tab-after-check-for-table-hook))
4907 ((eq arg t) ;; Global cycling
4908 (org-cycle-internal-global))
4910 ((and org-drawers org-drawer-regexp
4911 (save-excursion
4912 (beginning-of-line 1)
4913 (looking-at org-drawer-regexp)))
4914 ;; Toggle block visibility
4915 (org-flag-drawer
4916 (not (get-char-property (match-end 0) 'invisible))))
4918 ((integerp arg)
4919 ;; Show-subtree, ARG levels up from here.
4920 (save-excursion
4921 (org-back-to-heading)
4922 (outline-up-heading (if (< arg 0) (- arg)
4923 (- (funcall outline-level) arg)))
4924 (org-show-subtree)))
4926 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4927 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4929 (org-cycle-internal-local))
4931 ;; TAB emulation and template completion
4932 (buffer-read-only (org-back-to-heading))
4934 ((run-hook-with-args-until-success
4935 'org-tab-after-check-for-cycling-hook))
4937 ((org-try-structure-completion))
4939 ((org-try-cdlatex-tab))
4941 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4942 (or (not (bolp))
4943 (not (looking-at outline-regexp))))
4944 (call-interactively (global-key-binding "\t")))
4946 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4947 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4948 (or (and (eq org-cycle-emulate-tab 'white)
4949 (= (match-end 0) (point-at-eol)))
4950 (and (eq org-cycle-emulate-tab 'whitestart)
4951 (>= (match-end 0) pos))))
4953 (eq org-cycle-emulate-tab t))
4954 (call-interactively (global-key-binding "\t")))
4956 (t (save-excursion
4957 (org-back-to-heading)
4958 (org-cycle)))))))
4960 (defun org-cycle-internal-global ()
4961 "Do the global cycling action."
4962 (cond
4963 ((and (eq last-command this-command)
4964 (eq org-cycle-global-status 'overview))
4965 ;; We just created the overview - now do table of contents
4966 ;; This can be slow in very large buffers, so indicate action
4967 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4968 (message "CONTENTS...")
4969 (org-content)
4970 (message "CONTENTS...done")
4971 (setq org-cycle-global-status 'contents)
4972 (run-hook-with-args 'org-cycle-hook 'contents))
4974 ((and (eq last-command this-command)
4975 (eq org-cycle-global-status 'contents))
4976 ;; We just showed the table of contents - now show everything
4977 (run-hook-with-args 'org-pre-cycle-hook 'all)
4978 (show-all)
4979 (message "SHOW ALL")
4980 (setq org-cycle-global-status 'all)
4981 (run-hook-with-args 'org-cycle-hook 'all))
4984 ;; Default action: go to overview
4985 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4986 (org-overview)
4987 (message "OVERVIEW")
4988 (setq org-cycle-global-status 'overview)
4989 (run-hook-with-args 'org-cycle-hook 'overview))))
4991 (defun org-cycle-internal-local ()
4992 "Do the local cycling action."
4993 (org-back-to-heading)
4994 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
4995 ;; First, some boundaries
4996 (save-excursion
4997 (org-back-to-heading)
4998 (setq level (funcall outline-level))
4999 (save-excursion
5000 (beginning-of-line 2)
5001 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5002 ; XEmacs does not have `next-single-char-property-change'
5003 ; I'm not sure about Emacs 21.
5004 (while (and (not (eobp)) ;; this is like `next-line'
5005 (get-char-property (1- (point)) 'invisible))
5006 (beginning-of-line 2))
5007 (while (and (not (eobp)) ;; this is like `next-line'
5008 (get-char-property (1- (point)) 'invisible))
5009 (goto-char (next-single-char-property-change (point) 'invisible))
5010 ;;;??? (or (bolp) (beginning-of-line 2))))
5011 (and (eolp) (beginning-of-line 2))))
5012 (setq eol (point)))
5013 (outline-end-of-heading) (setq eoh (point))
5014 (save-excursion
5015 (outline-next-heading)
5016 (setq has-children (and (org-at-heading-p t)
5017 (> (funcall outline-level) level))))
5018 (org-end-of-subtree t)
5019 (unless (eobp)
5020 (skip-chars-forward " \t\n")
5021 (beginning-of-line 1) ; in case this is an item
5023 (setq eos (if (eobp) (point) (1- (point)))))
5024 ;; Find out what to do next and set `this-command'
5025 (cond
5026 ((= eos eoh)
5027 ;; Nothing is hidden behind this heading
5028 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5029 (message "EMPTY ENTRY")
5030 (setq org-cycle-subtree-status nil)
5031 (save-excursion
5032 (goto-char eos)
5033 (outline-next-heading)
5034 (if (org-invisible-p) (org-flag-heading nil))))
5035 ((and (or (>= eol eos)
5036 (not (string-match "\\S-" (buffer-substring eol eos))))
5037 (or has-children
5038 (not (setq children-skipped
5039 org-cycle-skip-children-state-if-no-children))))
5040 ;; Entire subtree is hidden in one line: children view
5041 (run-hook-with-args 'org-pre-cycle-hook 'children)
5042 (org-show-entry)
5043 (show-children)
5044 (message "CHILDREN")
5045 (save-excursion
5046 (goto-char eos)
5047 (outline-next-heading)
5048 (if (org-invisible-p) (org-flag-heading nil)))
5049 (setq org-cycle-subtree-status 'children)
5050 (run-hook-with-args 'org-cycle-hook 'children))
5051 ((or children-skipped
5052 (and (eq last-command this-command)
5053 (eq org-cycle-subtree-status 'children)))
5054 ;; We just showed the children, or no children are there,
5055 ;; now show everything.
5056 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5057 (org-show-subtree)
5058 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5059 (setq org-cycle-subtree-status 'subtree)
5060 (run-hook-with-args 'org-cycle-hook 'subtree))
5062 ;; Default action: hide the subtree.
5063 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5064 (hide-subtree)
5065 (message "FOLDED")
5066 (setq org-cycle-subtree-status 'folded)
5067 (run-hook-with-args 'org-cycle-hook 'folded)))))
5069 ;;;###autoload
5070 (defun org-global-cycle (&optional arg)
5071 "Cycle the global visibility. For details see `org-cycle'.
5072 With C-u prefix arg, switch to startup visibility.
5073 With a numeric prefix, show all headlines up to that level."
5074 (interactive "P")
5075 (let ((org-cycle-include-plain-lists
5076 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5077 (cond
5078 ((integerp arg)
5079 (show-all)
5080 (hide-sublevels arg)
5081 (setq org-cycle-global-status 'contents))
5082 ((equal arg '(4))
5083 (org-set-startup-visibility)
5084 (message "Startup visibility, plus VISIBILITY properties."))
5086 (org-cycle '(4))))))
5088 (defun org-set-startup-visibility ()
5089 "Set the visibility required by startup options and properties."
5090 (cond
5091 ((eq org-startup-folded t)
5092 (org-cycle '(4)))
5093 ((eq org-startup-folded 'content)
5094 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5095 (org-cycle '(4)) (org-cycle '(4)))))
5096 (if org-hide-block-startup (org-hide-block-all))
5097 (org-set-visibility-according-to-property 'no-cleanup)
5098 (org-cycle-hide-archived-subtrees 'all)
5099 (org-cycle-hide-drawers 'all)
5100 (org-cycle-show-empty-lines 'all))
5102 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5103 "Switch subtree visibilities according to :VISIBILITY: property."
5104 (interactive)
5105 (let (org-show-entry-below state)
5106 (save-excursion
5107 (goto-char (point-min))
5108 (while (re-search-forward
5109 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5110 nil t)
5111 (setq state (match-string 1))
5112 (save-excursion
5113 (org-back-to-heading t)
5114 (hide-subtree)
5115 (org-reveal)
5116 (cond
5117 ((equal state '("fold" "folded"))
5118 (hide-subtree))
5119 ((equal state "children")
5120 (org-show-hidden-entry)
5121 (show-children))
5122 ((equal state "content")
5123 (save-excursion
5124 (save-restriction
5125 (org-narrow-to-subtree)
5126 (org-content))))
5127 ((member state '("all" "showall"))
5128 (show-subtree)))))
5129 (unless no-cleanup
5130 (org-cycle-hide-archived-subtrees 'all)
5131 (org-cycle-hide-drawers 'all)
5132 (org-cycle-show-empty-lines 'all)))))
5134 (defun org-overview ()
5135 "Switch to overview mode, showing only top-level headlines.
5136 Really, this shows all headlines with level equal or greater than the level
5137 of the first headline in the buffer. This is important, because if the
5138 first headline is not level one, then (hide-sublevels 1) gives confusing
5139 results."
5140 (interactive)
5141 (let ((level (save-excursion
5142 (goto-char (point-min))
5143 (if (re-search-forward (concat "^" outline-regexp) nil t)
5144 (progn
5145 (goto-char (match-beginning 0))
5146 (funcall outline-level))))))
5147 (and level (hide-sublevels level))))
5149 (defun org-content (&optional arg)
5150 "Show all headlines in the buffer, like a table of contents.
5151 With numerical argument N, show content up to level N."
5152 (interactive "P")
5153 (save-excursion
5154 ;; Visit all headings and show their offspring
5155 (and (integerp arg) (org-overview))
5156 (goto-char (point-max))
5157 (catch 'exit
5158 (while (and (progn (condition-case nil
5159 (outline-previous-visible-heading 1)
5160 (error (goto-char (point-min))))
5162 (looking-at outline-regexp))
5163 (if (integerp arg)
5164 (show-children (1- arg))
5165 (show-branches))
5166 (if (bobp) (throw 'exit nil))))))
5169 (defun org-optimize-window-after-visibility-change (state)
5170 "Adjust the window after a change in outline visibility.
5171 This function is the default value of the hook `org-cycle-hook'."
5172 (when (get-buffer-window (current-buffer))
5173 (cond
5174 ((eq state 'content) nil)
5175 ((eq state 'all) nil)
5176 ((eq state 'folded) nil)
5177 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5178 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5180 ;; FIXME: no longer in use
5181 (defun org-compact-display-after-subtree-move ()
5182 "Show a compacter version of the tree of the entry's parent."
5183 (save-excursion
5184 (if (org-up-heading-safe)
5185 (progn
5186 (hide-subtree)
5187 (show-entry)
5188 (show-children)
5189 (org-cycle-show-empty-lines 'children)
5190 (org-cycle-hide-drawers 'children))
5191 (org-overview))))
5193 (defun org-remove-empty-overlays-at (pos)
5194 "Remove outline overlays that do not contain non-white stuff."
5195 (mapc
5196 (lambda (o)
5197 (and (eq 'outline (org-overlay-get o 'invisible))
5198 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5199 (org-overlay-end o))))
5200 (org-delete-overlay o)))
5201 (org-overlays-at pos)))
5203 (defun org-clean-visibility-after-subtree-move ()
5204 "Fix visibility issues after moving a subtree."
5205 ;; First, find a reasonable region to look at:
5206 ;; Start two siblings above, end three below
5207 (let* ((beg (save-excursion
5208 (and (org-get-last-sibling)
5209 (org-get-last-sibling))
5210 (point)))
5211 (end (save-excursion
5212 (and (org-get-next-sibling)
5213 (org-get-next-sibling)
5214 (org-get-next-sibling))
5215 (if (org-at-heading-p)
5216 (point-at-eol)
5217 (point))))
5218 (level (looking-at "\\*+"))
5219 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5220 (save-excursion
5221 (save-restriction
5222 (narrow-to-region beg end)
5223 (when re
5224 ;; Properly fold already folded siblings
5225 (goto-char (point-min))
5226 (while (re-search-forward re nil t)
5227 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5228 (hide-entry))))
5229 (org-cycle-show-empty-lines 'overview)
5230 (org-cycle-hide-drawers 'overview)))))
5232 (defun org-cycle-show-empty-lines (state)
5233 "Show empty lines above all visible headlines.
5234 The region to be covered depends on STATE when called through
5235 `org-cycle-hook'. Lisp program can use t for STATE to get the
5236 entire buffer covered. Note that an empty line is only shown if there
5237 are at least `org-cycle-separator-lines' empty lines before the headline."
5238 (when (not (= org-cycle-separator-lines 0))
5239 (save-excursion
5240 (let* ((n (abs org-cycle-separator-lines))
5241 (re (cond
5242 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5243 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5244 (t (let ((ns (number-to-string (- n 2))))
5245 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5246 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5247 beg end b e)
5248 (cond
5249 ((memq state '(overview contents t))
5250 (setq beg (point-min) end (point-max)))
5251 ((memq state '(children folded))
5252 (setq beg (point) end (progn (org-end-of-subtree t t)
5253 (beginning-of-line 2)
5254 (point)))))
5255 (when beg
5256 (goto-char beg)
5257 (while (re-search-forward re end t)
5258 (unless (get-char-property (match-end 1) 'invisible)
5259 (setq e (match-end 1))
5260 (if (< org-cycle-separator-lines 0)
5261 (setq b (save-excursion
5262 (goto-char (match-beginning 0))
5263 (org-back-over-empty-lines)
5264 (if (save-excursion
5265 (goto-char (max (point-min) (1- (point))))
5266 (org-on-heading-p))
5267 (1- (point))
5268 (point))))
5269 (setq b (match-beginning 1)))
5270 (outline-flag-region b e nil)))))))
5271 ;; Never hide empty lines at the end of the file.
5272 (save-excursion
5273 (goto-char (point-max))
5274 (outline-previous-heading)
5275 (outline-end-of-heading)
5276 (if (and (looking-at "[ \t\n]+")
5277 (= (match-end 0) (point-max)))
5278 (outline-flag-region (point) (match-end 0) nil))))
5280 (defun org-show-empty-lines-in-parent ()
5281 "Move to the parent and re-show empty lines before visible headlines."
5282 (save-excursion
5283 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5284 (org-cycle-show-empty-lines context))))
5286 (defun org-cycle-hide-drawers (state)
5287 "Re-hide all drawers after a visibility state change."
5288 (when (and (org-mode-p)
5289 (not (memq state '(overview folded contents))))
5290 (save-excursion
5291 (let* ((globalp (memq state '(contents all)))
5292 (beg (if globalp (point-min) (point)))
5293 (end (if globalp (point-max)
5294 (if (eq state 'children)
5295 (save-excursion (outline-next-heading) (point))
5296 (org-end-of-subtree t)))))
5297 (goto-char beg)
5298 (while (re-search-forward org-drawer-regexp end t)
5299 (org-flag-drawer t))))))
5301 (defun org-flag-drawer (flag)
5302 (save-excursion
5303 (beginning-of-line 1)
5304 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5305 (let ((b (match-end 0))
5306 (outline-regexp org-outline-regexp))
5307 (if (re-search-forward
5308 "^[ \t]*:END:"
5309 (save-excursion (outline-next-heading) (point)) t)
5310 (outline-flag-region b (point-at-eol) flag)
5311 (error ":END: line missing at position %s" b))))))
5313 (defun org-subtree-end-visible-p ()
5314 "Is the end of the current subtree visible?"
5315 (pos-visible-in-window-p
5316 (save-excursion (org-end-of-subtree t) (point))))
5318 (defun org-first-headline-recenter (&optional N)
5319 "Move cursor to the first headline and recenter the headline.
5320 Optional argument N means, put the headline into the Nth line of the window."
5321 (goto-char (point-min))
5322 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5323 (beginning-of-line)
5324 (recenter (prefix-numeric-value N))))
5326 ;;; Folding of blocks
5328 (defconst org-block-regexp
5330 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5331 "Regular expression for hiding blocks.")
5333 (defvar org-hide-block-overlays nil
5334 "Overays hiding blocks.")
5335 (make-variable-buffer-local 'org-hide-block-overlays)
5337 (defun org-block-map (function &optional start end)
5338 "Call func at the head of all source blocks in the current
5339 buffer. Optional arguments START and END can be used to limit
5340 the range."
5341 (let ((start (or start (point-min)))
5342 (end (or end (point-max))))
5343 (save-excursion
5344 (goto-char start)
5345 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5346 (save-excursion
5347 (save-match-data
5348 (goto-char (match-beginning 0))
5349 (funcall function)))))))
5351 (defun org-hide-block-toggle-all ()
5352 "Toggle the visibility of all blocks in the current buffer."
5353 (org-block-map #'org-hide-block-toggle))
5355 (defun org-hide-block-all ()
5356 "Fold all blocks in the current buffer."
5357 (interactive)
5358 (org-show-block-all)
5359 (org-block-map #'org-hide-block-toggle-maybe))
5361 (defun org-show-block-all ()
5362 "Unfold all blocks in the current buffer."
5363 (mapc 'org-delete-overlay org-hide-block-overlays)
5364 (setq org-hide-block-overlays nil))
5366 (defun org-hide-block-toggle-maybe ()
5367 "Toggle visibility of block at point."
5368 (interactive)
5369 (let ((case-fold-search t))
5370 (if (save-excursion
5371 (beginning-of-line 1)
5372 (looking-at org-block-regexp))
5373 (progn (org-hide-block-toggle)
5374 t) ;; to signal that we took action
5375 nil))) ;; to signal that we did not
5377 (defun org-hide-block-toggle (&optional force)
5378 "Toggle the visibility of the current block."
5379 (interactive)
5380 (save-excursion
5381 (beginning-of-line)
5382 (if (re-search-forward org-block-regexp nil t)
5383 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5384 (end (match-end 0)) ;; end of entire body
5386 (if (memq t (mapcar (lambda (overlay)
5387 (eq (org-overlay-get overlay 'invisible)
5388 'org-hide-block))
5389 (org-overlays-at start)))
5390 (if (or (not force) (eq force 'off))
5391 (mapc (lambda (ov)
5392 (when (member ov org-hide-block-overlays)
5393 (setq org-hide-block-overlays
5394 (delq ov org-hide-block-overlays)))
5395 (when (eq (org-overlay-get ov 'invisible)
5396 'org-hide-block)
5397 (org-delete-overlay ov)))
5398 (org-overlays-at start)))
5399 (setq ov (org-make-overlay start end))
5400 (org-overlay-put ov 'invisible 'org-hide-block)
5401 ;; make the block accessible to isearch
5402 (org-overlay-put
5403 ov 'isearch-open-invisible
5404 (lambda (ov)
5405 (when (member ov org-hide-block-overlays)
5406 (setq org-hide-block-overlays
5407 (delq ov org-hide-block-overlays)))
5408 (when (eq (org-overlay-get ov 'invisible)
5409 'org-hide-block)
5410 (org-delete-overlay ov))))
5411 (push ov org-hide-block-overlays)))
5412 (error "Not looking at a source block"))))
5414 ;; org-tab-after-check-for-cycling-hook
5415 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5416 ;; Remove overlays when changing major mode
5417 (add-hook 'org-mode-hook
5418 (lambda () (org-add-hook 'change-major-mode-hook
5419 'org-show-block-all 'append 'local)))
5421 ;;; Org-goto
5423 (defvar org-goto-window-configuration nil)
5424 (defvar org-goto-marker nil)
5425 (defvar org-goto-map
5426 (let ((map (make-sparse-keymap)))
5427 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5428 (while (setq cmd (pop cmds))
5429 (substitute-key-definition cmd cmd map global-map)))
5430 (suppress-keymap map)
5431 (org-defkey map "\C-m" 'org-goto-ret)
5432 (org-defkey map [(return)] 'org-goto-ret)
5433 (org-defkey map [(left)] 'org-goto-left)
5434 (org-defkey map [(right)] 'org-goto-right)
5435 (org-defkey map [(control ?g)] 'org-goto-quit)
5436 (org-defkey map "\C-i" 'org-cycle)
5437 (org-defkey map [(tab)] 'org-cycle)
5438 (org-defkey map [(down)] 'outline-next-visible-heading)
5439 (org-defkey map [(up)] 'outline-previous-visible-heading)
5440 (if org-goto-auto-isearch
5441 (if (fboundp 'define-key-after)
5442 (define-key-after map [t] 'org-goto-local-auto-isearch)
5443 nil)
5444 (org-defkey map "q" 'org-goto-quit)
5445 (org-defkey map "n" 'outline-next-visible-heading)
5446 (org-defkey map "p" 'outline-previous-visible-heading)
5447 (org-defkey map "f" 'outline-forward-same-level)
5448 (org-defkey map "b" 'outline-backward-same-level)
5449 (org-defkey map "u" 'outline-up-heading))
5450 (org-defkey map "/" 'org-occur)
5451 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5452 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5453 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5454 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5455 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5456 map))
5458 (defconst org-goto-help
5459 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5460 RET=jump to location [Q]uit and return to previous location
5461 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5463 (defvar org-goto-start-pos) ; dynamically scoped parameter
5465 ;; FIXME: Docstring doe not mention both interfaces
5466 (defun org-goto (&optional alternative-interface)
5467 "Look up a different location in the current file, keeping current visibility.
5469 When you want look-up or go to a different location in a document, the
5470 fastest way is often to fold the entire buffer and then dive into the tree.
5471 This method has the disadvantage, that the previous location will be folded,
5472 which may not be what you want.
5474 This command works around this by showing a copy of the current buffer
5475 in an indirect buffer, in overview mode. You can dive into the tree in
5476 that copy, use org-occur and incremental search to find a location.
5477 When pressing RET or `Q', the command returns to the original buffer in
5478 which the visibility is still unchanged. After RET is will also jump to
5479 the location selected in the indirect buffer and expose the
5480 the headline hierarchy above."
5481 (interactive "P")
5482 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5483 (org-refile-use-outline-path t)
5484 (org-refile-target-verify-function nil)
5485 (interface
5486 (if (not alternative-interface)
5487 org-goto-interface
5488 (if (eq org-goto-interface 'outline)
5489 'outline-path-completion
5490 'outline)))
5491 (org-goto-start-pos (point))
5492 (selected-point
5493 (if (eq interface 'outline)
5494 (car (org-get-location (current-buffer) org-goto-help))
5495 (nth 3 (org-refile-get-location "Goto: ")))))
5496 (if selected-point
5497 (progn
5498 (org-mark-ring-push org-goto-start-pos)
5499 (goto-char selected-point)
5500 (if (or (org-invisible-p) (org-invisible-p2))
5501 (org-show-context 'org-goto)))
5502 (message "Quit"))))
5504 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5505 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5506 (defvar org-goto-local-auto-isearch-map) ; defined below
5508 (defun org-get-location (buf help)
5509 "Let the user select a location in the Org-mode buffer BUF.
5510 This function uses a recursive edit. It returns the selected position
5511 or nil."
5512 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5513 (isearch-hide-immediately nil)
5514 (isearch-search-fun-function
5515 (lambda () 'org-goto-local-search-headings))
5516 (org-goto-selected-point org-goto-exit-command))
5517 (save-excursion
5518 (save-window-excursion
5519 (delete-other-windows)
5520 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5521 (switch-to-buffer
5522 (condition-case nil
5523 (make-indirect-buffer (current-buffer) "*org-goto*")
5524 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5525 (with-output-to-temp-buffer "*Help*"
5526 (princ help))
5527 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5528 (setq buffer-read-only nil)
5529 (let ((org-startup-truncated t)
5530 (org-startup-folded nil)
5531 (org-startup-align-all-tables nil))
5532 (org-mode)
5533 (org-overview))
5534 (setq buffer-read-only t)
5535 (if (and (boundp 'org-goto-start-pos)
5536 (integer-or-marker-p org-goto-start-pos))
5537 (let ((org-show-hierarchy-above t)
5538 (org-show-siblings t)
5539 (org-show-following-heading t))
5540 (goto-char org-goto-start-pos)
5541 (and (org-invisible-p) (org-show-context)))
5542 (goto-char (point-min)))
5543 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5544 (message "Select location and press RET")
5545 (use-local-map org-goto-map)
5546 (recursive-edit)
5548 (kill-buffer "*org-goto*")
5549 (cons org-goto-selected-point org-goto-exit-command)))
5551 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5552 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5553 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5554 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5556 (defun org-goto-local-search-headings (string bound noerror)
5557 "Search and make sure that any matches are in headlines."
5558 (catch 'return
5559 (while (if isearch-forward
5560 (search-forward string bound noerror)
5561 (search-backward string bound noerror))
5562 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5563 (and (member :headline context)
5564 (not (member :tags context))))
5565 (throw 'return (point))))))
5567 (defun org-goto-local-auto-isearch ()
5568 "Start isearch."
5569 (interactive)
5570 (goto-char (point-min))
5571 (let ((keys (this-command-keys)))
5572 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5573 (isearch-mode t)
5574 (isearch-process-search-char (string-to-char keys)))))
5576 (defun org-goto-ret (&optional arg)
5577 "Finish `org-goto' by going to the new location."
5578 (interactive "P")
5579 (setq org-goto-selected-point (point)
5580 org-goto-exit-command 'return)
5581 (throw 'exit nil))
5583 (defun org-goto-left ()
5584 "Finish `org-goto' by going to the new location."
5585 (interactive)
5586 (if (org-on-heading-p)
5587 (progn
5588 (beginning-of-line 1)
5589 (setq org-goto-selected-point (point)
5590 org-goto-exit-command 'left)
5591 (throw 'exit nil))
5592 (error "Not on a heading")))
5594 (defun org-goto-right ()
5595 "Finish `org-goto' by going to the new location."
5596 (interactive)
5597 (if (org-on-heading-p)
5598 (progn
5599 (setq org-goto-selected-point (point)
5600 org-goto-exit-command 'right)
5601 (throw 'exit nil))
5602 (error "Not on a heading")))
5604 (defun org-goto-quit ()
5605 "Finish `org-goto' without cursor motion."
5606 (interactive)
5607 (setq org-goto-selected-point nil)
5608 (setq org-goto-exit-command 'quit)
5609 (throw 'exit nil))
5611 ;;; Indirect buffer display of subtrees
5613 (defvar org-indirect-dedicated-frame nil
5614 "This is the frame being used for indirect tree display.")
5615 (defvar org-last-indirect-buffer nil)
5617 (defun org-tree-to-indirect-buffer (&optional arg)
5618 "Create indirect buffer and narrow it to current subtree.
5619 With numerical prefix ARG, go up to this level and then take that tree.
5620 If ARG is negative, go up that many levels.
5621 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5622 indirect buffer previously made with this command, to avoid proliferation of
5623 indirect buffers. However, when you call the command with a `C-u' prefix, or
5624 when `org-indirect-buffer-display' is `new-frame', the last buffer
5625 is kept so that you can work with several indirect buffers at the same time.
5626 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5627 requests that a new frame be made for the new buffer, so that the dedicated
5628 frame is not changed."
5629 (interactive "P")
5630 (let ((cbuf (current-buffer))
5631 (cwin (selected-window))
5632 (pos (point))
5633 beg end level heading ibuf)
5634 (save-excursion
5635 (org-back-to-heading t)
5636 (when (numberp arg)
5637 (setq level (org-outline-level))
5638 (if (< arg 0) (setq arg (+ level arg)))
5639 (while (> (setq level (org-outline-level)) arg)
5640 (outline-up-heading 1 t)))
5641 (setq beg (point)
5642 heading (org-get-heading))
5643 (org-end-of-subtree t) (setq end (point)))
5644 (if (and (buffer-live-p org-last-indirect-buffer)
5645 (not (eq org-indirect-buffer-display 'new-frame))
5646 (not arg))
5647 (kill-buffer org-last-indirect-buffer))
5648 (setq ibuf (org-get-indirect-buffer cbuf)
5649 org-last-indirect-buffer ibuf)
5650 (cond
5651 ((or (eq org-indirect-buffer-display 'new-frame)
5652 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5653 (select-frame (make-frame))
5654 (delete-other-windows)
5655 (switch-to-buffer ibuf)
5656 (org-set-frame-title heading))
5657 ((eq org-indirect-buffer-display 'dedicated-frame)
5658 (raise-frame
5659 (select-frame (or (and org-indirect-dedicated-frame
5660 (frame-live-p org-indirect-dedicated-frame)
5661 org-indirect-dedicated-frame)
5662 (setq org-indirect-dedicated-frame (make-frame)))))
5663 (delete-other-windows)
5664 (switch-to-buffer ibuf)
5665 (org-set-frame-title (concat "Indirect: " heading)))
5666 ((eq org-indirect-buffer-display 'current-window)
5667 (switch-to-buffer ibuf))
5668 ((eq org-indirect-buffer-display 'other-window)
5669 (pop-to-buffer ibuf))
5670 (t (error "Invalid value.")))
5671 (if (featurep 'xemacs)
5672 (save-excursion (org-mode) (turn-on-font-lock)))
5673 (narrow-to-region beg end)
5674 (show-all)
5675 (goto-char pos)
5676 (and (window-live-p cwin) (select-window cwin))))
5678 (defun org-get-indirect-buffer (&optional buffer)
5679 (setq buffer (or buffer (current-buffer)))
5680 (let ((n 1) (base (buffer-name buffer)) bname)
5681 (while (buffer-live-p
5682 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5683 (setq n (1+ n)))
5684 (condition-case nil
5685 (make-indirect-buffer buffer bname 'clone)
5686 (error (make-indirect-buffer buffer bname)))))
5688 (defun org-set-frame-title (title)
5689 "Set the title of the current frame to the string TITLE."
5690 ;; FIXME: how to name a single frame in XEmacs???
5691 (unless (featurep 'xemacs)
5692 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5694 ;;;; Structure editing
5696 ;;; Inserting headlines
5698 (defun org-previous-line-empty-p ()
5699 (save-excursion
5700 (and (not (bobp))
5701 (or (beginning-of-line 0) t)
5702 (save-match-data
5703 (looking-at "[ \t]*$")))))
5705 (defun org-insert-heading (&optional force-heading)
5706 "Insert a new heading or item with same depth at point.
5707 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5708 If point is at the beginning of a headline, insert a sibling before the
5709 current headline. If point is not at the beginning, do not split the line,
5710 but create the new headline after the current line."
5711 (interactive "P")
5712 (if (= (buffer-size) 0)
5713 (insert "\n* ")
5714 (when (or force-heading (not (org-insert-item)))
5715 (let* ((empty-line-p nil)
5716 (head (save-excursion
5717 (condition-case nil
5718 (progn
5719 (org-back-to-heading)
5720 (setq empty-line-p (org-previous-line-empty-p))
5721 (match-string 0))
5722 (error "*"))))
5723 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5724 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5725 pos hide-previous previous-pos)
5726 (cond
5727 ((and (org-on-heading-p) (bolp)
5728 (or (bobp)
5729 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5730 ;; insert before the current line
5731 (open-line (if blank 2 1)))
5732 ((and (bolp)
5733 (not org-insert-heading-respect-content)
5734 (or (bobp)
5735 (save-excursion
5736 (backward-char 1) (not (org-invisible-p)))))
5737 ;; insert right here
5738 nil)
5740 ;; somewhere in the line
5741 (save-excursion
5742 (setq previous-pos (point-at-bol))
5743 (end-of-line)
5744 (setq hide-previous (org-invisible-p)))
5745 (and org-insert-heading-respect-content (org-show-subtree))
5746 (let ((split
5747 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5748 (save-excursion
5749 (let ((p (point)))
5750 (goto-char (point-at-bol))
5751 (and (looking-at org-complex-heading-regexp)
5752 (> p (match-beginning 4)))))))
5753 tags pos)
5754 (cond
5755 (org-insert-heading-respect-content
5756 (org-end-of-subtree nil t)
5757 (or (bolp) (newline))
5758 (or (org-previous-line-empty-p)
5759 (and blank (newline)))
5760 (open-line 1))
5761 ((org-on-heading-p)
5762 (when hide-previous
5763 (show-children)
5764 (org-show-entry))
5765 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5766 (setq tags (and (match-end 2) (match-string 2)))
5767 (and (match-end 1)
5768 (delete-region (match-beginning 1) (match-end 1)))
5769 (setq pos (point-at-bol))
5770 (or split (end-of-line 1))
5771 (delete-horizontal-space)
5772 (newline (if blank 2 1))
5773 (when tags
5774 (save-excursion
5775 (goto-char pos)
5776 (end-of-line 1)
5777 (insert " " tags)
5778 (org-set-tags nil 'align))))
5780 (or split (end-of-line 1))
5781 (newline (if blank 2 1)))))))
5782 (insert head) (just-one-space)
5783 (setq pos (point))
5784 (end-of-line 1)
5785 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5786 (when (and org-insert-heading-respect-content hide-previous)
5787 (save-excursion
5788 (goto-char previous-pos)
5789 (hide-subtree)))
5790 (run-hooks 'org-insert-heading-hook)))))
5792 (defun org-get-heading (&optional no-tags)
5793 "Return the heading of the current entry, without the stars."
5794 (save-excursion
5795 (org-back-to-heading t)
5796 (if (looking-at
5797 (if no-tags
5798 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5799 "\\*+[ \t]+\\([^\r\n]*\\)"))
5800 (match-string 1) "")))
5802 (defun org-heading-components ()
5803 "Return the components of the current heading.
5804 This is a list with the following elements:
5805 - the level as an integer
5806 - the reduced level, different if `org-odd-levels-only' is set.
5807 - the TODO keyword, or nil
5808 - the priority character, like ?A, or nil if no priority is given
5809 - the headline text itself, or the tags string if no headline text
5810 - the tags string, or nil."
5811 (save-excursion
5812 (org-back-to-heading t)
5813 (if (looking-at org-complex-heading-regexp)
5814 (list (length (match-string 1))
5815 (org-reduced-level (length (match-string 1)))
5816 (org-match-string-no-properties 2)
5817 (and (match-end 3) (aref (match-string 3) 2))
5818 (org-match-string-no-properties 4)
5819 (org-match-string-no-properties 5)))))
5821 (defun org-get-entry ()
5822 "Get the entry text, after heading, entire subtree."
5823 (save-excursion
5824 (org-back-to-heading t)
5825 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5827 (defun org-insert-heading-after-current ()
5828 "Insert a new heading with same level as current, after current subtree."
5829 (interactive)
5830 (org-back-to-heading)
5831 (org-insert-heading)
5832 (org-move-subtree-down)
5833 (end-of-line 1))
5835 (defun org-insert-heading-respect-content ()
5836 (interactive)
5837 (let ((org-insert-heading-respect-content t))
5838 (org-insert-heading t)))
5840 (defun org-insert-todo-heading-respect-content (&optional force-state)
5841 (interactive "P")
5842 (let ((org-insert-heading-respect-content t))
5843 (org-insert-todo-heading force-state t)))
5845 (defun org-insert-todo-heading (arg &optional force-heading)
5846 "Insert a new heading with the same level and TODO state as current heading.
5847 If the heading has no TODO state, or if the state is DONE, use the first
5848 state (TODO by default). Also with prefix arg, force first state."
5849 (interactive "P")
5850 (when (or force-heading (not (org-insert-item 'checkbox)))
5851 (org-insert-heading force-heading)
5852 (save-excursion
5853 (org-back-to-heading)
5854 (outline-previous-heading)
5855 (looking-at org-todo-line-regexp))
5856 (let*
5857 ((new-mark-x
5858 (if (or arg
5859 (not (match-beginning 2))
5860 (member (match-string 2) org-done-keywords))
5861 (car org-todo-keywords-1)
5862 (match-string 2)))
5863 (new-mark
5865 (run-hook-with-args-until-success
5866 'org-todo-get-default-hook new-mark-x nil)
5867 new-mark-x)))
5868 (beginning-of-line 1)
5869 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5870 (if org-treat-insert-todo-heading-as-state-change
5871 (org-todo new-mark)
5872 (insert new-mark " "))))
5873 (when org-provide-todo-statistics
5874 (org-update-parent-todo-statistics))))
5876 (defun org-insert-subheading (arg)
5877 "Insert a new subheading and demote it.
5878 Works for outline headings and for plain lists alike."
5879 (interactive "P")
5880 (org-insert-heading arg)
5881 (cond
5882 ((org-on-heading-p) (org-do-demote))
5883 ((org-at-item-p) (org-indent-item 1))))
5885 (defun org-insert-todo-subheading (arg)
5886 "Insert a new subheading with TODO keyword or checkbox and demote it.
5887 Works for outline headings and for plain lists alike."
5888 (interactive "P")
5889 (org-insert-todo-heading arg)
5890 (cond
5891 ((org-on-heading-p) (org-do-demote))
5892 ((org-at-item-p) (org-indent-item 1))))
5894 ;;; Promotion and Demotion
5896 (defvar org-after-demote-entry-hook nil
5897 "Hook run after an entry has been demoted.
5898 The cursor will be at the beginning of the entry.
5899 When a subtree is being demoted, the hook will be called for each node.")
5901 (defvar org-after-promote-entry-hook nil
5902 "Hook run after an entry has been promoted.
5903 The cursor will be at the beginning of the entry.
5904 When a subtree is being promoted, the hook will be called for each node.")
5906 (defun org-promote-subtree ()
5907 "Promote the entire subtree.
5908 See also `org-promote'."
5909 (interactive)
5910 (save-excursion
5911 (org-map-tree 'org-promote))
5912 (org-fix-position-after-promote))
5914 (defun org-demote-subtree ()
5915 "Demote the entire subtree. See `org-demote'.
5916 See also `org-promote'."
5917 (interactive)
5918 (save-excursion
5919 (org-map-tree 'org-demote))
5920 (org-fix-position-after-promote))
5923 (defun org-do-promote ()
5924 "Promote the current heading higher up the tree.
5925 If the region is active in `transient-mark-mode', promote all headings
5926 in the region."
5927 (interactive)
5928 (save-excursion
5929 (if (org-region-active-p)
5930 (org-map-region 'org-promote (region-beginning) (region-end))
5931 (org-promote)))
5932 (org-fix-position-after-promote))
5934 (defun org-do-demote ()
5935 "Demote the current heading lower down the tree.
5936 If the region is active in `transient-mark-mode', demote all headings
5937 in the region."
5938 (interactive)
5939 (save-excursion
5940 (if (org-region-active-p)
5941 (org-map-region 'org-demote (region-beginning) (region-end))
5942 (org-demote)))
5943 (org-fix-position-after-promote))
5945 (defun org-fix-position-after-promote ()
5946 "Make sure that after pro/demotion cursor position is right."
5947 (let ((pos (point)))
5948 (when (save-excursion
5949 (beginning-of-line 1)
5950 (looking-at org-todo-line-regexp)
5951 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5952 (cond ((eobp) (insert " "))
5953 ((eolp) (insert " "))
5954 ((equal (char-after) ?\ ) (forward-char 1))))))
5956 (defun org-reduced-level (l)
5957 "Compute the effective level of a heading.
5958 This takes into account the setting of `org-odd-levels-only'."
5959 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5961 (defun org-get-valid-level (level &optional change)
5962 "Rectify a level change under the influence of `org-odd-levels-only'
5963 LEVEL is a current level, CHANGE is by how much the level should be
5964 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5965 even level numbers will become the next higher odd number."
5966 (if org-odd-levels-only
5967 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5968 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5969 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5970 (max 1 (+ level (or change 0)))))
5972 (if (boundp 'define-obsolete-function-alias)
5973 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5974 (define-obsolete-function-alias 'org-get-legal-level
5975 'org-get-valid-level)
5976 (define-obsolete-function-alias 'org-get-legal-level
5977 'org-get-valid-level "23.1")))
5979 (defun org-promote ()
5980 "Promote the current heading higher up the tree.
5981 If the region is active in `transient-mark-mode', promote all headings
5982 in the region."
5983 (org-back-to-heading t)
5984 (let* ((level (save-match-data (funcall outline-level)))
5985 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5986 (diff (abs (- level (length up-head) -1))))
5987 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5988 (replace-match up-head nil t)
5989 ;; Fixup tag positioning
5990 (and org-auto-align-tags (org-set-tags nil t))
5991 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5992 (run-hooks 'org-after-promote-entry-hook)))
5994 (defun org-demote ()
5995 "Demote the current heading lower down the tree.
5996 If the region is active in `transient-mark-mode', demote all headings
5997 in the region."
5998 (org-back-to-heading t)
5999 (let* ((level (save-match-data (funcall outline-level)))
6000 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6001 (diff (abs (- level (length down-head) -1))))
6002 (replace-match down-head nil t)
6003 ;; Fixup tag positioning
6004 (and org-auto-align-tags (org-set-tags nil t))
6005 (if org-adapt-indentation (org-fixup-indentation diff))
6006 (run-hooks 'org-after-demote-entry-hook)))
6008 (defun org-map-tree (fun)
6009 "Call FUN for every heading underneath the current one."
6010 (org-back-to-heading)
6011 (let ((level (funcall outline-level)))
6012 (save-excursion
6013 (funcall fun)
6014 (while (and (progn
6015 (outline-next-heading)
6016 (> (funcall outline-level) level))
6017 (not (eobp)))
6018 (funcall fun)))))
6020 (defun org-map-region (fun beg end)
6021 "Call FUN for every heading between BEG and END."
6022 (let ((org-ignore-region t))
6023 (save-excursion
6024 (setq end (copy-marker end))
6025 (goto-char beg)
6026 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6027 (< (point) end))
6028 (funcall fun))
6029 (while (and (progn
6030 (outline-next-heading)
6031 (< (point) end))
6032 (not (eobp)))
6033 (funcall fun)))))
6035 (defun org-fixup-indentation (diff)
6036 "Change the indentation in the current entry by DIFF
6037 However, if any line in the current entry has no indentation, or if it
6038 would end up with no indentation after the change, nothing at all is done."
6039 (save-excursion
6040 (let ((end (save-excursion (outline-next-heading)
6041 (point-marker)))
6042 (prohibit (if (> diff 0)
6043 "^\\S-"
6044 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6045 col)
6046 (unless (save-excursion (end-of-line 1)
6047 (re-search-forward prohibit end t))
6048 (while (and (< (point) end)
6049 (re-search-forward "^[ \t]+" end t))
6050 (goto-char (match-end 0))
6051 (setq col (current-column))
6052 (if (< diff 0) (replace-match ""))
6053 (org-indent-to-column (+ diff col))))
6054 (move-marker end nil))))
6056 (defun org-convert-to-odd-levels ()
6057 "Convert an org-mode file with all levels allowed to one with odd levels.
6058 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6059 level 5 etc."
6060 (interactive)
6061 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6062 (let ((org-odd-levels-only nil) n)
6063 (save-excursion
6064 (goto-char (point-min))
6065 (while (re-search-forward "^\\*\\*+ " nil t)
6066 (setq n (- (length (match-string 0)) 2))
6067 (while (>= (setq n (1- n)) 0)
6068 (org-demote))
6069 (end-of-line 1))))))
6072 (defun org-convert-to-oddeven-levels ()
6073 "Convert an org-mode file with only odd levels to one with odd and even levels.
6074 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6075 section with an even level, conversion would destroy the structure of the file. An error
6076 is signaled in this case."
6077 (interactive)
6078 (goto-char (point-min))
6079 ;; First check if there are no even levels
6080 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6081 (org-show-context t)
6082 (error "Not all levels are odd in this file. Conversion not possible."))
6083 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6084 (let ((org-odd-levels-only nil) n)
6085 (save-excursion
6086 (goto-char (point-min))
6087 (while (re-search-forward "^\\*\\*+ " nil t)
6088 (setq n (/ (1- (length (match-string 0))) 2))
6089 (while (>= (setq n (1- n)) 0)
6090 (org-promote))
6091 (end-of-line 1))))))
6093 (defun org-tr-level (n)
6094 "Make N odd if required."
6095 (if org-odd-levels-only (1+ (/ n 2)) n))
6097 ;;; Vertical tree motion, cutting and pasting of subtrees
6099 (defun org-move-subtree-up (&optional arg)
6100 "Move the current subtree up past ARG headlines of the same level."
6101 (interactive "p")
6102 (org-move-subtree-down (- (prefix-numeric-value arg))))
6104 (defun org-move-subtree-down (&optional arg)
6105 "Move the current subtree down past ARG headlines of the same level."
6106 (interactive "p")
6107 (setq arg (prefix-numeric-value arg))
6108 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6109 'org-get-last-sibling))
6110 (ins-point (make-marker))
6111 (cnt (abs arg))
6112 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6113 ;; Select the tree
6114 (org-back-to-heading)
6115 (setq beg0 (point))
6116 (save-excursion
6117 (setq ne-beg (org-back-over-empty-lines))
6118 (setq beg (point)))
6119 (save-match-data
6120 (save-excursion (outline-end-of-heading)
6121 (setq folded (org-invisible-p)))
6122 (outline-end-of-subtree))
6123 (outline-next-heading)
6124 (setq ne-end (org-back-over-empty-lines))
6125 (setq end (point))
6126 (goto-char beg0)
6127 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6128 ;; include less whitespace
6129 (save-excursion
6130 (goto-char beg)
6131 (forward-line (- ne-beg ne-end))
6132 (setq beg (point))))
6133 ;; Find insertion point, with error handling
6134 (while (> cnt 0)
6135 (or (and (funcall movfunc) (looking-at outline-regexp))
6136 (progn (goto-char beg0)
6137 (error "Cannot move past superior level or buffer limit")))
6138 (setq cnt (1- cnt)))
6139 (if (> arg 0)
6140 ;; Moving forward - still need to move over subtree
6141 (progn (org-end-of-subtree t t)
6142 (save-excursion
6143 (org-back-over-empty-lines)
6144 (or (bolp) (newline)))))
6145 (setq ne-ins (org-back-over-empty-lines))
6146 (move-marker ins-point (point))
6147 (setq txt (buffer-substring beg end))
6148 (org-save-markers-in-region beg end)
6149 (delete-region beg end)
6150 (org-remove-empty-overlays-at beg)
6151 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6152 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6153 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6154 (let ((bbb (point)))
6155 (insert-before-markers txt)
6156 (org-reinstall-markers-in-region bbb)
6157 (move-marker ins-point bbb))
6158 (or (bolp) (insert "\n"))
6159 (setq ins-end (point))
6160 (goto-char ins-point)
6161 (org-skip-whitespace)
6162 (when (and (< arg 0)
6163 (org-first-sibling-p)
6164 (> ne-ins ne-beg))
6165 ;; Move whitespace back to beginning
6166 (save-excursion
6167 (goto-char ins-end)
6168 (let ((kill-whole-line t))
6169 (kill-line (- ne-ins ne-beg)) (point)))
6170 (insert (make-string (- ne-ins ne-beg) ?\n)))
6171 (move-marker ins-point nil)
6172 (if folded
6173 (hide-subtree)
6174 (org-show-entry)
6175 (show-children)
6176 (org-cycle-hide-drawers 'children))
6177 (org-clean-visibility-after-subtree-move)))
6179 (defvar org-subtree-clip ""
6180 "Clipboard for cut and paste of subtrees.
6181 This is actually only a copy of the kill, because we use the normal kill
6182 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6184 (defvar org-subtree-clip-folded nil
6185 "Was the last copied subtree folded?
6186 This is used to fold the tree back after pasting.")
6188 (defun org-cut-subtree (&optional n)
6189 "Cut the current subtree into the clipboard.
6190 With prefix arg N, cut this many sequential subtrees.
6191 This is a short-hand for marking the subtree and then cutting it."
6192 (interactive "p")
6193 (org-copy-subtree n 'cut))
6195 (defun org-copy-subtree (&optional n cut force-store-markers)
6196 "Cut the current subtree into the clipboard.
6197 With prefix arg N, cut this many sequential subtrees.
6198 This is a short-hand for marking the subtree and then copying it.
6199 If CUT is non-nil, actually cut the subtree.
6200 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6201 of some markers in the region, even if CUT is non-nil. This is
6202 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6203 (interactive "p")
6204 (let (beg end folded (beg0 (point)))
6205 (if (interactive-p)
6206 (org-back-to-heading nil) ; take what looks like a subtree
6207 (org-back-to-heading t)) ; take what is really there
6208 (org-back-over-empty-lines)
6209 (setq beg (point))
6210 (skip-chars-forward " \t\r\n")
6211 (save-match-data
6212 (save-excursion (outline-end-of-heading)
6213 (setq folded (org-invisible-p)))
6214 (condition-case nil
6215 (org-forward-same-level (1- n) t)
6216 (error nil))
6217 (org-end-of-subtree t t))
6218 (org-back-over-empty-lines)
6219 (setq end (point))
6220 (goto-char beg0)
6221 (when (> end beg)
6222 (setq org-subtree-clip-folded folded)
6223 (when (or cut force-store-markers)
6224 (org-save-markers-in-region beg end))
6225 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6226 (setq org-subtree-clip (current-kill 0))
6227 (message "%s: Subtree(s) with %d characters"
6228 (if cut "Cut" "Copied")
6229 (length org-subtree-clip)))))
6231 (defun org-paste-subtree (&optional level tree for-yank)
6232 "Paste the clipboard as a subtree, with modification of headline level.
6233 The entire subtree is promoted or demoted in order to match a new headline
6234 level.
6236 If the cursor is at the beginning of a headline, the same level as
6237 that headline is used to paste the tree
6239 If not, the new level is derived from the *visible* headings
6240 before and after the insertion point, and taken to be the inferior headline
6241 level of the two. So if the previous visible heading is level 3 and the
6242 next is level 4 (or vice versa), level 4 will be used for insertion.
6243 This makes sure that the subtree remains an independent subtree and does
6244 not swallow low level entries.
6246 You can also force a different level, either by using a numeric prefix
6247 argument, or by inserting the heading marker by hand. For example, if the
6248 cursor is after \"*****\", then the tree will be shifted to level 5.
6250 If optional TREE is given, use this text instead of the kill ring.
6252 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6253 move back over whitespace before inserting, and move point to the end of
6254 the inserted text when done."
6255 (interactive "P")
6256 (setq tree (or tree (and kill-ring (current-kill 0))))
6257 (unless (org-kill-is-subtree-p tree)
6258 (error "%s"
6259 (substitute-command-keys
6260 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6261 (let* ((visp (not (org-invisible-p)))
6262 (txt tree)
6263 (^re (concat "^\\(" outline-regexp "\\)"))
6264 (re (concat "\\(" outline-regexp "\\)"))
6265 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6267 (old-level (if (string-match ^re txt)
6268 (- (match-end 0) (match-beginning 0) 1)
6269 -1))
6270 (force-level (cond (level (prefix-numeric-value level))
6271 ((and (looking-at "[ \t]*$")
6272 (string-match
6273 ^re_ (buffer-substring
6274 (point-at-bol) (point))))
6275 (- (match-end 1) (match-beginning 1)))
6276 ((and (bolp)
6277 (looking-at org-outline-regexp))
6278 (- (match-end 0) (point) 1))
6279 (t nil)))
6280 (previous-level (save-excursion
6281 (condition-case nil
6282 (progn
6283 (outline-previous-visible-heading 1)
6284 (if (looking-at re)
6285 (- (match-end 0) (match-beginning 0) 1)
6287 (error 1))))
6288 (next-level (save-excursion
6289 (condition-case nil
6290 (progn
6291 (or (looking-at outline-regexp)
6292 (outline-next-visible-heading 1))
6293 (if (looking-at re)
6294 (- (match-end 0) (match-beginning 0) 1)
6296 (error 1))))
6297 (new-level (or force-level (max previous-level next-level)))
6298 (shift (if (or (= old-level -1)
6299 (= new-level -1)
6300 (= old-level new-level))
6302 (- new-level old-level)))
6303 (delta (if (> shift 0) -1 1))
6304 (func (if (> shift 0) 'org-demote 'org-promote))
6305 (org-odd-levels-only nil)
6306 beg end newend)
6307 ;; Remove the forced level indicator
6308 (if force-level
6309 (delete-region (point-at-bol) (point)))
6310 ;; Paste
6311 (beginning-of-line 1)
6312 (unless for-yank (org-back-over-empty-lines))
6313 (setq beg (point))
6314 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6315 (insert-before-markers txt)
6316 (unless (string-match "\n\\'" txt) (insert "\n"))
6317 (setq newend (point))
6318 (org-reinstall-markers-in-region beg)
6319 (setq end (point))
6320 (goto-char beg)
6321 (skip-chars-forward " \t\n\r")
6322 (setq beg (point))
6323 (if (and (org-invisible-p) visp)
6324 (save-excursion (outline-show-heading)))
6325 ;; Shift if necessary
6326 (unless (= shift 0)
6327 (save-restriction
6328 (narrow-to-region beg end)
6329 (while (not (= shift 0))
6330 (org-map-region func (point-min) (point-max))
6331 (setq shift (+ delta shift)))
6332 (goto-char (point-min))
6333 (setq newend (point-max))))
6334 (when (or (interactive-p) for-yank)
6335 (message "Clipboard pasted as level %d subtree" new-level))
6336 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6337 kill-ring
6338 (eq org-subtree-clip (current-kill 0))
6339 org-subtree-clip-folded)
6340 ;; The tree was folded before it was killed/copied
6341 (hide-subtree))
6342 (and for-yank (goto-char newend))))
6344 (defun org-kill-is-subtree-p (&optional txt)
6345 "Check if the current kill is an outline subtree, or a set of trees.
6346 Returns nil if kill does not start with a headline, or if the first
6347 headline level is not the largest headline level in the tree.
6348 So this will actually accept several entries of equal levels as well,
6349 which is OK for `org-paste-subtree'.
6350 If optional TXT is given, check this string instead of the current kill."
6351 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6352 (start-level (and kill
6353 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6354 org-outline-regexp "\\)")
6355 kill)
6356 (- (match-end 2) (match-beginning 2) 1)))
6357 (re (concat "^" org-outline-regexp))
6358 (start (1+ (or (match-beginning 2) -1))))
6359 (if (not start-level)
6360 (progn
6361 nil) ;; does not even start with a heading
6362 (catch 'exit
6363 (while (setq start (string-match re kill (1+ start)))
6364 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6365 (throw 'exit nil)))
6366 t))))
6368 (defvar org-markers-to-move nil
6369 "Markers that should be moved with a cut-and-paste operation.
6370 Those markers are stored together with their positions relative to
6371 the start of the region.")
6373 (defun org-save-markers-in-region (beg end)
6374 "Check markers in region.
6375 If these markers are between BEG and END, record their position relative
6376 to BEG, so that after moving the block of text, we can put the markers back
6377 into place.
6378 This function gets called just before an entry or tree gets cut from the
6379 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6380 called immediately, to move the markers with the entries."
6381 (setq org-markers-to-move nil)
6382 (when (featurep 'org-clock)
6383 (org-clock-save-markers-for-cut-and-paste beg end))
6384 (when (featurep 'org-agenda)
6385 (org-agenda-save-markers-for-cut-and-paste beg end)))
6387 (defun org-check-and-save-marker (marker beg end)
6388 "Check if MARKER is between BEG and END.
6389 If yes, remember the marker and the distance to BEG."
6390 (when (and (marker-buffer marker)
6391 (equal (marker-buffer marker) (current-buffer)))
6392 (if (and (>= marker beg) (< marker end))
6393 (push (cons marker (- marker beg)) org-markers-to-move))))
6395 (defun org-reinstall-markers-in-region (beg)
6396 "Move all remembered markers to their position relative to BEG."
6397 (mapc (lambda (x)
6398 (move-marker (car x) (+ beg (cdr x))))
6399 org-markers-to-move)
6400 (setq org-markers-to-move nil))
6402 (defun org-narrow-to-subtree ()
6403 "Narrow buffer to the current subtree."
6404 (interactive)
6405 (save-excursion
6406 (save-match-data
6407 (narrow-to-region
6408 (progn (org-back-to-heading t) (point))
6409 (progn (org-end-of-subtree t) (point))))))
6411 (defun org-clone-subtree-with-time-shift (n &optional shift)
6412 "Clone the task (subtree) at point N times.
6413 The clones will be inserted as siblings.
6415 In interactive use, the user will be prompted for the number of clones
6416 to be produced, and for a time SHIFT, which may be a repeater as used
6417 in time stamps, for example `+3d'.
6419 When a valid repeater is given and the entry contains any time stamps,
6420 the clones will become a sequence in time, with time stamps in the
6421 subtree shifted for each clone produced. If SHIFT is nil or the
6422 empty string, time stamps will be left alone.
6424 If the original subtree did contain time stamps with a repeater,
6425 the following will happen:
6426 - the repeater will be removed in each clone
6427 - an additional clone will be produced, with the current, unshifted
6428 date(s) in the entry.
6429 - the original entry will be placed *after* all the clones, with
6430 repeater intact.
6431 - the start days in the repeater in the original entry will be shifted
6432 to past the last clone.
6433 I this way you can spell out a number of instances of a repeating task,
6434 and still retain the repeater to cover future instances of the task."
6435 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6436 (let (beg end template task
6437 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6438 (if (not (and (integerp n) (> n 0)))
6439 (error "Invalid number of replications %s" n))
6440 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6441 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6442 shift)))
6443 (error "Invalid shift specification %s" shift))
6444 (when doshift
6445 (setq shift-n (string-to-number (match-string 1 shift))
6446 shift-what (cdr (assoc (match-string 2 shift)
6447 '(("d" . day) ("w" . week)
6448 ("m" . month) ("y" . year))))))
6449 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6450 (setq nmin 1 nmax n)
6451 (org-back-to-heading t)
6452 (setq beg (point))
6453 (org-end-of-subtree t t)
6454 (setq end (point))
6455 (setq template (buffer-substring beg end))
6456 (when (and doshift
6457 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6458 (delete-region beg end)
6459 (setq end beg)
6460 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6461 (goto-char end)
6462 (loop for n from nmin to nmax do
6463 (if (not doshift)
6464 (setq task template)
6465 (with-temp-buffer
6466 (insert template)
6467 (org-mode)
6468 (goto-char (point-min))
6469 (while (re-search-forward org-ts-regexp-both nil t)
6470 (org-timestamp-change (* n shift-n) shift-what))
6471 (unless (= n n-no-remove)
6472 (goto-char (point-min))
6473 (while (re-search-forward org-ts-regexp nil t)
6474 (save-excursion
6475 (goto-char (match-beginning 0))
6476 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6477 (delete-region (match-beginning 1) (match-end 1))))))
6478 (setq task (buffer-string))))
6479 (insert task))
6480 (goto-char beg)))
6482 ;;; Outline Sorting
6484 (defun org-sort (with-case)
6485 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6486 Optional argument WITH-CASE means sort case-sensitively.
6487 With a double prefix argument, also remove duplicate entries."
6488 (interactive "P")
6489 (if (org-at-table-p)
6490 (org-call-with-arg 'org-table-sort-lines with-case)
6491 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6493 (defun org-sort-remove-invisible (s)
6494 (remove-text-properties 0 (length s) org-rm-props s)
6495 (while (string-match org-bracket-link-regexp s)
6496 (setq s (replace-match (if (match-end 2)
6497 (match-string 3 s)
6498 (match-string 1 s)) t t s)))
6501 (defvar org-priority-regexp) ; defined later in the file
6503 (defvar org-after-sorting-entries-or-items-hook nil
6504 "Hook that is run after a bunch of entries or items have been sorted.
6505 When children are sorted, the cursor is in the parent line when this
6506 hook gets called. When a region or a plain list is sorted, the cursor
6507 will be in the first entry of the sorted region/list.")
6509 (defun org-sort-entries-or-items
6510 (&optional with-case sorting-type getkey-func compare-func property)
6511 "Sort entries on a certain level of an outline tree, or plain list items.
6512 If there is an active region, the entries in the region are sorted.
6513 Else, if the cursor is before the first entry, sort the top-level items.
6514 Else, the children of the entry at point are sorted.
6515 If the cursor is at the first item in a plain list, the list items will be
6516 sorted.
6518 Sorting can be alphabetically, numerically, by date/time as given by
6519 a time stamp, by a property or by priority.
6521 The command prompts for the sorting type unless it has been given to the
6522 function through the SORTING-TYPE argument, which needs to a character,
6523 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6524 precise meaning of each character:
6526 n Numerically, by converting the beginning of the entry/item to a number.
6527 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6528 t By date/time, either the first active time stamp in the entry, or, if
6529 none exist, by the first inactive one.
6530 In items, only the first line will be chekced.
6531 s By the scheduled date/time.
6532 d By deadline date/time.
6533 c By creation time, which is assumed to be the first inactive time stamp
6534 at the beginning of a line.
6535 p By priority according to the cookie.
6536 r By the value of a property.
6538 Capital letters will reverse the sort order.
6540 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6541 called with point at the beginning of the record. It must return either
6542 a string or a number that should serve as the sorting key for that record.
6544 Comparing entries ignores case by default. However, with an optional argument
6545 WITH-CASE, the sorting considers case as well."
6546 (interactive "P")
6547 (let ((case-func (if with-case 'identity 'downcase))
6548 start beg end stars re re2
6549 txt what tmp plain-list-p)
6550 ;; Find beginning and end of region to sort
6551 (cond
6552 ((org-region-active-p)
6553 ;; we will sort the region
6554 (setq end (region-end)
6555 what "region")
6556 (goto-char (region-beginning))
6557 (if (not (org-on-heading-p)) (outline-next-heading))
6558 (setq start (point)))
6559 ((org-at-item-p)
6560 ;; we will sort this plain list
6561 (org-beginning-of-item-list) (setq start (point))
6562 (org-end-of-item-list) (setq end (point))
6563 (goto-char start)
6564 (setq plain-list-p t
6565 what "plain list"))
6566 ((or (org-on-heading-p)
6567 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6568 ;; we will sort the children of the current headline
6569 (org-back-to-heading)
6570 (setq start (point)
6571 end (progn (org-end-of-subtree t t)
6572 (org-back-over-empty-lines)
6573 (point))
6574 what "children")
6575 (goto-char start)
6576 (show-subtree)
6577 (outline-next-heading))
6579 ;; we will sort the top-level entries in this file
6580 (goto-char (point-min))
6581 (or (org-on-heading-p) (outline-next-heading))
6582 (setq start (point) end (point-max) what "top-level")
6583 (goto-char start)
6584 (show-all)))
6586 (setq beg (point))
6587 (if (>= beg end) (error "Nothing to sort"))
6589 (unless plain-list-p
6590 (looking-at "\\(\\*+\\)")
6591 (setq stars (match-string 1)
6592 re (concat "^" (regexp-quote stars) " +")
6593 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6594 txt (buffer-substring beg end))
6595 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6596 (if (and (not (equal stars "*")) (string-match re2 txt))
6597 (error "Region to sort contains a level above the first entry")))
6599 (unless sorting-type
6600 (message
6601 (if plain-list-p
6602 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6603 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6604 [t]ime [s]cheduled [d]eadline [c]reated
6605 A/N/T/S/D/C/P/O/F means reversed:")
6606 what)
6607 (setq sorting-type (read-char-exclusive))
6609 (and (= (downcase sorting-type) ?f)
6610 (setq getkey-func
6611 (org-icompleting-read "Sort using function: "
6612 obarray 'fboundp t nil nil))
6613 (setq getkey-func (intern getkey-func)))
6615 (and (= (downcase sorting-type) ?r)
6616 (setq property
6617 (org-icompleting-read "Property: "
6618 (mapcar 'list (org-buffer-property-keys t))
6619 nil t))))
6621 (message "Sorting entries...")
6623 (save-restriction
6624 (narrow-to-region start end)
6626 (let ((dcst (downcase sorting-type))
6627 (case-fold-search nil)
6628 (now (current-time)))
6629 (sort-subr
6630 (/= dcst sorting-type)
6631 ;; This function moves to the beginning character of the "record" to
6632 ;; be sorted.
6633 (if plain-list-p
6634 (lambda nil
6635 (if (org-at-item-p) t (goto-char (point-max))))
6636 (lambda nil
6637 (if (re-search-forward re nil t)
6638 (goto-char (match-beginning 0))
6639 (goto-char (point-max)))))
6640 ;; This function moves to the last character of the "record" being
6641 ;; sorted.
6642 (if plain-list-p
6643 'org-end-of-item
6644 (lambda nil
6645 (save-match-data
6646 (condition-case nil
6647 (outline-forward-same-level 1)
6648 (error
6649 (goto-char (point-max)))))))
6651 ;; This function returns the value that gets sorted against.
6652 (if plain-list-p
6653 (lambda nil
6654 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6655 (cond
6656 ((= dcst ?n)
6657 (string-to-number (buffer-substring (match-end 0)
6658 (point-at-eol))))
6659 ((= dcst ?a)
6660 (buffer-substring (match-end 0) (point-at-eol)))
6661 ((= dcst ?t)
6662 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6663 (re-search-forward org-ts-regexp-both
6664 (point-at-eol) t))
6665 (org-time-string-to-seconds (match-string 0))
6666 (org-float-time now)))
6667 ((= dcst ?f)
6668 (if getkey-func
6669 (progn
6670 (setq tmp (funcall getkey-func))
6671 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6672 tmp)
6673 (error "Invalid key function `%s'" getkey-func)))
6674 (t (error "Invalid sorting type `%c'" sorting-type)))))
6675 (lambda nil
6676 (cond
6677 ((= dcst ?n)
6678 (if (looking-at org-complex-heading-regexp)
6679 (string-to-number (match-string 4))
6680 nil))
6681 ((= dcst ?a)
6682 (if (looking-at org-complex-heading-regexp)
6683 (funcall case-func (match-string 4))
6684 nil))
6685 ((= dcst ?t)
6686 (let ((end (save-excursion (outline-next-heading) (point))))
6687 (if (or (re-search-forward org-ts-regexp end t)
6688 (re-search-forward org-ts-regexp-both end t))
6689 (org-time-string-to-seconds (match-string 0))
6690 (org-float-time now))))
6691 ((= dcst ?c)
6692 (let ((end (save-excursion (outline-next-heading) (point))))
6693 (if (re-search-forward
6694 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6695 end t)
6696 (org-time-string-to-seconds (match-string 0))
6697 (org-float-time now))))
6698 ((= dcst ?s)
6699 (let ((end (save-excursion (outline-next-heading) (point))))
6700 (if (re-search-forward org-scheduled-time-regexp end t)
6701 (org-time-string-to-seconds (match-string 1))
6702 (org-float-time now))))
6703 ((= dcst ?d)
6704 (let ((end (save-excursion (outline-next-heading) (point))))
6705 (if (re-search-forward org-deadline-time-regexp end t)
6706 (org-time-string-to-seconds (match-string 1))
6707 (org-float-time now))))
6708 ((= dcst ?p)
6709 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6710 (string-to-char (match-string 2))
6711 org-default-priority))
6712 ((= dcst ?r)
6713 (or (org-entry-get nil property) ""))
6714 ((= dcst ?o)
6715 (if (looking-at org-complex-heading-regexp)
6716 (- 9999 (length (member (match-string 2)
6717 org-todo-keywords-1)))))
6718 ((= dcst ?f)
6719 (if getkey-func
6720 (progn
6721 (setq tmp (funcall getkey-func))
6722 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6723 tmp)
6724 (error "Invalid key function `%s'" getkey-func)))
6725 (t (error "Invalid sorting type `%c'" sorting-type)))))
6727 (cond
6728 ((= dcst ?a) 'string<)
6729 ((= dcst ?f) compare-func)
6730 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6731 (t nil)))))
6732 (run-hooks 'org-after-sorting-entries-or-items-hook)
6733 (message "Sorting entries...done")))
6735 (defun org-do-sort (table what &optional with-case sorting-type)
6736 "Sort TABLE of WHAT according to SORTING-TYPE.
6737 The user will be prompted for the SORTING-TYPE if the call to this
6738 function does not specify it. WHAT is only for the prompt, to indicate
6739 what is being sorted. The sorting key will be extracted from
6740 the car of the elements of the table.
6741 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6742 (unless sorting-type
6743 (message
6744 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6745 what)
6746 (setq sorting-type (read-char-exclusive)))
6747 (let ((dcst (downcase sorting-type))
6748 extractfun comparefun)
6749 ;; Define the appropriate functions
6750 (cond
6751 ((= dcst ?n)
6752 (setq extractfun 'string-to-number
6753 comparefun (if (= dcst sorting-type) '< '>)))
6754 ((= dcst ?a)
6755 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6756 (lambda(x) (downcase (org-sort-remove-invisible x))))
6757 comparefun (if (= dcst sorting-type)
6758 'string<
6759 (lambda (a b) (and (not (string< a b))
6760 (not (string= a b)))))))
6761 ((= dcst ?t)
6762 (setq extractfun
6763 (lambda (x)
6764 (if (or (string-match org-ts-regexp x)
6765 (string-match org-ts-regexp-both x))
6766 (org-float-time
6767 (org-time-string-to-time (match-string 0 x)))
6769 comparefun (if (= dcst sorting-type) '< '>)))
6770 (t (error "Invalid sorting type `%c'" sorting-type)))
6772 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6773 table)
6774 (lambda (a b) (funcall comparefun (car a) (car b))))))
6777 ;;; The orgstruct minor mode
6779 ;; Define a minor mode which can be used in other modes in order to
6780 ;; integrate the org-mode structure editing commands.
6782 ;; This is really a hack, because the org-mode structure commands use
6783 ;; keys which normally belong to the major mode. Here is how it
6784 ;; works: The minor mode defines all the keys necessary to operate the
6785 ;; structure commands, but wraps the commands into a function which
6786 ;; tests if the cursor is currently at a headline or a plain list
6787 ;; item. If that is the case, the structure command is used,
6788 ;; temporarily setting many Org-mode variables like regular
6789 ;; expressions for filling etc. However, when any of those keys is
6790 ;; used at a different location, function uses `key-binding' to look
6791 ;; up if the key has an associated command in another currently active
6792 ;; keymap (minor modes, major mode, global), and executes that
6793 ;; command. There might be problems if any of the keys is otherwise
6794 ;; used as a prefix key.
6796 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6797 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6798 ;; addresses this by checking explicitly for both bindings.
6800 (defvar orgstruct-mode-map (make-sparse-keymap)
6801 "Keymap for the minor `orgstruct-mode'.")
6803 (defvar org-local-vars nil
6804 "List of local variables, for use by `orgstruct-mode'")
6806 ;;;###autoload
6807 (define-minor-mode orgstruct-mode
6808 "Toggle the minor more `orgstruct-mode'.
6809 This mode is for using Org-mode structure commands in other modes.
6810 The following key behave as if Org-mode was active, if the cursor
6811 is on a headline, or on a plain list item (both in the definition
6812 of Org-mode).
6814 M-up Move entry/item up
6815 M-down Move entry/item down
6816 M-left Promote
6817 M-right Demote
6818 M-S-up Move entry/item up
6819 M-S-down Move entry/item down
6820 M-S-left Promote subtree
6821 M-S-right Demote subtree
6822 M-q Fill paragraph and items like in Org-mode
6823 C-c ^ Sort entries
6824 C-c - Cycle list bullet
6825 TAB Cycle item visibility
6826 M-RET Insert new heading/item
6827 S-M-RET Insert new TODO heading / Checkbox item
6828 C-c C-c Set tags / toggle checkbox"
6829 nil " OrgStruct" nil
6830 (org-load-modules-maybe)
6831 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6833 ;;;###autoload
6834 (defun turn-on-orgstruct ()
6835 "Unconditionally turn on `orgstruct-mode'."
6836 (orgstruct-mode 1))
6838 (defun orgstruct++-mode (&optional arg)
6839 "Toggle `orgstruct-mode', the enhanced version of it.
6840 In addition to setting orgstruct-mode, this also exports all indentation
6841 and autofilling variables from org-mode into the buffer. It will also
6842 recognize item context in multiline items.
6843 Note that turning off orgstruct-mode will *not* remove the
6844 indentation/paragraph settings. This can only be done by refreshing the
6845 major mode, for example with \\[normal-mode]."
6846 (interactive "P")
6847 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6848 (if (< arg 1)
6849 (orgstruct-mode -1)
6850 (orgstruct-mode 1)
6851 (let (var val)
6852 (mapc
6853 (lambda (x)
6854 (when (string-match
6855 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6856 (symbol-name (car x)))
6857 (setq var (car x) val (nth 1 x))
6858 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6859 org-local-vars)
6860 (org-set-local 'orgstruct-is-++ t))))
6862 (defvar orgstruct-is-++ nil
6863 "Is orgstruct-mode in ++ version in the current-buffer?")
6864 (make-variable-buffer-local 'orgstruct-is-++)
6866 ;;;###autoload
6867 (defun turn-on-orgstruct++ ()
6868 "Unconditionally turn on `orgstruct++-mode'."
6869 (orgstruct++-mode 1))
6871 (defun orgstruct-error ()
6872 "Error when there is no default binding for a structure key."
6873 (interactive)
6874 (error "This key has no function outside structure elements"))
6876 (defun orgstruct-setup ()
6877 "Setup orgstruct keymaps."
6878 (let ((nfunc 0)
6879 (bindings
6880 (list
6881 '([(meta up)] org-metaup)
6882 '([(meta down)] org-metadown)
6883 '([(meta left)] org-metaleft)
6884 '([(meta right)] org-metaright)
6885 '([(meta shift up)] org-shiftmetaup)
6886 '([(meta shift down)] org-shiftmetadown)
6887 '([(meta shift left)] org-shiftmetaleft)
6888 '([(meta shift right)] org-shiftmetaright)
6889 '([?\e (up)] org-metaup)
6890 '([?\e (down)] org-metadown)
6891 '([?\e (left)] org-metaleft)
6892 '([?\e (right)] org-metaright)
6893 '([?\e (shift up)] org-shiftmetaup)
6894 '([?\e (shift down)] org-shiftmetadown)
6895 '([?\e (shift left)] org-shiftmetaleft)
6896 '([?\e (shift right)] org-shiftmetaright)
6897 '([(shift up)] org-shiftup)
6898 '([(shift down)] org-shiftdown)
6899 '([(shift left)] org-shiftleft)
6900 '([(shift right)] org-shiftright)
6901 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6902 '("\M-q" fill-paragraph)
6903 '("\C-c^" org-sort)
6904 '("\C-c-" org-cycle-list-bullet)))
6905 elt key fun cmd)
6906 (while (setq elt (pop bindings))
6907 (setq nfunc (1+ nfunc))
6908 (setq key (org-key (car elt))
6909 fun (nth 1 elt)
6910 cmd (orgstruct-make-binding fun nfunc key))
6911 (org-defkey orgstruct-mode-map key cmd))
6913 ;; Special treatment needed for TAB and RET
6914 (org-defkey orgstruct-mode-map [(tab)]
6915 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6916 (org-defkey orgstruct-mode-map "\C-i"
6917 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6919 (org-defkey orgstruct-mode-map "\M-\C-m"
6920 (orgstruct-make-binding 'org-insert-heading 105
6921 "\M-\C-m" [(meta return)]))
6922 (org-defkey orgstruct-mode-map [(meta return)]
6923 (orgstruct-make-binding 'org-insert-heading 106
6924 [(meta return)] "\M-\C-m"))
6926 (org-defkey orgstruct-mode-map [(shift meta return)]
6927 (orgstruct-make-binding 'org-insert-todo-heading 107
6928 [(meta return)] "\M-\C-m"))
6930 (org-defkey orgstruct-mode-map "\e\C-m"
6931 (orgstruct-make-binding 'org-insert-heading 108
6932 "\e\C-m" [?\e (return)]))
6933 (org-defkey orgstruct-mode-map [?\e (return)]
6934 (orgstruct-make-binding 'org-insert-heading 109
6935 [?\e (return)] "\e\C-m"))
6936 (org-defkey orgstruct-mode-map [?\e (shift return)]
6937 (orgstruct-make-binding 'org-insert-todo-heading 110
6938 [?\e (return)] "\e\C-m"))
6940 (unless org-local-vars
6941 (setq org-local-vars (org-get-local-variables)))
6945 (defun orgstruct-make-binding (fun n &rest keys)
6946 "Create a function for binding in the structure minor mode.
6947 FUN is the command to call inside a table. N is used to create a unique
6948 command name. KEYS are keys that should be checked in for a command
6949 to execute outside of tables."
6950 (eval
6951 (list 'defun
6952 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6953 '(arg)
6954 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6955 "Outside of structure, run the binding of `"
6956 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6957 "'.")
6958 '(interactive "p")
6959 (list 'if
6960 `(org-context-p 'headline 'item
6961 (and orgstruct-is-++
6962 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6963 'item-body))
6964 (list 'org-run-like-in-org-mode (list 'quote fun))
6965 (list 'let '(orgstruct-mode)
6966 (list 'call-interactively
6967 (append '(or)
6968 (mapcar (lambda (k)
6969 (list 'key-binding k))
6970 keys)
6971 '('orgstruct-error))))))))
6973 (defun org-context-p (&rest contexts)
6974 "Check if local context is any of CONTEXTS.
6975 Possible values in the list of contexts are `table', `headline', and `item'."
6976 (let ((pos (point)))
6977 (goto-char (point-at-bol))
6978 (prog1 (or (and (memq 'table contexts)
6979 (looking-at "[ \t]*|"))
6980 (and (memq 'headline contexts)
6981 ;;????????? (looking-at "\\*+"))
6982 (looking-at outline-regexp))
6983 (and (memq 'item contexts)
6984 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6985 (and (memq 'item-body contexts)
6986 (org-in-item-p)))
6987 (goto-char pos))))
6989 (defun org-get-local-variables ()
6990 "Return a list of all local variables in an org-mode buffer."
6991 (let (varlist)
6992 (with-current-buffer (get-buffer-create "*Org tmp*")
6993 (erase-buffer)
6994 (org-mode)
6995 (setq varlist (buffer-local-variables)))
6996 (kill-buffer "*Org tmp*")
6997 (delq nil
6998 (mapcar
6999 (lambda (x)
7000 (setq x
7001 (if (symbolp x)
7002 (list x)
7003 (list (car x) (list 'quote (cdr x)))))
7004 (if (string-match
7005 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7006 (symbol-name (car x)))
7007 x nil))
7008 varlist))))
7010 ;;;###autoload
7011 (defun org-run-like-in-org-mode (cmd)
7012 "Run a command, pretending that the current buffer is in Org-mode.
7013 This will temporarily bind local variables that are typically bound in
7014 Org-mode to the values they have in Org-mode, and then interactively
7015 call CMD."
7016 (org-load-modules-maybe)
7017 (unless org-local-vars
7018 (setq org-local-vars (org-get-local-variables)))
7019 (eval (list 'let org-local-vars
7020 (list 'call-interactively (list 'quote cmd)))))
7022 ;;;; Archiving
7024 (defun org-get-category (&optional pos)
7025 "Get the category applying to position POS."
7026 (get-text-property (or pos (point)) 'org-category))
7028 (defun org-refresh-category-properties ()
7029 "Refresh category text properties in the buffer."
7030 (let ((def-cat (cond
7031 ((null org-category)
7032 (if buffer-file-name
7033 (file-name-sans-extension
7034 (file-name-nondirectory buffer-file-name))
7035 "???"))
7036 ((symbolp org-category) (symbol-name org-category))
7037 (t org-category)))
7038 beg end cat pos optionp)
7039 (org-unmodified
7040 (save-excursion
7041 (save-restriction
7042 (widen)
7043 (goto-char (point-min))
7044 (put-text-property (point) (point-max) 'org-category def-cat)
7045 (while (re-search-forward
7046 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7047 (setq pos (match-end 0)
7048 optionp (equal (char-after (match-beginning 0)) ?#)
7049 cat (org-trim (match-string 2)))
7050 (if optionp
7051 (setq beg (point-at-bol) end (point-max))
7052 (org-back-to-heading t)
7053 (setq beg (point) end (org-end-of-subtree t t)))
7054 (put-text-property beg end 'org-category cat)
7055 (goto-char pos)))))))
7058 ;;;; Link Stuff
7060 ;;; Link abbreviations
7062 (defun org-link-expand-abbrev (link)
7063 "Apply replacements as defined in `org-link-abbrev-alist."
7064 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7065 (let* ((key (match-string 1 link))
7066 (as (or (assoc key org-link-abbrev-alist-local)
7067 (assoc key org-link-abbrev-alist)))
7068 (tag (and (match-end 2) (match-string 3 link)))
7069 rpl)
7070 (if (not as)
7071 link
7072 (setq rpl (cdr as))
7073 (cond
7074 ((symbolp rpl) (funcall rpl tag))
7075 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7076 ((string-match "%h" rpl)
7077 (replace-match (url-hexify-string (or tag "")) t t rpl))
7078 (t (concat rpl tag)))))
7079 link))
7081 ;;; Storing and inserting links
7083 (defvar org-insert-link-history nil
7084 "Minibuffer history for links inserted with `org-insert-link'.")
7086 (defvar org-stored-links nil
7087 "Contains the links stored with `org-store-link'.")
7089 (defvar org-store-link-plist nil
7090 "Plist with info about the most recently link created with `org-store-link'.")
7092 (defvar org-link-protocols nil
7093 "Link protocols added to Org-mode using `org-add-link-type'.")
7095 (defvar org-store-link-functions nil
7096 "List of functions that are called to create and store a link.
7097 Each function will be called in turn until one returns a non-nil
7098 value. Each function should check if it is responsible for creating
7099 this link (for example by looking at the major mode).
7100 If not, it must exit and return nil.
7101 If yes, it should return a non-nil value after a calling
7102 `org-store-link-props' with a list of properties and values.
7103 Special properties are:
7105 :type The link prefix. like \"http\". This must be given.
7106 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7107 This is obligatory as well.
7108 :description Optional default description for the second pair
7109 of brackets in an Org-mode link. The user can still change
7110 this when inserting this link into an Org-mode buffer.
7112 In addition to these, any additional properties can be specified
7113 and then used in remember templates.")
7115 (defun org-add-link-type (type &optional follow export)
7116 "Add TYPE to the list of `org-link-types'.
7117 Re-compute all regular expressions depending on `org-link-types'
7119 FOLLOW and EXPORT are two functions.
7121 FOLLOW should take the link path as the single argument and do whatever
7122 is necessary to follow the link, for example find a file or display
7123 a mail message.
7125 EXPORT should format the link path for export to one of the export formats.
7126 It should be a function accepting three arguments:
7128 path the path of the link, the text after the prefix (like \"http:\")
7129 desc the description of the link, if any, nil if there was no description
7130 format the export format, a symbol like `html' or `latex'.
7132 The function may use the FORMAT information to return different values
7133 depending on the format. The return value will be put literally into
7134 the exported file.
7135 Org-mode has a built-in default for exporting links. If you are happy with
7136 this default, there is no need to define an export function for the link
7137 type. For a simple example of an export function, see `org-bbdb.el'."
7138 (add-to-list 'org-link-types type t)
7139 (org-make-link-regexps)
7140 (if (assoc type org-link-protocols)
7141 (setcdr (assoc type org-link-protocols) (list follow export))
7142 (push (list type follow export) org-link-protocols)))
7144 ;;;###autoload
7145 (defun org-store-link (arg)
7146 "\\<org-mode-map>Store an org-link to the current location.
7147 This link is added to `org-stored-links' and can later be inserted
7148 into an org-buffer with \\[org-insert-link].
7150 For some link types, a prefix arg is interpreted:
7151 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7152 For file links, arg negates `org-context-in-file-links'."
7153 (interactive "P")
7154 (org-load-modules-maybe)
7155 (setq org-store-link-plist nil) ; reset
7156 (let ((outline-regexp (org-get-limited-outline-regexp))
7157 link cpltxt desc description search txt custom-id)
7158 (cond
7160 ((run-hook-with-args-until-success 'org-store-link-functions)
7161 (setq link (plist-get org-store-link-plist :link)
7162 desc (or (plist-get org-store-link-plist :description) link)))
7164 ((equal (buffer-name) "*Org Edit Src Example*")
7165 (let (label gc)
7166 (while (or (not label)
7167 (save-excursion
7168 (save-restriction
7169 (widen)
7170 (goto-char (point-min))
7171 (re-search-forward
7172 (regexp-quote (format org-coderef-label-format label))
7173 nil t))))
7174 (when label (message "Label exists already") (sit-for 2))
7175 (setq label (read-string "Code line label: " label)))
7176 (end-of-line 1)
7177 (setq link (format org-coderef-label-format label))
7178 (setq gc (- 79 (length link)))
7179 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7180 (insert link)
7181 (setq link (concat "(" label ")") desc nil)))
7183 ((eq major-mode 'calendar-mode)
7184 (let ((cd (calendar-cursor-to-date)))
7185 (setq link
7186 (format-time-string
7187 (car org-time-stamp-formats)
7188 (apply 'encode-time
7189 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7190 nil nil nil))))
7191 (org-store-link-props :type "calendar" :date cd)))
7193 ((eq major-mode 'w3-mode)
7194 (setq cpltxt (if (and (buffer-name)
7195 (not (string-match "Untitled" (buffer-name))))
7196 (buffer-name)
7197 (url-view-url t))
7198 link (org-make-link (url-view-url t)))
7199 (org-store-link-props :type "w3" :url (url-view-url t)))
7201 ((eq major-mode 'w3m-mode)
7202 (setq cpltxt (or w3m-current-title w3m-current-url)
7203 link (org-make-link w3m-current-url))
7204 (org-store-link-props :type "w3m" :url (url-view-url t)))
7206 ((setq search (run-hook-with-args-until-success
7207 'org-create-file-search-functions))
7208 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7209 "::" search))
7210 (setq cpltxt (or description link)))
7212 ((eq major-mode 'image-mode)
7213 (setq cpltxt (concat "file:"
7214 (abbreviate-file-name buffer-file-name))
7215 link (org-make-link cpltxt))
7216 (org-store-link-props :type "image" :file buffer-file-name))
7218 ((eq major-mode 'dired-mode)
7219 ;; link to the file in the current line
7220 (setq cpltxt (concat "file:"
7221 (abbreviate-file-name
7222 (expand-file-name
7223 (dired-get-filename nil t))))
7224 link (org-make-link cpltxt)))
7226 ((and buffer-file-name (org-mode-p))
7227 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7228 (cond
7229 ((org-in-regexp "<<\\(.*?\\)>>")
7230 (setq cpltxt
7231 (concat "file:"
7232 (abbreviate-file-name buffer-file-name)
7233 "::" (match-string 1))
7234 link (org-make-link cpltxt)))
7235 ((and (featurep 'org-id)
7236 (or (eq org-link-to-org-use-id t)
7237 (and (eq org-link-to-org-use-id 'create-if-interactive)
7238 (interactive-p))
7239 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7240 (interactive-p)
7241 (not custom-id))
7242 (and org-link-to-org-use-id
7243 (condition-case nil
7244 (org-entry-get nil "ID")
7245 (error nil)))))
7246 ;; We can make a link using the ID.
7247 (setq link (condition-case nil
7248 (prog1 (org-id-store-link)
7249 (setq desc (plist-get org-store-link-plist
7250 :description)))
7251 (error
7252 ;; probably before first headline, link to file only
7253 (concat "file:"
7254 (abbreviate-file-name buffer-file-name))))))
7256 ;; Just link to current headline
7257 (setq cpltxt (concat "file:"
7258 (abbreviate-file-name buffer-file-name)))
7259 ;; Add a context search string
7260 (when (org-xor org-context-in-file-links arg)
7261 (setq txt (cond
7262 ((org-on-heading-p) nil)
7263 ((org-region-active-p)
7264 (buffer-substring (region-beginning) (region-end)))
7265 (t nil)))
7266 (when (or (null txt) (string-match "\\S-" txt))
7267 (setq cpltxt
7268 (concat cpltxt "::"
7269 (condition-case nil
7270 (org-make-org-heading-search-string txt)
7271 (error "")))
7272 desc (or (nth 4 (ignore-errors
7273 (org-heading-components))) "NONE"))))
7274 (if (string-match "::\\'" cpltxt)
7275 (setq cpltxt (substring cpltxt 0 -2)))
7276 (setq link (org-make-link cpltxt)))))
7278 ((buffer-file-name (buffer-base-buffer))
7279 ;; Just link to this file here.
7280 (setq cpltxt (concat "file:"
7281 (abbreviate-file-name
7282 (buffer-file-name (buffer-base-buffer)))))
7283 ;; Add a context string
7284 (when (org-xor org-context-in-file-links arg)
7285 (setq txt (if (org-region-active-p)
7286 (buffer-substring (region-beginning) (region-end))
7287 (buffer-substring (point-at-bol) (point-at-eol))))
7288 ;; Only use search option if there is some text.
7289 (when (string-match "\\S-" txt)
7290 (setq cpltxt
7291 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7292 desc "NONE")))
7293 (setq link (org-make-link cpltxt)))
7295 ((interactive-p)
7296 (error "Cannot link to a buffer which is not visiting a file"))
7298 (t (setq link nil)))
7300 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7301 (setq link (or link cpltxt)
7302 desc (or desc cpltxt))
7303 (if (equal desc "NONE") (setq desc nil))
7305 (if (and (or (interactive-p) executing-kbd-macro) link)
7306 (progn
7307 (setq org-stored-links
7308 (cons (list link desc) org-stored-links))
7309 (message "Stored: %s" (or desc link))
7310 (when custom-id
7311 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7312 "::#" custom-id))
7313 (setq org-stored-links
7314 (cons (list link desc) org-stored-links))))
7315 (and link (org-make-link-string link desc)))))
7317 (defun org-store-link-props (&rest plist)
7318 "Store link properties, extract names and addresses."
7319 (let (x adr)
7320 (when (setq x (plist-get plist :from))
7321 (setq adr (mail-extract-address-components x))
7322 (setq plist (plist-put plist :fromname (car adr)))
7323 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7324 (when (setq x (plist-get plist :to))
7325 (setq adr (mail-extract-address-components x))
7326 (setq plist (plist-put plist :toname (car adr)))
7327 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7328 (let ((from (plist-get plist :from))
7329 (to (plist-get plist :to)))
7330 (when (and from to org-from-is-user-regexp)
7331 (setq plist
7332 (plist-put plist :fromto
7333 (if (string-match org-from-is-user-regexp from)
7334 (concat "to %t")
7335 (concat "from %f"))))))
7336 (setq org-store-link-plist plist))
7338 (defun org-add-link-props (&rest plist)
7339 "Add these properties to the link property list."
7340 (let (key value)
7341 (while plist
7342 (setq key (pop plist) value (pop plist))
7343 (setq org-store-link-plist
7344 (plist-put org-store-link-plist key value)))))
7346 (defun org-email-link-description (&optional fmt)
7347 "Return the description part of an email link.
7348 This takes information from `org-store-link-plist' and formats it
7349 according to FMT (default from `org-email-link-description-format')."
7350 (setq fmt (or fmt org-email-link-description-format))
7351 (let* ((p org-store-link-plist)
7352 (to (plist-get p :toaddress))
7353 (from (plist-get p :fromaddress))
7354 (table
7355 (list
7356 (cons "%c" (plist-get p :fromto))
7357 (cons "%F" (plist-get p :from))
7358 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7359 (cons "%T" (plist-get p :to))
7360 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7361 (cons "%s" (plist-get p :subject))
7362 (cons "%m" (plist-get p :message-id)))))
7363 (when (string-match "%c" fmt)
7364 ;; Check if the user wrote this message
7365 (if (and org-from-is-user-regexp from to
7366 (save-match-data (string-match org-from-is-user-regexp from)))
7367 (setq fmt (replace-match "to %t" t t fmt))
7368 (setq fmt (replace-match "from %f" t t fmt))))
7369 (org-replace-escapes fmt table)))
7371 (defun org-make-org-heading-search-string (&optional string heading)
7372 "Make search string for STRING or current headline."
7373 (interactive)
7374 (let ((s (or string (org-get-heading))))
7375 (unless (and string (not heading))
7376 ;; We are using a headline, clean up garbage in there.
7377 (if (string-match org-todo-regexp s)
7378 (setq s (replace-match "" t t s)))
7379 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7380 (setq s (replace-match "" t t s)))
7381 (setq s (org-trim s))
7382 (if (string-match (concat "^\\(" org-quote-string "\\|"
7383 org-comment-string "\\)") s)
7384 (setq s (replace-match "" t t s)))
7385 (while (string-match org-ts-regexp s)
7386 (setq s (replace-match "" t t s))))
7387 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7388 (setq s (replace-match " " t t s)))
7389 (or string (setq s (concat "*" s))) ; Add * for headlines
7390 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7392 (defun org-make-link (&rest strings)
7393 "Concatenate STRINGS."
7394 (apply 'concat strings))
7396 (defun org-make-link-string (link &optional description)
7397 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7398 (unless (string-match "\\S-" link)
7399 (error "Empty link"))
7400 (when (stringp description)
7401 ;; Remove brackets from the description, they are fatal.
7402 (while (string-match "\\[" description)
7403 (setq description (replace-match "{" t t description)))
7404 (while (string-match "\\]" description)
7405 (setq description (replace-match "}" t t description))))
7406 (when (equal (org-link-escape link) description)
7407 ;; No description needed, it is identical
7408 (setq description nil))
7409 (when (and (not description)
7410 (not (equal link (org-link-escape link))))
7411 (setq description (org-extract-attributes link)))
7412 (concat "[[" (org-link-escape link) "]"
7413 (if description (concat "[" description "]") "")
7414 "]"))
7416 (defconst org-link-escape-chars
7417 '((?\ . "%20")
7418 (?\[ . "%5B")
7419 (?\] . "%5D")
7420 (?\340 . "%E0") ; `a
7421 (?\342 . "%E2") ; ^a
7422 (?\347 . "%E7") ; ,c
7423 (?\350 . "%E8") ; `e
7424 (?\351 . "%E9") ; 'e
7425 (?\352 . "%EA") ; ^e
7426 (?\356 . "%EE") ; ^i
7427 (?\364 . "%F4") ; ^o
7428 (?\371 . "%F9") ; `u
7429 (?\373 . "%FB") ; ^u
7430 (?\; . "%3B")
7431 (?? . "%3F")
7432 (?= . "%3D")
7433 (?+ . "%2B")
7435 "Association list of escapes for some characters problematic in links.
7436 This is the list that is used for internal purposes.")
7438 (defvar org-url-encoding-use-url-hexify nil)
7440 (defconst org-link-escape-chars-browser
7441 '((?\ . "%20")) ; 32 for the SPC char
7442 "Association list of escapes for some characters problematic in links.
7443 This is the list that is used before handing over to the browser.")
7445 (defun org-link-escape (text &optional table)
7446 "Escape characters in TEXT that are problematic for links."
7447 (if org-url-encoding-use-url-hexify
7448 (url-hexify-string text)
7449 (setq table (or table org-link-escape-chars))
7450 (when text
7451 (let ((re (mapconcat (lambda (x) (regexp-quote
7452 (char-to-string (car x))))
7453 table "\\|")))
7454 (while (string-match re text)
7455 (setq text
7456 (replace-match
7457 (cdr (assoc (string-to-char (match-string 0 text))
7458 table))
7459 t t text)))
7460 text))))
7462 (defun org-link-unescape (text &optional table)
7463 "Reverse the action of `org-link-escape'."
7464 (if org-url-encoding-use-url-hexify
7465 (url-unhex-string text)
7466 (setq table (or table org-link-escape-chars))
7467 (when text
7468 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7469 table "\\|")))
7470 (while (string-match re text)
7471 (setq text
7472 (replace-match
7473 (char-to-string (car (rassoc (match-string 0 text) table)))
7474 t t text)))
7475 text))))
7477 (defun org-xor (a b)
7478 "Exclusive or."
7479 (if a (not b) b))
7481 (defun org-fixup-message-id-for-http (s)
7482 "Replace special characters in a message id, so it can be used in an http query."
7483 (while (string-match "<" s)
7484 (setq s (replace-match "%3C" t t s)))
7485 (while (string-match ">" s)
7486 (setq s (replace-match "%3E" t t s)))
7487 (while (string-match "@" s)
7488 (setq s (replace-match "%40" t t s)))
7491 ;;;###autoload
7492 (defun org-insert-link-global ()
7493 "Insert a link like Org-mode does.
7494 This command can be called in any mode to insert a link in Org-mode syntax."
7495 (interactive)
7496 (org-load-modules-maybe)
7497 (org-run-like-in-org-mode 'org-insert-link))
7499 (defun org-insert-link (&optional complete-file link-location)
7500 "Insert a link. At the prompt, enter the link.
7502 Completion can be used to insert any of the link protocol prefixes like
7503 http or ftp in use.
7505 The history can be used to select a link previously stored with
7506 `org-store-link'. When the empty string is entered (i.e. if you just
7507 press RET at the prompt), the link defaults to the most recently
7508 stored link. As SPC triggers completion in the minibuffer, you need to
7509 use M-SPC or C-q SPC to force the insertion of a space character.
7511 You will also be prompted for a description, and if one is given, it will
7512 be displayed in the buffer instead of the link.
7514 If there is already a link at point, this command will allow you to edit link
7515 and description parts.
7517 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7518 be selected using completion. The path to the file will be relative to the
7519 current directory if the file is in the current directory or a subdirectory.
7520 Otherwise, the link will be the absolute path as completed in the minibuffer
7521 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7522 option `org-link-file-path-type'.
7524 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7525 the current directory or below.
7527 With three \\[universal-argument] prefixes, negate the meaning of
7528 `org-keep-stored-link-after-insertion'.
7530 If `org-make-link-description-function' is non-nil, this function will be
7531 called with the link target, and the result will be the default
7532 link description.
7534 If the LINK-LOCATION parameter is non-nil, this value will be
7535 used as the link location instead of reading one interactively."
7536 (interactive "P")
7537 (let* ((wcf (current-window-configuration))
7538 (region (if (org-region-active-p)
7539 (buffer-substring (region-beginning) (region-end))))
7540 (remove (and region (list (region-beginning) (region-end))))
7541 (desc region)
7542 tmphist ; byte-compile incorrectly complains about this
7543 (link link-location)
7544 entry file all-prefixes)
7545 (cond
7546 (link-location) ; specified by arg, just use it.
7547 ((org-in-regexp org-bracket-link-regexp 1)
7548 ;; We do have a link at point, and we are going to edit it.
7549 (setq remove (list (match-beginning 0) (match-end 0)))
7550 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7551 (setq link (read-string "Link: "
7552 (org-link-unescape
7553 (org-match-string-no-properties 1)))))
7554 ((or (org-in-regexp org-angle-link-re)
7555 (org-in-regexp org-plain-link-re))
7556 ;; Convert to bracket link
7557 (setq remove (list (match-beginning 0) (match-end 0))
7558 link (read-string "Link: "
7559 (org-remove-angle-brackets (match-string 0)))))
7560 ((member complete-file '((4) (16)))
7561 ;; Completing read for file names.
7562 (setq link (org-file-complete-link complete-file)))
7564 ;; Read link, with completion for stored links.
7565 (with-output-to-temp-buffer "*Org Links*"
7566 (princ "Insert a link.
7567 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7568 (when org-stored-links
7569 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7570 (princ (mapconcat
7571 (lambda (x)
7572 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7573 (reverse org-stored-links) "\n"))))
7574 (let ((cw (selected-window)))
7575 (select-window (get-buffer-window "*Org Links*"))
7576 (setq truncate-lines t)
7577 (unless (pos-visible-in-window-p (point-max))
7578 (org-fit-window-to-buffer))
7579 (and (window-live-p cw) (select-window cw)))
7580 ;; Fake a link history, containing the stored links.
7581 (setq tmphist (append (mapcar 'car org-stored-links)
7582 org-insert-link-history))
7583 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7584 (mapcar 'car org-link-abbrev-alist)
7585 org-link-types))
7586 (unwind-protect
7587 (progn
7588 (setq link
7589 (let ((org-completion-use-ido nil)
7590 (org-completion-use-iswitchb nil))
7591 (org-completing-read
7592 "Link: "
7593 (append
7594 (mapcar (lambda (x) (list (concat x ":")))
7595 all-prefixes)
7596 (mapcar 'car org-stored-links))
7597 nil nil nil
7598 'tmphist
7599 (car (car org-stored-links)))))
7600 (if (or (member link all-prefixes)
7601 (and (equal ":" (substring link -1))
7602 (member (substring link 0 -1) all-prefixes)
7603 (setq link (substring link 0 -1))))
7604 (setq link (org-link-try-special-completion link))))
7605 (set-window-configuration wcf)
7606 (kill-buffer "*Org Links*"))
7607 (setq entry (assoc link org-stored-links))
7608 (or entry (push link org-insert-link-history))
7609 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7610 (not org-keep-stored-link-after-insertion))
7611 (setq org-stored-links (delq (assoc link org-stored-links)
7612 org-stored-links)))
7613 (setq desc (or desc (nth 1 entry)))))
7615 (if (string-match org-plain-link-re link)
7616 ;; URL-like link, normalize the use of angular brackets.
7617 (setq link (org-make-link (org-remove-angle-brackets link))))
7619 ;; Check if we are linking to the current file with a search option
7620 ;; If yes, simplify the link by using only the search option.
7621 (when (and buffer-file-name
7622 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7623 (let* ((path (match-string 1 link))
7624 (case-fold-search nil)
7625 (search (match-string 2 link)))
7626 (save-match-data
7627 (if (equal (file-truename buffer-file-name) (file-truename path))
7628 ;; We are linking to this same file, with a search option
7629 (setq link search)))))
7631 ;; Check if we can/should use a relative path. If yes, simplify the link
7632 (when (string-match "^file:\\(.*\\)" link)
7633 (let* ((path (match-string 1 link))
7634 (origpath path)
7635 (case-fold-search nil))
7636 (cond
7637 ((or (eq org-link-file-path-type 'absolute)
7638 (equal complete-file '(16)))
7639 (setq path (abbreviate-file-name (expand-file-name path))))
7640 ((eq org-link-file-path-type 'noabbrev)
7641 (setq path (expand-file-name path)))
7642 ((eq org-link-file-path-type 'relative)
7643 (setq path (file-relative-name path)))
7645 (save-match-data
7646 (if (string-match (concat "^" (regexp-quote
7647 (file-name-as-directory
7648 (expand-file-name "."))))
7649 (expand-file-name path))
7650 ;; We are linking a file with relative path name.
7651 (setq path (substring (expand-file-name path)
7652 (match-end 0)))
7653 (setq path (abbreviate-file-name (expand-file-name path)))))))
7654 (setq link (concat "file:" path))
7655 (if (equal desc origpath)
7656 (setq desc path))))
7658 (if org-make-link-description-function
7659 (setq desc (funcall org-make-link-description-function link desc)))
7661 (setq desc (read-string "Description: " desc))
7662 (unless (string-match "\\S-" desc) (setq desc nil))
7663 (if remove (apply 'delete-region remove))
7664 (insert (org-make-link-string link desc))))
7666 (defun org-link-try-special-completion (type)
7667 "If there is completion support for link type TYPE, offer it."
7668 (let ((fun (intern (concat "org-" type "-complete-link"))))
7669 (if (functionp fun)
7670 (funcall fun)
7671 (read-string "Link (no completion support): " (concat type ":")))))
7673 (defun org-file-complete-link (&optional arg)
7674 "Create a file link using completion."
7675 (let (file link)
7676 (setq file (read-file-name "File: "))
7677 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7678 (pwd1 (file-name-as-directory (abbreviate-file-name
7679 (expand-file-name ".")))))
7680 (cond
7681 ((equal arg '(16))
7682 (setq link (org-make-link
7683 "file:"
7684 (abbreviate-file-name (expand-file-name file)))))
7685 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7686 (setq link (org-make-link "file:" (match-string 1 file))))
7687 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7688 (expand-file-name file))
7689 (setq link (org-make-link
7690 "file:" (match-string 1 (expand-file-name file)))))
7691 (t (setq link (org-make-link "file:" file)))))
7692 link))
7694 (defun org-completing-read (&rest args)
7695 "Completing-read with SPACE being a normal character."
7696 (let ((minibuffer-local-completion-map
7697 (copy-keymap minibuffer-local-completion-map)))
7698 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7699 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7700 (apply 'org-icompleting-read args)))
7702 (defun org-completing-read-no-i (&rest args)
7703 (let (org-completion-use-ido org-completion-use-iswitchb)
7704 (apply 'org-completing-read args)))
7706 (defun org-iswitchb-completing-read (prompt choices &rest args)
7707 "Use iswitch as a completing-read replacement to choose from choices.
7708 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7709 from."
7710 (let* ((switchb-use-virtual-buffers nil)
7711 (iswitchb-make-buflist-hook
7712 (lambda ()
7713 (setq iswitchb-temp-buflist choices))))
7714 (iswitchb-read-buffer prompt)))
7716 (defun org-icompleting-read (&rest args)
7717 "Completing-read using `ido-mode' or `iswitchb' speedups if available"
7718 (if (and org-completion-use-ido
7719 (fboundp 'ido-completing-read)
7720 (boundp 'ido-mode) ido-mode
7721 (listp (second args)))
7722 (let ((ido-enter-matching-directory nil))
7723 (apply 'ido-completing-read (concat (car args))
7724 (if (consp (car (nth 1 args)))
7725 (mapcar (lambda (x) (car x)) (nth 1 args))
7726 (nth 1 args))
7727 (cddr args)))
7728 (if (and org-completion-use-iswitchb
7729 (boundp 'iswitchb-mode) iswitchb-mode
7730 (listp (second args)))
7731 (apply 'org-iswitchb-completing-read (concat (car args))
7732 (mapcar (lambda (x) (car x)) (nth 1 args))
7733 (cddr args))
7734 (apply 'completing-read args))))
7736 (defun org-extract-attributes (s)
7737 "Extract the attributes cookie from a string and set as text property."
7738 (let (a attr (start 0) key value)
7739 (save-match-data
7740 (when (string-match "{{\\([^}]+\\)}}$" s)
7741 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7742 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7743 (setq key (match-string 1 a) value (match-string 2 a)
7744 start (match-end 0)
7745 attr (plist-put attr (intern key) value))))
7746 (org-add-props s nil 'org-attr attr))
7749 (defun org-extract-attributes-from-string (tag)
7750 (let (key value attr)
7751 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7752 (setq key (match-string 1 tag) value (match-string 2 tag)
7753 tag (replace-match "" t t tag)
7754 attr (plist-put attr (intern key) value)))
7755 (cons tag attr)))
7757 (defun org-attributes-to-string (plist)
7758 "Format a property list into an HTML attribute list."
7759 (let ((s "") key value)
7760 (while plist
7761 (setq key (pop plist) value (pop plist))
7762 (and value
7763 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7766 ;;; Opening/following a link
7768 (defvar org-link-search-failed nil)
7770 (defun org-next-link ()
7771 "Move forward to the next link.
7772 If the link is in hidden text, expose it."
7773 (interactive)
7774 (when (and org-link-search-failed (eq this-command last-command))
7775 (goto-char (point-min))
7776 (message "Link search wrapped back to beginning of buffer"))
7777 (setq org-link-search-failed nil)
7778 (let* ((pos (point))
7779 (ct (org-context))
7780 (a (assoc :link ct)))
7781 (if a (goto-char (nth 2 a)))
7782 (if (re-search-forward org-any-link-re nil t)
7783 (progn
7784 (goto-char (match-beginning 0))
7785 (if (org-invisible-p) (org-show-context)))
7786 (goto-char pos)
7787 (setq org-link-search-failed t)
7788 (error "No further link found"))))
7790 (defun org-previous-link ()
7791 "Move backward to the previous link.
7792 If the link is in hidden text, expose it."
7793 (interactive)
7794 (when (and org-link-search-failed (eq this-command last-command))
7795 (goto-char (point-max))
7796 (message "Link search wrapped back to end of buffer"))
7797 (setq org-link-search-failed nil)
7798 (let* ((pos (point))
7799 (ct (org-context))
7800 (a (assoc :link ct)))
7801 (if a (goto-char (nth 1 a)))
7802 (if (re-search-backward org-any-link-re nil t)
7803 (progn
7804 (goto-char (match-beginning 0))
7805 (if (org-invisible-p) (org-show-context)))
7806 (goto-char pos)
7807 (setq org-link-search-failed t)
7808 (error "No further link found"))))
7810 (defun org-translate-link (s)
7811 "Translate a link string if a translation function has been defined."
7812 (if (and org-link-translation-function
7813 (fboundp org-link-translation-function)
7814 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7815 (progn
7816 (setq s (funcall org-link-translation-function
7817 (match-string 1) (match-string 2)))
7818 (concat (car s) ":" (cdr s)))
7821 (defun org-translate-link-from-planner (type path)
7822 "Translate a link from Emacs Planner syntax so that Org can follow it.
7823 This is still an experimental function, your mileage may vary."
7824 (cond
7825 ((member type '("http" "https" "news" "ftp"))
7826 ;; standard Internet links are the same.
7827 nil)
7828 ((and (equal type "irc") (string-match "^//" path))
7829 ;; Planner has two / at the beginning of an irc link, we have 1.
7830 ;; We should have zero, actually....
7831 (setq path (substring path 1)))
7832 ((and (equal type "lisp") (string-match "^/" path))
7833 ;; Planner has a slash, we do not.
7834 (setq type "elisp" path (substring path 1)))
7835 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7836 ;; A typical message link. Planner has the id after the fina slash,
7837 ;; we separate it with a hash mark
7838 (setq path (concat (match-string 1 path) "#"
7839 (org-remove-angle-brackets (match-string 2 path)))))
7841 (cons type path))
7843 (defun org-find-file-at-mouse (ev)
7844 "Open file link or URL at mouse."
7845 (interactive "e")
7846 (mouse-set-point ev)
7847 (org-open-at-point 'in-emacs))
7849 (defun org-open-at-mouse (ev)
7850 "Open file link or URL at mouse."
7851 (interactive "e")
7852 (mouse-set-point ev)
7853 (if (eq major-mode 'org-agenda-mode)
7854 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7855 (org-open-at-point))
7857 (defvar org-window-config-before-follow-link nil
7858 "The window configuration before following a link.
7859 This is saved in case the need arises to restore it.")
7861 (defvar org-open-link-marker (make-marker)
7862 "Marker pointing to the location where `org-open-at-point; was called.")
7864 ;;;###autoload
7865 (defun org-open-at-point-global ()
7866 "Follow a link like Org-mode does.
7867 This command can be called in any mode to follow a link that has
7868 Org-mode syntax."
7869 (interactive)
7870 (org-run-like-in-org-mode 'org-open-at-point))
7872 ;;;###autoload
7873 (defun org-open-link-from-string (s &optional arg reference-buffer)
7874 "Open a link in the string S, as if it was in Org-mode."
7875 (interactive "sLink: \nP")
7876 (let ((reference-buffer (or reference-buffer (current-buffer))))
7877 (with-temp-buffer
7878 (let ((org-inhibit-startup t))
7879 (org-mode)
7880 (insert s)
7881 (goto-char (point-min))
7882 (org-open-at-point arg reference-buffer)))))
7884 (defun org-open-at-point (&optional in-emacs reference-buffer)
7885 "Open link at or after point.
7886 If there is no link at point, this function will search forward up to
7887 the end of the current line.
7888 Normally, files will be opened by an appropriate application. If the
7889 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7890 With a double prefix argument, try to open outside of Emacs, in the
7891 application the system uses for this file type."
7892 (interactive "P")
7893 (org-load-modules-maybe)
7894 (move-marker org-open-link-marker (point))
7895 (setq org-window-config-before-follow-link (current-window-configuration))
7896 (org-remove-occur-highlights nil nil t)
7897 (cond
7898 ((and (org-on-heading-p)
7899 (not (org-in-regexp
7900 (concat org-plain-link-re "\\|"
7901 org-bracket-link-regexp "\\|"
7902 org-angle-link-re "\\|"
7903 "[ \t]:[^ \t\n]+:[ \t]*$"))))
7904 (org-offer-links-in-entry in-emacs))
7905 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7906 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7907 (org-footnote-action))
7909 (let (type path link line search (pos (point)))
7910 (catch 'match
7911 (save-excursion
7912 (skip-chars-forward "^]\n\r")
7913 (when (org-in-regexp org-bracket-link-regexp)
7914 (setq link (org-extract-attributes
7915 (org-link-unescape (org-match-string-no-properties 1))))
7916 (while (string-match " *\n *" link)
7917 (setq link (replace-match " " t t link)))
7918 (setq link (org-link-expand-abbrev link))
7919 (cond
7920 ((or (file-name-absolute-p link)
7921 (string-match "^\\.\\.?/" link))
7922 (setq type "file" path link))
7923 ((string-match org-link-re-with-space3 link)
7924 (setq type (match-string 1 link) path (match-string 2 link)))
7925 (t (setq type "thisfile" path link)))
7926 (throw 'match t)))
7928 (when (get-text-property (point) 'org-linked-text)
7929 (setq type "thisfile"
7930 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7931 (1+ (point)) (point))
7932 path (buffer-substring
7933 (previous-single-property-change pos 'org-linked-text)
7934 (next-single-property-change pos 'org-linked-text)))
7935 (throw 'match t))
7937 (save-excursion
7938 (when (or (org-in-regexp org-angle-link-re)
7939 (org-in-regexp org-plain-link-re))
7940 (setq type (match-string 1) path (match-string 2))
7941 (throw 'match t)))
7942 (save-excursion
7943 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7944 (setq type "tags"
7945 path (match-string 1))
7946 (while (string-match ":" path)
7947 (setq path (replace-match "+" t t path)))
7948 (throw 'match t)))
7949 (when (org-in-regexp "<\\([^><\n]+\\)>")
7950 (setq type "tree-match"
7951 path (match-string 1))
7952 (throw 'match t)))
7953 (unless path
7954 (error "No link found"))
7956 ;; switch back to reference buffer
7957 ;; needed when if called in a temporary buffer through
7958 ;; org-open-link-from-string
7959 (with-current-buffer (or reference-buffer (current-buffer))
7961 ;; Remove any trailing spaces in path
7962 (if (string-match " +\\'" path)
7963 (setq path (replace-match "" t t path)))
7964 (if (and org-link-translation-function
7965 (fboundp org-link-translation-function))
7966 ;; Check if we need to translate the link
7967 (let ((tmp (funcall org-link-translation-function type path)))
7968 (setq type (car tmp) path (cdr tmp))))
7970 (cond
7972 ((assoc type org-link-protocols)
7973 (funcall (nth 1 (assoc type org-link-protocols)) path))
7975 ((equal type "mailto")
7976 (let ((cmd (car org-link-mailto-program))
7977 (args (cdr org-link-mailto-program)) args1
7978 (address path) (subject "") a)
7979 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7980 (setq address (match-string 1 path)
7981 subject (org-link-escape (match-string 2 path))))
7982 (while args
7983 (cond
7984 ((not (stringp (car args))) (push (pop args) args1))
7985 (t (setq a (pop args))
7986 (if (string-match "%a" a)
7987 (setq a (replace-match address t t a)))
7988 (if (string-match "%s" a)
7989 (setq a (replace-match subject t t a)))
7990 (push a args1))))
7991 (apply cmd (nreverse args1))))
7993 ((member type '("http" "https" "ftp" "news"))
7994 (browse-url (concat type ":" (org-link-escape
7995 path org-link-escape-chars-browser))))
7997 ((member type '("message"))
7998 (browse-url (concat type ":" path)))
8000 ((string= type "tags")
8001 (org-tags-view in-emacs path))
8002 ((string= type "thisfile")
8003 (if in-emacs
8004 (switch-to-buffer-other-window
8005 (org-get-buffer-for-internal-link (current-buffer)))
8006 (org-mark-ring-push))
8007 (let ((cmd `(org-link-search
8008 ,path
8009 ,(cond ((equal in-emacs '(4)) 'occur)
8010 ((equal in-emacs '(16)) 'org-occur)
8011 (t nil))
8012 ,pos)))
8013 (condition-case nil (eval cmd)
8014 (error (progn (widen) (eval cmd))))))
8016 ((string= type "tree-match")
8017 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8019 ((string= type "file")
8020 (if (string-match "::\\([0-9]+\\)\\'" path)
8021 (setq line (string-to-number (match-string 1 path))
8022 path (substring path 0 (match-beginning 0)))
8023 (if (string-match "::\\(.+\\)\\'" path)
8024 (setq search (match-string 1 path)
8025 path (substring path 0 (match-beginning 0)))))
8026 (if (string-match "[*?{]" (file-name-nondirectory path))
8027 (dired path)
8028 (org-open-file path in-emacs line search)))
8030 ((string= type "news")
8031 (require 'org-gnus)
8032 (org-gnus-follow-link path))
8034 ((string= type "shell")
8035 (let ((cmd path))
8036 (if (or (not org-confirm-shell-link-function)
8037 (funcall org-confirm-shell-link-function
8038 (format "Execute \"%s\" in shell? "
8039 (org-add-props cmd nil
8040 'face 'org-warning))))
8041 (progn
8042 (message "Executing %s" cmd)
8043 (shell-command cmd))
8044 (error "Abort"))))
8046 ((string= type "elisp")
8047 (let ((cmd path))
8048 (if (or (not org-confirm-elisp-link-function)
8049 (funcall org-confirm-elisp-link-function
8050 (format "Execute \"%s\" as elisp? "
8051 (org-add-props cmd nil
8052 'face 'org-warning))))
8053 (message "%s => %s" cmd
8054 (if (equal (string-to-char cmd) ?\()
8055 (eval (read cmd))
8056 (call-interactively (read cmd))))
8057 (error "Abort"))))
8060 (browse-url-at-point))))))
8061 (move-marker org-open-link-marker nil)
8062 (run-hook-with-args 'org-follow-link-hook)))
8064 (defun org-offer-links-in-entry (&optional nth zero)
8065 "Offer links in the curren entry and follow the selected link.
8066 If there is only one link, follow it immediately as well.
8067 If NTH is an integer, immediately pick the NTH link found.
8068 If ZERO is a string, check also this string for a link, and if
8069 there is one, offer it as link number zero."
8070 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8071 "\\(" org-angle-link-re "\\)\\|"
8072 "\\(" org-plain-link-re "\\)"))
8073 (cnt ?0)
8074 (in-emacs (if (integerp nth) nil nth))
8075 have-zero end links link c)
8076 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8077 (push (match-string 0 zero) links)
8078 (setq cnt (1- cnt) have-zero t))
8079 (save-excursion
8080 (org-back-to-heading t)
8081 (setq end (save-excursion (outline-next-heading) (point)))
8082 (while (re-search-forward re end t)
8083 (push (match-string 0) links))
8084 (setq links (org-uniquify (reverse links))))
8086 (cond
8087 ((null links) (error "No links"))
8088 ((equal (length links) 1)
8089 (setq link (car links)))
8090 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8091 (setq link (nth (if have-zero nth (1- nth)) links)))
8092 (t ; we have to select a link
8093 (save-excursion
8094 (save-window-excursion
8095 (delete-other-windows)
8096 (with-output-to-temp-buffer "*Select Link*"
8097 (princ "Select link\n\n")
8098 (mapc (lambda (l)
8099 (if (not (string-match org-bracket-link-regexp l))
8100 (princ (format "[%c] %s\n" (incf cnt)
8101 (org-remove-angle-brackets l)))
8102 (if (match-end 3)
8103 (princ (format "[%c] %s (%s)\n" (incf cnt)
8104 (match-string 3 l) (match-string 1 l)))
8105 (princ (format "[%c] %s\n" (incf cnt)
8106 (match-string 1 l))))))
8107 links))
8108 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8109 (message "Select link to open:")
8110 (setq c (read-char-exclusive))
8111 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8112 (when (equal c ?q) (error "Abort"))
8113 (setq nth (- c ?0))
8114 (if have-zero (setq nth (1+ nth)))
8115 (unless (and (integerp nth) (>= (length links) nth))
8116 (error "Invalid link selection"))
8117 (setq link (nth (1- nth) links))))
8118 (org-open-link-from-string link in-emacs (current-buffer))))
8120 ;;;; Time estimates
8122 (defun org-get-effort (&optional pom)
8123 "Get the effort estimate for the current entry."
8124 (org-entry-get pom org-effort-property))
8126 ;;; File search
8128 (defvar org-create-file-search-functions nil
8129 "List of functions to construct the right search string for a file link.
8130 These functions are called in turn with point at the location to
8131 which the link should point.
8133 A function in the hook should first test if it would like to
8134 handle this file type, for example by checking the major-mode or
8135 the file extension. If it decides not to handle this file, it
8136 should just return nil to give other functions a chance. If it
8137 does handle the file, it must return the search string to be used
8138 when following the link. The search string will be part of the
8139 file link, given after a double colon, and `org-open-at-point'
8140 will automatically search for it. If special measures must be
8141 taken to make the search successful, another function should be
8142 added to the companion hook `org-execute-file-search-functions',
8143 which see.
8145 A function in this hook may also use `setq' to set the variable
8146 `description' to provide a suggestion for the descriptive text to
8147 be used for this link when it gets inserted into an Org-mode
8148 buffer with \\[org-insert-link].")
8150 (defvar org-execute-file-search-functions nil
8151 "List of functions to execute a file search triggered by a link.
8153 Functions added to this hook must accept a single argument, the
8154 search string that was part of the file link, the part after the
8155 double colon. The function must first check if it would like to
8156 handle this search, for example by checking the major-mode or the
8157 file extension. If it decides not to handle this search, it
8158 should just return nil to give other functions a chance. If it
8159 does handle the search, it must return a non-nil value to keep
8160 other functions from trying.
8162 Each function can access the current prefix argument through the
8163 variable `current-prefix-argument'. Note that a single prefix is
8164 used to force opening a link in Emacs, so it may be good to only
8165 use a numeric or double prefix to guide the search function.
8167 In case this is needed, a function in this hook can also restore
8168 the window configuration before `org-open-at-point' was called using:
8170 (set-window-configuration org-window-config-before-follow-link)")
8172 (defun org-link-search (s &optional type avoid-pos)
8173 "Search for a link search option.
8174 If S is surrounded by forward slashes, it is interpreted as a
8175 regular expression. In org-mode files, this will create an `org-occur'
8176 sparse tree. In ordinary files, `occur' will be used to list matches.
8177 If the current buffer is in `dired-mode', grep will be used to search
8178 in all files. If AVOID-POS is given, ignore matches near that position."
8179 (let ((case-fold-search t)
8180 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8181 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8182 (append '(("") (" ") ("\t") ("\n"))
8183 org-emphasis-alist)
8184 "\\|") "\\)"))
8185 (pos (point))
8186 (pre nil) (post nil)
8187 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8188 (cond
8189 ;; First check if there are any special
8190 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8191 ;; Now try the builtin stuff
8192 ((and (equal (string-to-char s0) ?#)
8193 (> (length s0) 1)
8194 (save-excursion
8195 (goto-char (point-min))
8196 (and
8197 (re-search-forward
8198 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8199 (setq type 'dedicated
8200 pos (match-beginning 0))))
8201 ;; There is an exact target for this
8202 (goto-char pos)
8203 (org-back-to-heading t)))
8204 ((save-excursion
8205 (goto-char (point-min))
8206 (and
8207 (re-search-forward
8208 (concat "<<" (regexp-quote s0) ">>") nil t)
8209 (setq type 'dedicated
8210 pos (match-beginning 0))))
8211 ;; There is an exact target for this
8212 (goto-char pos))
8213 ((and (string-match "^(\\(.*\\))$" s0)
8214 (save-excursion
8215 (goto-char (point-min))
8216 (and
8217 (re-search-forward
8218 (concat "[^[]" (regexp-quote
8219 (format org-coderef-label-format
8220 (match-string 1 s0))))
8221 nil t)
8222 (setq type 'dedicated
8223 pos (1+ (match-beginning 0))))))
8224 ;; There is a coderef target for this
8225 (goto-char pos))
8226 ((string-match "^/\\(.*\\)/$" s)
8227 ;; A regular expression
8228 (cond
8229 ((org-mode-p)
8230 (org-occur (match-string 1 s)))
8231 ;;((eq major-mode 'dired-mode)
8232 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8233 (t (org-do-occur (match-string 1 s)))))
8235 ;; A normal search strings
8236 (when (equal (string-to-char s) ?*)
8237 ;; Anchor on headlines, post may include tags.
8238 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8239 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8240 s (substring s 1)))
8241 (remove-text-properties
8242 0 (length s)
8243 '(face nil mouse-face nil keymap nil fontified nil) s)
8244 ;; Make a series of regular expressions to find a match
8245 (setq words (org-split-string s "[ \n\r\t]+")
8247 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8248 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8249 "\\)" markers)
8250 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8251 re2a (concat "[ \t\r\n]" re2a_)
8252 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8253 re4 (concat "[^a-zA-Z_]" re4_)
8255 re1 (concat pre re2 post)
8256 re3 (concat pre (if pre re4_ re4) post)
8257 re5 (concat pre ".*" re4)
8258 re2 (concat pre re2)
8259 re2a (concat pre (if pre re2a_ re2a))
8260 re4 (concat pre (if pre re4_ re4))
8261 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8262 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8263 re5 "\\)"
8265 (cond
8266 ((eq type 'org-occur) (org-occur reall))
8267 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8268 (t (goto-char (point-min))
8269 (setq type 'fuzzy)
8270 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8271 (org-search-not-self 1 re1 nil t)
8272 (org-search-not-self 1 re2 nil t)
8273 (org-search-not-self 1 re2a nil t)
8274 (org-search-not-self 1 re3 nil t)
8275 (org-search-not-self 1 re4 nil t)
8276 (org-search-not-self 1 re5 nil t)
8278 (goto-char (match-beginning 1))
8279 (goto-char pos)
8280 (error "No match")))))
8282 ;; Normal string-search
8283 (goto-char (point-min))
8284 (if (search-forward s nil t)
8285 (goto-char (match-beginning 0))
8286 (error "No match"))))
8287 (and (org-mode-p) (org-show-context 'link-search))
8288 type))
8290 (defun org-search-not-self (group &rest args)
8291 "Execute `re-search-forward', but only accept matches that do not
8292 enclose the position of `org-open-link-marker'."
8293 (let ((m org-open-link-marker))
8294 (catch 'exit
8295 (while (apply 're-search-forward args)
8296 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8297 (goto-char (match-end group))
8298 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8299 (> (match-beginning 0) (marker-position m))
8300 (< (match-end 0) (marker-position m)))
8301 (save-match-data
8302 (or (not (org-in-regexp
8303 org-bracket-link-analytic-regexp 1))
8304 (not (match-end 4)) ; no description
8305 (and (<= (match-beginning 4) (point))
8306 (>= (match-end 4) (point))))))
8307 (throw 'exit (point))))))))
8309 (defun org-get-buffer-for-internal-link (buffer)
8310 "Return a buffer to be used for displaying the link target of internal links."
8311 (cond
8312 ((not org-display-internal-link-with-indirect-buffer)
8313 buffer)
8314 ((string-match "(Clone)$" (buffer-name buffer))
8315 (message "Buffer is already a clone, not making another one")
8316 ;; we also do not modify visibility in this case
8317 buffer)
8318 (t ; make a new indirect buffer for displaying the link
8319 (let* ((bn (buffer-name buffer))
8320 (ibn (concat bn "(Clone)"))
8321 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8322 (with-current-buffer ib (org-overview))
8323 ib))))
8325 (defun org-do-occur (regexp &optional cleanup)
8326 "Call the Emacs command `occur'.
8327 If CLEANUP is non-nil, remove the printout of the regular expression
8328 in the *Occur* buffer. This is useful if the regex is long and not useful
8329 to read."
8330 (occur regexp)
8331 (when cleanup
8332 (let ((cwin (selected-window)) win beg end)
8333 (when (setq win (get-buffer-window "*Occur*"))
8334 (select-window win))
8335 (goto-char (point-min))
8336 (when (re-search-forward "match[a-z]+" nil t)
8337 (setq beg (match-end 0))
8338 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8339 (setq end (1- (match-beginning 0)))))
8340 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8341 (goto-char (point-min))
8342 (select-window cwin))))
8344 ;;; The mark ring for links jumps
8346 (defvar org-mark-ring nil
8347 "Mark ring for positions before jumps in Org-mode.")
8348 (defvar org-mark-ring-last-goto nil
8349 "Last position in the mark ring used to go back.")
8350 ;; Fill and close the ring
8351 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8352 (loop for i from 1 to org-mark-ring-length do
8353 (push (make-marker) org-mark-ring))
8354 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8355 org-mark-ring)
8357 (defun org-mark-ring-push (&optional pos buffer)
8358 "Put the current position or POS into the mark ring and rotate it."
8359 (interactive)
8360 (setq pos (or pos (point)))
8361 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8362 (move-marker (car org-mark-ring)
8363 (or pos (point))
8364 (or buffer (current-buffer)))
8365 (message "%s"
8366 (substitute-command-keys
8367 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8369 (defun org-mark-ring-goto (&optional n)
8370 "Jump to the previous position in the mark ring.
8371 With prefix arg N, jump back that many stored positions. When
8372 called several times in succession, walk through the entire ring.
8373 Org-mode commands jumping to a different position in the current file,
8374 or to another Org-mode file, automatically push the old position
8375 onto the ring."
8376 (interactive "p")
8377 (let (p m)
8378 (if (eq last-command this-command)
8379 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8380 (setq p org-mark-ring))
8381 (setq org-mark-ring-last-goto p)
8382 (setq m (car p))
8383 (switch-to-buffer (marker-buffer m))
8384 (goto-char m)
8385 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8387 (defun org-remove-angle-brackets (s)
8388 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8389 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8391 (defun org-add-angle-brackets (s)
8392 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8393 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8395 (defun org-remove-double-quotes (s)
8396 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8397 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8400 ;;; Following specific links
8402 (defun org-follow-timestamp-link ()
8403 (cond
8404 ((org-at-date-range-p t)
8405 (let ((org-agenda-start-on-weekday)
8406 (t1 (match-string 1))
8407 (t2 (match-string 2)))
8408 (setq t1 (time-to-days (org-time-string-to-time t1))
8409 t2 (time-to-days (org-time-string-to-time t2)))
8410 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8411 ((org-at-timestamp-p t)
8412 (org-agenda-list nil (time-to-days (org-time-string-to-time
8413 (substring (match-string 1) 0 10)))
8415 (t (error "This should not happen"))))
8418 ;;; Following file links
8419 (defvar org-wait nil)
8420 (defun org-open-file (path &optional in-emacs line search)
8421 "Open the file at PATH.
8422 First, this expands any special file name abbreviations. Then the
8423 configuration variable `org-file-apps' is checked if it contains an
8424 entry for this file type, and if yes, the corresponding command is launched.
8426 If no application is found, Emacs simply visits the file.
8428 With optional prefix argument IN-EMACS, Emacs will visit the file.
8429 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8430 and o use an external application to visit the file.
8432 Optional LINE specifies a line to go to, optional SEARCH a string to
8433 search for. If LINE or SEARCH is given, the file will always be
8434 opened in Emacs.
8435 If the file does not exist, an error is thrown."
8436 (setq in-emacs (or in-emacs line search))
8437 (let* ((file (if (equal path "")
8438 buffer-file-name
8439 (substitute-in-file-name (expand-file-name path))))
8440 (apps (append org-file-apps (org-default-apps)))
8441 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8442 (dirp (if remp nil (file-directory-p file)))
8443 (file (if (and dirp org-open-directory-means-index-dot-org)
8444 (concat (file-name-as-directory file) "index.org")
8445 file))
8446 (a-m-a-p (assq 'auto-mode apps))
8447 (dfile (downcase file))
8448 (old-buffer (current-buffer))
8449 (old-pos (point))
8450 (old-mode major-mode)
8451 ext cmd)
8452 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8453 (setq ext (match-string 1 dfile))
8454 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8455 (setq ext (match-string 1 dfile))))
8456 (cond
8457 ((equal in-emacs '(16))
8458 (setq cmd (cdr (assoc 'system apps))))
8459 (in-emacs (setq cmd 'emacs))
8461 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8462 (and dirp (cdr (assoc 'directory apps)))
8463 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8464 'string-match)
8465 (cdr (assoc ext apps))
8466 (cdr (assoc t apps))))))
8467 (when (eq cmd 'system)
8468 (setq cmd (cdr (assoc 'system apps))))
8469 (when (eq cmd 'default)
8470 (setq cmd (cdr (assoc t apps))))
8471 (when (eq cmd 'mailcap)
8472 (require 'mailcap)
8473 (mailcap-parse-mailcaps)
8474 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8475 (command (mailcap-mime-info mime-type)))
8476 (if (stringp command)
8477 (setq cmd command)
8478 (setq cmd 'emacs))))
8479 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8480 (not (file-exists-p file))
8481 (not org-open-non-existing-files))
8482 (error "No such file: %s" file))
8483 (cond
8484 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8485 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8486 (while (string-match "['\"]%s['\"]" cmd)
8487 (setq cmd (replace-match "%s" t t cmd)))
8488 (while (string-match "%s" cmd)
8489 (setq cmd (replace-match
8490 (save-match-data
8491 (shell-quote-argument
8492 (convert-standard-filename file)))
8493 t t cmd)))
8494 (save-window-excursion
8495 (start-process-shell-command cmd nil cmd)
8496 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8498 ((or (stringp cmd)
8499 (eq cmd 'emacs))
8500 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8501 (widen)
8502 (if line (org-goto-line line)
8503 (if search (org-link-search search))))
8504 ((consp cmd)
8505 (let ((file (convert-standard-filename file)))
8506 (eval cmd)))
8507 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8508 (and (org-mode-p) (eq old-mode 'org-mode)
8509 (or (not (equal old-buffer (current-buffer)))
8510 (not (equal old-pos (point))))
8511 (org-mark-ring-push old-pos old-buffer))))
8513 (defun org-default-apps ()
8514 "Return the default applications for this operating system."
8515 (cond
8516 ((eq system-type 'darwin)
8517 org-file-apps-defaults-macosx)
8518 ((eq system-type 'windows-nt)
8519 org-file-apps-defaults-windowsnt)
8520 (t org-file-apps-defaults-gnu)))
8522 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8523 "Convert extensions to regular expressions in the cars of LIST.
8524 Also, weed out any non-string entries, because the return value is used
8525 only for regexp matching.
8526 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8527 point to the symbol `emacs', indicating that the file should
8528 be opened in Emacs."
8529 (append
8530 (delq nil
8531 (mapcar (lambda (x)
8532 (if (not (stringp (car x)))
8534 (if (string-match "\\W" (car x))
8536 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8537 list))
8538 (if add-auto-mode
8539 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8541 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8542 (defun org-file-remote-p (file)
8543 "Test whether FILE specifies a location on a remote system.
8544 Return non-nil if the location is indeed remote.
8546 For example, the filename \"/user@host:/foo\" specifies a location
8547 on the system \"/user@host:\"."
8548 (cond ((fboundp 'file-remote-p)
8549 (file-remote-p file))
8550 ((fboundp 'tramp-handle-file-remote-p)
8551 (tramp-handle-file-remote-p file))
8552 ((and (boundp 'ange-ftp-name-format)
8553 (string-match (car ange-ftp-name-format) file))
8555 (t nil)))
8558 ;;;; Refiling
8560 (defun org-get-org-file ()
8561 "Read a filename, with default directory `org-directory'."
8562 (let ((default (or org-default-notes-file remember-data-file)))
8563 (read-file-name (format "File name [%s]: " default)
8564 (file-name-as-directory org-directory)
8565 default)))
8567 (defun org-notes-order-reversed-p ()
8568 "Check if the current file should receive notes in reversed order."
8569 (cond
8570 ((not org-reverse-note-order) nil)
8571 ((eq t org-reverse-note-order) t)
8572 ((not (listp org-reverse-note-order)) nil)
8573 (t (catch 'exit
8574 (let ((all org-reverse-note-order)
8575 entry)
8576 (while (setq entry (pop all))
8577 (if (string-match (car entry) buffer-file-name)
8578 (throw 'exit (cdr entry))))
8579 nil)))))
8581 (defvar org-refile-target-table nil
8582 "The list of refile targets, created by `org-refile'.")
8584 (defvar org-agenda-new-buffers nil
8585 "Buffers created to visit agenda files.")
8587 (defun org-get-refile-targets (&optional default-buffer)
8588 "Produce a table with refile targets."
8589 (let ((case-fold-search nil)
8590 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8591 (entries (or org-refile-targets '((nil . (:level . 1)))))
8592 targets txt re files f desc descre fast-path-p level pos0)
8593 (message "Getting targets...")
8594 (with-current-buffer (or default-buffer (current-buffer))
8595 (while (setq entry (pop entries))
8596 (setq files (car entry) desc (cdr entry))
8597 (setq fast-path-p nil)
8598 (cond
8599 ((null files) (setq files (list (current-buffer))))
8600 ((eq files 'org-agenda-files)
8601 (setq files (org-agenda-files 'unrestricted)))
8602 ((and (symbolp files) (fboundp files))
8603 (setq files (funcall files)))
8604 ((and (symbolp files) (boundp files))
8605 (setq files (symbol-value files))))
8606 (if (stringp files) (setq files (list files)))
8607 (cond
8608 ((eq (car desc) :tag)
8609 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8610 ((eq (car desc) :todo)
8611 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8612 ((eq (car desc) :regexp)
8613 (setq descre (cdr desc)))
8614 ((eq (car desc) :level)
8615 (setq descre (concat "^\\*\\{" (number-to-string
8616 (if org-odd-levels-only
8617 (1- (* 2 (cdr desc)))
8618 (cdr desc)))
8619 "\\}[ \t]")))
8620 ((eq (car desc) :maxlevel)
8621 (setq fast-path-p t)
8622 (setq descre (concat "^\\*\\{1," (number-to-string
8623 (if org-odd-levels-only
8624 (1- (* 2 (cdr desc)))
8625 (cdr desc)))
8626 "\\}[ \t]")))
8627 (t (error "Bad refiling target description %s" desc)))
8628 (while (setq f (pop files))
8629 (save-excursion
8630 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8631 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8632 (setq f (expand-file-name f))
8633 (if (eq org-refile-use-outline-path 'file)
8634 (push (list (file-name-nondirectory f) f nil nil) targets))
8635 (save-excursion
8636 (save-restriction
8637 (widen)
8638 (goto-char (point-min))
8639 (while (re-search-forward descre nil t)
8640 (goto-char (setq pos0 (point-at-bol)))
8641 (catch 'next
8642 (when org-refile-target-verify-function
8643 (save-match-data
8644 (or (funcall org-refile-target-verify-function)
8645 (throw 'next t))))
8646 (when (looking-at org-complex-heading-regexp)
8647 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8648 txt (org-link-display-format (match-string 4))
8649 re (concat "^" (regexp-quote
8650 (buffer-substring (match-beginning 1)
8651 (match-end 4)))))
8652 (if (match-end 5) (setq re (concat re "[ \t]+"
8653 (regexp-quote
8654 (match-string 5)))))
8655 (setq re (concat re "[ \t]*$"))
8656 (when org-refile-use-outline-path
8657 (setq txt (mapconcat 'org-protect-slash
8658 (append
8659 (if (eq org-refile-use-outline-path 'file)
8660 (list (file-name-nondirectory
8661 (buffer-file-name (buffer-base-buffer))))
8662 (if (eq org-refile-use-outline-path 'full-file-path)
8663 (list (buffer-file-name (buffer-base-buffer)))))
8664 (org-get-outline-path fast-path-p level txt)
8665 (list txt))
8666 "/")))
8667 (push (list txt f re (point)) targets)))
8668 (when (= (point) pos0)
8669 ;; verification function has not moved point
8670 (goto-char (point-at-eol))))))))))
8671 (message "Getting targets...done")
8672 (nreverse targets)))
8674 (defun org-protect-slash (s)
8675 (while (string-match "/" s)
8676 (setq s (replace-match "\\" t t s)))
8679 (defvar org-olpa (make-vector 20 nil))
8681 (defun org-get-outline-path (&optional fastp level heading)
8682 "Return the outline path to the current entry, as a list."
8683 (if fastp
8684 (progn
8685 (if (> level 19)
8686 (error "Outline path failure, more than 19 levels."))
8687 (loop for i from level upto 19 do
8688 (aset org-olpa i nil))
8689 (prog1
8690 (delq nil (append org-olpa nil))
8691 (aset org-olpa level heading)))
8692 (let (rtn)
8693 (save-excursion
8694 (while (org-up-heading-safe)
8695 (when (looking-at org-complex-heading-regexp)
8696 (push (org-match-string-no-properties 4) rtn)))
8697 rtn))))
8699 (defvar org-refile-history nil
8700 "History for refiling operations.")
8702 (defvar org-after-refile-insert-hook nil
8703 "Hook run after `org-refile' has inserted its stuff at the new location.
8704 Note that this is still *before* the stuff will be removed from
8705 the *old* location.")
8707 (defun org-refile (&optional goto default-buffer rfloc)
8708 "Move the entry at point to another heading.
8709 The list of target headings is compiled using the information in
8710 `org-refile-targets', which see. This list is created before each use
8711 and will therefore always be up-to-date.
8713 At the target location, the entry is filed as a subitem of the target heading.
8714 Depending on `org-reverse-note-order', the new subitem will either be the
8715 first or the last subitem.
8717 If there is an active region, all entries in that region will be moved.
8718 However, the region must fulfil the requirement that the first heading
8719 is the first one sets the top-level of the moved text - at most siblings
8720 below it are allowed.
8722 With prefix arg GOTO, the command will only visit the target location,
8723 not actually move anything.
8724 With a double prefix `C-u C-u', go to the location where the last refiling
8725 operation has put the subtree.
8727 RFLOC can be a refile location obtained in a different way.
8729 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8730 (interactive "P")
8731 (let* ((cbuf (current-buffer))
8732 (regionp (org-region-active-p))
8733 (region-start (and regionp (region-beginning)))
8734 (region-end (and regionp (region-end)))
8735 (region-length (and regionp (- region-end region-start)))
8736 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8737 pos it nbuf file re level reversed)
8738 (when regionp
8739 (goto-char region-start)
8740 (or (bolp) (goto-char (point-at-bol)))
8741 (setq region-start (point))
8742 (unless (org-kill-is-subtree-p
8743 (buffer-substring region-start region-end))
8744 (error "The region is not a (sequence of) subtree(s)")))
8745 (if (equal goto '(16))
8746 (org-refile-goto-last-stored)
8747 (when (setq it (or rfloc
8748 (save-excursion
8749 (org-refile-get-location
8750 (if goto "Goto: " "Refile to: ") default-buffer
8751 org-refile-allow-creating-parent-nodes))))
8752 (setq file (nth 1 it)
8753 re (nth 2 it)
8754 pos (nth 3 it))
8755 (if (and (not goto)
8757 (equal (buffer-file-name) file)
8758 (if regionp
8759 (and (>= pos region-start)
8760 (<= pos region-end))
8761 (and (>= pos (point))
8762 (< pos (save-excursion
8763 (org-end-of-subtree t t))))))
8764 (error "Cannot refile to position inside the tree or region"))
8766 (setq nbuf (or (find-buffer-visiting file)
8767 (find-file-noselect file)))
8768 (if goto
8769 (progn
8770 (switch-to-buffer nbuf)
8771 (goto-char pos)
8772 (org-show-context 'org-goto))
8773 (if regionp
8774 (progn
8775 (org-kill-new (buffer-substring region-start region-end))
8776 (org-save-markers-in-region region-start region-end))
8777 (org-copy-subtree 1 nil t))
8778 (save-excursion
8779 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8780 (find-file-noselect file))))
8781 (setq reversed (org-notes-order-reversed-p))
8782 (save-excursion
8783 (save-restriction
8784 (widen)
8785 (if pos
8786 (progn
8787 (goto-char pos)
8788 (looking-at outline-regexp)
8789 (setq level (org-get-valid-level (funcall outline-level) 1))
8790 (goto-char
8791 (if reversed
8792 (or (outline-next-heading) (point-max))
8793 (or (save-excursion (org-get-next-sibling))
8794 (org-end-of-subtree t t)
8795 (point-max)))))
8796 (setq level 1)
8797 (if (not reversed)
8798 (goto-char (point-max))
8799 (goto-char (point-min))
8800 (or (outline-next-heading) (goto-char (point-max)))))
8801 (if (not (bolp)) (newline))
8802 (bookmark-set "org-refile-last-stored")
8803 (org-paste-subtree level)
8804 (if (fboundp 'deactivate-mark) (deactivate-mark))
8805 (run-hooks 'org-after-refile-insert-hook))))
8806 (if regionp
8807 (delete-region (point) (+ (point) region-length))
8808 (org-cut-subtree))
8809 (when (featurep 'org-inlinetask)
8810 (org-inlinetask-remove-END-maybe))
8811 (setq org-markers-to-move nil)
8812 (message "Refiled to \"%s\"" (car it))))))
8813 (org-reveal))
8815 (defun org-refile-goto-last-stored ()
8816 "Go to the location where the last refile was stored."
8817 (interactive)
8818 (bookmark-jump "org-refile-last-stored")
8819 (message "This is the location of the last refile"))
8821 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8822 "Prompt the user for a refile location, using PROMPT."
8823 (let ((org-refile-targets org-refile-targets)
8824 (org-refile-use-outline-path org-refile-use-outline-path))
8825 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8826 (unless org-refile-target-table
8827 (error "No refile targets"))
8828 (let* ((cbuf (current-buffer))
8829 (partial-completion-mode nil)
8830 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8831 (cfunc (if (and org-refile-use-outline-path
8832 org-outline-path-complete-in-steps)
8833 'org-olpath-completing-read
8834 'org-icompleting-read))
8835 (extra (if org-refile-use-outline-path "/" ""))
8836 (filename (and cfn (expand-file-name cfn)))
8837 (tbl (mapcar
8838 (lambda (x)
8839 (if (and (not (member org-refile-use-outline-path
8840 '(file full-file-path)))
8841 (not (equal filename (nth 1 x))))
8842 (cons (concat (car x) extra " ("
8843 (file-name-nondirectory (nth 1 x)) ")")
8844 (cdr x))
8845 (cons (concat (car x) extra) (cdr x))))
8846 org-refile-target-table))
8847 (completion-ignore-case t)
8848 pa answ parent-target child parent old-hist)
8849 (setq old-hist org-refile-history)
8850 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8851 nil 'org-refile-history))
8852 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8853 (if pa
8854 (progn
8855 (when (or (not org-refile-history)
8856 (not (eq old-hist org-refile-history))
8857 (not (equal (car pa) (car org-refile-history))))
8858 (setq org-refile-history
8859 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8860 org-refile-history
8861 (cdr org-refile-history))))
8862 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8863 (pop org-refile-history)))
8865 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8866 (setq parent (match-string 1 answ)
8867 child (match-string 2 answ))
8868 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8869 (when (and parent-target
8870 (or (eq new-nodes t)
8871 (and (eq new-nodes 'confirm)
8872 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8873 (org-refile-new-child parent-target child))))))
8875 (defun org-refile-new-child (parent-target child)
8876 "Use refile target PARENT-TARGET to add new CHILD below it."
8877 (unless parent-target
8878 (error "Cannot find parent for new node"))
8879 (let ((file (nth 1 parent-target))
8880 (pos (nth 3 parent-target))
8881 level)
8882 (with-current-buffer (or (find-buffer-visiting file)
8883 (find-file-noselect file))
8884 (save-excursion
8885 (save-restriction
8886 (widen)
8887 (if pos
8888 (goto-char pos)
8889 (goto-char (point-max))
8890 (if (not (bolp)) (newline)))
8891 (when (looking-at outline-regexp)
8892 (setq level (funcall outline-level))
8893 (org-end-of-subtree t t))
8894 (org-back-over-empty-lines)
8895 (insert "\n" (make-string
8896 (if pos (org-get-valid-level level 1) 1) ?*)
8897 " " child "\n")
8898 (beginning-of-line 0)
8899 (list (concat (car parent-target) "/" child) file "" (point)))))))
8901 (defun org-olpath-completing-read (prompt collection &rest args)
8902 "Read an outline path like a file name."
8903 (let ((thetable collection)
8904 (org-completion-use-ido nil) ; does not work with ido.
8905 (org-completion-use-iswitchb nil)) ; or iswitchb
8906 (apply
8907 'org-icompleting-read prompt
8908 (lambda (string predicate &optional flag)
8909 (let (rtn r f (l (length string)))
8910 (cond
8911 ((eq flag nil)
8912 ;; try completion
8913 (try-completion string thetable))
8914 ((eq flag t)
8915 ;; all-completions
8916 (setq rtn (all-completions string thetable predicate))
8917 (mapcar
8918 (lambda (x)
8919 (setq r (substring x l))
8920 (if (string-match " ([^)]*)$" x)
8921 (setq f (match-string 0 x))
8922 (setq f ""))
8923 (if (string-match "/" r)
8924 (concat string (substring r 0 (match-end 0)) f)
8926 rtn))
8927 ((eq flag 'lambda)
8928 ;; exact match?
8929 (assoc string thetable)))
8931 args)))
8933 ;;;; Dynamic blocks
8935 (defun org-find-dblock (name)
8936 "Find the first dynamic block with name NAME in the buffer.
8937 If not found, stay at current position and return nil."
8938 (let (pos)
8939 (save-excursion
8940 (goto-char (point-min))
8941 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8942 nil t)
8943 (match-beginning 0))))
8944 (if pos (goto-char pos))
8945 pos))
8947 (defconst org-dblock-start-re
8948 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8949 "Matches the startline of a dynamic block, with parameters.")
8951 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8952 "Matches the end of a dynamic block.")
8954 (defun org-create-dblock (plist)
8955 "Create a dynamic block section, with parameters taken from PLIST.
8956 PLIST must contain a :name entry which is used as name of the block."
8957 (unless (bolp) (newline))
8958 (let ((name (plist-get plist :name)))
8959 (insert "#+BEGIN: " name)
8960 (while plist
8961 (if (eq (car plist) :name)
8962 (setq plist (cddr plist))
8963 (insert " " (prin1-to-string (pop plist)))))
8964 (insert "\n\n#+END:\n")
8965 (beginning-of-line -2)))
8967 (defun org-prepare-dblock ()
8968 "Prepare dynamic block for refresh.
8969 This empties the block, puts the cursor at the insert position and returns
8970 the property list including an extra property :name with the block name."
8971 (unless (looking-at org-dblock-start-re)
8972 (error "Not at a dynamic block"))
8973 (let* ((begdel (1+ (match-end 0)))
8974 (name (org-no-properties (match-string 1)))
8975 (params (append (list :name name)
8976 (read (concat "(" (match-string 3) ")")))))
8977 (unless (re-search-forward org-dblock-end-re nil t)
8978 (error "Dynamic block not terminated"))
8979 (setq params
8980 (append params
8981 (list :content (buffer-substring
8982 begdel (match-beginning 0)))))
8983 (delete-region begdel (match-beginning 0))
8984 (goto-char begdel)
8985 (open-line 1)
8986 params))
8988 (defun org-map-dblocks (&optional command)
8989 "Apply COMMAND to all dynamic blocks in the current buffer.
8990 If COMMAND is not given, use `org-update-dblock'."
8991 (let ((cmd (or command 'org-update-dblock))
8992 pos)
8993 (save-excursion
8994 (goto-char (point-min))
8995 (while (re-search-forward org-dblock-start-re nil t)
8996 (goto-char (setq pos (match-beginning 0)))
8997 (condition-case nil
8998 (funcall cmd)
8999 (error (message "Error during update of dynamic block")))
9000 (goto-char pos)
9001 (unless (re-search-forward org-dblock-end-re nil t)
9002 (error "Dynamic block not terminated"))))))
9004 (defun org-dblock-update (&optional arg)
9005 "User command for updating dynamic blocks.
9006 Update the dynamic block at point. With prefix ARG, update all dynamic
9007 blocks in the buffer."
9008 (interactive "P")
9009 (if arg
9010 (org-update-all-dblocks)
9011 (or (looking-at org-dblock-start-re)
9012 (org-beginning-of-dblock))
9013 (org-update-dblock)))
9015 (defun org-update-dblock ()
9016 "Update the dynamic block at point
9017 This means to empty the block, parse for parameters and then call
9018 the correct writing function."
9019 (save-window-excursion
9020 (let* ((pos (point))
9021 (line (org-current-line))
9022 (params (org-prepare-dblock))
9023 (name (plist-get params :name))
9024 (cmd (intern (concat "org-dblock-write:" name))))
9025 (message "Updating dynamic block `%s' at line %d..." name line)
9026 (funcall cmd params)
9027 (message "Updating dynamic block `%s' at line %d...done" name line)
9028 (goto-char pos))))
9030 (defun org-beginning-of-dblock ()
9031 "Find the beginning of the dynamic block at point.
9032 Error if there is no such block at point."
9033 (let ((pos (point))
9034 beg)
9035 (end-of-line 1)
9036 (if (and (re-search-backward org-dblock-start-re nil t)
9037 (setq beg (match-beginning 0))
9038 (re-search-forward org-dblock-end-re nil t)
9039 (> (match-end 0) pos))
9040 (goto-char beg)
9041 (goto-char pos)
9042 (error "Not in a dynamic block"))))
9044 (defun org-update-all-dblocks ()
9045 "Update all dynamic blocks in the buffer.
9046 This function can be used in a hook."
9047 (when (org-mode-p)
9048 (org-map-dblocks 'org-update-dblock)))
9051 ;;;; Completion
9053 (defconst org-additional-option-like-keywords
9054 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9055 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9056 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
9057 "BEGIN:" "END:"
9058 "ORGTBL" "TBLFM:" "TBLNAME:"
9059 "BEGIN_EXAMPLE" "END_EXAMPLE"
9060 "BEGIN_QUOTE" "END_QUOTE"
9061 "BEGIN_VERSE" "END_VERSE"
9062 "BEGIN_CENTER" "END_CENTER"
9063 "BEGIN_SRC" "END_SRC"
9064 "CATEGORY" "COLUMNS"
9065 "CAPTION" "LABEL"
9066 "BIND"
9067 "MACRO"))
9069 (defcustom org-structure-template-alist
9071 ("s" "#+begin_src ?\n\n#+end_src"
9072 "<src lang=\"?\">\n\n</src>")
9073 ("e" "#+begin_example\n?\n#+end_example"
9074 "<example>\n?\n</example>")
9075 ("q" "#+begin_quote\n?\n#+end_quote"
9076 "<quote>\n?\n</quote>")
9077 ("v" "#+begin_verse\n?\n#+end_verse"
9078 "<verse>\n?\n/verse>")
9079 ("c" "#+begin_center\n?\n#+end_center"
9080 "<center>\n?\n/center>")
9081 ("l" "#+begin_latex\n?\n#+end_latex"
9082 "<literal style=\"latex\">\n?\n</literal>")
9083 ("L" "#+latex: "
9084 "<literal style=\"latex\">?</literal>")
9085 ("h" "#+begin_html\n?\n#+end_html"
9086 "<literal style=\"html\">\n?\n</literal>")
9087 ("H" "#+html: "
9088 "<literal style=\"html\">?</literal>")
9089 ("a" "#+begin_ascii\n?\n#+end_ascii")
9090 ("A" "#+ascii: ")
9091 ("i" "#+include %file ?"
9092 "<include file=%file markup=\"?\">")
9094 "Structure completion elements.
9095 This is a list of abbreviation keys and values. The value gets inserted
9096 it you type @samp{.} followed by the key and then the completion key,
9097 usually `M-TAB'. %file will be replaced by a file name after prompting
9098 for the file using completion.
9099 There are two templates for each key, the first uses the original Org syntax,
9100 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9101 the default when the /org-mtags.el/ module has been loaded. See also the
9102 variable `org-mtags-prefer-muse-templates'.
9103 This is an experimental feature, it is undecided if it is going to stay in."
9104 :group 'org-completion
9105 :type '(repeat
9106 (string :tag "Key")
9107 (string :tag "Template")
9108 (string :tag "Muse Template")))
9110 (defun org-try-structure-completion ()
9111 "Try to complete a structure template before point.
9112 This looks for strings like \"<e\" on an otherwise empty line and
9113 expands them."
9114 (let ((l (buffer-substring (point-at-bol) (point)))
9116 (when (and (looking-at "[ \t]*$")
9117 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9118 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9119 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9120 (match-beginning 1)) a)
9121 t)))
9123 (defun org-complete-expand-structure-template (start cell)
9124 "Expand a structure template."
9125 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9126 (rpl (nth (if musep 2 1) cell))
9127 (ind ""))
9128 (delete-region start (point))
9129 (when (string-match "\\`#\\+" rpl)
9130 (cond
9131 ((bolp))
9132 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9133 (setq ind (buffer-substring (point-at-bol) (point))))
9134 (t (newline))))
9135 (setq start (point))
9136 (if (string-match "%file" rpl)
9137 (setq rpl (replace-match
9138 (concat
9139 "\""
9140 (save-match-data
9141 (abbreviate-file-name (read-file-name "Include file: ")))
9142 "\"")
9143 t t rpl)))
9144 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9145 (concat "\n" ind)))
9146 (insert rpl)
9147 (if (re-search-backward "\\?" start t) (delete-char 1))))
9150 (defun org-complete (&optional arg)
9151 "Perform completion on word at point.
9152 At the beginning of a headline, this completes TODO keywords as given in
9153 `org-todo-keywords'.
9154 If the current word is preceded by a backslash, completes the TeX symbols
9155 that are supported for HTML support.
9156 If the current word is preceded by \"#+\", completes special words for
9157 setting file options.
9158 In the line after \"#+STARTUP:, complete valid keywords.\"
9159 At all other locations, this simply calls the value of
9160 `org-completion-fallback-command'."
9161 (interactive "P")
9162 (org-without-partial-completion
9163 (catch 'exit
9164 (let* ((a nil)
9165 (end (point))
9166 (beg1 (save-excursion
9167 (skip-chars-backward (org-re "[:alnum:]_@"))
9168 (point)))
9169 (beg (save-excursion
9170 (skip-chars-backward "a-zA-Z0-9_:$")
9171 (point)))
9172 (confirm (lambda (x) (stringp (car x))))
9173 (searchhead (equal (char-before beg) ?*))
9174 (struct
9175 (when (and (member (char-before beg1) '(?. ?<))
9176 (setq a (assoc (buffer-substring beg1 (point))
9177 org-structure-template-alist)))
9178 (org-complete-expand-structure-template (1- beg1) a)
9179 (throw 'exit t)))
9180 (tag (and (equal (char-before beg1) ?:)
9181 (equal (char-after (point-at-bol)) ?*)))
9182 (prop (and (equal (char-before beg1) ?:)
9183 (not (equal (char-after (point-at-bol)) ?*))))
9184 (texp (equal (char-before beg) ?\\))
9185 (link (equal (char-before beg) ?\[))
9186 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9187 beg)
9188 "#+"))
9189 (startup (string-match "^#\\+STARTUP:.*"
9190 (buffer-substring (point-at-bol) (point))))
9191 (completion-ignore-case opt)
9192 (type nil)
9193 (tbl nil)
9194 (table (cond
9195 (opt
9196 (setq type :opt)
9197 (require 'org-exp)
9198 (append
9199 (delq nil
9200 (mapcar
9201 (lambda (x)
9202 (if (string-match
9203 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9204 (cons (match-string 2 x)
9205 (match-string 1 x))))
9206 (org-split-string (org-get-current-options) "\n")))
9207 (mapcar 'list org-additional-option-like-keywords)))
9208 (startup
9209 (setq type :startup)
9210 org-startup-options)
9211 (link (append org-link-abbrev-alist-local
9212 org-link-abbrev-alist))
9213 (texp
9214 (setq type :tex)
9215 org-html-entities)
9216 ((string-match "\\`\\*+[ \t]+\\'"
9217 (buffer-substring (point-at-bol) beg))
9218 (setq type :todo)
9219 (mapcar 'list org-todo-keywords-1))
9220 (searchhead
9221 (setq type :searchhead)
9222 (save-excursion
9223 (goto-char (point-min))
9224 (while (re-search-forward org-todo-line-regexp nil t)
9225 (push (list
9226 (org-make-org-heading-search-string
9227 (match-string 3) t))
9228 tbl)))
9229 tbl)
9230 (tag (setq type :tag beg beg1)
9231 (or org-tag-alist (org-get-buffer-tags)))
9232 (prop (setq type :prop beg beg1)
9233 (mapcar 'list (org-buffer-property-keys nil t t)))
9234 (t (progn
9235 (call-interactively org-completion-fallback-command)
9236 (throw 'exit nil)))))
9237 (pattern (buffer-substring-no-properties beg end))
9238 (completion (try-completion pattern table confirm)))
9239 (cond ((eq completion t)
9240 (if (not (assoc (upcase pattern) table))
9241 (message "Already complete")
9242 (if (and (equal type :opt)
9243 (not (member (car (assoc (upcase pattern) table))
9244 org-additional-option-like-keywords)))
9245 (insert (substring (cdr (assoc (upcase pattern) table))
9246 (length pattern)))
9247 (if (memq type '(:tag :prop)) (insert ":")))))
9248 ((null completion)
9249 (message "Can't find completion for \"%s\"" pattern)
9250 (ding))
9251 ((not (string= pattern completion))
9252 (delete-region beg end)
9253 (if (string-match " +$" completion)
9254 (setq completion (replace-match "" t t completion)))
9255 (insert completion)
9256 (if (get-buffer-window "*Completions*")
9257 (delete-window (get-buffer-window "*Completions*")))
9258 (if (assoc completion table)
9259 (if (eq type :todo) (insert " ")
9260 (if (memq type '(:tag :prop)) (insert ":"))))
9261 (if (and (equal type :opt) (assoc completion table))
9262 (message "%s" (substitute-command-keys
9263 "Press \\[org-complete] again to insert example settings"))))
9265 (message "Making completion list...")
9266 (let ((list (sort (all-completions pattern table confirm)
9267 'string<)))
9268 (with-output-to-temp-buffer "*Completions*"
9269 (condition-case nil
9270 ;; Protection needed for XEmacs and emacs 21
9271 (display-completion-list list pattern)
9272 (error (display-completion-list list)))))
9273 (message "Making completion list...%s" "done")))))))
9275 ;;;; TODO, DEADLINE, Comments
9277 (defun org-toggle-comment ()
9278 "Change the COMMENT state of an entry."
9279 (interactive)
9280 (save-excursion
9281 (org-back-to-heading)
9282 (let (case-fold-search)
9283 (if (looking-at (concat outline-regexp
9284 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9285 (replace-match "" t t nil 1)
9286 (if (looking-at outline-regexp)
9287 (progn
9288 (goto-char (match-end 0))
9289 (insert org-comment-string " ")))))))
9291 (defvar org-last-todo-state-is-todo nil
9292 "This is non-nil when the last TODO state change led to a TODO state.
9293 If the last change removed the TODO tag or switched to DONE, then
9294 this is nil.")
9296 (defvar org-setting-tags nil) ; dynamically skipped
9298 (defun org-parse-local-options (string var)
9299 "Parse STRING for startup setting relevant for variable VAR."
9300 (let ((rtn (symbol-value var))
9301 e opts)
9302 (save-match-data
9303 (if (or (not string) (not (string-match "\\S-" string)))
9305 (setq opts (delq nil (mapcar (lambda (x)
9306 (setq e (assoc x org-startup-options))
9307 (if (eq (nth 1 e) var) e nil))
9308 (org-split-string string "[ \t]+"))))
9309 (if (not opts)
9311 (setq rtn nil)
9312 (while (setq e (pop opts))
9313 (if (not (nth 3 e))
9314 (setq rtn (nth 2 e))
9315 (if (not (listp rtn)) (setq rtn nil))
9316 (push (nth 2 e) rtn)))
9317 rtn)))))
9319 (defvar org-todo-setup-filter-hook nil
9320 "Hook for functions that pre-filter todo specs.
9322 Each function takes a todo spec and returns either `nil' or the spec
9323 transformed into canonical form." )
9325 (defvar org-todo-get-default-hook nil
9326 "Hook for functions that get a default item for todo.
9328 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9329 `nil' or a string to be used for the todo mark." )
9331 (defvar org-agenda-headline-snapshot-before-repeat)
9333 (defun org-todo (&optional arg)
9334 "Change the TODO state of an item.
9335 The state of an item is given by a keyword at the start of the heading,
9336 like
9337 *** TODO Write paper
9338 *** DONE Call mom
9340 The different keywords are specified in the variable `org-todo-keywords'.
9341 By default the available states are \"TODO\" and \"DONE\".
9342 So for this example: when the item starts with TODO, it is changed to DONE.
9343 When it starts with DONE, the DONE is removed. And when neither TODO nor
9344 DONE are present, add TODO at the beginning of the heading.
9346 With C-u prefix arg, use completion to determine the new state.
9347 With numeric prefix arg, switch to that state.
9348 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9349 With a tripple C-u prefix, circumvent any state blocking.
9351 For calling through lisp, arg is also interpreted in the following way:
9352 'none -> empty state
9353 \"\"(empty string) -> switch to empty state
9354 'done -> switch to DONE
9355 'nextset -> switch to the next set of keywords
9356 'previousset -> switch to the previous set of keywords
9357 \"WAITING\" -> switch to the specified keyword, but only if it
9358 really is a member of `org-todo-keywords'."
9359 (interactive "P")
9360 (if (equal arg '(16)) (setq arg 'nextset))
9361 (let ((org-blocker-hook org-blocker-hook)
9362 (case-fold-search nil))
9363 (when (equal arg '(64))
9364 (setq arg nil org-blocker-hook nil))
9365 (when (and org-blocker-hook
9366 (or org-inhibit-blocking
9367 (org-entry-get nil "NOBLOCKING")))
9368 (setq org-blocker-hook nil))
9369 (save-excursion
9370 (catch 'exit
9371 (org-back-to-heading)
9372 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9373 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9374 (looking-at " *"))
9375 (let* ((match-data (match-data))
9376 (startpos (point-at-bol))
9377 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9378 (org-log-done org-log-done)
9379 (org-log-repeat org-log-repeat)
9380 (org-todo-log-states org-todo-log-states)
9381 (this (match-string 1))
9382 (hl-pos (match-beginning 0))
9383 (head (org-get-todo-sequence-head this))
9384 (ass (assoc head org-todo-kwd-alist))
9385 (interpret (nth 1 ass))
9386 (done-word (nth 3 ass))
9387 (final-done-word (nth 4 ass))
9388 (last-state (or this ""))
9389 (completion-ignore-case t)
9390 (member (member this org-todo-keywords-1))
9391 (tail (cdr member))
9392 (state (cond
9393 ((and org-todo-key-trigger
9394 (or (and (equal arg '(4))
9395 (eq org-use-fast-todo-selection 'prefix))
9396 (and (not arg) org-use-fast-todo-selection
9397 (not (eq org-use-fast-todo-selection
9398 'prefix)))))
9399 ;; Use fast selection
9400 (org-fast-todo-selection))
9401 ((and (equal arg '(4))
9402 (or (not org-use-fast-todo-selection)
9403 (not org-todo-key-trigger)))
9404 ;; Read a state with completion
9405 (org-icompleting-read
9406 "State: " (mapcar (lambda(x) (list x))
9407 org-todo-keywords-1)
9408 nil t))
9409 ((eq arg 'right)
9410 (if this
9411 (if tail (car tail) nil)
9412 (car org-todo-keywords-1)))
9413 ((eq arg 'left)
9414 (if (equal member org-todo-keywords-1)
9416 (if this
9417 (nth (- (length org-todo-keywords-1)
9418 (length tail) 2)
9419 org-todo-keywords-1)
9420 (org-last org-todo-keywords-1))))
9421 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9422 (setq arg nil))) ; hack to fall back to cycling
9423 (arg
9424 ;; user or caller requests a specific state
9425 (cond
9426 ((equal arg "") nil)
9427 ((eq arg 'none) nil)
9428 ((eq arg 'done) (or done-word (car org-done-keywords)))
9429 ((eq arg 'nextset)
9430 (or (car (cdr (member head org-todo-heads)))
9431 (car org-todo-heads)))
9432 ((eq arg 'previousset)
9433 (let ((org-todo-heads (reverse org-todo-heads)))
9434 (or (car (cdr (member head org-todo-heads)))
9435 (car org-todo-heads))))
9436 ((car (member arg org-todo-keywords-1)))
9437 ((nth (1- (prefix-numeric-value arg))
9438 org-todo-keywords-1))))
9439 ((null member) (or head (car org-todo-keywords-1)))
9440 ((equal this final-done-word) nil) ;; -> make empty
9441 ((null tail) nil) ;; -> first entry
9442 ((memq interpret '(type priority))
9443 (if (eq this-command last-command)
9444 (car tail)
9445 (if (> (length tail) 0)
9446 (or done-word (car org-done-keywords))
9447 nil)))
9449 (car tail))))
9450 (state (or
9451 (run-hook-with-args-until-success
9452 'org-todo-get-default-hook state last-state)
9453 state))
9454 (next (if state (concat " " state " ") " "))
9455 (change-plist (list :type 'todo-state-change :from this :to state
9456 :position startpos))
9457 dolog now-done-p)
9458 (when org-blocker-hook
9459 (setq org-last-todo-state-is-todo
9460 (not (member this org-done-keywords)))
9461 (unless (save-excursion
9462 (save-match-data
9463 (run-hook-with-args-until-failure
9464 'org-blocker-hook change-plist)))
9465 (if (interactive-p)
9466 (error "TODO state change from %s to %s blocked" this state)
9467 ;; fail silently
9468 (message "TODO state change from %s to %s blocked" this state)
9469 (throw 'exit nil))))
9470 (store-match-data match-data)
9471 (replace-match next t t)
9472 (unless (pos-visible-in-window-p hl-pos)
9473 (message "TODO state changed to %s" (org-trim next)))
9474 (unless head
9475 (setq head (org-get-todo-sequence-head state)
9476 ass (assoc head org-todo-kwd-alist)
9477 interpret (nth 1 ass)
9478 done-word (nth 3 ass)
9479 final-done-word (nth 4 ass)))
9480 (when (memq arg '(nextset previousset))
9481 (message "Keyword-Set %d/%d: %s"
9482 (- (length org-todo-sets) -1
9483 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9484 (length org-todo-sets)
9485 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9486 (setq org-last-todo-state-is-todo
9487 (not (member state org-done-keywords)))
9488 (setq now-done-p (and (member state org-done-keywords)
9489 (not (member this org-done-keywords))))
9490 (and logging (org-local-logging logging))
9491 (when (and (or org-todo-log-states org-log-done)
9492 (not (eq org-inhibit-logging t))
9493 (not (memq arg '(nextset previousset))))
9494 ;; we need to look at recording a time and note
9495 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9496 (nth 2 (assoc this org-todo-log-states))))
9497 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9498 (setq dolog 'time))
9499 (when (and state
9500 (member state org-not-done-keywords)
9501 (not (member this org-not-done-keywords)))
9502 ;; This is now a todo state and was not one before
9503 ;; If there was a CLOSED time stamp, get rid of it.
9504 (org-add-planning-info nil nil 'closed))
9505 (when (and now-done-p org-log-done)
9506 ;; It is now done, and it was not done before
9507 (org-add-planning-info 'closed (org-current-time))
9508 (if (and (not dolog) (eq 'note org-log-done))
9509 (org-add-log-setup 'done state this 'findpos 'note)))
9510 (when (and state dolog)
9511 ;; This is a non-nil state, and we need to log it
9512 (org-add-log-setup 'state state this 'findpos dolog)))
9513 ;; Fixup tag positioning
9514 (org-todo-trigger-tag-changes state)
9515 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9516 (when org-provide-todo-statistics
9517 (org-update-parent-todo-statistics))
9518 (run-hooks 'org-after-todo-state-change-hook)
9519 (if (and arg (not (member state org-done-keywords)))
9520 (setq head (org-get-todo-sequence-head state)))
9521 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9522 ;; Do we need to trigger a repeat?
9523 (when now-done-p
9524 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9525 ;; This is for the agenda, take a snapshot of the headline.
9526 (save-match-data
9527 (setq org-agenda-headline-snapshot-before-repeat
9528 (org-get-heading))))
9529 (org-auto-repeat-maybe state))
9530 ;; Fixup cursor location if close to the keyword
9531 (if (and (outline-on-heading-p)
9532 (not (bolp))
9533 (save-excursion (beginning-of-line 1)
9534 (looking-at org-todo-line-regexp))
9535 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9536 (progn
9537 (goto-char (or (match-end 2) (match-end 1)))
9538 (and (looking-at " ") (just-one-space))))
9539 (when org-trigger-hook
9540 (save-excursion
9541 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9543 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9544 "Block turning an entry into a TODO, using the hierarchy.
9545 This checks whether the current task should be blocked from state
9546 changes. Such blocking occurs when:
9548 1. The task has children which are not all in a completed state.
9550 2. A task has a parent with the property :ORDERED:, and there
9551 are siblings prior to the current task with incomplete
9552 status.
9554 3. The parent of the task is blocked because it has siblings that should
9555 be done first, or is child of a block grandparent TODO entry."
9557 (catch 'dont-block
9558 ;; If this is not a todo state change, or if this entry is already DONE,
9559 ;; do not block
9560 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9561 (member (plist-get change-plist :from)
9562 (cons 'done org-done-keywords))
9563 (member (plist-get change-plist :to)
9564 (cons 'todo org-not-done-keywords)))
9565 (throw 'dont-block t))
9566 ;; If this task has children, and any are undone, it's blocked
9567 (save-excursion
9568 (org-back-to-heading t)
9569 (let ((this-level (funcall outline-level)))
9570 (outline-next-heading)
9571 (let ((child-level (funcall outline-level)))
9572 (while (and (not (eobp))
9573 (> child-level this-level))
9574 ;; this todo has children, check whether they are all
9575 ;; completed
9576 (if (and (not (org-entry-is-done-p))
9577 (org-entry-is-todo-p))
9578 (throw 'dont-block nil))
9579 (outline-next-heading)
9580 (setq child-level (funcall outline-level))))))
9581 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9582 ;; any previous siblings are undone, it's blocked
9583 (save-excursion
9584 (org-back-to-heading t)
9585 (let* ((pos (point))
9586 (parent-pos (and (org-up-heading-safe) (point))))
9587 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9588 (when (and (org-entry-get (point) "ORDERED")
9589 (forward-line 1)
9590 (re-search-forward org-not-done-heading-regexp pos t))
9591 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9592 ;; Search further up the hierarchy, to see if an anchestor is blocked
9593 (while t
9594 (goto-char parent-pos)
9595 (if (not (looking-at org-not-done-heading-regexp))
9596 (throw 'dont-block t)) ; do not block, parent is not a TODO
9597 (setq pos (point))
9598 (setq parent-pos (and (org-up-heading-safe) (point)))
9599 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9600 (when (and (org-entry-get (point) "ORDERED")
9601 (forward-line 1)
9602 (re-search-forward org-not-done-heading-regexp pos t))
9603 (throw 'dont-block nil))))))) ; block, older sibling not done.
9605 (defcustom org-track-ordered-property-with-tag nil
9606 "Should the ORDERED property also be shown as a tag?
9607 The ORDERED property decides if an entry should require subtasks to be
9608 completed in sequence. Since a property is not very visible, setting
9609 this option means that toggling the ORDERED property with the command
9610 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9611 not relevant for the behavior, but it makes things more visible.
9613 Note that toggling the tag with tags commands will not change the property
9614 and therefore not influence behavior!
9616 This can be t, meaning the tag ORDERED should be used, It can also be a
9617 string to select a different tag for this task."
9618 :group 'org-todo
9619 :type '(choice
9620 (const :tag "No tracking" nil)
9621 (const :tag "Track with ORDERED tag" t)
9622 (string :tag "Use other tag")))
9624 (defun org-toggle-ordered-property ()
9625 "Toggle the ORDERED property of the current entry.
9626 For better visibility, you can track the value of this property with a tag.
9627 See variable `org-track-ordered-property-with-tag'."
9628 (interactive)
9629 (let* ((t1 org-track-ordered-property-with-tag)
9630 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9631 (save-excursion
9632 (org-back-to-heading)
9633 (if (org-entry-get nil "ORDERED")
9634 (progn
9635 (org-delete-property "ORDERED")
9636 (and tag (org-toggle-tag tag 'off))
9637 (message "Subtasks can be completed in arbitrary order"))
9638 (org-entry-put nil "ORDERED" "t")
9639 (and tag (org-toggle-tag tag 'on))
9640 (message "Subtasks must be completed in sequence")))))
9642 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9643 (defun org-block-todo-from-checkboxes (change-plist)
9644 "Block turning an entry into a TODO, using checkboxes.
9645 This checks whether the current task should be blocked from state
9646 changes because there are uncheckd boxes in this entry."
9647 (catch 'dont-block
9648 ;; If this is not a todo state change, or if this entry is already DONE,
9649 ;; do not block
9650 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9651 (member (plist-get change-plist :from)
9652 (cons 'done org-done-keywords))
9653 (member (plist-get change-plist :to)
9654 (cons 'todo org-not-done-keywords)))
9655 (throw 'dont-block t))
9656 ;; If this task has checkboxes that are not checked, it's blocked
9657 (save-excursion
9658 (org-back-to-heading t)
9659 (let ((beg (point)) end)
9660 (outline-next-heading)
9661 (setq end (point))
9662 (goto-char beg)
9663 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9664 end t)
9665 (progn
9666 (if (boundp 'org-blocked-by-checkboxes)
9667 (setq org-blocked-by-checkboxes t))
9668 (throw 'dont-block nil)))))
9669 t)) ; do not block
9671 (defun org-update-statistics-cookies (all)
9672 "Update the statistics cookie, either from TODO or from checkboxes.
9673 This should be called with the cursor in a line with a statistics cookie."
9674 (interactive "P")
9675 (if all
9676 (progn
9677 (org-update-checkbox-count 'all)
9678 (org-map-entries 'org-update-parent-todo-statistics))
9679 (if (not (org-on-heading-p))
9680 (org-update-checkbox-count)
9681 (let ((pos (move-marker (make-marker) (point)))
9682 end l1 l2)
9683 (ignore-errors (org-back-to-heading t))
9684 (if (not (org-on-heading-p))
9685 (org-update-checkbox-count)
9686 (setq l1 (org-outline-level))
9687 (setq end (save-excursion
9688 (outline-next-heading)
9689 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9690 (point)))
9691 (if (and (save-excursion (re-search-forward
9692 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9693 (not (save-excursion (re-search-forward
9694 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9695 (org-update-checkbox-count)
9696 (if (and l2 (> l2 l1))
9697 (progn
9698 (goto-char end)
9699 (org-update-parent-todo-statistics))
9700 (error "No data for statistics cookie"))))
9701 (goto-char pos)
9702 (move-marker pos nil)))))
9704 (defvar org-entry-property-inherited-from) ;; defined below
9705 (defun org-update-parent-todo-statistics ()
9706 "Update any statistics cookie in the parent of the current headline.
9707 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9708 the entire subtree and this will travel up the hierarchy and update
9709 statistics everywhere."
9710 (interactive)
9711 (let* ((lim 0) prop
9712 (recursive (or (not org-hierarchical-todo-statistics)
9713 (string-match
9714 "\\<recursive\\>"
9715 (or (setq prop (org-entry-get
9716 nil "COOKIE_DATA" 'inherit)) ""))))
9717 (lim (or (and prop (marker-position
9718 org-entry-property-inherited-from))
9719 lim))
9720 (first t)
9721 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9722 level ltoggle l1
9723 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9724 (catch 'exit
9725 (save-excursion
9726 (beginning-of-line 1)
9727 (if (org-at-heading-p)
9728 (setq ltoggle (funcall outline-level))
9729 (error "This should not happen"))
9730 (while (and (setq level (org-up-heading-safe))
9731 (or recursive first)
9732 (>= (point) lim))
9733 (setq first nil)
9734 (unless (and level
9735 (not (string-match
9736 "\\<checkbox\\>"
9737 (downcase
9738 (or (org-entry-get
9739 nil "COOKIE_DATA")
9740 "")))))
9741 (throw 'exit nil))
9742 (while (re-search-forward box-re (point-at-eol) t)
9743 (setq cnt-all 0 cnt-done 0 cookie-present t)
9744 (setq is-percent (match-end 2))
9745 (save-match-data
9746 (unless (outline-next-heading) (throw 'exit nil))
9747 (while (and (looking-at org-complex-heading-regexp)
9748 (> (setq l1 (length (match-string 1))) level))
9749 (setq kwd (and (or recursive (= l1 ltoggle))
9750 (match-string 2)))
9751 (if (or (eq org-provide-todo-statistics 'all-headlines)
9752 (and (listp org-provide-todo-statistics)
9753 (or (member kwd org-provide-todo-statistics)
9754 (member kwd org-done-keywords))))
9755 (setq cnt-all (1+ cnt-all))
9756 (if (eq org-provide-todo-statistics t)
9757 (and kwd (setq cnt-all (1+ cnt-all)))))
9758 (and (member kwd org-done-keywords)
9759 (setq cnt-done (1+ cnt-done)))
9760 (outline-next-heading)))
9761 (replace-match
9762 (if is-percent
9763 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9764 (format "[%d/%d]" cnt-done cnt-all)))))
9765 (when cookie-present
9766 (run-hook-with-args 'org-after-todo-statistics-hook
9767 cnt-done (- cnt-all cnt-done)))))
9768 (run-hooks 'org-todo-statistics-hook)))
9770 (defvar org-after-todo-statistics-hook nil
9771 "Hook that is called after a TODO statistics cookie has been updated.
9772 Each function is called with two arguments: the number of not-done entries
9773 and the number of done entries.
9775 For example, the following function, when added to this hook, will switch
9776 an entry to DONE when all children are done, and back to TODO when new
9777 entries are set to a TODO status. Note that this hook is only called
9778 when there is a statistics cookie in the headline!
9780 (defun org-summary-todo (n-done n-not-done)
9781 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9782 (let (org-log-done org-log-states) ; turn off logging
9783 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9786 (defvar org-todo-statistics-hook nil
9787 "Hook that is run whenever Org thinks TODO statistics should be updated.
9788 This hook runs even if there is no statisics cookie present, in which case
9789 `org-after-todo-statistics-hook' would not run.")
9791 (defun org-todo-trigger-tag-changes (state)
9792 "Apply the changes defined in `org-todo-state-tags-triggers'."
9793 (let ((l org-todo-state-tags-triggers)
9794 changes)
9795 (when (or (not state) (equal state ""))
9796 (setq changes (append changes (cdr (assoc "" l)))))
9797 (when (and (stringp state) (> (length state) 0))
9798 (setq changes (append changes (cdr (assoc state l)))))
9799 (when (member state org-not-done-keywords)
9800 (setq changes (append changes (cdr (assoc 'todo l)))))
9801 (when (member state org-done-keywords)
9802 (setq changes (append changes (cdr (assoc 'done l)))))
9803 (dolist (c changes)
9804 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9806 (defun org-local-logging (value)
9807 "Get logging settings from a property VALUE."
9808 (let* (words w a)
9809 ;; directly set the variables, they are already local.
9810 (setq org-log-done nil
9811 org-log-repeat nil
9812 org-todo-log-states nil)
9813 (setq words (org-split-string value))
9814 (while (setq w (pop words))
9815 (cond
9816 ((setq a (assoc w org-startup-options))
9817 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9818 (set (nth 1 a) (nth 2 a))))
9819 ((setq a (org-extract-log-state-settings w))
9820 (and (member (car a) org-todo-keywords-1)
9821 (push a org-todo-log-states)))))))
9823 (defun org-get-todo-sequence-head (kwd)
9824 "Return the head of the TODO sequence to which KWD belongs.
9825 If KWD is not set, check if there is a text property remembering the
9826 right sequence."
9827 (let (p)
9828 (cond
9829 ((not kwd)
9830 (or (get-text-property (point-at-bol) 'org-todo-head)
9831 (progn
9832 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9833 nil (point-at-eol)))
9834 (get-text-property p 'org-todo-head))))
9835 ((not (member kwd org-todo-keywords-1))
9836 (car org-todo-keywords-1))
9837 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9839 (defun org-fast-todo-selection ()
9840 "Fast TODO keyword selection with single keys.
9841 Returns the new TODO keyword, or nil if no state change should occur."
9842 (let* ((fulltable org-todo-key-alist)
9843 (done-keywords org-done-keywords) ;; needed for the faces.
9844 (maxlen (apply 'max (mapcar
9845 (lambda (x)
9846 (if (stringp (car x)) (string-width (car x)) 0))
9847 fulltable)))
9848 (expert nil)
9849 (fwidth (+ maxlen 3 1 3))
9850 (ncol (/ (- (window-width) 4) fwidth))
9851 tg cnt e c tbl
9852 groups ingroup)
9853 (save-excursion
9854 (save-window-excursion
9855 (if expert
9856 (set-buffer (get-buffer-create " *Org todo*"))
9857 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9858 (erase-buffer)
9859 (org-set-local 'org-done-keywords done-keywords)
9860 (setq tbl fulltable cnt 0)
9861 (while (setq e (pop tbl))
9862 (cond
9863 ((equal e '(:startgroup))
9864 (push '() groups) (setq ingroup t)
9865 (when (not (= cnt 0))
9866 (setq cnt 0)
9867 (insert "\n"))
9868 (insert "{ "))
9869 ((equal e '(:endgroup))
9870 (setq ingroup nil cnt 0)
9871 (insert "}\n"))
9872 ((equal e '(:newline))
9873 (when (not (= cnt 0))
9874 (setq cnt 0)
9875 (insert "\n")
9876 (setq e (car tbl))
9877 (while (equal (car tbl) '(:newline))
9878 (insert "\n")
9879 (setq tbl (cdr tbl)))))
9881 (setq tg (car e) c (cdr e))
9882 (if ingroup (push tg (car groups)))
9883 (setq tg (org-add-props tg nil 'face
9884 (org-get-todo-face tg)))
9885 (if (and (= cnt 0) (not ingroup)) (insert " "))
9886 (insert "[" c "] " tg (make-string
9887 (- fwidth 4 (length tg)) ?\ ))
9888 (when (= (setq cnt (1+ cnt)) ncol)
9889 (insert "\n")
9890 (if ingroup (insert " "))
9891 (setq cnt 0)))))
9892 (insert "\n")
9893 (goto-char (point-min))
9894 (if (not expert) (org-fit-window-to-buffer))
9895 (message "[a-z..]:Set [SPC]:clear")
9896 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9897 (cond
9898 ((or (= c ?\C-g)
9899 (and (= c ?q) (not (rassoc c fulltable))))
9900 (setq quit-flag t))
9901 ((= c ?\ ) nil)
9902 ((setq e (rassoc c fulltable) tg (car e))
9904 (t (setq quit-flag t)))))))
9906 (defun org-entry-is-todo-p ()
9907 (member (org-get-todo-state) org-not-done-keywords))
9909 (defun org-entry-is-done-p ()
9910 (member (org-get-todo-state) org-done-keywords))
9912 (defun org-get-todo-state ()
9913 (save-excursion
9914 (org-back-to-heading t)
9915 (and (looking-at org-todo-line-regexp)
9916 (match-end 2)
9917 (match-string 2))))
9919 (defun org-at-date-range-p (&optional inactive-ok)
9920 "Is the cursor inside a date range?"
9921 (interactive)
9922 (save-excursion
9923 (catch 'exit
9924 (let ((pos (point)))
9925 (skip-chars-backward "^[<\r\n")
9926 (skip-chars-backward "<[")
9927 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9928 (>= (match-end 0) pos)
9929 (throw 'exit t))
9930 (skip-chars-backward "^<[\r\n")
9931 (skip-chars-backward "<[")
9932 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9933 (>= (match-end 0) pos)
9934 (throw 'exit t)))
9935 nil)))
9937 (defun org-get-repeat ()
9938 "Check if there is a deadline/schedule with repeater in this entry."
9939 (save-match-data
9940 (save-excursion
9941 (org-back-to-heading t)
9942 (if (re-search-forward
9943 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9944 (match-string 1)))))
9946 (defvar org-last-changed-timestamp)
9947 (defvar org-last-inserted-timestamp)
9948 (defvar org-log-post-message)
9949 (defvar org-log-note-purpose)
9950 (defvar org-log-note-how)
9951 (defvar org-log-note-extra)
9952 (defun org-auto-repeat-maybe (done-word)
9953 "Check if the current headline contains a repeated deadline/schedule.
9954 If yes, set TODO state back to what it was and change the base date
9955 of repeating deadline/scheduled time stamps to new date.
9956 This function is run automatically after each state change to a DONE state."
9957 ;; last-state is dynamically scoped into this function
9958 (let* ((repeat (org-get-repeat))
9959 (aa (assoc last-state org-todo-kwd-alist))
9960 (interpret (nth 1 aa))
9961 (head (nth 2 aa))
9962 (whata '(("d" . day) ("m" . month) ("y" . year)))
9963 (msg "Entry repeats: ")
9964 (org-log-done nil)
9965 (org-todo-log-states nil)
9966 (nshiftmax 10) (nshift 0)
9967 re type n what ts time)
9968 (when repeat
9969 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9970 (org-todo (if (eq interpret 'type) last-state head))
9971 (org-entry-put nil "LAST_REPEAT" (format-time-string
9972 (org-time-stamp-format t t)))
9973 (when org-log-repeat
9974 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9975 (memq 'org-add-log-note post-command-hook))
9976 ;; OK, we are already setup for some record
9977 (if (eq org-log-repeat 'note)
9978 ;; make sure we take a note, not only a time stamp
9979 (setq org-log-note-how 'note))
9980 ;; Set up for taking a record
9981 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9982 last-state
9983 'findpos org-log-repeat)))
9984 (org-back-to-heading t)
9985 (org-add-planning-info nil nil 'closed)
9986 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9987 org-deadline-time-regexp "\\)\\|\\("
9988 org-ts-regexp "\\)"))
9989 (while (re-search-forward
9990 re (save-excursion (outline-next-heading) (point)) t)
9991 (setq type (if (match-end 1) org-scheduled-string
9992 (if (match-end 3) org-deadline-string "Plain:"))
9993 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9994 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9995 (setq n (string-to-number (match-string 2 ts))
9996 what (match-string 3 ts))
9997 (if (equal what "w") (setq n (* n 7) what "d"))
9998 ;; Preparation, see if we need to modify the start date for the change
9999 (when (match-end 1)
10000 (setq time (save-match-data (org-time-string-to-time ts)))
10001 (cond
10002 ((equal (match-string 1 ts) ".")
10003 ;; Shift starting date to today
10004 (org-timestamp-change
10005 (- (time-to-days (current-time)) (time-to-days time))
10006 'day))
10007 ((equal (match-string 1 ts) "+")
10008 (while (or (= nshift 0)
10009 (<= (time-to-days time) (time-to-days (current-time))))
10010 (when (= (incf nshift) nshiftmax)
10011 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10012 (error "Abort")))
10013 (org-timestamp-change n (cdr (assoc what whata)))
10014 (org-at-timestamp-p t)
10015 (setq ts (match-string 1))
10016 (setq time (save-match-data (org-time-string-to-time ts))))
10017 (org-timestamp-change (- n) (cdr (assoc what whata)))
10018 ;; rematch, so that we have everything in place for the real shift
10019 (org-at-timestamp-p t)
10020 (setq ts (match-string 1))
10021 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10022 (org-timestamp-change n (cdr (assoc what whata)))
10023 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10024 (setq org-log-post-message msg)
10025 (message "%s" msg))))
10027 (defun org-show-todo-tree (arg)
10028 "Make a compact tree which shows all headlines marked with TODO.
10029 The tree will show the lines where the regexp matches, and all higher
10030 headlines above the match.
10031 With a \\[universal-argument] prefix, prompt for a regexp to match.
10032 With a numeric prefix N, construct a sparse tree for the Nth element
10033 of `org-todo-keywords-1'."
10034 (interactive "P")
10035 (let ((case-fold-search nil)
10036 (kwd-re
10037 (cond ((null arg) org-not-done-regexp)
10038 ((equal arg '(4))
10039 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10040 (mapcar 'list org-todo-keywords-1))))
10041 (concat "\\("
10042 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10043 "\\)\\>")))
10044 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10045 (regexp-quote (nth (1- (prefix-numeric-value arg))
10046 org-todo-keywords-1)))
10047 (t (error "Invalid prefix argument: %s" arg)))))
10048 (message "%d TODO entries found"
10049 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10051 (defun org-deadline (&optional remove time)
10052 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10053 With argument REMOVE, remove any deadline from the item.
10054 When TIME is set, it should be an internal time specification, and the
10055 scheduling will use the corresponding date."
10056 (interactive "P")
10057 (if remove
10058 (progn
10059 (org-remove-timestamp-with-keyword org-deadline-string)
10060 (message "Item no longer has a deadline."))
10061 (if (org-get-repeat)
10062 (error "Cannot change deadline on task with repeater, please do that by hand")
10063 (org-add-planning-info 'deadline time 'closed)
10064 (message "Deadline on %s" org-last-inserted-timestamp))))
10066 (defun org-schedule (&optional remove time)
10067 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10068 With argument REMOVE, remove any scheduling date from the item.
10069 When TIME is set, it should be an internal time specification, and the
10070 scheduling will use the corresponding date."
10071 (interactive "P")
10072 (if remove
10073 (progn
10074 (org-remove-timestamp-with-keyword org-scheduled-string)
10075 (message "Item is no longer scheduled."))
10076 (if (org-get-repeat)
10077 (error "Cannot reschedule task with repeater, please do that by hand")
10078 (org-add-planning-info 'scheduled time 'closed)
10079 (message "Scheduled to %s" org-last-inserted-timestamp))))
10081 (defun org-get-scheduled-time (pom &optional inherit)
10082 "Get the scheduled time as a time tuple, of a format suitable
10083 for calling org-schedule with, or if there is no scheduling,
10084 returns nil."
10085 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10086 (when time
10087 (apply 'encode-time (org-parse-time-string time)))))
10089 (defun org-get-deadline-time (pom &optional inherit)
10090 "Get the deadine as a time tuple, of a format suitable for
10091 calling org-deadlin with, or if there is no scheduling, returns
10092 nil."
10093 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10094 (when time
10095 (apply 'encode-time (org-parse-time-string time)))))
10097 (defun org-remove-timestamp-with-keyword (keyword)
10098 "Remove all time stamps with KEYWORD in the current entry."
10099 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10100 beg)
10101 (save-excursion
10102 (org-back-to-heading t)
10103 (setq beg (point))
10104 (outline-next-heading)
10105 (while (re-search-backward re beg t)
10106 (replace-match "")
10107 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10108 (equal (char-before) ?\ ))
10109 (backward-delete-char 1)
10110 (if (string-match "^[ \t]*$" (buffer-substring
10111 (point-at-bol) (point-at-eol)))
10112 (delete-region (point-at-bol)
10113 (min (point-max) (1+ (point-at-eol))))))))))
10115 (defun org-add-planning-info (what &optional time &rest remove)
10116 "Insert new timestamp with keyword in the line directly after the headline.
10117 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10118 If non is given, the user is prompted for a date.
10119 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10120 be removed."
10121 (interactive)
10122 (let (org-time-was-given org-end-time-was-given ts
10123 end default-time default-input)
10125 (catch 'exit
10126 (when (and (not time) (memq what '(scheduled deadline)))
10127 ;; Try to get a default date/time from existing timestamp
10128 (save-excursion
10129 (org-back-to-heading t)
10130 (setq end (save-excursion (outline-next-heading) (point)))
10131 (when (re-search-forward (if (eq what 'scheduled)
10132 org-scheduled-time-regexp
10133 org-deadline-time-regexp)
10134 end t)
10135 (setq ts (match-string 1)
10136 default-time
10137 (apply 'encode-time (org-parse-time-string ts))
10138 default-input (and ts (org-get-compact-tod ts))))))
10139 (when what
10140 ;; If necessary, get the time from the user
10141 (setq time (or time (org-read-date nil 'to-time nil nil
10142 default-time default-input))))
10144 (when (and org-insert-labeled-timestamps-at-point
10145 (member what '(scheduled deadline)))
10146 (insert
10147 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10148 (org-insert-time-stamp time org-time-was-given
10149 nil nil nil (list org-end-time-was-given))
10150 (setq what nil))
10151 (save-excursion
10152 (save-restriction
10153 (let (col list elt ts buffer-invisibility-spec)
10154 (org-back-to-heading t)
10155 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10156 (goto-char (match-end 1))
10157 (setq col (current-column))
10158 (goto-char (match-end 0))
10159 (if (eobp) (insert "\n") (forward-char 1))
10160 (when (and (not what)
10161 (not (looking-at
10162 (concat "[ \t]*"
10163 org-keyword-time-not-clock-regexp))))
10164 ;; Nothing to add, nothing to remove...... :-)
10165 (throw 'exit nil))
10166 (if (and (not (looking-at outline-regexp))
10167 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10168 "[^\r\n]*"))
10169 (not (equal (match-string 1) org-clock-string)))
10170 (narrow-to-region (match-beginning 0) (match-end 0))
10171 (insert-before-markers "\n")
10172 (backward-char 1)
10173 (narrow-to-region (point) (point))
10174 (and org-adapt-indentation (org-indent-to-column col)))
10175 ;; Check if we have to remove something.
10176 (setq list (cons what remove))
10177 (while list
10178 (setq elt (pop list))
10179 (goto-char (point-min))
10180 (when (or (and (eq elt 'scheduled)
10181 (re-search-forward org-scheduled-time-regexp nil t))
10182 (and (eq elt 'deadline)
10183 (re-search-forward org-deadline-time-regexp nil t))
10184 (and (eq elt 'closed)
10185 (re-search-forward org-closed-time-regexp nil t)))
10186 (replace-match "")
10187 (if (looking-at "--+<[^>]+>") (replace-match ""))
10188 (if (looking-at " +") (replace-match ""))))
10189 (goto-char (point-max))
10190 (when what
10191 (insert
10192 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10193 (cond ((eq what 'scheduled) org-scheduled-string)
10194 ((eq what 'deadline) org-deadline-string)
10195 ((eq what 'closed) org-closed-string))
10196 " ")
10197 (setq ts (org-insert-time-stamp
10198 time
10199 (or org-time-was-given
10200 (and (eq what 'closed) org-log-done-with-time))
10201 (eq what 'closed)
10202 nil nil (list org-end-time-was-given)))
10203 (end-of-line 1))
10204 (goto-char (point-min))
10205 (widen)
10206 (if (and (looking-at "[ \t]+\n")
10207 (equal (char-before) ?\n))
10208 (delete-region (1- (point)) (point-at-eol)))
10209 ts))))))
10211 (defvar org-log-note-marker (make-marker))
10212 (defvar org-log-note-purpose nil)
10213 (defvar org-log-note-state nil)
10214 (defvar org-log-note-previous-state nil)
10215 (defvar org-log-note-how nil)
10216 (defvar org-log-note-extra nil)
10217 (defvar org-log-note-window-configuration nil)
10218 (defvar org-log-note-return-to (make-marker))
10219 (defvar org-log-post-message nil
10220 "Message to be displayed after a log note has been stored.
10221 The auto-repeater uses this.")
10223 (defun org-add-note ()
10224 "Add a note to the current entry.
10225 This is done in the same way as adding a state change note."
10226 (interactive)
10227 (org-add-log-setup 'note nil nil 'findpos nil))
10229 (defvar org-property-end-re)
10230 (defun org-add-log-setup (&optional purpose state prev-state
10231 findpos how &optional extra)
10232 "Set up the post command hook to take a note.
10233 If this is about to TODO state change, the new state is expected in STATE.
10234 When FINDPOS is non-nil, find the correct position for the note in
10235 the current entry. If not, assume that it can be inserted at point.
10236 HOW is an indicator what kind of note should be created.
10237 EXTRA is additional text that will be inserted into the notes buffer."
10238 (let* ((org-log-into-drawer (org-log-into-drawer))
10239 (drawer (cond ((stringp org-log-into-drawer)
10240 org-log-into-drawer)
10241 (org-log-into-drawer "LOGBOOK")
10242 (t nil))))
10243 (save-restriction
10244 (save-excursion
10245 (when findpos
10246 (org-back-to-heading t)
10247 (narrow-to-region (point) (save-excursion
10248 (outline-next-heading) (point)))
10249 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10250 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10251 "[^\r\n]*\\)?"))
10252 (goto-char (match-end 0))
10253 (cond
10254 (drawer
10255 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10256 nil t)
10257 (progn
10258 (goto-char (match-end 0))
10259 (or org-log-states-order-reversed
10260 (and (re-search-forward org-property-end-re nil t)
10261 (goto-char (1- (match-beginning 0))))))
10262 (insert "\n:" drawer ":\n:END:")
10263 (beginning-of-line 0)
10264 (org-indent-line-function)
10265 (beginning-of-line 2)
10266 (org-indent-line-function)
10267 (end-of-line 0)))
10268 ((and org-log-state-notes-insert-after-drawers
10269 (save-excursion
10270 (forward-line) (looking-at org-drawer-regexp)))
10271 (forward-line)
10272 (while (looking-at org-drawer-regexp)
10273 (goto-char (match-end 0))
10274 (re-search-forward org-property-end-re (point-max) t)
10275 (forward-line))
10276 (forward-line -1)))
10277 (unless org-log-states-order-reversed
10278 (and (= (char-after) ?\n) (forward-char 1))
10279 (org-skip-over-state-notes)
10280 (skip-chars-backward " \t\n\r")))
10281 (move-marker org-log-note-marker (point))
10282 (setq org-log-note-purpose purpose
10283 org-log-note-state state
10284 org-log-note-previous-state prev-state
10285 org-log-note-how how
10286 org-log-note-extra extra)
10287 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10289 (defun org-skip-over-state-notes ()
10290 "Skip past the list of State notes in an entry."
10291 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10292 (while (looking-at "[ \t]*- State")
10293 (condition-case nil
10294 (org-next-item)
10295 (error (org-end-of-item)))))
10297 (defun org-add-log-note (&optional purpose)
10298 "Pop up a window for taking a note, and add this note later at point."
10299 (remove-hook 'post-command-hook 'org-add-log-note)
10300 (setq org-log-note-window-configuration (current-window-configuration))
10301 (delete-other-windows)
10302 (move-marker org-log-note-return-to (point))
10303 (switch-to-buffer (marker-buffer org-log-note-marker))
10304 (goto-char org-log-note-marker)
10305 (org-switch-to-buffer-other-window "*Org Note*")
10306 (erase-buffer)
10307 (if (memq org-log-note-how '(time state))
10308 (let (current-prefix-arg) (org-store-log-note))
10309 (let ((org-inhibit-startup t)) (org-mode))
10310 (insert (format "# Insert note for %s.
10311 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10312 (cond
10313 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10314 ((eq org-log-note-purpose 'done) "closed todo item")
10315 ((eq org-log-note-purpose 'state)
10316 (format "state change from \"%s\" to \"%s\""
10317 (or org-log-note-previous-state "")
10318 (or org-log-note-state "")))
10319 ((eq org-log-note-purpose 'note)
10320 "this entry")
10321 (t (error "This should not happen")))))
10322 (if org-log-note-extra (insert org-log-note-extra))
10323 (org-set-local 'org-finish-function 'org-store-log-note)))
10325 (defvar org-note-abort nil) ; dynamically scoped
10326 (defun org-store-log-note ()
10327 "Finish taking a log note, and insert it to where it belongs."
10328 (let ((txt (buffer-string))
10329 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10330 lines ind)
10331 (kill-buffer (current-buffer))
10332 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10333 (setq txt (replace-match "" t t txt)))
10334 (if (string-match "\\s-+\\'" txt)
10335 (setq txt (replace-match "" t t txt)))
10336 (setq lines (org-split-string txt "\n"))
10337 (when (and note (string-match "\\S-" note))
10338 (setq note
10339 (org-replace-escapes
10340 note
10341 (list (cons "%u" (user-login-name))
10342 (cons "%U" user-full-name)
10343 (cons "%t" (format-time-string
10344 (org-time-stamp-format 'long 'inactive)
10345 (current-time)))
10346 (cons "%s" (if org-log-note-state
10347 (concat "\"" org-log-note-state "\"")
10348 ""))
10349 (cons "%S" (if org-log-note-previous-state
10350 (concat "\"" org-log-note-previous-state "\"")
10351 "\"\"")))))
10352 (if lines (setq note (concat note " \\\\")))
10353 (push note lines))
10354 (when (or current-prefix-arg org-note-abort)
10355 (when org-log-into-drawer
10356 (org-remove-empty-drawer-at
10357 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10358 org-log-note-marker))
10359 (setq lines nil))
10360 (when lines
10361 (save-excursion
10362 (set-buffer (marker-buffer org-log-note-marker))
10363 (save-excursion
10364 (goto-char org-log-note-marker)
10365 (move-marker org-log-note-marker nil)
10366 (end-of-line 1)
10367 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10368 (insert "- " (pop lines))
10369 (org-indent-line-function)
10370 (beginning-of-line 1)
10371 (looking-at "[ \t]*")
10372 (setq ind (concat (match-string 0) " "))
10373 (end-of-line 1)
10374 (while lines (insert "\n" ind (pop lines)))
10375 (message "Note stored")
10376 (org-back-to-heading t)
10377 (org-cycle-hide-drawers 'children)))))
10378 (set-window-configuration org-log-note-window-configuration)
10379 (with-current-buffer (marker-buffer org-log-note-return-to)
10380 (goto-char org-log-note-return-to))
10381 (move-marker org-log-note-return-to nil)
10382 (and org-log-post-message (message "%s" org-log-post-message)))
10384 (defun org-remove-empty-drawer-at (drawer pos)
10385 "Remove an emptyr DARWER drawer at position POS.
10386 POS may also be a marker."
10387 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10388 (save-excursion
10389 (save-restriction
10390 (widen)
10391 (goto-char pos)
10392 (if (org-in-regexp
10393 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10394 (replace-match ""))))))
10396 (defun org-sparse-tree (&optional arg)
10397 "Create a sparse tree, prompt for the details.
10398 This command can create sparse trees. You first need to select the type
10399 of match used to create the tree:
10401 t Show entries with a specific TODO keyword.
10402 m Show entries selected by a tags/property match.
10403 p Enter a property name and its value (both with completion on existing
10404 names/values) and show entries with that property.
10405 r Show entries matching a regular expression.
10406 d Show deadlines due within `org-deadline-warning-days'.
10407 b Show deadlines and scheduled items before a date.
10408 a Show deadlines and scheduled items after a date."
10409 (interactive "P")
10410 (let (ans kwd value)
10411 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10412 (setq ans (read-char-exclusive))
10413 (cond
10414 ((equal ans ?d)
10415 (call-interactively 'org-check-deadlines))
10416 ((equal ans ?b)
10417 (call-interactively 'org-check-before-date))
10418 ((equal ans ?a)
10419 (call-interactively 'org-check-after-date))
10420 ((equal ans ?t)
10421 (org-show-todo-tree '(4)))
10422 ((member ans '(?T ?m))
10423 (call-interactively 'org-match-sparse-tree))
10424 ((member ans '(?p ?P))
10425 (setq kwd (org-icompleting-read "Property: "
10426 (mapcar 'list (org-buffer-property-keys))))
10427 (setq value (org-icompleting-read "Value: "
10428 (mapcar 'list (org-property-values kwd))))
10429 (unless (string-match "\\`{.*}\\'" value)
10430 (setq value (concat "\"" value "\"")))
10431 (org-match-sparse-tree arg (concat kwd "=" value)))
10432 ((member ans '(?r ?R ?/))
10433 (call-interactively 'org-occur))
10434 (t (error "No such sparse tree command \"%c\"" ans)))))
10436 (defvar org-occur-highlights nil
10437 "List of overlays used for occur matches.")
10438 (make-variable-buffer-local 'org-occur-highlights)
10439 (defvar org-occur-parameters nil
10440 "Parameters of the active org-occur calls.
10441 This is a list, each call to org-occur pushes as cons cell,
10442 containing the regular expression and the callback, onto the list.
10443 The list can contain several entries if `org-occur' has been called
10444 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10445 will only contain one set of parameters. When the highlights are
10446 removed (for example with `C-c C-c', or with the next edit (depending
10447 on `org-remove-highlights-with-change'), this variable is emptied
10448 as well.")
10449 (make-variable-buffer-local 'org-occur-parameters)
10451 (defun org-occur (regexp &optional keep-previous callback)
10452 "Make a compact tree which shows all matches of REGEXP.
10453 The tree will show the lines where the regexp matches, and all higher
10454 headlines above the match. It will also show the heading after the match,
10455 to make sure editing the matching entry is easy.
10456 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10457 call to `org-occur' will be kept, to allow stacking of calls to this
10458 command.
10459 If CALLBACK is non-nil, it is a function which is called to confirm
10460 that the match should indeed be shown."
10461 (interactive "sRegexp: \nP")
10462 (when (equal regexp "")
10463 (error "Regexp cannot be empty"))
10464 (unless keep-previous
10465 (org-remove-occur-highlights nil nil t))
10466 (push (cons regexp callback) org-occur-parameters)
10467 (let ((cnt 0))
10468 (save-excursion
10469 (goto-char (point-min))
10470 (if (or (not keep-previous) ; do not want to keep
10471 (not org-occur-highlights)) ; no previous matches
10472 ;; hide everything
10473 (org-overview))
10474 (while (re-search-forward regexp nil t)
10475 (when (or (not callback)
10476 (save-match-data (funcall callback)))
10477 (setq cnt (1+ cnt))
10478 (when org-highlight-sparse-tree-matches
10479 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10480 (org-show-context 'occur-tree))))
10481 (when org-remove-highlights-with-change
10482 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10483 nil 'local))
10484 (unless org-sparse-tree-open-archived-trees
10485 (org-hide-archived-subtrees (point-min) (point-max)))
10486 (run-hooks 'org-occur-hook)
10487 (if (interactive-p)
10488 (message "%d match(es) for regexp %s" cnt regexp))
10489 cnt))
10491 (defun org-show-context (&optional key)
10492 "Make sure point and context and visible.
10493 How much context is shown depends upon the variables
10494 `org-show-hierarchy-above', `org-show-following-heading'. and
10495 `org-show-siblings'."
10496 (let ((heading-p (org-on-heading-p t))
10497 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10498 (following-p (org-get-alist-option org-show-following-heading key))
10499 (entry-p (org-get-alist-option org-show-entry-below key))
10500 (siblings-p (org-get-alist-option org-show-siblings key)))
10501 (catch 'exit
10502 ;; Show heading or entry text
10503 (if (and heading-p (not entry-p))
10504 (org-flag-heading nil) ; only show the heading
10505 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10506 (org-show-hidden-entry))) ; show entire entry
10507 (when following-p
10508 ;; Show next sibling, or heading below text
10509 (save-excursion
10510 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10511 (org-flag-heading nil))))
10512 (when siblings-p (org-show-siblings))
10513 (when hierarchy-p
10514 ;; show all higher headings, possibly with siblings
10515 (save-excursion
10516 (while (and (condition-case nil
10517 (progn (org-up-heading-all 1) t)
10518 (error nil))
10519 (not (bobp)))
10520 (org-flag-heading nil)
10521 (when siblings-p (org-show-siblings))))))))
10523 (defun org-reveal (&optional siblings)
10524 "Show current entry, hierarchy above it, and the following headline.
10525 This can be used to show a consistent set of context around locations
10526 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10527 not t for the search context.
10529 With optional argument SIBLINGS, on each level of the hierarchy all
10530 siblings are shown. This repairs the tree structure to what it would
10531 look like when opened with hierarchical calls to `org-cycle'."
10532 (interactive "P")
10533 (let ((org-show-hierarchy-above t)
10534 (org-show-following-heading t)
10535 (org-show-siblings (if siblings t org-show-siblings)))
10536 (org-show-context nil)))
10538 (defun org-highlight-new-match (beg end)
10539 "Highlight from BEG to END and mark the highlight is an occur headline."
10540 (let ((ov (org-make-overlay beg end)))
10541 (org-overlay-put ov 'face 'secondary-selection)
10542 (push ov org-occur-highlights)))
10544 (defun org-remove-occur-highlights (&optional beg end noremove)
10545 "Remove the occur highlights from the buffer.
10546 BEG and END are ignored. If NOREMOVE is nil, remove this function
10547 from the `before-change-functions' in the current buffer."
10548 (interactive)
10549 (unless org-inhibit-highlight-removal
10550 (mapc 'org-delete-overlay org-occur-highlights)
10551 (setq org-occur-highlights nil)
10552 (setq org-occur-parameters nil)
10553 (unless noremove
10554 (remove-hook 'before-change-functions
10555 'org-remove-occur-highlights 'local))))
10557 ;;;; Priorities
10559 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10560 "Regular expression matching the priority indicator.")
10562 (defvar org-remove-priority-next-time nil)
10564 (defun org-priority-up ()
10565 "Increase the priority of the current item."
10566 (interactive)
10567 (org-priority 'up))
10569 (defun org-priority-down ()
10570 "Decrease the priority of the current item."
10571 (interactive)
10572 (org-priority 'down))
10574 (defun org-priority (&optional action)
10575 "Change the priority of an item by ARG.
10576 ACTION can be `set', `up', `down', or a character."
10577 (interactive)
10578 (unless org-enable-priority-commands
10579 (error "Priority commands are disabled"))
10580 (setq action (or action 'set))
10581 (let (current new news have remove)
10582 (save-excursion
10583 (org-back-to-heading t)
10584 (if (looking-at org-priority-regexp)
10585 (setq current (string-to-char (match-string 2))
10586 have t)
10587 (setq current org-default-priority))
10588 (cond
10589 ((or (eq action 'set)
10590 (if (featurep 'xemacs) (characterp action) (integerp action)))
10591 (if (not (eq action 'set))
10592 (setq new action)
10593 (message "Priority %c-%c, SPC to remove: "
10594 org-highest-priority org-lowest-priority)
10595 (setq new (read-char-exclusive)))
10596 (if (and (= (upcase org-highest-priority) org-highest-priority)
10597 (= (upcase org-lowest-priority) org-lowest-priority))
10598 (setq new (upcase new)))
10599 (cond ((equal new ?\ ) (setq remove t))
10600 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10601 (error "Priority must be between `%c' and `%c'"
10602 org-highest-priority org-lowest-priority))))
10603 ((eq action 'up)
10604 (if (and (not have) (eq last-command this-command))
10605 (setq new org-lowest-priority)
10606 (setq new (if (and org-priority-start-cycle-with-default (not have))
10607 org-default-priority (1- current)))))
10608 ((eq action 'down)
10609 (if (and (not have) (eq last-command this-command))
10610 (setq new org-highest-priority)
10611 (setq new (if (and org-priority-start-cycle-with-default (not have))
10612 org-default-priority (1+ current)))))
10613 (t (error "Invalid action")))
10614 (if (or (< (upcase new) org-highest-priority)
10615 (> (upcase new) org-lowest-priority))
10616 (setq remove t))
10617 (setq news (format "%c" new))
10618 (if have
10619 (if remove
10620 (replace-match "" t t nil 1)
10621 (replace-match news t t nil 2))
10622 (if remove
10623 (error "No priority cookie found in line")
10624 (let ((case-fold-search nil))
10625 (looking-at org-todo-line-regexp))
10626 (if (match-end 2)
10627 (progn
10628 (goto-char (match-end 2))
10629 (insert " [#" news "]"))
10630 (goto-char (match-beginning 3))
10631 (insert "[#" news "] "))))
10632 (org-preserve-lc (org-set-tags nil 'align)))
10633 (if remove
10634 (message "Priority removed")
10635 (message "Priority of current item set to %s" news))))
10637 (defun org-get-priority (s)
10638 "Find priority cookie and return priority."
10639 (save-match-data
10640 (if (not (string-match org-priority-regexp s))
10641 (* 1000 (- org-lowest-priority org-default-priority))
10642 (* 1000 (- org-lowest-priority
10643 (string-to-char (match-string 2 s)))))))
10645 ;;;; Tags
10647 (defvar org-agenda-archives-mode)
10648 (defvar org-map-continue-from nil
10649 "Position from where mapping should continue.
10650 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10652 (defvar org-scanner-tags nil
10653 "The current tag list while the tags scanner is running.")
10654 (defvar org-trust-scanner-tags nil
10655 "Should `org-get-tags-at' use the tags fro the scanner.
10656 This is for internal dynamical scoping only.
10657 When this is non-nil, the function `org-get-tags-at' will return the value
10658 of `org-scanner-tags' instead of building the list by itself. This
10659 can lead to large speed-ups when the tags scanner is used in a file with
10660 many entries, and when the list of tags is retrieved, for example to
10661 obtain a list of properties. Building the tags list for each entry in such
10662 a file becomes an N^2 operation - but with this variable set, it scales
10663 as N.")
10665 (defun org-scan-tags (action matcher &optional todo-only)
10666 "Scan headline tags with inheritance and produce output ACTION.
10668 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10669 or `agenda' to produce an entry list for an agenda view. It can also be
10670 a Lisp form or a function that should be called at each matched headline, in
10671 this case the return value is a list of all return values from these calls.
10673 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10674 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10675 only lines with a TODO keyword are included in the output."
10676 (require 'org-agenda)
10677 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10678 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10679 (org-re
10680 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10681 (props (list 'face 'default
10682 'done-face 'org-agenda-done
10683 'undone-face 'default
10684 'mouse-face 'highlight
10685 'org-not-done-regexp org-not-done-regexp
10686 'org-todo-regexp org-todo-regexp
10687 'keymap org-agenda-keymap
10688 'help-echo
10689 (format "mouse-2 or RET jump to org file %s"
10690 (abbreviate-file-name
10691 (or (buffer-file-name (buffer-base-buffer))
10692 (buffer-name (buffer-base-buffer)))))))
10693 (case-fold-search nil)
10694 (org-map-continue-from nil)
10695 lspos tags tags-list
10696 (tags-alist (list (cons 0 org-file-tags)))
10697 (llast 0) rtn rtn1 level category i txt
10698 todo marker entry priority)
10699 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10700 (setq action (list 'lambda nil action)))
10701 (save-excursion
10702 (goto-char (point-min))
10703 (when (eq action 'sparse-tree)
10704 (org-overview)
10705 (org-remove-occur-highlights))
10706 (while (re-search-forward re nil t)
10707 (catch :skip
10708 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10709 tags (if (match-end 4) (org-match-string-no-properties 4)))
10710 (goto-char (setq lspos (match-beginning 0)))
10711 (setq level (org-reduced-level (funcall outline-level))
10712 category (org-get-category))
10713 (setq i llast llast level)
10714 ;; remove tag lists from same and sublevels
10715 (while (>= i level)
10716 (when (setq entry (assoc i tags-alist))
10717 (setq tags-alist (delete entry tags-alist)))
10718 (setq i (1- i)))
10719 ;; add the next tags
10720 (when tags
10721 (setq tags (org-split-string tags ":")
10722 tags-alist
10723 (cons (cons level tags) tags-alist)))
10724 ;; compile tags for current headline
10725 (setq tags-list
10726 (if org-use-tag-inheritance
10727 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10728 tags)
10729 org-scanner-tags tags-list)
10730 (when org-use-tag-inheritance
10731 (setcdr (car tags-alist)
10732 (mapcar (lambda (x)
10733 (setq x (copy-sequence x))
10734 (org-add-prop-inherited x))
10735 (cdar tags-alist))))
10736 (when (and tags org-use-tag-inheritance
10737 (or (not (eq t org-use-tag-inheritance))
10738 org-tags-exclude-from-inheritance))
10739 ;; selective inheritance, remove uninherited ones
10740 (setcdr (car tags-alist)
10741 (org-remove-uniherited-tags (cdar tags-alist))))
10742 (when (and (or (not todo-only)
10743 (and (member todo org-not-done-keywords)
10744 (or (not org-agenda-tags-todo-honor-ignore-options)
10745 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10746 (let ((case-fold-search t)) (eval matcher))
10748 (not (member org-archive-tag tags-list))
10749 ;; we have an archive tag, should we use this anyway?
10750 (or (not org-agenda-skip-archived-trees)
10751 (and (eq action 'agenda) org-agenda-archives-mode))))
10752 (unless (eq action 'sparse-tree) (org-agenda-skip))
10754 ;; select this headline
10756 (cond
10757 ((eq action 'sparse-tree)
10758 (and org-highlight-sparse-tree-matches
10759 (org-get-heading) (match-end 0)
10760 (org-highlight-new-match
10761 (match-beginning 0) (match-beginning 1)))
10762 (org-show-context 'tags-tree))
10763 ((eq action 'agenda)
10764 (setq txt (org-format-agenda-item
10766 (concat
10767 (if (eq org-tags-match-list-sublevels 'indented)
10768 (make-string (1- level) ?.) "")
10769 (org-get-heading))
10770 category
10771 tags-list
10773 priority (org-get-priority txt))
10774 (goto-char lspos)
10775 (setq marker (org-agenda-new-marker))
10776 (org-add-props txt props
10777 'org-marker marker 'org-hd-marker marker 'org-category category
10778 'todo-state todo
10779 'priority priority 'type "tagsmatch")
10780 (push txt rtn))
10781 ((functionp action)
10782 (setq org-map-continue-from nil)
10783 (save-excursion
10784 (setq rtn1 (funcall action))
10785 (push rtn1 rtn)))
10786 (t (error "Invalid action")))
10788 ;; if we are to skip sublevels, jump to end of subtree
10789 (unless org-tags-match-list-sublevels
10790 (org-end-of-subtree t)
10791 (backward-char 1))))
10792 ;; Get the correct position from where to continue
10793 (if org-map-continue-from
10794 (goto-char org-map-continue-from)
10795 (and (= (point) lspos) (end-of-line 1)))))
10796 (when (and (eq action 'sparse-tree)
10797 (not org-sparse-tree-open-archived-trees))
10798 (org-hide-archived-subtrees (point-min) (point-max)))
10799 (nreverse rtn)))
10801 (defun org-remove-uniherited-tags (tags)
10802 "Remove all tags that are not inherited from the list TAGS."
10803 (cond
10804 ((eq org-use-tag-inheritance t)
10805 (if org-tags-exclude-from-inheritance
10806 (org-delete-all org-tags-exclude-from-inheritance tags)
10807 tags))
10808 ((not org-use-tag-inheritance) nil)
10809 ((stringp org-use-tag-inheritance)
10810 (delq nil (mapcar
10811 (lambda (x)
10812 (if (and (string-match org-use-tag-inheritance x)
10813 (not (member x org-tags-exclude-from-inheritance)))
10814 x nil))
10815 tags)))
10816 ((listp org-use-tag-inheritance)
10817 (delq nil (mapcar
10818 (lambda (x)
10819 (if (member x org-use-tag-inheritance) x nil))
10820 tags)))))
10822 (defvar todo-only) ;; dynamically scoped
10824 (defun org-match-sparse-tree (&optional todo-only match)
10825 "Create a sparse tree according to tags string MATCH.
10826 MATCH can contain positive and negative selection of tags, like
10827 \"+WORK+URGENT-WITHBOSS\".
10828 If optional argument TODO-ONLY is non-nil, only select lines that are
10829 also TODO lines."
10830 (interactive "P")
10831 (org-prepare-agenda-buffers (list (current-buffer)))
10832 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10834 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10836 (defvar org-cached-props nil)
10837 (defun org-cached-entry-get (pom property)
10838 (if (or (eq t org-use-property-inheritance)
10839 (and (stringp org-use-property-inheritance)
10840 (string-match org-use-property-inheritance property))
10841 (and (listp org-use-property-inheritance)
10842 (member property org-use-property-inheritance)))
10843 ;; Caching is not possible, check it directly
10844 (org-entry-get pom property 'inherit)
10845 ;; Get all properties, so that we can do complicated checks easily
10846 (cdr (assoc property (or org-cached-props
10847 (setq org-cached-props
10848 (org-entry-properties pom)))))))
10850 (defun org-global-tags-completion-table (&optional files)
10851 "Return the list of all tags in all agenda buffer/files."
10852 (save-excursion
10853 (org-uniquify
10854 (delq nil
10855 (apply 'append
10856 (mapcar
10857 (lambda (file)
10858 (set-buffer (find-file-noselect file))
10859 (append (org-get-buffer-tags)
10860 (mapcar (lambda (x) (if (stringp (car-safe x))
10861 (list (car-safe x)) nil))
10862 org-tag-alist)))
10863 (if (and files (car files))
10864 files
10865 (org-agenda-files))))))))
10867 (defun org-make-tags-matcher (match)
10868 "Create the TAGS//TODO matcher form for the selection string MATCH."
10869 ;; todo-only is scoped dynamically into this function, and the function
10870 ;; may change it if the matcher asks for it.
10871 (unless match
10872 ;; Get a new match request, with completion
10873 (let ((org-last-tags-completion-table
10874 (org-global-tags-completion-table)))
10875 (setq match (org-completing-read-no-i
10876 "Match: " 'org-tags-completion-function nil nil nil
10877 'org-tags-history))))
10879 ;; Parse the string and create a lisp form
10880 (let ((match0 match)
10881 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10882 minus tag mm
10883 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10884 orterms term orlist re-p str-p level-p level-op time-p
10885 prop-p pn pv po cat-p gv rest)
10886 (if (string-match "/+" match)
10887 ;; match contains also a todo-matching request
10888 (progn
10889 (setq tagsmatch (substring match 0 (match-beginning 0))
10890 todomatch (substring match (match-end 0)))
10891 (if (string-match "^!" todomatch)
10892 (setq todo-only t todomatch (substring todomatch 1)))
10893 (if (string-match "^\\s-*$" todomatch)
10894 (setq todomatch nil)))
10895 ;; only matching tags
10896 (setq tagsmatch match todomatch nil))
10898 ;; Make the tags matcher
10899 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10900 (setq tagsmatcher t)
10901 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10902 (while (setq term (pop orterms))
10903 (while (and (equal (substring term -1) "\\") orterms)
10904 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10905 (while (string-match re term)
10906 (setq rest (substring term (match-end 0))
10907 minus (and (match-end 1)
10908 (equal (match-string 1 term) "-"))
10909 tag (match-string 2 term)
10910 re-p (equal (string-to-char tag) ?{)
10911 level-p (match-end 4)
10912 prop-p (match-end 5)
10913 mm (cond
10914 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10915 (level-p
10916 (setq level-op (org-op-to-function (match-string 3 term)))
10917 `(,level-op level ,(string-to-number
10918 (match-string 4 term))))
10919 (prop-p
10920 (setq pn (match-string 5 term)
10921 po (match-string 6 term)
10922 pv (match-string 7 term)
10923 cat-p (equal pn "CATEGORY")
10924 re-p (equal (string-to-char pv) ?{)
10925 str-p (equal (string-to-char pv) ?\")
10926 time-p (save-match-data
10927 (string-match "^\"[[<].*[]>]\"$" pv))
10928 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10929 (if time-p (setq pv (org-matcher-time pv)))
10930 (setq po (org-op-to-function po (if time-p 'time str-p)))
10931 (cond
10932 ((equal pn "CATEGORY")
10933 (setq gv '(get-text-property (point) 'org-category)))
10934 ((equal pn "TODO")
10935 (setq gv 'todo))
10937 (setq gv `(org-cached-entry-get nil ,pn))))
10938 (if re-p
10939 (if (eq po 'org<>)
10940 `(not (string-match ,pv (or ,gv "")))
10941 `(string-match ,pv (or ,gv "")))
10942 (if str-p
10943 `(,po (or ,gv "") ,pv)
10944 `(,po (string-to-number (or ,gv ""))
10945 ,(string-to-number pv) ))))
10946 (t `(member ,tag tags-list)))
10947 mm (if minus (list 'not mm) mm)
10948 term rest)
10949 (push mm tagsmatcher))
10950 (push (if (> (length tagsmatcher) 1)
10951 (cons 'and tagsmatcher)
10952 (car tagsmatcher))
10953 orlist)
10954 (setq tagsmatcher nil))
10955 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10956 (setq tagsmatcher
10957 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10958 ;; Make the todo matcher
10959 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10960 (setq todomatcher t)
10961 (setq orterms (org-split-string todomatch "|") orlist nil)
10962 (while (setq term (pop orterms))
10963 (while (string-match re term)
10964 (setq minus (and (match-end 1)
10965 (equal (match-string 1 term) "-"))
10966 kwd (match-string 2 term)
10967 re-p (equal (string-to-char kwd) ?{)
10968 term (substring term (match-end 0))
10969 mm (if re-p
10970 `(string-match ,(substring kwd 1 -1) todo)
10971 (list 'equal 'todo kwd))
10972 mm (if minus (list 'not mm) mm))
10973 (push mm todomatcher))
10974 (push (if (> (length todomatcher) 1)
10975 (cons 'and todomatcher)
10976 (car todomatcher))
10977 orlist)
10978 (setq todomatcher nil))
10979 (setq todomatcher (if (> (length orlist) 1)
10980 (cons 'or orlist) (car orlist))))
10982 ;; Return the string and lisp forms of the matcher
10983 (setq matcher (if todomatcher
10984 (list 'and tagsmatcher todomatcher)
10985 tagsmatcher))
10986 (cons match0 matcher)))
10988 (defun org-op-to-function (op &optional stringp)
10989 "Turn an operator into the appropriate function."
10990 (setq op
10991 (cond
10992 ((equal op "<" ) '(< string< org-time<))
10993 ((equal op ">" ) '(> org-string> org-time>))
10994 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10995 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10996 ((member op '("=" "==")) '(= string= org-time=))
10997 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10998 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11000 (defun org<> (a b) (not (= a b)))
11001 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11002 (defun org-string>= (a b) (not (string< a b)))
11003 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11004 (defun org-string<> (a b) (not (string= a b)))
11005 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11006 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11007 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11008 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11009 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11010 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11011 (defun org-2ft (s)
11012 "Convert S to a floating point time.
11013 If S is already a number, just return it. If it is a string, parse
11014 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11015 (cond
11016 ((numberp s) s)
11017 ((stringp s)
11018 (condition-case nil
11019 (float-time (apply 'encode-time (org-parse-time-string s)))
11020 (error 0.)))
11021 (t 0.)))
11023 (defun org-time-today ()
11024 "Time in seconds today at 0:00.
11025 Returns the float number of seconds since the beginning of the
11026 epoch to the beginning of today (00:00)."
11027 (float-time (apply 'encode-time
11028 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11030 (defun org-matcher-time (s)
11031 "Interpret a time comparison value."
11032 (save-match-data
11033 (cond
11034 ((string= s "<now>") (float-time))
11035 ((string= s "<today>") (org-time-today))
11036 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11037 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11038 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11039 (+ (org-time-today)
11040 (* (string-to-number (match-string 1 s))
11041 (cdr (assoc (match-string 2 s)
11042 '(("d" . 86400.0) ("w" . 604800.0)
11043 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11044 (t (org-2ft s)))))
11046 (defun org-match-any-p (re list)
11047 "Does re match any element of list?"
11048 (setq list (mapcar (lambda (x) (string-match re x)) list))
11049 (delq nil list))
11051 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11052 (defvar org-tags-overlay (org-make-overlay 1 1))
11053 (org-detach-overlay org-tags-overlay)
11055 (defun org-get-local-tags-at (&optional pos)
11056 "Get a list of tags defined in the current headline."
11057 (org-get-tags-at pos 'local))
11059 (defun org-get-local-tags ()
11060 "Get a list of tags defined in the current headline."
11061 (org-get-tags-at nil 'local))
11063 (defun org-get-tags-at (&optional pos local)
11064 "Get a list of all headline tags applicable at POS.
11065 POS defaults to point. If tags are inherited, the list contains
11066 the targets in the same sequence as the headlines appear, i.e.
11067 the tags of the current headline come last.
11068 When LOCAL is non-nil, only return tags from the current headline,
11069 ignore inherited ones."
11070 (interactive)
11071 (if (and org-trust-scanner-tags
11072 (or (not pos) (equal pos (point)))
11073 (not local))
11074 org-scanner-tags
11075 (let (tags ltags lastpos parent)
11076 (save-excursion
11077 (save-restriction
11078 (widen)
11079 (goto-char (or pos (point)))
11080 (save-match-data
11081 (catch 'done
11082 (condition-case nil
11083 (progn
11084 (org-back-to-heading t)
11085 (while (not (equal lastpos (point)))
11086 (setq lastpos (point))
11087 (when (looking-at
11088 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11089 (setq ltags (org-split-string
11090 (org-match-string-no-properties 1) ":"))
11091 (when parent
11092 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11093 (setq tags (append
11094 (if parent
11095 (org-remove-uniherited-tags ltags)
11096 ltags)
11097 tags)))
11098 (or org-use-tag-inheritance (throw 'done t))
11099 (if local (throw 'done t))
11100 (or (org-up-heading-safe) (error nil))
11101 (setq parent t)))
11102 (error nil)))))
11103 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11105 (defun org-add-prop-inherited (s)
11106 (add-text-properties 0 (length s) '(inherited t) s)
11109 (defun org-toggle-tag (tag &optional onoff)
11110 "Toggle the tag TAG for the current line.
11111 If ONOFF is `on' or `off', don't toggle but set to this state."
11112 (let (res current)
11113 (save-excursion
11114 (org-back-to-heading t)
11115 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11116 (point-at-eol) t)
11117 (progn
11118 (setq current (match-string 1))
11119 (replace-match ""))
11120 (setq current ""))
11121 (setq current (nreverse (org-split-string current ":")))
11122 (cond
11123 ((eq onoff 'on)
11124 (setq res t)
11125 (or (member tag current) (push tag current)))
11126 ((eq onoff 'off)
11127 (or (not (member tag current)) (setq current (delete tag current))))
11128 (t (if (member tag current)
11129 (setq current (delete tag current))
11130 (setq res t)
11131 (push tag current))))
11132 (end-of-line 1)
11133 (if current
11134 (progn
11135 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11136 (org-set-tags nil t))
11137 (delete-horizontal-space))
11138 (run-hooks 'org-after-tags-change-hook))
11139 res))
11141 (defun org-align-tags-here (to-col)
11142 ;; Assumes that this is a headline
11143 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11144 (beginning-of-line 1)
11145 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11146 (< pos (match-beginning 2)))
11147 (progn
11148 (setq tags-l (- (match-end 2) (match-beginning 2)))
11149 (goto-char (match-beginning 1))
11150 (insert " ")
11151 (delete-region (point) (1+ (match-beginning 2)))
11152 (setq ncol (max (1+ (current-column))
11153 (1+ col)
11154 (if (> to-col 0)
11155 to-col
11156 (- (abs to-col) tags-l))))
11157 (setq p (point))
11158 (insert (make-string (- ncol (current-column)) ?\ ))
11159 (setq ncol (current-column))
11160 (when indent-tabs-mode (tabify p (point-at-eol)))
11161 (org-move-to-column (min ncol col) t))
11162 (goto-char pos))))
11164 (defun org-set-tags-command (&optional arg just-align)
11165 "Call the set-tags command for the current entry."
11166 (interactive "P")
11167 (if (org-on-heading-p)
11168 (org-set-tags arg just-align)
11169 (save-excursion
11170 (org-back-to-heading t)
11171 (org-set-tags arg just-align))))
11173 (defun org-set-tags (&optional arg just-align)
11174 "Set the tags for the current headline.
11175 With prefix ARG, realign all tags in headings in the current buffer."
11176 (interactive "P")
11177 (let* ((re (concat "^" outline-regexp))
11178 (current (org-get-tags-string))
11179 (col (current-column))
11180 (org-setting-tags t)
11181 table current-tags inherited-tags ; computed below when needed
11182 tags p0 c0 c1 rpl)
11183 (if arg
11184 (save-excursion
11185 (goto-char (point-min))
11186 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11187 (while (re-search-forward re nil t)
11188 (org-set-tags nil t)
11189 (end-of-line 1)))
11190 (message "All tags realigned to column %d" org-tags-column))
11191 (if just-align
11192 (setq tags current)
11193 ;; Get a new set of tags from the user
11194 (save-excursion
11195 (setq table (append org-tag-persistent-alist
11196 (or org-tag-alist (org-get-buffer-tags)))
11197 org-last-tags-completion-table table
11198 current-tags (org-split-string current ":")
11199 inherited-tags (nreverse
11200 (nthcdr (length current-tags)
11201 (nreverse (org-get-tags-at))))
11202 tags
11203 (if (or (eq t org-use-fast-tag-selection)
11204 (and org-use-fast-tag-selection
11205 (delq nil (mapcar 'cdr table))))
11206 (org-fast-tag-selection
11207 current-tags inherited-tags table
11208 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11209 (let ((org-add-colon-after-tag-completion t))
11210 (org-trim
11211 (org-without-partial-completion
11212 (org-icompleting-read "Tags: " 'org-tags-completion-function
11213 nil nil current 'org-tags-history)))))))
11214 (while (string-match "[-+&]+" tags)
11215 ;; No boolean logic, just a list
11216 (setq tags (replace-match ":" t t tags))))
11218 (if org-tags-sort-function
11219 (setq tags (mapconcat 'identity
11220 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11221 org-tags-sort-function) ":")))
11223 (if (string-match "\\`[\t ]*\\'" tags)
11224 (setq tags "")
11225 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11226 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11228 ;; Insert new tags at the correct column
11229 (beginning-of-line 1)
11230 (cond
11231 ((and (equal current "") (equal tags "")))
11232 ((re-search-forward
11233 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11234 (point-at-eol) t)
11235 (if (equal tags "")
11236 (setq rpl "")
11237 (goto-char (match-beginning 0))
11238 (setq c0 (current-column) p0 (point)
11239 c1 (max (1+ c0) (if (> org-tags-column 0)
11240 org-tags-column
11241 (- (- org-tags-column) (length tags))))
11242 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11243 (replace-match rpl t t)
11244 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11245 tags)
11246 (t (error "Tags alignment failed")))
11247 (org-move-to-column col)
11248 (unless just-align
11249 (run-hooks 'org-after-tags-change-hook)))))
11251 (defun org-change-tag-in-region (beg end tag off)
11252 "Add or remove TAG for each entry in the region.
11253 This works in the agenda, and also in an org-mode buffer."
11254 (interactive
11255 (list (region-beginning) (region-end)
11256 (let ((org-last-tags-completion-table
11257 (if (org-mode-p)
11258 (org-get-buffer-tags)
11259 (org-global-tags-completion-table))))
11260 (org-icompleting-read
11261 "Tag: " 'org-tags-completion-function nil nil nil
11262 'org-tags-history))
11263 (progn
11264 (message "[s]et or [r]emove? ")
11265 (equal (read-char-exclusive) ?r))))
11266 (if (fboundp 'deactivate-mark) (deactivate-mark))
11267 (let ((agendap (equal major-mode 'org-agenda-mode))
11268 l1 l2 m buf pos newhead (cnt 0))
11269 (goto-char end)
11270 (setq l2 (1- (org-current-line)))
11271 (goto-char beg)
11272 (setq l1 (org-current-line))
11273 (loop for l from l1 to l2 do
11274 (org-goto-line l)
11275 (setq m (get-text-property (point) 'org-hd-marker))
11276 (when (or (and (org-mode-p) (org-on-heading-p))
11277 (and agendap m))
11278 (setq buf (if agendap (marker-buffer m) (current-buffer))
11279 pos (if agendap m (point)))
11280 (with-current-buffer buf
11281 (save-excursion
11282 (save-restriction
11283 (goto-char pos)
11284 (setq cnt (1+ cnt))
11285 (org-toggle-tag tag (if off 'off 'on))
11286 (setq newhead (org-get-heading)))))
11287 (and agendap (org-agenda-change-all-lines newhead m))))
11288 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11290 (defun org-tags-completion-function (string predicate &optional flag)
11291 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11292 (confirm (lambda (x) (stringp (car x)))))
11293 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11294 (setq s1 (match-string 1 string)
11295 s2 (match-string 2 string))
11296 (setq s1 "" s2 string))
11297 (cond
11298 ((eq flag nil)
11299 ;; try completion
11300 (setq rtn (try-completion s2 ctable confirm))
11301 (if (stringp rtn)
11302 (setq rtn
11303 (concat s1 s2 (substring rtn (length s2))
11304 (if (and org-add-colon-after-tag-completion
11305 (assoc rtn ctable))
11306 ":" ""))))
11307 rtn)
11308 ((eq flag t)
11309 ;; all-completions
11310 (all-completions s2 ctable confirm)
11312 ((eq flag 'lambda)
11313 ;; exact match?
11314 (assoc s2 ctable)))
11317 (defun org-fast-tag-insert (kwd tags face &optional end)
11318 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11319 (insert (format "%-12s" (concat kwd ":"))
11320 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11321 (or end "")))
11323 (defun org-fast-tag-show-exit (flag)
11324 (save-excursion
11325 (org-goto-line 3)
11326 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11327 (replace-match ""))
11328 (when flag
11329 (end-of-line 1)
11330 (org-move-to-column (- (window-width) 19) t)
11331 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11333 (defun org-set-current-tags-overlay (current prefix)
11334 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11335 (if (featurep 'xemacs)
11336 (org-overlay-display org-tags-overlay (concat prefix s)
11337 'secondary-selection)
11338 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11339 (org-overlay-display org-tags-overlay (concat prefix s)))))
11341 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11342 "Fast tag selection with single keys.
11343 CURRENT is the current list of tags in the headline, INHERITED is the
11344 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11345 possibly with grouping information. TODO-TABLE is a similar table with
11346 TODO keywords, should these have keys assigned to them.
11347 If the keys are nil, a-z are automatically assigned.
11348 Returns the new tags string, or nil to not change the current settings."
11349 (let* ((fulltable (append table todo-table))
11350 (maxlen (apply 'max (mapcar
11351 (lambda (x)
11352 (if (stringp (car x)) (string-width (car x)) 0))
11353 fulltable)))
11354 (buf (current-buffer))
11355 (expert (eq org-fast-tag-selection-single-key 'expert))
11356 (buffer-tags nil)
11357 (fwidth (+ maxlen 3 1 3))
11358 (ncol (/ (- (window-width) 4) fwidth))
11359 (i-face 'org-done)
11360 (c-face 'org-todo)
11361 tg cnt e c char c1 c2 ntable tbl rtn
11362 ov-start ov-end ov-prefix
11363 (exit-after-next org-fast-tag-selection-single-key)
11364 (done-keywords org-done-keywords)
11365 groups ingroup)
11366 (save-excursion
11367 (beginning-of-line 1)
11368 (if (looking-at
11369 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11370 (setq ov-start (match-beginning 1)
11371 ov-end (match-end 1)
11372 ov-prefix "")
11373 (setq ov-start (1- (point-at-eol))
11374 ov-end (1+ ov-start))
11375 (skip-chars-forward "^\n\r")
11376 (setq ov-prefix
11377 (concat
11378 (buffer-substring (1- (point)) (point))
11379 (if (> (current-column) org-tags-column)
11381 (make-string (- org-tags-column (current-column)) ?\ ))))))
11382 (org-move-overlay org-tags-overlay ov-start ov-end)
11383 (save-window-excursion
11384 (if expert
11385 (set-buffer (get-buffer-create " *Org tags*"))
11386 (delete-other-windows)
11387 (split-window-vertically)
11388 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11389 (erase-buffer)
11390 (org-set-local 'org-done-keywords done-keywords)
11391 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11392 (org-fast-tag-insert "Current" current c-face "\n\n")
11393 (org-fast-tag-show-exit exit-after-next)
11394 (org-set-current-tags-overlay current ov-prefix)
11395 (setq tbl fulltable char ?a cnt 0)
11396 (while (setq e (pop tbl))
11397 (cond
11398 ((equal e '(:startgroup))
11399 (push '() groups) (setq ingroup t)
11400 (when (not (= cnt 0))
11401 (setq cnt 0)
11402 (insert "\n"))
11403 (insert "{ "))
11404 ((equal e '(:endgroup))
11405 (setq ingroup nil cnt 0)
11406 (insert "}\n"))
11407 ((equal e '(:newline))
11408 (when (not (= cnt 0))
11409 (setq cnt 0)
11410 (insert "\n")
11411 (setq e (car tbl))
11412 (while (equal (car tbl) '(:newline))
11413 (insert "\n")
11414 (setq tbl (cdr tbl)))))
11416 (setq tg (copy-sequence (car e)) c2 nil)
11417 (if (cdr e)
11418 (setq c (cdr e))
11419 ;; automatically assign a character.
11420 (setq c1 (string-to-char
11421 (downcase (substring
11422 tg (if (= (string-to-char tg) ?@) 1 0)))))
11423 (if (or (rassoc c1 ntable) (rassoc c1 table))
11424 (while (or (rassoc char ntable) (rassoc char table))
11425 (setq char (1+ char)))
11426 (setq c2 c1))
11427 (setq c (or c2 char)))
11428 (if ingroup (push tg (car groups)))
11429 (setq tg (org-add-props tg nil 'face
11430 (cond
11431 ((not (assoc tg table))
11432 (org-get-todo-face tg))
11433 ((member tg current) c-face)
11434 ((member tg inherited) i-face)
11435 (t nil))))
11436 (if (and (= cnt 0) (not ingroup)) (insert " "))
11437 (insert "[" c "] " tg (make-string
11438 (- fwidth 4 (length tg)) ?\ ))
11439 (push (cons tg c) ntable)
11440 (when (= (setq cnt (1+ cnt)) ncol)
11441 (insert "\n")
11442 (if ingroup (insert " "))
11443 (setq cnt 0)))))
11444 (setq ntable (nreverse ntable))
11445 (insert "\n")
11446 (goto-char (point-min))
11447 (if (not expert) (org-fit-window-to-buffer))
11448 (setq rtn
11449 (catch 'exit
11450 (while t
11451 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11452 (if groups " [!] no groups" " [!]groups")
11453 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11454 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11455 (cond
11456 ((= c ?\r) (throw 'exit t))
11457 ((= c ?!)
11458 (setq groups (not groups))
11459 (goto-char (point-min))
11460 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11461 ((= c ?\C-c)
11462 (if (not expert)
11463 (org-fast-tag-show-exit
11464 (setq exit-after-next (not exit-after-next)))
11465 (setq expert nil)
11466 (delete-other-windows)
11467 (split-window-vertically)
11468 (org-switch-to-buffer-other-window " *Org tags*")
11469 (org-fit-window-to-buffer)))
11470 ((or (= c ?\C-g)
11471 (and (= c ?q) (not (rassoc c ntable))))
11472 (org-detach-overlay org-tags-overlay)
11473 (setq quit-flag t))
11474 ((= c ?\ )
11475 (setq current nil)
11476 (if exit-after-next (setq exit-after-next 'now)))
11477 ((= c ?\t)
11478 (condition-case nil
11479 (setq tg (org-icompleting-read
11480 "Tag: "
11481 (or buffer-tags
11482 (with-current-buffer buf
11483 (org-get-buffer-tags)))))
11484 (quit (setq tg "")))
11485 (when (string-match "\\S-" tg)
11486 (add-to-list 'buffer-tags (list tg))
11487 (if (member tg current)
11488 (setq current (delete tg current))
11489 (push tg current)))
11490 (if exit-after-next (setq exit-after-next 'now)))
11491 ((setq e (rassoc c todo-table) tg (car e))
11492 (with-current-buffer buf
11493 (save-excursion (org-todo tg)))
11494 (if exit-after-next (setq exit-after-next 'now)))
11495 ((setq e (rassoc c ntable) tg (car e))
11496 (if (member tg current)
11497 (setq current (delete tg current))
11498 (loop for g in groups do
11499 (if (member tg g)
11500 (mapc (lambda (x)
11501 (setq current (delete x current)))
11502 g)))
11503 (push tg current))
11504 (if exit-after-next (setq exit-after-next 'now))))
11506 ;; Create a sorted list
11507 (setq current
11508 (sort current
11509 (lambda (a b)
11510 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11511 (if (eq exit-after-next 'now) (throw 'exit t))
11512 (goto-char (point-min))
11513 (beginning-of-line 2)
11514 (delete-region (point) (point-at-eol))
11515 (org-fast-tag-insert "Current" current c-face)
11516 (org-set-current-tags-overlay current ov-prefix)
11517 (while (re-search-forward
11518 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11519 (setq tg (match-string 1))
11520 (add-text-properties
11521 (match-beginning 1) (match-end 1)
11522 (list 'face
11523 (cond
11524 ((member tg current) c-face)
11525 ((member tg inherited) i-face)
11526 (t (get-text-property (match-beginning 1) 'face))))))
11527 (goto-char (point-min)))))
11528 (org-detach-overlay org-tags-overlay)
11529 (if rtn
11530 (mapconcat 'identity current ":")
11531 nil))))
11533 (defun org-get-tags-string ()
11534 "Get the TAGS string in the current headline."
11535 (unless (org-on-heading-p t)
11536 (error "Not on a heading"))
11537 (save-excursion
11538 (beginning-of-line 1)
11539 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11540 (org-match-string-no-properties 1)
11541 "")))
11543 (defun org-get-tags ()
11544 "Get the list of tags specified in the current headline."
11545 (org-split-string (org-get-tags-string) ":"))
11547 (defun org-get-buffer-tags ()
11548 "Get a table of all tags used in the buffer, for completion."
11549 (let (tags)
11550 (save-excursion
11551 (goto-char (point-min))
11552 (while (re-search-forward
11553 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11554 (when (equal (char-after (point-at-bol 0)) ?*)
11555 (mapc (lambda (x) (add-to-list 'tags x))
11556 (org-split-string (org-match-string-no-properties 1) ":")))))
11557 (mapcar 'list tags)))
11559 ;;;; The mapping API
11561 ;;;###autoload
11562 (defun org-map-entries (func &optional match scope &rest skip)
11563 "Call FUNC at each headline selected by MATCH in SCOPE.
11565 FUNC is a function or a lisp form. The function will be called without
11566 arguments, with the cursor positioned at the beginning of the headline.
11567 The return values of all calls to the function will be collected and
11568 returned as a list.
11570 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11571 does not need to preserve point. After evaluation, the cursor will be
11572 moved to the end of the line (presumably of the headline of the
11573 processed entry) and search continues from there. Under some
11574 circumstances, this may not produce the wanted results. For example,
11575 if you have removed (e.g. archived) the current (sub)tree it could
11576 mean that the next entry will be skipped entirely. In such cases, you
11577 can specify the position from where search should continue by making
11578 FUNC set the variable `org-map-continue-from' to the desired buffer
11579 position.
11581 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11582 Only headlines that are matched by this query will be considered during
11583 the iteration. When MATCH is nil or t, all headlines will be
11584 visited by the iteration.
11586 SCOPE determines the scope of this command. It can be any of:
11588 nil The current buffer, respecting the restriction if any
11589 tree The subtree started with the entry at point
11590 file The current buffer, without restriction
11591 file-with-archives
11592 The current buffer, and any archives associated with it
11593 agenda All agenda files
11594 agenda-with-archives
11595 All agenda files with any archive files associated with them
11596 \(file1 file2 ...)
11597 If this is a list, all files in the list will be scanned
11599 The remaining args are treated as settings for the skipping facilities of
11600 the scanner. The following items can be given here:
11602 archive skip trees with the archive tag.
11603 comment skip trees with the COMMENT keyword
11604 function or Emacs Lisp form:
11605 will be used as value for `org-agenda-skip-function', so whenever
11606 the the function returns t, FUNC will not be called for that
11607 entry and search will continue from the point where the
11608 function leaves it.
11610 If your function needs to retrieve the tags including inherited tags
11611 at the *current* entry, you can use the value of the variable
11612 `org-scanner-tags' which will be much faster than getting the value
11613 with `org-get-tags-at'. If your function gets properties with
11614 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11615 to t around the call to `org-entry-properties' to get the same speedup.
11616 Note that if your function moves around to retrieve tags and properties at
11617 a *different* entry, you cannot use these techniques."
11618 (let* ((org-agenda-archives-mode nil) ; just to make sure
11619 (org-agenda-skip-archived-trees (memq 'archive skip))
11620 (org-agenda-skip-comment-trees (memq 'comment skip))
11621 (org-agenda-skip-function
11622 (car (org-delete-all '(comment archive) skip)))
11623 (org-tags-match-list-sublevels t)
11624 matcher file res
11625 org-todo-keywords-for-agenda
11626 org-done-keywords-for-agenda
11627 org-todo-keyword-alist-for-agenda
11628 org-tag-alist-for-agenda)
11630 (cond
11631 ((eq match t) (setq matcher t))
11632 ((eq match nil) (setq matcher t))
11633 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11635 (save-excursion
11636 (save-restriction
11637 (when (eq scope 'tree)
11638 (org-back-to-heading t)
11639 (org-narrow-to-subtree)
11640 (setq scope nil))
11642 (if (not scope)
11643 (progn
11644 (org-prepare-agenda-buffers
11645 (list (buffer-file-name (current-buffer))))
11646 (setq res (org-scan-tags func matcher)))
11647 ;; Get the right scope
11648 (cond
11649 ((and scope (listp scope) (symbolp (car scope)))
11650 (setq scope (eval scope)))
11651 ((eq scope 'agenda)
11652 (setq scope (org-agenda-files t)))
11653 ((eq scope 'agenda-with-archives)
11654 (setq scope (org-agenda-files t))
11655 (setq scope (org-add-archive-files scope)))
11656 ((eq scope 'file)
11657 (setq scope (list (buffer-file-name))))
11658 ((eq scope 'file-with-archives)
11659 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11660 (org-prepare-agenda-buffers scope)
11661 (while (setq file (pop scope))
11662 (with-current-buffer (org-find-base-buffer-visiting file)
11663 (save-excursion
11664 (save-restriction
11665 (widen)
11666 (goto-char (point-min))
11667 (setq res (append res (org-scan-tags func matcher))))))))))
11668 res))
11670 ;;;; Properties
11672 ;;; Setting and retrieving properties
11674 (defconst org-special-properties
11675 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11676 "TIMESTAMP" "TIMESTAMP_IA")
11677 "The special properties valid in Org-mode.
11679 These are properties that are not defined in the property drawer,
11680 but in some other way.")
11682 (defconst org-default-properties
11683 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11684 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11685 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11686 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11687 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11688 "CLOCK_MODELINE_TOTAL")
11689 "Some properties that are used by Org-mode for various purposes.
11690 Being in this list makes sure that they are offered for completion.")
11692 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11693 "Regular expression matching the first line of a property drawer.")
11695 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11696 "Regular expression matching the first line of a property drawer.")
11698 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11699 "Regular expression matching the first line of a property drawer.")
11701 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11702 "Regular expression matching the first line of a property drawer.")
11704 (defconst org-property-drawer-re
11705 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11706 org-property-end-re "\\)\n?")
11707 "Matches an entire property drawer.")
11709 (defconst org-clock-drawer-re
11710 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11711 org-property-end-re "\\)\n?")
11712 "Matches an entire clock drawer.")
11714 (defun org-property-action ()
11715 "Do an action on properties."
11716 (interactive)
11717 (let (c)
11718 (org-at-property-p)
11719 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11720 (setq c (read-char-exclusive))
11721 (cond
11722 ((equal c ?s)
11723 (call-interactively 'org-set-property))
11724 ((equal c ?d)
11725 (call-interactively 'org-delete-property))
11726 ((equal c ?D)
11727 (call-interactively 'org-delete-property-globally))
11728 ((equal c ?c)
11729 (call-interactively 'org-compute-property-at-point))
11730 (t (error "No such property action %c" c)))))
11732 (defun org-set-effort (&optional value)
11733 "Set the effort property of the current entry.
11734 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
11735 allowed value."
11736 (interactive "P")
11737 (if (equal value 0) (setq value 10))
11738 (let* ((completion-ignore-case t)
11739 (prop org-effort-property)
11740 (cur (org-entry-get nil prop))
11741 (allowed (org-property-get-allowed-values nil prop 'table))
11742 (existing (mapcar 'list (org-property-values prop)))
11743 (val (cond
11744 ((stringp value) value)
11745 ((and allowed (integerp value))
11746 (or (car (nth (1- value) allowed))
11747 (car (org-last allowed))))
11748 (allowed
11749 (org-completing-read "Value: " allowed nil 'req-match))
11751 (let (org-completion-use-ido org-completion-use-iswitchb)
11752 (org-completing-read
11753 (concat "Value " (if (and cur (string-match "\\S-" cur))
11754 (concat "[" cur "]") "")
11755 ": ")
11756 existing nil nil "" nil cur))))))
11757 (unless (equal (org-entry-get nil prop) val)
11758 (org-entry-put nil prop val))
11759 (message "%s is now %s" prop val)))
11761 (defun org-at-property-p ()
11762 "Is the cursor in a property line?"
11763 ;; FIXME: Does not check if we are actually in the drawer.
11764 ;; FIXME: also returns true on any drawers.....
11765 ;; This is used by C-c C-c for property action.
11766 (save-excursion
11767 (beginning-of-line 1)
11768 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11770 (defun org-get-property-block (&optional beg end force)
11771 "Return the (beg . end) range of the body of the property drawer.
11772 BEG and END can be beginning and end of subtree, if not given
11773 they will be found.
11774 If the drawer does not exist and FORCE is non-nil, create the drawer."
11775 (catch 'exit
11776 (save-excursion
11777 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11778 (end (or end (progn (outline-next-heading) (point)))))
11779 (goto-char beg)
11780 (if (re-search-forward org-property-start-re end t)
11781 (setq beg (1+ (match-end 0)))
11782 (if force
11783 (save-excursion
11784 (org-insert-property-drawer)
11785 (setq end (progn (outline-next-heading) (point))))
11786 (throw 'exit nil))
11787 (goto-char beg)
11788 (if (re-search-forward org-property-start-re end t)
11789 (setq beg (1+ (match-end 0)))))
11790 (if (re-search-forward org-property-end-re end t)
11791 (setq end (match-beginning 0))
11792 (or force (throw 'exit nil))
11793 (goto-char beg)
11794 (setq end beg)
11795 (org-indent-line-function)
11796 (insert ":END:\n"))
11797 (cons beg end)))))
11799 (defun org-entry-properties (&optional pom which)
11800 "Get all properties of the entry at point-or-marker POM.
11801 This includes the TODO keyword, the tags, time strings for deadline,
11802 scheduled, and clocking, and any additional properties defined in the
11803 entry. The return value is an alist, keys may occur multiple times
11804 if the property key was used several times.
11805 POM may also be nil, in which case the current entry is used.
11806 If WHICH is nil or `all', get all properties. If WHICH is
11807 `special' or `standard', only get that subclass."
11808 (setq which (or which 'all))
11809 (org-with-point-at pom
11810 (let ((clockstr (substring org-clock-string 0 -1))
11811 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11812 beg end range props sum-props key value string clocksum)
11813 (save-excursion
11814 (when (condition-case nil
11815 (and (org-mode-p) (org-back-to-heading t))
11816 (error nil))
11817 (setq beg (point))
11818 (setq sum-props (get-text-property (point) 'org-summaries))
11819 (setq clocksum (get-text-property (point) :org-clock-minutes))
11820 (outline-next-heading)
11821 (setq end (point))
11822 (when (memq which '(all special))
11823 ;; Get the special properties, like TODO and tags
11824 (goto-char beg)
11825 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11826 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11827 (when (looking-at org-priority-regexp)
11828 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11829 (when (and (setq value (org-get-tags-string))
11830 (string-match "\\S-" value))
11831 (push (cons "TAGS" value) props))
11832 (when (setq value (org-get-tags-at))
11833 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11834 props))
11835 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11836 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11837 string (if (equal key clockstr)
11838 (org-no-properties
11839 (org-trim
11840 (buffer-substring
11841 (match-beginning 3) (goto-char (point-at-eol)))))
11842 (substring (org-match-string-no-properties 3) 1 -1)))
11843 (unless key
11844 (if (= (char-after (match-beginning 3)) ?\[)
11845 (setq key "TIMESTAMP_IA")
11846 (setq key "TIMESTAMP")))
11847 (when (or (equal key clockstr) (not (assoc key props)))
11848 (push (cons key string) props)))
11852 (when (memq which '(all standard))
11853 ;; Get the standard properties, like :PROP: ...
11854 (setq range (org-get-property-block beg end))
11855 (when range
11856 (goto-char (car range))
11857 (while (re-search-forward
11858 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11859 (cdr range) t)
11860 (setq key (org-match-string-no-properties 1)
11861 value (org-trim (or (org-match-string-no-properties 2) "")))
11862 (unless (member key excluded)
11863 (push (cons key (or value "")) props)))))
11864 (if clocksum
11865 (push (cons "CLOCKSUM"
11866 (org-columns-number-to-string (/ (float clocksum) 60.)
11867 'add_times))
11868 props))
11869 (unless (assoc "CATEGORY" props)
11870 (setq value (or (org-get-category)
11871 (progn (org-refresh-category-properties)
11872 (org-get-category))))
11873 (push (cons "CATEGORY" value) props))
11874 (append sum-props (nreverse props)))))))
11876 (defun org-entry-get (pom property &optional inherit)
11877 "Get value of PROPERTY for entry at point-or-marker POM.
11878 If INHERIT is non-nil and the entry does not have the property,
11879 then also check higher levels of the hierarchy.
11880 If INHERIT is the symbol `selective', use inheritance only if the setting
11881 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11882 If the property is present but empty, the return value is the empty string.
11883 If the property is not present at all, nil is returned."
11884 (org-with-point-at pom
11885 (if (and inherit (if (eq inherit 'selective)
11886 (org-property-inherit-p property)
11888 (org-entry-get-with-inheritance property)
11889 (if (member property org-special-properties)
11890 ;; We need a special property. Use brute force, get all properties.
11891 (cdr (assoc property (org-entry-properties nil 'special)))
11892 (let ((range (org-get-property-block)))
11893 (if (and range
11894 (goto-char (car range))
11895 (re-search-forward
11896 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11897 (cdr range) t))
11898 ;; Found the property, return it.
11899 (if (match-end 1)
11900 (org-match-string-no-properties 1)
11901 "")))))))
11903 (defun org-property-or-variable-value (var &optional inherit)
11904 "Check if there is a property fixing the value of VAR.
11905 If yes, return this value. If not, return the current value of the variable."
11906 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11907 (if (and prop (stringp prop) (string-match "\\S-" prop))
11908 (read prop)
11909 (symbol-value var))))
11911 (defun org-entry-delete (pom property)
11912 "Delete the property PROPERTY from entry at point-or-marker POM."
11913 (org-with-point-at pom
11914 (if (member property org-special-properties)
11915 nil ; cannot delete these properties.
11916 (let ((range (org-get-property-block)))
11917 (if (and range
11918 (goto-char (car range))
11919 (re-search-forward
11920 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11921 (cdr range) t))
11922 (progn
11923 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11925 nil)))))
11927 ;; Multi-values properties are properties that contain multiple values
11928 ;; These values are assumed to be single words, separated by whitespace.
11929 (defun org-entry-add-to-multivalued-property (pom property value)
11930 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11931 (let* ((old (org-entry-get pom property))
11932 (values (and old (org-split-string old "[ \t]"))))
11933 (setq value (org-entry-protect-space value))
11934 (unless (member value values)
11935 (setq values (cons value values))
11936 (org-entry-put pom property
11937 (mapconcat 'identity values " ")))))
11939 (defun org-entry-remove-from-multivalued-property (pom property value)
11940 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11941 (let* ((old (org-entry-get pom property))
11942 (values (and old (org-split-string old "[ \t]"))))
11943 (setq value (org-entry-protect-space value))
11944 (when (member value values)
11945 (setq values (delete value values))
11946 (org-entry-put pom property
11947 (mapconcat 'identity values " ")))))
11949 (defun org-entry-member-in-multivalued-property (pom property value)
11950 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11951 (let* ((old (org-entry-get pom property))
11952 (values (and old (org-split-string old "[ \t]"))))
11953 (setq value (org-entry-protect-space value))
11954 (member value values)))
11956 (defun org-entry-get-multivalued-property (pom property)
11957 "Return a list of values in a multivalued property."
11958 (let* ((value (org-entry-get pom property))
11959 (values (and value (org-split-string value "[ \t]"))))
11960 (mapcar 'org-entry-restore-space values)))
11962 (defun org-entry-put-multivalued-property (pom property &rest values)
11963 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11964 VALUES should be a list of strings. Spaces will be protected."
11965 (org-entry-put pom property
11966 (mapconcat 'org-entry-protect-space values " "))
11967 (let* ((value (org-entry-get pom property))
11968 (values (and value (org-split-string value "[ \t]"))))
11969 (mapcar 'org-entry-restore-space values)))
11971 (defun org-entry-protect-space (s)
11972 "Protect spaces and newline in string S."
11973 (while (string-match " " s)
11974 (setq s (replace-match "%20" t t s)))
11975 (while (string-match "\n" s)
11976 (setq s (replace-match "%0A" t t s)))
11979 (defun org-entry-restore-space (s)
11980 "Restore spaces and newline in string S."
11981 (while (string-match "%20" s)
11982 (setq s (replace-match " " t t s)))
11983 (while (string-match "%0A" s)
11984 (setq s (replace-match "\n" t t s)))
11987 (defvar org-entry-property-inherited-from (make-marker)
11988 "Marker pointing to the entry from where a property was inherited.
11989 Each call to `org-entry-get-with-inheritance' will set this marker to the
11990 location of the entry where the inheritance search matched. If there was
11991 no match, the marker will point nowhere.
11992 Note that also `org-entry-get' calls this function, if the INHERIT flag
11993 is set.")
11995 (defun org-entry-get-with-inheritance (property)
11996 "Get entry property, and search higher levels if not present."
11997 (move-marker org-entry-property-inherited-from nil)
11998 (let (tmp)
11999 (save-excursion
12000 (save-restriction
12001 (widen)
12002 (catch 'ex
12003 (while t
12004 (when (setq tmp (org-entry-get nil property))
12005 (org-back-to-heading t)
12006 (move-marker org-entry-property-inherited-from (point))
12007 (throw 'ex tmp))
12008 (or (org-up-heading-safe) (throw 'ex nil)))))
12009 (or tmp
12010 (cdr (assoc property org-file-properties))
12011 (cdr (assoc property org-global-properties))
12012 (cdr (assoc property org-global-properties-fixed))))))
12014 (defun org-entry-put (pom property value)
12015 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12016 (org-with-point-at pom
12017 (org-back-to-heading t)
12018 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12019 range)
12020 (cond
12021 ((equal property "TODO")
12022 (when (and (stringp value) (string-match "\\S-" value)
12023 (not (member value org-todo-keywords-1)))
12024 (error "\"%s\" is not a valid TODO state" value))
12025 (if (or (not value)
12026 (not (string-match "\\S-" value)))
12027 (setq value 'none))
12028 (org-todo value)
12029 (org-set-tags nil 'align))
12030 ((equal property "PRIORITY")
12031 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12032 (string-to-char value) ?\ ))
12033 (org-set-tags nil 'align))
12034 ((equal property "SCHEDULED")
12035 (if (re-search-forward org-scheduled-time-regexp end t)
12036 (cond
12037 ((eq value 'earlier) (org-timestamp-change -1 'day))
12038 ((eq value 'later) (org-timestamp-change 1 'day))
12039 (t (call-interactively 'org-schedule)))
12040 (call-interactively 'org-schedule)))
12041 ((equal property "DEADLINE")
12042 (if (re-search-forward org-deadline-time-regexp end t)
12043 (cond
12044 ((eq value 'earlier) (org-timestamp-change -1 'day))
12045 ((eq value 'later) (org-timestamp-change 1 'day))
12046 (t (call-interactively 'org-deadline)))
12047 (call-interactively 'org-deadline)))
12048 ((member property org-special-properties)
12049 (error "The %s property can not yet be set with `org-entry-put'"
12050 property))
12051 (t ; a non-special property
12052 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12053 (setq range (org-get-property-block beg end 'force))
12054 (goto-char (car range))
12055 (if (re-search-forward
12056 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12057 (progn
12058 (delete-region (match-beginning 1) (match-end 1))
12059 (goto-char (match-beginning 1)))
12060 (goto-char (cdr range))
12061 (insert "\n")
12062 (backward-char 1)
12063 (org-indent-line-function)
12064 (insert ":" property ":"))
12065 (and value (insert " " value))
12066 (org-indent-line-function)))))))
12068 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12069 "Get all property keys in the current buffer.
12070 With INCLUDE-SPECIALS, also list the special properties that reflect things
12071 like tags and TODO state.
12072 With INCLUDE-DEFAULTS, also include properties that has special meaning
12073 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12074 With INCLUDE-COLUMNS, also include property names given in COLUMN
12075 formats in the current buffer."
12076 (let (rtn range cfmt s p)
12077 (save-excursion
12078 (save-restriction
12079 (widen)
12080 (goto-char (point-min))
12081 (while (re-search-forward org-property-start-re nil t)
12082 (setq range (org-get-property-block))
12083 (goto-char (car range))
12084 (while (re-search-forward
12085 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12086 (cdr range) t)
12087 (add-to-list 'rtn (org-match-string-no-properties 1)))
12088 (outline-next-heading))))
12090 (when include-specials
12091 (setq rtn (append org-special-properties rtn)))
12093 (when include-defaults
12094 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12095 (add-to-list 'rtn org-effort-property))
12097 (when include-columns
12098 (save-excursion
12099 (save-restriction
12100 (widen)
12101 (goto-char (point-min))
12102 (while (re-search-forward
12103 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12104 nil t)
12105 (setq cfmt (match-string 2) s 0)
12106 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12107 cfmt s)
12108 (setq s (match-end 0)
12109 p (match-string 1 cfmt))
12110 (unless (or (equal p "ITEM")
12111 (member p org-special-properties))
12112 (add-to-list 'rtn (match-string 1 cfmt))))))))
12114 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12116 (defun org-property-values (key)
12117 "Return a list of all values of property KEY."
12118 (save-excursion
12119 (save-restriction
12120 (widen)
12121 (goto-char (point-min))
12122 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12123 values)
12124 (while (re-search-forward re nil t)
12125 (add-to-list 'values (org-trim (match-string 1))))
12126 (delete "" values)))))
12128 (defun org-insert-property-drawer ()
12129 "Insert a property drawer into the current entry."
12130 (interactive)
12131 (org-back-to-heading t)
12132 (looking-at outline-regexp)
12133 (let ((indent (if org-adapt-indentation
12134 (- (match-end 0)(match-beginning 0))
12136 (beg (point))
12137 (re (concat "^[ \t]*" org-keyword-time-regexp))
12138 end hiddenp)
12139 (outline-next-heading)
12140 (setq end (point))
12141 (goto-char beg)
12142 (while (re-search-forward re end t))
12143 (setq hiddenp (org-invisible-p))
12144 (end-of-line 1)
12145 (and (equal (char-after) ?\n) (forward-char 1))
12146 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12147 (if (member (match-string 1) '("CLOCK:" ":END:"))
12148 ;; just skip this line
12149 (beginning-of-line 2)
12150 ;; Drawer start, find the end
12151 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12152 (beginning-of-line 1)))
12153 (org-skip-over-state-notes)
12154 (skip-chars-backward " \t\n\r")
12155 (if (eq (char-before) ?*) (forward-char 1))
12156 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12157 (beginning-of-line 0)
12158 (org-indent-to-column indent)
12159 (beginning-of-line 2)
12160 (org-indent-to-column indent)
12161 (beginning-of-line 0)
12162 (if hiddenp
12163 (save-excursion
12164 (org-back-to-heading t)
12165 (hide-entry))
12166 (org-flag-drawer t))))
12168 (defun org-set-property (property value)
12169 "In the current entry, set PROPERTY to VALUE.
12170 When called interactively, this will prompt for a property name, offering
12171 completion on existing and default properties. And then it will prompt
12172 for a value, offering completion either on allowed values (via an inherited
12173 xxx_ALL property) or on existing values in other instances of this property
12174 in the current file."
12175 (interactive
12176 (let* ((completion-ignore-case t)
12177 (keys (org-buffer-property-keys nil t t))
12178 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12179 (prop (if (member prop0 keys)
12180 prop0
12181 (or (cdr (assoc (downcase prop0)
12182 (mapcar (lambda (x) (cons (downcase x) x))
12183 keys)))
12184 prop0)))
12185 (cur (org-entry-get nil prop))
12186 (allowed (org-property-get-allowed-values nil prop 'table))
12187 (existing (mapcar 'list (org-property-values prop)))
12188 (val (if allowed
12189 (org-completing-read "Value: " allowed nil 'req-match)
12190 (let (org-completion-use-ido org-completion-use-iswitchb)
12191 (org-completing-read
12192 (concat "Value " (if (and cur (string-match "\\S-" cur))
12193 (concat "[" cur "]") "")
12194 ": ")
12195 existing nil nil "" nil cur)))))
12196 (list prop (if (equal val "") cur val))))
12197 (unless (equal (org-entry-get nil property) value)
12198 (org-entry-put nil property value)))
12200 (defun org-delete-property (property)
12201 "In the current entry, delete PROPERTY."
12202 (interactive
12203 (let* ((completion-ignore-case t)
12204 (prop (org-icompleting-read
12205 "Property: " (org-entry-properties nil 'standard))))
12206 (list prop)))
12207 (message "Property %s %s" property
12208 (if (org-entry-delete nil property)
12209 "deleted"
12210 "was not present in the entry")))
12212 (defun org-delete-property-globally (property)
12213 "Remove PROPERTY globally, from all entries."
12214 (interactive
12215 (let* ((completion-ignore-case t)
12216 (prop (org-icompleting-read
12217 "Globally remove property: "
12218 (mapcar 'list (org-buffer-property-keys)))))
12219 (list prop)))
12220 (save-excursion
12221 (save-restriction
12222 (widen)
12223 (goto-char (point-min))
12224 (let ((cnt 0))
12225 (while (re-search-forward
12226 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12227 nil t)
12228 (setq cnt (1+ cnt))
12229 (replace-match ""))
12230 (message "Property \"%s\" removed from %d entries" property cnt)))))
12232 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12234 (defun org-compute-property-at-point ()
12235 "Compute the property at point.
12236 This looks for an enclosing column format, extracts the operator and
12237 then applies it to the property in the column format's scope."
12238 (interactive)
12239 (unless (org-at-property-p)
12240 (error "Not at a property"))
12241 (let ((prop (org-match-string-no-properties 2)))
12242 (org-columns-get-format-and-top-level)
12243 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12244 (error "No operator defined for property %s" prop))
12245 (org-columns-compute prop)))
12247 (defun org-property-get-allowed-values (pom property &optional table)
12248 "Get allowed values for the property PROPERTY.
12249 When TABLE is non-nil, return an alist that can directly be used for
12250 completion."
12251 (let (vals)
12252 (cond
12253 ((equal property "TODO")
12254 (setq vals (org-with-point-at pom
12255 (append org-todo-keywords-1 '("")))))
12256 ((equal property "PRIORITY")
12257 (let ((n org-lowest-priority))
12258 (while (>= n org-highest-priority)
12259 (push (char-to-string n) vals)
12260 (setq n (1- n)))))
12261 ((member property org-special-properties))
12263 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12265 (when (and vals (string-match "\\S-" vals))
12266 (setq vals (car (read-from-string (concat "(" vals ")"))))
12267 (setq vals (mapcar (lambda (x)
12268 (cond ((stringp x) x)
12269 ((numberp x) (number-to-string x))
12270 ((symbolp x) (symbol-name x))
12271 (t "???")))
12272 vals)))))
12273 (if table (mapcar 'list vals) vals)))
12275 (defun org-property-previous-allowed-value (&optional previous)
12276 "Switch to the next allowed value for this property."
12277 (interactive)
12278 (org-property-next-allowed-value t))
12280 (defun org-property-next-allowed-value (&optional previous)
12281 "Switch to the next allowed value for this property."
12282 (interactive)
12283 (unless (org-at-property-p)
12284 (error "Not at a property"))
12285 (let* ((key (match-string 2))
12286 (value (match-string 3))
12287 (allowed (or (org-property-get-allowed-values (point) key)
12288 (and (member value '("[ ]" "[-]" "[X]"))
12289 '("[ ]" "[X]"))))
12290 nval)
12291 (unless allowed
12292 (error "Allowed values for this property have not been defined"))
12293 (if previous (setq allowed (reverse allowed)))
12294 (if (member value allowed)
12295 (setq nval (car (cdr (member value allowed)))))
12296 (setq nval (or nval (car allowed)))
12297 (if (equal nval value)
12298 (error "Only one allowed value for this property"))
12299 (org-at-property-p)
12300 (replace-match (concat " :" key ": " nval) t t)
12301 (org-indent-line-function)
12302 (beginning-of-line 1)
12303 (skip-chars-forward " \t")))
12305 (defun org-find-entry-with-id (ident)
12306 "Locate the entry that contains the ID property with exact value IDENT.
12307 IDENT can be a string, a symbol or a number, this function will search for
12308 the string representation of it.
12309 Return the position where this entry starts, or nil if there is no such entry."
12310 (interactive "sID: ")
12311 (let ((id (cond
12312 ((stringp ident) ident)
12313 ((symbol-name ident) (symbol-name ident))
12314 ((numberp ident) (number-to-string ident))
12315 (t (error "IDENT %s must be a string, symbol or number" ident))))
12316 (case-fold-search nil))
12317 (save-excursion
12318 (save-restriction
12319 (widen)
12320 (goto-char (point-min))
12321 (when (re-search-forward
12322 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12323 nil t)
12324 (org-back-to-heading t)
12325 (point))))))
12327 ;;;; Timestamps
12329 (defvar org-last-changed-timestamp nil)
12330 (defvar org-last-inserted-timestamp nil
12331 "The last time stamp inserted with `org-insert-time-stamp'.")
12332 (defvar org-time-was-given) ; dynamically scoped parameter
12333 (defvar org-end-time-was-given) ; dynamically scoped parameter
12334 (defvar org-ts-what) ; dynamically scoped parameter
12336 (defun org-time-stamp (arg &optional inactive)
12337 "Prompt for a date/time and insert a time stamp.
12338 If the user specifies a time like HH:MM, or if this command is called
12339 with a prefix argument, the time stamp will contain date and time.
12340 Otherwise, only the date will be included. All parts of a date not
12341 specified by the user will be filled in from the current date/time.
12342 So if you press just return without typing anything, the time stamp
12343 will represent the current date/time. If there is already a timestamp
12344 at the cursor, it will be modified."
12345 (interactive "P")
12346 (let* ((ts nil)
12347 (default-time
12348 ;; Default time is either today, or, when entering a range,
12349 ;; the range start.
12350 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12351 (save-excursion
12352 (re-search-backward
12353 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12354 (- (point) 20) t)))
12355 (apply 'encode-time (org-parse-time-string (match-string 1)))
12356 (current-time)))
12357 (default-input (and ts (org-get-compact-tod ts)))
12358 org-time-was-given org-end-time-was-given time)
12359 (cond
12360 ((and (org-at-timestamp-p t)
12361 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12362 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12363 (insert "--")
12364 (setq time (let ((this-command this-command))
12365 (org-read-date arg 'totime nil nil
12366 default-time default-input)))
12367 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12368 ((org-at-timestamp-p t)
12369 (setq time (let ((this-command this-command))
12370 (org-read-date arg 'totime nil nil default-time default-input)))
12371 (when (org-at-timestamp-p t) ; just to get the match data
12372 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12373 (replace-match "")
12374 (setq org-last-changed-timestamp
12375 (org-insert-time-stamp
12376 time (or org-time-was-given arg)
12377 inactive nil nil (list org-end-time-was-given))))
12378 (message "Timestamp updated"))
12380 (setq time (let ((this-command this-command))
12381 (org-read-date arg 'totime nil nil default-time default-input)))
12382 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12383 nil nil (list org-end-time-was-given))))))
12385 ;; FIXME: can we use this for something else, like computing time differences?
12386 (defun org-get-compact-tod (s)
12387 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12388 (let* ((t1 (match-string 1 s))
12389 (h1 (string-to-number (match-string 2 s)))
12390 (m1 (string-to-number (match-string 3 s)))
12391 (t2 (and (match-end 4) (match-string 5 s)))
12392 (h2 (and t2 (string-to-number (match-string 6 s))))
12393 (m2 (and t2 (string-to-number (match-string 7 s))))
12394 dh dm)
12395 (if (not t2)
12397 (setq dh (- h2 h1) dm (- m2 m1))
12398 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12399 (concat t1 "+" (number-to-string dh)
12400 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12402 (defun org-time-stamp-inactive (&optional arg)
12403 "Insert an inactive time stamp.
12404 An inactive time stamp is enclosed in square brackets instead of angle
12405 brackets. It is inactive in the sense that it does not trigger agenda entries,
12406 does not link to the calendar and cannot be changed with the S-cursor keys.
12407 So these are more for recording a certain time/date."
12408 (interactive "P")
12409 (org-time-stamp arg 'inactive))
12411 (defvar org-date-ovl (org-make-overlay 1 1))
12412 (org-overlay-put org-date-ovl 'face 'org-warning)
12413 (org-detach-overlay org-date-ovl)
12415 (defvar org-ans1) ; dynamically scoped parameter
12416 (defvar org-ans2) ; dynamically scoped parameter
12418 (defvar org-plain-time-of-day-regexp) ; defined below
12420 (defvar org-overriding-default-time nil) ; dynamically scoped
12421 (defvar org-read-date-overlay nil)
12422 (defvar org-dcst nil) ; dynamically scoped
12423 (defvar org-read-date-history nil)
12424 (defvar org-read-date-final-answer nil)
12426 (defun org-read-date (&optional with-time to-time from-string prompt
12427 default-time default-input)
12428 "Read a date, possibly a time, and make things smooth for the user.
12429 The prompt will suggest to enter an ISO date, but you can also enter anything
12430 which will at least partially be understood by `parse-time-string'.
12431 Unrecognized parts of the date will default to the current day, month, year,
12432 hour and minute. If this command is called to replace a timestamp at point,
12433 of to enter the second timestamp of a range, the default time is taken from the
12434 existing stamp. For example,
12435 3-2-5 --> 2003-02-05
12436 feb 15 --> currentyear-02-15
12437 sep 12 9 --> 2009-09-12
12438 12:45 --> today 12:45
12439 22 sept 0:34 --> currentyear-09-22 0:34
12440 12 --> currentyear-currentmonth-12
12441 Fri --> nearest Friday (today or later)
12442 etc.
12444 Furthermore you can specify a relative date by giving, as the *first* thing
12445 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12446 change in days weeks, months, years.
12447 With a single plus or minus, the date is relative to today. With a double
12448 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12449 +4d --> four days from today
12450 +4 --> same as above
12451 +2w --> two weeks from today
12452 ++5 --> five days from default date
12454 The function understands only English month and weekday abbreviations,
12455 but this can be configured with the variables `parse-time-months' and
12456 `parse-time-weekdays'.
12458 While prompting, a calendar is popped up - you can also select the
12459 date with the mouse (button 1). The calendar shows a period of three
12460 months. To scroll it to other months, use the keys `>' and `<'.
12461 If you don't like the calendar, turn it off with
12462 \(setq org-read-date-popup-calendar nil)
12464 With optional argument TO-TIME, the date will immediately be converted
12465 to an internal time.
12466 With an optional argument WITH-TIME, the prompt will suggest to also
12467 insert a time. Note that when WITH-TIME is not set, you can still
12468 enter a time, and this function will inform the calling routine about
12469 this change. The calling routine may then choose to change the format
12470 used to insert the time stamp into the buffer to include the time.
12471 With optional argument FROM-STRING, read from this string instead from
12472 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12473 the time/date that is used for everything that is not specified by the
12474 user."
12475 (require 'parse-time)
12476 (let* ((org-time-stamp-rounding-minutes
12477 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12478 (org-dcst org-display-custom-times)
12479 (ct (org-current-time))
12480 (def (or org-overriding-default-time default-time ct))
12481 (defdecode (decode-time def))
12482 (dummy (progn
12483 (when (< (nth 2 defdecode) org-extend-today-until)
12484 (setcar (nthcdr 2 defdecode) -1)
12485 (setcar (nthcdr 1 defdecode) 59)
12486 (setq def (apply 'encode-time defdecode)
12487 defdecode (decode-time def)))))
12488 (calendar-frame-setup nil)
12489 (calendar-move-hook nil)
12490 (calendar-view-diary-initially-flag nil)
12491 (view-diary-entries-initially nil)
12492 (calendar-view-holidays-initially-flag nil)
12493 (view-calendar-holidays-initially nil)
12494 (timestr (format-time-string
12495 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12496 (prompt (concat (if prompt (concat prompt " ") "")
12497 (format "Date+time [%s]: " timestr)))
12498 ans (org-ans0 "") org-ans1 org-ans2 final)
12500 (cond
12501 (from-string (setq ans from-string))
12502 (org-read-date-popup-calendar
12503 (save-excursion
12504 (save-window-excursion
12505 (calendar)
12506 (calendar-forward-day (- (time-to-days def)
12507 (calendar-absolute-from-gregorian
12508 (calendar-current-date))))
12509 (org-eval-in-calendar nil t)
12510 (let* ((old-map (current-local-map))
12511 (map (copy-keymap calendar-mode-map))
12512 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12513 (org-defkey map (kbd "RET") 'org-calendar-select)
12514 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12515 'org-calendar-select-mouse)
12516 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12517 'org-calendar-select-mouse)
12518 (org-defkey minibuffer-local-map [(meta shift left)]
12519 (lambda () (interactive)
12520 (org-eval-in-calendar '(calendar-backward-month 1))))
12521 (org-defkey minibuffer-local-map [(meta shift right)]
12522 (lambda () (interactive)
12523 (org-eval-in-calendar '(calendar-forward-month 1))))
12524 (org-defkey minibuffer-local-map [(meta shift up)]
12525 (lambda () (interactive)
12526 (org-eval-in-calendar '(calendar-backward-year 1))))
12527 (org-defkey minibuffer-local-map [(meta shift down)]
12528 (lambda () (interactive)
12529 (org-eval-in-calendar '(calendar-forward-year 1))))
12530 (org-defkey minibuffer-local-map [?\e (shift left)]
12531 (lambda () (interactive)
12532 (org-eval-in-calendar '(calendar-backward-month 1))))
12533 (org-defkey minibuffer-local-map [?\e (shift right)]
12534 (lambda () (interactive)
12535 (org-eval-in-calendar '(calendar-forward-month 1))))
12536 (org-defkey minibuffer-local-map [?\e (shift up)]
12537 (lambda () (interactive)
12538 (org-eval-in-calendar '(calendar-backward-year 1))))
12539 (org-defkey minibuffer-local-map [?\e (shift down)]
12540 (lambda () (interactive)
12541 (org-eval-in-calendar '(calendar-forward-year 1))))
12542 (org-defkey minibuffer-local-map [(shift up)]
12543 (lambda () (interactive)
12544 (org-eval-in-calendar '(calendar-backward-week 1))))
12545 (org-defkey minibuffer-local-map [(shift down)]
12546 (lambda () (interactive)
12547 (org-eval-in-calendar '(calendar-forward-week 1))))
12548 (org-defkey minibuffer-local-map [(shift left)]
12549 (lambda () (interactive)
12550 (org-eval-in-calendar '(calendar-backward-day 1))))
12551 (org-defkey minibuffer-local-map [(shift right)]
12552 (lambda () (interactive)
12553 (org-eval-in-calendar '(calendar-forward-day 1))))
12554 (org-defkey minibuffer-local-map ">"
12555 (lambda () (interactive)
12556 (org-eval-in-calendar '(scroll-calendar-left 1))))
12557 (org-defkey minibuffer-local-map "<"
12558 (lambda () (interactive)
12559 (org-eval-in-calendar '(scroll-calendar-right 1))))
12560 (run-hooks 'org-read-date-minibuffer-setup-hook)
12561 (unwind-protect
12562 (progn
12563 (use-local-map map)
12564 (add-hook 'post-command-hook 'org-read-date-display)
12565 (setq org-ans0 (read-string prompt default-input
12566 'org-read-date-history nil))
12567 ;; org-ans0: from prompt
12568 ;; org-ans1: from mouse click
12569 ;; org-ans2: from calendar motion
12570 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12571 (remove-hook 'post-command-hook 'org-read-date-display)
12572 (use-local-map old-map)
12573 (when org-read-date-overlay
12574 (org-delete-overlay org-read-date-overlay)
12575 (setq org-read-date-overlay nil)))))))
12577 (t ; Naked prompt only
12578 (unwind-protect
12579 (setq ans (read-string prompt default-input
12580 'org-read-date-history timestr))
12581 (when org-read-date-overlay
12582 (org-delete-overlay org-read-date-overlay)
12583 (setq org-read-date-overlay nil)))))
12585 (setq final (org-read-date-analyze ans def defdecode))
12586 (setq org-read-date-final-answer ans)
12588 (if to-time
12589 (apply 'encode-time final)
12590 (if (and (boundp 'org-time-was-given) org-time-was-given)
12591 (format "%04d-%02d-%02d %02d:%02d"
12592 (nth 5 final) (nth 4 final) (nth 3 final)
12593 (nth 2 final) (nth 1 final))
12594 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12596 (defvar def)
12597 (defvar defdecode)
12598 (defvar with-time)
12599 (defun org-read-date-display ()
12600 "Display the current date prompt interpretation in the minibuffer."
12601 (when org-read-date-display-live
12602 (when org-read-date-overlay
12603 (org-delete-overlay org-read-date-overlay))
12604 (let ((p (point)))
12605 (end-of-line 1)
12606 (while (not (equal (buffer-substring
12607 (max (point-min) (- (point) 4)) (point))
12608 " "))
12609 (insert " "))
12610 (goto-char p))
12611 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12612 " " (or org-ans1 org-ans2)))
12613 (org-end-time-was-given nil)
12614 (f (org-read-date-analyze ans def defdecode))
12615 (fmts (if org-dcst
12616 org-time-stamp-custom-formats
12617 org-time-stamp-formats))
12618 (fmt (if (or with-time
12619 (and (boundp 'org-time-was-given) org-time-was-given))
12620 (cdr fmts)
12621 (car fmts)))
12622 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12623 (when (and org-end-time-was-given
12624 (string-match org-plain-time-of-day-regexp txt))
12625 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12626 org-end-time-was-given
12627 (substring txt (match-end 0)))))
12628 (setq org-read-date-overlay
12629 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12630 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12632 (defun org-read-date-analyze (ans def defdecode)
12633 "Analyse the combined answer of the date prompt."
12634 ;; FIXME: cleanup and comment
12635 (let (delta deltan deltaw deltadef year month day
12636 hour minute second wday pm h2 m2 tl wday1
12637 iso-year iso-weekday iso-week iso-year iso-date)
12639 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12640 (setq ans "+0"))
12642 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12643 (setq ans (replace-match "" t t ans)
12644 deltan (car delta)
12645 deltaw (nth 1 delta)
12646 deltadef (nth 2 delta)))
12648 ;; Check if there is an iso week date in there
12649 ;; If yes, sore the info and postpone interpreting it until the rest
12650 ;; of the parsing is done
12651 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12652 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12653 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12654 iso-week (string-to-number (match-string 2 ans)))
12655 (setq ans (replace-match "" t t ans)))
12657 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12658 (when (string-match
12659 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12660 (setq year (if (match-end 2)
12661 (string-to-number (match-string 2 ans))
12662 (string-to-number (format-time-string "%Y")))
12663 month (string-to-number (match-string 3 ans))
12664 day (string-to-number (match-string 4 ans)))
12665 (if (< year 100) (setq year (+ 2000 year)))
12666 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12667 t nil ans)))
12668 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12669 ;; If there is a time with am/pm, and *no* time without it, we convert
12670 ;; so that matching will be successful.
12671 (loop for i from 1 to 2 do ; twice, for end time as well
12672 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12673 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12674 (setq hour (string-to-number (match-string 1 ans))
12675 minute (if (match-end 3)
12676 (string-to-number (match-string 3 ans))
12678 pm (equal ?p
12679 (string-to-char (downcase (match-string 4 ans)))))
12680 (if (and (= hour 12) (not pm))
12681 (setq hour 0)
12682 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12683 (setq ans (replace-match (format "%02d:%02d" hour minute)
12684 t t ans))))
12686 ;; Check if a time range is given as a duration
12687 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12688 (setq hour (string-to-number (match-string 1 ans))
12689 h2 (+ hour (string-to-number (match-string 3 ans)))
12690 minute (string-to-number (match-string 2 ans))
12691 m2 (+ minute (if (match-end 5) (string-to-number
12692 (match-string 5 ans))0)))
12693 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12694 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12695 t t ans)))
12697 ;; Check if there is a time range
12698 (when (boundp 'org-end-time-was-given)
12699 (setq org-time-was-given nil)
12700 (when (and (string-match org-plain-time-of-day-regexp ans)
12701 (match-end 8))
12702 (setq org-end-time-was-given (match-string 8 ans))
12703 (setq ans (concat (substring ans 0 (match-beginning 7))
12704 (substring ans (match-end 7))))))
12706 (setq tl (parse-time-string ans)
12707 day (or (nth 3 tl) (nth 3 defdecode))
12708 month (or (nth 4 tl)
12709 (if (and org-read-date-prefer-future
12710 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12711 (1+ (nth 4 defdecode))
12712 (nth 4 defdecode)))
12713 year (or (nth 5 tl)
12714 (if (and org-read-date-prefer-future
12715 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12716 (1+ (nth 5 defdecode))
12717 (nth 5 defdecode)))
12718 hour (or (nth 2 tl) (nth 2 defdecode))
12719 minute (or (nth 1 tl) (nth 1 defdecode))
12720 second (or (nth 0 tl) 0)
12721 wday (nth 6 tl))
12723 ;; Special date definitions below
12724 (cond
12725 (iso-week
12726 ;; There was an iso week
12727 (setq year (or iso-year year)
12728 day (or iso-weekday wday 1)
12729 wday nil ; to make sure that the trigger below does not match
12730 iso-date (calendar-gregorian-from-absolute
12731 (calendar-absolute-from-iso
12732 (list iso-week day year))))
12733 ; FIXME: Should we also push ISO weeks into the future?
12734 ; (when (and org-read-date-prefer-future
12735 ; (not iso-year)
12736 ; (< (calendar-absolute-from-gregorian iso-date)
12737 ; (time-to-days (current-time))))
12738 ; (setq year (1+ year)
12739 ; iso-date (calendar-gregorian-from-absolute
12740 ; (calendar-absolute-from-iso
12741 ; (list iso-week day year)))))
12742 (setq month (car iso-date)
12743 year (nth 2 iso-date)
12744 day (nth 1 iso-date)))
12745 (deltan
12746 (unless deltadef
12747 (let ((now (decode-time (current-time))))
12748 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12749 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12750 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12751 ((equal deltaw "m") (setq month (+ month deltan)))
12752 ((equal deltaw "y") (setq year (+ year deltan)))))
12753 ((and wday (not (nth 3 tl)))
12754 ;; Weekday was given, but no day, so pick that day in the week
12755 ;; on or after the derived date.
12756 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12757 (unless (equal wday wday1)
12758 (setq day (+ day (% (- wday wday1 -7) 7))))))
12759 (if (and (boundp 'org-time-was-given)
12760 (nth 2 tl))
12761 (setq org-time-was-given t))
12762 (if (< year 100) (setq year (+ 2000 year)))
12763 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12764 (list second minute hour day month year)))
12766 (defvar parse-time-weekdays)
12768 (defun org-read-date-get-relative (s today default)
12769 "Check string S for special relative date string.
12770 TODAY and DEFAULT are internal times, for today and for a default.
12771 Return shift list (N what def-flag)
12772 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12773 N is the number of WHATs to shift.
12774 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12775 the DEFAULT date rather than TODAY."
12776 (when (and
12777 (string-match
12778 (concat
12779 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12780 "\\([0-9]+\\)?"
12781 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12782 "\\([ \t]\\|$\\)") s)
12783 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12784 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12785 (string-to-char (substring (match-string 1 s) -1))
12786 ?+))
12787 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12788 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12789 (what (if (match-end 3) (match-string 3 s) "d"))
12790 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12791 (date (if rel default today))
12792 (wday (nth 6 (decode-time date)))
12793 delta)
12794 (if wday1
12795 (progn
12796 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12797 (if (= dir ?-) (setq delta (- delta 7)))
12798 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12799 (list delta "d" rel))
12800 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12802 (defun org-eval-in-calendar (form &optional keepdate)
12803 "Eval FORM in the calendar window and return to current window.
12804 Also, store the cursor date in variable org-ans2."
12805 (let ((sf (selected-frame))
12806 (sw (selected-window)))
12807 (select-window (get-buffer-window "*Calendar*" t))
12808 (eval form)
12809 (when (and (not keepdate) (calendar-cursor-to-date))
12810 (let* ((date (calendar-cursor-to-date))
12811 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12812 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12813 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12814 (select-window sw)
12815 (org-select-frame-set-input-focus sf)))
12817 (defun org-calendar-select ()
12818 "Return to `org-read-date' with the date currently selected.
12819 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12820 (interactive)
12821 (when (calendar-cursor-to-date)
12822 (let* ((date (calendar-cursor-to-date))
12823 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12824 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12825 (if (active-minibuffer-window) (exit-minibuffer))))
12827 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12828 "Insert a date stamp for the date given by the internal TIME.
12829 WITH-HM means, use the stamp format that includes the time of the day.
12830 INACTIVE means use square brackets instead of angular ones, so that the
12831 stamp will not contribute to the agenda.
12832 PRE and POST are optional strings to be inserted before and after the
12833 stamp.
12834 The command returns the inserted time stamp."
12835 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12836 stamp)
12837 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12838 (insert-before-markers (or pre ""))
12839 (insert-before-markers (setq stamp (format-time-string fmt time)))
12840 (when (listp extra)
12841 (setq extra (car extra))
12842 (if (and (stringp extra)
12843 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12844 (setq extra (format "-%02d:%02d"
12845 (string-to-number (match-string 1 extra))
12846 (string-to-number (match-string 2 extra))))
12847 (setq extra nil)))
12848 (when extra
12849 (backward-char 1)
12850 (insert-before-markers extra)
12851 (forward-char 1))
12852 (insert-before-markers (or post ""))
12853 (setq org-last-inserted-timestamp stamp)))
12855 (defun org-toggle-time-stamp-overlays ()
12856 "Toggle the use of custom time stamp formats."
12857 (interactive)
12858 (setq org-display-custom-times (not org-display-custom-times))
12859 (unless org-display-custom-times
12860 (let ((p (point-min)) (bmp (buffer-modified-p)))
12861 (while (setq p (next-single-property-change p 'display))
12862 (if (and (get-text-property p 'display)
12863 (eq (get-text-property p 'face) 'org-date))
12864 (remove-text-properties
12865 p (setq p (next-single-property-change p 'display))
12866 '(display t))))
12867 (set-buffer-modified-p bmp)))
12868 (if (featurep 'xemacs)
12869 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12870 (org-restart-font-lock)
12871 (setq org-table-may-need-update t)
12872 (if org-display-custom-times
12873 (message "Time stamps are overlayed with custom format")
12874 (message "Time stamp overlays removed")))
12876 (defun org-display-custom-time (beg end)
12877 "Overlay modified time stamp format over timestamp between BEG and END."
12878 (let* ((ts (buffer-substring beg end))
12879 t1 w1 with-hm tf time str w2 (off 0))
12880 (save-match-data
12881 (setq t1 (org-parse-time-string ts t))
12882 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12883 (setq off (- (match-end 0) (match-beginning 0)))))
12884 (setq end (- end off))
12885 (setq w1 (- end beg)
12886 with-hm (and (nth 1 t1) (nth 2 t1))
12887 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12888 time (org-fix-decoded-time t1)
12889 str (org-add-props
12890 (format-time-string
12891 (substring tf 1 -1) (apply 'encode-time time))
12892 nil 'mouse-face 'highlight)
12893 w2 (length str))
12894 (if (not (= w2 w1))
12895 (add-text-properties (1+ beg) (+ 2 beg)
12896 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12897 (if (featurep 'xemacs)
12898 (progn
12899 (put-text-property beg end 'invisible t)
12900 (put-text-property beg end 'end-glyph (make-glyph str)))
12901 (put-text-property beg end 'display str))))
12903 (defun org-translate-time (string)
12904 "Translate all timestamps in STRING to custom format.
12905 But do this only if the variable `org-display-custom-times' is set."
12906 (when org-display-custom-times
12907 (save-match-data
12908 (let* ((start 0)
12909 (re org-ts-regexp-both)
12910 t1 with-hm inactive tf time str beg end)
12911 (while (setq start (string-match re string start))
12912 (setq beg (match-beginning 0)
12913 end (match-end 0)
12914 t1 (save-match-data
12915 (org-parse-time-string (substring string beg end) t))
12916 with-hm (and (nth 1 t1) (nth 2 t1))
12917 inactive (equal (substring string beg (1+ beg)) "[")
12918 tf (funcall (if with-hm 'cdr 'car)
12919 org-time-stamp-custom-formats)
12920 time (org-fix-decoded-time t1)
12921 str (format-time-string
12922 (concat
12923 (if inactive "[" "<") (substring tf 1 -1)
12924 (if inactive "]" ">"))
12925 (apply 'encode-time time))
12926 string (replace-match str t t string)
12927 start (+ start (length str)))))))
12928 string)
12930 (defun org-fix-decoded-time (time)
12931 "Set 0 instead of nil for the first 6 elements of time.
12932 Don't touch the rest."
12933 (let ((n 0))
12934 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12936 (defun org-days-to-time (timestamp-string)
12937 "Difference between TIMESTAMP-STRING and now in days."
12938 (- (time-to-days (org-time-string-to-time timestamp-string))
12939 (time-to-days (current-time))))
12941 (defun org-deadline-close (timestamp-string &optional ndays)
12942 "Is the time in TIMESTAMP-STRING close to the current date?"
12943 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12944 (and (< (org-days-to-time timestamp-string) ndays)
12945 (not (org-entry-is-done-p))))
12947 (defun org-get-wdays (ts)
12948 "Get the deadline lead time appropriate for timestring TS."
12949 (cond
12950 ((<= org-deadline-warning-days 0)
12951 ;; 0 or negative, enforce this value no matter what
12952 (- org-deadline-warning-days))
12953 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12954 ;; lead time is specified.
12955 (floor (* (string-to-number (match-string 1 ts))
12956 (cdr (assoc (match-string 2 ts)
12957 '(("d" . 1) ("w" . 7)
12958 ("m" . 30.4) ("y" . 365.25)))))))
12959 ;; go for the default.
12960 (t org-deadline-warning-days)))
12962 (defun org-calendar-select-mouse (ev)
12963 "Return to `org-read-date' with the date currently selected.
12964 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12965 (interactive "e")
12966 (mouse-set-point ev)
12967 (when (calendar-cursor-to-date)
12968 (let* ((date (calendar-cursor-to-date))
12969 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12970 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12971 (if (active-minibuffer-window) (exit-minibuffer))))
12973 (defun org-check-deadlines (ndays)
12974 "Check if there are any deadlines due or past due.
12975 A deadline is considered due if it happens within `org-deadline-warning-days'
12976 days from today's date. If the deadline appears in an entry marked DONE,
12977 it is not shown. The prefix arg NDAYS can be used to test that many
12978 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12979 (interactive "P")
12980 (let* ((org-warn-days
12981 (cond
12982 ((equal ndays '(4)) 100000)
12983 (ndays (prefix-numeric-value ndays))
12984 (t (abs org-deadline-warning-days))))
12985 (case-fold-search nil)
12986 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12987 (callback
12988 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12990 (message "%d deadlines past-due or due within %d days"
12991 (org-occur regexp nil callback)
12992 org-warn-days)))
12994 (defun org-check-before-date (date)
12995 "Check if there are deadlines or scheduled entries before DATE."
12996 (interactive (list (org-read-date)))
12997 (let ((case-fold-search nil)
12998 (regexp (concat "\\<\\(" org-deadline-string
12999 "\\|" org-scheduled-string
13000 "\\) *<\\([^>]+\\)>"))
13001 (callback
13002 (lambda () (time-less-p
13003 (org-time-string-to-time (match-string 2))
13004 (org-time-string-to-time date)))))
13005 (message "%d entries before %s"
13006 (org-occur regexp nil callback) date)))
13008 (defun org-check-after-date (date)
13009 "Check if there are deadlines or scheduled entries after DATE."
13010 (interactive (list (org-read-date)))
13011 (let ((case-fold-search nil)
13012 (regexp (concat "\\<\\(" org-deadline-string
13013 "\\|" org-scheduled-string
13014 "\\) *<\\([^>]+\\)>"))
13015 (callback
13016 (lambda () (not
13017 (time-less-p
13018 (org-time-string-to-time (match-string 2))
13019 (org-time-string-to-time date))))))
13020 (message "%d entries after %s"
13021 (org-occur regexp nil callback) date)))
13023 (defun org-evaluate-time-range (&optional to-buffer)
13024 "Evaluate a time range by computing the difference between start and end.
13025 Normally the result is just printed in the echo area, but with prefix arg
13026 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13027 If the time range is actually in a table, the result is inserted into the
13028 next column.
13029 For time difference computation, a year is assumed to be exactly 365
13030 days in order to avoid rounding problems."
13031 (interactive "P")
13033 (org-clock-update-time-maybe)
13034 (save-excursion
13035 (unless (org-at-date-range-p t)
13036 (goto-char (point-at-bol))
13037 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13038 (if (not (org-at-date-range-p t))
13039 (error "Not at a time-stamp range, and none found in current line")))
13040 (let* ((ts1 (match-string 1))
13041 (ts2 (match-string 2))
13042 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13043 (match-end (match-end 0))
13044 (time1 (org-time-string-to-time ts1))
13045 (time2 (org-time-string-to-time ts2))
13046 (t1 (org-float-time time1))
13047 (t2 (org-float-time time2))
13048 (diff (abs (- t2 t1)))
13049 (negative (< (- t2 t1) 0))
13050 ;; (ys (floor (* 365 24 60 60)))
13051 (ds (* 24 60 60))
13052 (hs (* 60 60))
13053 (fy "%dy %dd %02d:%02d")
13054 (fy1 "%dy %dd")
13055 (fd "%dd %02d:%02d")
13056 (fd1 "%dd")
13057 (fh "%02d:%02d")
13058 y d h m align)
13059 (if havetime
13060 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13062 d (floor (/ diff ds)) diff (mod diff ds)
13063 h (floor (/ diff hs)) diff (mod diff hs)
13064 m (floor (/ diff 60)))
13065 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13067 d (floor (+ (/ diff ds) 0.5))
13068 h 0 m 0))
13069 (if (not to-buffer)
13070 (message "%s" (org-make-tdiff-string y d h m))
13071 (if (org-at-table-p)
13072 (progn
13073 (goto-char match-end)
13074 (setq align t)
13075 (and (looking-at " *|") (goto-char (match-end 0))))
13076 (goto-char match-end))
13077 (if (looking-at
13078 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13079 (replace-match ""))
13080 (if negative (insert " -"))
13081 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13082 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13083 (insert " " (format fh h m))))
13084 (if align (org-table-align))
13085 (message "Time difference inserted")))))
13087 (defun org-make-tdiff-string (y d h m)
13088 (let ((fmt "")
13089 (l nil))
13090 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13091 l (push y l)))
13092 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13093 l (push d l)))
13094 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13095 l (push h l)))
13096 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13097 l (push m l)))
13098 (apply 'format fmt (nreverse l))))
13100 (defun org-time-string-to-time (s)
13101 (apply 'encode-time (org-parse-time-string s)))
13102 (defun org-time-string-to-seconds (s)
13103 (org-float-time (org-time-string-to-time s)))
13105 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13106 "Convert a time stamp to an absolute day number.
13107 If there is a specifyer for a cyclic time stamp, get the closest date to
13108 DAYNR.
13109 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13110 the variable date is bound by the calendar when this is called."
13111 (cond
13112 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13113 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13114 daynr
13115 (+ daynr 1000)))
13116 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13117 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13118 (time-to-days (current-time))) (match-string 0 s)
13119 prefer show-all))
13120 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13122 (defun org-days-to-iso-week (days)
13123 "Return the iso week number."
13124 (require 'cal-iso)
13125 (car (calendar-iso-from-absolute days)))
13127 (defun org-small-year-to-year (year)
13128 "Convert 2-digit years into 4-digit years.
13129 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13130 The year 2000 cannot be abbreviated. Any year larger than 99
13131 is returned unchanged."
13132 (if (< year 38)
13133 (setq year (+ 2000 year))
13134 (if (< year 100)
13135 (setq year (+ 1900 year))))
13136 year)
13138 (defun org-time-from-absolute (d)
13139 "Return the time corresponding to date D.
13140 D may be an absolute day number, or a calendar-type list (month day year)."
13141 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13142 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13144 (defun org-calendar-holiday ()
13145 "List of holidays, for Diary display in Org-mode."
13146 (require 'holidays)
13147 (let ((hl (funcall
13148 (if (fboundp 'calendar-check-holidays)
13149 'calendar-check-holidays 'check-calendar-holidays) date)))
13150 (if hl (mapconcat 'identity hl "; "))))
13152 (defun org-diary-sexp-entry (sexp entry date)
13153 "Process a SEXP diary ENTRY for DATE."
13154 (require 'diary-lib)
13155 (let ((result (if calendar-debug-sexp
13156 (let ((stack-trace-on-error t))
13157 (eval (car (read-from-string sexp))))
13158 (condition-case nil
13159 (eval (car (read-from-string sexp)))
13160 (error
13161 (beep)
13162 (message "Bad sexp at line %d in %s: %s"
13163 (org-current-line)
13164 (buffer-file-name) sexp)
13165 (sleep-for 2))))))
13166 (cond ((stringp result) result)
13167 ((and (consp result)
13168 (stringp (cdr result))) (cdr result))
13169 (result entry)
13170 (t nil))))
13172 (defun org-diary-to-ical-string (frombuf)
13173 "Get iCalendar entries from diary entries in buffer FROMBUF.
13174 This uses the icalendar.el library."
13175 (let* ((tmpdir (if (featurep 'xemacs)
13176 (temp-directory)
13177 temporary-file-directory))
13178 (tmpfile (make-temp-name
13179 (expand-file-name "orgics" tmpdir)))
13180 buf rtn b e)
13181 (save-excursion
13182 (set-buffer frombuf)
13183 (icalendar-export-region (point-min) (point-max) tmpfile)
13184 (setq buf (find-buffer-visiting tmpfile))
13185 (set-buffer buf)
13186 (goto-char (point-min))
13187 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13188 (setq b (match-beginning 0)))
13189 (goto-char (point-max))
13190 (if (re-search-backward "^END:VEVENT" nil t)
13191 (setq e (match-end 0)))
13192 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13193 (kill-buffer buf)
13194 (delete-file tmpfile)
13195 rtn))
13197 (defun org-closest-date (start current change prefer show-all)
13198 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13199 When PREFER is `past' return a date that is either CURRENT or past.
13200 When PREFER is `future', return a date that is either CURRENT or future.
13201 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13202 ;; Make the proper lists from the dates
13203 (catch 'exit
13204 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13205 dn dw sday cday n1 n2 n0
13206 d m y y1 y2 date1 date2 nmonths nm ny m2)
13208 (setq start (org-date-to-gregorian start)
13209 current (org-date-to-gregorian
13210 (if show-all
13211 current
13212 (time-to-days (current-time))))
13213 sday (calendar-absolute-from-gregorian start)
13214 cday (calendar-absolute-from-gregorian current))
13216 (if (<= cday sday) (throw 'exit sday))
13218 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13219 (setq dn (string-to-number (match-string 1 change))
13220 dw (cdr (assoc (match-string 2 change) a1)))
13221 (error "Invalid change specifyer: %s" change))
13222 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13223 (cond
13224 ((eq dw 'day)
13225 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13226 n2 (+ n1 dn)))
13227 ((eq dw 'year)
13228 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13229 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13230 (setq date1 (list m d y1)
13231 n1 (calendar-absolute-from-gregorian date1)
13232 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13233 n2 (calendar-absolute-from-gregorian date2)))
13234 ((eq dw 'month)
13235 ;; approx number of month between the two dates
13236 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13237 ;; How often does dn fit in there?
13238 (setq d (nth 1 start) m (car start) y (nth 2 start)
13239 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13240 m (+ m nm)
13241 ny (floor (/ m 12))
13242 y (+ y ny)
13243 m (- m (* ny 12)))
13244 (while (> m 12) (setq m (- m 12) y (1+ y)))
13245 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13246 (setq m2 (+ m dn) y2 y)
13247 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13248 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13249 (while (<= n2 cday)
13250 (setq n1 n2 m m2 y y2)
13251 (setq m2 (+ m dn) y2 y)
13252 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13253 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13254 ;; Make sure n1 is the earlier date
13255 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13256 (if show-all
13257 (cond
13258 ((eq prefer 'past) n1)
13259 ((eq prefer 'future) (if (= cday n1) n1 n2))
13260 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13261 (cond
13262 ((eq prefer 'past) n1)
13263 ((eq prefer 'future) (if (= cday n1) n1 n2))
13264 (t (if (= cday n1) n1 n2)))))))
13266 (defun org-date-to-gregorian (date)
13267 "Turn any specification of DATE into a gregorian date for the calendar."
13268 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13269 ((and (listp date) (= (length date) 3)) date)
13270 ((stringp date)
13271 (setq date (org-parse-time-string date))
13272 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13273 ((listp date)
13274 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13276 (defun org-parse-time-string (s &optional nodefault)
13277 "Parse the standard Org-mode time string.
13278 This should be a lot faster than the normal `parse-time-string'.
13279 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13280 hour and minute fields will be nil if not given."
13281 (if (string-match org-ts-regexp0 s)
13282 (list 0
13283 (if (or (match-beginning 8) (not nodefault))
13284 (string-to-number (or (match-string 8 s) "0")))
13285 (if (or (match-beginning 7) (not nodefault))
13286 (string-to-number (or (match-string 7 s) "0")))
13287 (string-to-number (match-string 4 s))
13288 (string-to-number (match-string 3 s))
13289 (string-to-number (match-string 2 s))
13290 nil nil nil)
13291 (error "Not a standard Org-mode time string: %s" s)))
13293 (defun org-timestamp-up (&optional arg)
13294 "Increase the date item at the cursor by one.
13295 If the cursor is on the year, change the year. If it is on the month or
13296 the day, change that.
13297 With prefix ARG, change by that many units."
13298 (interactive "p")
13299 (org-timestamp-change (prefix-numeric-value arg)))
13301 (defun org-timestamp-down (&optional arg)
13302 "Decrease the date item at the cursor by one.
13303 If the cursor is on the year, change the year. If it is on the month or
13304 the day, change that.
13305 With prefix ARG, change by that many units."
13306 (interactive "p")
13307 (org-timestamp-change (- (prefix-numeric-value arg))))
13309 (defun org-timestamp-up-day (&optional arg)
13310 "Increase the date in the time stamp by one day.
13311 With prefix ARG, change that many days."
13312 (interactive "p")
13313 (if (and (not (org-at-timestamp-p t))
13314 (org-on-heading-p))
13315 (org-todo 'up)
13316 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13318 (defun org-timestamp-down-day (&optional arg)
13319 "Decrease the date in the time stamp by one day.
13320 With prefix ARG, change that many days."
13321 (interactive "p")
13322 (if (and (not (org-at-timestamp-p t))
13323 (org-on-heading-p))
13324 (org-todo 'down)
13325 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13327 (defun org-at-timestamp-p (&optional inactive-ok)
13328 "Determine if the cursor is in or at a timestamp."
13329 (interactive)
13330 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13331 (pos (point))
13332 (ans (or (looking-at tsr)
13333 (save-excursion
13334 (skip-chars-backward "^[<\n\r\t")
13335 (if (> (point) (point-min)) (backward-char 1))
13336 (and (looking-at tsr)
13337 (> (- (match-end 0) pos) -1))))))
13338 (and ans
13339 (boundp 'org-ts-what)
13340 (setq org-ts-what
13341 (cond
13342 ((= pos (match-beginning 0)) 'bracket)
13343 ((= pos (1- (match-end 0))) 'bracket)
13344 ((org-pos-in-match-range pos 2) 'year)
13345 ((org-pos-in-match-range pos 3) 'month)
13346 ((org-pos-in-match-range pos 7) 'hour)
13347 ((org-pos-in-match-range pos 8) 'minute)
13348 ((or (org-pos-in-match-range pos 4)
13349 (org-pos-in-match-range pos 5)) 'day)
13350 ((and (> pos (or (match-end 8) (match-end 5)))
13351 (< pos (match-end 0)))
13352 (- pos (or (match-end 8) (match-end 5))))
13353 (t 'day))))
13354 ans))
13356 (defun org-toggle-timestamp-type ()
13357 "Toggle the type (<active> or [inactive]) of a time stamp."
13358 (interactive)
13359 (when (org-at-timestamp-p t)
13360 (let ((beg (match-beginning 0)) (end (match-end 0))
13361 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13362 (save-excursion
13363 (goto-char beg)
13364 (while (re-search-forward "[][<>]" end t)
13365 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13366 t t)))
13367 (message "Timestamp is now %sactive"
13368 (if (equal (char-after beg) ?<) "" "in")))))
13370 (defun org-timestamp-change (n &optional what)
13371 "Change the date in the time stamp at point.
13372 The date will be changed by N times WHAT. WHAT can be `day', `month',
13373 `year', `minute', `second'. If WHAT is not given, the cursor position
13374 in the timestamp determines what will be changed."
13375 (let ((pos (point))
13376 with-hm inactive
13377 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13378 org-ts-what
13379 extra rem
13380 ts time time0)
13381 (if (not (org-at-timestamp-p t))
13382 (error "Not at a timestamp"))
13383 (if (and (not what) (eq org-ts-what 'bracket))
13384 (org-toggle-timestamp-type)
13385 (if (and (not what) (not (eq org-ts-what 'day))
13386 org-display-custom-times
13387 (get-text-property (point) 'display)
13388 (not (get-text-property (1- (point)) 'display)))
13389 (setq org-ts-what 'day))
13390 (setq org-ts-what (or what org-ts-what)
13391 inactive (= (char-after (match-beginning 0)) ?\[)
13392 ts (match-string 0))
13393 (replace-match "")
13394 (if (string-match
13395 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13397 (setq extra (match-string 1 ts)))
13398 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13399 (setq with-hm t))
13400 (setq time0 (org-parse-time-string ts))
13401 (when (and (eq org-ts-what 'minute)
13402 (eq current-prefix-arg nil))
13403 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13404 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13405 (setcar (cdr time0) (+ (nth 1 time0)
13406 (if (> n 0) (- rem) (- dm rem))))))
13407 (setq time
13408 (encode-time (or (car time0) 0)
13409 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13410 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13411 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13412 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13413 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13414 (nthcdr 6 time0)))
13415 (when (and (member org-ts-what '(hour minute))
13416 extra
13417 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13418 (setq extra (org-modify-ts-extra
13419 extra
13420 (if (eq org-ts-what 'hour) 2 5)
13421 n dm)))
13422 (when (integerp org-ts-what)
13423 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13424 (if (eq what 'calendar)
13425 (let ((cal-date (org-get-date-from-calendar)))
13426 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13427 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13428 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13429 (setcar time0 (or (car time0) 0))
13430 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13431 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13432 (setq time (apply 'encode-time time0))))
13433 (setq org-last-changed-timestamp
13434 (org-insert-time-stamp time with-hm inactive nil nil extra))
13435 (org-clock-update-time-maybe)
13436 (goto-char pos)
13437 ;; Try to recenter the calendar window, if any
13438 (if (and org-calendar-follow-timestamp-change
13439 (get-buffer-window "*Calendar*" t)
13440 (memq org-ts-what '(day month year)))
13441 (org-recenter-calendar (time-to-days time))))))
13443 (defun org-modify-ts-extra (s pos n dm)
13444 "Change the different parts of the lead-time and repeat fields in timestamp."
13445 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13446 ng h m new rem)
13447 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13448 (cond
13449 ((or (org-pos-in-match-range pos 2)
13450 (org-pos-in-match-range pos 3))
13451 (setq m (string-to-number (match-string 3 s))
13452 h (string-to-number (match-string 2 s)))
13453 (if (org-pos-in-match-range pos 2)
13454 (setq h (+ h n))
13455 (setq n (* dm (org-no-warnings (signum n))))
13456 (when (not (= 0 (setq rem (% m dm))))
13457 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13458 (setq m (+ m n)))
13459 (if (< m 0) (setq m (+ m 60) h (1- h)))
13460 (if (> m 59) (setq m (- m 60) h (1+ h)))
13461 (setq h (min 24 (max 0 h)))
13462 (setq ng 1 new (format "-%02d:%02d" h m)))
13463 ((org-pos-in-match-range pos 6)
13464 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13465 ((org-pos-in-match-range pos 5)
13466 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13468 ((org-pos-in-match-range pos 9)
13469 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13470 ((org-pos-in-match-range pos 8)
13471 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13473 (when ng
13474 (setq s (concat
13475 (substring s 0 (match-beginning ng))
13477 (substring s (match-end ng))))))
13480 (defun org-recenter-calendar (date)
13481 "If the calendar is visible, recenter it to DATE."
13482 (let* ((win (selected-window))
13483 (cwin (get-buffer-window "*Calendar*" t))
13484 (calendar-move-hook nil))
13485 (when cwin
13486 (select-window cwin)
13487 (calendar-goto-date (if (listp date) date
13488 (calendar-gregorian-from-absolute date)))
13489 (select-window win))))
13491 (defun org-goto-calendar (&optional arg)
13492 "Go to the Emacs calendar at the current date.
13493 If there is a time stamp in the current line, go to that date.
13494 A prefix ARG can be used to force the current date."
13495 (interactive "P")
13496 (let ((tsr org-ts-regexp) diff
13497 (calendar-move-hook nil)
13498 (calendar-view-holidays-initially-flag nil)
13499 (view-calendar-holidays-initially nil)
13500 (calendar-view-diary-initially-flag nil)
13501 (view-diary-entries-initially nil))
13502 (if (or (org-at-timestamp-p)
13503 (save-excursion
13504 (beginning-of-line 1)
13505 (looking-at (concat ".*" tsr))))
13506 (let ((d1 (time-to-days (current-time)))
13507 (d2 (time-to-days
13508 (org-time-string-to-time (match-string 1)))))
13509 (setq diff (- d2 d1))))
13510 (calendar)
13511 (calendar-goto-today)
13512 (if (and diff (not arg)) (calendar-forward-day diff))))
13514 (defun org-get-date-from-calendar ()
13515 "Return a list (month day year) of date at point in calendar."
13516 (with-current-buffer "*Calendar*"
13517 (save-match-data
13518 (calendar-cursor-to-date))))
13520 (defun org-date-from-calendar ()
13521 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13522 If there is already a time stamp at the cursor position, update it."
13523 (interactive)
13524 (if (org-at-timestamp-p t)
13525 (org-timestamp-change 0 'calendar)
13526 (let ((cal-date (org-get-date-from-calendar)))
13527 (org-insert-time-stamp
13528 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13530 (defun org-minutes-to-hh:mm-string (m)
13531 "Compute H:MM from a number of minutes."
13532 (let ((h (/ m 60)))
13533 (setq m (- m (* 60 h)))
13534 (format org-time-clocksum-format h m)))
13536 (defun org-hh:mm-string-to-minutes (s)
13537 "Convert a string H:MM to a number of minutes.
13538 If the string is just a number, interprete it as minutes.
13539 In fact, the first hh:mm or number in the string will be taken,
13540 there can be extra stuff in the string.
13541 If no number is found, the return value is 0."
13542 (cond
13543 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13544 (+ (* (string-to-number (match-string 1 s)) 60)
13545 (string-to-number (match-string 2 s))))
13546 ((string-match "\\([0-9]+\\)" s)
13547 (string-to-number (match-string 1 s)))
13548 (t 0)))
13550 ;;;; Files
13552 (defun org-save-all-org-buffers ()
13553 "Save all Org-mode buffers without user confirmation."
13554 (interactive)
13555 (message "Saving all Org-mode buffers...")
13556 (save-some-buffers t 'org-mode-p)
13557 (when (featurep 'org-id) (org-id-locations-save))
13558 (message "Saving all Org-mode buffers... done"))
13560 (defun org-revert-all-org-buffers ()
13561 "Revert all Org-mode buffers.
13562 Prompt for confirmation when there are unsaved changes.
13563 Be sure you know what you are doing before letting this function
13564 overwrite your changes.
13566 This function is useful in a setup where one tracks org files
13567 with a version control system, to revert on one machine after pulling
13568 changes from another. I believe the procedure must be like this:
13570 1. M-x org-save-all-org-buffers
13571 2. Pull changes from the other machine, resolve conflicts
13572 3. M-x org-revert-all-org-buffers"
13573 (interactive)
13574 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13575 (error "Abort"))
13576 (save-excursion
13577 (save-window-excursion
13578 (mapc
13579 (lambda (b)
13580 (when (and (with-current-buffer b (org-mode-p))
13581 (with-current-buffer b buffer-file-name))
13582 (switch-to-buffer b)
13583 (revert-buffer t 'no-confirm)))
13584 (buffer-list))
13585 (when (and (featurep 'org-id) org-id-track-globally)
13586 (org-id-locations-load)))))
13588 ;;;; Agenda files
13590 ;;;###autoload
13591 (defun org-iswitchb (&optional arg)
13592 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13593 With a prefix argument, restrict available to files.
13594 With two prefix arguments, restrict available buffers to agenda files."
13595 (interactive "P")
13596 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13597 ((equal arg '(16)) (org-buffer-list 'agenda))
13598 (t (org-buffer-list)))))
13599 (switch-to-buffer
13600 (org-icompleting-read "Org buffer: "
13601 (mapcar 'list (mapcar 'buffer-name blist))
13602 nil t))))
13604 ;;;###autoload
13605 (defalias 'org-ido-switchb 'org-iswitchb)
13607 (defun org-buffer-list (&optional predicate exclude-tmp)
13608 "Return a list of Org buffers.
13609 PREDICATE can be `export', `files' or `agenda'.
13611 export restrict the list to Export buffers.
13612 files restrict the list to buffers visiting Org files.
13613 agenda restrict the list to buffers visiting agenda files.
13615 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13616 (let* ((bfn nil)
13617 (agenda-files (and (eq predicate 'agenda)
13618 (mapcar 'file-truename (org-agenda-files t))))
13619 (filter
13620 (cond
13621 ((eq predicate 'files)
13622 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13623 ((eq predicate 'export)
13624 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13625 ((eq predicate 'agenda)
13626 (lambda (b)
13627 (with-current-buffer b
13628 (and (eq major-mode 'org-mode)
13629 (setq bfn (buffer-file-name b))
13630 (member (file-truename bfn) agenda-files)))))
13631 (t (lambda (b) (with-current-buffer b
13632 (or (eq major-mode 'org-mode)
13633 (string-match "\*Org .*Export"
13634 (buffer-name b)))))))))
13635 (delq nil
13636 (mapcar
13637 (lambda(b)
13638 (if (and (funcall filter b)
13639 (or (not exclude-tmp)
13640 (not (string-match "tmp" (buffer-name b)))))
13642 nil))
13643 (buffer-list)))))
13645 (defun org-agenda-files (&optional unrestricted archives)
13646 "Get the list of agenda files.
13647 Optional UNRESTRICTED means return the full list even if a restriction
13648 is currently in place.
13649 When ARCHIVES is t, include all archive files hat are really being
13650 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13651 `org-agenda-archives-mode' is t."
13652 (let ((files
13653 (cond
13654 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13655 ((stringp org-agenda-files) (org-read-agenda-file-list))
13656 ((listp org-agenda-files) org-agenda-files)
13657 (t (error "Invalid value of `org-agenda-files'")))))
13658 (setq files (apply 'append
13659 (mapcar (lambda (f)
13660 (if (file-directory-p f)
13661 (directory-files
13662 f t org-agenda-file-regexp)
13663 (list f)))
13664 files)))
13665 (when org-agenda-skip-unavailable-files
13666 (setq files (delq nil
13667 (mapcar (function
13668 (lambda (file)
13669 (and (file-readable-p file) file)))
13670 files))))
13671 (when (or (eq archives t)
13672 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13673 (setq files (org-add-archive-files files)))
13674 files))
13676 (defun org-edit-agenda-file-list ()
13677 "Edit the list of agenda files.
13678 Depending on setup, this either uses customize to edit the variable
13679 `org-agenda-files', or it visits the file that is holding the list. In the
13680 latter case, the buffer is set up in a way that saving it automatically kills
13681 the buffer and restores the previous window configuration."
13682 (interactive)
13683 (if (stringp org-agenda-files)
13684 (let ((cw (current-window-configuration)))
13685 (find-file org-agenda-files)
13686 (org-set-local 'org-window-configuration cw)
13687 (org-add-hook 'after-save-hook
13688 (lambda ()
13689 (set-window-configuration
13690 (prog1 org-window-configuration
13691 (kill-buffer (current-buffer))))
13692 (org-install-agenda-files-menu)
13693 (message "New agenda file list installed"))
13694 nil 'local)
13695 (message "%s" (substitute-command-keys
13696 "Edit list and finish with \\[save-buffer]")))
13697 (customize-variable 'org-agenda-files)))
13699 (defun org-store-new-agenda-file-list (list)
13700 "Set new value for the agenda file list and save it correctly."
13701 (if (stringp org-agenda-files)
13702 (let ((f org-agenda-files) b)
13703 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13704 (with-temp-file f
13705 (insert (mapconcat 'identity list "\n") "\n")))
13706 (let ((org-mode-hook nil) (org-inhibit-startup t)
13707 (org-insert-mode-line-in-empty-file nil))
13708 (setq org-agenda-files list)
13709 (customize-save-variable 'org-agenda-files org-agenda-files))))
13711 (defun org-read-agenda-file-list ()
13712 "Read the list of agenda files from a file."
13713 (when (file-directory-p org-agenda-files)
13714 (error "`org-agenda-files' cannot be a single directory"))
13715 (when (stringp org-agenda-files)
13716 (with-temp-buffer
13717 (insert-file-contents org-agenda-files)
13718 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13721 ;;;###autoload
13722 (defun org-cycle-agenda-files ()
13723 "Cycle through the files in `org-agenda-files'.
13724 If the current buffer visits an agenda file, find the next one in the list.
13725 If the current buffer does not, find the first agenda file."
13726 (interactive)
13727 (let* ((fs (org-agenda-files t))
13728 (files (append fs (list (car fs))))
13729 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13730 file)
13731 (unless files (error "No agenda files"))
13732 (catch 'exit
13733 (while (setq file (pop files))
13734 (if (equal (file-truename file) tcf)
13735 (when (car files)
13736 (find-file (car files))
13737 (throw 'exit t))))
13738 (find-file (car fs)))
13739 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13741 (defun org-agenda-file-to-front (&optional to-end)
13742 "Move/add the current file to the top of the agenda file list.
13743 If the file is not present in the list, it is added to the front. If it is
13744 present, it is moved there. With optional argument TO-END, add/move to the
13745 end of the list."
13746 (interactive "P")
13747 (let ((org-agenda-skip-unavailable-files nil)
13748 (file-alist (mapcar (lambda (x)
13749 (cons (file-truename x) x))
13750 (org-agenda-files t)))
13751 (ctf (file-truename buffer-file-name))
13752 x had)
13753 (setq x (assoc ctf file-alist) had x)
13755 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13756 (if to-end
13757 (setq file-alist (append (delq x file-alist) (list x)))
13758 (setq file-alist (cons x (delq x file-alist))))
13759 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13760 (org-install-agenda-files-menu)
13761 (message "File %s to %s of agenda file list"
13762 (if had "moved" "added") (if to-end "end" "front"))))
13764 (defun org-remove-file (&optional file)
13765 "Remove current file from the list of files in variable `org-agenda-files'.
13766 These are the files which are being checked for agenda entries.
13767 Optional argument FILE means, use this file instead of the current."
13768 (interactive)
13769 (let* ((org-agenda-skip-unavailable-files nil)
13770 (file (or file buffer-file-name))
13771 (true-file (file-truename file))
13772 (afile (abbreviate-file-name file))
13773 (files (delq nil (mapcar
13774 (lambda (x)
13775 (if (equal true-file
13776 (file-truename x))
13777 nil x))
13778 (org-agenda-files t)))))
13779 (if (not (= (length files) (length (org-agenda-files t))))
13780 (progn
13781 (org-store-new-agenda-file-list files)
13782 (org-install-agenda-files-menu)
13783 (message "Removed file: %s" afile))
13784 (message "File was not in list: %s (not removed)" afile))))
13786 (defun org-file-menu-entry (file)
13787 (vector file (list 'find-file file) t))
13789 (defun org-check-agenda-file (file)
13790 "Make sure FILE exists. If not, ask user what to do."
13791 (when (not (file-exists-p file))
13792 (message "non-existent file %s. [R]emove from list or [A]bort?"
13793 (abbreviate-file-name file))
13794 (let ((r (downcase (read-char-exclusive))))
13795 (cond
13796 ((equal r ?r)
13797 (org-remove-file file)
13798 (throw 'nextfile t))
13799 (t (error "Abort"))))))
13801 (defun org-get-agenda-file-buffer (file)
13802 "Get a buffer visiting FILE. If the buffer needs to be created, add
13803 it to the list of buffers which might be released later."
13804 (let ((buf (org-find-base-buffer-visiting file)))
13805 (if buf
13806 buf ; just return it
13807 ;; Make a new buffer and remember it
13808 (setq buf (find-file-noselect file))
13809 (if buf (push buf org-agenda-new-buffers))
13810 buf)))
13812 (defun org-release-buffers (blist)
13813 "Release all buffers in list, asking the user for confirmation when needed.
13814 When a buffer is unmodified, it is just killed. When modified, it is saved
13815 \(if the user agrees) and then killed."
13816 (let (buf file)
13817 (while (setq buf (pop blist))
13818 (setq file (buffer-file-name buf))
13819 (when (and (buffer-modified-p buf)
13820 file
13821 (y-or-n-p (format "Save file %s? " file)))
13822 (with-current-buffer buf (save-buffer)))
13823 (kill-buffer buf))))
13825 (defun org-prepare-agenda-buffers (files)
13826 "Create buffers for all agenda files, protect archived trees and comments."
13827 (interactive)
13828 (let ((pa '(:org-archived t))
13829 (pc '(:org-comment t))
13830 (pall '(:org-archived t :org-comment t))
13831 (inhibit-read-only t)
13832 (rea (concat ":" org-archive-tag ":"))
13833 bmp file re)
13834 (save-excursion
13835 (save-restriction
13836 (while (setq file (pop files))
13837 (catch 'nextfile
13838 (if (bufferp file)
13839 (set-buffer file)
13840 (org-check-agenda-file file)
13841 (set-buffer (org-get-agenda-file-buffer file)))
13842 (widen)
13843 (setq bmp (buffer-modified-p))
13844 (org-refresh-category-properties)
13845 (setq org-todo-keywords-for-agenda
13846 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13847 (setq org-done-keywords-for-agenda
13848 (append org-done-keywords-for-agenda org-done-keywords))
13849 (setq org-todo-keyword-alist-for-agenda
13850 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13851 (setq org-tag-alist-for-agenda
13852 (append org-tag-alist-for-agenda org-tag-alist))
13854 (save-excursion
13855 (remove-text-properties (point-min) (point-max) pall)
13856 (when org-agenda-skip-archived-trees
13857 (goto-char (point-min))
13858 (while (re-search-forward rea nil t)
13859 (if (org-on-heading-p t)
13860 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13861 (goto-char (point-min))
13862 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13863 (while (re-search-forward re nil t)
13864 (add-text-properties
13865 (match-beginning 0) (org-end-of-subtree t) pc)))
13866 (set-buffer-modified-p bmp)))))
13867 (setq org-todo-keyword-alist-for-agenda
13868 (org-uniquify org-todo-keyword-alist-for-agenda)
13869 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13871 ;;;; Embedded LaTeX
13873 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13874 "Keymap for the minor `org-cdlatex-mode'.")
13876 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13877 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13878 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13879 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13880 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13882 (defvar org-cdlatex-texmathp-advice-is-done nil
13883 "Flag remembering if we have applied the advice to texmathp already.")
13885 (define-minor-mode org-cdlatex-mode
13886 "Toggle the minor `org-cdlatex-mode'.
13887 This mode supports entering LaTeX environment and math in LaTeX fragments
13888 in Org-mode.
13889 \\{org-cdlatex-mode-map}"
13890 nil " OCDL" nil
13891 (when org-cdlatex-mode (require 'cdlatex))
13892 (unless org-cdlatex-texmathp-advice-is-done
13893 (setq org-cdlatex-texmathp-advice-is-done t)
13894 (defadvice texmathp (around org-math-always-on activate)
13895 "Always return t in org-mode buffers.
13896 This is because we want to insert math symbols without dollars even outside
13897 the LaTeX math segments. If Orgmode thinks that point is actually inside
13898 an embedded LaTeX fragment, let texmathp do its job.
13899 \\[org-cdlatex-mode-map]"
13900 (interactive)
13901 (let (p)
13902 (cond
13903 ((not (org-mode-p)) ad-do-it)
13904 ((eq this-command 'cdlatex-math-symbol)
13905 (setq ad-return-value t
13906 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13908 (let ((p (org-inside-LaTeX-fragment-p)))
13909 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13910 (setq ad-return-value t
13911 texmathp-why '("Org-mode embedded math" . 0))
13912 (if p ad-do-it)))))))))
13914 (defun turn-on-org-cdlatex ()
13915 "Unconditionally turn on `org-cdlatex-mode'."
13916 (org-cdlatex-mode 1))
13918 (defun org-inside-LaTeX-fragment-p ()
13919 "Test if point is inside a LaTeX fragment.
13920 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13921 sequence appearing also before point.
13922 Even though the matchers for math are configurable, this function assumes
13923 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13924 delimiters are skipped when they have been removed by customization.
13925 The return value is nil, or a cons cell with the delimiter and
13926 and the position of this delimiter.
13928 This function does a reasonably good job, but can locally be fooled by
13929 for example currency specifications. For example it will assume being in
13930 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13931 fragments that are properly closed, but during editing, we have to live
13932 with the uncertainty caused by missing closing delimiters. This function
13933 looks only before point, not after."
13934 (catch 'exit
13935 (let ((pos (point))
13936 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13937 (lim (progn
13938 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13939 (point)))
13940 dd-on str (start 0) m re)
13941 (goto-char pos)
13942 (when dodollar
13943 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13944 re (nth 1 (assoc "$" org-latex-regexps)))
13945 (while (string-match re str start)
13946 (cond
13947 ((= (match-end 0) (length str))
13948 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13949 ((= (match-end 0) (- (length str) 5))
13950 (throw 'exit nil))
13951 (t (setq start (match-end 0))))))
13952 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13953 (goto-char pos)
13954 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13955 (and (match-beginning 2) (throw 'exit nil))
13956 ;; count $$
13957 (while (re-search-backward "\\$\\$" lim t)
13958 (setq dd-on (not dd-on)))
13959 (goto-char pos)
13960 (if dd-on (cons "$$" m))))))
13963 (defun org-try-cdlatex-tab ()
13964 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13965 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13966 - inside a LaTeX fragment, or
13967 - after the first word in a line, where an abbreviation expansion could
13968 insert a LaTeX environment."
13969 (when org-cdlatex-mode
13970 (cond
13971 ((save-excursion
13972 (skip-chars-backward "a-zA-Z0-9*")
13973 (skip-chars-backward " \t")
13974 (bolp))
13975 (cdlatex-tab) t)
13976 ((org-inside-LaTeX-fragment-p)
13977 (cdlatex-tab) t)
13978 (t nil))))
13980 (defun org-cdlatex-underscore-caret (&optional arg)
13981 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13982 Revert to the normal definition outside of these fragments."
13983 (interactive "P")
13984 (if (org-inside-LaTeX-fragment-p)
13985 (call-interactively 'cdlatex-sub-superscript)
13986 (let (org-cdlatex-mode)
13987 (call-interactively (key-binding (vector last-input-event))))))
13989 (defun org-cdlatex-math-modify (&optional arg)
13990 "Execute `cdlatex-math-modify' in LaTeX fragments.
13991 Revert to the normal definition outside of these fragments."
13992 (interactive "P")
13993 (if (org-inside-LaTeX-fragment-p)
13994 (call-interactively 'cdlatex-math-modify)
13995 (let (org-cdlatex-mode)
13996 (call-interactively (key-binding (vector last-input-event))))))
13998 (defvar org-latex-fragment-image-overlays nil
13999 "List of overlays carrying the images of latex fragments.")
14000 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14002 (defun org-remove-latex-fragment-image-overlays ()
14003 "Remove all overlays with LaTeX fragment images in current buffer."
14004 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14005 (setq org-latex-fragment-image-overlays nil))
14007 (defun org-preview-latex-fragment (&optional subtree)
14008 "Preview the LaTeX fragment at point, or all locally or globally.
14009 If the cursor is in a LaTeX fragment, create the image and overlay
14010 it over the source code. If there is no fragment at point, display
14011 all fragments in the current text, from one headline to the next. With
14012 prefix SUBTREE, display all fragments in the current subtree. With a
14013 double prefix `C-u C-u', or when the cursor is before the first headline,
14014 display all fragments in the buffer.
14015 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14016 (interactive "P")
14017 (org-remove-latex-fragment-image-overlays)
14018 (save-excursion
14019 (save-restriction
14020 (let (beg end at msg)
14021 (cond
14022 ((or (equal subtree '(16))
14023 (not (save-excursion
14024 (re-search-backward (concat "^" outline-regexp) nil t))))
14025 (setq beg (point-min) end (point-max)
14026 msg "Creating images for buffer...%s"))
14027 ((equal subtree '(4))
14028 (org-back-to-heading)
14029 (setq beg (point) end (org-end-of-subtree t)
14030 msg "Creating images for subtree...%s"))
14032 (if (setq at (org-inside-LaTeX-fragment-p))
14033 (goto-char (max (point-min) (- (cdr at) 2)))
14034 (org-back-to-heading))
14035 (setq beg (point) end (progn (outline-next-heading) (point))
14036 msg (if at "Creating image...%s"
14037 "Creating images for entry...%s"))))
14038 (message msg "")
14039 (narrow-to-region beg end)
14040 (goto-char beg)
14041 (org-format-latex
14042 (concat "ltxpng/" (file-name-sans-extension
14043 (file-name-nondirectory
14044 buffer-file-name)))
14045 default-directory 'overlays msg at 'forbuffer)
14046 (message msg "done. Use `C-c C-c' to remove images.")))))
14048 (defvar org-latex-regexps
14049 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14050 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14051 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14052 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14053 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14054 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14055 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14056 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14057 "Regular expressions for matching embedded LaTeX.")
14059 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14060 "Replace LaTeX fragments with links to an image, and produce images."
14061 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14062 (let* ((prefixnodir (file-name-nondirectory prefix))
14063 (absprefix (expand-file-name prefix dir))
14064 (todir (file-name-directory absprefix))
14065 (opt org-format-latex-options)
14066 (matchers (plist-get opt :matchers))
14067 (re-list org-latex-regexps)
14068 (cnt 0) txt link beg end re e checkdir
14069 executables-checked
14070 m n block linkfile movefile ov)
14071 ;; Check if there are old images files with this prefix, and remove them
14072 (when (file-directory-p todir)
14073 (mapc 'delete-file
14074 (directory-files
14075 todir 'full
14076 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14077 ;; Check the different regular expressions
14078 (while (setq e (pop re-list))
14079 (setq m (car e) re (nth 1 e) n (nth 2 e)
14080 block (if (nth 3 e) "\n\n" ""))
14081 (when (member m matchers)
14082 (goto-char (point-min))
14083 (while (re-search-forward re nil t)
14084 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14085 (not (get-text-property (match-beginning n)
14086 'org-protected))
14087 (or (not overlays)
14088 (not (eq (get-char-property (match-beginning n)
14089 'org-overlay-type)
14090 'org-latex-overlay))))
14091 (setq txt (match-string n)
14092 beg (match-beginning n) end (match-end n)
14093 cnt (1+ cnt)
14094 linkfile (format "%s_%04d.png" prefix cnt)
14095 movefile (format "%s_%04d.png" absprefix cnt)
14096 link (concat block "[[file:" linkfile "]]" block))
14097 (if msg (message msg cnt))
14098 (goto-char beg)
14099 (unless checkdir ; make sure the directory exists
14100 (setq checkdir t)
14101 (or (file-directory-p todir) (make-directory todir)))
14103 (unless executables-checked
14104 (org-check-external-command
14105 "latex" "needed to convert LaTeX fragments to images")
14106 (org-check-external-command
14107 "dvipng" "needed to convert LaTeX fragments to images")
14108 (setq executables-checked t))
14110 (org-create-formula-image
14111 txt movefile opt forbuffer)
14112 (if overlays
14113 (progn
14114 (mapc (lambda (o)
14115 (if (eq (org-overlay-get o 'org-overlay-type)
14116 'org-latex-overlay)
14117 (org-delete-overlay o)))
14118 (org-overlays-in beg end))
14119 (setq ov (org-make-overlay beg end))
14120 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14121 (if (featurep 'xemacs)
14122 (progn
14123 (org-overlay-put ov 'invisible t)
14124 (org-overlay-put
14125 ov 'end-glyph
14126 (make-glyph (vector 'png :file movefile))))
14127 (org-overlay-put
14128 ov 'display
14129 (list 'image :type 'png :file movefile :ascent 'center)))
14130 (push ov org-latex-fragment-image-overlays)
14131 (goto-char end))
14132 (delete-region beg end)
14133 (insert link))))))))
14135 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14136 ;; This function borrows from Ganesh Swami's latex2png.el
14137 (defun org-create-formula-image (string tofile options buffer)
14138 (require 'org-latex)
14139 (let* ((tmpdir (if (featurep 'xemacs)
14140 (temp-directory)
14141 temporary-file-directory))
14142 (texfilebase (make-temp-name
14143 (expand-file-name "orgtex" tmpdir)))
14144 (texfile (concat texfilebase ".tex"))
14145 (dvifile (concat texfilebase ".dvi"))
14146 (pngfile (concat texfilebase ".png"))
14147 (fnh (if (featurep 'xemacs)
14148 (font-height (get-face-font 'default))
14149 (face-attribute 'default :height nil)))
14150 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14151 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14152 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14153 "Black"))
14154 (bg (or (plist-get options (if buffer :background :html-background))
14155 "Transparent")))
14156 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14157 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14158 (with-temp-file texfile
14159 (insert org-format-latex-header
14160 (if org-export-latex-packages-alist
14161 (concat "\n"
14162 (mapconcat (lambda(p)
14163 (if (equal "" (car p))
14164 (format "\\usepackage{%s}" (cadr p))
14165 (format "\\usepackage[%s]{%s}"
14166 (car p) (cadr p))))
14167 org-export-latex-packages-alist "\n"))
14169 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14170 (let ((dir default-directory))
14171 (condition-case nil
14172 (progn
14173 (cd tmpdir)
14174 (call-process "latex" nil nil nil texfile))
14175 (error nil))
14176 (cd dir))
14177 (if (not (file-exists-p dvifile))
14178 (progn (message "Failed to create dvi file from %s" texfile) nil)
14179 (condition-case nil
14180 (call-process "dvipng" nil nil nil
14181 "-fg" fg "-bg" bg
14182 "-D" dpi
14183 ;;"-x" scale "-y" scale
14184 "-T" "tight"
14185 "-o" pngfile
14186 dvifile)
14187 (error nil))
14188 (if (not (file-exists-p pngfile))
14189 (progn (message "Failed to create png file from %s" texfile) nil)
14190 ;; Use the requested file name and clean up
14191 (copy-file pngfile tofile 'replace)
14192 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14193 (delete-file (concat texfilebase e)))
14194 pngfile))))
14196 (defun org-dvipng-color (attr)
14197 "Return an rgb color specification for dvipng."
14198 (apply 'format "rgb %s %s %s"
14199 (mapcar 'org-normalize-color
14200 (color-values (face-attribute 'default attr nil)))))
14202 (defun org-normalize-color (value)
14203 "Return string to be used as color value for an RGB component."
14204 (format "%g" (/ value 65535.0)))
14206 ;;;; Key bindings
14208 ;; Make `C-c C-x' a prefix key
14209 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14211 ;; TAB key with modifiers
14212 (org-defkey org-mode-map "\C-i" 'org-cycle)
14213 (org-defkey org-mode-map [(tab)] 'org-cycle)
14214 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14215 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14216 (org-defkey org-mode-map "\M-\t" 'org-complete)
14217 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14218 ;; The following line is necessary under Suse GNU/Linux
14219 (unless (featurep 'xemacs)
14220 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14221 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14222 (define-key org-mode-map [backtab] 'org-shifttab)
14224 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14225 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14226 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14228 ;; Cursor keys with modifiers
14229 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14230 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14231 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14232 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14234 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14235 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14236 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14237 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14239 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14240 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14241 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14242 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14244 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14245 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14247 ;;; Extra keys for tty access.
14248 ;; We only set them when really needed because otherwise the
14249 ;; menus don't show the simple keys
14251 (when (or org-use-extra-keys
14252 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14253 (not window-system))
14254 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14255 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14256 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14257 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14258 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14259 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14260 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14261 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14262 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14263 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14264 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14265 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14266 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14267 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14268 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14269 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14270 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14271 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14272 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14273 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14274 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14275 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14276 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14277 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14278 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14279 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14280 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14281 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14283 ;; All the other keys
14285 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14286 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14287 (if (boundp 'narrow-map)
14288 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14289 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14290 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14291 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14292 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14293 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14294 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14295 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14296 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14297 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14298 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14299 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14300 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14301 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14302 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14303 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14304 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14305 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14306 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14307 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14308 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14309 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14310 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14311 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14312 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14313 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14314 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14315 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14316 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14317 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14318 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14319 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14320 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14321 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14322 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14323 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14324 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14325 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14326 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14327 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14328 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14329 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14330 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14331 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14332 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14333 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14334 (org-defkey org-mode-map "\C-c^" 'org-sort)
14335 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14336 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14337 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14338 (org-defkey org-mode-map "\C-m" 'org-return)
14339 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14340 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14341 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14342 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14343 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14344 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14345 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14346 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14347 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14348 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14349 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14350 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14351 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14352 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14353 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14354 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14355 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14356 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14357 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14359 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14360 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14361 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14362 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14364 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14365 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14366 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14367 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14368 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14369 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14370 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14371 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14372 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14373 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14374 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14375 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14376 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14377 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14378 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14380 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14381 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14382 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14383 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14385 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14387 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14389 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14390 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14392 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14395 (when (featurep 'xemacs)
14396 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14399 (defvar org-self-insert-command-undo-counter 0)
14401 (defvar org-table-auto-blank-field) ; defined in org-table.el
14402 (defun org-self-insert-command (N)
14403 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14404 If the cursor is in a table looking at whitespace, the whitespace is
14405 overwritten, and the table is not marked as requiring realignment."
14406 (interactive "p")
14407 (if (and
14408 (org-table-p)
14409 (progn
14410 ;; check if we blank the field, and if that triggers align
14411 (and (featurep 'org-table) org-table-auto-blank-field
14412 (member last-command
14413 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14414 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14415 ;; got extra space, this field does not determine column width
14416 (let (org-table-may-need-update) (org-table-blank-field))
14417 ;; no extra space, this field may determine column width
14418 (org-table-blank-field)))
14420 (eq N 1)
14421 (looking-at "[^|\n]* |"))
14422 (let (org-table-may-need-update)
14423 (goto-char (1- (match-end 0)))
14424 (delete-backward-char 1)
14425 (goto-char (match-beginning 0))
14426 (self-insert-command N))
14427 (setq org-table-may-need-update t)
14428 (self-insert-command N)
14429 (org-fix-tags-on-the-fly)
14430 (if org-self-insert-cluster-for-undo
14431 (if (not (eq last-command 'org-self-insert-command))
14432 (setq org-self-insert-command-undo-counter 1)
14433 (if (>= org-self-insert-command-undo-counter 20)
14434 (setq org-self-insert-command-undo-counter 1)
14435 (and (> org-self-insert-command-undo-counter 0)
14436 buffer-undo-list
14437 (not (cadr buffer-undo-list)) ; remove nil entry
14438 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14439 (setq org-self-insert-command-undo-counter
14440 (1+ org-self-insert-command-undo-counter)))))))
14442 (defun org-fix-tags-on-the-fly ()
14443 (when (and (equal (char-after (point-at-bol)) ?*)
14444 (org-on-heading-p))
14445 (org-align-tags-here org-tags-column)))
14447 (defun org-delete-backward-char (N)
14448 "Like `delete-backward-char', insert whitespace at field end in tables.
14449 When deleting backwards, in tables this function will insert whitespace in
14450 front of the next \"|\" separator, to keep the table aligned. The table will
14451 still be marked for re-alignment if the field did fill the entire column,
14452 because, in this case the deletion might narrow the column."
14453 (interactive "p")
14454 (if (and (org-table-p)
14455 (eq N 1)
14456 (string-match "|" (buffer-substring (point-at-bol) (point)))
14457 (looking-at ".*?|"))
14458 (let ((pos (point))
14459 (noalign (looking-at "[^|\n\r]* |"))
14460 (c org-table-may-need-update))
14461 (backward-delete-char N)
14462 (skip-chars-forward "^|")
14463 (insert " ")
14464 (goto-char (1- pos))
14465 ;; noalign: if there were two spaces at the end, this field
14466 ;; does not determine the width of the column.
14467 (if noalign (setq org-table-may-need-update c)))
14468 (backward-delete-char N)
14469 (org-fix-tags-on-the-fly)))
14471 (defun org-delete-char (N)
14472 "Like `delete-char', but insert whitespace at field end in tables.
14473 When deleting characters, in tables this function will insert whitespace in
14474 front of the next \"|\" separator, to keep the table aligned. The table will
14475 still be marked for re-alignment if the field did fill the entire column,
14476 because, in this case the deletion might narrow the column."
14477 (interactive "p")
14478 (if (and (org-table-p)
14479 (not (bolp))
14480 (not (= (char-after) ?|))
14481 (eq N 1))
14482 (if (looking-at ".*?|")
14483 (let ((pos (point))
14484 (noalign (looking-at "[^|\n\r]* |"))
14485 (c org-table-may-need-update))
14486 (replace-match (concat
14487 (substring (match-string 0) 1 -1)
14488 " |"))
14489 (goto-char pos)
14490 ;; noalign: if there were two spaces at the end, this field
14491 ;; does not determine the width of the column.
14492 (if noalign (setq org-table-may-need-update c)))
14493 (delete-char N))
14494 (delete-char N)
14495 (org-fix-tags-on-the-fly)))
14497 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14498 (put 'org-self-insert-command 'delete-selection t)
14499 (put 'orgtbl-self-insert-command 'delete-selection t)
14500 (put 'org-delete-char 'delete-selection 'supersede)
14501 (put 'org-delete-backward-char 'delete-selection 'supersede)
14502 (put 'org-yank 'delete-selection 'yank)
14504 ;; Make `flyspell-mode' delay after some commands
14505 (put 'org-self-insert-command 'flyspell-delayed t)
14506 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14507 (put 'org-delete-char 'flyspell-delayed t)
14508 (put 'org-delete-backward-char 'flyspell-delayed t)
14510 ;; Make pabbrev-mode expand after org-mode commands
14511 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14512 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14514 ;; How to do this: Measure non-white length of current string
14515 ;; If equal to column width, we should realign.
14517 (defun org-remap (map &rest commands)
14518 "In MAP, remap the functions given in COMMANDS.
14519 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14520 (let (new old)
14521 (while commands
14522 (setq old (pop commands) new (pop commands))
14523 (if (fboundp 'command-remapping)
14524 (org-defkey map (vector 'remap old) new)
14525 (substitute-key-definition old new map global-map)))))
14527 (when (eq org-enable-table-editor 'optimized)
14528 ;; If the user wants maximum table support, we need to hijack
14529 ;; some standard editing functions
14530 (org-remap org-mode-map
14531 'self-insert-command 'org-self-insert-command
14532 'delete-char 'org-delete-char
14533 'delete-backward-char 'org-delete-backward-char)
14534 (org-defkey org-mode-map "|" 'org-force-self-insert))
14536 (defvar org-ctrl-c-ctrl-c-hook nil
14537 "Hook for functions attaching themselves to `C-c C-c'.
14538 This can be used to add additional functionality to the C-c C-c key which
14539 executes context-dependent commands.
14540 Each function will be called with no arguments. The function must check
14541 if the context is appropriate for it to act. If yes, it should do its
14542 thing and then return a non-nil value. If the context is wrong,
14543 just do nothing and return nil.")
14545 (defvar org-tab-first-hook nil
14546 "Hook for functions to attach themselves to TAB.
14547 See `org-ctrl-c-ctrl-c-hook' for more information.
14548 This hook runs as the first action when TAB is pressed, even before
14549 `org-cycle' messes around with the `outline-regexp' to cater for
14550 inline tasks and plain list item folding.
14551 If any function in this hook returns t, not other actions like table
14552 field motion visibility cycling will be done.")
14554 (defvar org-tab-after-check-for-table-hook nil
14555 "Hook for functions to attach themselves to TAB.
14556 See `org-ctrl-c-ctrl-c-hook' for more information.
14557 This hook runs after it has been established that the cursor is not in a
14558 table, but before checking if the cursor is in a headline or if global cycling
14559 should be done.
14560 If any function in this hook returns t, not other actions like visibility
14561 cycling will be done.")
14563 (defvar org-tab-after-check-for-cycling-hook nil
14564 "Hook for functions to attach themselves to TAB.
14565 See `org-ctrl-c-ctrl-c-hook' for more information.
14566 This hook runs after it has been established that not table field motion and
14567 not visibility should be done because of current context. This is probably
14568 the place where a package like yasnippets can hook in.")
14570 (defvar org-metaleft-hook nil
14571 "Hook for functions attaching themselves to `M-left'.
14572 See `org-ctrl-c-ctrl-c-hook' for more information.")
14573 (defvar org-metaright-hook nil
14574 "Hook for functions attaching themselves to `M-right'.
14575 See `org-ctrl-c-ctrl-c-hook' for more information.")
14576 (defvar org-metaup-hook nil
14577 "Hook for functions attaching themselves to `M-up'.
14578 See `org-ctrl-c-ctrl-c-hook' for more information.")
14579 (defvar org-metadown-hook nil
14580 "Hook for functions attaching themselves to `M-down'.
14581 See `org-ctrl-c-ctrl-c-hook' for more information.")
14582 (defvar org-shiftmetaleft-hook nil
14583 "Hook for functions attaching themselves to `M-S-left'.
14584 See `org-ctrl-c-ctrl-c-hook' for more information.")
14585 (defvar org-shiftmetaright-hook nil
14586 "Hook for functions attaching themselves to `M-S-right'.
14587 See `org-ctrl-c-ctrl-c-hook' for more information.")
14588 (defvar org-shiftmetaup-hook nil
14589 "Hook for functions attaching themselves to `M-S-up'.
14590 See `org-ctrl-c-ctrl-c-hook' for more information.")
14591 (defvar org-shiftmetadown-hook nil
14592 "Hook for functions attaching themselves to `M-S-down'.
14593 See `org-ctrl-c-ctrl-c-hook' for more information.")
14594 (defvar org-metareturn-hook nil
14595 "Hook for functions attaching themselves to `M-RET'.
14596 See `org-ctrl-c-ctrl-c-hook' for more information.")
14598 (defun org-modifier-cursor-error ()
14599 "Throw an error, a modified cursor command was applied in wrong context."
14600 (error "This command is active in special context like tables, headlines or items"))
14602 (defun org-shiftselect-error ()
14603 "Throw an error because Shift-Cursor command was applied in wrong context."
14604 (if (and (boundp 'shift-select-mode) shift-select-mode)
14605 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14606 (error "This command works only in special context like headlines or timestamps.")))
14608 (defun org-call-for-shift-select (cmd)
14609 (let ((this-command-keys-shift-translated t))
14610 (call-interactively cmd)))
14612 (defun org-shifttab (&optional arg)
14613 "Global visibility cycling or move to previous table field.
14614 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14615 on context.
14616 See the individual commands for more information."
14617 (interactive "P")
14618 (cond
14619 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14620 ((integerp arg)
14621 (message "Content view to level: %d" arg)
14622 (org-content (prefix-numeric-value arg))
14623 (setq org-cycle-global-status 'overview))
14624 (t (call-interactively 'org-global-cycle))))
14626 (defun org-shiftmetaleft ()
14627 "Promote subtree or delete table column.
14628 Calls `org-promote-subtree', `org-outdent-item',
14629 or `org-table-delete-column', depending on context.
14630 See the individual commands for more information."
14631 (interactive)
14632 (cond
14633 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14634 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14635 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14636 ((org-at-item-p) (call-interactively 'org-outdent-item))
14637 (t (org-modifier-cursor-error))))
14639 (defun org-shiftmetaright ()
14640 "Demote subtree or insert table column.
14641 Calls `org-demote-subtree', `org-indent-item',
14642 or `org-table-insert-column', depending on context.
14643 See the individual commands for more information."
14644 (interactive)
14645 (cond
14646 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14647 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14648 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14649 ((org-at-item-p) (call-interactively 'org-indent-item))
14650 (t (org-modifier-cursor-error))))
14652 (defun org-shiftmetaup (&optional arg)
14653 "Move subtree up or kill table row.
14654 Calls `org-move-subtree-up' or `org-table-kill-row' or
14655 `org-move-item-up' depending on context. See the individual commands
14656 for more information."
14657 (interactive "P")
14658 (cond
14659 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14660 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14661 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14662 ((org-at-item-p) (call-interactively 'org-move-item-up))
14663 (t (org-modifier-cursor-error))))
14665 (defun org-shiftmetadown (&optional arg)
14666 "Move subtree down or insert table row.
14667 Calls `org-move-subtree-down' or `org-table-insert-row' or
14668 `org-move-item-down', depending on context. See the individual
14669 commands for more information."
14670 (interactive "P")
14671 (cond
14672 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14673 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14674 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14675 ((org-at-item-p) (call-interactively 'org-move-item-down))
14676 (t (org-modifier-cursor-error))))
14678 (defun org-metaleft (&optional arg)
14679 "Promote heading or move table column to left.
14680 Calls `org-do-promote' or `org-table-move-column', depending on context.
14681 With no specific context, calls the Emacs default `backward-word'.
14682 See the individual commands for more information."
14683 (interactive "P")
14684 (cond
14685 ((run-hook-with-args-until-success 'org-metaleft-hook))
14686 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14687 ((or (org-on-heading-p)
14688 (and (org-region-active-p)
14689 (save-excursion
14690 (goto-char (region-beginning))
14691 (org-on-heading-p))))
14692 (call-interactively 'org-do-promote))
14693 ((or (org-at-item-p)
14694 (and (org-region-active-p)
14695 (save-excursion
14696 (goto-char (region-beginning))
14697 (org-at-item-p))))
14698 (call-interactively 'org-outdent-item))
14699 (t (call-interactively 'backward-word))))
14701 (defun org-metaright (&optional arg)
14702 "Demote subtree or move table column to right.
14703 Calls `org-do-demote' or `org-table-move-column', depending on context.
14704 With no specific context, calls the Emacs default `forward-word'.
14705 See the individual commands for more information."
14706 (interactive "P")
14707 (cond
14708 ((run-hook-with-args-until-success 'org-metaright-hook))
14709 ((org-at-table-p) (call-interactively 'org-table-move-column))
14710 ((or (org-on-heading-p)
14711 (and (org-region-active-p)
14712 (save-excursion
14713 (goto-char (region-beginning))
14714 (org-on-heading-p))))
14715 (call-interactively 'org-do-demote))
14716 ((or (org-at-item-p)
14717 (and (org-region-active-p)
14718 (save-excursion
14719 (goto-char (region-beginning))
14720 (org-at-item-p))))
14721 (call-interactively 'org-indent-item))
14722 (t (call-interactively 'forward-word))))
14724 (defun org-metaup (&optional arg)
14725 "Move subtree up or move table row up.
14726 Calls `org-move-subtree-up' or `org-table-move-row' or
14727 `org-move-item-up', depending on context. See the individual commands
14728 for more information."
14729 (interactive "P")
14730 (cond
14731 ((run-hook-with-args-until-success 'org-metaup-hook))
14732 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14733 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14734 ((org-at-item-p) (call-interactively 'org-move-item-up))
14735 (t (transpose-lines 1) (beginning-of-line -1))))
14737 (defun org-metadown (&optional arg)
14738 "Move subtree down or move table row down.
14739 Calls `org-move-subtree-down' or `org-table-move-row' or
14740 `org-move-item-down', depending on context. See the individual
14741 commands for more information."
14742 (interactive "P")
14743 (cond
14744 ((run-hook-with-args-until-success 'org-metadown-hook))
14745 ((org-at-table-p) (call-interactively 'org-table-move-row))
14746 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14747 ((org-at-item-p) (call-interactively 'org-move-item-down))
14748 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14750 (defun org-shiftup (&optional arg)
14751 "Increase item in timestamp or increase priority of current headline.
14752 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14753 depending on context. See the individual commands for more information."
14754 (interactive "P")
14755 (cond
14756 ((and org-support-shift-select (org-region-active-p))
14757 (org-call-for-shift-select 'previous-line))
14758 ((org-at-timestamp-p t)
14759 (call-interactively (if org-edit-timestamp-down-means-later
14760 'org-timestamp-down 'org-timestamp-up)))
14761 ((and (not (eq org-support-shift-select 'always))
14762 org-enable-priority-commands
14763 (org-on-heading-p))
14764 (call-interactively 'org-priority-up))
14765 ((and (not org-support-shift-select) (org-at-item-p))
14766 (call-interactively 'org-previous-item))
14767 ((org-clocktable-try-shift 'up arg))
14768 (org-support-shift-select
14769 (org-call-for-shift-select 'previous-line))
14770 (t (org-shiftselect-error))))
14772 (defun org-shiftdown (&optional arg)
14773 "Decrease item in timestamp or decrease priority of current headline.
14774 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14775 depending on context. See the individual commands for more information."
14776 (interactive "P")
14777 (cond
14778 ((and org-support-shift-select (org-region-active-p))
14779 (org-call-for-shift-select 'next-line))
14780 ((org-at-timestamp-p t)
14781 (call-interactively (if org-edit-timestamp-down-means-later
14782 'org-timestamp-up 'org-timestamp-down)))
14783 ((and (not (eq org-support-shift-select 'always))
14784 org-enable-priority-commands
14785 (org-on-heading-p))
14786 (call-interactively 'org-priority-down))
14787 ((and (not org-support-shift-select) (org-at-item-p))
14788 (call-interactively 'org-next-item))
14789 ((org-clocktable-try-shift 'down arg))
14790 (org-support-shift-select
14791 (org-call-for-shift-select 'next-line))
14792 (t (org-shiftselect-error))))
14794 (defun org-shiftright (&optional arg)
14795 "Cycle the thing at point or in the current line, depending on context.
14796 Depending on context, this does one of the following:
14798 - switch a timestamp at point one day into the future
14799 - on a headline, switch to the next TODO keyword.
14800 - on an item, switch entire list to the next bullet type
14801 - on a property line, switch to the next allowed value
14802 - on a clocktable definition line, move time block into the future"
14803 (interactive "P")
14804 (cond
14805 ((and org-support-shift-select (org-region-active-p))
14806 (org-call-for-shift-select 'forward-char))
14807 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14808 ((and (not (eq org-support-shift-select 'always))
14809 (org-on-heading-p))
14810 (let ((org-inhibit-logging
14811 (not org-treat-S-cursor-todo-selection-as-state-change))
14812 (org-inhibit-blocking
14813 (not org-treat-S-cursor-todo-selection-as-state-change)))
14814 (org-call-with-arg 'org-todo 'right)))
14815 ((or (and org-support-shift-select
14816 (not (eq org-support-shift-select 'always))
14817 (org-at-item-bullet-p))
14818 (and (not org-support-shift-select) (org-at-item-p)))
14819 (org-call-with-arg 'org-cycle-list-bullet nil))
14820 ((and (not (eq org-support-shift-select 'always))
14821 (org-at-property-p))
14822 (call-interactively 'org-property-next-allowed-value))
14823 ((org-clocktable-try-shift 'right arg))
14824 (org-support-shift-select
14825 (org-call-for-shift-select 'forward-char))
14826 (t (org-shiftselect-error))))
14828 (defun org-shiftleft (&optional arg)
14829 "Cycle the thing at point or in the current line, depending on context.
14830 Depending on context, this does one of the following:
14832 - switch a timestamp at point one day into the past
14833 - on a headline, switch to the previous TODO keyword.
14834 - on an item, switch entire list to the previous bullet type
14835 - on a property line, switch to the previous allowed value
14836 - on a clocktable definition line, move time block into the past"
14837 (interactive "P")
14838 (cond
14839 ((and org-support-shift-select (org-region-active-p))
14840 (org-call-for-shift-select 'backward-char))
14841 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14842 ((and (not (eq org-support-shift-select 'always))
14843 (org-on-heading-p))
14844 (let ((org-inhibit-logging
14845 (not org-treat-S-cursor-todo-selection-as-state-change))
14846 (org-inhibit-blocking
14847 (not org-treat-S-cursor-todo-selection-as-state-change)))
14848 (org-call-with-arg 'org-todo 'left)))
14849 ((or (and org-support-shift-select
14850 (not (eq org-support-shift-select 'always))
14851 (org-at-item-bullet-p))
14852 (and (not org-support-shift-select) (org-at-item-p)))
14853 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14854 ((and (not (eq org-support-shift-select 'always))
14855 (org-at-property-p))
14856 (call-interactively 'org-property-previous-allowed-value))
14857 ((org-clocktable-try-shift 'left arg))
14858 (org-support-shift-select
14859 (org-call-for-shift-select 'backward-char))
14860 (t (org-shiftselect-error))))
14862 (defun org-shiftcontrolright ()
14863 "Switch to next TODO set."
14864 (interactive)
14865 (cond
14866 ((and org-support-shift-select (org-region-active-p))
14867 (org-call-for-shift-select 'forward-word))
14868 ((and (not (eq org-support-shift-select 'always))
14869 (org-on-heading-p))
14870 (org-call-with-arg 'org-todo 'nextset))
14871 (org-support-shift-select
14872 (org-call-for-shift-select 'forward-word))
14873 (t (org-shiftselect-error))))
14875 (defun org-shiftcontrolleft ()
14876 "Switch to previous TODO set."
14877 (interactive)
14878 (cond
14879 ((and org-support-shift-select (org-region-active-p))
14880 (org-call-for-shift-select 'backward-word))
14881 ((and (not (eq org-support-shift-select 'always))
14882 (org-on-heading-p))
14883 (org-call-with-arg 'org-todo 'previousset))
14884 (org-support-shift-select
14885 (org-call-for-shift-select 'backward-word))
14886 (t (org-shiftselect-error))))
14888 (defun org-ctrl-c-ret ()
14889 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14890 (interactive)
14891 (cond
14892 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14893 (t (call-interactively 'org-insert-heading))))
14895 (defun org-copy-special ()
14896 "Copy region in table or copy current subtree.
14897 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14898 See the individual commands for more information."
14899 (interactive)
14900 (call-interactively
14901 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14903 (defun org-cut-special ()
14904 "Cut region in table or cut current subtree.
14905 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14906 See the individual commands for more information."
14907 (interactive)
14908 (call-interactively
14909 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14911 (defun org-paste-special (arg)
14912 "Paste rectangular region into table, or past subtree relative to level.
14913 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14914 See the individual commands for more information."
14915 (interactive "P")
14916 (if (org-at-table-p)
14917 (org-table-paste-rectangle)
14918 (org-paste-subtree arg)))
14920 (defun org-edit-special ()
14921 "Call a special editor for the stuff at point.
14922 When at a table, call the formula editor with `org-table-edit-formulas'.
14923 When at the first line of an src example, call `org-edit-src-code'.
14924 When in an #+include line, visit the include file. Otherwise call
14925 `ffap' to visit the file at point."
14926 (interactive)
14927 (cond
14928 ((org-at-table-p)
14929 (call-interactively 'org-table-edit-formulas))
14930 ((save-excursion
14931 (beginning-of-line 1)
14932 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14933 (find-file (org-trim (match-string 1))))
14934 ((org-edit-src-code))
14935 ((org-edit-fixed-width-region))
14936 (t (call-interactively 'ffap))))
14939 (defun org-ctrl-c-ctrl-c (&optional arg)
14940 "Set tags in headline, or update according to changed information at point.
14942 This command does many different things, depending on context:
14944 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14945 this is what we do.
14947 - If the cursor is on a statistics cookie, update it.
14949 - If the cursor is in a headline, prompt for tags and insert them
14950 into the current line, aligned to `org-tags-column'. When called
14951 with prefix arg, realign all tags in the current buffer.
14953 - If the cursor is in one of the special #+KEYWORD lines, this
14954 triggers scanning the buffer for these lines and updating the
14955 information.
14957 - If the cursor is inside a table, realign the table. This command
14958 works even if the automatic table editor has been turned off.
14960 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14961 the entire table.
14963 - If the cursor is at a footnote reference or definition, jump to
14964 the corresponding definition or references, respectively.
14966 - If the cursor is a the beginning of a dynamic block, update it.
14968 - If the cursor is inside a table created by the table.el package,
14969 activate that table.
14971 - If the current buffer is a remember buffer, close note and file
14972 it. A prefix argument of 1 files to the default location
14973 without further interaction. A prefix argument of 2 files to
14974 the currently clocking task.
14976 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14977 links in this buffer.
14979 - If the cursor is on a numbered item in a plain list, renumber the
14980 ordered list.
14982 - If the cursor is on a checkbox, toggle it."
14983 (interactive "P")
14984 (let ((org-enable-table-editor t))
14985 (cond
14986 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14987 org-occur-highlights
14988 org-latex-fragment-image-overlays)
14989 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14990 (org-remove-occur-highlights)
14991 (org-remove-latex-fragment-image-overlays)
14992 (message "Temporary highlights/overlays removed from current buffer"))
14993 ((and (local-variable-p 'org-finish-function (current-buffer))
14994 (fboundp org-finish-function))
14995 (funcall org-finish-function))
14996 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14997 ((org-at-property-p)
14998 (call-interactively 'org-property-action))
14999 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15000 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15001 (or (org-on-heading-p) (org-at-item-p)))
15002 (call-interactively 'org-update-statistics-cookies))
15003 ((org-on-heading-p) (call-interactively 'org-set-tags))
15004 ((org-at-table.el-p)
15005 (require 'table)
15006 (beginning-of-line 1)
15007 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15008 (call-interactively 'table-recognize-table))
15009 ((org-at-table-p)
15010 (org-table-maybe-eval-formula)
15011 (if arg
15012 (call-interactively 'org-table-recalculate)
15013 (org-table-maybe-recalculate-line))
15014 (call-interactively 'org-table-align))
15015 ((or (org-footnote-at-reference-p)
15016 (org-footnote-at-definition-p))
15017 (call-interactively 'org-footnote-action))
15018 ((org-at-item-checkbox-p)
15019 (call-interactively 'org-toggle-checkbox))
15020 ((org-at-item-p)
15021 (if arg
15022 (call-interactively 'org-toggle-checkbox)
15023 (call-interactively 'org-maybe-renumber-ordered-list)))
15024 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
15025 ;; Dynamic block
15026 (beginning-of-line 1)
15027 (save-excursion (org-update-dblock)))
15028 ((save-excursion
15029 (beginning-of-line 1)
15030 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15031 (cond
15032 ((equal (match-string 1) "TBLFM")
15033 ;; Recalculate the table before this line
15034 (save-excursion
15035 (beginning-of-line 1)
15036 (skip-chars-backward " \r\n\t")
15037 (if (org-at-table-p)
15038 (org-call-with-arg 'org-table-recalculate t))))
15040 ; (org-set-regexps-and-options)
15041 ; (org-restart-font-lock)
15042 (let ((org-inhibit-startup t)) (org-mode-restart))
15043 (message "Local setup has been refreshed"))))
15044 ((org-clock-update-time-maybe))
15045 (t (error "C-c C-c can do nothing useful at this location.")))))
15047 (defun org-mode-restart ()
15048 "Restart Org-mode, to scan again for special lines.
15049 Also updates the keyword regular expressions."
15050 (interactive)
15051 (org-mode)
15052 (message "Org-mode restarted"))
15054 (defun org-kill-note-or-show-branches ()
15055 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15056 (interactive)
15057 (if (not org-finish-function)
15058 (call-interactively 'show-branches)
15059 (let ((org-note-abort t))
15060 (funcall org-finish-function))))
15062 (defun org-return (&optional indent)
15063 "Goto next table row or insert a newline.
15064 Calls `org-table-next-row' or `newline', depending on context.
15065 See the individual commands for more information."
15066 (interactive)
15067 (cond
15068 ((bobp) (if indent (newline-and-indent) (newline)))
15069 ((org-at-table-p)
15070 (org-table-justify-field-maybe)
15071 (call-interactively 'org-table-next-row))
15072 ((and org-return-follows-link
15073 (eq (get-text-property (point) 'face) 'org-link))
15074 (call-interactively 'org-open-at-point))
15075 ((and (org-at-heading-p)
15076 (looking-at
15077 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15078 (org-show-entry)
15079 (end-of-line 1)
15080 (newline))
15081 (t (if indent (newline-and-indent) (newline)))))
15083 (defun org-return-indent ()
15084 "Goto next table row or insert a newline and indent.
15085 Calls `org-table-next-row' or `newline-and-indent', depending on
15086 context. See the individual commands for more information."
15087 (interactive)
15088 (org-return t))
15090 (defun org-ctrl-c-star ()
15091 "Compute table, or change heading status of lines.
15092 Calls `org-table-recalculate' or `org-toggle-heading',
15093 depending on context."
15094 (interactive)
15095 (cond
15096 ((org-at-table-p)
15097 (call-interactively 'org-table-recalculate))
15099 ;; Convert all lines in region to list items
15100 (call-interactively 'org-toggle-heading))))
15102 (defun org-ctrl-c-minus ()
15103 "Insert separator line in table or modify bullet status of line.
15104 Also turns a plain line or a region of lines into list items.
15105 Calls `org-table-insert-hline', `org-toggle-item', or
15106 `org-cycle-list-bullet', depending on context."
15107 (interactive)
15108 (cond
15109 ((org-at-table-p)
15110 (call-interactively 'org-table-insert-hline))
15111 ((org-region-active-p)
15112 (call-interactively 'org-toggle-item))
15113 ((org-in-item-p)
15114 (call-interactively 'org-cycle-list-bullet))
15116 (call-interactively 'org-toggle-item))))
15118 (defun org-toggle-item ()
15119 "Convert headings or normal lines to items, items to normal lines.
15120 If there is no active region, only the current line is considered.
15122 If the first line in the region is a headline, convert all headlines to items.
15124 If the first line in the region is an item, convert all items to normal lines.
15126 If the first line is normal text, add an item bullet to each line."
15127 (interactive)
15128 (let (l2 l beg end)
15129 (if (org-region-active-p)
15130 (setq beg (region-beginning) end (region-end))
15131 (setq beg (point-at-bol)
15132 end (min (1+ (point-at-eol)) (point-max))))
15133 (save-excursion
15134 (goto-char end)
15135 (setq l2 (org-current-line))
15136 (goto-char beg)
15137 (beginning-of-line 1)
15138 (setq l (1- (org-current-line)))
15139 (if (org-at-item-p)
15140 ;; We already have items, de-itemize
15141 (while (< (setq l (1+ l)) l2)
15142 (when (org-at-item-p)
15143 (goto-char (match-beginning 2))
15144 (delete-region (match-beginning 2) (match-end 2))
15145 (and (looking-at "[ \t]+") (replace-match "")))
15146 (beginning-of-line 2))
15147 (if (org-on-heading-p)
15148 ;; Headings, convert to items
15149 (while (< (setq l (1+ l)) l2)
15150 (if (looking-at org-outline-regexp)
15151 (replace-match "- " t t))
15152 (beginning-of-line 2))
15153 ;; normal lines, turn them into items
15154 (while (< (setq l (1+ l)) l2)
15155 (unless (org-at-item-p)
15156 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15157 (replace-match "\\1- \\2")))
15158 (beginning-of-line 2)))))))
15160 (defun org-toggle-heading (&optional nstars)
15161 "Convert headings to normal text, or items or text to headings.
15162 If there is no active region, only the current line is considered.
15164 If the first line is a heading, remove the stars from all headlines
15165 in the region.
15167 If the first line is a plain list item, turn all plain list items
15168 into headings.
15170 If the first line is a normal line, turn each and every line in the
15171 region into a heading.
15173 When converting a line into a heading, the number of stars is chosen
15174 such that the lines become children of the current entry. However,
15175 when a prefix argument is given, its value determines the number of
15176 stars to add."
15177 (interactive "P")
15178 (let (l2 l itemp beg end)
15179 (if (org-region-active-p)
15180 (setq beg (region-beginning) end (region-end))
15181 (setq beg (point-at-bol)
15182 end (min (1+ (point-at-eol)) (point-max))))
15183 (save-excursion
15184 (goto-char end)
15185 (setq l2 (org-current-line))
15186 (goto-char beg)
15187 (beginning-of-line 1)
15188 (setq l (1- (org-current-line)))
15189 (if (org-on-heading-p)
15190 ;; We already have headlines, de-star them
15191 (while (< (setq l (1+ l)) l2)
15192 (when (org-on-heading-p t)
15193 (and (looking-at outline-regexp) (replace-match "")))
15194 (beginning-of-line 2))
15195 (setq itemp (org-at-item-p))
15196 (let* ((stars
15197 (if nstars
15198 (make-string (prefix-numeric-value current-prefix-arg)
15200 (save-excursion
15201 (if (re-search-backward org-complex-heading-regexp nil t)
15202 (match-string 1) ""))))
15203 (add-stars (cond (nstars "")
15204 ((equal stars "") "*")
15205 (org-odd-levels-only "**")
15206 (t "*")))
15207 (rpl (concat stars add-stars " ")))
15208 (while (< (setq l (1+ l)) l2)
15209 (if itemp
15210 (and (org-at-item-p) (replace-match rpl t t))
15211 (unless (org-on-heading-p)
15212 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15213 (replace-match (concat rpl (match-string 2))))))
15214 (beginning-of-line 2)))))))
15216 (defun org-meta-return (&optional arg)
15217 "Insert a new heading or wrap a region in a table.
15218 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15219 See the individual commands for more information."
15220 (interactive "P")
15221 (cond
15222 ((run-hook-with-args-until-success 'org-metareturn-hook))
15223 ((org-at-table-p)
15224 (call-interactively 'org-table-wrap-region))
15225 (t (call-interactively 'org-insert-heading))))
15227 ;;; Menu entries
15229 ;; Define the Org-mode menus
15230 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15231 '("Tbl"
15232 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15233 ["Next Field" org-cycle (org-at-table-p)]
15234 ["Previous Field" org-shifttab (org-at-table-p)]
15235 ["Next Row" org-return (org-at-table-p)]
15236 "--"
15237 ["Blank Field" org-table-blank-field (org-at-table-p)]
15238 ["Edit Field" org-table-edit-field (org-at-table-p)]
15239 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15240 "--"
15241 ("Column"
15242 ["Move Column Left" org-metaleft (org-at-table-p)]
15243 ["Move Column Right" org-metaright (org-at-table-p)]
15244 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15245 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15246 ("Row"
15247 ["Move Row Up" org-metaup (org-at-table-p)]
15248 ["Move Row Down" org-metadown (org-at-table-p)]
15249 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15250 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15251 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15252 "--"
15253 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15254 ("Rectangle"
15255 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15256 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15257 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15258 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15259 "--"
15260 ("Calculate"
15261 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15262 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15263 ["Edit Formulas" org-edit-special (org-at-table-p)]
15264 "--"
15265 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15266 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15267 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15268 "--"
15269 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15270 "--"
15271 ["Sum Column/Rectangle" org-table-sum
15272 (or (org-at-table-p) (org-region-active-p))]
15273 ["Which Column?" org-table-current-column (org-at-table-p)])
15274 ["Debug Formulas"
15275 org-table-toggle-formula-debugger
15276 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15277 ["Show Col/Row Numbers"
15278 org-table-toggle-coordinate-overlays
15279 :style toggle
15280 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15281 "--"
15282 ["Create" org-table-create (and (not (org-at-table-p))
15283 org-enable-table-editor)]
15284 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15285 ["Import from File" org-table-import (not (org-at-table-p))]
15286 ["Export to File" org-table-export (org-at-table-p)]
15287 "--"
15288 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15290 (easy-menu-define org-org-menu org-mode-map "Org menu"
15291 '("Org"
15292 ("Show/Hide"
15293 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15294 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15295 ["Sparse Tree..." org-sparse-tree t]
15296 ["Reveal Context" org-reveal t]
15297 ["Show All" show-all t]
15298 "--"
15299 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15300 "--"
15301 ["New Heading" org-insert-heading t]
15302 ("Navigate Headings"
15303 ["Up" outline-up-heading t]
15304 ["Next" outline-next-visible-heading t]
15305 ["Previous" outline-previous-visible-heading t]
15306 ["Next Same Level" outline-forward-same-level t]
15307 ["Previous Same Level" outline-backward-same-level t]
15308 "--"
15309 ["Jump" org-goto t])
15310 ("Edit Structure"
15311 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15312 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15313 "--"
15314 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15315 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15316 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15317 "--"
15318 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15319 "--"
15320 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15321 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15322 ["Demote Heading" org-metaright (not (org-at-table-p))]
15323 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15324 "--"
15325 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15326 "--"
15327 ["Convert to odd levels" org-convert-to-odd-levels t]
15328 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15329 ("Editing"
15330 ["Emphasis..." org-emphasize t]
15331 ["Edit Source Example" org-edit-special t]
15332 "--"
15333 ["Footnote new/jump" org-footnote-action t]
15334 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15335 ("Archive"
15336 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15337 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15338 ; :active t :keys "C-u C-c C-x C-a"]
15339 ["Sparse trees open ARCHIVE trees"
15340 (setq org-sparse-tree-open-archived-trees
15341 (not org-sparse-tree-open-archived-trees))
15342 :style toggle :selected org-sparse-tree-open-archived-trees]
15343 ["Cycling opens ARCHIVE trees"
15344 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15345 :style toggle :selected org-cycle-open-archived-trees]
15346 "--"
15347 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15348 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15349 ; ["Check and Move Children" (org-archive-subtree '(4))
15350 ; :active t :keys "C-u C-c C-x C-s"]
15352 "--"
15353 ("Hyperlinks"
15354 ["Store Link (Global)" org-store-link t]
15355 ["Find existing link to here" org-occur-link-in-agenda-files t]
15356 ["Insert Link" org-insert-link t]
15357 ["Follow Link" org-open-at-point t]
15358 "--"
15359 ["Next link" org-next-link t]
15360 ["Previous link" org-previous-link t]
15361 "--"
15362 ["Descriptive Links"
15363 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15364 :style radio
15365 :selected (member '(org-link) buffer-invisibility-spec)]
15366 ["Literal Links"
15367 (progn
15368 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15369 :style radio
15370 :selected (not (member '(org-link) buffer-invisibility-spec))])
15371 "--"
15372 ("TODO Lists"
15373 ["TODO/DONE/-" org-todo t]
15374 ("Select keyword"
15375 ["Next keyword" org-shiftright (org-on-heading-p)]
15376 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15377 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15378 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15379 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15380 ["Show TODO Tree" org-show-todo-tree t]
15381 ["Global TODO list" org-todo-list t]
15382 "--"
15383 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15384 :selected org-enforce-todo-dependencies :style toggle :active t]
15385 "Settings for tree at point"
15386 ["Do Children sequentially" org-toggle-ordered-property :style radio
15387 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15388 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15389 ["Do Children parallel" org-toggle-ordered-property :style radio
15390 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15391 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15392 "--"
15393 ["Set Priority" org-priority t]
15394 ["Priority Up" org-shiftup t]
15395 ["Priority Down" org-shiftdown t]
15396 "--"
15397 ["Get news from all feeds" org-feed-update-all t]
15398 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15399 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15400 ("TAGS and Properties"
15401 ["Set Tags" org-set-tags-command t]
15402 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15403 "--"
15404 ["Set property" org-set-property t]
15405 ["Column view of properties" org-columns t]
15406 ["Insert Column View DBlock" org-insert-columns-dblock t])
15407 ("Dates and Scheduling"
15408 ["Timestamp" org-time-stamp t]
15409 ["Timestamp (inactive)" org-time-stamp-inactive t]
15410 ("Change Date"
15411 ["1 Day Later" org-shiftright t]
15412 ["1 Day Earlier" org-shiftleft t]
15413 ["1 ... Later" org-shiftup t]
15414 ["1 ... Earlier" org-shiftdown t])
15415 ["Compute Time Range" org-evaluate-time-range t]
15416 ["Schedule Item" org-schedule t]
15417 ["Deadline" org-deadline t]
15418 "--"
15419 ["Custom time format" org-toggle-time-stamp-overlays
15420 :style radio :selected org-display-custom-times]
15421 "--"
15422 ["Goto Calendar" org-goto-calendar t]
15423 ["Date from Calendar" org-date-from-calendar t]
15424 "--"
15425 ["Start/Restart Timer" org-timer-start t]
15426 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15427 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15428 ["Insert Timer String" org-timer t]
15429 ["Insert Timer Item" org-timer-item t])
15430 ("Logging work"
15431 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15432 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15433 ["Clock out" org-clock-out t]
15434 ["Clock cancel" org-clock-cancel t]
15435 "--"
15436 ["Mark as default task" org-clock-mark-default-task t]
15437 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15438 ["Goto running clock" org-clock-goto t]
15439 "--"
15440 ["Display times" org-clock-display t]
15441 ["Create clock table" org-clock-report t]
15442 "--"
15443 ["Record DONE time"
15444 (progn (setq org-log-done (not org-log-done))
15445 (message "Switching to %s will %s record a timestamp"
15446 (car org-done-keywords)
15447 (if org-log-done "automatically" "not")))
15448 :style toggle :selected org-log-done])
15449 "--"
15450 ["Agenda Command..." org-agenda t]
15451 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15452 ("File List for Agenda")
15453 ("Special views current file"
15454 ["TODO Tree" org-show-todo-tree t]
15455 ["Check Deadlines" org-check-deadlines t]
15456 ["Timeline" org-timeline t]
15457 ["Tags/Property tree" org-match-sparse-tree t])
15458 "--"
15459 ["Export/Publish..." org-export t]
15460 ("LaTeX"
15461 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15462 :selected org-cdlatex-mode]
15463 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15464 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15465 ["Modify math symbol" org-cdlatex-math-modify
15466 (org-inside-LaTeX-fragment-p)]
15467 ["Insert citation" org-reftex-citation t]
15468 "--"
15469 ["Export LaTeX fragments as images"
15470 (if (featurep 'org-exp)
15471 (setq org-export-with-LaTeX-fragments
15472 (not org-export-with-LaTeX-fragments))
15473 (require 'org-exp))
15474 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15475 org-export-with-LaTeX-fragments)])
15476 "--"
15477 ("Documentation"
15478 ["Show Version" org-version t]
15479 ["Info Documentation" org-info t])
15480 ("Customize"
15481 ["Browse Org Group" org-customize t]
15482 "--"
15483 ["Expand This Menu" org-create-customize-menu
15484 (fboundp 'customize-menu-create)])
15485 ["Send bug report" org-submit-bug-report t]
15486 "--"
15487 ("Refresh/Reload"
15488 ["Refresh setup current buffer" org-mode-restart t]
15489 ["Reload Org (after update)" org-reload t]
15490 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15493 (defun org-info (&optional node)
15494 "Read documentation for Org-mode in the info system.
15495 With optional NODE, go directly to that node."
15496 (interactive)
15497 (info (format "(org)%s" (or node ""))))
15499 ;;;###autoload
15500 (defun org-submit-bug-report ()
15501 "Submit a bug report on Org-mode via mail.
15503 Don't hesitate to report any problems or inaccurate documentation.
15505 If you don't have setup sending mail from (X)Emacs, please copy the
15506 output buffer into your mail program, as it gives us important
15507 information about your Org-mode version and configuration."
15508 (interactive)
15509 (require 'reporter)
15510 (org-load-modules-maybe)
15511 (org-require-autoloaded-modules)
15512 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15513 (reporter-submit-bug-report
15514 "emacs-orgmode@gnu.org"
15515 (org-version)
15516 (let (list)
15517 (save-window-excursion
15518 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15519 (delete-other-windows)
15520 (erase-buffer)
15521 (insert "You are about to submit a bug report to the Org-mode mailing list.
15523 We would like to add your full Org-mode and Outline configuration to the
15524 bug report. This greatly simplifies the work of the maintainer and
15525 other experts on the mailing list.
15527 HOWEVER, some variables you have customized may contain private
15528 information. The names of customers, colleagues, or friends, might
15529 appear in the form of file names, tags, todo states, or search strings.
15530 If you answer yes to the prompt, you might want to check and remove
15531 such private information before sending the email.")
15532 (add-text-properties (point-min) (point-max) '(face org-warning))
15533 (when (yes-or-no-p "Include your Org-mode configuration ")
15534 (mapatoms
15535 (lambda (v)
15536 (and (boundp v)
15537 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15538 (or (and (symbol-value v)
15539 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15540 (and
15541 (get v 'custom-type) (get v 'standard-value)
15542 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15543 (push v list)))))
15544 (kill-buffer (get-buffer "*Warn about privacy*"))
15545 list))
15546 nil nil
15547 "Remember to cover the basics, that is, what you expected to happen and
15548 what in fact did happen. You don't know how to make a good report? See
15550 http://orgmode.org/manual/Feedback.html#Feedback
15552 Your bug report will be posted to the Org-mode mailing list.
15553 ------------------------------------------------------------------------")))
15555 (defun org-install-agenda-files-menu ()
15556 (let ((bl (buffer-list)))
15557 (save-excursion
15558 (while bl
15559 (set-buffer (pop bl))
15560 (if (org-mode-p) (setq bl nil)))
15561 (when (org-mode-p)
15562 (easy-menu-change
15563 '("Org") "File List for Agenda"
15564 (append
15565 (list
15566 ["Edit File List" (org-edit-agenda-file-list) t]
15567 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15568 ["Remove Current File from List" org-remove-file t]
15569 ["Cycle through agenda files" org-cycle-agenda-files t]
15570 ["Occur in all agenda files" org-occur-in-agenda-files t]
15571 "--")
15572 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15574 ;;;; Documentation
15576 ;;;###autoload
15577 (defun org-require-autoloaded-modules ()
15578 (interactive)
15579 (mapc 'require
15580 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15581 org-docbook org-exp org-html org-icalendar
15582 org-id org-latex
15583 org-publish org-remember org-table
15584 org-timer org-xoxo)))
15586 ;;;###autoload
15587 (defun org-reload (&optional uncompiled)
15588 "Reload all org lisp files.
15589 With prefix arg UNCOMPILED, load the uncompiled versions."
15590 (interactive "P")
15591 (require 'find-func)
15592 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15593 (dir-org (file-name-directory (org-find-library-name "org")))
15594 (dir-org-contrib (ignore-errors
15595 (file-name-directory
15596 (org-find-library-name "org-contribdir"))))
15597 (files
15598 (append (directory-files dir-org t file-re)
15599 (and dir-org-contrib
15600 (directory-files dir-org-contrib t file-re))))
15601 (remove-re (concat (if (featurep 'xemacs)
15602 "org-colview" "org-colview-xemacs")
15603 "\\'")))
15604 (setq files (mapcar 'file-name-sans-extension files))
15605 (setq files (mapcar
15606 (lambda (x) (if (string-match remove-re x) nil x))
15607 files))
15608 (setq files (delq nil files))
15609 (mapc
15610 (lambda (f)
15611 (when (featurep (intern (file-name-nondirectory f)))
15612 (if (and (not uncompiled)
15613 (file-exists-p (concat f ".elc")))
15614 (load (concat f ".elc") nil nil t)
15615 (load (concat f ".el") nil nil t))))
15616 files))
15617 (org-version))
15619 ;;;###autoload
15620 (defun org-customize ()
15621 "Call the customize function with org as argument."
15622 (interactive)
15623 (org-load-modules-maybe)
15624 (org-require-autoloaded-modules)
15625 (customize-browse 'org))
15627 (defun org-create-customize-menu ()
15628 "Create a full customization menu for Org-mode, insert it into the menu."
15629 (interactive)
15630 (org-load-modules-maybe)
15631 (org-require-autoloaded-modules)
15632 (if (fboundp 'customize-menu-create)
15633 (progn
15634 (easy-menu-change
15635 '("Org") "Customize"
15636 `(["Browse Org group" org-customize t]
15637 "--"
15638 ,(customize-menu-create 'org)
15639 ["Set" Custom-set t]
15640 ["Save" Custom-save t]
15641 ["Reset to Current" Custom-reset-current t]
15642 ["Reset to Saved" Custom-reset-saved t]
15643 ["Reset to Standard Settings" Custom-reset-standard t]))
15644 (message "\"Org\"-menu now contains full customization menu"))
15645 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15647 ;;;; Miscellaneous stuff
15649 ;;; Generally useful functions
15651 (defun org-find-text-property-in-string (prop s)
15652 "Return the first non-nil value of property PROP in string S."
15653 (or (get-text-property 0 prop s)
15654 (get-text-property (or (next-single-property-change 0 prop s) 0)
15655 prop s)))
15657 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15658 "Display the given MESSAGE as a warning."
15659 (if (fboundp 'display-warning)
15660 (display-warning 'org message
15661 (if (featurep 'xemacs)
15662 'warning
15663 :warning))
15664 (let ((buf (get-buffer-create "*Org warnings*")))
15665 (with-current-buffer buf
15666 (goto-char (point-max))
15667 (insert "Warning (Org): " message)
15668 (unless (bolp)
15669 (newline)))
15670 (display-buffer buf)
15671 (sit-for 0))))
15673 (defun org-in-commented-line ()
15674 "Is point in a line starting with `#'?"
15675 (equal (char-after (point-at-bol)) ?#))
15677 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15678 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15679 (if (and marker (marker-buffer marker)
15680 (buffer-live-p (marker-buffer marker)))
15681 (progn
15682 (switch-to-buffer (marker-buffer marker))
15683 (if (or (> marker (point-max)) (< marker (point-min)))
15684 (widen))
15685 (goto-char marker)
15686 (org-show-context 'org-goto))
15687 (if bookmark
15688 (bookmark-jump bookmark)
15689 (error "Cannot find location"))))
15691 (defun org-quote-csv-field (s)
15692 "Quote field for inclusion in CSV material."
15693 (if (string-match "[\",]" s)
15694 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15697 (defun org-plist-delete (plist property)
15698 "Delete PROPERTY from PLIST.
15699 This is in contrast to merely setting it to 0."
15700 (let (p)
15701 (while plist
15702 (if (not (eq property (car plist)))
15703 (setq p (plist-put p (car plist) (nth 1 plist))))
15704 (setq plist (cddr plist)))
15707 (defun org-force-self-insert (N)
15708 "Needed to enforce self-insert under remapping."
15709 (interactive "p")
15710 (self-insert-command N))
15712 (defun org-string-width (s)
15713 "Compute width of string, ignoring invisible characters.
15714 This ignores character with invisibility property `org-link', and also
15715 characters with property `org-cwidth', because these will become invisible
15716 upon the next fontification round."
15717 (let (b l)
15718 (when (or (eq t buffer-invisibility-spec)
15719 (assq 'org-link buffer-invisibility-spec))
15720 (while (setq b (text-property-any 0 (length s)
15721 'invisible 'org-link s))
15722 (setq s (concat (substring s 0 b)
15723 (substring s (or (next-single-property-change
15724 b 'invisible s) (length s)))))))
15725 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15726 (setq s (concat (substring s 0 b)
15727 (substring s (or (next-single-property-change
15728 b 'org-cwidth s) (length s))))))
15729 (setq l (string-width s) b -1)
15730 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15731 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15734 (defun org-get-indentation (&optional line)
15735 "Get the indentation of the current line, interpreting tabs.
15736 When LINE is given, assume it represents a line and compute its indentation."
15737 (if line
15738 (if (string-match "^ *" (org-remove-tabs line))
15739 (match-end 0))
15740 (save-excursion
15741 (beginning-of-line 1)
15742 (skip-chars-forward " \t")
15743 (current-column))))
15745 (defun org-remove-tabs (s &optional width)
15746 "Replace tabulators in S with spaces.
15747 Assumes that s is a single line, starting in column 0."
15748 (setq width (or width tab-width))
15749 (while (string-match "\t" s)
15750 (setq s (replace-match
15751 (make-string
15752 (- (* width (/ (+ (match-beginning 0) width) width))
15753 (match-beginning 0)) ?\ )
15754 t t s)))
15757 (defun org-fix-indentation (line ind)
15758 "Fix indentation in LINE.
15759 IND is a cons cell with target and minimum indentation.
15760 If the current indentation in LINE is smaller than the minimum,
15761 leave it alone. If it is larger than ind, set it to the target."
15762 (let* ((l (org-remove-tabs line))
15763 (i (org-get-indentation l))
15764 (i1 (car ind)) (i2 (cdr ind)))
15765 (if (>= i i2) (setq l (substring line i2)))
15766 (if (> i1 0)
15767 (concat (make-string i1 ?\ ) l)
15768 l)))
15770 (defun org-remove-indentation (code &optional n)
15771 "Remove the maximum common indentation from the lines in CODE.
15772 N may optionally be the number of spaces to remove."
15773 (with-temp-buffer
15774 (insert code)
15775 (org-do-remove-indentation n)
15776 (buffer-string)))
15778 (defun org-do-remove-indentation (&optional n)
15779 "Remove the maximum common indentation from the buffer."
15780 (untabify (point-min) (point-max))
15781 (let ((min 10000) re)
15782 (if n
15783 (setq min n)
15784 (goto-char (point-min))
15785 (while (re-search-forward "^ *[^ \n]" nil t)
15786 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15787 (unless (or (= min 0) (= min 10000))
15788 (setq re (format "^ \\{%d\\}" min))
15789 (goto-char (point-min))
15790 (while (re-search-forward re nil t)
15791 (replace-match "")
15792 (end-of-line 1))
15793 min)))
15795 (defun org-base-buffer (buffer)
15796 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15797 (if (not buffer)
15798 buffer
15799 (or (buffer-base-buffer buffer)
15800 buffer)))
15802 (defun org-trim (s)
15803 "Remove whitespace at beginning and end of string."
15804 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15805 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15808 (defun org-wrap (string &optional width lines)
15809 "Wrap string to either a number of lines, or a width in characters.
15810 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15811 that costs. If there is a word longer than WIDTH, the text is actually
15812 wrapped to the length of that word.
15813 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15814 many lines, whatever width that takes.
15815 The return value is a list of lines, without newlines at the end."
15816 (let* ((words (org-split-string string "[ \t\n]+"))
15817 (maxword (apply 'max (mapcar 'org-string-width words)))
15818 w ll)
15819 (cond (width
15820 (org-do-wrap words (max maxword width)))
15821 (lines
15822 (setq w maxword)
15823 (setq ll (org-do-wrap words maxword))
15824 (if (<= (length ll) lines)
15826 (setq ll words)
15827 (while (> (length ll) lines)
15828 (setq w (1+ w))
15829 (setq ll (org-do-wrap words w)))
15830 ll))
15831 (t (error "Cannot wrap this")))))
15833 (defun org-do-wrap (words width)
15834 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15835 (let (lines line)
15836 (while words
15837 (setq line (pop words))
15838 (while (and words (< (+ (length line) (length (car words))) width))
15839 (setq line (concat line " " (pop words))))
15840 (setq lines (push line lines)))
15841 (nreverse lines)))
15843 (defun org-split-string (string &optional separators)
15844 "Splits STRING into substrings at SEPARATORS.
15845 No empty strings are returned if there are matches at the beginning
15846 and end of string."
15847 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15848 (start 0)
15849 notfirst
15850 (list nil))
15851 (while (and (string-match rexp string
15852 (if (and notfirst
15853 (= start (match-beginning 0))
15854 (< start (length string)))
15855 (1+ start) start))
15856 (< (match-beginning 0) (length string)))
15857 (setq notfirst t)
15858 (or (eq (match-beginning 0) 0)
15859 (and (eq (match-beginning 0) (match-end 0))
15860 (eq (match-beginning 0) start))
15861 (setq list
15862 (cons (substring string start (match-beginning 0))
15863 list)))
15864 (setq start (match-end 0)))
15865 (or (eq start (length string))
15866 (setq list
15867 (cons (substring string start)
15868 list)))
15869 (nreverse list)))
15871 (defun org-quote-vert (s)
15872 "Replace \"|\" with \"\\vert\"."
15873 (while (string-match "|" s)
15874 (setq s (replace-match "\\vert" t t s)))
15877 (defun org-uuidgen-p (s)
15878 "Is S an ID created by UUIDGEN?"
15879 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15881 (defun org-context ()
15882 "Return a list of contexts of the current cursor position.
15883 If several contexts apply, all are returned.
15884 Each context entry is a list with a symbol naming the context, and
15885 two positions indicating start and end of the context. Possible
15886 contexts are:
15888 :headline anywhere in a headline
15889 :headline-stars on the leading stars in a headline
15890 :todo-keyword on a TODO keyword (including DONE) in a headline
15891 :tags on the TAGS in a headline
15892 :priority on the priority cookie in a headline
15893 :item on the first line of a plain list item
15894 :item-bullet on the bullet/number of a plain list item
15895 :checkbox on the checkbox in a plain list item
15896 :table in an org-mode table
15897 :table-special on a special filed in a table
15898 :table-table in a table.el table
15899 :link on a hyperlink
15900 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15901 :target on a <<target>>
15902 :radio-target on a <<<radio-target>>>
15903 :latex-fragment on a LaTeX fragment
15904 :latex-preview on a LaTeX fragment with overlayed preview image
15906 This function expects the position to be visible because it uses font-lock
15907 faces as a help to recognize the following contexts: :table-special, :link,
15908 and :keyword."
15909 (let* ((f (get-text-property (point) 'face))
15910 (faces (if (listp f) f (list f)))
15911 (p (point)) clist o)
15912 ;; First the large context
15913 (cond
15914 ((org-on-heading-p t)
15915 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15916 (when (progn
15917 (beginning-of-line 1)
15918 (looking-at org-todo-line-tags-regexp))
15919 (push (org-point-in-group p 1 :headline-stars) clist)
15920 (push (org-point-in-group p 2 :todo-keyword) clist)
15921 (push (org-point-in-group p 4 :tags) clist))
15922 (goto-char p)
15923 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15924 (if (looking-at "\\[#[A-Z0-9]\\]")
15925 (push (org-point-in-group p 0 :priority) clist)))
15927 ((org-at-item-p)
15928 (push (org-point-in-group p 2 :item-bullet) clist)
15929 (push (list :item (point-at-bol)
15930 (save-excursion (org-end-of-item) (point)))
15931 clist)
15932 (and (org-at-item-checkbox-p)
15933 (push (org-point-in-group p 0 :checkbox) clist)))
15935 ((org-at-table-p)
15936 (push (list :table (org-table-begin) (org-table-end)) clist)
15937 (if (memq 'org-formula faces)
15938 (push (list :table-special
15939 (previous-single-property-change p 'face)
15940 (next-single-property-change p 'face)) clist)))
15941 ((org-at-table-p 'any)
15942 (push (list :table-table) clist)))
15943 (goto-char p)
15945 ;; Now the small context
15946 (cond
15947 ((org-at-timestamp-p)
15948 (push (org-point-in-group p 0 :timestamp) clist))
15949 ((memq 'org-link faces)
15950 (push (list :link
15951 (previous-single-property-change p 'face)
15952 (next-single-property-change p 'face)) clist))
15953 ((memq 'org-special-keyword faces)
15954 (push (list :keyword
15955 (previous-single-property-change p 'face)
15956 (next-single-property-change p 'face)) clist))
15957 ((org-on-target-p)
15958 (push (org-point-in-group p 0 :target) clist)
15959 (goto-char (1- (match-beginning 0)))
15960 (if (looking-at org-radio-target-regexp)
15961 (push (org-point-in-group p 0 :radio-target) clist))
15962 (goto-char p))
15963 ((setq o (car (delq nil
15964 (mapcar
15965 (lambda (x)
15966 (if (memq x org-latex-fragment-image-overlays) x))
15967 (org-overlays-at (point))))))
15968 (push (list :latex-fragment
15969 (org-overlay-start o) (org-overlay-end o)) clist)
15970 (push (list :latex-preview
15971 (org-overlay-start o) (org-overlay-end o)) clist))
15972 ((org-inside-LaTeX-fragment-p)
15973 ;; FIXME: positions wrong.
15974 (push (list :latex-fragment (point) (point)) clist)))
15976 (setq clist (nreverse (delq nil clist)))
15977 clist))
15979 ;; FIXME: Compare with at-regexp-p Do we need both?
15980 (defun org-in-regexp (re &optional nlines visually)
15981 "Check if point is inside a match of regexp.
15982 Normally only the current line is checked, but you can include NLINES extra
15983 lines both before and after point into the search.
15984 If VISUALLY is set, require that the cursor is not after the match but
15985 really on, so that the block visually is on the match."
15986 (catch 'exit
15987 (let ((pos (point))
15988 (eol (point-at-eol (+ 1 (or nlines 0))))
15989 (inc (if visually 1 0)))
15990 (save-excursion
15991 (beginning-of-line (- 1 (or nlines 0)))
15992 (while (re-search-forward re eol t)
15993 (if (and (<= (match-beginning 0) pos)
15994 (>= (+ inc (match-end 0)) pos))
15995 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15997 (defun org-at-regexp-p (regexp)
15998 "Is point inside a match of REGEXP in the current line?"
15999 (catch 'exit
16000 (save-excursion
16001 (let ((pos (point)) (end (point-at-eol)))
16002 (beginning-of-line 1)
16003 (while (re-search-forward regexp end t)
16004 (if (and (<= (match-beginning 0) pos)
16005 (>= (match-end 0) pos))
16006 (throw 'exit t)))
16007 nil))))
16009 (defun org-occur-in-agenda-files (regexp &optional nlines)
16010 "Call `multi-occur' with buffers for all agenda files."
16011 (interactive "sOrg-files matching: \np")
16012 (let* ((files (org-agenda-files))
16013 (tnames (mapcar 'file-truename files))
16014 (extra org-agenda-text-search-extra-files)
16016 (when (eq (car extra) 'agenda-archives)
16017 (setq extra (cdr extra))
16018 (setq files (org-add-archive-files files)))
16019 (while (setq f (pop extra))
16020 (unless (member (file-truename f) tnames)
16021 (add-to-list 'files f 'append)
16022 (add-to-list 'tnames (file-truename f) 'append)))
16023 (multi-occur
16024 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16025 regexp)))
16027 (if (boundp 'occur-mode-find-occurrence-hook)
16028 ;; Emacs 23
16029 (add-hook 'occur-mode-find-occurrence-hook
16030 (lambda ()
16031 (when (org-mode-p)
16032 (org-reveal))))
16033 ;; Emacs 22
16034 (defadvice occur-mode-goto-occurrence
16035 (after org-occur-reveal activate)
16036 (and (org-mode-p) (org-reveal)))
16037 (defadvice occur-mode-goto-occurrence-other-window
16038 (after org-occur-reveal activate)
16039 (and (org-mode-p) (org-reveal)))
16040 (defadvice occur-mode-display-occurrence
16041 (after org-occur-reveal activate)
16042 (when (org-mode-p)
16043 (let ((pos (occur-mode-find-occurrence)))
16044 (with-current-buffer (marker-buffer pos)
16045 (save-excursion
16046 (goto-char pos)
16047 (org-reveal)))))))
16049 (defun org-occur-link-in-agenda-files ()
16050 "Create a link and search for it in the agendas.
16051 The link is not stored in `org-stored-links', it is just created
16052 for the search purpose."
16053 (interactive)
16054 (let ((link (condition-case nil
16055 (org-store-link nil)
16056 (error "Unable to create a link to here"))))
16057 (org-occur-in-agenda-files (regexp-quote link))))
16059 (defun org-uniquify (list)
16060 "Remove duplicate elements from LIST."
16061 (let (res)
16062 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16063 res))
16065 (defun org-delete-all (elts list)
16066 "Remove all elements in ELTS from LIST."
16067 (while elts
16068 (setq list (delete (pop elts) list)))
16069 list)
16071 (defun org-back-over-empty-lines ()
16072 "Move backwards over whitespace, to the beginning of the first empty line.
16073 Returns the number of empty lines passed."
16074 (let ((pos (point)))
16075 (skip-chars-backward " \t\n\r")
16076 (beginning-of-line 2)
16077 (goto-char (min (point) pos))
16078 (count-lines (point) pos)))
16080 (defun org-skip-whitespace ()
16081 (skip-chars-forward " \t\n\r"))
16083 (defun org-point-in-group (point group &optional context)
16084 "Check if POINT is in match-group GROUP.
16085 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16086 match. If the match group does ot exist or point is not inside it,
16087 return nil."
16088 (and (match-beginning group)
16089 (>= point (match-beginning group))
16090 (<= point (match-end group))
16091 (if context
16092 (list context (match-beginning group) (match-end group))
16093 t)))
16095 (defun org-switch-to-buffer-other-window (&rest args)
16096 "Switch to buffer in a second window on the current frame.
16097 In particular, do not allow pop-up frames."
16098 (let (pop-up-frames special-display-buffer-names special-display-regexps
16099 special-display-function)
16100 (apply 'switch-to-buffer-other-window args)))
16102 (defun org-combine-plists (&rest plists)
16103 "Create a single property list from all plists in PLISTS.
16104 The process starts by copying the first list, and then setting properties
16105 from the other lists. Settings in the last list are the most significant
16106 ones and overrule settings in the other lists."
16107 (let ((rtn (copy-sequence (pop plists)))
16108 p v ls)
16109 (while plists
16110 (setq ls (pop plists))
16111 (while ls
16112 (setq p (pop ls) v (pop ls))
16113 (setq rtn (plist-put rtn p v))))
16114 rtn))
16116 (defun org-move-line-down (arg)
16117 "Move the current line down. With prefix argument, move it past ARG lines."
16118 (interactive "p")
16119 (let ((col (current-column))
16120 beg end pos)
16121 (beginning-of-line 1) (setq beg (point))
16122 (beginning-of-line 2) (setq end (point))
16123 (beginning-of-line (+ 1 arg))
16124 (setq pos (move-marker (make-marker) (point)))
16125 (insert (delete-and-extract-region beg end))
16126 (goto-char pos)
16127 (org-move-to-column col)))
16129 (defun org-move-line-up (arg)
16130 "Move the current line up. With prefix argument, move it past ARG lines."
16131 (interactive "p")
16132 (let ((col (current-column))
16133 beg end pos)
16134 (beginning-of-line 1) (setq beg (point))
16135 (beginning-of-line 2) (setq end (point))
16136 (beginning-of-line (- arg))
16137 (setq pos (move-marker (make-marker) (point)))
16138 (insert (delete-and-extract-region beg end))
16139 (goto-char pos)
16140 (org-move-to-column col)))
16142 (defun org-replace-escapes (string table)
16143 "Replace %-escapes in STRING with values in TABLE.
16144 TABLE is an association list with keys like \"%a\" and string values.
16145 The sequences in STRING may contain normal field width and padding information,
16146 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16147 so values can contain further %-escapes if they are define later in TABLE."
16148 (let ((case-fold-search nil)
16149 e re rpl)
16150 (while (setq e (pop table))
16151 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16152 (while (string-match re string)
16153 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16154 (cdr e)))
16155 (setq string (replace-match rpl t t string))))
16156 string))
16159 (defun org-sublist (list start end)
16160 "Return a section of LIST, from START to END.
16161 Counting starts at 1."
16162 (let (rtn (c start))
16163 (setq list (nthcdr (1- start) list))
16164 (while (and list (<= c end))
16165 (push (pop list) rtn)
16166 (setq c (1+ c)))
16167 (nreverse rtn)))
16169 (defun org-find-base-buffer-visiting (file)
16170 "Like `find-buffer-visiting' but always return the base buffer and
16171 not an indirect buffer."
16172 (let ((buf (or (get-file-buffer file)
16173 (find-buffer-visiting file))))
16174 (if buf
16175 (or (buffer-base-buffer buf) buf)
16176 nil)))
16178 (defun org-image-file-name-regexp (&optional extensions)
16179 "Return regexp matching the file names of images.
16180 If EXTENSIONS is given, only match these."
16181 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16182 (image-file-name-regexp)
16183 (let ((image-file-name-extensions
16184 (or extensions
16185 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16186 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16187 (concat "\\."
16188 (regexp-opt (nconc (mapcar 'upcase
16189 image-file-name-extensions)
16190 image-file-name-extensions)
16192 "\\'"))))
16194 (defun org-file-image-p (file &optional extensions)
16195 "Return non-nil if FILE is an image."
16196 (save-match-data
16197 (string-match (org-image-file-name-regexp extensions) file)))
16199 (defun org-get-cursor-date ()
16200 "Return the date at cursor in as a time.
16201 This works in the calendar and in the agenda, anywhere else it just
16202 returns the current time."
16203 (let (date day defd)
16204 (cond
16205 ((eq major-mode 'calendar-mode)
16206 (setq date (calendar-cursor-to-date)
16207 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16208 ((eq major-mode 'org-agenda-mode)
16209 (setq day (get-text-property (point) 'day))
16210 (if day
16211 (setq date (calendar-gregorian-from-absolute day)
16212 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16213 (nth 2 date))))))
16214 (or defd (current-time))))
16216 (defvar org-agenda-action-marker (make-marker)
16217 "Marker pointing to the entry for the next agenda action.")
16219 (defun org-mark-entry-for-agenda-action ()
16220 "Mark the current entry as target of an agenda action.
16221 Agenda actions are actions executed from the agenda with the key `k',
16222 which make use of the date at the cursor."
16223 (interactive)
16224 (move-marker org-agenda-action-marker
16225 (save-excursion (org-back-to-heading t) (point))
16226 (current-buffer))
16227 (message
16228 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16230 ;;; Paragraph filling stuff.
16231 ;; We want this to be just right, so use the full arsenal.
16233 (defun org-indent-line-function ()
16234 "Indent line like previous, but further if previous was headline or item."
16235 (interactive)
16236 (let* ((pos (point))
16237 (itemp (org-at-item-p))
16238 (case-fold-search t)
16239 (org-drawer-regexp (or org-drawer-regexp "\000"))
16240 column bpos bcol tpos tcol bullet btype bullet-type)
16241 ;; Find the previous relevant line
16242 (beginning-of-line 1)
16243 (cond
16244 ((looking-at "#") (setq column 0))
16245 ((looking-at "\\*+ ") (setq column 0))
16246 ((and (looking-at "[ \t]*:END:")
16247 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16248 (save-excursion
16249 (goto-char (1- (match-beginning 1)))
16250 (setq column (current-column))))
16251 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16252 (save-excursion
16253 (re-search-backward
16254 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16255 (setq column (org-get-indentation (match-string 0))))
16257 (beginning-of-line 0)
16258 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16259 (not (looking-at "[ \t]*:END:"))
16260 (not (looking-at org-drawer-regexp)))
16261 (beginning-of-line 0))
16262 (cond
16263 ((looking-at "\\*+[ \t]+")
16264 (if (not org-adapt-indentation)
16265 (setq column 0)
16266 (goto-char (match-end 0))
16267 (setq column (current-column))))
16268 ((looking-at org-drawer-regexp)
16269 (goto-char (1- (match-beginning 1)))
16270 (setq column (current-column)))
16271 ((looking-at "\\([ \t]*\\):END:")
16272 (goto-char (match-end 1))
16273 (setq column (current-column)))
16274 ((org-in-item-p)
16275 (org-beginning-of-item)
16276 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16277 (setq bpos (match-beginning 1) tpos (match-end 0)
16278 bcol (progn (goto-char bpos) (current-column))
16279 tcol (progn (goto-char tpos) (current-column))
16280 bullet (match-string 1)
16281 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16282 (if (> tcol (+ bcol org-description-max-indent))
16283 (setq tcol (+ bcol 5)))
16284 (if (not itemp)
16285 (setq column tcol)
16286 (goto-char pos)
16287 (beginning-of-line 1)
16288 (if (looking-at "\\S-")
16289 (progn
16290 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16291 (setq bullet (match-string 1)
16292 btype (if (string-match "[0-9]" bullet) "n" bullet))
16293 (setq column (if (equal btype bullet-type) bcol tcol)))
16294 (setq column (org-get-indentation)))))
16295 (t (setq column (org-get-indentation))))))
16296 (goto-char pos)
16297 (if (<= (current-column) (current-indentation))
16298 (org-indent-line-to column)
16299 (save-excursion (org-indent-line-to column)))
16300 (setq column (current-column))
16301 (beginning-of-line 1)
16302 (if (looking-at
16303 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16304 (replace-match (concat "\\1" (format org-property-format
16305 (match-string 2) (match-string 3)))
16306 t nil))
16307 (org-move-to-column column)))
16309 (defun org-set-autofill-regexps ()
16310 (interactive)
16311 ;; In the paragraph separator we include headlines, because filling
16312 ;; text in a line directly attached to a headline would otherwise
16313 ;; fill the headline as well.
16314 (org-set-local 'comment-start-skip "^#+[ \t]*")
16315 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16316 ;; The paragraph starter includes hand-formatted lists.
16317 (org-set-local
16318 'paragraph-start
16319 (concat
16320 "\f" "\\|"
16321 "[ ]*$" "\\|"
16322 "\\*+ " "\\|"
16323 "[ \t]*#" "\\|"
16324 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16325 "[ \t]*[:|]" "\\|"
16326 "\\$\\$" "\\|"
16327 "\\\\\\(begin\\|end\\|[][]\\)"))
16328 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16329 ;; But only if the user has not turned off tables or fixed-width regions
16330 (org-set-local
16331 'auto-fill-inhibit-regexp
16332 (concat "\\*+ \\|#\\+"
16333 "\\|[ \t]*" org-keyword-time-regexp
16334 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16335 (concat
16336 "\\|[ \t]*["
16337 (if org-enable-table-editor "|" "")
16338 (if org-enable-fixed-width-editor ":" "")
16339 "]"))))
16340 ;; We use our own fill-paragraph function, to make sure that tables
16341 ;; and fixed-width regions are not wrapped. That function will pass
16342 ;; through to `fill-paragraph' when appropriate.
16343 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16344 ; Adaptive filling: To get full control, first make sure that
16345 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16346 (org-set-local 'adaptive-fill-regexp "\000")
16347 (org-set-local 'adaptive-fill-function
16348 'org-adaptive-fill-function)
16349 (org-set-local
16350 'align-mode-rules-list
16351 '((org-in-buffer-settings
16352 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16353 (modes . '(org-mode))))))
16355 (defun org-fill-paragraph (&optional justify)
16356 "Re-align a table, pass through to fill-paragraph if no table."
16357 (let ((table-p (org-at-table-p))
16358 (table.el-p (org-at-table.el-p)))
16359 (cond ((and (equal (char-after (point-at-bol)) ?*)
16360 (save-excursion (goto-char (point-at-bol))
16361 (looking-at outline-regexp)))
16362 t) ; skip headlines
16363 (table.el-p t) ; skip table.el tables
16364 (table-p (org-table-align) t) ; align org-mode tables
16365 (t nil)))) ; call paragraph-fill
16367 ;; For reference, this is the default value of adaptive-fill-regexp
16368 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16370 (defun org-adaptive-fill-function ()
16371 "Return a fill prefix for org-mode files.
16372 In particular, this makes sure hanging paragraphs for hand-formatted lists
16373 work correctly."
16374 (cond ((looking-at "#[ \t]+")
16375 (match-string 0))
16376 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16377 (save-excursion
16378 (if (> (match-end 1) (+ (match-beginning 1)
16379 org-description-max-indent))
16380 (goto-char (+ (match-beginning 1) 5))
16381 (goto-char (match-end 0)))
16382 (make-string (current-column) ?\ )))
16383 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16384 (save-excursion
16385 (goto-char (match-end 0))
16386 (make-string (current-column) ?\ )))
16387 (t nil)))
16389 ;;; Other stuff.
16391 (defun org-toggle-fixed-width-section (arg)
16392 "Toggle the fixed-width export.
16393 If there is no active region, the QUOTE keyword at the current headline is
16394 inserted or removed. When present, it causes the text between this headline
16395 and the next to be exported as fixed-width text, and unmodified.
16396 If there is an active region, this command adds or removes a colon as the
16397 first character of this line. If the first character of a line is a colon,
16398 this line is also exported in fixed-width font."
16399 (interactive "P")
16400 (let* ((cc 0)
16401 (regionp (org-region-active-p))
16402 (beg (if regionp (region-beginning) (point)))
16403 (end (if regionp (region-end)))
16404 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16405 (case-fold-search nil)
16406 (re "[ \t]*\\(: \\)")
16407 off)
16408 (if regionp
16409 (save-excursion
16410 (goto-char beg)
16411 (setq cc (current-column))
16412 (beginning-of-line 1)
16413 (setq off (looking-at re))
16414 (while (> nlines 0)
16415 (setq nlines (1- nlines))
16416 (beginning-of-line 1)
16417 (cond
16418 (arg
16419 (org-move-to-column cc t)
16420 (insert ": \n")
16421 (forward-line -1))
16422 ((and off (looking-at re))
16423 (replace-match "" t t nil 1))
16424 ((not off) (org-move-to-column cc t) (insert ": ")))
16425 (forward-line 1)))
16426 (save-excursion
16427 (org-back-to-heading)
16428 (if (looking-at (concat outline-regexp
16429 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16430 (replace-match "" t t nil 1)
16431 (if (looking-at outline-regexp)
16432 (progn
16433 (goto-char (match-end 0))
16434 (insert org-quote-string " "))))))))
16436 (defun org-reftex-citation ()
16437 "Use reftex-citation to insert a citation into the buffer.
16438 This looks for a line like
16440 #+BIBLIOGRAPHY: foo plain option:-d
16442 and derives from it that foo.bib is the bbliography file relevant
16443 for this document. It then installs the necessary environment for RefTeX
16444 to work in this buffer and calls `reftex-citation' to insert a citation
16445 into the buffer.
16447 Export of such citations to both LaTeX and HTML is handled by the contributed
16448 package org-exp-bibtex by Taru Karttunen."
16449 (interactive)
16450 (let ((reftex-docstruct-symbol 'rds)
16451 (reftex-cite-format "\\cite{%l}")
16452 rds bib)
16453 (save-excursion
16454 (save-restriction
16455 (widen)
16456 (let ((case-fold-search t)
16457 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16458 (if (not (save-excursion
16459 (or (re-search-forward re nil t)
16460 (re-search-backward re nil t))))
16461 (error "No bibliography defined in file")
16462 (setq bib (concat (match-string 1) ".bib")
16463 rds (list (list 'bib bib)))))))
16464 (call-interactively 'reftex-citation)))
16466 ;;;; Functions extending outline functionality
16468 (defun org-beginning-of-line (&optional arg)
16469 "Go to the beginning of the current line. If that is invisible, continue
16470 to a visible line beginning. This makes the function of C-a more intuitive.
16471 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16472 first attempt, and only move to after the tags when the cursor is already
16473 beyond the end of the headline."
16474 (interactive "P")
16475 (let ((pos (point))
16476 (special (if (consp org-special-ctrl-a/e)
16477 (car org-special-ctrl-a/e)
16478 org-special-ctrl-a/e))
16479 refpos)
16480 (if (org-bound-and-true-p line-move-visual)
16481 (beginning-of-visual-line 1)
16482 (beginning-of-line 1))
16483 (if (and arg (fboundp 'move-beginning-of-line))
16484 (call-interactively 'move-beginning-of-line)
16485 (if (bobp)
16487 (backward-char 1)
16488 (if (org-invisible-p)
16489 (while (and (not (bobp)) (org-invisible-p))
16490 (backward-char 1)
16491 (beginning-of-line 1))
16492 (forward-char 1))))
16493 (when special
16494 (cond
16495 ((and (looking-at org-complex-heading-regexp)
16496 (= (char-after (match-end 1)) ?\ ))
16497 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16498 (point-at-eol)))
16499 (goto-char
16500 (if (eq special t)
16501 (cond ((> pos refpos) refpos)
16502 ((= pos (point)) refpos)
16503 (t (point)))
16504 (cond ((> pos (point)) (point))
16505 ((not (eq last-command this-command)) (point))
16506 (t refpos)))))
16507 ((org-at-item-p)
16508 (goto-char
16509 (if (eq special t)
16510 (cond ((> pos (match-end 4)) (match-end 4))
16511 ((= pos (point)) (match-end 4))
16512 (t (point)))
16513 (cond ((> pos (point)) (point))
16514 ((not (eq last-command this-command)) (point))
16515 (t (match-end 4))))))))
16516 (org-no-warnings
16517 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16519 (defun org-end-of-line (&optional arg)
16520 "Go to the end of the line.
16521 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16522 first attempt, and only move to after the tags when the cursor is already
16523 beyond the end of the headline."
16524 (interactive "P")
16525 (let ((special (if (consp org-special-ctrl-a/e)
16526 (cdr org-special-ctrl-a/e)
16527 org-special-ctrl-a/e)))
16528 (if (or (not special)
16529 (not (org-on-heading-p))
16530 arg)
16531 (call-interactively
16532 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16533 ((fboundp 'move-end-of-line) 'move-end-of-line)
16534 (t 'end-of-line)))
16535 (let ((pos (point)))
16536 (beginning-of-line 1)
16537 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16538 (if (eq special t)
16539 (if (or (< pos (match-beginning 1))
16540 (= pos (match-end 0)))
16541 (goto-char (match-beginning 1))
16542 (goto-char (match-end 0)))
16543 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16544 (goto-char (match-end 0))
16545 (goto-char (match-beginning 1))))
16546 (call-interactively (if (fboundp 'move-end-of-line)
16547 'move-end-of-line
16548 'end-of-line)))))
16549 (org-no-warnings
16550 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16552 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16553 (define-key org-mode-map "\C-e" 'org-end-of-line)
16555 (defun org-backward-sentence (&optional arg)
16556 "Go to beginning of sentence, or beginning of table field.
16557 This will call `backward-sentence' or `org-table-beginning-of-field',
16558 depending on context."
16559 (interactive "P")
16560 (cond
16561 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16562 (t (call-interactively 'backward-sentence))))
16564 (defun org-forward-sentence (&optional arg)
16565 "Go to end of sentence, or end of table field.
16566 This will call `forward-sentence' or `org-table-end-of-field',
16567 depending on context."
16568 (interactive "P")
16569 (cond
16570 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16571 (t (call-interactively 'forward-sentence))))
16573 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16574 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16576 (defun org-kill-line (&optional arg)
16577 "Kill line, to tags or end of line."
16578 (interactive "P")
16579 (cond
16580 ((or (not org-special-ctrl-k)
16581 (bolp)
16582 (not (org-on-heading-p)))
16583 (call-interactively 'kill-line))
16584 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16585 (kill-region (point) (match-beginning 1))
16586 (org-set-tags nil t))
16587 (t (kill-region (point) (point-at-eol)))))
16589 (define-key org-mode-map "\C-k" 'org-kill-line)
16591 (defun org-yank (&optional arg)
16592 "Yank. If the kill is a subtree, treat it specially.
16593 This command will look at the current kill and check if is a single
16594 subtree, or a series of subtrees[1]. If it passes the test, and if the
16595 cursor is at the beginning of a line or after the stars of a currently
16596 empty headline, then the yank is handled specially. How exactly depends
16597 on the value of the following variables, both set by default.
16599 org-yank-folded-subtrees
16600 When set, the subtree(s) will be folded after insertion, but only
16601 if doing so would now swallow text after the yanked text.
16603 org-yank-adjusted-subtrees
16604 When set, the subtree will be promoted or demoted in order to
16605 fit into the local outline tree structure, which means that the level
16606 will be adjusted so that it becomes the smaller one of the two
16607 *visible* surrounding headings.
16609 Any prefix to this command will cause `yank' to be called directly with
16610 no special treatment. In particular, a simple `C-u' prefix will just
16611 plainly yank the text as it is.
16613 \[1] The test checks if the first non-white line is a heading
16614 and if there are no other headings with fewer stars."
16615 (interactive "P")
16616 (org-yank-generic 'yank arg))
16618 (defun org-yank-generic (command arg)
16619 "Perform some yank-like command.
16621 This function implements the behavior described in the `org-yank'
16622 documentation. However, it has been generalized to work for any
16623 interactive command with similar behavior."
16625 ;; pretend to be command COMMAND
16626 (setq this-command command)
16628 (if arg
16629 (call-interactively command)
16631 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16632 (and (org-kill-is-subtree-p)
16633 (or (bolp)
16634 (and (looking-at "[ \t]*$")
16635 (string-match
16636 "\\`\\*+\\'"
16637 (buffer-substring (point-at-bol) (point)))))))
16638 swallowp)
16639 (cond
16640 ((and subtreep org-yank-folded-subtrees)
16641 (let ((beg (point))
16642 end)
16643 (if (and subtreep org-yank-adjusted-subtrees)
16644 (org-paste-subtree nil nil 'for-yank)
16645 (call-interactively command))
16647 (setq end (point))
16648 (goto-char beg)
16649 (when (and (bolp) subtreep
16650 (not (setq swallowp
16651 (org-yank-folding-would-swallow-text beg end))))
16652 (or (looking-at outline-regexp)
16653 (re-search-forward (concat "^" outline-regexp) end t))
16654 (while (and (< (point) end) (looking-at outline-regexp))
16655 (hide-subtree)
16656 (org-cycle-show-empty-lines 'folded)
16657 (condition-case nil
16658 (outline-forward-same-level 1)
16659 (error (goto-char end)))))
16660 (when swallowp
16661 (message
16662 "Inserted text not folded because that would swallow text"))
16664 (goto-char end)
16665 (skip-chars-forward " \t\n\r")
16666 (beginning-of-line 1)
16667 (push-mark beg 'nomsg)))
16668 ((and subtreep org-yank-adjusted-subtrees)
16669 (let ((beg (point-at-bol)))
16670 (org-paste-subtree nil nil 'for-yank)
16671 (push-mark beg 'nomsg)))
16673 (call-interactively command))))))
16675 (defun org-yank-folding-would-swallow-text (beg end)
16676 "Would hide-subtree at BEG swallow any text after END?"
16677 (let (level)
16678 (save-excursion
16679 (goto-char beg)
16680 (when (or (looking-at outline-regexp)
16681 (re-search-forward (concat "^" outline-regexp) end t))
16682 (setq level (org-outline-level)))
16683 (goto-char end)
16684 (skip-chars-forward " \t\r\n\v\f")
16685 (if (or (eobp)
16686 (and (bolp) (looking-at org-outline-regexp)
16687 (<= (org-outline-level) level)))
16688 nil ; Nothing would be swallowed
16689 t)))) ; something would swallow
16691 (define-key org-mode-map "\C-y" 'org-yank)
16693 (defun org-invisible-p ()
16694 "Check if point is at a character currently not visible."
16695 ;; Early versions of noutline don't have `outline-invisible-p'.
16696 (if (fboundp 'outline-invisible-p)
16697 (outline-invisible-p)
16698 (get-char-property (point) 'invisible)))
16700 (defun org-invisible-p2 ()
16701 "Check if point is at a character currently not visible."
16702 (save-excursion
16703 (if (and (eolp) (not (bobp))) (backward-char 1))
16704 ;; Early versions of noutline don't have `outline-invisible-p'.
16705 (if (fboundp 'outline-invisible-p)
16706 (outline-invisible-p)
16707 (get-char-property (point) 'invisible))))
16709 (defun org-back-to-heading (&optional invisible-ok)
16710 "Call `outline-back-to-heading', but provide a better error message."
16711 (condition-case nil
16712 (outline-back-to-heading invisible-ok)
16713 (error (error "Before first headline at position %d in buffer %s"
16714 (point) (current-buffer)))))
16716 (defun org-before-first-heading-p ()
16717 "Before first heading?"
16718 (save-excursion
16719 (null (re-search-backward "^\\*+ " nil t))))
16721 (defalias 'org-on-heading-p 'outline-on-heading-p)
16722 (defalias 'org-at-heading-p 'outline-on-heading-p)
16723 (defun org-at-heading-or-item-p ()
16724 (or (org-on-heading-p) (org-at-item-p)))
16726 (defun org-on-target-p ()
16727 (or (org-in-regexp org-radio-target-regexp)
16728 (org-in-regexp org-target-regexp)))
16730 (defun org-up-heading-all (arg)
16731 "Move to the heading line of which the present line is a subheading.
16732 This function considers both visible and invisible heading lines.
16733 With argument, move up ARG levels."
16734 (if (fboundp 'outline-up-heading-all)
16735 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16736 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16738 (defun org-up-heading-safe ()
16739 "Move to the heading line of which the present line is a subheading.
16740 This version will not throw an error. It will return the level of the
16741 headline found, or nil if no higher level is found.
16743 Also, this function will be a lot faster than `outline-up-heading',
16744 because it relies on stars being the outline starters. This can really
16745 make a significant difference in outlines with very many siblings."
16746 (let (start-level re)
16747 (org-back-to-heading t)
16748 (setq start-level (funcall outline-level))
16749 (if (equal start-level 1)
16751 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16752 (if (re-search-backward re nil t)
16753 (funcall outline-level)))))
16755 (defun org-first-sibling-p ()
16756 "Is this heading the first child of its parents?"
16757 (interactive)
16758 (let ((re (concat "^" outline-regexp))
16759 level l)
16760 (unless (org-at-heading-p t)
16761 (error "Not at a heading"))
16762 (setq level (funcall outline-level))
16763 (save-excursion
16764 (if (not (re-search-backward re nil t))
16766 (setq l (funcall outline-level))
16767 (< l level)))))
16769 (defun org-goto-sibling (&optional previous)
16770 "Goto the next sibling, even if it is invisible.
16771 When PREVIOUS is set, go to the previous sibling instead. Returns t
16772 when a sibling was found. When none is found, return nil and don't
16773 move point."
16774 (let ((fun (if previous 're-search-backward 're-search-forward))
16775 (pos (point))
16776 (re (concat "^" outline-regexp))
16777 level l)
16778 (when (condition-case nil (org-back-to-heading t) (error nil))
16779 (setq level (funcall outline-level))
16780 (catch 'exit
16781 (or previous (forward-char 1))
16782 (while (funcall fun re nil t)
16783 (setq l (funcall outline-level))
16784 (when (< l level) (goto-char pos) (throw 'exit nil))
16785 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16786 (goto-char pos)
16787 nil))))
16789 (defun org-show-siblings ()
16790 "Show all siblings of the current headline."
16791 (save-excursion
16792 (while (org-goto-sibling) (org-flag-heading nil)))
16793 (save-excursion
16794 (while (org-goto-sibling 'previous)
16795 (org-flag-heading nil))))
16797 (defun org-show-hidden-entry ()
16798 "Show an entry where even the heading is hidden."
16799 (save-excursion
16800 (org-show-entry)))
16802 (defun org-flag-heading (flag &optional entry)
16803 "Flag the current heading. FLAG non-nil means make invisible.
16804 When ENTRY is non-nil, show the entire entry."
16805 (save-excursion
16806 (org-back-to-heading t)
16807 ;; Check if we should show the entire entry
16808 (if entry
16809 (progn
16810 (org-show-entry)
16811 (save-excursion
16812 (and (outline-next-heading)
16813 (org-flag-heading nil))))
16814 (outline-flag-region (max (point-min) (1- (point)))
16815 (save-excursion (outline-end-of-heading) (point))
16816 flag))))
16818 (defun org-get-next-sibling ()
16819 "Move to next heading of the same level, and return point.
16820 If there is no such heading, return nil.
16821 This is like outline-next-sibling, but invisible headings are ok."
16822 (let ((level (funcall outline-level)))
16823 (outline-next-heading)
16824 (while (and (not (eobp)) (> (funcall outline-level) level))
16825 (outline-next-heading))
16826 (if (or (eobp) (< (funcall outline-level) level))
16828 (point))))
16830 (defun org-get-last-sibling ()
16831 "Move to previous heading of the same level, and return point.
16832 If there is no such heading, return nil."
16833 (let ((opoint (point))
16834 (level (funcall outline-level)))
16835 (outline-previous-heading)
16836 (when (and (/= (point) opoint) (outline-on-heading-p t))
16837 (while (and (> (funcall outline-level) level)
16838 (not (bobp)))
16839 (outline-previous-heading))
16840 (if (< (funcall outline-level) level)
16842 (point)))))
16844 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16845 ;; This contains an exact copy of the original function, but it uses
16846 ;; `org-back-to-heading', to make it work also in invisible
16847 ;; trees. And is uses an invisible-OK argument.
16848 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16849 ;; Furthermore, when used inside Org, finding the end of a large subtree
16850 ;; with many children and grandchildren etc, this can be much faster
16851 ;; than the outline version.
16852 (org-back-to-heading invisible-OK)
16853 (let ((first t)
16854 (level (funcall outline-level)))
16855 (if (and (org-mode-p) (< level 1000))
16856 ;; A true heading (not a plain list item), in Org-mode
16857 ;; This means we can easily find the end by looking
16858 ;; only for the right number of stars. Using a regexp to do
16859 ;; this is so much faster than using a Lisp loop.
16860 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16861 (forward-char 1)
16862 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16863 ;; something else, do it the slow way
16864 (while (and (not (eobp))
16865 (or first (> (funcall outline-level) level)))
16866 (setq first nil)
16867 (outline-next-heading)))
16868 (unless to-heading
16869 (if (memq (preceding-char) '(?\n ?\^M))
16870 (progn
16871 ;; Go to end of line before heading
16872 (forward-char -1)
16873 (if (memq (preceding-char) '(?\n ?\^M))
16874 ;; leave blank line before heading
16875 (forward-char -1))))))
16876 (point))
16878 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16879 "Use Org version in org-mode, for dramatic speed-up."
16880 (if (eq major-mode 'org-mode)
16881 (progn
16882 (org-end-of-subtree nil t)
16883 (unless (eobp) (backward-char 1)))
16884 ad-do-it))
16886 (defun org-forward-same-level (arg &optional invisible-ok)
16887 "Move forward to the arg'th subheading at same level as this one.
16888 Stop at the first and last subheadings of a superior heading."
16889 (interactive "p")
16890 (org-back-to-heading invisible-ok)
16891 (org-on-heading-p)
16892 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16893 (re (format "^\\*\\{1,%d\\} " level))
16895 (forward-char 1)
16896 (while (> arg 0)
16897 (while (and (re-search-forward re nil 'move)
16898 (setq l (- (match-end 0) (match-beginning 0) 1))
16899 (= l level)
16900 (not invisible-ok)
16901 (org-invisible-p))
16902 (if (< l level) (setq arg 1)))
16903 (setq arg (1- arg)))
16904 (beginning-of-line 1)))
16906 (defun org-backward-same-level (arg &optional invisible-ok)
16907 "Move backward to the arg'th subheading at same level as this one.
16908 Stop at the first and last subheadings of a superior heading."
16909 (interactive "p")
16910 (org-back-to-heading)
16911 (org-on-heading-p)
16912 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16913 (re (format "^\\*\\{1,%d\\} " level))
16915 (while (> arg 0)
16916 (while (and (re-search-backward re nil 'move)
16917 (setq l (- (match-end 0) (match-beginning 0) 1))
16918 (= l level)
16919 (not invisible-ok)
16920 (org-invisible-p))
16921 (if (< l level) (setq arg 1)))
16922 (setq arg (1- arg)))))
16924 (defun org-show-subtree ()
16925 "Show everything after this heading at deeper levels."
16926 (outline-flag-region
16927 (point)
16928 (save-excursion
16929 (org-end-of-subtree t t))
16930 nil))
16932 (defun org-show-entry ()
16933 "Show the body directly following this heading.
16934 Show the heading too, if it is currently invisible."
16935 (interactive)
16936 (save-excursion
16937 (condition-case nil
16938 (progn
16939 (org-back-to-heading t)
16940 (outline-flag-region
16941 (max (point-min) (1- (point)))
16942 (save-excursion
16943 (if (re-search-forward
16944 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16945 (match-beginning 1)
16946 (point-max)))
16947 nil)
16948 (org-cycle-hide-drawers 'children))
16949 (error nil))))
16951 (defun org-make-options-regexp (kwds &optional extra)
16952 "Make a regular expression for keyword lines."
16953 (concat
16955 "#?[ \t]*\\+\\("
16956 (mapconcat 'regexp-quote kwds "\\|")
16957 (if extra (concat "\\|" extra))
16958 "\\):[ \t]*"
16959 "\\(.*\\)"))
16961 ;; Make isearch reveal the necessary context
16962 (defun org-isearch-end ()
16963 "Reveal context after isearch exits."
16964 (when isearch-success ; only if search was successful
16965 (if (featurep 'xemacs)
16966 ;; Under XEmacs, the hook is run in the correct place,
16967 ;; we directly show the context.
16968 (org-show-context 'isearch)
16969 ;; In Emacs the hook runs *before* restoring the overlays.
16970 ;; So we have to use a one-time post-command-hook to do this.
16971 ;; (Emacs 22 has a special variable, see function `org-mode')
16972 (unless (and (boundp 'isearch-mode-end-hook-quit)
16973 isearch-mode-end-hook-quit)
16974 ;; Only when the isearch was not quitted.
16975 (org-add-hook 'post-command-hook 'org-isearch-post-command
16976 'append 'local)))))
16978 (defun org-isearch-post-command ()
16979 "Remove self from hook, and show context."
16980 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16981 (org-show-context 'isearch))
16984 ;;;; Integration with and fixes for other packages
16986 ;;; Imenu support
16988 (defvar org-imenu-markers nil
16989 "All markers currently used by Imenu.")
16990 (make-variable-buffer-local 'org-imenu-markers)
16992 (defun org-imenu-new-marker (&optional pos)
16993 "Return a new marker for use by Imenu, and remember the marker."
16994 (let ((m (make-marker)))
16995 (move-marker m (or pos (point)))
16996 (push m org-imenu-markers)
16999 (defun org-imenu-get-tree ()
17000 "Produce the index for Imenu."
17001 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17002 (setq org-imenu-markers nil)
17003 (let* ((n org-imenu-depth)
17004 (re (concat "^" outline-regexp))
17005 (subs (make-vector (1+ n) nil))
17006 (last-level 0)
17007 m level head)
17008 (save-excursion
17009 (save-restriction
17010 (widen)
17011 (goto-char (point-max))
17012 (while (re-search-backward re nil t)
17013 (setq level (org-reduced-level (funcall outline-level)))
17014 (when (<= level n)
17015 (looking-at org-complex-heading-regexp)
17016 (setq head (org-link-display-format
17017 (org-match-string-no-properties 4))
17018 m (org-imenu-new-marker))
17019 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17020 (if (>= level last-level)
17021 (push (cons head m) (aref subs level))
17022 (push (cons head (aref subs (1+ level))) (aref subs level))
17023 (loop for i from (1+ level) to n do (aset subs i nil)))
17024 (setq last-level level)))))
17025 (aref subs 1)))
17027 (eval-after-load "imenu"
17028 '(progn
17029 (add-hook 'imenu-after-jump-hook
17030 (lambda ()
17031 (if (eq major-mode 'org-mode)
17032 (org-show-context 'org-goto))))))
17034 (defun org-link-display-format (link)
17035 "Replace a link with either the description, or the link target
17036 if no description is present"
17037 (save-match-data
17038 (if (string-match org-bracket-link-analytic-regexp link)
17039 (replace-match (or (match-string 5 link)
17040 (concat (match-string 1 link)
17041 (match-string 3 link)))
17042 nil nil link)
17043 link)))
17045 ;; Speedbar support
17047 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17048 "Overlay marking the agenda restriction line in speedbar.")
17049 (org-overlay-put org-speedbar-restriction-lock-overlay
17050 'face 'org-agenda-restriction-lock)
17051 (org-overlay-put org-speedbar-restriction-lock-overlay
17052 'help-echo "Agendas are currently limited to this item.")
17053 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17055 (defun org-speedbar-set-agenda-restriction ()
17056 "Restrict future agenda commands to the location at point in speedbar.
17057 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17058 (interactive)
17059 (require 'org-agenda)
17060 (let (p m tp np dir txt)
17061 (cond
17062 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17063 'org-imenu t))
17064 (setq m (get-text-property p 'org-imenu-marker))
17065 (save-excursion
17066 (save-restriction
17067 (set-buffer (marker-buffer m))
17068 (goto-char m)
17069 (org-agenda-set-restriction-lock 'subtree))))
17070 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17071 'speedbar-function 'speedbar-find-file))
17072 (setq tp (previous-single-property-change
17073 (1+ p) 'speedbar-function)
17074 np (next-single-property-change
17075 tp 'speedbar-function)
17076 dir (speedbar-line-directory)
17077 txt (buffer-substring-no-properties (or tp (point-min))
17078 (or np (point-max))))
17079 (save-excursion
17080 (save-restriction
17081 (set-buffer (find-file-noselect
17082 (let ((default-directory dir))
17083 (expand-file-name txt))))
17084 (unless (org-mode-p)
17085 (error "Cannot restrict to non-Org-mode file"))
17086 (org-agenda-set-restriction-lock 'file))))
17087 (t (error "Don't know how to restrict Org-mode's agenda")))
17088 (org-move-overlay org-speedbar-restriction-lock-overlay
17089 (point-at-bol) (point-at-eol))
17090 (setq current-prefix-arg nil)
17091 (org-agenda-maybe-redo)))
17093 (eval-after-load "speedbar"
17094 '(progn
17095 (speedbar-add-supported-extension ".org")
17096 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17097 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17098 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17099 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17100 (add-hook 'speedbar-visiting-tag-hook
17101 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17104 ;;; Fixes and Hacks for problems with other packages
17106 ;; Make flyspell not check words in links, to not mess up our keymap
17107 (defun org-mode-flyspell-verify ()
17108 "Don't let flyspell put overlays at active buttons."
17109 (and (not (get-text-property (point) 'keymap))
17110 (not (get-text-property (point) 'org-no-flyspell))))
17112 (defun org-remove-flyspell-overlays-in (beg end)
17113 "Remove flyspell overlays in region."
17114 (and (org-bound-and-true-p flyspell-mode)
17115 (fboundp 'flyspell-delete-region-overlays)
17116 (flyspell-delete-region-overlays beg end))
17117 (add-text-properties beg end '(org-no-flyspell t)))
17119 ;; Make `bookmark-jump' show the jump location if it was hidden.
17120 (eval-after-load "bookmark"
17121 '(if (boundp 'bookmark-after-jump-hook)
17122 ;; We can use the hook
17123 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17124 ;; Hook not available, use advice
17125 (defadvice bookmark-jump (after org-make-visible activate)
17126 "Make the position visible."
17127 (org-bookmark-jump-unhide))))
17129 ;; Make sure saveplace show the location if it was hidden
17130 (eval-after-load "saveplace"
17131 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17132 "Make the position visible."
17133 (org-bookmark-jump-unhide)))
17135 (defun org-bookmark-jump-unhide ()
17136 "Unhide the current position, to show the bookmark location."
17137 (and (org-mode-p)
17138 (or (org-invisible-p)
17139 (save-excursion (goto-char (max (point-min) (1- (point))))
17140 (org-invisible-p)))
17141 (org-show-context 'bookmark-jump)))
17143 ;; Make session.el ignore our circular variable
17144 (eval-after-load "session"
17145 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17147 ;;;; Experimental code
17149 (defun org-closed-in-range ()
17150 "Sparse tree of items closed in a certain time range.
17151 Still experimental, may disappear in the future."
17152 (interactive)
17153 ;; Get the time interval from the user.
17154 (let* ((time1 (org-float-time
17155 (org-read-date nil 'to-time nil "Starting date: ")))
17156 (time2 (org-float-time
17157 (org-read-date nil 'to-time nil "End date:")))
17158 ;; callback function
17159 (callback (lambda ()
17160 (let ((time
17161 (org-float-time
17162 (apply 'encode-time
17163 (org-parse-time-string
17164 (match-string 1))))))
17165 ;; check if time in interval
17166 (and (>= time time1) (<= time time2))))))
17167 ;; make tree, check each match with the callback
17168 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17170 ;;;; Finish up
17172 (provide 'org)
17174 (run-hooks 'org-load-hook)
17176 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17178 ;;; org.el ends here