orgstruct++-mode: Make more visible in docs, parse item body
[org-mode.git] / lisp / org.el
blobb67b7a4489d22999d84d6908ebcf70ea2922586c
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.23a
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-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.23a"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (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)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
185 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
186 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
187 (const :tag "C eval: Include command output as text" org-eval)
188 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
189 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
190 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
191 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
192 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
193 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
194 (const :tag "C mtags: Support for muse-like tags" org-mtags)
195 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
196 (const :tag "C R: Computation using the R language" org-R)
197 (const :tag "C registry: A registry for Org links" org-registry)
198 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
199 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
200 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
201 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
202 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
204 (defcustom org-support-shift-select nil
205 "Non-nil means, make shift-cursor commands select text when possible.
207 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
208 selecting a region, or enlarge thusly regions started in this way.
209 In Org-mode, in special contexts, these same keys are used for other
210 purposes, important enough to compete with shift selection. Org tries
211 to balance these needs by supporting `shift-select-mode' outside these
212 special contexts, under control of this variable.
214 The default of this variable is nil, to avoid confusing behavior. Shifted
215 cursor keys will then execute Org commands in the following contexts:
216 - on a headline, changing TODO state (left/right) and priority (up/down)
217 - on a time stamp, changing the time
218 - in a plain list item, changing the bullet type
219 - in a property definition line, switching between allowed values
220 - in the BEGIN line of a clock table (changing the time block).
221 Outside these contexts, the commands will throw an error.
223 When this variable is t and the cursor is not in a special context,
224 Org-mode will support shift-selection for making and enlarging regions.
225 To make this more effective, the bullet cycling will no longer happen
226 anywhere in an item line, but only if the cursor is exactly on the bullet.
228 If you set this variable to the symbol `always', then the keys
229 will not be special in headlines, property lines, and item lines, to make
230 shift selection work there as well. If this is what you want, you can
231 use the following alternative commands: `C-c C-t' and `C-c ,' to
232 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
233 TODO sets, `C-c -' to cycle item bullet types, and properties can be
234 edited by hand or in column view.
236 However, when the cursor is on a timestamp, shift-cursor commands
237 will still edit the time stamp - this is just too good to give up.
239 XEmacs user should have this variable set to nil, because shift-select-mode
240 is Emacs 23 only."
241 :group 'org
242 :type '(choice
243 (const :tag "Never" nil)
244 (const :tag "When outside special context" t)
245 (const :tag "Everywhere except timestamps" always)))
247 (defgroup org-startup nil
248 "Options concerning startup of Org-mode."
249 :tag "Org Startup"
250 :group 'org)
252 (defcustom org-startup-folded t
253 "Non-nil means, entering Org-mode will switch to OVERVIEW.
254 This can also be configured on a per-file basis by adding one of
255 the following lines anywhere in the buffer:
257 #+STARTUP: fold
258 #+STARTUP: nofold
259 #+STARTUP: content"
260 :group 'org-startup
261 :type '(choice
262 (const :tag "nofold: show all" nil)
263 (const :tag "fold: overview" t)
264 (const :tag "content: all headlines" content)))
266 (defcustom org-startup-truncated t
267 "Non-nil means, entering Org-mode will set `truncate-lines'.
268 This is useful since some lines containing links can be very long and
269 uninteresting. Also tables look terrible when wrapped."
270 :group 'org-startup
271 :type 'boolean)
273 (defcustom org-startup-align-all-tables nil
274 "Non-nil means, align all tables when visiting a file.
275 This is useful when the column width in tables is forced with <N> cookies
276 in table fields. Such tables will look correct only after the first re-align.
277 This can also be configured on a per-file basis by adding one of
278 the following lines anywhere in the buffer:
279 #+STARTUP: align
280 #+STARTUP: noalign"
281 :group 'org-startup
282 :type 'boolean)
284 (defcustom org-insert-mode-line-in-empty-file nil
285 "Non-nil means insert the first line setting Org-mode in empty files.
286 When the function `org-mode' is called interactively in an empty file, this
287 normally means that the file name does not automatically trigger Org-mode.
288 To ensure that the file will always be in Org-mode in the future, a
289 line enforcing Org-mode will be inserted into the buffer, if this option
290 has been set."
291 :group 'org-startup
292 :type 'boolean)
294 (defcustom org-replace-disputed-keys nil
295 "Non-nil means use alternative key bindings for some keys.
296 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
297 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
298 If you want to use Org-mode together with one of these other modes,
299 or more generally if you would like to move some Org-mode commands to
300 other keys, set this variable and configure the keys with the variable
301 `org-disputed-keys'.
303 This option is only relevant at load-time of Org-mode, and must be set
304 *before* org.el is loaded. Changing it requires a restart of Emacs to
305 become effective."
306 :group 'org-startup
307 :type 'boolean)
309 (defcustom org-use-extra-keys nil
310 "Non-nil means use extra key sequence definitions for certain
311 commands. This happens automatically if you run XEmacs or if
312 window-system is nil. This variable lets you do the same
313 manually. You must set it before loading org.
315 Example: on Carbon Emacs 22 running graphically, with an external
316 keyboard on a Powerbook, the default way of setting M-left might
317 not work for either Alt or ESC. Setting this variable will make
318 it work for ESC."
319 :group 'org-startup
320 :type 'boolean)
322 (if (fboundp 'defvaralias)
323 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
325 (defcustom org-disputed-keys
326 '(([(shift up)] . [(meta p)])
327 ([(shift down)] . [(meta n)])
328 ([(shift left)] . [(meta -)])
329 ([(shift right)] . [(meta +)])
330 ([(control shift right)] . [(meta shift +)])
331 ([(control shift left)] . [(meta shift -)]))
332 "Keys for which Org-mode and other modes compete.
333 This is an alist, cars are the default keys, second element specifies
334 the alternative to use when `org-replace-disputed-keys' is t.
336 Keys can be specified in any syntax supported by `define-key'.
337 The value of this option takes effect only at Org-mode's startup,
338 therefore you'll have to restart Emacs to apply it after changing."
339 :group 'org-startup
340 :type 'alist)
342 (defun org-key (key)
343 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
344 Or return the original if not disputed."
345 (if org-replace-disputed-keys
346 (let* ((nkey (key-description key))
347 (x (org-find-if (lambda (x)
348 (equal (key-description (car x)) nkey))
349 org-disputed-keys)))
350 (if x (cdr x) key))
351 key))
353 (defun org-find-if (predicate seq)
354 (catch 'exit
355 (while seq
356 (if (funcall predicate (car seq))
357 (throw 'exit (car seq))
358 (pop seq)))))
360 (defun org-defkey (keymap key def)
361 "Define a key, possibly translated, as returned by `org-key'."
362 (define-key keymap (org-key key) def))
364 (defcustom org-ellipsis nil
365 "The ellipsis to use in the Org-mode outline.
366 When nil, just use the standard three dots. When a string, use that instead,
367 When a face, use the standard 3 dots, but with the specified face.
368 The change affects only Org-mode (which will then use its own display table).
369 Changing this requires executing `M-x org-mode' in a buffer to become
370 effective."
371 :group 'org-startup
372 :type '(choice (const :tag "Default" nil)
373 (face :tag "Face" :value org-warning)
374 (string :tag "String" :value "...#")))
376 (defvar org-display-table nil
377 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
379 (defgroup org-keywords nil
380 "Keywords in Org-mode."
381 :tag "Org Keywords"
382 :group 'org)
384 (defcustom org-deadline-string "DEADLINE:"
385 "String to mark deadline entries.
386 A deadline is this string, followed by a time stamp. Should be a word,
387 terminated by a colon. You can insert a schedule keyword and
388 a timestamp with \\[org-deadline].
389 Changes become only effective after restarting Emacs."
390 :group 'org-keywords
391 :type 'string)
393 (defcustom org-scheduled-string "SCHEDULED:"
394 "String to mark scheduled TODO entries.
395 A schedule is this string, followed by a time stamp. Should be a word,
396 terminated by a colon. You can insert a schedule keyword and
397 a timestamp with \\[org-schedule].
398 Changes become only effective after restarting Emacs."
399 :group 'org-keywords
400 :type 'string)
402 (defcustom org-closed-string "CLOSED:"
403 "String used as the prefix for timestamps logging closing a TODO entry."
404 :group 'org-keywords
405 :type 'string)
407 (defcustom org-clock-string "CLOCK:"
408 "String used as prefix for timestamps clocking work hours on an item."
409 :group 'org-keywords
410 :type 'string)
412 (defcustom org-comment-string "COMMENT"
413 "Entries starting with this keyword will never be exported.
414 An entry can be toggled between COMMENT and normal with
415 \\[org-toggle-comment].
416 Changes become only effective after restarting Emacs."
417 :group 'org-keywords
418 :type 'string)
420 (defcustom org-quote-string "QUOTE"
421 "Entries starting with this keyword will be exported in fixed-width font.
422 Quoting applies only to the text in the entry following the headline, and does
423 not extend beyond the next headline, even if that is lower level.
424 An entry can be toggled between QUOTE and normal with
425 \\[org-toggle-fixed-width-section]."
426 :group 'org-keywords
427 :type 'string)
429 (defconst org-repeat-re
430 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
431 "Regular expression for specifying repeated events.
432 After a match, group 1 contains the repeat expression.")
434 (defgroup org-structure nil
435 "Options concerning the general structure of Org-mode files."
436 :tag "Org Structure"
437 :group 'org)
439 (defgroup org-reveal-location nil
440 "Options about how to make context of a location visible."
441 :tag "Org Reveal Location"
442 :group 'org-structure)
444 (defconst org-context-choice
445 '(choice
446 (const :tag "Always" t)
447 (const :tag "Never" nil)
448 (repeat :greedy t :tag "Individual contexts"
449 (cons
450 (choice :tag "Context"
451 (const agenda)
452 (const org-goto)
453 (const occur-tree)
454 (const tags-tree)
455 (const link-search)
456 (const mark-goto)
457 (const bookmark-jump)
458 (const isearch)
459 (const default))
460 (boolean))))
461 "Contexts for the reveal options.")
463 (defcustom org-show-hierarchy-above '((default . t))
464 "Non-nil means, show full hierarchy when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the hierarchy of headings
467 above the exposed location is shown.
468 Turning this off for example for sparse trees makes them very compact.
469 Instead of t, this can also be an alist specifying this option for different
470 contexts. Valid contexts are
471 agenda when exposing an entry from the agenda
472 org-goto when using the command `org-goto' on key C-c C-j
473 occur-tree when using the command `org-occur' on key C-c /
474 tags-tree when constructing a sparse tree based on tags matches
475 link-search when exposing search matches associated with a link
476 mark-goto when exposing the jump goal of a mark
477 bookmark-jump when exposing a bookmark location
478 isearch when exiting from an incremental search
479 default default for all contexts not set explicitly"
480 :group 'org-reveal-location
481 :type org-context-choice)
483 (defcustom org-show-following-heading '((default . nil))
484 "Non-nil means, show following heading when revealing a location.
485 Org-mode often shows locations in an org-mode file which might have
486 been invisible before. When this is set, the heading following the
487 match is shown.
488 Turning this off for example for sparse trees makes them very compact,
489 but makes it harder to edit the location of the match. In such a case,
490 use the command \\[org-reveal] to show more context.
491 Instead of t, this can also be an alist specifying this option for different
492 contexts. See `org-show-hierarchy-above' for valid contexts."
493 :group 'org-reveal-location
494 :type org-context-choice)
496 (defcustom org-show-siblings '((default . nil) (isearch t))
497 "Non-nil means, show all sibling heading when revealing a location.
498 Org-mode often shows locations in an org-mode file which might have
499 been invisible before. When this is set, the sibling of the current entry
500 heading are all made visible. If `org-show-hierarchy-above' is t,
501 the same happens on each level of the hierarchy above the current entry.
503 By default this is on for the isearch context, off for all other contexts.
504 Turning this off for example for sparse trees makes them very compact,
505 but makes it harder to edit the location of the match. In such a case,
506 use the command \\[org-reveal] to show more context.
507 Instead of t, this can also be an alist specifying this option for different
508 contexts. See `org-show-hierarchy-above' for valid contexts."
509 :group 'org-reveal-location
510 :type org-context-choice)
512 (defcustom org-show-entry-below '((default . nil))
513 "Non-nil means, show the entry below a headline when revealing a location.
514 Org-mode often shows locations in an org-mode file which might have
515 been invisible before. When this is set, the text below the headline that is
516 exposed is also shown.
518 By default this is off for all contexts.
519 Instead of t, this can also be an alist specifying this option for different
520 contexts. See `org-show-hierarchy-above' for valid contexts."
521 :group 'org-reveal-location
522 :type org-context-choice)
524 (defcustom org-indirect-buffer-display 'other-window
525 "How should indirect tree buffers be displayed?
526 This applies to indirect buffers created with the commands
527 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
528 Valid values are:
529 current-window Display in the current window
530 other-window Just display in another window.
531 dedicated-frame Create one new frame, and re-use it each time.
532 new-frame Make a new frame each time. Note that in this case
533 previously-made indirect buffers are kept, and you need to
534 kill these buffers yourself."
535 :group 'org-structure
536 :group 'org-agenda-windows
537 :type '(choice
538 (const :tag "In current window" current-window)
539 (const :tag "In current frame, other window" other-window)
540 (const :tag "Each time a new frame" new-frame)
541 (const :tag "One dedicated frame" dedicated-frame)))
543 (defgroup org-cycle nil
544 "Options concerning visibility cycling in Org-mode."
545 :tag "Org Cycle"
546 :group 'org-structure)
548 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
549 "Names of drawers. Drawers are not opened by cycling on the headline above.
550 Drawers only open with a TAB on the drawer line itself. A drawer looks like
551 this:
552 :DRAWERNAME:
553 .....
554 :END:
555 The drawer \"PROPERTIES\" is special for capturing properties through
556 the property API.
558 Drawers can be defined on the per-file basis with a line like:
560 #+DRAWERS: HIDDEN STATE PROPERTIES"
561 :group 'org-structure
562 :type '(repeat (string :tag "Drawer Name")))
564 (defcustom org-cycle-global-at-bob nil
565 "Cycle globally if cursor is at beginning of buffer and not at a headline.
566 This makes it possible to do global cycling without having to use S-TAB or
567 C-u TAB. For this special case to work, the first line of the buffer
568 must not be a headline - it may be empty or some other text. When used in
569 this way, `org-cycle-hook' is disables temporarily, to make sure the
570 cursor stays at the beginning of the buffer.
571 When this option is nil, don't do anything special at the beginning
572 of the buffer."
573 :group 'org-cycle
574 :type 'boolean)
576 (defcustom org-cycle-emulate-tab t
577 "Where should `org-cycle' emulate TAB.
578 nil Never
579 white Only in completely white lines
580 whitestart Only at the beginning of lines, before the first non-white char
581 t Everywhere except in headlines
582 exc-hl-bol Everywhere except at the start of a headline
583 If TAB is used in a place where it does not emulate TAB, the current subtree
584 visibility is cycled."
585 :group 'org-cycle
586 :type '(choice (const :tag "Never" nil)
587 (const :tag "Only in completely white lines" white)
588 (const :tag "Before first char in a line" whitestart)
589 (const :tag "Everywhere except in headlines" t)
590 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
593 (defcustom org-cycle-separator-lines 2
594 "Number of empty lines needed to keep an empty line between collapsed trees.
595 If you leave an empty line between the end of a subtree and the following
596 headline, this empty line is hidden when the subtree is folded.
597 Org-mode will leave (exactly) one empty line visible if the number of
598 empty lines is equal or larger to the number given in this variable.
599 So the default 2 means, at least 2 empty lines after the end of a subtree
600 are needed to produce free space between a collapsed subtree and the
601 following headline.
603 Special case: when 0, never leave empty lines in collapsed view."
604 :group 'org-cycle
605 :type 'integer)
606 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
608 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
609 org-cycle-hide-drawers
610 org-cycle-show-empty-lines
611 org-optimize-window-after-visibility-change)
612 "Hook that is run after `org-cycle' has changed the buffer visibility.
613 The function(s) in this hook must accept a single argument which indicates
614 the new state that was set by the most recent `org-cycle' command. The
615 argument is a symbol. After a global state change, it can have the values
616 `overview', `content', or `all'. After a local state change, it can have
617 the values `folded', `children', or `subtree'."
618 :group 'org-cycle
619 :type 'hook)
621 (defgroup org-edit-structure nil
622 "Options concerning structure editing in Org-mode."
623 :tag "Org Edit Structure"
624 :group 'org-structure)
626 (defcustom org-odd-levels-only nil
627 "Non-nil means, skip even levels and only use odd levels for the outline.
628 This has the effect that two stars are being added/taken away in
629 promotion/demotion commands. It also influences how levels are
630 handled by the exporters.
631 Changing it requires restart of `font-lock-mode' to become effective
632 for fontification also in regions already fontified.
633 You may also set this on a per-file basis by adding one of the following
634 lines to the buffer:
636 #+STARTUP: odd
637 #+STARTUP: oddeven"
638 :group 'org-edit-structure
639 :group 'org-font-lock
640 :type 'boolean)
642 (defcustom org-adapt-indentation t
643 "Non-nil means, adapt indentation when promoting and demoting.
644 When this is set and the *entire* text in an entry is indented, the
645 indentation is increased by one space in a demotion command, and
646 decreased by one in a promotion command. If any line in the entry
647 body starts at column 0, indentation is not changed at all."
648 :group 'org-edit-structure
649 :type 'boolean)
651 (defcustom org-special-ctrl-a/e nil
652 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
653 When t, `C-a' will bring back the cursor to the beginning of the
654 headline text, i.e. after the stars and after a possible TODO keyword.
655 In an item, this will be the position after the bullet.
656 When the cursor is already at that position, another `C-a' will bring
657 it to the beginning of the line.
658 `C-e' will jump to the end of the headline, ignoring the presence of tags
659 in the headline. A second `C-e' will then jump to the true end of the
660 line, after any tags.
661 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
662 and only a directly following, identical keypress will bring the cursor
663 to the special positions."
664 :group 'org-edit-structure
665 :type '(choice
666 (const :tag "off" nil)
667 (const :tag "after bullet first" t)
668 (const :tag "border first" reversed)))
670 (if (fboundp 'defvaralias)
671 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
673 (defcustom org-special-ctrl-k nil
674 "Non-nil means `C-k' will behave specially in headlines.
675 When nil, `C-k' will call the default `kill-line' command.
676 When t, the following will happen while the cursor is in the headline:
678 - When the cursor is at the beginning of a headline, kill the entire
679 line and possible the folded subtree below the line.
680 - When in the middle of the headline text, kill the headline up to the tags.
681 - When after the headline text, kill the tags."
682 :group 'org-edit-structure
683 :type 'boolean)
685 (defcustom org-yank-folded-subtrees t
686 "Non-nil means, when yanking subtrees, fold them.
687 If the kill is a single subtree, or a sequence of subtrees, i.e. if
688 it starts with a heading and all other headings in it are either children
689 or siblings, then fold all the subtrees. However, do this only if no
690 text after the yank would be swallowed into a folded tree by this action."
691 :group 'org-edit-structure
692 :type 'boolean)
694 (defcustom org-yank-adjusted-subtrees nil
695 "Non-nil means, when yanking subtrees, adjust the level.
696 With this setting, `org-paste-subtree' is used to insert the subtree, see
697 this function for details."
698 :group 'org-edit-structure
699 :type 'boolean)
701 (defcustom org-M-RET-may-split-line '((default . t))
702 "Non-nil means, M-RET will split the line at the cursor position.
703 When nil, it will go to the end of the line before making a
704 new line.
705 You may also set this option in a different way for different
706 contexts. Valid contexts are:
708 headline when creating a new headline
709 item when creating a new item
710 table in a table field
711 default the value to be used for all contexts not explicitly
712 customized"
713 :group 'org-structure
714 :group 'org-table
715 :type '(choice
716 (const :tag "Always" t)
717 (const :tag "Never" nil)
718 (repeat :greedy t :tag "Individual contexts"
719 (cons
720 (choice :tag "Context"
721 (const headline)
722 (const item)
723 (const table)
724 (const default))
725 (boolean)))))
728 (defcustom org-insert-heading-respect-content nil
729 "Non-nil means, insert new headings after the current subtree.
730 When nil, the new heading is created directly after the current line.
731 The commands \\[org-insert-heading-respect-content] and
732 \\[org-insert-todo-heading-respect-content] turn this variable on
733 for the duration of the command."
734 :group 'org-structure
735 :type 'boolean)
737 (defcustom org-blank-before-new-entry '((heading . auto)
738 (plain-list-item . auto))
739 "Should `org-insert-heading' leave a blank line before new heading/item?
740 The value is an alist, with `heading' and `plain-list-item' as car,
741 and a boolean flag as cdr."
742 :group 'org-edit-structure
743 :type '(list
744 (cons (const heading)
745 (choice (const :tag "Never" nil)
746 (const :tag "Always" t)
747 (const :tag "Auto" auto)))
748 (cons (const plain-list-item)
749 (choice (const :tag "Never" nil)
750 (const :tag "Always" t)
751 (const :tag "Auto" auto)))))
753 (defcustom org-insert-heading-hook nil
754 "Hook being run after inserting a new heading."
755 :group 'org-edit-structure
756 :type 'hook)
758 (defcustom org-enable-fixed-width-editor t
759 "Non-nil means, lines starting with \":\" are treated as fixed-width.
760 This currently only means, they are never auto-wrapped.
761 When nil, such lines will be treated like ordinary lines.
762 See also the QUOTE keyword."
763 :group 'org-edit-structure
764 :type 'boolean)
766 (defcustom org-edit-src-region-extra nil
767 "Additional regexps to identify regions for editing with `org-edit-src-code'.
768 For examples see the function `org-edit-src-find-region-and-lang'.
769 The regular expression identifying the begin marker should end with a newline,
770 and the regexp marking the end line should start with a newline, to make sure
771 there are kept outside the narrowed region."
772 :group 'org-edit-structure
773 :type '(repeat
774 (list
775 (regexp :tag "begin regexp")
776 (regexp :tag "end regexp")
777 (choice :tag "language"
778 (string :tag "specify")
779 (integer :tag "from match group")
780 (const :tag "from `lang' element")
781 (const :tag "from `style' element")))))
783 (defcustom org-coderef-label-format "(ref:%s)"
784 "The default coderef format.
785 This format string will be used to search for coderef labels in literal
786 examples (EXAMPLE and SRC blocks). The format can be overwritten
787 an individual literal example with the -f option, like
789 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
791 #+END_SRC
793 If you want to use this for HTML export, make sure that the format does
794 not introduce special font-locking, and avoid the HTML special
795 characters `<', `>', and `&'. The reason for this restriction is that
796 the labels are searched for only after htmlize has done its job."
797 :group 'org-edit-structure ; FIXME this is not in the right group
798 :type 'string)
800 (defcustom org-edit-fixed-width-region-mode 'artist-mode
801 "The mode that should be used to edit fixed-width regions.
802 These are the regions where each line starts with a colon."
803 :group 'org-edit-structure
804 :type '(choice
805 (const artist-mode)
806 (const picture-mode)
807 (const fundamental-mode)
808 (function :tag "Other (specify)")))
810 (defcustom org-goto-auto-isearch t
811 "Non-nil means, typing characters in org-goto starts incremental search."
812 :group 'org-edit-structure
813 :type 'boolean)
815 (defgroup org-sparse-trees nil
816 "Options concerning sparse trees in Org-mode."
817 :tag "Org Sparse Trees"
818 :group 'org-structure)
820 (defcustom org-highlight-sparse-tree-matches t
821 "Non-nil means, highlight all matches that define a sparse tree.
822 The highlights will automatically disappear the next time the buffer is
823 changed by an edit command."
824 :group 'org-sparse-trees
825 :type 'boolean)
827 (defcustom org-remove-highlights-with-change t
828 "Non-nil means, any change to the buffer will remove temporary highlights.
829 Such highlights are created by `org-occur' and `org-clock-display'.
830 When nil, `C-c C-c needs to be used to get rid of the highlights.
831 The highlights created by `org-preview-latex-fragment' always need
832 `C-c C-c' to be removed."
833 :group 'org-sparse-trees
834 :group 'org-time
835 :type 'boolean)
838 (defcustom org-occur-hook '(org-first-headline-recenter)
839 "Hook that is run after `org-occur' has constructed a sparse tree.
840 This can be used to recenter the window to show as much of the structure
841 as possible."
842 :group 'org-sparse-trees
843 :type 'hook)
845 (defgroup org-imenu-and-speedbar nil
846 "Options concerning imenu and speedbar in Org-mode."
847 :tag "Org Imenu and Speedbar"
848 :group 'org-structure)
850 (defcustom org-imenu-depth 2
851 "The maximum level for Imenu access to Org-mode headlines.
852 This also applied for speedbar access."
853 :group 'org-imenu-and-speedbar
854 :type 'number)
856 (defgroup org-table nil
857 "Options concerning tables in Org-mode."
858 :tag "Org Table"
859 :group 'org)
861 (defcustom org-enable-table-editor 'optimized
862 "Non-nil means, lines starting with \"|\" are handled by the table editor.
863 When nil, such lines will be treated like ordinary lines.
865 When equal to the symbol `optimized', the table editor will be optimized to
866 do the following:
867 - Automatic overwrite mode in front of whitespace in table fields.
868 This makes the structure of the table stay in tact as long as the edited
869 field does not exceed the column width.
870 - Minimize the number of realigns. Normally, the table is aligned each time
871 TAB or RET are pressed to move to another field. With optimization this
872 happens only if changes to a field might have changed the column width.
873 Optimization requires replacing the functions `self-insert-command',
874 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
875 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
876 very good at guessing when a re-align will be necessary, but you can always
877 force one with \\[org-ctrl-c-ctrl-c].
879 If you would like to use the optimized version in Org-mode, but the
880 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
882 This variable can be used to turn on and off the table editor during a session,
883 but in order to toggle optimization, a restart is required.
885 See also the variable `org-table-auto-blank-field'."
886 :group 'org-table
887 :type '(choice
888 (const :tag "off" nil)
889 (const :tag "on" t)
890 (const :tag "on, optimized" optimized)))
892 (defcustom org-table-tab-recognizes-table.el t
893 "Non-nil means, TAB will automatically notice a table.el table.
894 When it sees such a table, it moves point into it and - if necessary -
895 calls `table-recognize-table'."
896 :group 'org-table-editing
897 :type 'boolean)
899 (defgroup org-link nil
900 "Options concerning links in Org-mode."
901 :tag "Org Link"
902 :group 'org)
904 (defvar org-link-abbrev-alist-local nil
905 "Buffer-local version of `org-link-abbrev-alist', which see.
906 The value of this is taken from the #+LINK lines.")
907 (make-variable-buffer-local 'org-link-abbrev-alist-local)
909 (defcustom org-link-abbrev-alist nil
910 "Alist of link abbreviations.
911 The car of each element is a string, to be replaced at the start of a link.
912 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
913 links in Org-mode buffers can have an optional tag after a double colon, e.g.
915 [[linkkey:tag][description]]
917 If REPLACE is a string, the tag will simply be appended to create the link.
918 If the string contains \"%s\", the tag will be inserted there. Alternatively,
919 the placeholder \"%h\" will cause a url-encoded version of the tag to
920 be inserted at that point (see the function `url-hexify-string').
922 REPLACE may also be a function that will be called with the tag as the
923 only argument to create the link, which should be returned as a string.
925 See the manual for examples."
926 :group 'org-link
927 :type '(repeat
928 (cons
929 (string :tag "Protocol")
930 (choice
931 (string :tag "Format")
932 (function)))))
934 (defcustom org-descriptive-links t
935 "Non-nil means, hide link part and only show description of bracket links.
936 Bracket links are like [[link][description]]. This variable sets the initial
937 state in new org-mode buffers. The setting can then be toggled on a
938 per-buffer basis from the Org->Hyperlinks menu."
939 :group 'org-link
940 :type 'boolean)
942 (defcustom org-link-file-path-type 'adaptive
943 "How the path name in file links should be stored.
944 Valid values are:
946 relative Relative to the current directory, i.e. the directory of the file
947 into which the link is being inserted.
948 absolute Absolute path, if possible with ~ for home directory.
949 noabbrev Absolute path, no abbreviation of home directory.
950 adaptive Use relative path for files in the current directory and sub-
951 directories of it. For other files, use an absolute path."
952 :group 'org-link
953 :type '(choice
954 (const relative)
955 (const absolute)
956 (const noabbrev)
957 (const adaptive)))
959 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
960 "Types of links that should be activated in Org-mode files.
961 This is a list of symbols, each leading to the activation of a certain link
962 type. In principle, it does not hurt to turn on most link types - there may
963 be a small gain when turning off unused link types. The types are:
965 bracket The recommended [[link][description]] or [[link]] links with hiding.
966 angular Links in angular brackets that may contain whitespace like
967 <bbdb:Carsten Dominik>.
968 plain Plain links in normal text, no whitespace, like http://google.com.
969 radio Text that is matched by a radio target, see manual for details.
970 tag Tag settings in a headline (link to tag search).
971 date Time stamps (link to calendar).
972 footnote Footnote labels.
974 Changing this variable requires a restart of Emacs to become effective."
975 :group 'org-link
976 :type '(set :greedy t
977 (const :tag "Double bracket links (new style)" bracket)
978 (const :tag "Angular bracket links (old style)" angular)
979 (const :tag "Plain text links" plain)
980 (const :tag "Radio target matches" radio)
981 (const :tag "Tags" tag)
982 (const :tag "Timestamps" date)
983 (const :tag "Footnotes" footnote)))
985 (defcustom org-make-link-description-function nil
986 "Function to use to generate link descriptions from links. If
987 nil the link location will be used. This function must take two
988 parameters; the first is the link and the second the description
989 org-insert-link has generated, and should return the description
990 to use."
991 :group 'org-link
992 :type 'function)
994 (defgroup org-link-store nil
995 "Options concerning storing links in Org-mode."
996 :tag "Org Store Link"
997 :group 'org-link)
999 (defcustom org-email-link-description-format "Email %c: %.30s"
1000 "Format of the description part of a link to an email or usenet message.
1001 The following %-escapes will be replaced by corresponding information:
1003 %F full \"From\" field
1004 %f name, taken from \"From\" field, address if no name
1005 %T full \"To\" field
1006 %t first name in \"To\" field, address if no name
1007 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1008 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1009 %s subject
1010 %m message-id.
1012 You may use normal field width specification between the % and the letter.
1013 This is for example useful to limit the length of the subject.
1015 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1016 :group 'org-link-store
1017 :type 'string)
1019 (defcustom org-from-is-user-regexp
1020 (let (r1 r2)
1021 (when (and user-mail-address (not (string= user-mail-address "")))
1022 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1023 (when (and user-full-name (not (string= user-full-name "")))
1024 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1025 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1026 "Regexp matched against the \"From:\" header of an email or usenet message.
1027 It should match if the message is from the user him/herself."
1028 :group 'org-link-store
1029 :type 'regexp)
1031 (defcustom org-link-to-org-use-id 'create-if-interactive
1032 "Non-nil means, storing a link to an Org file will use entry IDs.
1034 Note that before this variable is even considered, org-id must be loaded,
1035 to please customize `org-modules' and turn it on.
1037 The variable can have the following values:
1039 t Create an ID if needed to make a link to the current entry.
1041 create-if-interactive
1042 If `org-store-link' is called directly (interactively, as a user
1043 command), do create an ID to support the link. But when doing the
1044 job for remember, only use the ID if it already exists. The
1045 purpose of this setting is to avoid proliferation of unwanted
1046 IDs, just because you happen to be in an Org file when you
1047 call `org-remember' that automatically and preemptively
1048 creates a link. If you do want to get an ID link in a remember
1049 template to an entry not having an ID, create it first by
1050 explicitly creating a link to it, using `C-c C-l' first.
1052 use-existing
1053 Use existing ID, do not create one.
1055 nil Never use an ID to make a link, instead link using a text search for
1056 the headline text."
1057 :group 'org-link-store
1058 :type '(choice
1059 (const :tag "Create ID to make link" t)
1060 (const :tag "Create if string link interactively"
1061 'create-if-interactive)
1062 (const :tag "Only use existing" 'use-existing)
1063 (const :tag "Do not use ID to create link" nil)))
1065 (defcustom org-context-in-file-links t
1066 "Non-nil means, file links from `org-store-link' contain context.
1067 A search string will be added to the file name with :: as separator and
1068 used to find the context when the link is activated by the command
1069 `org-open-at-point'.
1070 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1071 negates this setting for the duration of the command."
1072 :group 'org-link-store
1073 :type 'boolean)
1075 (defcustom org-keep-stored-link-after-insertion nil
1076 "Non-nil means, keep link in list for entire session.
1078 The command `org-store-link' adds a link pointing to the current
1079 location to an internal list. These links accumulate during a session.
1080 The command `org-insert-link' can be used to insert links into any
1081 Org-mode file (offering completion for all stored links). When this
1082 option is nil, every link which has been inserted once using \\[org-insert-link]
1083 will be removed from the list, to make completing the unused links
1084 more efficient."
1085 :group 'org-link-store
1086 :type 'boolean)
1088 (defgroup org-link-follow nil
1089 "Options concerning following links in Org-mode."
1090 :tag "Org Follow Link"
1091 :group 'org-link)
1093 (defcustom org-link-translation-function nil
1094 "Function to translate links with different syntax to Org syntax.
1095 This can be used to translate links created for example by the Planner
1096 or emacs-wiki packages to Org syntax.
1097 The function must accept two parameters, a TYPE containing the link
1098 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1099 which is everything after the link protocol. It should return a cons
1100 with possibly modified values of type and path.
1101 Org contains a function for this, so if you set this variable to
1102 `org-translate-link-from-planner', you should be able follow many
1103 links created by planner."
1104 :group 'org-link-follow
1105 :type 'function)
1107 (defcustom org-follow-link-hook nil
1108 "Hook that is run after a link has been followed."
1109 :group 'org-link-follow
1110 :type 'hook)
1112 (defcustom org-tab-follows-link nil
1113 "Non-nil means, on links TAB will follow the link.
1114 Needs to be set before org.el is loaded.
1115 This really should not be used, it does not make sense, and the
1116 implementation is bad."
1117 :group 'org-link-follow
1118 :type 'boolean)
1120 (defcustom org-return-follows-link nil
1121 "Non-nil means, on links RET will follow the link.
1122 Needs to be set before org.el is loaded."
1123 :group 'org-link-follow
1124 :type 'boolean)
1126 (defcustom org-mouse-1-follows-link
1127 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1128 "Non-nil means, mouse-1 on a link will follow the link.
1129 A longer mouse click will still set point. Does not work on XEmacs.
1130 Needs to be set before org.el is loaded."
1131 :group 'org-link-follow
1132 :type 'boolean)
1134 (defcustom org-mark-ring-length 4
1135 "Number of different positions to be recorded in the ring
1136 Changing this requires a restart of Emacs to work correctly."
1137 :group 'org-link-follow
1138 :type 'integer)
1140 (defcustom org-link-frame-setup
1141 '((vm . vm-visit-folder-other-frame)
1142 (gnus . gnus-other-frame)
1143 (file . find-file-other-window))
1144 "Setup the frame configuration for following links.
1145 When following a link with Emacs, it may often be useful to display
1146 this link in another window or frame. This variable can be used to
1147 set this up for the different types of links.
1148 For VM, use any of
1149 `vm-visit-folder'
1150 `vm-visit-folder-other-frame'
1151 For Gnus, use any of
1152 `gnus'
1153 `gnus-other-frame'
1154 `org-gnus-no-new-news'
1155 For FILE, use any of
1156 `find-file'
1157 `find-file-other-window'
1158 `find-file-other-frame'
1159 For the calendar, use the variable `calendar-setup'.
1160 For BBDB, it is currently only possible to display the matches in
1161 another window."
1162 :group 'org-link-follow
1163 :type '(list
1164 (cons (const vm)
1165 (choice
1166 (const vm-visit-folder)
1167 (const vm-visit-folder-other-window)
1168 (const vm-visit-folder-other-frame)))
1169 (cons (const gnus)
1170 (choice
1171 (const gnus)
1172 (const gnus-other-frame)
1173 (const org-gnus-no-new-news)))
1174 (cons (const file)
1175 (choice
1176 (const find-file)
1177 (const find-file-other-window)
1178 (const find-file-other-frame)))))
1180 (defcustom org-display-internal-link-with-indirect-buffer nil
1181 "Non-nil means, use indirect buffer to display infile links.
1182 Activating internal links (from one location in a file to another location
1183 in the same file) normally just jumps to the location. When the link is
1184 activated with a C-u prefix (or with mouse-3), the link is displayed in
1185 another window. When this option is set, the other window actually displays
1186 an indirect buffer clone of the current buffer, to avoid any visibility
1187 changes to the current buffer."
1188 :group 'org-link-follow
1189 :type 'boolean)
1191 (defcustom org-open-non-existing-files nil
1192 "Non-nil means, `org-open-file' will open non-existing files.
1193 When nil, an error will be generated."
1194 :group 'org-link-follow
1195 :type 'boolean)
1197 (defcustom org-open-directory-means-index-dot-org nil
1198 "Non-nil means, a link to a directory really means to index.org.
1199 When nil, following a directory link will run dired or open a finder/explorer
1200 window on that directory."
1201 :group 'org-link-follow
1202 :type 'boolean)
1204 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1205 "Function and arguments to call for following mailto links.
1206 This is a list with the first element being a lisp function, and the
1207 remaining elements being arguments to the function. In string arguments,
1208 %a will be replaced by the address, and %s will be replaced by the subject
1209 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1210 :group 'org-link-follow
1211 :type '(choice
1212 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1213 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1214 (const :tag "message-mail" (message-mail "%a" "%s"))
1215 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1217 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1218 "Non-nil means, ask for confirmation before executing shell links.
1219 Shell links can be dangerous: just think about a link
1221 [[shell:rm -rf ~/*][Google Search]]
1223 This link would show up in your Org-mode document as \"Google Search\",
1224 but really it would remove your entire home directory.
1225 Therefore we advise against setting this variable to nil.
1226 Just change it to `y-or-n-p' of you want to confirm with a
1227 single keystroke rather than having to type \"yes\"."
1228 :group 'org-link-follow
1229 :type '(choice
1230 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1231 (const :tag "with y-or-n (faster)" y-or-n-p)
1232 (const :tag "no confirmation (dangerous)" nil)))
1234 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1235 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1236 Elisp links can be dangerous: just think about a link
1238 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1240 This link would show up in your Org-mode document as \"Google Search\",
1241 but really it would remove your entire home directory.
1242 Therefore we advise against setting this variable to nil.
1243 Just change it to `y-or-n-p' of you want to confirm with a
1244 single keystroke rather than having to type \"yes\"."
1245 :group 'org-link-follow
1246 :type '(choice
1247 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1248 (const :tag "with y-or-n (faster)" y-or-n-p)
1249 (const :tag "no confirmation (dangerous)" nil)))
1251 (defconst org-file-apps-defaults-gnu
1252 '((remote . emacs)
1253 (system . mailcap)
1254 (t . mailcap))
1255 "Default file applications on a UNIX or GNU/Linux system.
1256 See `org-file-apps'.")
1258 (defconst org-file-apps-defaults-macosx
1259 '((remote . emacs)
1260 (t . "open %s")
1261 (system . "open %s")
1262 ("ps.gz" . "gv %s")
1263 ("eps.gz" . "gv %s")
1264 ("dvi" . "xdvi %s")
1265 ("fig" . "xfig %s"))
1266 "Default file applications on a MacOS X system.
1267 The system \"open\" is known as a default, but we use X11 applications
1268 for some files for which the OS does not have a good default.
1269 See `org-file-apps'.")
1271 (defconst org-file-apps-defaults-windowsnt
1272 (list
1273 '(remote . emacs)
1274 (cons t
1275 (list (if (featurep 'xemacs)
1276 'mswindows-shell-execute
1277 'w32-shell-execute)
1278 "open" 'file))
1279 (cons 'system
1280 (list (if (featurep 'xemacs)
1281 'mswindows-shell-execute
1282 'w32-shell-execute)
1283 "open" 'file)))
1284 "Default file applications on a Windows NT system.
1285 The system \"open\" is used for most files.
1286 See `org-file-apps'.")
1288 (defcustom org-file-apps
1290 (auto-mode . emacs)
1291 ("\\.x?html?\\'" . default)
1292 ("\\.pdf\\'" . default)
1294 "External applications for opening `file:path' items in a document.
1295 Org-mode uses system defaults for different file types, but
1296 you can use this variable to set the application for a given file
1297 extension. The entries in this list are cons cells where the car identifies
1298 files and the cdr the corresponding command. Possible values for the
1299 file identifier are
1300 \"regex\" Regular expression matched against the file name. For backward
1301 compatibility, this can also be a string with only alphanumeric
1302 characters, which is then interpreted as an extension.
1303 `directory' Matches a directory
1304 `remote' Matches a remote file, accessible through tramp or efs.
1305 Remote files most likely should be visited through Emacs
1306 because external applications cannot handle such paths.
1307 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1308 so all files Emacs knows how to handle. Using this with
1309 command `emacs' will open most files in Emacs. Beware that this
1310 will also open html files inside Emacs, unless you add
1311 (\"html\" . default) to the list as well.
1312 t Default for files not matched by any of the other options.
1313 `system' The system command to open files, like `open' on Windows
1314 and Mac OS X, and mailcap under GNU/Linux. This is the command
1315 that will be selected if you call `C-c C-o' with a double
1316 `C-u C-u' prefix.
1318 Possible values for the command are:
1319 `emacs' The file will be visited by the current Emacs process.
1320 `default' Use the default application for this file type, which is the
1321 association for t in the list, most likely in the system-specific
1322 part.
1323 This can be used to overrule an unwanted setting in the
1324 system-specific variable.
1325 `system' Use the system command for opening files, like \"open\".
1326 This command is specified by the entry whose car is `system'.
1327 Most likely, the system-specific version of this variable
1328 does define this command, but you can overrule/replace it
1329 here.
1330 string A command to be executed by a shell; %s will be replaced
1331 by the path to the file.
1332 sexp A Lisp form which will be evaluated. The file path will
1333 be available in the Lisp variable `file'.
1334 For more examples, see the system specific constants
1335 `org-file-apps-defaults-macosx'
1336 `org-file-apps-defaults-windowsnt'
1337 `org-file-apps-defaults-gnu'."
1338 :group 'org-link-follow
1339 :type '(repeat
1340 (cons (choice :value ""
1341 (string :tag "Extension")
1342 (const :tag "System command to open files" system)
1343 (const :tag "Default for unrecognized files" t)
1344 (const :tag "Remote file" remote)
1345 (const :tag "Links to a directory" directory)
1346 (const :tag "Any files that have Emacs modes"
1347 auto-mode))
1348 (choice :value ""
1349 (const :tag "Visit with Emacs" emacs)
1350 (const :tag "Use default" default)
1351 (const :tag "Use the system command" system)
1352 (string :tag "Command")
1353 (sexp :tag "Lisp form")))))
1355 (defgroup org-refile nil
1356 "Options concerning refiling entries in Org-mode."
1357 :tag "Org Refile"
1358 :group 'org)
1360 (defcustom org-directory "~/org"
1361 "Directory with org files.
1362 This is just a default location to look for Org files. There is no need
1363 at all to put your files into this directory. It is only used in the
1364 following situations:
1366 1. When a remember template specifies a target file that is not an
1367 absolute path. The path will then be interpreted relative to
1368 `org-directory'
1369 2. When a remember note is filed away in an interactive way (when exiting the
1370 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1371 with `org-directory' as the default path."
1372 :group 'org-refile
1373 :group 'org-remember
1374 :type 'directory)
1376 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1377 "Default target for storing notes.
1378 Used by the hooks for remember.el. This can be a string, or nil to mean
1379 the value of `remember-data-file'.
1380 You can set this on a per-template basis with the variable
1381 `org-remember-templates'."
1382 :group 'org-refile
1383 :group 'org-remember
1384 :type '(choice
1385 (const :tag "Default from remember-data-file" nil)
1386 file))
1388 (defcustom org-goto-interface 'outline
1389 "The default interface to be used for `org-goto'.
1390 Allowed values are:
1391 outline The interface shows an outline of the relevant file
1392 and the correct heading is found by moving through
1393 the outline or by searching with incremental search.
1394 outline-path-completion Headlines in the current buffer are offered via
1395 completion. This is the interface also used by
1396 the refile command."
1397 :group 'org-refile
1398 :type '(choice
1399 (const :tag "Outline" outline)
1400 (const :tag "Outline-path-completion" outline-path-completion)))
1402 (defcustom org-goto-max-level 5
1403 "Maximum level to be considered when running org-goto with refile interface."
1404 :group 'org-refile
1405 :type 'number)
1407 (defcustom org-reverse-note-order nil
1408 "Non-nil means, store new notes at the beginning of a file or entry.
1409 When nil, new notes will be filed to the end of a file or entry.
1410 This can also be a list with cons cells of regular expressions that
1411 are matched against file names, and values."
1412 :group 'org-remember
1413 :group 'org-refile
1414 :type '(choice
1415 (const :tag "Reverse always" t)
1416 (const :tag "Reverse never" nil)
1417 (repeat :tag "By file name regexp"
1418 (cons regexp boolean))))
1420 (defcustom org-refile-targets nil
1421 "Targets for refiling entries with \\[org-refile].
1422 This is list of cons cells. Each cell contains:
1423 - a specification of the files to be considered, either a list of files,
1424 or a symbol whose function or variable value will be used to retrieve
1425 a file name or a list of file names. If you use `org-agenda-files' for
1426 that, all agenda files will be scanned for targets. Nil means, consider
1427 headings in the current buffer.
1428 - A specification of how to find candidate refile targets. This may be
1429 any of:
1430 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1431 This tag has to be present in all target headlines, inheritance will
1432 not be considered.
1433 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1434 todo keyword.
1435 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1436 headlines that are refiling targets.
1437 - a cons cell (:level . N). Any headline of level N is considered a target.
1438 Note that, when `org-odd-levels-only' is set, level corresponds to
1439 order in hierarchy, not to the number of stars.
1440 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1441 Note that, when `org-odd-levels-only' is set, level corresponds to
1442 order in hierarchy, not to the number of stars.
1444 When this variable is nil, all top-level headlines in the current buffer
1445 are used, equivalent to the value `((nil . (:level . 1))'."
1446 :group 'org-refile
1447 :type '(repeat
1448 (cons
1449 (choice :value org-agenda-files
1450 (const :tag "All agenda files" org-agenda-files)
1451 (const :tag "Current buffer" nil)
1452 (function) (variable) (file))
1453 (choice :tag "Identify target headline by"
1454 (cons :tag "Specific tag" (const :value :tag) (string))
1455 (cons :tag "TODO keyword" (const :value :todo) (string))
1456 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1457 (cons :tag "Level number" (const :value :level) (integer))
1458 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1460 (defcustom org-refile-use-outline-path nil
1461 "Non-nil means, provide refile targets as paths.
1462 So a level 3 headline will be available as level1/level2/level3.
1463 When the value is `file', also include the file name (without directory)
1464 into the path. When `full-file-path', include the full file path."
1465 :group 'org-refile
1466 :type '(choice
1467 (const :tag "Not" nil)
1468 (const :tag "Yes" t)
1469 (const :tag "Start with file name" file)
1470 (const :tag "Start with full file path" full-file-path)))
1472 (defcustom org-outline-path-complete-in-steps t
1473 "Non-nil means, complete the outline path in hierarchical steps.
1474 When Org-mode uses the refile interface to select an outline path
1475 \(see variable `org-refile-use-outline-path'), the completion of
1476 the path can be done is a single go, or if can be done in steps down
1477 the headline hierarchy. Going in steps is probably the best if you
1478 do not use a special completion package like `ido' or `icicles'.
1479 However, when using these packages, going in one step can be very
1480 fast, while still showing the whole path to the entry."
1481 :group 'org-refile
1482 :type 'boolean)
1484 (defgroup org-todo nil
1485 "Options concerning TODO items in Org-mode."
1486 :tag "Org TODO"
1487 :group 'org)
1489 (defgroup org-progress nil
1490 "Options concerning Progress logging in Org-mode."
1491 :tag "Org Progress"
1492 :group 'org-time)
1494 (defvar org-todo-interpretation-widgets
1496 (:tag "Sequence (cycling hits every state)" sequence)
1497 (:tag "Type (cycling directly to DONE)" type))
1498 "The available interpretation symbols for customizing
1499 `org-todo-keywords'.
1500 Interested libraries should add to this list.")
1502 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1503 "List of TODO entry keyword sequences and their interpretation.
1504 \\<org-mode-map>This is a list of sequences.
1506 Each sequence starts with a symbol, either `sequence' or `type',
1507 indicating if the keywords should be interpreted as a sequence of
1508 action steps, or as different types of TODO items. The first
1509 keywords are states requiring action - these states will select a headline
1510 for inclusion into the global TODO list Org-mode produces. If one of
1511 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1512 signify that no further action is necessary. If \"|\" is not found,
1513 the last keyword is treated as the only DONE state of the sequence.
1515 The command \\[org-todo] cycles an entry through these states, and one
1516 additional state where no keyword is present. For details about this
1517 cycling, see the manual.
1519 TODO keywords and interpretation can also be set on a per-file basis with
1520 the special #+SEQ_TODO and #+TYP_TODO lines.
1522 Each keyword can optionally specify a character for fast state selection
1523 \(in combination with the variable `org-use-fast-todo-selection')
1524 and specifiers for state change logging, using the same syntax
1525 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1526 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1527 indicates to record a time stamp each time this state is selected.
1529 Each keyword may also specify if a timestamp or a note should be
1530 recorded when entering or leaving the state, by adding additional
1531 characters in the parenthesis after the keyword. This looks like this:
1532 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1533 record only the time of the state change. With X and Y being either
1534 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1535 Y when leaving the state if and only if the *target* state does not
1536 define X. You may omit any of the fast-selection key or X or /Y,
1537 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1539 For backward compatibility, this variable may also be just a list
1540 of keywords - in this case the interpretation (sequence or type) will be
1541 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1542 :group 'org-todo
1543 :group 'org-keywords
1544 :type '(choice
1545 (repeat :tag "Old syntax, just keywords"
1546 (string :tag "Keyword"))
1547 (repeat :tag "New syntax"
1548 (cons
1549 (choice
1550 :tag "Interpretation"
1551 ;;Quick and dirty way to see
1552 ;;`org-todo-interpretations'. This takes the
1553 ;;place of item arguments
1554 :convert-widget
1555 (lambda (widget)
1556 (widget-put widget
1557 :args (mapcar
1558 #'(lambda (x)
1559 (widget-convert
1560 (cons 'const x)))
1561 org-todo-interpretation-widgets))
1562 widget))
1563 (repeat
1564 (string :tag "Keyword"))))))
1566 (defvar org-todo-keywords-1 nil
1567 "All TODO and DONE keywords active in a buffer.")
1568 (make-variable-buffer-local 'org-todo-keywords-1)
1569 (defvar org-todo-keywords-for-agenda nil)
1570 (defvar org-done-keywords-for-agenda nil)
1571 (defvar org-todo-keyword-alist-for-agenda nil)
1572 (defvar org-tag-alist-for-agenda nil)
1573 (defvar org-agenda-contributing-files nil)
1574 (defvar org-not-done-keywords nil)
1575 (make-variable-buffer-local 'org-not-done-keywords)
1576 (defvar org-done-keywords nil)
1577 (make-variable-buffer-local 'org-done-keywords)
1578 (defvar org-todo-heads nil)
1579 (make-variable-buffer-local 'org-todo-heads)
1580 (defvar org-todo-sets nil)
1581 (make-variable-buffer-local 'org-todo-sets)
1582 (defvar org-todo-log-states nil)
1583 (make-variable-buffer-local 'org-todo-log-states)
1584 (defvar org-todo-kwd-alist nil)
1585 (make-variable-buffer-local 'org-todo-kwd-alist)
1586 (defvar org-todo-key-alist nil)
1587 (make-variable-buffer-local 'org-todo-key-alist)
1588 (defvar org-todo-key-trigger nil)
1589 (make-variable-buffer-local 'org-todo-key-trigger)
1591 (defcustom org-todo-interpretation 'sequence
1592 "Controls how TODO keywords are interpreted.
1593 This variable is in principle obsolete and is only used for
1594 backward compatibility, if the interpretation of todo keywords is
1595 not given already in `org-todo-keywords'. See that variable for
1596 more information."
1597 :group 'org-todo
1598 :group 'org-keywords
1599 :type '(choice (const sequence)
1600 (const type)))
1602 (defcustom org-use-fast-todo-selection t
1603 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1604 This variable describes if and under what circumstances the cycling
1605 mechanism for TODO keywords will be replaced by a single-key, direct
1606 selection scheme.
1608 When nil, fast selection is never used.
1610 When the symbol `prefix', it will be used when `org-todo' is called with
1611 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1612 in an agenda buffer.
1614 When t, fast selection is used by default. In this case, the prefix
1615 argument forces cycling instead.
1617 In all cases, the special interface is only used if access keys have actually
1618 been assigned by the user, i.e. if keywords in the configuration are followed
1619 by a letter in parenthesis, like TODO(t)."
1620 :group 'org-todo
1621 :type '(choice
1622 (const :tag "Never" nil)
1623 (const :tag "By default" t)
1624 (const :tag "Only with C-u C-c C-t" prefix)))
1626 (defcustom org-provide-todo-statistics t
1627 "Non-nil means, update todo statistics after insert and toggle.
1628 When this is set, todo statistics is updated in the parent of the current
1629 entry each time a todo state is changed."
1630 :group 'org-todo
1631 :type 'boolean)
1633 (defcustom org-after-todo-state-change-hook nil
1634 "Hook which is run after the state of a TODO item was changed.
1635 The new state (a string with a TODO keyword, or nil) is available in the
1636 Lisp variable `state'."
1637 :group 'org-todo
1638 :type 'hook)
1640 (defvar org-blocker-hook nil
1641 "Hook for functions that are allowed to block a state change.
1643 Each function gets as its single argument a property list, see
1644 `org-trigger-hook' for more information about this list.
1646 If any of the functions in this hook returns nil, the state change
1647 is blocked.")
1649 (defvar org-trigger-hook nil
1650 "Hook for functions that are triggered by a state change.
1652 Each function gets as its single argument a property list with at least
1653 the following elements:
1655 (:type type-of-change :position pos-at-entry-start
1656 :from old-state :to new-state)
1658 Depending on the type, more properties may be present.
1660 This mechanism is currently implemented for:
1662 TODO state changes
1663 ------------------
1664 :type todo-state-change
1665 :from previous state (keyword as a string), or nil, or a symbol
1666 'todo' or 'done', to indicate the general type of state.
1667 :to new state, like in :from")
1669 (defcustom org-enforce-todo-dependencies nil
1670 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1671 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1672 be blocked if any prior sibling is not yet done.
1673 This variable needs to be set before org.el is loaded, and you need to
1674 restart Emacs after a change to make the change effective. The only way
1675 to change is while Emacs is running is through the customize interface."
1676 :set (lambda (var val)
1677 (set var val)
1678 (if val
1679 (add-hook 'org-blocker-hook
1680 'org-block-todo-from-children-or-siblings)
1681 (remove-hook 'org-blocker-hook
1682 'org-block-todo-from-children-or-siblings)))
1683 :group 'org-todo
1684 :type 'boolean)
1686 (defcustom org-enforce-todo-checkbox-dependencies nil
1687 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1688 When this is nil, checkboxes have no influence on switching TODO states.
1689 When non-nil, you first need to check off all check boxes before the TODO
1690 entry can be switched to DONE.
1691 This variable needs to be set before org.el is loaded, and you need to
1692 restart Emacs after a change to make the change effective. The only way
1693 to change is while Emacs is running is through the customize interface."
1694 :set (lambda (var val)
1695 (set var val)
1696 (if val
1697 (add-hook 'org-blocker-hook
1698 'org-block-todo-from-checkboxes)
1699 (remove-hook 'org-blocker-hook
1700 'org-block-todo-from-checkboxes)))
1701 :group 'org-todo
1702 :type 'boolean)
1704 (defcustom org-todo-state-tags-triggers nil
1705 "Tag changes that should be triggered by TODO state changes.
1706 This is a list. Each entry is
1708 (state-change (tag . flag) .......)
1710 State-change can be a string with a state, and empty string to indicate the
1711 state that has no TODO keyword, or it can be one of the symbols `todo'
1712 or `done', meaning any not-done or done state, respectively."
1713 :group 'org-todo
1714 :group 'org-tags
1715 :type '(repeat
1716 (cons (choice :tag "When changing to"
1717 (const :tag "Not-done state" todo)
1718 (const :tag "Done state" done)
1719 (string :tag "State"))
1720 (repeat
1721 (cons :tag "Tag action"
1722 (string :tag "Tag")
1723 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1725 (defcustom org-log-done nil
1726 "Information to record when a task moves to the DONE state.
1728 Possible values are:
1730 nil Don't add anything, just change the keyword
1731 time Add a time stamp to the task
1732 note Prompt a closing note and add it with template `org-log-note-headings'
1734 This option can also be set with on a per-file-basis with
1736 #+STARTUP: nologdone
1737 #+STARTUP: logdone
1738 #+STARTUP: lognotedone
1740 You can have local logging settings for a subtree by setting the LOGGING
1741 property to one or more of these keywords."
1742 :group 'org-todo
1743 :group 'org-progress
1744 :type '(choice
1745 (const :tag "No logging" nil)
1746 (const :tag "Record CLOSED timestamp" time)
1747 (const :tag "Record CLOSED timestamp with closing note." note)))
1749 ;; Normalize old uses of org-log-done.
1750 (cond
1751 ((eq org-log-done t) (setq org-log-done 'time))
1752 ((and (listp org-log-done) (memq 'done org-log-done))
1753 (setq org-log-done 'note)))
1755 (defcustom org-log-note-clock-out nil
1756 "Non-nil means, record a note when clocking out of an item.
1757 This can also be configured on a per-file basis by adding one of
1758 the following lines anywhere in the buffer:
1760 #+STARTUP: lognoteclock-out
1761 #+STARTUP: nolognoteclock-out"
1762 :group 'org-todo
1763 :group 'org-progress
1764 :type 'boolean)
1766 (defcustom org-log-done-with-time t
1767 "Non-nil means, the CLOSED time stamp will contain date and time.
1768 When nil, only the date will be recorded."
1769 :group 'org-progress
1770 :type 'boolean)
1772 (defcustom org-log-note-headings
1773 '((done . "CLOSING NOTE %t")
1774 (state . "State %-12s from %-12S %t")
1775 (note . "Note taken on %t")
1776 (clock-out . ""))
1777 "Headings for notes added to entries.
1778 The value is an alist, with the car being a symbol indicating the note
1779 context, and the cdr is the heading to be used. The heading may also be the
1780 empty string.
1781 %t in the heading will be replaced by a time stamp.
1782 %s will be replaced by the new TODO state, in double quotes.
1783 %S will be replaced by the old TODO state, in double quotes.
1784 %u will be replaced by the user name.
1785 %U will be replaced by the full user name."
1786 :group 'org-todo
1787 :group 'org-progress
1788 :type '(list :greedy t
1789 (cons (const :tag "Heading when closing an item" done) string)
1790 (cons (const :tag
1791 "Heading when changing todo state (todo sequence only)"
1792 state) string)
1793 (cons (const :tag "Heading when just taking a note" note) string)
1794 (cons (const :tag "Heading when clocking out" clock-out) string)))
1796 (unless (assq 'note org-log-note-headings)
1797 (push '(note . "%t") org-log-note-headings))
1799 (defcustom org-log-into-drawer nil
1800 "Non-nil means, insert state change notes and time stamps into a drawer.
1801 When nil, state changes notes will be inserted after the headline and
1802 any scheduling and clock lines, but not inside a drawer.
1804 The value of this variable should be the name of the drawer to use.
1805 LOGBOOK is proposed at the default drawer for this purpose, you can
1806 also set this to a string to define the drawer of your choice.
1808 A value of t is also allowed, representing \"LOGBOOK\".
1810 If this variable is set, `org-log-state-notes-insert-after-drawers'
1811 will be ognored."
1812 :group 'org-todo
1813 :group 'org-progress
1814 :type '(choice
1815 (const :tag "Not into a drawer" nil)
1816 (const :tag "LOGBOOK" t)
1817 (string :tag "Other")))
1819 (if (fboundp 'defvaralias)
1820 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1822 (defcustom org-log-state-notes-insert-after-drawers nil
1823 "Non-nil means, insert state change notes after any drawers in entry.
1824 Only the drawers that *immediately* follow the headline and the
1825 deadline/scheduled line are skipped.
1826 When nil, insert notes right after the heading and perhaps the line
1827 with deadline/scheduling if present.
1829 This variable will have no effect if `org-log-into-drawer' is
1830 set."
1831 :group 'org-todo
1832 :group 'org-progress
1833 :type 'boolean)
1835 (defcustom org-log-states-order-reversed t
1836 "Non-nil means, the latest state change note will be directly after heading.
1837 When nil, the notes will be orderer according to time."
1838 :group 'org-todo
1839 :group 'org-progress
1840 :type 'boolean)
1842 (defcustom org-log-repeat 'time
1843 "Non-nil means, record moving through the DONE state when triggering repeat.
1844 An auto-repeating tasks is immediately switched back to TODO when marked
1845 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1846 the TODO keyword definition, or recording a closing note by setting
1847 `org-log-done', there will be no record of the task moving through DONE.
1848 This variable forces taking a note anyway. Possible values are:
1850 nil Don't force a record
1851 time Record a time stamp
1852 note Record a note
1854 This option can also be set with on a per-file-basis with
1856 #+STARTUP: logrepeat
1857 #+STARTUP: lognoterepeat
1858 #+STARTUP: nologrepeat
1860 You can have local logging settings for a subtree by setting the LOGGING
1861 property to one or more of these keywords."
1862 :group 'org-todo
1863 :group 'org-progress
1864 :type '(choice
1865 (const :tag "Don't force a record" nil)
1866 (const :tag "Force recording the DONE state" time)
1867 (const :tag "Force recording a note with the DONE state" note)))
1870 (defgroup org-priorities nil
1871 "Priorities in Org-mode."
1872 :tag "Org Priorities"
1873 :group 'org-todo)
1875 (defcustom org-highest-priority ?A
1876 "The highest priority of TODO items. A character like ?A, ?B etc.
1877 Must have a smaller ASCII number than `org-lowest-priority'."
1878 :group 'org-priorities
1879 :type 'character)
1881 (defcustom org-lowest-priority ?C
1882 "The lowest priority of TODO items. A character like ?A, ?B etc.
1883 Must have a larger ASCII number than `org-highest-priority'."
1884 :group 'org-priorities
1885 :type 'character)
1887 (defcustom org-default-priority ?B
1888 "The default priority of TODO items.
1889 This is the priority an item get if no explicit priority is given."
1890 :group 'org-priorities
1891 :type 'character)
1893 (defcustom org-priority-start-cycle-with-default t
1894 "Non-nil means, start with default priority when starting to cycle.
1895 When this is nil, the first step in the cycle will be (depending on the
1896 command used) one higher or lower that the default priority."
1897 :group 'org-priorities
1898 :type 'boolean)
1900 (defgroup org-time nil
1901 "Options concerning time stamps and deadlines in Org-mode."
1902 :tag "Org Time"
1903 :group 'org)
1905 (defcustom org-insert-labeled-timestamps-at-point nil
1906 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1907 When nil, these labeled time stamps are forces into the second line of an
1908 entry, just after the headline. When scheduling from the global TODO list,
1909 the time stamp will always be forced into the second line."
1910 :group 'org-time
1911 :type 'boolean)
1913 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1914 "Formats for `format-time-string' which are used for time stamps.
1915 It is not recommended to change this constant.")
1917 (defcustom org-time-stamp-rounding-minutes '(0 5)
1918 "Number of minutes to round time stamps to.
1919 These are two values, the first applies when first creating a time stamp.
1920 The second applies when changing it with the commands `S-up' and `S-down'.
1921 When changing the time stamp, this means that it will change in steps
1922 of N minutes, as given by the second value.
1924 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1925 numbers should be factors of 60, so for example 5, 10, 15.
1927 When this is larger than 1, you can still force an exact time-stamp by using
1928 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1929 and by using a prefix arg to `S-up/down' to specify the exact number
1930 of minutes to shift."
1931 :group 'org-time
1932 :get '(lambda (var) ; Make sure all entries have 5 elements
1933 (if (integerp (default-value var))
1934 (list (default-value var) 5)
1935 (default-value var)))
1936 :type '(list
1937 (integer :tag "when inserting times")
1938 (integer :tag "when modifying times")))
1940 ;; Normalize old customizations of this variable.
1941 (when (integerp org-time-stamp-rounding-minutes)
1942 (setq org-time-stamp-rounding-minutes
1943 (list org-time-stamp-rounding-minutes
1944 org-time-stamp-rounding-minutes)))
1946 (defcustom org-display-custom-times nil
1947 "Non-nil means, overlay custom formats over all time stamps.
1948 The formats are defined through the variable `org-time-stamp-custom-formats'.
1949 To turn this on on a per-file basis, insert anywhere in the file:
1950 #+STARTUP: customtime"
1951 :group 'org-time
1952 :set 'set-default
1953 :type 'sexp)
1954 (make-variable-buffer-local 'org-display-custom-times)
1956 (defcustom org-time-stamp-custom-formats
1957 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1958 "Custom formats for time stamps. See `format-time-string' for the syntax.
1959 These are overlayed over the default ISO format if the variable
1960 `org-display-custom-times' is set. Time like %H:%M should be at the
1961 end of the second format."
1962 :group 'org-time
1963 :type 'sexp)
1965 (defun org-time-stamp-format (&optional long inactive)
1966 "Get the right format for a time string."
1967 (let ((f (if long (cdr org-time-stamp-formats)
1968 (car org-time-stamp-formats))))
1969 (if inactive
1970 (concat "[" (substring f 1 -1) "]")
1971 f)))
1973 (defcustom org-time-clocksum-format "%d:%02d"
1974 "The format string used when creating CLOCKSUM lines, or when
1975 org-mode generates a time duration."
1976 :group 'org-time
1977 :type 'string)
1979 (defcustom org-deadline-warning-days 14
1980 "No. of days before expiration during which a deadline becomes active.
1981 This variable governs the display in sparse trees and in the agenda.
1982 When 0 or negative, it means use this number (the absolute value of it)
1983 even if a deadline has a different individual lead time specified."
1984 :group 'org-time
1985 :group 'org-agenda-daily/weekly
1986 :type 'number)
1988 (defcustom org-read-date-prefer-future t
1989 "Non-nil means, assume future for incomplete date input from user.
1990 This affects the following situations:
1991 1. The user gives a day, but no month.
1992 For example, if today is the 15th, and you enter \"3\", Org-mode will
1993 read this as the third of *next* month. However, if you enter \"17\",
1994 it will be considered as *this* month.
1995 2. The user gives a month but not a year.
1996 For example, if it is april and you enter \"feb 2\", this will be read
1997 as feb 2, *next* year. \"May 5\", however, will be this year.
1999 Currently this does not work for ISO week specifications.
2001 When this option is nil, the current month and year will always be used
2002 as defaults."
2003 :group 'org-time
2004 :type 'boolean)
2006 (defcustom org-read-date-display-live t
2007 "Non-nil means, display current interpretation of date prompt live.
2008 This display will be in an overlay, in the minibuffer."
2009 :group 'org-time
2010 :type 'boolean)
2012 (defcustom org-read-date-popup-calendar t
2013 "Non-nil means, pop up a calendar when prompting for a date.
2014 In the calendar, the date can be selected with mouse-1. However, the
2015 minibuffer will also be active, and you can simply enter the date as well.
2016 When nil, only the minibuffer will be available."
2017 :group 'org-time
2018 :type 'boolean)
2019 (if (fboundp 'defvaralias)
2020 (defvaralias 'org-popup-calendar-for-date-prompt
2021 'org-read-date-popup-calendar))
2023 (defcustom org-extend-today-until 0
2024 "The hour when your day really ends. Must be an integer.
2025 This has influence for the following applications:
2026 - When switching the agenda to \"today\". It it is still earlier than
2027 the time given here, the day recognized as TODAY is actually yesterday.
2028 - When a date is read from the user and it is still before the time given
2029 here, the current date and time will be assumed to be yesterday, 23:59.
2030 Also, timestamps inserted in remember templates follow this rule.
2032 IMPORTANT: This is a feature whose implementation is and likely will
2033 remain incomplete. Really, it is only here because past midnight seems to
2034 be the favorite working time of John Wiegley :-)"
2035 :group 'org-time
2036 :type 'number)
2038 (defcustom org-edit-timestamp-down-means-later nil
2039 "Non-nil means, S-down will increase the time in a time stamp.
2040 When nil, S-up will increase."
2041 :group 'org-time
2042 :type 'boolean)
2044 (defcustom org-calendar-follow-timestamp-change t
2045 "Non-nil means, make the calendar window follow timestamp changes.
2046 When a timestamp is modified and the calendar window is visible, it will be
2047 moved to the new date."
2048 :group 'org-time
2049 :type 'boolean)
2051 (defgroup org-tags nil
2052 "Options concerning tags in Org-mode."
2053 :tag "Org Tags"
2054 :group 'org)
2056 (defcustom org-tag-alist nil
2057 "List of tags allowed in Org-mode files.
2058 When this list is nil, Org-mode will base TAG input on what is already in the
2059 buffer.
2060 The value of this variable is an alist, the car of each entry must be a
2061 keyword as a string, the cdr may be a character that is used to select
2062 that tag through the fast-tag-selection interface.
2063 See the manual for details."
2064 :group 'org-tags
2065 :type '(repeat
2066 (choice
2067 (cons (string :tag "Tag name")
2068 (character :tag "Access char"))
2069 (const :tag "Start radio group" (:startgroup))
2070 (const :tag "End radio group" (:endgroup))
2071 (const :tag "New line" (:newline)))))
2073 (defvar org-file-tags nil
2074 "List of tags that can be inherited by all entries in the file.
2075 The tags will be inherited if the variable `org-use-tag-inheritance'
2076 says they should be.
2077 This variable is populated from #+TAG lines.")
2079 (defcustom org-use-fast-tag-selection 'auto
2080 "Non-nil means, use fast tag selection scheme.
2081 This is a special interface to select and deselect tags with single keys.
2082 When nil, fast selection is never used.
2083 When the symbol `auto', fast selection is used if and only if selection
2084 characters for tags have been configured, either through the variable
2085 `org-tag-alist' or through a #+TAGS line in the buffer.
2086 When t, fast selection is always used and selection keys are assigned
2087 automatically if necessary."
2088 :group 'org-tags
2089 :type '(choice
2090 (const :tag "Always" t)
2091 (const :tag "Never" nil)
2092 (const :tag "When selection characters are configured" 'auto)))
2094 (defcustom org-fast-tag-selection-single-key nil
2095 "Non-nil means, fast tag selection exits after first change.
2096 When nil, you have to press RET to exit it.
2097 During fast tag selection, you can toggle this flag with `C-c'.
2098 This variable can also have the value `expert'. In this case, the window
2099 displaying the tags menu is not even shown, until you press C-c again."
2100 :group 'org-tags
2101 :type '(choice
2102 (const :tag "No" nil)
2103 (const :tag "Yes" t)
2104 (const :tag "Expert" expert)))
2106 (defvar org-fast-tag-selection-include-todo nil
2107 "Non-nil means, fast tags selection interface will also offer TODO states.
2108 This is an undocumented feature, you should not rely on it.")
2110 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2111 "The column to which tags should be indented in a headline.
2112 If this number is positive, it specifies the column. If it is negative,
2113 it means that the tags should be flushright to that column. For example,
2114 -80 works well for a normal 80 character screen."
2115 :group 'org-tags
2116 :type 'integer)
2118 (defcustom org-auto-align-tags t
2119 "Non-nil means, realign tags after pro/demotion of TODO state change.
2120 These operations change the length of a headline and therefore shift
2121 the tags around. With this options turned on, after each such operation
2122 the tags are again aligned to `org-tags-column'."
2123 :group 'org-tags
2124 :type 'boolean)
2126 (defcustom org-use-tag-inheritance t
2127 "Non-nil means, tags in levels apply also for sublevels.
2128 When nil, only the tags directly given in a specific line apply there.
2129 This may also be a list of tags that should be inherited, or a regexp that
2130 matches tags that should be inherited. Additional control is possible
2131 with the variable `org-tags-exclude-from-inheritance' which gives an
2132 explicit list of tags to be excluded from inheritance., even if the value of
2133 `org-use-tag-inheritance' would select it for inheritance.
2135 If this option is t, a match early-on in a tree can lead to a large
2136 number of matches in the subtree when constructing the agenda or creating
2137 a sparse tree. If you only want to see the first match in a tree during
2138 a search, check out the variable `org-tags-match-list-sublevels'."
2139 :group 'org-tags
2140 :type '(choice
2141 (const :tag "Not" nil)
2142 (const :tag "Always" t)
2143 (repeat :tag "Specific tags" (string :tag "Tag"))
2144 (regexp :tag "Tags matched by regexp")))
2146 (defcustom org-tags-exclude-from-inheritance nil
2147 "List of tags that should never be inherited.
2148 This is a way to exclude a few tags from inheritance. For way to do
2149 the opposite, to actively allow inheritance for selected tags,
2150 see the variable `org-use-tag-inheritance'."
2151 :group 'org-tags
2152 :type '(repeat (string :tag "Tag")))
2154 (defun org-tag-inherit-p (tag)
2155 "Check if TAG is one that should be inherited."
2156 (cond
2157 ((member tag org-tags-exclude-from-inheritance) nil)
2158 ((eq org-use-tag-inheritance t) t)
2159 ((not org-use-tag-inheritance) nil)
2160 ((stringp org-use-tag-inheritance)
2161 (string-match org-use-tag-inheritance tag))
2162 ((listp org-use-tag-inheritance)
2163 (member tag org-use-tag-inheritance))
2164 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2166 (defcustom org-tags-match-list-sublevels t
2167 "Non-nil means list also sublevels of headlines matching tag search.
2168 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2169 the sublevels of a headline matching a tag search often also match
2170 the same search. Listing all of them can create very long lists.
2171 Setting this variable to nil causes subtrees of a match to be skipped.
2172 This option is off by default, because inheritance in on. If you turn
2173 inheritance off, you very likely want to turn this option on.
2175 As a special case, if the tag search is restricted to TODO items, the
2176 value of this variable is ignored and sublevels are always checked, to
2177 make sure all corresponding TODO items find their way into the list.
2179 This variable is semi-obsolete and probably should always be true. It
2180 is better to limit inheritance to certain tags using the variables
2181 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2182 :group 'org-tags
2183 :type 'boolean)
2185 (defvar org-tags-history nil
2186 "History of minibuffer reads for tags.")
2187 (defvar org-last-tags-completion-table nil
2188 "The last used completion table for tags.")
2189 (defvar org-after-tags-change-hook nil
2190 "Hook that is run after the tags in a line have changed.")
2192 (defgroup org-properties nil
2193 "Options concerning properties in Org-mode."
2194 :tag "Org Properties"
2195 :group 'org)
2197 (defcustom org-property-format "%-10s %s"
2198 "How property key/value pairs should be formatted by `indent-line'.
2199 When `indent-line' hits a property definition, it will format the line
2200 according to this format, mainly to make sure that the values are
2201 lined-up with respect to each other."
2202 :group 'org-properties
2203 :type 'string)
2205 (defcustom org-use-property-inheritance nil
2206 "Non-nil means, properties apply also for sublevels.
2208 This setting is chiefly used during property searches. Turning it on can
2209 cause significant overhead when doing a search, which is why it is not
2210 on by default.
2212 When nil, only the properties directly given in the current entry count.
2213 When t, every property is inherited. The value may also be a list of
2214 properties that should have inheritance, or a regular expression matching
2215 properties that should be inherited.
2217 However, note that some special properties use inheritance under special
2218 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2219 and the properties ending in \"_ALL\" when they are used as descriptor
2220 for valid values of a property.
2222 Note for programmers:
2223 When querying an entry with `org-entry-get', you can control if inheritance
2224 should be used. By default, `org-entry-get' looks only at the local
2225 properties. You can request inheritance by setting the inherit argument
2226 to t (to force inheritance) or to `selective' (to respect the setting
2227 in this variable)."
2228 :group 'org-properties
2229 :type '(choice
2230 (const :tag "Not" nil)
2231 (const :tag "Always" t)
2232 (repeat :tag "Specific properties" (string :tag "Property"))
2233 (regexp :tag "Properties matched by regexp")))
2235 (defun org-property-inherit-p (property)
2236 "Check if PROPERTY is one that should be inherited."
2237 (cond
2238 ((eq org-use-property-inheritance t) t)
2239 ((not org-use-property-inheritance) nil)
2240 ((stringp org-use-property-inheritance)
2241 (string-match org-use-property-inheritance property))
2242 ((listp org-use-property-inheritance)
2243 (member property org-use-property-inheritance))
2244 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2246 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2247 "The default column format, if no other format has been defined.
2248 This variable can be set on the per-file basis by inserting a line
2250 #+COLUMNS: %25ITEM ....."
2251 :group 'org-properties
2252 :type 'string)
2254 (defcustom org-columns-ellipses ".."
2255 "The ellipses to be used when a field in column view is truncated.
2256 When this is the empty string, as many characters as possible are shown,
2257 but then there will be no visual indication that the field has been truncated.
2258 When this is a string of length N, the last N characters of a truncated
2259 field are replaced by this string. If the column is narrower than the
2260 ellipses string, only part of the ellipses string will be shown."
2261 :group 'org-properties
2262 :type 'string)
2264 (defcustom org-columns-modify-value-for-display-function nil
2265 "Function that modifies values for display in column view.
2266 For example, it can be used to cut out a certain part from a time stamp.
2267 The function must take 2 arguments:
2269 column-title The title of the column (*not* the property name)
2270 value The value that should be modified.
2272 The function should return the value that should be displayed,
2273 or nil if the normal value should be used."
2274 :group 'org-properties
2275 :type 'function)
2277 (defcustom org-effort-property "Effort"
2278 "The property that is being used to keep track of effort estimates.
2279 Effort estimates given in this property need to have the format H:MM."
2280 :group 'org-properties
2281 :group 'org-progress
2282 :type '(string :tag "Property"))
2284 (defconst org-global-properties-fixed
2285 '(("VISIBILITY_ALL" . "folded children content all"))
2286 "List of property/value pairs that can be inherited by any entry.
2287 These are fixed values, for the preset properties.")
2290 (defcustom org-global-properties nil
2291 "List of property/value pairs that can be inherited by any entry.
2292 You can set buffer-local values for the same purpose in the variable
2293 `org-file-properties' this by adding lines like
2295 #+PROPERTY: NAME VALUE"
2296 :group 'org-properties
2297 :type '(repeat
2298 (cons (string :tag "Property")
2299 (string :tag "Value"))))
2301 (defvar org-file-properties nil
2302 "List of property/value pairs that can be inherited by any entry.
2303 Valid for the current buffer.
2304 This variable is populated from #+PROPERTY lines.")
2305 (make-variable-buffer-local 'org-file-properties)
2307 (defgroup org-agenda nil
2308 "Options concerning agenda views in Org-mode."
2309 :tag "Org Agenda"
2310 :group 'org)
2312 (defvar org-category nil
2313 "Variable used by org files to set a category for agenda display.
2314 Such files should use a file variable to set it, for example
2316 # -*- mode: org; org-category: \"ELisp\"
2318 or contain a special line
2320 #+CATEGORY: ELisp
2322 If the file does not specify a category, then file's base name
2323 is used instead.")
2324 (make-variable-buffer-local 'org-category)
2325 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2327 (defcustom org-agenda-files nil
2328 "The files to be used for agenda display.
2329 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2330 \\[org-remove-file]. You can also use customize to edit the list.
2332 If an entry is a directory, all files in that directory that are matched by
2333 `org-agenda-file-regexp' will be part of the file list.
2335 If the value of the variable is not a list but a single file name, then
2336 the list of agenda files is actually stored and maintained in that file, one
2337 agenda file per line."
2338 :group 'org-agenda
2339 :type '(choice
2340 (repeat :tag "List of files and directories" file)
2341 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2343 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2344 "Regular expression to match files for `org-agenda-files'.
2345 If any element in the list in that variable contains a directory instead
2346 of a normal file, all files in that directory that are matched by this
2347 regular expression will be included."
2348 :group 'org-agenda
2349 :type 'regexp)
2351 (defcustom org-agenda-text-search-extra-files nil
2352 "List of extra files to be searched by text search commands.
2353 These files will be search in addition to the agenda files by the
2354 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2355 Note that these files will only be searched for text search commands,
2356 not for the other agenda views like todo lists, tag searches or the weekly
2357 agenda. This variable is intended to list notes and possibly archive files
2358 that should also be searched by these two commands.
2359 In fact, if the first element in the list is the symbol `agenda-archives',
2360 than all archive files of all agenda files will be added to the search
2361 scope."
2362 :group 'org-agenda
2363 :type '(set :greedy t
2364 (const :tag "Agenda Archives" agenda-archives)
2365 (repeat :inline t (file))))
2367 (if (fboundp 'defvaralias)
2368 (defvaralias 'org-agenda-multi-occur-extra-files
2369 'org-agenda-text-search-extra-files))
2371 (defcustom org-agenda-skip-unavailable-files nil
2372 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2373 A nil value means to remove them, after a query, from the list."
2374 :group 'org-agenda
2375 :type 'boolean)
2377 (defcustom org-calendar-to-agenda-key [?c]
2378 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2379 The command `org-calendar-goto-agenda' will be bound to this key. The
2380 default is the character `c' because then `c' can be used to switch back and
2381 forth between agenda and calendar."
2382 :group 'org-agenda
2383 :type 'sexp)
2385 (defcustom org-calendar-agenda-action-key [?k]
2386 "The key to be installed in `calendar-mode-map' for agenda-action.
2387 The command `org-agenda-action' will be bound to this key. The
2388 default is the character `k' because we use the same key in the agenda."
2389 :group 'org-agenda
2390 :type 'sexp)
2392 (eval-after-load "calendar"
2393 '(progn
2394 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2395 'org-calendar-goto-agenda)
2396 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2397 'org-agenda-action)))
2399 (defgroup org-latex nil
2400 "Options for embedding LaTeX code into Org-mode."
2401 :tag "Org LaTeX"
2402 :group 'org)
2404 (defcustom org-format-latex-options
2405 '(:foreground default :background default :scale 1.0
2406 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2407 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2408 "Options for creating images from LaTeX fragments.
2409 This is a property list with the following properties:
2410 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2411 `default' means use the foreground of the default face.
2412 :background the background color, or \"Transparent\".
2413 `default' means use the background of the default face.
2414 :scale a scaling factor for the size of the images.
2415 :html-foreground, :html-background, :html-scale
2416 the same numbers for HTML export.
2417 :matchers a list indicating which matchers should be used to
2418 find LaTeX fragments. Valid members of this list are:
2419 \"begin\" find environments
2420 \"$1\" find single characters surrounded by $.$
2421 \"$\" find math expressions surrounded by $...$
2422 \"$$\" find math expressions surrounded by $$....$$
2423 \"\\(\" find math expressions surrounded by \\(...\\)
2424 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2425 :group 'org-latex
2426 :type 'plist)
2428 (defcustom org-format-latex-header "\\documentclass{article}
2429 \\usepackage{fullpage} % do not remove
2430 \\usepackage{amssymb}
2431 \\usepackage[usenames]{color}
2432 \\usepackage{amsmath}
2433 \\usepackage{latexsym}
2434 \\usepackage[mathscr]{eucal}
2435 \\pagestyle{empty} % do not remove"
2436 "The document header used for processing LaTeX fragments."
2437 :group 'org-latex
2438 :type 'string)
2441 (defgroup org-font-lock nil
2442 "Font-lock settings for highlighting in Org-mode."
2443 :tag "Org Font Lock"
2444 :group 'org)
2446 (defcustom org-level-color-stars-only nil
2447 "Non-nil means fontify only the stars in each headline.
2448 When nil, the entire headline is fontified.
2449 Changing it requires restart of `font-lock-mode' to become effective
2450 also in regions already fontified."
2451 :group 'org-font-lock
2452 :type 'boolean)
2454 (defcustom org-hide-leading-stars nil
2455 "Non-nil means, hide the first N-1 stars in a headline.
2456 This works by using the face `org-hide' for these stars. This
2457 face is white for a light background, and black for a dark
2458 background. You may have to customize the face `org-hide' to
2459 make this work.
2460 Changing it requires restart of `font-lock-mode' to become effective
2461 also in regions already fontified.
2462 You may also set this on a per-file basis by adding one of the following
2463 lines to the buffer:
2465 #+STARTUP: hidestars
2466 #+STARTUP: showstars"
2467 :group 'org-font-lock
2468 :type 'boolean)
2470 (defcustom org-fontify-done-headline nil
2471 "Non-nil means, change the face of a headline if it is marked DONE.
2472 Normally, only the TODO/DONE keyword indicates the state of a headline.
2473 When this is non-nil, the headline after the keyword is set to the
2474 `org-headline-done' as an additional indication."
2475 :group 'org-font-lock
2476 :type 'boolean)
2478 (defcustom org-fontify-emphasized-text t
2479 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2480 Changing this variable requires a restart of Emacs to take effect."
2481 :group 'org-font-lock
2482 :type 'boolean)
2484 (defcustom org-highlight-latex-fragments-and-specials nil
2485 "Non-nil means, fontify what is treated specially by the exporters."
2486 :group 'org-font-lock
2487 :type 'boolean)
2489 (defcustom org-hide-emphasis-markers nil
2490 "Non-nil mean font-lock should hide the emphasis marker characters."
2491 :group 'org-font-lock
2492 :type 'boolean)
2494 (defvar org-emph-re nil
2495 "Regular expression for matching emphasis.")
2496 (defvar org-verbatim-re nil
2497 "Regular expression for matching verbatim text.")
2498 (defvar org-emphasis-regexp-components) ; defined just below
2499 (defvar org-emphasis-alist) ; defined just below
2500 (defun org-set-emph-re (var val)
2501 "Set variable and compute the emphasis regular expression."
2502 (set var val)
2503 (when (and (boundp 'org-emphasis-alist)
2504 (boundp 'org-emphasis-regexp-components)
2505 org-emphasis-alist org-emphasis-regexp-components)
2506 (let* ((e org-emphasis-regexp-components)
2507 (pre (car e))
2508 (post (nth 1 e))
2509 (border (nth 2 e))
2510 (body (nth 3 e))
2511 (nl (nth 4 e))
2512 (body1 (concat body "*?"))
2513 (markers (mapconcat 'car org-emphasis-alist ""))
2514 (vmarkers (mapconcat
2515 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2516 org-emphasis-alist "")))
2517 ;; make sure special characters appear at the right position in the class
2518 (if (string-match "\\^" markers)
2519 (setq markers (concat (replace-match "" t t markers) "^")))
2520 (if (string-match "-" markers)
2521 (setq markers (concat (replace-match "" t t markers) "-")))
2522 (if (string-match "\\^" vmarkers)
2523 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2524 (if (string-match "-" vmarkers)
2525 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2526 (if (> nl 0)
2527 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2528 (int-to-string nl) "\\}")))
2529 ;; Make the regexp
2530 (setq org-emph-re
2531 (concat "\\([" pre "]\\|^\\)"
2532 "\\("
2533 "\\([" markers "]\\)"
2534 "\\("
2535 "[^" border "]\\|"
2536 "[^" border "]"
2537 body1
2538 "[^" border "]"
2539 "\\)"
2540 "\\3\\)"
2541 "\\([" post "]\\|$\\)"))
2542 (setq org-verbatim-re
2543 (concat "\\([" pre "]\\|^\\)"
2544 "\\("
2545 "\\([" vmarkers "]\\)"
2546 "\\("
2547 "[^" border "]\\|"
2548 "[^" border "]"
2549 body1
2550 "[^" border "]"
2551 "\\)"
2552 "\\3\\)"
2553 "\\([" post "]\\|$\\)")))))
2555 (defcustom org-emphasis-regexp-components
2556 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2557 "Components used to build the regular expression for emphasis.
2558 This is a list with 6 entries. Terminology: In an emphasis string
2559 like \" *strong word* \", we call the initial space PREMATCH, the final
2560 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2561 and \"trong wor\" is the body. The different components in this variable
2562 specify what is allowed/forbidden in each part:
2564 pre Chars allowed as prematch. Beginning of line will be allowed too.
2565 post Chars allowed as postmatch. End of line will be allowed too.
2566 border The chars *forbidden* as border characters.
2567 body-regexp A regexp like \".\" to match a body character. Don't use
2568 non-shy groups here, and don't allow newline here.
2569 newline The maximum number of newlines allowed in an emphasis exp.
2571 Use customize to modify this, or restart Emacs after changing it."
2572 :group 'org-font-lock
2573 :set 'org-set-emph-re
2574 :type '(list
2575 (sexp :tag "Allowed chars in pre ")
2576 (sexp :tag "Allowed chars in post ")
2577 (sexp :tag "Forbidden chars in border ")
2578 (sexp :tag "Regexp for body ")
2579 (integer :tag "number of newlines allowed")
2580 (option (boolean :tag "Please ignore this button"))))
2582 (defcustom org-emphasis-alist
2583 `(("*" bold "<b>" "</b>")
2584 ("/" italic "<i>" "</i>")
2585 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2586 ("=" org-code "<code>" "</code>" verbatim)
2587 ("~" org-verbatim "<code>" "</code>" verbatim)
2588 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2589 "<del>" "</del>")
2591 "Special syntax for emphasized text.
2592 Text starting and ending with a special character will be emphasized, for
2593 example *bold*, _underlined_ and /italic/. This variable sets the marker
2594 characters, the face to be used by font-lock for highlighting in Org-mode
2595 Emacs buffers, and the HTML tags to be used for this.
2596 Use customize to modify this, or restart Emacs after changing it."
2597 :group 'org-font-lock
2598 :set 'org-set-emph-re
2599 :type '(repeat
2600 (list
2601 (string :tag "Marker character")
2602 (choice
2603 (face :tag "Font-lock-face")
2604 (plist :tag "Face property list"))
2605 (string :tag "HTML start tag")
2606 (string :tag "HTML end tag")
2607 (option (const verbatim)))))
2609 ;;; Miscellaneous options
2611 (defgroup org-completion nil
2612 "Completion in Org-mode."
2613 :tag "Org Completion"
2614 :group 'org)
2616 (defcustom org-completion-use-ido nil
2617 "Non-nil means, use ido completion wherever possible.
2618 Note that `ido-mode' must be active for this variable to be relevant.
2619 If you decide to turn this variable on, you might well want to turn off
2620 `org-outline-path-complete-in-steps'."
2621 :group 'org-completion
2622 :type 'boolean)
2624 (defcustom org-completion-fallback-command 'hippie-expand
2625 "The expansion command called by \\[org-complete] in normal context.
2626 Normal means, no org-mode-specific context."
2627 :group 'org-completion
2628 :type 'function)
2630 ;;; Functions and variables from ther packages
2631 ;; Declared here to avoid compiler warnings
2633 ;; XEmacs only
2634 (defvar outline-mode-menu-heading)
2635 (defvar outline-mode-menu-show)
2636 (defvar outline-mode-menu-hide)
2637 (defvar zmacs-regions) ; XEmacs regions
2639 ;; Emacs only
2640 (defvar mark-active)
2642 ;; Various packages
2643 (declare-function find-library-name "find-func" (library))
2644 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2645 (declare-function calendar-forward-day "cal-move" (arg))
2646 (declare-function calendar-goto-date "cal-move" (date))
2647 (declare-function calendar-goto-today "cal-move" ())
2648 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2649 (defvar calc-embedded-close-formula)
2650 (defvar calc-embedded-open-formula)
2651 (declare-function cdlatex-tab "ext:cdlatex" ())
2652 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2653 (defvar font-lock-unfontify-region-function)
2654 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2655 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2656 (defvar iswitchb-temp-buflist)
2657 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2658 (defvar org-agenda-tags-todo-honor-ignore-options)
2659 (declare-function org-agenda-skip "org-agenda" ())
2660 (declare-function org-format-agenda-item "org-agenda"
2661 (extra txt &optional category tags dotime noprefix remove-re))
2662 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2663 (declare-function org-agenda-change-all-lines "org-agenda"
2664 (newhead hdmarker &optional fixface just-this))
2665 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2666 (declare-function org-agenda-maybe-redo "org-agenda" ())
2667 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2668 (beg end))
2669 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2670 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2671 "org-agenda" (&optional end))
2673 (declare-function parse-time-string "parse-time" (string))
2674 (declare-function remember "remember" (&optional initial))
2675 (declare-function remember-buffer-desc "remember" ())
2676 (declare-function remember-finalize "remember" ())
2677 (defvar remember-save-after-remembering)
2678 (defvar remember-data-file)
2679 (defvar remember-register)
2680 (defvar remember-buffer)
2681 (defvar remember-handler-functions)
2682 (defvar remember-annotation-functions)
2683 (defvar texmathp-why)
2684 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2685 (declare-function table--at-cell-p "table" (position &optional object at-column))
2687 (defvar w3m-current-url)
2688 (defvar w3m-current-title)
2690 (defvar org-latex-regexps)
2692 ;;; Autoload and prepare some org modules
2694 ;; Some table stuff that needs to be defined here, because it is used
2695 ;; by the functions setting up org-mode or checking for table context.
2697 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2698 "Detects an org-type or table-type table.")
2699 (defconst org-table-line-regexp "^[ \t]*|"
2700 "Detects an org-type table line.")
2701 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2702 "Detects an org-type table line.")
2703 (defconst org-table-hline-regexp "^[ \t]*|-"
2704 "Detects an org-type table hline.")
2705 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2706 "Detects a table-type table hline.")
2707 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2708 "Searching from within a table (any type) this finds the first line
2709 outside the table.")
2711 ;; Autoload the functions in org-table.el that are needed by functions here.
2713 (eval-and-compile
2714 (org-autoload "org-table"
2715 '(org-table-align org-table-begin org-table-blank-field
2716 org-table-convert org-table-convert-region org-table-copy-down
2717 org-table-copy-region org-table-create
2718 org-table-create-or-convert-from-region
2719 org-table-create-with-table.el org-table-current-dline
2720 org-table-cut-region org-table-delete-column org-table-edit-field
2721 org-table-edit-formulas org-table-end org-table-eval-formula
2722 org-table-export org-table-field-info
2723 org-table-get-stored-formulas org-table-goto-column
2724 org-table-hline-and-move org-table-import org-table-insert-column
2725 org-table-insert-hline org-table-insert-row org-table-iterate
2726 org-table-justify-field-maybe org-table-kill-row
2727 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2728 org-table-move-column org-table-move-column-left
2729 org-table-move-column-right org-table-move-row
2730 org-table-move-row-down org-table-move-row-up
2731 org-table-next-field org-table-next-row org-table-paste-rectangle
2732 org-table-previous-field org-table-recalculate
2733 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2734 org-table-toggle-coordinate-overlays
2735 org-table-toggle-formula-debugger org-table-wrap-region
2736 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2738 (defun org-at-table-p (&optional table-type)
2739 "Return t if the cursor is inside an org-type table.
2740 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2741 (if org-enable-table-editor
2742 (save-excursion
2743 (beginning-of-line 1)
2744 (looking-at (if table-type org-table-any-line-regexp
2745 org-table-line-regexp)))
2746 nil))
2747 (defsubst org-table-p () (org-at-table-p))
2749 (defun org-at-table.el-p ()
2750 "Return t if and only if we are at a table.el table."
2751 (and (org-at-table-p 'any)
2752 (save-excursion
2753 (goto-char (org-table-begin 'any))
2754 (looking-at org-table1-hline-regexp))))
2755 (defun org-table-recognize-table.el ()
2756 "If there is a table.el table nearby, recognize it and move into it."
2757 (if org-table-tab-recognizes-table.el
2758 (if (org-at-table.el-p)
2759 (progn
2760 (beginning-of-line 1)
2761 (if (looking-at org-table-dataline-regexp)
2763 (if (looking-at org-table1-hline-regexp)
2764 (progn
2765 (beginning-of-line 2)
2766 (if (looking-at org-table-any-border-regexp)
2767 (beginning-of-line -1)))))
2768 (if (re-search-forward "|" (org-table-end t) t)
2769 (progn
2770 (require 'table)
2771 (if (table--at-cell-p (point))
2773 (message "recognizing table.el table...")
2774 (table-recognize-table)
2775 (message "recognizing table.el table...done")))
2776 (error "This should not happen..."))
2778 nil)
2779 nil))
2781 (defun org-at-table-hline-p ()
2782 "Return t if the cursor is inside a hline in a table."
2783 (if org-enable-table-editor
2784 (save-excursion
2785 (beginning-of-line 1)
2786 (looking-at org-table-hline-regexp))
2787 nil))
2789 (defvar org-table-clean-did-remove-column nil)
2791 (defun org-table-map-tables (function)
2792 "Apply FUNCTION to the start of all tables in the buffer."
2793 (save-excursion
2794 (save-restriction
2795 (widen)
2796 (goto-char (point-min))
2797 (while (re-search-forward org-table-any-line-regexp nil t)
2798 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2799 (beginning-of-line 1)
2800 (if (looking-at org-table-line-regexp)
2801 (save-excursion (funcall function)))
2802 (re-search-forward org-table-any-border-regexp nil 1))))
2803 (message "Mapping tables: done"))
2805 ;; Declare and autoload functions from org-exp.el
2807 (declare-function org-default-export-plist "org-exp")
2808 (declare-function org-infile-export-plist "org-exp")
2809 (declare-function org-get-current-options "org-exp")
2810 (eval-and-compile
2811 (org-autoload "org-exp"
2812 '(org-export org-export-as-ascii org-export-visible
2813 org-insert-export-options-template org-export-as-html-and-open
2814 org-export-as-html-batch org-export-as-html-to-buffer
2815 org-replace-region-by-html org-export-region-as-html
2816 org-export-as-html org-export-icalendar-this-file
2817 org-export-icalendar-all-agenda-files
2818 org-table-clean-before-export
2819 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2821 ;; Declare and autoload functions from org-agenda.el
2823 (eval-and-compile
2824 (org-autoload "org-agenda"
2825 '(org-agenda org-agenda-list org-search-view
2826 org-todo-list org-tags-view org-agenda-list-stuck-projects
2827 org-diary org-agenda-to-appt
2828 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2830 ;; Autoload org-remember
2832 (eval-and-compile
2833 (org-autoload "org-remember"
2834 '(org-remember-insinuate org-remember-annotation
2835 org-remember-apply-template org-remember org-remember-handler)))
2837 ;; Autoload org-clock.el
2840 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2841 (beg end))
2842 (declare-function org-clock-update-mode-line "org-clock" ())
2843 (defvar org-clock-start-time)
2844 (defvar org-clock-marker (make-marker)
2845 "Marker recording the last clock-in.")
2847 (eval-and-compile
2848 (org-autoload
2849 "org-clock"
2850 '(org-clock-in org-clock-out org-clock-cancel
2851 org-clock-goto org-clock-sum org-clock-display
2852 org-clock-remove-overlays org-clock-report
2853 org-clocktable-shift org-dblock-write:clocktable
2854 org-get-clocktable)))
2856 (defun org-clock-update-time-maybe ()
2857 "If this is a CLOCK line, update it and return t.
2858 Otherwise, return nil."
2859 (interactive)
2860 (save-excursion
2861 (beginning-of-line 1)
2862 (skip-chars-forward " \t")
2863 (when (looking-at org-clock-string)
2864 (let ((re (concat "[ \t]*" org-clock-string
2865 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2866 "\\([ \t]*=>.*\\)?\\)?"))
2867 ts te h m s neg)
2868 (cond
2869 ((not (looking-at re))
2870 nil)
2871 ((not (match-end 2))
2872 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2873 (> org-clock-marker (point))
2874 (<= org-clock-marker (point-at-eol)))
2875 ;; The clock is running here
2876 (setq org-clock-start-time
2877 (apply 'encode-time
2878 (org-parse-time-string (match-string 1))))
2879 (org-clock-update-mode-line)))
2881 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2882 (end-of-line 1)
2883 (setq ts (match-string 1)
2884 te (match-string 3))
2885 (setq s (- (time-to-seconds
2886 (apply 'encode-time (org-parse-time-string te)))
2887 (time-to-seconds
2888 (apply 'encode-time (org-parse-time-string ts))))
2889 neg (< s 0)
2890 s (abs s)
2891 h (floor (/ s 3600))
2892 s (- s (* 3600 h))
2893 m (floor (/ s 60))
2894 s (- s (* 60 s)))
2895 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2896 t))))))
2898 (defun org-check-running-clock ()
2899 "Check if the current buffer contains the running clock.
2900 If yes, offer to stop it and to save the buffer with the changes."
2901 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2902 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2903 (buffer-name))))
2904 (org-clock-out)
2905 (when (y-or-n-p "Save changed buffer?")
2906 (save-buffer))))
2908 (defun org-clocktable-try-shift (dir n)
2909 "Check if this line starts a clock table, if yes, shift the time block."
2910 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2911 (org-clocktable-shift dir n)))
2913 ;; Autoload org-timer.el
2915 ;(declare-function org-timer "org-timer")
2917 (eval-and-compile
2918 (org-autoload
2919 "org-timer"
2920 '(org-timer-start org-timer org-timer-item
2921 org-timer-change-times-in-region)))
2924 ;; Autoload archiving code
2925 ;; The stuff that is needed for cycling and tags has to be defined here.
2927 (defgroup org-archive nil
2928 "Options concerning archiving in Org-mode."
2929 :tag "Org Archive"
2930 :group 'org-structure)
2932 (defcustom org-archive-location "%s_archive::"
2933 "The location where subtrees should be archived.
2935 The value of this variable is a string, consisting of two parts,
2936 separated by a double-colon. The first part is a filename and
2937 the second part is a headline.
2939 When the filename is omitted, archiving happens in the same file.
2940 %s in the filename will be replaced by the current file
2941 name (without the directory part). Archiving to a different file
2942 is useful to keep archived entries from contributing to the
2943 Org-mode Agenda.
2945 The archived entries will be filed as subtrees of the specified
2946 headline. When the headline is omitted, the subtrees are simply
2947 filed away at the end of the file, as top-level entries. Also in
2948 the heading you can use %s to represent the file name, this can be
2949 useful when using the same archive for a number of different files.
2951 Here are a few examples:
2952 \"%s_archive::\"
2953 If the current file is Projects.org, archive in file
2954 Projects.org_archive, as top-level trees. This is the default.
2956 \"::* Archived Tasks\"
2957 Archive in the current file, under the top-level headline
2958 \"* Archived Tasks\".
2960 \"~/org/archive.org::\"
2961 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2963 \"~/org/archive.org::From %s\"
2964 Archive in file ~/org/archive.org (absolute path), und headlines
2965 \"From FILENAME\" where file name is the current file name.
2967 \"basement::** Finished Tasks\"
2968 Archive in file ./basement (relative path), as level 3 trees
2969 below the level 2 heading \"** Finished Tasks\".
2971 You may set this option on a per-file basis by adding to the buffer a
2972 line like
2974 #+ARCHIVE: basement::** Finished Tasks
2976 You may also define it locally for a subtree by setting an ARCHIVE property
2977 in the entry. If such a property is found in an entry, or anywhere up
2978 the hierarchy, it will be used."
2979 :group 'org-archive
2980 :type 'string)
2982 (defcustom org-archive-tag "ARCHIVE"
2983 "The tag that marks a subtree as archived.
2984 An archived subtree does not open during visibility cycling, and does
2985 not contribute to the agenda listings.
2986 After changing this, font-lock must be restarted in the relevant buffers to
2987 get the proper fontification."
2988 :group 'org-archive
2989 :group 'org-keywords
2990 :type 'string)
2992 (defcustom org-agenda-skip-archived-trees t
2993 "Non-nil means, the agenda will skip any items located in archived trees.
2994 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2995 variable is no longer recommended, you should leave it at the value t.
2996 Instead, use the key `v' to cycle the archives-mode in the agenda."
2997 :group 'org-archive
2998 :group 'org-agenda-skip
2999 :type 'boolean)
3001 (defcustom org-cycle-open-archived-trees nil
3002 "Non-nil means, `org-cycle' will open archived trees.
3003 An archived tree is a tree marked with the tag ARCHIVE.
3004 When nil, archived trees will stay folded. You can still open them with
3005 normal outline commands like `show-all', but not with the cycling commands."
3006 :group 'org-archive
3007 :group 'org-cycle
3008 :type 'boolean)
3010 (defcustom org-sparse-tree-open-archived-trees nil
3011 "Non-nil means sparse tree construction shows matches in archived trees.
3012 When nil, matches in these trees are highlighted, but the trees are kept in
3013 collapsed state."
3014 :group 'org-archive
3015 :group 'org-sparse-trees
3016 :type 'boolean)
3018 (defun org-cycle-hide-archived-subtrees (state)
3019 "Re-hide all archived subtrees after a visibility state change."
3020 (when (and (not org-cycle-open-archived-trees)
3021 (not (memq state '(overview folded))))
3022 (save-excursion
3023 (let* ((globalp (memq state '(contents all)))
3024 (beg (if globalp (point-min) (point)))
3025 (end (if globalp (point-max) (org-end-of-subtree t))))
3026 (org-hide-archived-subtrees beg end)
3027 (goto-char beg)
3028 (if (looking-at (concat ".*:" org-archive-tag ":"))
3029 (message "%s" (substitute-command-keys
3030 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3032 (defun org-force-cycle-archived ()
3033 "Cycle subtree even if it is archived."
3034 (interactive)
3035 (setq this-command 'org-cycle)
3036 (let ((org-cycle-open-archived-trees t))
3037 (call-interactively 'org-cycle)))
3039 (defun org-hide-archived-subtrees (beg end)
3040 "Re-hide all archived subtrees after a visibility state change."
3041 (save-excursion
3042 (let* ((re (concat ":" org-archive-tag ":")))
3043 (goto-char beg)
3044 (while (re-search-forward re end t)
3045 (and (org-on-heading-p) (hide-subtree))
3046 (org-end-of-subtree t)))))
3048 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3050 (eval-and-compile
3051 (org-autoload "org-archive"
3052 '(org-add-archive-files org-archive-subtree
3053 org-archive-to-archive-sibling org-toggle-archive-tag)))
3055 ;; Autoload Column View Code
3057 (declare-function org-columns-number-to-string "org-colview")
3058 (declare-function org-columns-get-format-and-top-level "org-colview")
3059 (declare-function org-columns-compute "org-colview")
3061 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3062 '(org-columns-number-to-string org-columns-get-format-and-top-level
3063 org-columns-compute org-agenda-columns org-columns-remove-overlays
3064 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3066 ;; Autoload ID code
3068 (declare-function org-id-store-link "org-id")
3069 (declare-function org-id-locations-load "org-id")
3070 (declare-function org-id-locations-save "org-id")
3071 (defvar org-id-track-globally)
3072 (org-autoload "org-id"
3073 '(org-id-get-create org-id-new org-id-copy org-id-get
3074 org-id-get-with-outline-path-completion
3075 org-id-get-with-outline-drilling
3076 org-id-goto org-id-find org-id-store-link))
3078 ;; Autoload Plotting Code
3080 (org-autoload "org-plot"
3081 '(org-plot/gnuplot))
3083 ;;; Variables for pre-computed regular expressions, all buffer local
3085 (defvar org-drawer-regexp nil
3086 "Matches first line of a hidden block.")
3087 (make-variable-buffer-local 'org-drawer-regexp)
3088 (defvar org-todo-regexp nil
3089 "Matches any of the TODO state keywords.")
3090 (make-variable-buffer-local 'org-todo-regexp)
3091 (defvar org-not-done-regexp nil
3092 "Matches any of the TODO state keywords except the last one.")
3093 (make-variable-buffer-local 'org-not-done-regexp)
3094 (defvar org-todo-line-regexp nil
3095 "Matches a headline and puts TODO state into group 2 if present.")
3096 (make-variable-buffer-local 'org-todo-line-regexp)
3097 (defvar org-complex-heading-regexp nil
3098 "Matches a headline and puts everything into groups:
3099 group 1: the stars
3100 group 2: The todo keyword, maybe
3101 group 3: Priority cookie
3102 group 4: True headline
3103 group 5: Tags")
3104 (make-variable-buffer-local 'org-complex-heading-regexp)
3105 (defvar org-todo-line-tags-regexp nil
3106 "Matches a headline and puts TODO state into group 2 if present.
3107 Also put tags into group 4 if tags are present.")
3108 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3109 (defvar org-nl-done-regexp nil
3110 "Matches newline followed by a headline with the DONE keyword.")
3111 (make-variable-buffer-local 'org-nl-done-regexp)
3112 (defvar org-looking-at-done-regexp nil
3113 "Matches the DONE keyword a point.")
3114 (make-variable-buffer-local 'org-looking-at-done-regexp)
3115 (defvar org-ds-keyword-length 12
3116 "Maximum length of the Deadline and SCHEDULED keywords.")
3117 (make-variable-buffer-local 'org-ds-keyword-length)
3118 (defvar org-deadline-regexp nil
3119 "Matches the DEADLINE keyword.")
3120 (make-variable-buffer-local 'org-deadline-regexp)
3121 (defvar org-deadline-time-regexp nil
3122 "Matches the DEADLINE keyword together with a time stamp.")
3123 (make-variable-buffer-local 'org-deadline-time-regexp)
3124 (defvar org-deadline-line-regexp nil
3125 "Matches the DEADLINE keyword and the rest of the line.")
3126 (make-variable-buffer-local 'org-deadline-line-regexp)
3127 (defvar org-scheduled-regexp nil
3128 "Matches the SCHEDULED keyword.")
3129 (make-variable-buffer-local 'org-scheduled-regexp)
3130 (defvar org-scheduled-time-regexp nil
3131 "Matches the SCHEDULED keyword together with a time stamp.")
3132 (make-variable-buffer-local 'org-scheduled-time-regexp)
3133 (defvar org-closed-time-regexp nil
3134 "Matches the CLOSED keyword together with a time stamp.")
3135 (make-variable-buffer-local 'org-closed-time-regexp)
3137 (defvar org-keyword-time-regexp nil
3138 "Matches any of the 4 keywords, together with the time stamp.")
3139 (make-variable-buffer-local 'org-keyword-time-regexp)
3140 (defvar org-keyword-time-not-clock-regexp nil
3141 "Matches any of the 3 keywords, together with the time stamp.")
3142 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3143 (defvar org-maybe-keyword-time-regexp nil
3144 "Matches a timestamp, possibly preceeded by a keyword.")
3145 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3146 (defvar org-planning-or-clock-line-re nil
3147 "Matches a line with planning or clock info.")
3148 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3150 (defconst org-plain-time-of-day-regexp
3151 (concat
3152 "\\(\\<[012]?[0-9]"
3153 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3154 "\\(--?"
3155 "\\(\\<[012]?[0-9]"
3156 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3157 "\\)?")
3158 "Regular expression to match a plain time or time range.
3159 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3160 groups carry important information:
3161 0 the full match
3162 1 the first time, range or not
3163 8 the second time, if it is a range.")
3165 (defconst org-plain-time-extension-regexp
3166 (concat
3167 "\\(\\<[012]?[0-9]"
3168 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3169 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3170 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3171 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3172 groups carry important information:
3173 0 the full match
3174 7 hours of duration
3175 9 minutes of duration")
3177 (defconst org-stamp-time-of-day-regexp
3178 (concat
3179 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3180 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3181 "\\(--?"
3182 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3183 "Regular expression to match a timestamp time or time range.
3184 After a match, the following groups carry important information:
3185 0 the full match
3186 1 date plus weekday, for backreferencing to make sure both times on same day
3187 2 the first time, range or not
3188 4 the second time, if it is a range.")
3190 (defconst org-startup-options
3191 '(("fold" org-startup-folded t)
3192 ("overview" org-startup-folded t)
3193 ("nofold" org-startup-folded nil)
3194 ("showall" org-startup-folded nil)
3195 ("content" org-startup-folded content)
3196 ("hidestars" org-hide-leading-stars t)
3197 ("showstars" org-hide-leading-stars nil)
3198 ("odd" org-odd-levels-only t)
3199 ("oddeven" org-odd-levels-only nil)
3200 ("align" org-startup-align-all-tables t)
3201 ("noalign" org-startup-align-all-tables nil)
3202 ("customtime" org-display-custom-times t)
3203 ("logdone" org-log-done time)
3204 ("lognotedone" org-log-done note)
3205 ("nologdone" org-log-done nil)
3206 ("lognoteclock-out" org-log-note-clock-out t)
3207 ("nolognoteclock-out" org-log-note-clock-out nil)
3208 ("logrepeat" org-log-repeat state)
3209 ("lognoterepeat" org-log-repeat note)
3210 ("nologrepeat" org-log-repeat nil)
3211 ("fninline" org-footnote-define-inline t)
3212 ("nofninline" org-footnote-define-inline nil)
3213 ("fnlocal" org-footnote-section nil)
3214 ("fnauto" org-footnote-auto-label t)
3215 ("fnprompt" org-footnote-auto-label nil)
3216 ("fnconfirm" org-footnote-auto-label confirm)
3217 ("fnplain" org-footnote-auto-label plain)
3218 ("constcgs" constants-unit-system cgs)
3219 ("constSI" constants-unit-system SI))
3220 "Variable associated with STARTUP options for org-mode.
3221 Each element is a list of three items: The startup options as written
3222 in the #+STARTUP line, the corresponding variable, and the value to
3223 set this variable to if the option is found. An optional forth element PUSH
3224 means to push this value onto the list in the variable.")
3226 (defun org-set-regexps-and-options ()
3227 "Precompute regular expressions for current buffer."
3228 (when (org-mode-p)
3229 (org-set-local 'org-todo-kwd-alist nil)
3230 (org-set-local 'org-todo-key-alist nil)
3231 (org-set-local 'org-todo-key-trigger nil)
3232 (org-set-local 'org-todo-keywords-1 nil)
3233 (org-set-local 'org-done-keywords nil)
3234 (org-set-local 'org-todo-heads nil)
3235 (org-set-local 'org-todo-sets nil)
3236 (org-set-local 'org-todo-log-states nil)
3237 (org-set-local 'org-file-properties nil)
3238 (org-set-local 'org-file-tags nil)
3239 (let ((re (org-make-options-regexp
3240 '("CATEGORY" "TODO" "COLUMNS"
3241 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3242 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3243 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3244 (splitre "[ \t]+")
3245 kwds kws0 kwsa key log value cat arch tags const links hw dws
3246 tail sep kws1 prio props ftags drawers
3247 ext-setup-or-nil setup-contents (start 0))
3248 (save-excursion
3249 (save-restriction
3250 (widen)
3251 (goto-char (point-min))
3252 (while (or (and ext-setup-or-nil
3253 (string-match re ext-setup-or-nil start)
3254 (setq start (match-end 0)))
3255 (and (setq ext-setup-or-nil nil start 0)
3256 (re-search-forward re nil t)))
3257 (setq key (upcase (match-string 1 ext-setup-or-nil))
3258 value (org-match-string-no-properties 2 ext-setup-or-nil))
3259 (cond
3260 ((equal key "CATEGORY")
3261 (if (string-match "[ \t]+$" value)
3262 (setq value (replace-match "" t t value)))
3263 (setq cat value))
3264 ((member key '("SEQ_TODO" "TODO"))
3265 (push (cons 'sequence (org-split-string value splitre)) kwds))
3266 ((equal key "TYP_TODO")
3267 (push (cons 'type (org-split-string value splitre)) kwds))
3268 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3269 ;; general TODO-like setup
3270 (push (cons (intern (downcase (match-string 1 key)))
3271 (org-split-string value splitre)) kwds))
3272 ((equal key "TAGS")
3273 (setq tags (append tags (if tags '("\\n") nil)
3274 (org-split-string value splitre))))
3275 ((equal key "COLUMNS")
3276 (org-set-local 'org-columns-default-format value))
3277 ((equal key "LINK")
3278 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3279 (push (cons (match-string 1 value)
3280 (org-trim (match-string 2 value)))
3281 links)))
3282 ((equal key "PRIORITIES")
3283 (setq prio (org-split-string value " +")))
3284 ((equal key "PROPERTY")
3285 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3286 (push (cons (match-string 1 value) (match-string 2 value))
3287 props)))
3288 ((equal key "FILETAGS")
3289 (when (string-match "\\S-" value)
3290 (setq ftags
3291 (append
3292 ftags
3293 (apply 'append
3294 (mapcar (lambda (x) (org-split-string x ":"))
3295 (org-split-string value)))))))
3296 ((equal key "DRAWERS")
3297 (setq drawers (org-split-string value splitre)))
3298 ((equal key "CONSTANTS")
3299 (setq const (append const (org-split-string value splitre))))
3300 ((equal key "STARTUP")
3301 (let ((opts (org-split-string value splitre))
3302 l var val)
3303 (while (setq l (pop opts))
3304 (when (setq l (assoc l org-startup-options))
3305 (setq var (nth 1 l) val (nth 2 l))
3306 (if (not (nth 3 l))
3307 (set (make-local-variable var) val)
3308 (if (not (listp (symbol-value var)))
3309 (set (make-local-variable var) nil))
3310 (set (make-local-variable var) (symbol-value var))
3311 (add-to-list var val))))))
3312 ((equal key "ARCHIVE")
3313 (string-match " *$" value)
3314 (setq arch (replace-match "" t t value))
3315 (remove-text-properties 0 (length arch)
3316 '(face t fontified t) arch))
3317 ((equal key "SETUPFILE")
3318 (setq setup-contents (org-file-contents
3319 (expand-file-name
3320 (org-remove-double-quotes value))
3321 'noerror))
3322 (if (not ext-setup-or-nil)
3323 (setq ext-setup-or-nil setup-contents start 0)
3324 (setq ext-setup-or-nil
3325 (concat (substring ext-setup-or-nil 0 start)
3326 "\n" setup-contents "\n"
3327 (substring ext-setup-or-nil start)))))
3328 ))))
3329 (when cat
3330 (org-set-local 'org-category (intern cat))
3331 (push (cons "CATEGORY" cat) props))
3332 (when prio
3333 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3334 (setq prio (mapcar 'string-to-char prio))
3335 (org-set-local 'org-highest-priority (nth 0 prio))
3336 (org-set-local 'org-lowest-priority (nth 1 prio))
3337 (org-set-local 'org-default-priority (nth 2 prio)))
3338 (and props (org-set-local 'org-file-properties (nreverse props)))
3339 (and ftags (org-set-local 'org-file-tags ftags))
3340 (and drawers (org-set-local 'org-drawers drawers))
3341 (and arch (org-set-local 'org-archive-location arch))
3342 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3343 ;; Process the TODO keywords
3344 (unless kwds
3345 ;; Use the global values as if they had been given locally.
3346 (setq kwds (default-value 'org-todo-keywords))
3347 (if (stringp (car kwds))
3348 (setq kwds (list (cons org-todo-interpretation
3349 (default-value 'org-todo-keywords)))))
3350 (setq kwds (reverse kwds)))
3351 (setq kwds (nreverse kwds))
3352 (let (inter kws kw)
3353 (while (setq kws (pop kwds))
3354 (let ((kws (or
3355 (run-hook-with-args-until-success
3356 'org-todo-setup-filter-hook kws)
3357 kws)))
3358 (setq inter (pop kws) sep (member "|" kws)
3359 kws0 (delete "|" (copy-sequence kws))
3360 kwsa nil
3361 kws1 (mapcar
3362 (lambda (x)
3363 ;; 1 2
3364 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3365 (progn
3366 (setq kw (match-string 1 x)
3367 key (and (match-end 2) (match-string 2 x))
3368 log (org-extract-log-state-settings x))
3369 (push (cons kw (and key (string-to-char key))) kwsa)
3370 (and log (push log org-todo-log-states))
3372 (error "Invalid TODO keyword %s" x)))
3373 kws0)
3374 kwsa (if kwsa (append '((:startgroup))
3375 (nreverse kwsa)
3376 '((:endgroup))))
3377 hw (car kws1)
3378 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3379 tail (list inter hw (car dws) (org-last dws))))
3380 (add-to-list 'org-todo-heads hw 'append)
3381 (push kws1 org-todo-sets)
3382 (setq org-done-keywords (append org-done-keywords dws nil))
3383 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3384 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3385 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3386 (setq org-todo-sets (nreverse org-todo-sets)
3387 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3388 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3389 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3390 ;; Process the constants
3391 (when const
3392 (let (e cst)
3393 (while (setq e (pop const))
3394 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3395 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3396 (setq org-table-formula-constants-local cst)))
3398 ;; Process the tags.
3399 (when tags
3400 (let (e tgs)
3401 (while (setq e (pop tags))
3402 (cond
3403 ((equal e "{") (push '(:startgroup) tgs))
3404 ((equal e "}") (push '(:endgroup) tgs))
3405 ((equal e "\\n") (push '(:newline) tgs))
3406 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3407 (push (cons (match-string 1 e)
3408 (string-to-char (match-string 2 e)))
3409 tgs))
3410 (t (push (list e) tgs))))
3411 (org-set-local 'org-tag-alist nil)
3412 (while (setq e (pop tgs))
3413 (or (and (stringp (car e))
3414 (assoc (car e) org-tag-alist))
3415 (push e org-tag-alist)))))
3417 ;; Compute the regular expressions and other local variables
3418 (if (not org-done-keywords)
3419 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3420 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3421 (length org-scheduled-string)
3422 (length org-clock-string)
3423 (length org-closed-string)))
3424 org-drawer-regexp
3425 (concat "^[ \t]*:\\("
3426 (mapconcat 'regexp-quote org-drawers "\\|")
3427 "\\):[ \t]*$")
3428 org-not-done-keywords
3429 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3430 org-todo-regexp
3431 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3432 "\\|") "\\)\\>")
3433 org-not-done-regexp
3434 (concat "\\<\\("
3435 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3436 "\\)\\>")
3437 org-todo-line-regexp
3438 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3439 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3440 "\\)\\>\\)?[ \t]*\\(.*\\)")
3441 org-complex-heading-regexp
3442 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3443 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3444 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3445 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3446 org-nl-done-regexp
3447 (concat "\n\\*+[ \t]+"
3448 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3449 "\\)" "\\>")
3450 org-todo-line-tags-regexp
3451 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3452 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3453 (org-re
3454 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3455 org-looking-at-done-regexp
3456 (concat "^" "\\(?:"
3457 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3458 "\\>")
3459 org-deadline-regexp (concat "\\<" org-deadline-string)
3460 org-deadline-time-regexp
3461 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3462 org-deadline-line-regexp
3463 (concat "\\<\\(" org-deadline-string "\\).*")
3464 org-scheduled-regexp
3465 (concat "\\<" org-scheduled-string)
3466 org-scheduled-time-regexp
3467 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3468 org-closed-time-regexp
3469 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3470 org-keyword-time-regexp
3471 (concat "\\<\\(" org-scheduled-string
3472 "\\|" org-deadline-string
3473 "\\|" org-closed-string
3474 "\\|" org-clock-string "\\)"
3475 " *[[<]\\([^]>]+\\)[]>]")
3476 org-keyword-time-not-clock-regexp
3477 (concat "\\<\\(" org-scheduled-string
3478 "\\|" org-deadline-string
3479 "\\|" org-closed-string
3480 "\\)"
3481 " *[[<]\\([^]>]+\\)[]>]")
3482 org-maybe-keyword-time-regexp
3483 (concat "\\(\\<\\(" org-scheduled-string
3484 "\\|" org-deadline-string
3485 "\\|" org-closed-string
3486 "\\|" org-clock-string "\\)\\)?"
3487 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3488 org-planning-or-clock-line-re
3489 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3490 "\\|" org-deadline-string
3491 "\\|" org-closed-string "\\|" org-clock-string
3492 "\\)\\>\\)")
3494 (org-compute-latex-and-specials-regexp)
3495 (org-set-font-lock-defaults))))
3497 (defun org-file-contents (file &optional noerror)
3498 "Return the contents of FILE, as a string."
3499 (if (or (not file)
3500 (not (file-readable-p file)))
3501 (if noerror
3502 (progn
3503 (message "Cannot read file %s" file)
3504 (ding) (sit-for 2)
3506 (error "Cannot read file %s" file))
3507 (with-temp-buffer
3508 (insert-file-contents file)
3509 (buffer-string))))
3511 (defun org-extract-log-state-settings (x)
3512 "Extract the log state setting from a TODO keyword string.
3513 This will extract info from a string like \"WAIT(w@/!)\"."
3514 (let (kw key log1 log2)
3515 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3516 (setq kw (match-string 1 x)
3517 key (and (match-end 2) (match-string 2 x))
3518 log1 (and (match-end 3) (match-string 3 x))
3519 log2 (and (match-end 4) (match-string 4 x)))
3520 (and (or log1 log2)
3521 (list kw
3522 (and log1 (if (equal log1 "!") 'time 'note))
3523 (and log2 (if (equal log2 "!") 'time 'note)))))))
3525 (defun org-remove-keyword-keys (list)
3526 "Remove a pair of parenthesis at the end of each string in LIST."
3527 (mapcar (lambda (x)
3528 (if (string-match "(.*)$" x)
3529 (substring x 0 (match-beginning 0))
3531 list))
3533 ;; FIXME: this could be done much better, using second characters etc.
3534 (defun org-assign-fast-keys (alist)
3535 "Assign fast keys to a keyword-key alist.
3536 Respect keys that are already there."
3537 (let (new e k c c1 c2 (char ?a))
3538 (while (setq e (pop alist))
3539 (cond
3540 ((equal e '(:startgroup)) (push e new))
3541 ((equal e '(:endgroup)) (push e new))
3542 ((equal e '(:newline)) (push e new))
3544 (setq k (car e) c2 nil)
3545 (if (cdr e)
3546 (setq c (cdr e))
3547 ;; automatically assign a character.
3548 (setq c1 (string-to-char
3549 (downcase (substring
3550 k (if (= (string-to-char k) ?@) 1 0)))))
3551 (if (or (rassoc c1 new) (rassoc c1 alist))
3552 (while (or (rassoc char new) (rassoc char alist))
3553 (setq char (1+ char)))
3554 (setq c2 c1))
3555 (setq c (or c2 char)))
3556 (push (cons k c) new))))
3557 (nreverse new)))
3559 ;;; Some variables used in various places
3561 (defvar org-window-configuration nil
3562 "Used in various places to store a window configuration.")
3563 (defvar org-finish-function nil
3564 "Function to be called when `C-c C-c' is used.
3565 This is for getting out of special buffers like remember.")
3568 ;; FIXME: Occasionally check by commenting these, to make sure
3569 ;; no other functions uses these, forgetting to let-bind them.
3570 (defvar entry)
3571 (defvar state)
3572 (defvar last-state)
3573 (defvar date)
3574 (defvar description)
3576 ;; Defined somewhere in this file, but used before definition.
3577 (defvar org-html-entities)
3578 (defvar org-struct-menu)
3579 (defvar org-org-menu)
3580 (defvar org-tbl-menu)
3581 (defvar org-agenda-keymap)
3583 ;;;; Define the Org-mode
3585 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3586 (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."))
3589 ;; We use a before-change function to check if a table might need
3590 ;; an update.
3591 (defvar org-table-may-need-update t
3592 "Indicates that a table might need an update.
3593 This variable is set by `org-before-change-function'.
3594 `org-table-align' sets it back to nil.")
3595 (defun org-before-change-function (beg end)
3596 "Every change indicates that a table might need an update."
3597 (setq org-table-may-need-update t))
3598 (defvar org-mode-map)
3599 (defvar org-mode-hook nil
3600 "Mode hook for Org-mode, run after the mode was turned on.")
3601 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3602 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3603 (defvar org-table-buffer-is-an nil)
3604 (defconst org-outline-regexp "\\*+ ")
3606 ;;;###autoload
3607 (define-derived-mode org-mode outline-mode "Org"
3608 "Outline-based notes management and organizer, alias
3609 \"Carsten's outline-mode for keeping track of everything.\"
3611 Org-mode develops organizational tasks around a NOTES file which
3612 contains information about projects as plain text. Org-mode is
3613 implemented on top of outline-mode, which is ideal to keep the content
3614 of large files well structured. It supports ToDo items, deadlines and
3615 time stamps, which magically appear in the diary listing of the Emacs
3616 calendar. Tables are easily created with a built-in table editor.
3617 Plain text URL-like links connect to websites, emails (VM), Usenet
3618 messages (Gnus), BBDB entries, and any files related to the project.
3619 For printing and sharing of notes, an Org-mode file (or a part of it)
3620 can be exported as a structured ASCII or HTML file.
3622 The following commands are available:
3624 \\{org-mode-map}"
3626 ;; Get rid of Outline menus, they are not needed
3627 ;; Need to do this here because define-derived-mode sets up
3628 ;; the keymap so late. Still, it is a waste to call this each time
3629 ;; we switch another buffer into org-mode.
3630 (if (featurep 'xemacs)
3631 (when (boundp 'outline-mode-menu-heading)
3632 ;; Assume this is Greg's port, it used easymenu
3633 (easy-menu-remove outline-mode-menu-heading)
3634 (easy-menu-remove outline-mode-menu-show)
3635 (easy-menu-remove outline-mode-menu-hide))
3636 (define-key org-mode-map [menu-bar headings] 'undefined)
3637 (define-key org-mode-map [menu-bar hide] 'undefined)
3638 (define-key org-mode-map [menu-bar show] 'undefined))
3640 (org-load-modules-maybe)
3641 (easy-menu-add org-org-menu)
3642 (easy-menu-add org-tbl-menu)
3643 (org-install-agenda-files-menu)
3644 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3645 (org-add-to-invisibility-spec '(org-cwidth))
3646 (when (featurep 'xemacs)
3647 (org-set-local 'line-move-ignore-invisible t))
3648 (org-set-local 'outline-regexp org-outline-regexp)
3649 (org-set-local 'outline-level 'org-outline-level)
3650 (when (and org-ellipsis
3651 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3652 (fboundp 'make-glyph-code))
3653 (unless org-display-table
3654 (setq org-display-table (make-display-table)))
3655 (set-display-table-slot
3656 org-display-table 4
3657 (vconcat (mapcar
3658 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3659 org-ellipsis)))
3660 (if (stringp org-ellipsis) org-ellipsis "..."))))
3661 (setq buffer-display-table org-display-table))
3662 (org-set-regexps-and-options)
3663 (when (and org-tag-faces (not org-tags-special-faces-re))
3664 ;; tag faces set outside customize.... force initialization.
3665 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3666 ;; Calc embedded
3667 (org-set-local 'calc-embedded-open-mode "# ")
3668 (modify-syntax-entry ?# "<")
3669 (modify-syntax-entry ?@ "w")
3670 (if org-startup-truncated (setq truncate-lines t))
3671 (org-set-local 'font-lock-unfontify-region-function
3672 'org-unfontify-region)
3673 ;; Activate before-change-function
3674 (org-set-local 'org-table-may-need-update t)
3675 (org-add-hook 'before-change-functions 'org-before-change-function nil
3676 'local)
3677 ;; Check for running clock before killing a buffer
3678 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3679 ;; Paragraphs and auto-filling
3680 (org-set-autofill-regexps)
3681 (setq indent-line-function 'org-indent-line-function)
3682 (org-update-radio-target-regexp)
3683 ;; Make sure dependence stuff works reliably, even for users who set it
3684 ;; too late :-(
3685 (if org-enforce-todo-dependencies
3686 (add-hook 'org-blocker-hook
3687 'org-block-todo-from-children-or-siblings)
3688 (remove-hook 'org-blocker-hook
3689 'org-block-todo-from-children-or-siblings))
3690 (if org-enforce-todo-checkbox-dependencies
3691 (add-hook 'org-blocker-hook
3692 'org-block-todo-from-checkboxes)
3693 (remove-hook 'org-blocker-hook
3694 'org-block-todo-from-checkboxes))
3696 ;; Comment characters
3697 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3698 (org-set-local 'comment-padding " ")
3700 ;; Align options lines
3701 (org-set-local
3702 'align-mode-rules-list
3703 '((org-in-buffer-settings
3704 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3705 (modes . '(org-mode)))))
3707 ;; Imenu
3708 (org-set-local 'imenu-create-index-function
3709 'org-imenu-get-tree)
3711 ;; Make isearch reveal context
3712 (if (or (featurep 'xemacs)
3713 (not (boundp 'outline-isearch-open-invisible-function)))
3714 ;; Emacs 21 and XEmacs make use of the hook
3715 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3716 ;; Emacs 22 deals with this through a special variable
3717 (org-set-local 'outline-isearch-open-invisible-function
3718 (lambda (&rest ignore) (org-show-context 'isearch))))
3720 ;; If empty file that did not turn on org-mode automatically, make it to.
3721 (if (and org-insert-mode-line-in-empty-file
3722 (interactive-p)
3723 (= (point-min) (point-max)))
3724 (insert "# -*- mode: org -*-\n\n"))
3726 (unless org-inhibit-startup
3727 (when org-startup-align-all-tables
3728 (let ((bmp (buffer-modified-p)))
3729 (org-table-map-tables 'org-table-align)
3730 (set-buffer-modified-p bmp)))
3731 (org-set-startup-visibility)))
3733 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3735 (defun org-current-time ()
3736 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3737 (if (> (car org-time-stamp-rounding-minutes) 1)
3738 (let ((r (car org-time-stamp-rounding-minutes))
3739 (time (decode-time)))
3740 (apply 'encode-time
3741 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3742 (nthcdr 2 time))))
3743 (current-time)))
3745 ;;;; Font-Lock stuff, including the activators
3747 (defvar org-mouse-map (make-sparse-keymap))
3748 (org-defkey org-mouse-map
3749 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3750 (org-defkey org-mouse-map
3751 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3752 (when org-mouse-1-follows-link
3753 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3754 (when org-tab-follows-link
3755 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3756 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3758 (require 'font-lock)
3760 (defconst org-non-link-chars "]\t\n\r<>")
3761 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3762 "shell" "elisp"))
3763 (defvar org-link-types-re nil
3764 "Matches a link that has a url-like prefix like \"http:\"")
3765 (defvar org-link-re-with-space nil
3766 "Matches a link with spaces, optional angular brackets around it.")
3767 (defvar org-link-re-with-space2 nil
3768 "Matches a link with spaces, optional angular brackets around it.")
3769 (defvar org-link-re-with-space3 nil
3770 "Matches a link with spaces, only for internal part in bracket links.")
3771 (defvar org-angle-link-re nil
3772 "Matches link with angular brackets, spaces are allowed.")
3773 (defvar org-plain-link-re nil
3774 "Matches plain link, without spaces.")
3775 (defvar org-bracket-link-regexp nil
3776 "Matches a link in double brackets.")
3777 (defvar org-bracket-link-analytic-regexp nil
3778 "Regular expression used to analyze links.
3779 Here is what the match groups contain after a match:
3780 1: http:
3781 2: http
3782 3: path
3783 4: [desc]
3784 5: desc")
3785 (defvar org-bracket-link-analytic-regexp++ nil
3786 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3787 (defvar org-any-link-re nil
3788 "Regular expression matching any link.")
3790 (defun org-make-link-regexps ()
3791 "Update the link regular expressions.
3792 This should be called after the variable `org-link-types' has changed."
3793 (setq org-link-types-re
3794 (concat
3795 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3796 org-link-re-with-space
3797 (concat
3798 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3799 "\\([^" org-non-link-chars " ]"
3800 "[^" org-non-link-chars "]*"
3801 "[^" org-non-link-chars " ]\\)>?")
3802 org-link-re-with-space2
3803 (concat
3804 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3805 "\\([^" org-non-link-chars " ]"
3806 "[^\t\n\r]*"
3807 "[^" org-non-link-chars " ]\\)>?")
3808 org-link-re-with-space3
3809 (concat
3810 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3811 "\\([^" org-non-link-chars " ]"
3812 "[^\t\n\r]*\\)")
3813 org-angle-link-re
3814 (concat
3815 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3816 "\\([^" org-non-link-chars " ]"
3817 "[^" org-non-link-chars "]*"
3818 "\\)>")
3819 org-plain-link-re
3820 (concat
3821 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3822 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3823 org-bracket-link-regexp
3824 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3825 org-bracket-link-analytic-regexp
3826 (concat
3827 "\\[\\["
3828 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3829 "\\([^]]+\\)"
3830 "\\]"
3831 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3832 "\\]")
3833 org-bracket-link-analytic-regexp++
3834 (concat
3835 "\\[\\["
3836 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3837 "\\([^]]+\\)"
3838 "\\]"
3839 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3840 "\\]")
3841 org-any-link-re
3842 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3843 org-angle-link-re "\\)\\|\\("
3844 org-plain-link-re "\\)")))
3846 (org-make-link-regexps)
3848 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3849 "Regular expression for fast time stamp matching.")
3850 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3851 "Regular expression for fast time stamp matching.")
3852 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3853 "Regular expression matching time strings for analysis.
3854 This one does not require the space after the date, so it can be used
3855 on a string that terminates immediately after the date.")
3856 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3857 "Regular expression matching time strings for analysis.")
3858 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3859 "Regular expression matching time stamps, with groups.")
3860 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3861 "Regular expression matching time stamps (also [..]), with groups.")
3862 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3863 "Regular expression matching a time stamp range.")
3864 (defconst org-tr-regexp-both
3865 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3866 "Regular expression matching a time stamp range.")
3867 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3868 org-ts-regexp "\\)?")
3869 "Regular expression matching a time stamp or time stamp range.")
3870 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3871 org-ts-regexp-both "\\)?")
3872 "Regular expression matching a time stamp or time stamp range.
3873 The time stamps may be either active or inactive.")
3875 (defvar org-emph-face nil)
3877 (defun org-do-emphasis-faces (limit)
3878 "Run through the buffer and add overlays to links."
3879 (let (rtn)
3880 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3881 (if (not (= (char-after (match-beginning 3))
3882 (char-after (match-beginning 4))))
3883 (progn
3884 (setq rtn t)
3885 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3886 'face
3887 (nth 1 (assoc (match-string 3)
3888 org-emphasis-alist)))
3889 (add-text-properties (match-beginning 2) (match-end 2)
3890 '(font-lock-multiline t))
3891 (when org-hide-emphasis-markers
3892 (add-text-properties (match-end 4) (match-beginning 5)
3893 '(invisible org-link))
3894 (add-text-properties (match-beginning 3) (match-end 3)
3895 '(invisible org-link)))))
3896 (backward-char 1))
3897 rtn))
3899 (defun org-emphasize (&optional char)
3900 "Insert or change an emphasis, i.e. a font like bold or italic.
3901 If there is an active region, change that region to a new emphasis.
3902 If there is no region, just insert the marker characters and position
3903 the cursor between them.
3904 CHAR should be either the marker character, or the first character of the
3905 HTML tag associated with that emphasis. If CHAR is a space, the means
3906 to remove the emphasis of the selected region.
3907 If char is not given (for example in an interactive call) it
3908 will be prompted for."
3909 (interactive)
3910 (let ((eal org-emphasis-alist) e det
3911 (erc org-emphasis-regexp-components)
3912 (prompt "")
3913 (string "") beg end move tag c s)
3914 (if (org-region-active-p)
3915 (setq beg (region-beginning) end (region-end)
3916 string (buffer-substring beg end))
3917 (setq move t))
3919 (while (setq e (pop eal))
3920 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3921 c (aref tag 0))
3922 (push (cons c (string-to-char (car e))) det)
3923 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3924 (substring tag 1)))))
3925 (setq det (nreverse det))
3926 (unless char
3927 (message "%s" (concat "Emphasis marker or tag:" prompt))
3928 (setq char (read-char-exclusive)))
3929 (setq char (or (cdr (assoc char det)) char))
3930 (if (equal char ?\ )
3931 (setq s "" move nil)
3932 (unless (assoc (char-to-string char) org-emphasis-alist)
3933 (error "No such emphasis marker: \"%c\"" char))
3934 (setq s (char-to-string char)))
3935 (while (and (> (length string) 1)
3936 (equal (substring string 0 1) (substring string -1))
3937 (assoc (substring string 0 1) org-emphasis-alist))
3938 (setq string (substring string 1 -1)))
3939 (setq string (concat s string s))
3940 (if beg (delete-region beg end))
3941 (unless (or (bolp)
3942 (string-match (concat "[" (nth 0 erc) "\n]")
3943 (char-to-string (char-before (point)))))
3944 (insert " "))
3945 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3946 (char-to-string (char-after (point))))
3947 (insert " ") (backward-char 1))
3948 (insert string)
3949 (and move (backward-char 1))))
3951 (defconst org-nonsticky-props
3952 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3955 (defun org-activate-plain-links (limit)
3956 "Run through the buffer and add overlays to links."
3957 (catch 'exit
3958 (let (f)
3959 (while (re-search-forward org-plain-link-re limit t)
3960 (setq f (get-text-property (match-beginning 0) 'face))
3961 (if (or (eq f 'org-tag)
3962 (and (listp f) (memq 'org-tag f)))
3964 (add-text-properties (match-beginning 0) (match-end 0)
3965 (list 'mouse-face 'highlight
3966 'rear-nonsticky org-nonsticky-props
3967 'keymap org-mouse-map
3969 (throw 'exit t))))))
3971 (defun org-activate-code (limit)
3972 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3973 (progn
3974 (remove-text-properties (match-beginning 0) (match-end 0)
3975 '(display t invisible t intangible t))
3976 t)))
3978 (defun org-activate-angle-links (limit)
3979 "Run through the buffer and add overlays to links."
3980 (if (re-search-forward org-angle-link-re limit t)
3981 (progn
3982 (add-text-properties (match-beginning 0) (match-end 0)
3983 (list 'mouse-face 'highlight
3984 'rear-nonsticky org-nonsticky-props
3985 'keymap org-mouse-map
3987 t)))
3989 (defun org-activate-footnote-links (limit)
3990 "Run through the buffer and add overlays to links."
3991 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3992 limit t)
3993 (progn
3994 (add-text-properties (match-beginning 2) (match-end 2)
3995 (list 'mouse-face 'highlight
3996 'rear-nonsticky org-nonsticky-props
3997 'keymap org-mouse-map
3998 'help-echo
3999 (if (= (point-at-bol) (match-beginning 2))
4000 "Footnote definition"
4001 "Footnote reference")
4003 t)))
4005 (defun org-activate-bracket-links (limit)
4006 "Run through the buffer and add overlays to bracketed links."
4007 (if (re-search-forward org-bracket-link-regexp limit t)
4008 (let* ((help (concat "LINK: "
4009 (org-match-string-no-properties 1)))
4010 ;; FIXME: above we should remove the escapes.
4011 ;; but that requires another match, protecting match data,
4012 ;; a lot of overhead for font-lock.
4013 (ip (org-maybe-intangible
4014 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4015 'keymap org-mouse-map 'mouse-face 'highlight
4016 'font-lock-multiline t 'help-echo help)))
4017 (vp (list 'rear-nonsticky org-nonsticky-props
4018 'keymap org-mouse-map 'mouse-face 'highlight
4019 ' font-lock-multiline t 'help-echo help)))
4020 ;; We need to remove the invisible property here. Table narrowing
4021 ;; may have made some of this invisible.
4022 (remove-text-properties (match-beginning 0) (match-end 0)
4023 '(invisible nil))
4024 (if (match-end 3)
4025 (progn
4026 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4027 (add-text-properties (match-beginning 3) (match-end 3) vp)
4028 (add-text-properties (match-end 3) (match-end 0) ip))
4029 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4030 (add-text-properties (match-beginning 1) (match-end 1) vp)
4031 (add-text-properties (match-end 1) (match-end 0) ip))
4032 t)))
4034 (defun org-activate-dates (limit)
4035 "Run through the buffer and add overlays to dates."
4036 (if (re-search-forward org-tsr-regexp-both limit t)
4037 (progn
4038 (add-text-properties (match-beginning 0) (match-end 0)
4039 (list 'mouse-face 'highlight
4040 'rear-nonsticky org-nonsticky-props
4041 'keymap org-mouse-map))
4042 (when org-display-custom-times
4043 (if (match-end 3)
4044 (org-display-custom-time (match-beginning 3) (match-end 3)))
4045 (org-display-custom-time (match-beginning 1) (match-end 1)))
4046 t)))
4048 (defvar org-target-link-regexp nil
4049 "Regular expression matching radio targets in plain text.")
4050 (make-variable-buffer-local 'org-target-link-regexp)
4051 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4052 "Regular expression matching a link target.")
4053 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4054 "Regular expression matching a radio target.")
4055 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4056 "Regular expression matching any target.")
4058 (defun org-activate-target-links (limit)
4059 "Run through the buffer and add overlays to target matches."
4060 (when org-target-link-regexp
4061 (let ((case-fold-search t))
4062 (if (re-search-forward org-target-link-regexp limit t)
4063 (progn
4064 (add-text-properties (match-beginning 0) (match-end 0)
4065 (list 'mouse-face 'highlight
4066 'rear-nonsticky org-nonsticky-props
4067 'keymap org-mouse-map
4068 'help-echo "Radio target link"
4069 'org-linked-text t))
4070 t)))))
4072 (defun org-update-radio-target-regexp ()
4073 "Find all radio targets in this file and update the regular expression."
4074 (interactive)
4075 (when (memq 'radio org-activate-links)
4076 (setq org-target-link-regexp
4077 (org-make-target-link-regexp (org-all-targets 'radio)))
4078 (org-restart-font-lock)))
4080 (defun org-hide-wide-columns (limit)
4081 (let (s e)
4082 (setq s (text-property-any (point) (or limit (point-max))
4083 'org-cwidth t))
4084 (when s
4085 (setq e (next-single-property-change s 'org-cwidth))
4086 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4087 (goto-char e)
4088 t)))
4090 (defvar org-latex-and-specials-regexp nil
4091 "Regular expression for highlighting export special stuff.")
4092 (defvar org-match-substring-regexp)
4093 (defvar org-match-substring-with-braces-regexp)
4094 (defvar org-export-html-special-string-regexps)
4096 (defun org-compute-latex-and-specials-regexp ()
4097 "Compute regular expression for stuff treated specially by exporters."
4098 (if (not org-highlight-latex-fragments-and-specials)
4099 (org-set-local 'org-latex-and-specials-regexp nil)
4100 (require 'org-exp)
4101 (let*
4102 ((matchers (plist-get org-format-latex-options :matchers))
4103 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4104 org-latex-regexps)))
4105 (options (org-combine-plists (org-default-export-plist)
4106 (org-infile-export-plist)))
4107 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4108 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4109 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4110 (org-export-html-expand (plist-get options :expand-quoted-html))
4111 (org-export-with-special-strings (plist-get options :special-strings))
4112 (re-sub
4113 (cond
4114 ((equal org-export-with-sub-superscripts '{})
4115 (list org-match-substring-with-braces-regexp))
4116 (org-export-with-sub-superscripts
4117 (list org-match-substring-regexp))
4118 (t nil)))
4119 (re-latex
4120 (if org-export-with-LaTeX-fragments
4121 (mapcar (lambda (x) (nth 1 x)) latexs)))
4122 (re-macros
4123 (if org-export-with-TeX-macros
4124 (list (concat "\\\\"
4125 (regexp-opt
4126 (append (mapcar 'car org-html-entities)
4127 (if (boundp 'org-latex-entities)
4128 org-latex-entities nil))
4129 'words))) ; FIXME
4131 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4132 (re-special (if org-export-with-special-strings
4133 (mapcar (lambda (x) (car x))
4134 org-export-html-special-string-regexps)))
4135 (re-rest
4136 (delq nil
4137 (list
4138 (if org-export-html-expand "@<[^>\n]+>")
4139 ))))
4140 (org-set-local
4141 'org-latex-and-specials-regexp
4142 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4143 re-rest) "\\|")))))
4145 (defun org-do-latex-and-special-faces (limit)
4146 "Run through the buffer and add overlays to links."
4147 (when org-latex-and-specials-regexp
4148 (let (rtn d)
4149 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4150 limit t))
4151 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4152 'face))
4153 '(org-code org-verbatim underline)))
4154 (progn
4155 (setq rtn t
4156 d (cond ((member (char-after (1+ (match-beginning 0)))
4157 '(?_ ?^)) 1)
4158 (t 0)))
4159 (font-lock-prepend-text-property
4160 (+ d (match-beginning 0)) (match-end 0)
4161 'face 'org-latex-and-export-specials)
4162 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4163 '(font-lock-multiline t)))))
4164 rtn)))
4166 (defun org-restart-font-lock ()
4167 "Restart font-lock-mode, to force refontification."
4168 (when (and (boundp 'font-lock-mode) font-lock-mode)
4169 (font-lock-mode -1)
4170 (font-lock-mode 1)))
4172 (defun org-all-targets (&optional radio)
4173 "Return a list of all targets in this file.
4174 With optional argument RADIO, only find radio targets."
4175 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4176 rtn)
4177 (save-excursion
4178 (goto-char (point-min))
4179 (while (re-search-forward re nil t)
4180 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4181 rtn)))
4183 (defun org-make-target-link-regexp (targets)
4184 "Make regular expression matching all strings in TARGETS.
4185 The regular expression finds the targets also if there is a line break
4186 between words."
4187 (and targets
4188 (concat
4189 "\\<\\("
4190 (mapconcat
4191 (lambda (x)
4192 (while (string-match " +" x)
4193 (setq x (replace-match "\\s-+" t t x)))
4195 targets
4196 "\\|")
4197 "\\)\\>")))
4199 (defun org-activate-tags (limit)
4200 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4201 (progn
4202 (add-text-properties (match-beginning 1) (match-end 1)
4203 (list 'mouse-face 'highlight
4204 'rear-nonsticky org-nonsticky-props
4205 'keymap org-mouse-map))
4206 t)))
4208 (defun org-outline-level ()
4209 (save-excursion
4210 (looking-at outline-regexp)
4211 (if (match-beginning 1)
4212 (+ (org-get-string-indentation (match-string 1)) 1000)
4213 (1- (- (match-end 0) (match-beginning 0))))))
4215 (defvar org-font-lock-keywords nil)
4217 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4218 "Regular expression matching a property line.")
4220 (defvar org-font-lock-hook nil
4221 "Functions to be called for special font lock stuff.")
4223 (defun org-font-lock-hook (limit)
4224 (run-hook-with-args 'org-font-lock-hook limit))
4226 (defun org-set-font-lock-defaults ()
4227 (let* ((em org-fontify-emphasized-text)
4228 (lk org-activate-links)
4229 (org-font-lock-extra-keywords
4230 (list
4231 ;; Call the hook
4232 '(org-font-lock-hook)
4233 ;; Headlines
4234 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4235 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4236 ;; Table lines
4237 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4238 (1 'org-table t))
4239 ;; Table internals
4240 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4241 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4242 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4243 ;; Drawers
4244 (list org-drawer-regexp '(0 'org-special-keyword t))
4245 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4246 ;; Properties
4247 (list org-property-re
4248 '(1 'org-special-keyword t)
4249 '(3 'org-property-value t))
4250 (if org-format-transports-properties-p
4251 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4252 ;; Links
4253 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4254 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4255 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4256 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4257 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4258 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4259 (if (memq 'footnote lk) '(org-activate-footnote-links
4260 (2 'org-footnote t)))
4261 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4262 '(org-hide-wide-columns (0 nil append))
4263 ;; TODO lines
4264 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4265 '(1 (org-get-todo-face 1) t))
4266 ;; DONE
4267 (if org-fontify-done-headline
4268 (list (concat "^[*]+ +\\<\\("
4269 (mapconcat 'regexp-quote org-done-keywords "\\|")
4270 "\\)\\(.*\\)")
4271 '(2 'org-headline-done t))
4272 nil)
4273 ;; Priorities
4274 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4275 ;; Tags
4276 '(org-font-lock-add-tag-faces)
4277 ;; Special keywords
4278 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4279 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4280 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4281 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4282 ;; Emphasis
4283 (if em
4284 (if (featurep 'xemacs)
4285 '(org-do-emphasis-faces (0 nil append))
4286 '(org-do-emphasis-faces)))
4287 ;; Checkboxes
4288 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4289 2 'bold prepend)
4290 (if org-provide-checkbox-statistics
4291 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4292 (0 (org-get-checkbox-statistics-face) t)))
4293 ;; Description list items
4294 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4295 2 'bold prepend)
4296 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4297 '(1 'org-archived prepend))
4298 ;; Specials
4299 '(org-do-latex-and-special-faces)
4300 ;; Code
4301 '(org-activate-code (1 'org-code t))
4302 ;; COMMENT
4303 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4304 "\\|" org-quote-string "\\)\\>")
4305 '(1 'org-special-keyword t))
4306 '("^#.*" (0 'font-lock-comment-face t))
4308 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4309 ;; Now set the full font-lock-keywords
4310 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4311 (org-set-local 'font-lock-defaults
4312 '(org-font-lock-keywords t nil nil backward-paragraph))
4313 (kill-local-variable 'font-lock-keywords) nil))
4315 (defvar org-m nil)
4316 (defvar org-l nil)
4317 (defvar org-f nil)
4318 (defun org-get-level-face (n)
4319 "Get the right face for match N in font-lock matching of headlines."
4320 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4321 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4322 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4323 (cond
4324 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4325 ((eq n 2) org-f)
4326 (t (if org-level-color-stars-only nil org-f))))
4328 (defun org-get-todo-face (kwd)
4329 "Get the right face for a TODO keyword KWD.
4330 If KWD is a number, get the corresponding match group."
4331 (if (numberp kwd) (setq kwd (match-string kwd)))
4332 (or (cdr (assoc kwd org-todo-keyword-faces))
4333 (and (member kwd org-done-keywords) 'org-done)
4334 'org-todo))
4336 (defun org-font-lock-add-tag-faces (limit)
4337 "Add the special tag faces."
4338 (when (and org-tag-faces org-tags-special-faces-re)
4339 (while (re-search-forward org-tags-special-faces-re limit t)
4340 (add-text-properties (match-beginning 1) (match-end 1)
4341 (list 'face (org-get-tag-face 1)
4342 'font-lock-fontified t))
4343 (backward-char 1))))
4345 (defun org-get-tag-face (kwd)
4346 "Get the right face for a TODO keyword KWD.
4347 If KWD is a number, get the corresponding match group."
4348 (if (numberp kwd) (setq kwd (match-string kwd)))
4349 (or (cdr (assoc kwd org-tag-faces))
4350 'org-tag))
4352 (defun org-unfontify-region (beg end &optional maybe_loudly)
4353 "Remove fontification and activation overlays from links."
4354 (font-lock-default-unfontify-region beg end)
4355 (let* ((buffer-undo-list t)
4356 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4357 (inhibit-modification-hooks t)
4358 deactivate-mark buffer-file-name buffer-file-truename)
4359 (remove-text-properties beg end
4360 '(mouse-face t keymap t org-linked-text t
4361 invisible t intangible t))))
4363 ;;;; Visibility cycling, including org-goto and indirect buffer
4365 ;;; Cycling
4367 (defvar org-cycle-global-status nil)
4368 (make-variable-buffer-local 'org-cycle-global-status)
4369 (defvar org-cycle-subtree-status nil)
4370 (make-variable-buffer-local 'org-cycle-subtree-status)
4372 ;;;###autoload
4373 (defun org-cycle (&optional arg)
4374 "Visibility cycling for Org-mode.
4376 - When this function is called with a prefix argument, rotate the entire
4377 buffer through 3 states (global cycling)
4378 1. OVERVIEW: Show only top-level headlines.
4379 2. CONTENTS: Show all headlines of all levels, but no body text.
4380 3. SHOW ALL: Show everything.
4381 When called with two C-u C-u prefixes, switch to the startup visibility,
4382 determined by the variable `org-startup-folded', and by any VISIBILITY
4383 properties in the buffer.
4384 When called with three C-u C-u C-u prefixed, show the entire buffer,
4385 including drawers.
4387 - When point is at the beginning of a headline, rotate the subtree started
4388 by this line through 3 different states (local cycling)
4389 1. FOLDED: Only the main headline is shown.
4390 2. CHILDREN: The main headline and the direct children are shown.
4391 From this state, you can move to one of the children
4392 and zoom in further.
4393 3. SUBTREE: Show the entire subtree, including body text.
4395 - When there is a numeric prefix, go up to a heading with level ARG, do
4396 a `show-subtree' and return to the previous cursor position. If ARG
4397 is negative, go up that many levels.
4399 - When point is not at the beginning of a headline, execute the global
4400 binding for TAB, which is re-indenting the line. See the option
4401 `org-cycle-emulate-tab' for details.
4403 - Special case: if point is at the beginning of the buffer and there is
4404 no headline in line 1, this function will act as if called with prefix arg.
4405 But only if also the variable `org-cycle-global-at-bob' is t."
4406 (interactive "P")
4407 (org-load-modules-maybe)
4408 (let* ((outline-regexp
4409 (if (and (org-mode-p) org-cycle-include-plain-lists)
4410 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4411 outline-regexp))
4412 (bob-special (and org-cycle-global-at-bob (bobp)
4413 (not (looking-at outline-regexp))))
4414 (org-cycle-hook
4415 (if bob-special
4416 (delq 'org-optimize-window-after-visibility-change
4417 (copy-sequence org-cycle-hook))
4418 org-cycle-hook))
4419 (pos (point)))
4421 (if (or bob-special (equal arg '(4)))
4422 ;; special case: use global cycling
4423 (setq arg t))
4425 (cond
4427 ((equal arg '(16))
4428 (org-set-startup-visibility)
4429 (message "Startup visibility, plus VISIBILITY properties"))
4431 ((equal arg '(64))
4432 (show-all)
4433 (message "Entire buffer visible, including drawers"))
4435 ((org-at-table-p 'any)
4436 ;; Enter the table or move to the next field in the table
4437 (or (org-table-recognize-table.el)
4438 (progn
4439 (if arg (org-table-edit-field t)
4440 (org-table-justify-field-maybe)
4441 (call-interactively 'org-table-next-field)))))
4443 ((eq arg t) ;; Global cycling
4445 (cond
4446 ((and (eq last-command this-command)
4447 (eq org-cycle-global-status 'overview))
4448 ;; We just created the overview - now do table of contents
4449 ;; This can be slow in very large buffers, so indicate action
4450 (message "CONTENTS...")
4451 (org-content)
4452 (message "CONTENTS...done")
4453 (setq org-cycle-global-status 'contents)
4454 (run-hook-with-args 'org-cycle-hook 'contents))
4456 ((and (eq last-command this-command)
4457 (eq org-cycle-global-status 'contents))
4458 ;; We just showed the table of contents - now show everything
4459 (show-all)
4460 (message "SHOW ALL")
4461 (setq org-cycle-global-status 'all)
4462 (run-hook-with-args 'org-cycle-hook 'all))
4465 ;; Default action: go to overview
4466 (org-overview)
4467 (message "OVERVIEW")
4468 (setq org-cycle-global-status 'overview)
4469 (run-hook-with-args 'org-cycle-hook 'overview))))
4471 ((and org-drawers org-drawer-regexp
4472 (save-excursion
4473 (beginning-of-line 1)
4474 (looking-at org-drawer-regexp)))
4475 ;; Toggle block visibility
4476 (org-flag-drawer
4477 (not (get-char-property (match-end 0) 'invisible))))
4479 ((integerp arg)
4480 ;; Show-subtree, ARG levels up from here.
4481 (save-excursion
4482 (org-back-to-heading)
4483 (outline-up-heading (if (< arg 0) (- arg)
4484 (- (funcall outline-level) arg)))
4485 (org-show-subtree)))
4487 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4488 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4489 ;; At a heading: rotate between three different views
4490 (org-back-to-heading)
4491 (let ((goal-column 0) eoh eol eos)
4492 ;; First, some boundaries
4493 (save-excursion
4494 (org-back-to-heading)
4495 (save-excursion
4496 (beginning-of-line 2)
4497 (while (and (not (eobp)) ;; this is like `next-line'
4498 (get-char-property (1- (point)) 'invisible))
4499 (beginning-of-line 2)) (setq eol (point)))
4500 (outline-end-of-heading) (setq eoh (point))
4501 (org-end-of-subtree t)
4502 (unless (eobp)
4503 (skip-chars-forward " \t\n")
4504 (beginning-of-line 1) ; in case this is an item
4506 (setq eos (1- (point))))
4507 ;; Find out what to do next and set `this-command'
4508 (cond
4509 ((= eos eoh)
4510 ;; Nothing is hidden behind this heading
4511 (message "EMPTY ENTRY")
4512 (setq org-cycle-subtree-status nil)
4513 (save-excursion
4514 (goto-char eos)
4515 (outline-next-heading)
4516 (if (org-invisible-p) (org-flag-heading nil))))
4517 ((or (>= eol eos)
4518 (not (string-match "\\S-" (buffer-substring eol eos))))
4519 ;; Entire subtree is hidden in one line: open it
4520 (org-show-entry)
4521 (show-children)
4522 (message "CHILDREN")
4523 (save-excursion
4524 (goto-char eos)
4525 (outline-next-heading)
4526 (if (org-invisible-p) (org-flag-heading nil)))
4527 (setq org-cycle-subtree-status 'children)
4528 (run-hook-with-args 'org-cycle-hook 'children))
4529 ((and (eq last-command this-command)
4530 (eq org-cycle-subtree-status 'children))
4531 ;; We just showed the children, now show everything.
4532 (org-show-subtree)
4533 (message "SUBTREE")
4534 (setq org-cycle-subtree-status 'subtree)
4535 (run-hook-with-args 'org-cycle-hook 'subtree))
4537 ;; Default action: hide the subtree.
4538 (hide-subtree)
4539 (message "FOLDED")
4540 (setq org-cycle-subtree-status 'folded)
4541 (run-hook-with-args 'org-cycle-hook 'folded)))))
4543 ;; TAB emulation and template completion
4544 (buffer-read-only (org-back-to-heading))
4546 ((org-try-structure-completion))
4548 ((org-try-cdlatex-tab))
4550 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4551 (or (not (bolp))
4552 (not (looking-at outline-regexp))))
4553 (call-interactively (global-key-binding "\t")))
4555 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4556 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4557 (or (and (eq org-cycle-emulate-tab 'white)
4558 (= (match-end 0) (point-at-eol)))
4559 (and (eq org-cycle-emulate-tab 'whitestart)
4560 (>= (match-end 0) pos))))
4562 (eq org-cycle-emulate-tab t))
4563 (call-interactively (global-key-binding "\t")))
4565 (t (save-excursion
4566 (org-back-to-heading)
4567 (org-cycle))))))
4569 ;;;###autoload
4570 (defun org-global-cycle (&optional arg)
4571 "Cycle the global visibility. For details see `org-cycle'.
4572 With C-u prefix arg, switch to startup visibility.
4573 With a numeric prefix, show all headlines up to that level."
4574 (interactive "P")
4575 (let ((org-cycle-include-plain-lists
4576 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4577 (cond
4578 ((integerp arg)
4579 (show-all)
4580 (hide-sublevels arg)
4581 (setq org-cycle-global-status 'contents))
4582 ((equal arg '(4))
4583 (org-set-startup-visibility)
4584 (message "Startup visibility, plus VISIBILITY properties."))
4586 (org-cycle '(4))))))
4588 (defun org-set-startup-visibility ()
4589 "Set the visibility required by startup options and properties."
4590 (cond
4591 ((eq org-startup-folded t)
4592 (org-cycle '(4)))
4593 ((eq org-startup-folded 'content)
4594 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4595 (org-cycle '(4)) (org-cycle '(4)))))
4596 (org-set-visibility-according-to-property 'no-cleanup)
4597 (org-cycle-hide-archived-subtrees 'all)
4598 (org-cycle-hide-drawers 'all)
4599 (org-cycle-show-empty-lines 'all))
4601 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4602 "Switch subtree visibilities according to :VISIBILITY: property."
4603 (interactive)
4604 (let (org-show-entry-below state)
4605 (save-excursion
4606 (goto-char (point-min))
4607 (while (re-search-forward
4608 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4609 nil t)
4610 (setq state (match-string 1))
4611 (save-excursion
4612 (org-back-to-heading t)
4613 (hide-subtree)
4614 (org-reveal)
4615 (cond
4616 ((equal state '("fold" "folded"))
4617 (hide-subtree))
4618 ((equal state "children")
4619 (org-show-hidden-entry)
4620 (show-children))
4621 ((equal state "content")
4622 (save-excursion
4623 (save-restriction
4624 (org-narrow-to-subtree)
4625 (org-content))))
4626 ((member state '("all" "showall"))
4627 (show-subtree)))))
4628 (unless no-cleanup
4629 (org-cycle-hide-archived-subtrees 'all)
4630 (org-cycle-hide-drawers 'all)
4631 (org-cycle-show-empty-lines 'all)))))
4633 (defun org-overview ()
4634 "Switch to overview mode, showing only top-level headlines.
4635 Really, this shows all headlines with level equal or greater than the level
4636 of the first headline in the buffer. This is important, because if the
4637 first headline is not level one, then (hide-sublevels 1) gives confusing
4638 results."
4639 (interactive)
4640 (let ((level (save-excursion
4641 (goto-char (point-min))
4642 (if (re-search-forward (concat "^" outline-regexp) nil t)
4643 (progn
4644 (goto-char (match-beginning 0))
4645 (funcall outline-level))))))
4646 (and level (hide-sublevels level))))
4648 (defun org-content (&optional arg)
4649 "Show all headlines in the buffer, like a table of contents.
4650 With numerical argument N, show content up to level N."
4651 (interactive "P")
4652 (save-excursion
4653 ;; Visit all headings and show their offspring
4654 (and (integerp arg) (org-overview))
4655 (goto-char (point-max))
4656 (catch 'exit
4657 (while (and (progn (condition-case nil
4658 (outline-previous-visible-heading 1)
4659 (error (goto-char (point-min))))
4661 (looking-at outline-regexp))
4662 (if (integerp arg)
4663 (show-children (1- arg))
4664 (show-branches))
4665 (if (bobp) (throw 'exit nil))))))
4668 (defun org-optimize-window-after-visibility-change (state)
4669 "Adjust the window after a change in outline visibility.
4670 This function is the default value of the hook `org-cycle-hook'."
4671 (when (get-buffer-window (current-buffer))
4672 (cond
4673 ((eq state 'content) nil)
4674 ((eq state 'all) nil)
4675 ((eq state 'folded) nil)
4676 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4677 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4679 (defun org-compact-display-after-subtree-move ()
4680 "Show a compacter version of the tree of the entry's parent."
4681 (save-excursion
4682 (if (org-up-heading-safe)
4683 (progn
4684 (hide-subtree)
4685 (show-entry)
4686 (show-children)
4687 (org-cycle-show-empty-lines 'children)
4688 (org-cycle-hide-drawers 'children))
4689 (org-overview))))
4691 (defun org-cycle-show-empty-lines (state)
4692 "Show empty lines above all visible headlines.
4693 The region to be covered depends on STATE when called through
4694 `org-cycle-hook'. Lisp program can use t for STATE to get the
4695 entire buffer covered. Note that an empty line is only shown if there
4696 are at least `org-cycle-separator-lines' empty lines before the headline."
4697 (when (> org-cycle-separator-lines 0)
4698 (save-excursion
4699 (let* ((n org-cycle-separator-lines)
4700 (re (cond
4701 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4702 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4703 (t (let ((ns (number-to-string (- n 2))))
4704 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4705 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4706 beg end)
4707 (cond
4708 ((memq state '(overview contents t))
4709 (setq beg (point-min) end (point-max)))
4710 ((memq state '(children folded))
4711 (setq beg (point) end (progn (org-end-of-subtree t t)
4712 (beginning-of-line 2)
4713 (point)))))
4714 (when beg
4715 (goto-char beg)
4716 (while (re-search-forward re end t)
4717 (if (not (get-char-property (match-end 1) 'invisible))
4718 (outline-flag-region
4719 (match-beginning 1) (match-end 1) nil)))))))
4720 ;; Never hide empty lines at the end of the file.
4721 (save-excursion
4722 (goto-char (point-max))
4723 (outline-previous-heading)
4724 (outline-end-of-heading)
4725 (if (and (looking-at "[ \t\n]+")
4726 (= (match-end 0) (point-max)))
4727 (outline-flag-region (point) (match-end 0) nil))))
4729 (defun org-show-empty-lines-in-parent ()
4730 "Move to the parent and re-show empty lines before visible headlines."
4731 (save-excursion
4732 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4733 (org-cycle-show-empty-lines context))))
4735 (defun org-cycle-hide-drawers (state)
4736 "Re-hide all drawers after a visibility state change."
4737 (when (and (org-mode-p)
4738 (not (memq state '(overview folded))))
4739 (save-excursion
4740 (let* ((globalp (memq state '(contents all)))
4741 (beg (if globalp (point-min) (point)))
4742 (end (if globalp (point-max) (org-end-of-subtree t))))
4743 (goto-char beg)
4744 (while (re-search-forward org-drawer-regexp end t)
4745 (org-flag-drawer t))))))
4747 (defun org-flag-drawer (flag)
4748 (save-excursion
4749 (beginning-of-line 1)
4750 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4751 (let ((b (match-end 0))
4752 (outline-regexp org-outline-regexp))
4753 (if (re-search-forward
4754 "^[ \t]*:END:"
4755 (save-excursion (outline-next-heading) (point)) t)
4756 (outline-flag-region b (point-at-eol) flag)
4757 (error ":END: line missing"))))))
4759 (defun org-subtree-end-visible-p ()
4760 "Is the end of the current subtree visible?"
4761 (pos-visible-in-window-p
4762 (save-excursion (org-end-of-subtree t) (point))))
4764 (defun org-first-headline-recenter (&optional N)
4765 "Move cursor to the first headline and recenter the headline.
4766 Optional argument N means, put the headline into the Nth line of the window."
4767 (goto-char (point-min))
4768 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4769 (beginning-of-line)
4770 (recenter (prefix-numeric-value N))))
4772 ;;; Org-goto
4774 (defvar org-goto-window-configuration nil)
4775 (defvar org-goto-marker nil)
4776 (defvar org-goto-map
4777 (let ((map (make-sparse-keymap)))
4778 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4779 (while (setq cmd (pop cmds))
4780 (substitute-key-definition cmd cmd map global-map)))
4781 (suppress-keymap map)
4782 (org-defkey map "\C-m" 'org-goto-ret)
4783 (org-defkey map [(return)] 'org-goto-ret)
4784 (org-defkey map [(left)] 'org-goto-left)
4785 (org-defkey map [(right)] 'org-goto-right)
4786 (org-defkey map [(control ?g)] 'org-goto-quit)
4787 (org-defkey map "\C-i" 'org-cycle)
4788 (org-defkey map [(tab)] 'org-cycle)
4789 (org-defkey map [(down)] 'outline-next-visible-heading)
4790 (org-defkey map [(up)] 'outline-previous-visible-heading)
4791 (if org-goto-auto-isearch
4792 (if (fboundp 'define-key-after)
4793 (define-key-after map [t] 'org-goto-local-auto-isearch)
4794 nil)
4795 (org-defkey map "q" 'org-goto-quit)
4796 (org-defkey map "n" 'outline-next-visible-heading)
4797 (org-defkey map "p" 'outline-previous-visible-heading)
4798 (org-defkey map "f" 'outline-forward-same-level)
4799 (org-defkey map "b" 'outline-backward-same-level)
4800 (org-defkey map "u" 'outline-up-heading))
4801 (org-defkey map "/" 'org-occur)
4802 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4803 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4804 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4805 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4806 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4807 map))
4809 (defconst org-goto-help
4810 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4811 RET=jump to location [Q]uit and return to previous location
4812 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4814 (defvar org-goto-start-pos) ; dynamically scoped parameter
4816 ;; FIXME: Docstring doe not mention both interfaces
4817 (defun org-goto (&optional alternative-interface)
4818 "Look up a different location in the current file, keeping current visibility.
4820 When you want look-up or go to a different location in a document, the
4821 fastest way is often to fold the entire buffer and then dive into the tree.
4822 This method has the disadvantage, that the previous location will be folded,
4823 which may not be what you want.
4825 This command works around this by showing a copy of the current buffer
4826 in an indirect buffer, in overview mode. You can dive into the tree in
4827 that copy, use org-occur and incremental search to find a location.
4828 When pressing RET or `Q', the command returns to the original buffer in
4829 which the visibility is still unchanged. After RET is will also jump to
4830 the location selected in the indirect buffer and expose the
4831 the headline hierarchy above."
4832 (interactive "P")
4833 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4834 (org-refile-use-outline-path t)
4835 (interface
4836 (if (not alternative-interface)
4837 org-goto-interface
4838 (if (eq org-goto-interface 'outline)
4839 'outline-path-completion
4840 'outline)))
4841 (org-goto-start-pos (point))
4842 (selected-point
4843 (if (eq interface 'outline)
4844 (car (org-get-location (current-buffer) org-goto-help))
4845 (nth 3 (org-refile-get-location "Goto: ")))))
4846 (if selected-point
4847 (progn
4848 (org-mark-ring-push org-goto-start-pos)
4849 (goto-char selected-point)
4850 (if (or (org-invisible-p) (org-invisible-p2))
4851 (org-show-context 'org-goto)))
4852 (message "Quit"))))
4854 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4855 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4856 (defvar org-goto-local-auto-isearch-map) ; defined below
4858 (defun org-get-location (buf help)
4859 "Let the user select a location in the Org-mode buffer BUF.
4860 This function uses a recursive edit. It returns the selected position
4861 or nil."
4862 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4863 (isearch-hide-immediately nil)
4864 (isearch-search-fun-function
4865 (lambda () 'org-goto-local-search-headings))
4866 (org-goto-selected-point org-goto-exit-command))
4867 (save-excursion
4868 (save-window-excursion
4869 (delete-other-windows)
4870 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4871 (switch-to-buffer
4872 (condition-case nil
4873 (make-indirect-buffer (current-buffer) "*org-goto*")
4874 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4875 (with-output-to-temp-buffer "*Help*"
4876 (princ help))
4877 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4878 (setq buffer-read-only nil)
4879 (let ((org-startup-truncated t)
4880 (org-startup-folded nil)
4881 (org-startup-align-all-tables nil))
4882 (org-mode)
4883 (org-overview))
4884 (setq buffer-read-only t)
4885 (if (and (boundp 'org-goto-start-pos)
4886 (integer-or-marker-p org-goto-start-pos))
4887 (let ((org-show-hierarchy-above t)
4888 (org-show-siblings t)
4889 (org-show-following-heading t))
4890 (goto-char org-goto-start-pos)
4891 (and (org-invisible-p) (org-show-context)))
4892 (goto-char (point-min)))
4893 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4894 (message "Select location and press RET")
4895 (use-local-map org-goto-map)
4896 (recursive-edit)
4898 (kill-buffer "*org-goto*")
4899 (cons org-goto-selected-point org-goto-exit-command)))
4901 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4902 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4903 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4904 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4906 (defun org-goto-local-search-headings (string bound noerror)
4907 "Search and make sure that any matches are in headlines."
4908 (catch 'return
4909 (while (if isearch-forward
4910 (search-forward string bound noerror)
4911 (search-backward string bound noerror))
4912 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4913 (and (member :headline context)
4914 (not (member :tags context))))
4915 (throw 'return (point))))))
4917 (defun org-goto-local-auto-isearch ()
4918 "Start isearch."
4919 (interactive)
4920 (goto-char (point-min))
4921 (let ((keys (this-command-keys)))
4922 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4923 (isearch-mode t)
4924 (isearch-process-search-char (string-to-char keys)))))
4926 (defun org-goto-ret (&optional arg)
4927 "Finish `org-goto' by going to the new location."
4928 (interactive "P")
4929 (setq org-goto-selected-point (point)
4930 org-goto-exit-command 'return)
4931 (throw 'exit nil))
4933 (defun org-goto-left ()
4934 "Finish `org-goto' by going to the new location."
4935 (interactive)
4936 (if (org-on-heading-p)
4937 (progn
4938 (beginning-of-line 1)
4939 (setq org-goto-selected-point (point)
4940 org-goto-exit-command 'left)
4941 (throw 'exit nil))
4942 (error "Not on a heading")))
4944 (defun org-goto-right ()
4945 "Finish `org-goto' by going to the new location."
4946 (interactive)
4947 (if (org-on-heading-p)
4948 (progn
4949 (setq org-goto-selected-point (point)
4950 org-goto-exit-command 'right)
4951 (throw 'exit nil))
4952 (error "Not on a heading")))
4954 (defun org-goto-quit ()
4955 "Finish `org-goto' without cursor motion."
4956 (interactive)
4957 (setq org-goto-selected-point nil)
4958 (setq org-goto-exit-command 'quit)
4959 (throw 'exit nil))
4961 ;;; Indirect buffer display of subtrees
4963 (defvar org-indirect-dedicated-frame nil
4964 "This is the frame being used for indirect tree display.")
4965 (defvar org-last-indirect-buffer nil)
4967 (defun org-tree-to-indirect-buffer (&optional arg)
4968 "Create indirect buffer and narrow it to current subtree.
4969 With numerical prefix ARG, go up to this level and then take that tree.
4970 If ARG is negative, go up that many levels.
4971 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4972 indirect buffer previously made with this command, to avoid proliferation of
4973 indirect buffers. However, when you call the command with a `C-u' prefix, or
4974 when `org-indirect-buffer-display' is `new-frame', the last buffer
4975 is kept so that you can work with several indirect buffers at the same time.
4976 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4977 requests that a new frame be made for the new buffer, so that the dedicated
4978 frame is not changed."
4979 (interactive "P")
4980 (let ((cbuf (current-buffer))
4981 (cwin (selected-window))
4982 (pos (point))
4983 beg end level heading ibuf)
4984 (save-excursion
4985 (org-back-to-heading t)
4986 (when (numberp arg)
4987 (setq level (org-outline-level))
4988 (if (< arg 0) (setq arg (+ level arg)))
4989 (while (> (setq level (org-outline-level)) arg)
4990 (outline-up-heading 1 t)))
4991 (setq beg (point)
4992 heading (org-get-heading))
4993 (org-end-of-subtree t) (setq end (point)))
4994 (if (and (buffer-live-p org-last-indirect-buffer)
4995 (not (eq org-indirect-buffer-display 'new-frame))
4996 (not arg))
4997 (kill-buffer org-last-indirect-buffer))
4998 (setq ibuf (org-get-indirect-buffer cbuf)
4999 org-last-indirect-buffer ibuf)
5000 (cond
5001 ((or (eq org-indirect-buffer-display 'new-frame)
5002 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5003 (select-frame (make-frame))
5004 (delete-other-windows)
5005 (switch-to-buffer ibuf)
5006 (org-set-frame-title heading))
5007 ((eq org-indirect-buffer-display 'dedicated-frame)
5008 (raise-frame
5009 (select-frame (or (and org-indirect-dedicated-frame
5010 (frame-live-p org-indirect-dedicated-frame)
5011 org-indirect-dedicated-frame)
5012 (setq org-indirect-dedicated-frame (make-frame)))))
5013 (delete-other-windows)
5014 (switch-to-buffer ibuf)
5015 (org-set-frame-title (concat "Indirect: " heading)))
5016 ((eq org-indirect-buffer-display 'current-window)
5017 (switch-to-buffer ibuf))
5018 ((eq org-indirect-buffer-display 'other-window)
5019 (pop-to-buffer ibuf))
5020 (t (error "Invalid value.")))
5021 (if (featurep 'xemacs)
5022 (save-excursion (org-mode) (turn-on-font-lock)))
5023 (narrow-to-region beg end)
5024 (show-all)
5025 (goto-char pos)
5026 (and (window-live-p cwin) (select-window cwin))))
5028 (defun org-get-indirect-buffer (&optional buffer)
5029 (setq buffer (or buffer (current-buffer)))
5030 (let ((n 1) (base (buffer-name buffer)) bname)
5031 (while (buffer-live-p
5032 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5033 (setq n (1+ n)))
5034 (condition-case nil
5035 (make-indirect-buffer buffer bname 'clone)
5036 (error (make-indirect-buffer buffer bname)))))
5038 (defun org-set-frame-title (title)
5039 "Set the title of the current frame to the string TITLE."
5040 ;; FIXME: how to name a single frame in XEmacs???
5041 (unless (featurep 'xemacs)
5042 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5044 ;;;; Structure editing
5046 ;;; Inserting headlines
5048 (defun org-previous-line-empty-p ()
5049 (save-excursion
5050 (and (not (bobp))
5051 (or (beginning-of-line 0) t)
5052 (save-match-data
5053 (looking-at "[ \t]*$")))))
5055 (defun org-insert-heading (&optional force-heading)
5056 "Insert a new heading or item with same depth at point.
5057 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5058 If point is at the beginning of a headline, insert a sibling before the
5059 current headline. If point is not at the beginning, do not split the line,
5060 but create the new headline after the current line."
5061 (interactive "P")
5062 (if (= (buffer-size) 0)
5063 (insert "\n* ")
5064 (when (or force-heading (not (org-insert-item)))
5065 (let* ((empty-line-p nil)
5066 (head (save-excursion
5067 (condition-case nil
5068 (progn
5069 (org-back-to-heading)
5070 (setq empty-line-p (org-previous-line-empty-p))
5071 (match-string 0))
5072 (error "*"))))
5073 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5074 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5075 pos hide-previous previous-pos)
5076 (cond
5077 ((and (org-on-heading-p) (bolp)
5078 (or (bobp)
5079 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5080 ;; insert before the current line
5081 (open-line (if blank 2 1)))
5082 ((and (bolp)
5083 (or (bobp)
5084 (save-excursion
5085 (backward-char 1) (not (org-invisible-p)))))
5086 ;; insert right here
5087 nil)
5089 ;; somewhere in the line
5090 (save-excursion
5091 (setq previous-pos (point-at-bol))
5092 (end-of-line)
5093 (setq hide-previous (org-invisible-p)))
5094 (and org-insert-heading-respect-content (org-show-subtree))
5095 (let ((split
5096 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5097 (save-excursion
5098 (let ((p (point)))
5099 (goto-char (point-at-bol))
5100 (and (looking-at org-complex-heading-regexp)
5101 (> p (match-beginning 4)))))))
5102 tags pos)
5103 (cond
5104 (org-insert-heading-respect-content
5105 (org-end-of-subtree nil t)
5106 (or (bolp) (newline))
5107 (or (org-previous-line-empty-p)
5108 (and blank (newline)))
5109 (open-line 1))
5110 ((org-on-heading-p)
5111 (when hide-previous
5112 (show-children)
5113 (org-show-entry))
5114 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5115 (setq tags (and (match-end 2) (match-string 2)))
5116 (and (match-end 1)
5117 (delete-region (match-beginning 1) (match-end 1)))
5118 (setq pos (point-at-bol))
5119 (or split (end-of-line 1))
5120 (delete-horizontal-space)
5121 (newline (if blank 2 1))
5122 (when tags
5123 (save-excursion
5124 (goto-char pos)
5125 (end-of-line 1)
5126 (insert " " tags)
5127 (org-set-tags nil 'align))))
5129 (or split (end-of-line 1))
5130 (newline (if blank 2 1)))))))
5131 (insert head) (just-one-space)
5132 (setq pos (point))
5133 (end-of-line 1)
5134 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5135 (when (and org-insert-heading-respect-content hide-previous)
5136 (save-excursion
5137 (goto-char previous-pos)
5138 (hide-subtree)))
5139 (run-hooks 'org-insert-heading-hook)))))
5141 (defun org-get-heading (&optional no-tags)
5142 "Return the heading of the current entry, without the stars."
5143 (save-excursion
5144 (org-back-to-heading t)
5145 (if (looking-at
5146 (if no-tags
5147 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5148 "\\*+[ \t]+\\([^\r\n]*\\)"))
5149 (match-string 1) "")))
5151 (defun org-heading-components ()
5152 "Return the components of the current heading.
5153 This is a list with the following elements:
5154 - the level as an integer
5155 - the reduced level, different if `org-odd-levels-only' is set.
5156 - the TODO keyword, or nil
5157 - the priority character, like ?A, or nil if no priority is given
5158 - the headline text itself, or the tags string if no headline text
5159 - the tags string, or nil."
5160 (save-excursion
5161 (org-back-to-heading t)
5162 (if (looking-at org-complex-heading-regexp)
5163 (list (length (match-string 1))
5164 (org-reduced-level (length (match-string 1)))
5165 (org-match-string-no-properties 2)
5166 (and (match-end 3) (aref (match-string 3) 2))
5167 (org-match-string-no-properties 4)
5168 (org-match-string-no-properties 5)))))
5170 (defun org-insert-heading-after-current ()
5171 "Insert a new heading with same level as current, after current subtree."
5172 (interactive)
5173 (org-back-to-heading)
5174 (org-insert-heading)
5175 (org-move-subtree-down)
5176 (end-of-line 1))
5178 (defun org-insert-heading-respect-content ()
5179 (interactive)
5180 (let ((org-insert-heading-respect-content t))
5181 (org-insert-heading t)))
5183 (defun org-insert-todo-heading-respect-content (&optional force-state)
5184 (interactive "P")
5185 (let ((org-insert-heading-respect-content t))
5186 (org-insert-todo-heading force-state t)))
5188 (defun org-insert-todo-heading (arg &optional force-heading)
5189 "Insert a new heading with the same level and TODO state as current heading.
5190 If the heading has no TODO state, or if the state is DONE, use the first
5191 state (TODO by default). Also with prefix arg, force first state."
5192 (interactive "P")
5193 (when (or force-heading (not (org-insert-item 'checkbox)))
5194 (org-insert-heading force-heading)
5195 (save-excursion
5196 (org-back-to-heading)
5197 (outline-previous-heading)
5198 (looking-at org-todo-line-regexp))
5199 (let*
5200 ((new-mark-x
5201 (if (or arg
5202 (not (match-beginning 2))
5203 (member (match-string 2) org-done-keywords))
5204 (car org-todo-keywords-1)
5205 (match-string 2)))
5206 (new-mark
5208 (run-hook-with-args-until-success
5209 'org-todo-get-default-hook new-mark-x nil)
5210 new-mark-x)))
5211 (insert new-mark " "))
5212 (when org-provide-todo-statistics
5213 (org-update-parent-todo-statistics))))
5215 (defun org-insert-subheading (arg)
5216 "Insert a new subheading and demote it.
5217 Works for outline headings and for plain lists alike."
5218 (interactive "P")
5219 (org-insert-heading arg)
5220 (cond
5221 ((org-on-heading-p) (org-do-demote))
5222 ((org-at-item-p) (org-indent-item 1))))
5224 (defun org-insert-todo-subheading (arg)
5225 "Insert a new subheading with TODO keyword or checkbox and demote it.
5226 Works for outline headings and for plain lists alike."
5227 (interactive "P")
5228 (org-insert-todo-heading arg)
5229 (cond
5230 ((org-on-heading-p) (org-do-demote))
5231 ((org-at-item-p) (org-indent-item 1))))
5233 ;;; Promotion and Demotion
5235 (defun org-promote-subtree ()
5236 "Promote the entire subtree.
5237 See also `org-promote'."
5238 (interactive)
5239 (save-excursion
5240 (org-map-tree 'org-promote))
5241 (org-fix-position-after-promote))
5243 (defun org-demote-subtree ()
5244 "Demote the entire subtree. See `org-demote'.
5245 See also `org-promote'."
5246 (interactive)
5247 (save-excursion
5248 (org-map-tree 'org-demote))
5249 (org-fix-position-after-promote))
5252 (defun org-do-promote ()
5253 "Promote the current heading higher up the tree.
5254 If the region is active in `transient-mark-mode', promote all headings
5255 in the region."
5256 (interactive)
5257 (save-excursion
5258 (if (org-region-active-p)
5259 (org-map-region 'org-promote (region-beginning) (region-end))
5260 (org-promote)))
5261 (org-fix-position-after-promote))
5263 (defun org-do-demote ()
5264 "Demote the current heading lower down the tree.
5265 If the region is active in `transient-mark-mode', demote all headings
5266 in the region."
5267 (interactive)
5268 (save-excursion
5269 (if (org-region-active-p)
5270 (org-map-region 'org-demote (region-beginning) (region-end))
5271 (org-demote)))
5272 (org-fix-position-after-promote))
5274 (defun org-fix-position-after-promote ()
5275 "Make sure that after pro/demotion cursor position is right."
5276 (let ((pos (point)))
5277 (when (save-excursion
5278 (beginning-of-line 1)
5279 (looking-at org-todo-line-regexp)
5280 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5281 (cond ((eobp) (insert " "))
5282 ((eolp) (insert " "))
5283 ((equal (char-after) ?\ ) (forward-char 1))))))
5285 (defun org-reduced-level (l)
5286 "Compute the effective level of a heading.
5287 This takes into account the setting of `org-odd-levels-only'."
5288 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5290 (defun org-get-valid-level (level &optional change)
5291 "Rectify a level change under the influence of `org-odd-levels-only'
5292 LEVEL is a current level, CHANGE is by how much the level should be
5293 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5294 even level numbers will become the next higher odd number."
5295 (if org-odd-levels-only
5296 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5297 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5298 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5299 (max 1 (+ level change))))
5301 (if (boundp 'define-obsolete-function-alias)
5302 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5303 (define-obsolete-function-alias 'org-get-legal-level
5304 'org-get-valid-level)
5305 (define-obsolete-function-alias 'org-get-legal-level
5306 'org-get-valid-level "23.1")))
5308 (defun org-promote ()
5309 "Promote the current heading higher up the tree.
5310 If the region is active in `transient-mark-mode', promote all headings
5311 in the region."
5312 (org-back-to-heading t)
5313 (let* ((level (save-match-data (funcall outline-level)))
5314 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5315 (diff (abs (- level (length up-head) -1))))
5316 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5317 (replace-match up-head nil t)
5318 ;; Fixup tag positioning
5319 (and org-auto-align-tags (org-set-tags nil t))
5320 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5322 (defun org-demote ()
5323 "Demote the current heading lower down the tree.
5324 If the region is active in `transient-mark-mode', demote all headings
5325 in the region."
5326 (org-back-to-heading t)
5327 (let* ((level (save-match-data (funcall outline-level)))
5328 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5329 (diff (abs (- level (length down-head) -1))))
5330 (replace-match down-head nil t)
5331 ;; Fixup tag positioning
5332 (and org-auto-align-tags (org-set-tags nil t))
5333 (if org-adapt-indentation (org-fixup-indentation diff))))
5335 (defun org-map-tree (fun)
5336 "Call FUN for every heading underneath the current one."
5337 (org-back-to-heading)
5338 (let ((level (funcall outline-level)))
5339 (save-excursion
5340 (funcall fun)
5341 (while (and (progn
5342 (outline-next-heading)
5343 (> (funcall outline-level) level))
5344 (not (eobp)))
5345 (funcall fun)))))
5347 (defun org-map-region (fun beg end)
5348 "Call FUN for every heading between BEG and END."
5349 (let ((org-ignore-region t))
5350 (save-excursion
5351 (setq end (copy-marker end))
5352 (goto-char beg)
5353 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5354 (< (point) end))
5355 (funcall fun))
5356 (while (and (progn
5357 (outline-next-heading)
5358 (< (point) end))
5359 (not (eobp)))
5360 (funcall fun)))))
5362 (defun org-fixup-indentation (diff)
5363 "Change the indentation in the current entry by DIFF
5364 However, if any line in the current entry has no indentation, or if it
5365 would end up with no indentation after the change, nothing at all is done."
5366 (save-excursion
5367 (let ((end (save-excursion (outline-next-heading)
5368 (point-marker)))
5369 (prohibit (if (> diff 0)
5370 "^\\S-"
5371 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5372 col)
5373 (unless (save-excursion (end-of-line 1)
5374 (re-search-forward prohibit end t))
5375 (while (and (< (point) end)
5376 (re-search-forward "^[ \t]+" end t))
5377 (goto-char (match-end 0))
5378 (setq col (current-column))
5379 (if (< diff 0) (replace-match ""))
5380 (org-indent-to-column (+ diff col))))
5381 (move-marker end nil))))
5383 (defun org-convert-to-odd-levels ()
5384 "Convert an org-mode file with all levels allowed to one with odd levels.
5385 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5386 level 5 etc."
5387 (interactive)
5388 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5389 (let ((org-odd-levels-only nil) n)
5390 (save-excursion
5391 (goto-char (point-min))
5392 (while (re-search-forward "^\\*\\*+ " nil t)
5393 (setq n (- (length (match-string 0)) 2))
5394 (while (>= (setq n (1- n)) 0)
5395 (org-demote))
5396 (end-of-line 1))))))
5399 (defun org-convert-to-oddeven-levels ()
5400 "Convert an org-mode file with only odd levels to one with odd and even levels.
5401 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5402 section with an even level, conversion would destroy the structure of the file. An error
5403 is signaled in this case."
5404 (interactive)
5405 (goto-char (point-min))
5406 ;; First check if there are no even levels
5407 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5408 (org-show-context t)
5409 (error "Not all levels are odd in this file. Conversion not possible."))
5410 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5411 (let ((org-odd-levels-only nil) n)
5412 (save-excursion
5413 (goto-char (point-min))
5414 (while (re-search-forward "^\\*\\*+ " nil t)
5415 (setq n (/ (1- (length (match-string 0))) 2))
5416 (while (>= (setq n (1- n)) 0)
5417 (org-promote))
5418 (end-of-line 1))))))
5420 (defun org-tr-level (n)
5421 "Make N odd if required."
5422 (if org-odd-levels-only (1+ (/ n 2)) n))
5424 ;;; Vertical tree motion, cutting and pasting of subtrees
5426 (defun org-move-subtree-up (&optional arg)
5427 "Move the current subtree up past ARG headlines of the same level."
5428 (interactive "p")
5429 (org-move-subtree-down (- (prefix-numeric-value arg))))
5431 (defun org-move-subtree-down (&optional arg)
5432 "Move the current subtree down past ARG headlines of the same level."
5433 (interactive "p")
5434 (setq arg (prefix-numeric-value arg))
5435 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5436 'outline-get-last-sibling))
5437 (ins-point (make-marker))
5438 (cnt (abs arg))
5439 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5440 ;; Select the tree
5441 (org-back-to-heading)
5442 (setq beg0 (point))
5443 (save-excursion
5444 (setq ne-beg (org-back-over-empty-lines))
5445 (setq beg (point)))
5446 (save-match-data
5447 (save-excursion (outline-end-of-heading)
5448 (setq folded (org-invisible-p)))
5449 (outline-end-of-subtree))
5450 (outline-next-heading)
5451 (setq ne-end (org-back-over-empty-lines))
5452 (setq end (point))
5453 (goto-char beg0)
5454 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5455 ;; include less whitespace
5456 (save-excursion
5457 (goto-char beg)
5458 (forward-line (- ne-beg ne-end))
5459 (setq beg (point))))
5460 ;; Find insertion point, with error handling
5461 (while (> cnt 0)
5462 (or (and (funcall movfunc) (looking-at outline-regexp))
5463 (progn (goto-char beg0)
5464 (error "Cannot move past superior level or buffer limit")))
5465 (setq cnt (1- cnt)))
5466 (if (> arg 0)
5467 ;; Moving forward - still need to move over subtree
5468 (progn (org-end-of-subtree t t)
5469 (save-excursion
5470 (org-back-over-empty-lines)
5471 (or (bolp) (newline)))))
5472 (setq ne-ins (org-back-over-empty-lines))
5473 (move-marker ins-point (point))
5474 (setq txt (buffer-substring beg end))
5475 (org-save-markers-in-region beg end)
5476 (delete-region beg end)
5477 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5478 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5479 (let ((bbb (point)))
5480 (insert-before-markers txt)
5481 (org-reinstall-markers-in-region bbb)
5482 (move-marker ins-point bbb))
5483 (or (bolp) (insert "\n"))
5484 (setq ins-end (point))
5485 (goto-char ins-point)
5486 (org-skip-whitespace)
5487 (when (and (< arg 0)
5488 (org-first-sibling-p)
5489 (> ne-ins ne-beg))
5490 ;; Move whitespace back to beginning
5491 (save-excursion
5492 (goto-char ins-end)
5493 (let ((kill-whole-line t))
5494 (kill-line (- ne-ins ne-beg)) (point)))
5495 (insert (make-string (- ne-ins ne-beg) ?\n)))
5496 (move-marker ins-point nil)
5497 (org-compact-display-after-subtree-move)
5498 (org-show-empty-lines-in-parent)
5499 (unless folded
5500 (org-show-entry)
5501 (show-children)
5502 (org-cycle-hide-drawers 'children))))
5504 (defvar org-subtree-clip ""
5505 "Clipboard for cut and paste of subtrees.
5506 This is actually only a copy of the kill, because we use the normal kill
5507 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5509 (defvar org-subtree-clip-folded nil
5510 "Was the last copied subtree folded?
5511 This is used to fold the tree back after pasting.")
5513 (defun org-cut-subtree (&optional n)
5514 "Cut the current subtree into the clipboard.
5515 With prefix arg N, cut this many sequential subtrees.
5516 This is a short-hand for marking the subtree and then cutting it."
5517 (interactive "p")
5518 (org-copy-subtree n 'cut))
5520 (defun org-copy-subtree (&optional n cut force-store-markers)
5521 "Cut the current subtree into the clipboard.
5522 With prefix arg N, cut this many sequential subtrees.
5523 This is a short-hand for marking the subtree and then copying it.
5524 If CUT is non-nil, actually cut the subtree.
5525 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5526 of some markers in the region, even if CUT is non-nil. This is
5527 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5528 (interactive "p")
5529 (let (beg end folded (beg0 (point)))
5530 (if (interactive-p)
5531 (org-back-to-heading nil) ; take what looks like a subtree
5532 (org-back-to-heading t)) ; take what is really there
5533 (org-back-over-empty-lines)
5534 (setq beg (point))
5535 (skip-chars-forward " \t\r\n")
5536 (save-match-data
5537 (save-excursion (outline-end-of-heading)
5538 (setq folded (org-invisible-p)))
5539 (condition-case nil
5540 (outline-forward-same-level (1- n))
5541 (error nil))
5542 (org-end-of-subtree t t))
5543 (org-back-over-empty-lines)
5544 (setq end (point))
5545 (goto-char beg0)
5546 (when (> end beg)
5547 (setq org-subtree-clip-folded folded)
5548 (when (or cut force-store-markers)
5549 (org-save-markers-in-region beg end))
5550 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5551 (setq org-subtree-clip (current-kill 0))
5552 (message "%s: Subtree(s) with %d characters"
5553 (if cut "Cut" "Copied")
5554 (length org-subtree-clip)))))
5556 (defun org-paste-subtree (&optional level tree for-yank)
5557 "Paste the clipboard as a subtree, with modification of headline level.
5558 The entire subtree is promoted or demoted in order to match a new headline
5559 level.
5561 If the cursor is at the beginning of a headline, the same level as
5562 that headline is used to paste the tree
5564 If not, the new level is derived from the *visible* headings
5565 before and after the insertion point, and taken to be the inferior headline
5566 level of the two. So if the previous visible heading is level 3 and the
5567 next is level 4 (or vice versa), level 4 will be used for insertion.
5568 This makes sure that the subtree remains an independent subtree and does
5569 not swallow low level entries.
5571 You can also force a different level, either by using a numeric prefix
5572 argument, or by inserting the heading marker by hand. For example, if the
5573 cursor is after \"*****\", then the tree will be shifted to level 5.
5575 If optional TREE is given, use this text instead of the kill ring.
5577 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5578 move back over whitespace before inserting, and move point to the end of
5579 the inserted text when done."
5580 (interactive "P")
5581 (unless (org-kill-is-subtree-p tree)
5582 (error "%s"
5583 (substitute-command-keys
5584 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5585 (let* ((visp (not (org-invisible-p)))
5586 (txt (or tree (and kill-ring (current-kill 0))))
5587 (^re (concat "^\\(" outline-regexp "\\)"))
5588 (re (concat "\\(" outline-regexp "\\)"))
5589 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5591 (old-level (if (string-match ^re txt)
5592 (- (match-end 0) (match-beginning 0) 1)
5593 -1))
5594 (force-level (cond (level (prefix-numeric-value level))
5595 ((and (looking-at "[ \t]*$")
5596 (string-match
5597 ^re_ (buffer-substring
5598 (point-at-bol) (point))))
5599 (- (match-end 1) (match-beginning 1)))
5600 ((and (bolp)
5601 (looking-at org-outline-regexp))
5602 (- (match-end 0) (point) 1))
5603 (t nil)))
5604 (previous-level (save-excursion
5605 (condition-case nil
5606 (progn
5607 (outline-previous-visible-heading 1)
5608 (if (looking-at re)
5609 (- (match-end 0) (match-beginning 0) 1)
5611 (error 1))))
5612 (next-level (save-excursion
5613 (condition-case nil
5614 (progn
5615 (or (looking-at outline-regexp)
5616 (outline-next-visible-heading 1))
5617 (if (looking-at re)
5618 (- (match-end 0) (match-beginning 0) 1)
5620 (error 1))))
5621 (new-level (or force-level (max previous-level next-level)))
5622 (shift (if (or (= old-level -1)
5623 (= new-level -1)
5624 (= old-level new-level))
5626 (- new-level old-level)))
5627 (delta (if (> shift 0) -1 1))
5628 (func (if (> shift 0) 'org-demote 'org-promote))
5629 (org-odd-levels-only nil)
5630 beg end newend)
5631 ;; Remove the forced level indicator
5632 (if force-level
5633 (delete-region (point-at-bol) (point)))
5634 ;; Paste
5635 (beginning-of-line 1)
5636 (unless for-yank (org-back-over-empty-lines))
5637 (setq beg (point))
5638 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5639 (insert-before-markers txt)
5640 (unless (string-match "\n\\'" txt) (insert "\n"))
5641 (setq newend (point))
5642 (org-reinstall-markers-in-region beg)
5643 (setq end (point))
5644 (goto-char beg)
5645 (skip-chars-forward " \t\n\r")
5646 (setq beg (point))
5647 (if (and (org-invisible-p) visp)
5648 (save-excursion (outline-show-heading)))
5649 ;; Shift if necessary
5650 (unless (= shift 0)
5651 (save-restriction
5652 (narrow-to-region beg end)
5653 (while (not (= shift 0))
5654 (org-map-region func (point-min) (point-max))
5655 (setq shift (+ delta shift)))
5656 (goto-char (point-min))
5657 (setq newend (point-max))))
5658 (when (or (interactive-p) for-yank)
5659 (message "Clipboard pasted as level %d subtree" new-level))
5660 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5661 kill-ring
5662 (eq org-subtree-clip (current-kill 0))
5663 org-subtree-clip-folded)
5664 ;; The tree was folded before it was killed/copied
5665 (hide-subtree))
5666 (and for-yank (goto-char newend))))
5668 (defun org-kill-is-subtree-p (&optional txt)
5669 "Check if the current kill is an outline subtree, or a set of trees.
5670 Returns nil if kill does not start with a headline, or if the first
5671 headline level is not the largest headline level in the tree.
5672 So this will actually accept several entries of equal levels as well,
5673 which is OK for `org-paste-subtree'.
5674 If optional TXT is given, check this string instead of the current kill."
5675 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5676 (start-level (and kill
5677 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5678 org-outline-regexp "\\)")
5679 kill)
5680 (- (match-end 2) (match-beginning 2) 1)))
5681 (re (concat "^" org-outline-regexp))
5682 (start (1+ (or (match-beginning 2) -1))))
5683 (if (not start-level)
5684 (progn
5685 nil) ;; does not even start with a heading
5686 (catch 'exit
5687 (while (setq start (string-match re kill (1+ start)))
5688 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5689 (throw 'exit nil)))
5690 t))))
5692 (defvar org-markers-to-move nil
5693 "Markers that should be moved with a cut-and-paste operation.
5694 Those markers are stored together with their positions relative to
5695 the start of the region.")
5697 (defun org-save-markers-in-region (beg end)
5698 "Check markers in region.
5699 If these markers are between BEG and END, record their position relative
5700 to BEG, so that after moving the block of text, we can put the markers back
5701 into place.
5702 This function gets called just before an entry or tree gets cut from the
5703 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5704 called immediately, to move the markers with the entries."
5705 (setq org-markers-to-move nil)
5706 (when (featurep 'org-clock)
5707 (org-clock-save-markers-for-cut-and-paste beg end))
5708 (when (featurep 'org-agenda)
5709 (org-agenda-save-markers-for-cut-and-paste beg end)))
5711 (defun org-check-and-save-marker (marker beg end)
5712 "Check if MARKER is between BEG and END.
5713 If yes, remember the marker and the distance to BEG."
5714 (when (and (marker-buffer marker)
5715 (equal (marker-buffer marker) (current-buffer)))
5716 (if (and (>= marker beg) (< marker end))
5717 (push (cons marker (- marker beg)) org-markers-to-move))))
5719 (defun org-reinstall-markers-in-region (beg)
5720 "Move all remembered markers to their position relative to BEG."
5721 (mapc (lambda (x)
5722 (move-marker (car x) (+ beg (cdr x))))
5723 org-markers-to-move)
5724 (setq org-markers-to-move nil))
5726 (defun org-narrow-to-subtree ()
5727 "Narrow buffer to the current subtree."
5728 (interactive)
5729 (save-excursion
5730 (save-match-data
5731 (narrow-to-region
5732 (progn (org-back-to-heading) (point))
5733 (progn (org-end-of-subtree t) (point))))))
5736 ;;; Outline Sorting
5738 (defun org-sort (with-case)
5739 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5740 Optional argument WITH-CASE means sort case-sensitively.
5741 With a double prefix argument, also remove duplicate entries."
5742 (interactive "P")
5743 (if (org-at-table-p)
5744 (org-call-with-arg 'org-table-sort-lines with-case)
5745 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5747 (defun org-sort-remove-invisible (s)
5748 (remove-text-properties 0 (length s) org-rm-props s)
5749 (while (string-match org-bracket-link-regexp s)
5750 (setq s (replace-match (if (match-end 2)
5751 (match-string 3 s)
5752 (match-string 1 s)) t t s)))
5755 (defvar org-priority-regexp) ; defined later in the file
5757 (defun org-sort-entries-or-items
5758 (&optional with-case sorting-type getkey-func compare-func property)
5759 "Sort entries on a certain level of an outline tree.
5760 If there is an active region, the entries in the region are sorted.
5761 Else, if the cursor is before the first entry, sort the top-level items.
5762 Else, the children of the entry at point are sorted.
5764 Sorting can be alphabetically, numerically, and by date/time as given by
5765 the first time stamp in the entry. The command prompts for the sorting
5766 type unless it has been given to the function through the SORTING-TYPE
5767 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5768 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5769 called with point at the beginning of the record. It must return either
5770 a string or a number that should serve as the sorting key for that record.
5772 Comparing entries ignores case by default. However, with an optional argument
5773 WITH-CASE, the sorting considers case as well."
5774 (interactive "P")
5775 (let ((case-func (if with-case 'identity 'downcase))
5776 start beg end stars re re2
5777 txt what tmp plain-list-p)
5778 ;; Find beginning and end of region to sort
5779 (cond
5780 ((org-region-active-p)
5781 ;; we will sort the region
5782 (setq end (region-end)
5783 what "region")
5784 (goto-char (region-beginning))
5785 (if (not (org-on-heading-p)) (outline-next-heading))
5786 (setq start (point)))
5787 ((org-at-item-p)
5788 ;; we will sort this plain list
5789 (org-beginning-of-item-list) (setq start (point))
5790 (org-end-of-item-list) (setq end (point))
5791 (goto-char start)
5792 (setq plain-list-p t
5793 what "plain list"))
5794 ((or (org-on-heading-p)
5795 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5796 ;; we will sort the children of the current headline
5797 (org-back-to-heading)
5798 (setq start (point)
5799 end (progn (org-end-of-subtree t t)
5800 (org-back-over-empty-lines)
5801 (point))
5802 what "children")
5803 (goto-char start)
5804 (show-subtree)
5805 (outline-next-heading))
5807 ;; we will sort the top-level entries in this file
5808 (goto-char (point-min))
5809 (or (org-on-heading-p) (outline-next-heading))
5810 (setq start (point) end (point-max) what "top-level")
5811 (goto-char start)
5812 (show-all)))
5814 (setq beg (point))
5815 (if (>= beg end) (error "Nothing to sort"))
5817 (unless plain-list-p
5818 (looking-at "\\(\\*+\\)")
5819 (setq stars (match-string 1)
5820 re (concat "^" (regexp-quote stars) " +")
5821 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5822 txt (buffer-substring beg end))
5823 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5824 (if (and (not (equal stars "*")) (string-match re2 txt))
5825 (error "Region to sort contains a level above the first entry")))
5827 (unless sorting-type
5828 (message
5829 (if plain-list-p
5830 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5831 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5832 what)
5833 (setq sorting-type (read-char-exclusive))
5835 (and (= (downcase sorting-type) ?f)
5836 (setq getkey-func
5837 (org-ido-completing-read "Sort using function: "
5838 obarray 'fboundp t nil nil))
5839 (setq getkey-func (intern getkey-func)))
5841 (and (= (downcase sorting-type) ?r)
5842 (setq property
5843 (org-ido-completing-read "Property: "
5844 (mapcar 'list (org-buffer-property-keys t))
5845 nil t))))
5847 (message "Sorting entries...")
5849 (save-restriction
5850 (narrow-to-region start end)
5852 (let ((dcst (downcase sorting-type))
5853 (now (current-time)))
5854 (sort-subr
5855 (/= dcst sorting-type)
5856 ;; This function moves to the beginning character of the "record" to
5857 ;; be sorted.
5858 (if plain-list-p
5859 (lambda nil
5860 (if (org-at-item-p) t (goto-char (point-max))))
5861 (lambda nil
5862 (if (re-search-forward re nil t)
5863 (goto-char (match-beginning 0))
5864 (goto-char (point-max)))))
5865 ;; This function moves to the last character of the "record" being
5866 ;; sorted.
5867 (if plain-list-p
5868 'org-end-of-item
5869 (lambda nil
5870 (save-match-data
5871 (condition-case nil
5872 (outline-forward-same-level 1)
5873 (error
5874 (goto-char (point-max)))))))
5876 ;; This function returns the value that gets sorted against.
5877 (if plain-list-p
5878 (lambda nil
5879 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5880 (cond
5881 ((= dcst ?n)
5882 (string-to-number (buffer-substring (match-end 0)
5883 (point-at-eol))))
5884 ((= dcst ?a)
5885 (buffer-substring (match-end 0) (point-at-eol)))
5886 ((= dcst ?t)
5887 (if (re-search-forward org-ts-regexp
5888 (point-at-eol) t)
5889 (org-time-string-to-time (match-string 0))
5890 now))
5891 ((= dcst ?f)
5892 (if getkey-func
5893 (progn
5894 (setq tmp (funcall getkey-func))
5895 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5896 tmp)
5897 (error "Invalid key function `%s'" getkey-func)))
5898 (t (error "Invalid sorting type `%c'" sorting-type)))))
5899 (lambda nil
5900 (cond
5901 ((= dcst ?n)
5902 (if (looking-at org-complex-heading-regexp)
5903 (string-to-number (match-string 4))
5904 nil))
5905 ((= dcst ?a)
5906 (if (looking-at org-complex-heading-regexp)
5907 (funcall case-func (match-string 4))
5908 nil))
5909 ((= dcst ?t)
5910 (if (re-search-forward org-ts-regexp
5911 (save-excursion
5912 (forward-line 2)
5913 (point)) t)
5914 (org-time-string-to-time (match-string 0))
5915 now))
5916 ((= dcst ?p)
5917 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5918 (string-to-char (match-string 2))
5919 org-default-priority))
5920 ((= dcst ?r)
5921 (or (org-entry-get nil property) ""))
5922 ((= dcst ?o)
5923 (if (looking-at org-complex-heading-regexp)
5924 (- 9999 (length (member (match-string 2)
5925 org-todo-keywords-1)))))
5926 ((= dcst ?f)
5927 (if getkey-func
5928 (progn
5929 (setq tmp (funcall getkey-func))
5930 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5931 tmp)
5932 (error "Invalid key function `%s'" getkey-func)))
5933 (t (error "Invalid sorting type `%c'" sorting-type)))))
5935 (cond
5936 ((= dcst ?a) 'string<)
5937 ((= dcst ?t) 'time-less-p)
5938 ((= dcst ?f) compare-func)
5939 (t nil)))))
5940 (message "Sorting entries...done")))
5942 (defun org-do-sort (table what &optional with-case sorting-type)
5943 "Sort TABLE of WHAT according to SORTING-TYPE.
5944 The user will be prompted for the SORTING-TYPE if the call to this
5945 function does not specify it. WHAT is only for the prompt, to indicate
5946 what is being sorted. The sorting key will be extracted from
5947 the car of the elements of the table.
5948 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5949 (unless sorting-type
5950 (message
5951 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5952 what)
5953 (setq sorting-type (read-char-exclusive)))
5954 (let ((dcst (downcase sorting-type))
5955 extractfun comparefun)
5956 ;; Define the appropriate functions
5957 (cond
5958 ((= dcst ?n)
5959 (setq extractfun 'string-to-number
5960 comparefun (if (= dcst sorting-type) '< '>)))
5961 ((= dcst ?a)
5962 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5963 (lambda(x) (downcase (org-sort-remove-invisible x))))
5964 comparefun (if (= dcst sorting-type)
5965 'string<
5966 (lambda (a b) (and (not (string< a b))
5967 (not (string= a b)))))))
5968 ((= dcst ?t)
5969 (setq extractfun
5970 (lambda (x)
5971 (if (or (string-match org-ts-regexp x)
5972 (string-match org-ts-regexp-both x))
5973 (time-to-seconds
5974 (org-time-string-to-time (match-string 0 x)))
5976 comparefun (if (= dcst sorting-type) '< '>)))
5977 (t (error "Invalid sorting type `%c'" sorting-type)))
5979 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5980 table)
5981 (lambda (a b) (funcall comparefun (car a) (car b))))))
5983 ;;; Editing source examples
5985 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5986 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5987 (defvar org-edit-src-force-single-line nil)
5988 (defvar org-edit-src-from-org-mode nil)
5989 (defvar org-edit-src-picture nil)
5991 (define-minor-mode org-exit-edit-mode
5992 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5994 (defun org-edit-src-code ()
5995 "Edit the source code example at point.
5996 An indirect buffer is created, and that buffer is then narrowed to the
5997 example at point and switched to the correct language mode. When done,
5998 exit by killing the buffer with \\[org-edit-src-exit]."
5999 (interactive)
6000 (let ((line (org-current-line))
6001 (case-fold-search t)
6002 (msg (substitute-command-keys
6003 "Edit, then exit with C-c ' (C-c and single quote)"))
6004 (info (org-edit-src-find-region-and-lang))
6005 (org-mode-p (eq major-mode 'org-mode))
6006 beg end lang lang-f single lfmt)
6007 (if (not info)
6009 (setq beg (nth 0 info)
6010 end (nth 1 info)
6011 lang (nth 2 info)
6012 single (nth 3 info)
6013 lfmt (nth 4 info)
6014 lang-f (intern (concat lang "-mode")))
6015 (unless (functionp lang-f)
6016 (error "No such language mode: %s" lang-f))
6017 (goto-line line)
6018 (if (get-buffer "*Org Edit Src Example*")
6019 (kill-buffer "*Org Edit Src Example*"))
6020 (switch-to-buffer (make-indirect-buffer (current-buffer)
6021 "*Org Edit Src Example*"))
6022 (narrow-to-region beg end)
6023 (remove-text-properties beg end '(display nil invisible nil
6024 intangible nil))
6025 (let ((org-inhibit-startup t))
6026 (funcall lang-f))
6027 (set (make-local-variable 'org-edit-src-force-single-line) single)
6028 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6029 (when lfmt
6030 (set (make-local-variable 'org-coderef-label-format) lfmt))
6031 (when org-mode-p
6032 (goto-char (point-min))
6033 (while (re-search-forward "^," nil t)
6034 (replace-match "")))
6035 (goto-line line)
6036 (org-exit-edit-mode)
6037 (org-set-local 'header-line-format msg)
6038 (message "%s" msg)
6039 t)))
6041 (defun org-edit-fixed-width-region ()
6042 "Edit the fixed-width ascii drawing at point.
6043 This must be a region where each line starts with a colon followed by
6044 a space character.
6045 An indirect buffer is created, and that buffer is then narrowed to the
6046 example at point and switched to artist-mode. When done,
6047 exit by killing the buffer with \\[org-edit-src-exit]."
6048 (interactive)
6049 (let ((line (org-current-line))
6050 (case-fold-search t)
6051 (msg (substitute-command-keys
6052 "Edit, then exit with C-c ' (C-c and single quote)"))
6053 (org-mode-p (eq major-mode 'org-mode))
6054 beg end)
6055 (beginning-of-line 1)
6056 (if (looking-at "[ \t]*[^:\n \t]")
6058 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6059 (setq beg (point) end beg)
6060 (save-excursion
6061 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6062 (setq beg (point-at-bol 2))
6063 (setq beg (point))))
6064 (save-excursion
6065 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6066 (setq end (1- (match-beginning 0)))
6067 (setq end (point))))
6068 (goto-line line))
6069 (if (get-buffer "*Org Edit Picture*")
6070 (kill-buffer "*Org Edit Picture*"))
6071 (switch-to-buffer (make-indirect-buffer (current-buffer)
6072 "*Org Edit Picture*"))
6073 (narrow-to-region beg end)
6074 (remove-text-properties beg end '(display nil invisible nil
6075 intangible nil))
6076 (when (fboundp 'font-lock-unfontify-region)
6077 (font-lock-unfontify-region (point-min) (point-max)))
6078 (cond
6079 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6080 (fundamental-mode)
6081 (artist-mode 1))
6082 (t (funcall org-edit-fixed-width-region-mode)))
6083 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6084 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6085 (set (make-local-variable 'org-edit-src-picture) t)
6086 (goto-char (point-min))
6087 (while (re-search-forward "^[ \t]*: ?" nil t)
6088 (replace-match ""))
6089 (goto-line line)
6090 (org-exit-edit-mode)
6091 (org-set-local 'header-line-format msg)
6092 (message "%s" msg)
6093 t)))
6096 (defun org-edit-src-find-region-and-lang ()
6097 "Find the region and language for a local edit.
6098 Return a list with beginning and end of the region, a string representing
6099 the language, a switch telling of the content should be in a single line."
6100 (let ((re-list
6101 (append
6102 org-edit-src-region-extra
6104 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6105 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6106 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6107 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6108 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6109 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6110 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6111 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6112 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6113 ("^#\\+html:" "\n" "html" single-line)
6114 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6115 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6116 ("^#\\+latex:" "\n" "latex" single-line)
6117 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6118 ("^#\\+ascii:" "\n" "ascii" single-line)
6120 (pos (point))
6121 re1 re2 single beg end lang lfmt match-re1)
6122 (catch 'exit
6123 (while (setq entry (pop re-list))
6124 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6125 single (nth 3 entry))
6126 (save-excursion
6127 (if (or (looking-at re1)
6128 (re-search-backward re1 nil t))
6129 (progn
6130 (setq match-re1 (match-string 0))
6131 (setq beg (match-end 0)
6132 lang (org-edit-src-get-lang lang)
6133 lfmt (org-edit-src-get-label-format match-re1))
6134 (if (and (re-search-forward re2 nil t)
6135 (>= (match-end 0) pos))
6136 (throw 'exit (list beg (match-beginning 0)
6137 lang single lfmt))))
6138 (if (or (looking-at re2)
6139 (re-search-forward re2 nil t))
6140 (progn
6141 (setq end (match-beginning 0))
6142 (if (and (re-search-backward re1 nil t)
6143 (<= (match-beginning 0) pos))
6144 (progn
6145 (setq lfmt (org-edit-src-get-label-format
6146 (match-string 0)))
6147 (throw 'exit
6148 (list (match-end 0) end
6149 (org-edit-src-get-lang lang)
6150 single lfmt))))))))))))
6152 (defun org-edit-src-get-lang (lang)
6153 "Extract the src language."
6154 (let ((m (match-string 0)))
6155 (cond
6156 ((stringp lang) lang)
6157 ((integerp lang) (match-string lang))
6158 ((and (eq lang 'lang)
6159 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6160 (match-string 1 m))
6161 ((and (eq lang 'style)
6162 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6163 (match-string 1 m))
6164 (t "fundamental"))))
6166 (defun org-edit-src-get-label-format (s)
6167 "Extract the label format."
6168 (save-match-data
6169 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6170 (match-string 1 s))))
6172 (defun org-edit-src-exit ()
6173 "Exit special edit and protect problematic lines."
6174 (interactive)
6175 (unless (buffer-base-buffer (current-buffer))
6176 (error "This is not an indirect buffer, something is wrong..."))
6177 (unless (> (point-min) 1)
6178 (error "This buffer is not narrowed, something is wrong..."))
6179 (goto-char (point-min))
6180 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6181 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6182 (when (org-bound-and-true-p org-edit-src-force-single-line)
6183 (goto-char (point-min))
6184 (while (re-search-forward "\n" nil t)
6185 (replace-match " "))
6186 (goto-char (point-min))
6187 (if (looking-at "\\s-*") (replace-match " "))
6188 (if (re-search-forward "\\s-+\\'" nil t)
6189 (replace-match "")))
6190 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6191 (goto-char (point-min))
6192 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6193 (replace-match ",\\1"))
6194 (when font-lock-mode
6195 (font-lock-unfontify-region (point-min) (point-max)))
6196 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6197 (when (org-bound-and-true-p org-edit-src-picture)
6198 (untabify (point-min) (point-max))
6199 (goto-char (point-min))
6200 (while (re-search-forward "^" nil t)
6201 (replace-match ": "))
6202 (when font-lock-mode
6203 (font-lock-unfontify-region (point-min) (point-max)))
6204 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6205 (kill-buffer (current-buffer))
6206 (and (org-mode-p) (org-restart-font-lock)))
6209 ;;; The orgstruct minor mode
6211 ;; Define a minor mode which can be used in other modes in order to
6212 ;; integrate the org-mode structure editing commands.
6214 ;; This is really a hack, because the org-mode structure commands use
6215 ;; keys which normally belong to the major mode. Here is how it
6216 ;; works: The minor mode defines all the keys necessary to operate the
6217 ;; structure commands, but wraps the commands into a function which
6218 ;; tests if the cursor is currently at a headline or a plain list
6219 ;; item. If that is the case, the structure command is used,
6220 ;; temporarily setting many Org-mode variables like regular
6221 ;; expressions for filling etc. However, when any of those keys is
6222 ;; used at a different location, function uses `key-binding' to look
6223 ;; up if the key has an associated command in another currently active
6224 ;; keymap (minor modes, major mode, global), and executes that
6225 ;; command. There might be problems if any of the keys is otherwise
6226 ;; used as a prefix key.
6228 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6229 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6230 ;; addresses this by checking explicitly for both bindings.
6232 (defvar orgstruct-mode-map (make-sparse-keymap)
6233 "Keymap for the minor `orgstruct-mode'.")
6235 (defvar org-local-vars nil
6236 "List of local variables, for use by `orgstruct-mode'")
6238 ;;;###autoload
6239 (define-minor-mode orgstruct-mode
6240 "Toggle the minor more `orgstruct-mode'.
6241 This mode is for using Org-mode structure commands in other modes.
6242 The following key behave as if Org-mode was active, if the cursor
6243 is on a headline, or on a plain list item (both in the definition
6244 of Org-mode).
6246 M-up Move entry/item up
6247 M-down Move entry/item down
6248 M-left Promote
6249 M-right Demote
6250 M-S-up Move entry/item up
6251 M-S-down Move entry/item down
6252 M-S-left Promote subtree
6253 M-S-right Demote subtree
6254 M-q Fill paragraph and items like in Org-mode
6255 C-c ^ Sort entries
6256 C-c - Cycle list bullet
6257 TAB Cycle item visibility
6258 M-RET Insert new heading/item
6259 S-M-RET Insert new TODO heading / Checkbox item
6260 C-c C-c Set tags / toggle checkbox"
6261 nil " OrgStruct" nil
6262 (org-load-modules-maybe)
6263 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6265 ;;;###autoload
6266 (defun turn-on-orgstruct ()
6267 "Unconditionally turn on `orgstruct-mode'."
6268 (orgstruct-mode 1))
6270 (defun orgstruct++-mode (&optional arg)
6271 "Toggle `orgstruct-mode', the enhanced version of it.
6272 In addition to setting orgstruct-mode, this also exports all indentation and
6273 autofilling variables from org-mode into the buffer. It will also
6274 recognize item context in multiline items.
6275 Note that turning off orgstruct-mode will *not* remove the
6276 indentation/paragraph settings. This can only be done by refreshing the
6277 major mode, for example with \[normal-mode]."
6278 (interactive "P")
6279 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6280 (if (< arg 1)
6281 (orgstruct-mode -1)
6282 (orgstruct-mode 1)
6283 (let (var val)
6284 (mapc
6285 (lambda (x)
6286 (when (string-match
6287 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6288 (symbol-name (car x)))
6289 (setq var (car x) val (nth 1 x))
6290 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6291 org-local-vars)
6292 (org-set-local 'orgstruct-is-++ t))))
6294 (defvar orgstruct-is-++ nil
6295 "Is orgstruct-mode in ++ version in the current-buffer?")
6296 (make-variable-buffer-local 'orgstruct-is-++)
6298 ;;;###autoload
6299 (defun turn-on-orgstruct++ ()
6300 "Unconditionally turn on `orgstruct++-mode'."
6301 (orgstruct++-mode 1))
6303 (defun orgstruct-error ()
6304 "Error when there is no default binding for a structure key."
6305 (interactive)
6306 (error "This key has no function outside structure elements"))
6308 (defun orgstruct-setup ()
6309 "Setup orgstruct keymaps."
6310 (let ((nfunc 0)
6311 (bindings
6312 (list
6313 '([(meta up)] org-metaup)
6314 '([(meta down)] org-metadown)
6315 '([(meta left)] org-metaleft)
6316 '([(meta right)] org-metaright)
6317 '([(meta shift up)] org-shiftmetaup)
6318 '([(meta shift down)] org-shiftmetadown)
6319 '([(meta shift left)] org-shiftmetaleft)
6320 '([(meta shift right)] org-shiftmetaright)
6321 '([(shift up)] org-shiftup)
6322 '([(shift down)] org-shiftdown)
6323 '([(shift left)] org-shiftleft)
6324 '([(shift right)] org-shiftright)
6325 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6326 '("\M-q" fill-paragraph)
6327 '("\C-c^" org-sort)
6328 '("\C-c-" org-cycle-list-bullet)))
6329 elt key fun cmd)
6330 (while (setq elt (pop bindings))
6331 (setq nfunc (1+ nfunc))
6332 (setq key (org-key (car elt))
6333 fun (nth 1 elt)
6334 cmd (orgstruct-make-binding fun nfunc key))
6335 (org-defkey orgstruct-mode-map key cmd))
6337 ;; Special treatment needed for TAB and RET
6338 (org-defkey orgstruct-mode-map [(tab)]
6339 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6340 (org-defkey orgstruct-mode-map "\C-i"
6341 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6343 (org-defkey orgstruct-mode-map "\M-\C-m"
6344 (orgstruct-make-binding 'org-insert-heading 105
6345 "\M-\C-m" [(meta return)]))
6346 (org-defkey orgstruct-mode-map [(meta return)]
6347 (orgstruct-make-binding 'org-insert-heading 106
6348 [(meta return)] "\M-\C-m"))
6350 (org-defkey orgstruct-mode-map [(shift meta return)]
6351 (orgstruct-make-binding 'org-insert-todo-heading 107
6352 [(meta return)] "\M-\C-m"))
6354 (unless org-local-vars
6355 (setq org-local-vars (org-get-local-variables)))
6359 (defun orgstruct-make-binding (fun n &rest keys)
6360 "Create a function for binding in the structure minor mode.
6361 FUN is the command to call inside a table. N is used to create a unique
6362 command name. KEYS are keys that should be checked in for a command
6363 to execute outside of tables."
6364 (eval
6365 (list 'defun
6366 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6367 '(arg)
6368 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6369 "Outside of structure, run the binding of `"
6370 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6371 "'.")
6372 '(interactive "p")
6373 (list 'if
6374 `(org-context-p 'headline 'item
6375 (and orgstruct-is-++
6376 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6377 'item-body))
6378 (list 'org-run-like-in-org-mode (list 'quote fun))
6379 (list 'let '(orgstruct-mode)
6380 (list 'call-interactively
6381 (append '(or)
6382 (mapcar (lambda (k)
6383 (list 'key-binding k))
6384 keys)
6385 '('orgstruct-error))))))))
6387 (defun org-context-p (&rest contexts)
6388 "Check if local context is any of CONTEXTS.
6389 Possible values in the list of contexts are `table', `headline', and `item'."
6390 (let ((pos (point)))
6391 (goto-char (point-at-bol))
6392 (prog1 (or (and (memq 'table contexts)
6393 (looking-at "[ \t]*|"))
6394 (and (memq 'headline contexts)
6395 ;;????????? (looking-at "\\*+"))
6396 (looking-at outline-regexp))
6397 (and (memq 'item contexts)
6398 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6399 (and (memq 'item-body contexts)
6400 (org-in-item-p)))
6401 (goto-char pos))))
6403 (defun org-get-local-variables ()
6404 "Return a list of all local variables in an org-mode buffer."
6405 (let (varlist)
6406 (with-current-buffer (get-buffer-create "*Org tmp*")
6407 (erase-buffer)
6408 (org-mode)
6409 (setq varlist (buffer-local-variables)))
6410 (kill-buffer "*Org tmp*")
6411 (delq nil
6412 (mapcar
6413 (lambda (x)
6414 (setq x
6415 (if (symbolp x)
6416 (list x)
6417 (list (car x) (list 'quote (cdr x)))))
6418 (if (string-match
6419 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6420 (symbol-name (car x)))
6421 x nil))
6422 varlist))))
6424 ;;;###autoload
6425 (defun org-run-like-in-org-mode (cmd)
6426 (org-load-modules-maybe)
6427 (unless org-local-vars
6428 (setq org-local-vars (org-get-local-variables)))
6429 (eval (list 'let org-local-vars
6430 (list 'call-interactively (list 'quote cmd)))))
6432 ;;;; Archiving
6434 (defun org-get-category (&optional pos)
6435 "Get the category applying to position POS."
6436 (get-text-property (or pos (point)) 'org-category))
6438 (defun org-refresh-category-properties ()
6439 "Refresh category text properties in the buffer."
6440 (let ((def-cat (cond
6441 ((null org-category)
6442 (if buffer-file-name
6443 (file-name-sans-extension
6444 (file-name-nondirectory buffer-file-name))
6445 "???"))
6446 ((symbolp org-category) (symbol-name org-category))
6447 (t org-category)))
6448 beg end cat pos optionp)
6449 (org-unmodified
6450 (save-excursion
6451 (save-restriction
6452 (widen)
6453 (goto-char (point-min))
6454 (put-text-property (point) (point-max) 'org-category def-cat)
6455 (while (re-search-forward
6456 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6457 (setq pos (match-end 0)
6458 optionp (equal (char-after (match-beginning 0)) ?#)
6459 cat (org-trim (match-string 2)))
6460 (if optionp
6461 (setq beg (point-at-bol) end (point-max))
6462 (org-back-to-heading t)
6463 (setq beg (point) end (org-end-of-subtree t t)))
6464 (put-text-property beg end 'org-category cat)
6465 (goto-char pos)))))))
6468 ;;;; Link Stuff
6470 ;;; Link abbreviations
6472 (defun org-link-expand-abbrev (link)
6473 "Apply replacements as defined in `org-link-abbrev-alist."
6474 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6475 (let* ((key (match-string 1 link))
6476 (as (or (assoc key org-link-abbrev-alist-local)
6477 (assoc key org-link-abbrev-alist)))
6478 (tag (and (match-end 2) (match-string 3 link)))
6479 rpl)
6480 (if (not as)
6481 link
6482 (setq rpl (cdr as))
6483 (cond
6484 ((symbolp rpl) (funcall rpl tag))
6485 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6486 ((string-match "%h" rpl)
6487 (replace-match (url-hexify-string (or tag "")) t t rpl))
6488 (t (concat rpl tag)))))
6489 link))
6491 ;;; Storing and inserting links
6493 (defvar org-insert-link-history nil
6494 "Minibuffer history for links inserted with `org-insert-link'.")
6496 (defvar org-stored-links nil
6497 "Contains the links stored with `org-store-link'.")
6499 (defvar org-store-link-plist nil
6500 "Plist with info about the most recently link created with `org-store-link'.")
6502 (defvar org-link-protocols nil
6503 "Link protocols added to Org-mode using `org-add-link-type'.")
6505 (defvar org-store-link-functions nil
6506 "List of functions that are called to create and store a link.
6507 Each function will be called in turn until one returns a non-nil
6508 value. Each function should check if it is responsible for creating
6509 this link (for example by looking at the major mode).
6510 If not, it must exit and return nil.
6511 If yes, it should return a non-nil value after a calling
6512 `org-store-link-props' with a list of properties and values.
6513 Special properties are:
6515 :type The link prefix. like \"http\". This must be given.
6516 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6517 This is obligatory as well.
6518 :description Optional default description for the second pair
6519 of brackets in an Org-mode link. The user can still change
6520 this when inserting this link into an Org-mode buffer.
6522 In addition to these, any additional properties can be specified
6523 and then used in remember templates.")
6525 (defun org-add-link-type (type &optional follow export)
6526 "Add TYPE to the list of `org-link-types'.
6527 Re-compute all regular expressions depending on `org-link-types'
6529 FOLLOW and EXPORT are two functions.
6531 FOLLOW should take the link path as the single argument and do whatever
6532 is necessary to follow the link, for example find a file or display
6533 a mail message.
6535 EXPORT should format the link path for export to one of the export formats.
6536 It should be a function accepting three arguments:
6538 path the path of the link, the text after the prefix (like \"http:\")
6539 desc the description of the link, if any, nil if there was no description
6540 format the export format, a symbol like `html' or `latex'.
6542 The function may use the FORMAT information to return different values
6543 depending on the format. The return value will be put literally into
6544 the exported file.
6545 Org-mode has a built-in default for exporting links. If you are happy with
6546 this default, there is no need to define an export function for the link
6547 type. For a simple example of an export function, see `org-bbdb.el'."
6548 (add-to-list 'org-link-types type t)
6549 (org-make-link-regexps)
6550 (if (assoc type org-link-protocols)
6551 (setcdr (assoc type org-link-protocols) (list follow export))
6552 (push (list type follow export) org-link-protocols)))
6554 ;;;###autoload
6555 (defun org-store-link (arg)
6556 "\\<org-mode-map>Store an org-link to the current location.
6557 This link is added to `org-stored-links' and can later be inserted
6558 into an org-buffer with \\[org-insert-link].
6560 For some link types, a prefix arg is interpreted:
6561 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6562 For file links, arg negates `org-context-in-file-links'."
6563 (interactive "P")
6564 (org-load-modules-maybe)
6565 (setq org-store-link-plist nil) ; reset
6566 (let (link cpltxt desc description search txt)
6567 (cond
6569 ((run-hook-with-args-until-success 'org-store-link-functions)
6570 (setq link (plist-get org-store-link-plist :link)
6571 desc (or (plist-get org-store-link-plist :description) link)))
6573 ((equal (buffer-name) "*Org Edit Src Example*")
6574 (let (label gc)
6575 (while (or (not label)
6576 (save-excursion
6577 (save-restriction
6578 (widen)
6579 (goto-char (point-min))
6580 (re-search-forward
6581 (regexp-quote (format org-coderef-label-format label))
6582 nil t))))
6583 (when label (message "Label exists already") (sit-for 2))
6584 (setq label (read-string "Code line label: " label)))
6585 (end-of-line 1)
6586 (setq link (format org-coderef-label-format label))
6587 (setq gc (- 79 (length link)))
6588 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6589 (insert link)
6590 (setq link (concat "(" label ")") desc nil)))
6592 ((eq major-mode 'calendar-mode)
6593 (let ((cd (calendar-cursor-to-date)))
6594 (setq link
6595 (format-time-string
6596 (car org-time-stamp-formats)
6597 (apply 'encode-time
6598 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6599 nil nil nil))))
6600 (org-store-link-props :type "calendar" :date cd)))
6602 ((eq major-mode 'w3-mode)
6603 (setq cpltxt (url-view-url t)
6604 link (org-make-link cpltxt))
6605 (org-store-link-props :type "w3" :url (url-view-url t)))
6607 ((eq major-mode 'w3m-mode)
6608 (setq cpltxt (or w3m-current-title w3m-current-url)
6609 link (org-make-link w3m-current-url))
6610 (org-store-link-props :type "w3m" :url (url-view-url t)))
6612 ((setq search (run-hook-with-args-until-success
6613 'org-create-file-search-functions))
6614 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6615 "::" search))
6616 (setq cpltxt (or description link)))
6618 ((eq major-mode 'image-mode)
6619 (setq cpltxt (concat "file:"
6620 (abbreviate-file-name buffer-file-name))
6621 link (org-make-link cpltxt))
6622 (org-store-link-props :type "image" :file buffer-file-name))
6624 ((eq major-mode 'dired-mode)
6625 ;; link to the file in the current line
6626 (setq cpltxt (concat "file:"
6627 (abbreviate-file-name
6628 (expand-file-name
6629 (dired-get-filename nil t))))
6630 link (org-make-link cpltxt)))
6632 ((and buffer-file-name (org-mode-p))
6633 (cond
6634 ((org-in-regexp "<<\\(.*?\\)>>")
6635 (setq cpltxt
6636 (concat "file:"
6637 (abbreviate-file-name buffer-file-name)
6638 "::" (match-string 1))
6639 link (org-make-link cpltxt)))
6640 ((and (featurep 'org-id)
6641 (or (eq org-link-to-org-use-id t)
6642 (and (eq org-link-to-org-use-id 'create-if-interactive)
6643 (interactive-p))
6644 (and org-link-to-org-use-id
6645 (condition-case nil
6646 (org-entry-get nil "ID")
6647 (error nil)))))
6648 ;; We can make a link using the ID.
6649 (setq link (condition-case nil
6650 (prog1 (org-id-store-link)
6651 (setq desc (plist-get org-store-link-plist
6652 :description)))
6653 (error
6654 ;; probably before first headline, link to file only
6655 (concat "file:"
6656 (abbreviate-file-name buffer-file-name))))))
6658 ;; Just link to current headline
6659 (setq cpltxt (concat "file:"
6660 (abbreviate-file-name buffer-file-name)))
6661 ;; Add a context search string
6662 (when (org-xor org-context-in-file-links arg)
6663 (setq txt (cond
6664 ((org-on-heading-p) nil)
6665 ((org-region-active-p)
6666 (buffer-substring (region-beginning) (region-end)))
6667 (t nil)))
6668 (when (or (null txt) (string-match "\\S-" txt))
6669 (setq cpltxt
6670 (concat cpltxt "::"
6671 (condition-case nil
6672 (org-make-org-heading-search-string txt)
6673 (error "")))
6674 desc "NONE")))
6675 (if (string-match "::\\'" cpltxt)
6676 (setq cpltxt (substring cpltxt 0 -2)))
6677 (setq link (org-make-link cpltxt)))))
6679 ((buffer-file-name (buffer-base-buffer))
6680 ;; Just link to this file here.
6681 (setq cpltxt (concat "file:"
6682 (abbreviate-file-name
6683 (buffer-file-name (buffer-base-buffer)))))
6684 ;; Add a context string
6685 (when (org-xor org-context-in-file-links arg)
6686 (setq txt (if (org-region-active-p)
6687 (buffer-substring (region-beginning) (region-end))
6688 (buffer-substring (point-at-bol) (point-at-eol))))
6689 ;; Only use search option if there is some text.
6690 (when (string-match "\\S-" txt)
6691 (setq cpltxt
6692 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6693 desc "NONE")))
6694 (setq link (org-make-link cpltxt)))
6696 ((interactive-p)
6697 (error "Cannot link to a buffer which is not visiting a file"))
6699 (t (setq link nil)))
6701 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6702 (setq link (or link cpltxt)
6703 desc (or desc cpltxt))
6704 (if (equal desc "NONE") (setq desc nil))
6706 (if (and (interactive-p) link)
6707 (progn
6708 (setq org-stored-links
6709 (cons (list link desc) org-stored-links))
6710 (message "Stored: %s" (or desc link)))
6711 (and link (org-make-link-string link desc)))))
6713 (defun org-store-link-props (&rest plist)
6714 "Store link properties, extract names and addresses."
6715 (let (x adr)
6716 (when (setq x (plist-get plist :from))
6717 (setq adr (mail-extract-address-components x))
6718 (setq plist (plist-put plist :fromname (car adr)))
6719 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6720 (when (setq x (plist-get plist :to))
6721 (setq adr (mail-extract-address-components x))
6722 (setq plist (plist-put plist :toname (car adr)))
6723 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6724 (let ((from (plist-get plist :from))
6725 (to (plist-get plist :to)))
6726 (when (and from to org-from-is-user-regexp)
6727 (setq plist
6728 (plist-put plist :fromto
6729 (if (string-match org-from-is-user-regexp from)
6730 (concat "to %t")
6731 (concat "from %f"))))))
6732 (setq org-store-link-plist plist))
6734 (defun org-add-link-props (&rest plist)
6735 "Add these properties to the link property list."
6736 (let (key value)
6737 (while plist
6738 (setq key (pop plist) value (pop plist))
6739 (setq org-store-link-plist
6740 (plist-put org-store-link-plist key value)))))
6742 (defun org-email-link-description (&optional fmt)
6743 "Return the description part of an email link.
6744 This takes information from `org-store-link-plist' and formats it
6745 according to FMT (default from `org-email-link-description-format')."
6746 (setq fmt (or fmt org-email-link-description-format))
6747 (let* ((p org-store-link-plist)
6748 (to (plist-get p :toaddress))
6749 (from (plist-get p :fromaddress))
6750 (table
6751 (list
6752 (cons "%c" (plist-get p :fromto))
6753 (cons "%F" (plist-get p :from))
6754 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6755 (cons "%T" (plist-get p :to))
6756 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6757 (cons "%s" (plist-get p :subject))
6758 (cons "%m" (plist-get p :message-id)))))
6759 (when (string-match "%c" fmt)
6760 ;; Check if the user wrote this message
6761 (if (and org-from-is-user-regexp from to
6762 (save-match-data (string-match org-from-is-user-regexp from)))
6763 (setq fmt (replace-match "to %t" t t fmt))
6764 (setq fmt (replace-match "from %f" t t fmt))))
6765 (org-replace-escapes fmt table)))
6767 (defun org-make-org-heading-search-string (&optional string heading)
6768 "Make search string for STRING or current headline."
6769 (interactive)
6770 (let ((s (or string (org-get-heading))))
6771 (unless (and string (not heading))
6772 ;; We are using a headline, clean up garbage in there.
6773 (if (string-match org-todo-regexp s)
6774 (setq s (replace-match "" t t s)))
6775 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6776 (setq s (replace-match "" t t s)))
6777 (setq s (org-trim s))
6778 (if (string-match (concat "^\\(" org-quote-string "\\|"
6779 org-comment-string "\\)") s)
6780 (setq s (replace-match "" t t s)))
6781 (while (string-match org-ts-regexp s)
6782 (setq s (replace-match "" t t s))))
6783 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6784 (setq s (replace-match " " t t s)))
6785 (or string (setq s (concat "*" s))) ; Add * for headlines
6786 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6788 (defun org-make-link (&rest strings)
6789 "Concatenate STRINGS."
6790 (apply 'concat strings))
6792 (defun org-make-link-string (link &optional description)
6793 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6794 (unless (string-match "\\S-" link)
6795 (error "Empty link"))
6796 (when (stringp description)
6797 ;; Remove brackets from the description, they are fatal.
6798 (while (string-match "\\[" description)
6799 (setq description (replace-match "{" t t description)))
6800 (while (string-match "\\]" description)
6801 (setq description (replace-match "}" t t description))))
6802 (when (equal (org-link-escape link) description)
6803 ;; No description needed, it is identical
6804 (setq description nil))
6805 (when (and (not description)
6806 (not (equal link (org-link-escape link))))
6807 (setq description (org-extract-attributes link)))
6808 (concat "[[" (org-link-escape link) "]"
6809 (if description (concat "[" description "]") "")
6810 "]"))
6812 (defconst org-link-escape-chars
6813 '((?\ . "%20")
6814 (?\[ . "%5B")
6815 (?\] . "%5D")
6816 (?\340 . "%E0") ; `a
6817 (?\342 . "%E2") ; ^a
6818 (?\347 . "%E7") ; ,c
6819 (?\350 . "%E8") ; `e
6820 (?\351 . "%E9") ; 'e
6821 (?\352 . "%EA") ; ^e
6822 (?\356 . "%EE") ; ^i
6823 (?\364 . "%F4") ; ^o
6824 (?\371 . "%F9") ; `u
6825 (?\373 . "%FB") ; ^u
6826 (?\; . "%3B")
6827 (?? . "%3F")
6828 (?= . "%3D")
6829 (?+ . "%2B")
6831 "Association list of escapes for some characters problematic in links.
6832 This is the list that is used for internal purposes.")
6834 (defconst org-link-escape-chars-browser
6835 '((?\ . "%20")) ; 32 for the SPC char
6836 "Association list of escapes for some characters problematic in links.
6837 This is the list that is used before handing over to the browser.")
6839 (defun org-link-escape (text &optional table)
6840 "Escape characters in TEXT that are problematic for links."
6841 (setq table (or table org-link-escape-chars))
6842 (when text
6843 (let ((re (mapconcat (lambda (x) (regexp-quote
6844 (char-to-string (car x))))
6845 table "\\|")))
6846 (while (string-match re text)
6847 (setq text
6848 (replace-match
6849 (cdr (assoc (string-to-char (match-string 0 text))
6850 table))
6851 t t text)))
6852 text)))
6854 (defun org-link-unescape (text &optional table)
6855 "Reverse the action of `org-link-escape'."
6856 (setq table (or table org-link-escape-chars))
6857 (when text
6858 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6859 table "\\|")))
6860 (while (string-match re text)
6861 (setq text
6862 (replace-match
6863 (char-to-string (car (rassoc (match-string 0 text) table)))
6864 t t text)))
6865 text)))
6867 (defun org-xor (a b)
6868 "Exclusive or."
6869 (if a (not b) b))
6871 (defun org-fixup-message-id-for-http (s)
6872 "Replace special characters in a message id, so it can be used in an http query."
6873 (while (string-match "<" s)
6874 (setq s (replace-match "%3C" t t s)))
6875 (while (string-match ">" s)
6876 (setq s (replace-match "%3E" t t s)))
6877 (while (string-match "@" s)
6878 (setq s (replace-match "%40" t t s)))
6881 ;;;###autoload
6882 (defun org-insert-link-global ()
6883 "Insert a link like Org-mode does.
6884 This command can be called in any mode to insert a link in Org-mode syntax."
6885 (interactive)
6886 (org-load-modules-maybe)
6887 (org-run-like-in-org-mode 'org-insert-link))
6889 (defun org-insert-link (&optional complete-file link-location)
6890 "Insert a link. At the prompt, enter the link.
6892 Completion can be used to insert any of the link protocol prefixes like
6893 http or ftp in use.
6895 The history can be used to select a link previously stored with
6896 `org-store-link'. When the empty string is entered (i.e. if you just
6897 press RET at the prompt), the link defaults to the most recently
6898 stored link. As SPC triggers completion in the minibuffer, you need to
6899 use M-SPC or C-q SPC to force the insertion of a space character.
6901 You will also be prompted for a description, and if one is given, it will
6902 be displayed in the buffer instead of the link.
6904 If there is already a link at point, this command will allow you to edit link
6905 and description parts.
6907 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6908 be selected using completion. The path to the file will be relative to the
6909 current directory if the file is in the current directory or a subdirectory.
6910 Otherwise, the link will be the absolute path as completed in the minibuffer
6911 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6912 option `org-link-file-path-type'.
6914 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6915 the current directory or below.
6917 With three \\[universal-argument] prefixes, negate the meaning of
6918 `org-keep-stored-link-after-insertion'.
6920 If `org-make-link-description-function' is non-nil, this function will be
6921 called with the link target, and the result will be the default
6922 link description.
6924 If the LINK-LOCATION parameter is non-nil, this value will be
6925 used as the link location instead of reading one interactively."
6926 (interactive "P")
6927 (let* ((wcf (current-window-configuration))
6928 (region (if (org-region-active-p)
6929 (buffer-substring (region-beginning) (region-end))))
6930 (remove (and region (list (region-beginning) (region-end))))
6931 (desc region)
6932 tmphist ; byte-compile incorrectly complains about this
6933 (link link-location)
6934 entry file)
6935 (cond
6936 (link-location) ; specified by arg, just use it.
6937 ((org-in-regexp org-bracket-link-regexp 1)
6938 ;; We do have a link at point, and we are going to edit it.
6939 (setq remove (list (match-beginning 0) (match-end 0)))
6940 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6941 (setq link (read-string "Link: "
6942 (org-link-unescape
6943 (org-match-string-no-properties 1)))))
6944 ((or (org-in-regexp org-angle-link-re)
6945 (org-in-regexp org-plain-link-re))
6946 ;; Convert to bracket link
6947 (setq remove (list (match-beginning 0) (match-end 0))
6948 link (read-string "Link: "
6949 (org-remove-angle-brackets (match-string 0)))))
6950 ((member complete-file '((4) (16)))
6951 ;; Completing read for file names.
6952 (setq file (read-file-name "File: "))
6953 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6954 (pwd1 (file-name-as-directory (abbreviate-file-name
6955 (expand-file-name ".")))))
6956 (cond
6957 ((equal complete-file '(16))
6958 (setq link (org-make-link
6959 "file:"
6960 (abbreviate-file-name (expand-file-name file)))))
6961 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6962 (setq link (org-make-link "file:" (match-string 1 file))))
6963 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6964 (expand-file-name file))
6965 (setq link (org-make-link
6966 "file:" (match-string 1 (expand-file-name file)))))
6967 (t (setq link (org-make-link "file:" file))))))
6969 ;; Read link, with completion for stored links.
6970 (with-output-to-temp-buffer "*Org Links*"
6971 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6972 (when org-stored-links
6973 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6974 (princ (mapconcat
6975 (lambda (x)
6976 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6977 (reverse org-stored-links) "\n"))))
6978 (let ((cw (selected-window)))
6979 (select-window (get-buffer-window "*Org Links*"))
6980 (setq truncate-lines t)
6981 (org-fit-window-to-buffer)
6982 (select-window cw))
6983 ;; Fake a link history, containing the stored links.
6984 (setq tmphist (append (mapcar 'car org-stored-links)
6985 org-insert-link-history))
6986 (unwind-protect
6987 (setq link
6988 (let ((org-completion-use-ido nil))
6989 (org-completing-read
6990 "Link: "
6991 (append
6992 (mapcar (lambda (x) (list (concat (car x) ":")))
6993 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6994 (mapcar (lambda (x) (list (concat x ":")))
6995 org-link-types))
6996 nil nil nil
6997 'tmphist
6998 (or (car (car org-stored-links))))))
6999 (set-window-configuration wcf)
7000 (kill-buffer "*Org Links*"))
7001 (setq entry (assoc link org-stored-links))
7002 (or entry (push link org-insert-link-history))
7003 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7004 (not org-keep-stored-link-after-insertion))
7005 (setq org-stored-links (delq (assoc link org-stored-links)
7006 org-stored-links)))
7007 (setq desc (or desc (nth 1 entry)))))
7009 (if (string-match org-plain-link-re link)
7010 ;; URL-like link, normalize the use of angular brackets.
7011 (setq link (org-make-link (org-remove-angle-brackets link))))
7013 ;; Check if we are linking to the current file with a search option
7014 ;; If yes, simplify the link by using only the search option.
7015 (when (and buffer-file-name
7016 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7017 (let* ((path (match-string 1 link))
7018 (case-fold-search nil)
7019 (search (match-string 2 link)))
7020 (save-match-data
7021 (if (equal (file-truename buffer-file-name) (file-truename path))
7022 ;; We are linking to this same file, with a search option
7023 (setq link search)))))
7025 ;; Check if we can/should use a relative path. If yes, simplify the link
7026 (when (string-match "^file:\\(.*\\)" link)
7027 (let* ((path (match-string 1 link))
7028 (origpath path)
7029 (case-fold-search nil))
7030 (cond
7031 ((or (eq org-link-file-path-type 'absolute)
7032 (equal complete-file '(16)))
7033 (setq path (abbreviate-file-name (expand-file-name path))))
7034 ((eq org-link-file-path-type 'noabbrev)
7035 (setq path (expand-file-name path)))
7036 ((eq org-link-file-path-type 'relative)
7037 (setq path (file-relative-name path)))
7039 (save-match-data
7040 (if (string-match (concat "^" (regexp-quote
7041 (file-name-as-directory
7042 (expand-file-name "."))))
7043 (expand-file-name path))
7044 ;; We are linking a file with relative path name.
7045 (setq path (substring (expand-file-name path)
7046 (match-end 0)))
7047 (setq path (abbreviate-file-name (expand-file-name path)))))))
7048 (setq link (concat "file:" path))
7049 (if (equal desc origpath)
7050 (setq desc path))))
7052 (if org-make-link-description-function
7053 (setq desc (funcall org-make-link-description-function link desc)))
7055 (setq desc (read-string "Description: " desc))
7056 (unless (string-match "\\S-" desc) (setq desc nil))
7057 (if remove (apply 'delete-region remove))
7058 (insert (org-make-link-string link desc))))
7060 (defun org-completing-read (&rest args)
7061 "Completing-read with SPACE being a normal character."
7062 (let ((minibuffer-local-completion-map
7063 (copy-keymap minibuffer-local-completion-map)))
7064 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7065 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7066 (apply 'org-ido-completing-read args)))
7068 (defun org-completing-read-no-ido (&rest args)
7069 (let (org-completion-use-ido)
7070 (apply 'org-completing-read args)))
7072 (defun org-ido-completing-read (&rest args)
7073 "Completing-read using `ido-mode' speedups if available"
7074 (if (and org-completion-use-ido
7075 (fboundp 'ido-completing-read)
7076 (boundp 'ido-mode) ido-mode
7077 (listp (second args)))
7078 (let ((ido-enter-matching-directory nil))
7079 (apply 'ido-completing-read (concat (car args))
7080 (mapcar (lambda (x) (car x)) (nth 1 args))
7081 (cddr args)))
7082 (apply 'completing-read args)))
7085 (defun org-extract-attributes (s)
7086 "Extract the attributes cookie from a string and set as text property."
7087 (let (a attr (start 0) key value)
7088 (save-match-data
7089 (when (string-match "{{\\([^}]+\\)}}$" s)
7090 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7091 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7092 (setq key (match-string 1 a) value (match-string 2 a)
7093 start (match-end 0)
7094 attr (plist-put attr (intern key) value))))
7095 (org-add-props s nil 'org-attr attr))
7098 (defun org-attributes-to-string (plist)
7099 "Format a property list into an HTML attribute list."
7100 (let ((s "") key value)
7101 (while plist
7102 (setq key (pop plist) value (pop plist))
7103 (and value
7104 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7107 ;;; Opening/following a link
7109 (defvar org-link-search-failed nil)
7111 (defun org-next-link ()
7112 "Move forward to the next link.
7113 If the link is in hidden text, expose it."
7114 (interactive)
7115 (when (and org-link-search-failed (eq this-command last-command))
7116 (goto-char (point-min))
7117 (message "Link search wrapped back to beginning of buffer"))
7118 (setq org-link-search-failed nil)
7119 (let* ((pos (point))
7120 (ct (org-context))
7121 (a (assoc :link ct)))
7122 (if a (goto-char (nth 2 a)))
7123 (if (re-search-forward org-any-link-re nil t)
7124 (progn
7125 (goto-char (match-beginning 0))
7126 (if (org-invisible-p) (org-show-context)))
7127 (goto-char pos)
7128 (setq org-link-search-failed t)
7129 (error "No further link found"))))
7131 (defun org-previous-link ()
7132 "Move backward to the previous link.
7133 If the link is in hidden text, expose it."
7134 (interactive)
7135 (when (and org-link-search-failed (eq this-command last-command))
7136 (goto-char (point-max))
7137 (message "Link search wrapped back to end of buffer"))
7138 (setq org-link-search-failed nil)
7139 (let* ((pos (point))
7140 (ct (org-context))
7141 (a (assoc :link ct)))
7142 (if a (goto-char (nth 1 a)))
7143 (if (re-search-backward org-any-link-re nil t)
7144 (progn
7145 (goto-char (match-beginning 0))
7146 (if (org-invisible-p) (org-show-context)))
7147 (goto-char pos)
7148 (setq org-link-search-failed t)
7149 (error "No further link found"))))
7151 (defun org-translate-link (s)
7152 "Translate a link string if a translation function has been defined."
7153 (if (and org-link-translation-function
7154 (fboundp org-link-translation-function)
7155 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7156 (progn
7157 (setq s (funcall org-link-translation-function
7158 (match-string 1) (match-string 2)))
7159 (concat (car s) ":" (cdr s)))
7162 (defun org-translate-link-from-planner (type path)
7163 "Translate a link from Emacs Planner syntax so that Org can follow it.
7164 This is still an experimental function, your mileage may vary."
7165 (cond
7166 ((member type '("http" "https" "news" "ftp"))
7167 ;; standard Internet links are the same.
7168 nil)
7169 ((and (equal type "irc") (string-match "^//" path))
7170 ;; Planner has two / at the beginning of an irc link, we have 1.
7171 ;; We should have zero, actually....
7172 (setq path (substring path 1)))
7173 ((and (equal type "lisp") (string-match "^/" path))
7174 ;; Planner has a slash, we do not.
7175 (setq type "elisp" path (substring path 1)))
7176 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7177 ;; A typical message link. Planner has the id after the fina slash,
7178 ;; we separate it with a hash mark
7179 (setq path (concat (match-string 1 path) "#"
7180 (org-remove-angle-brackets (match-string 2 path)))))
7182 (cons type path))
7184 (defun org-find-file-at-mouse (ev)
7185 "Open file link or URL at mouse."
7186 (interactive "e")
7187 (mouse-set-point ev)
7188 (org-open-at-point 'in-emacs))
7190 (defun org-open-at-mouse (ev)
7191 "Open file link or URL at mouse."
7192 (interactive "e")
7193 (mouse-set-point ev)
7194 (if (eq major-mode 'org-agenda-mode)
7195 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7196 (org-open-at-point))
7198 (defvar org-window-config-before-follow-link nil
7199 "The window configuration before following a link.
7200 This is saved in case the need arises to restore it.")
7202 (defvar org-open-link-marker (make-marker)
7203 "Marker pointing to the location where `org-open-at-point; was called.")
7205 ;;;###autoload
7206 (defun org-open-at-point-global ()
7207 "Follow a link like Org-mode does.
7208 This command can be called in any mode to follow a link that has
7209 Org-mode syntax."
7210 (interactive)
7211 (org-run-like-in-org-mode 'org-open-at-point))
7213 ;;;###autoload
7214 (defun org-open-link-from-string (s &optional arg)
7215 "Open a link in the string S, as if it was in Org-mode."
7216 (interactive "sLink: \nP")
7217 (with-temp-buffer
7218 (let ((org-inhibit-startup t))
7219 (org-mode)
7220 (insert s)
7221 (goto-char (point-min))
7222 (org-open-at-point arg))))
7224 (defun org-open-at-point (&optional in-emacs)
7225 "Open link at or after point.
7226 If there is no link at point, this function will search forward up to
7227 the end of the current subtree.
7228 Normally, files will be opened by an appropriate application. If the
7229 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7230 With a double prefix argument, try to open outside of Emacs, in the
7231 application the system uses for this file type."
7232 (interactive "P")
7233 (org-load-modules-maybe)
7234 (move-marker org-open-link-marker (point))
7235 (setq org-window-config-before-follow-link (current-window-configuration))
7236 (org-remove-occur-highlights nil nil t)
7237 (cond
7238 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7239 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7240 (org-footnote-action))
7242 (let (type path link line search (pos (point)))
7243 (catch 'match
7244 (save-excursion
7245 (skip-chars-forward "^]\n\r")
7246 (when (org-in-regexp org-bracket-link-regexp)
7247 (setq link (org-extract-attributes
7248 (org-link-unescape (org-match-string-no-properties 1))))
7249 (while (string-match " *\n *" link)
7250 (setq link (replace-match " " t t link)))
7251 (setq link (org-link-expand-abbrev link))
7252 (cond
7253 ((or (file-name-absolute-p link)
7254 (string-match "^\\.\\.?/" link))
7255 (setq type "file" path link))
7256 ((string-match org-link-re-with-space3 link)
7257 (setq type (match-string 1 link) path (match-string 2 link)))
7258 (t (setq type "thisfile" path link)))
7259 (throw 'match t)))
7261 (when (get-text-property (point) 'org-linked-text)
7262 (setq type "thisfile"
7263 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7264 (1+ (point)) (point))
7265 path (buffer-substring
7266 (previous-single-property-change pos 'org-linked-text)
7267 (next-single-property-change pos 'org-linked-text)))
7268 (throw 'match t))
7270 (save-excursion
7271 (when (or (org-in-regexp org-angle-link-re)
7272 (org-in-regexp org-plain-link-re))
7273 (setq type (match-string 1) path (match-string 2))
7274 (throw 'match t)))
7275 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7276 (setq type "tree-match"
7277 path (match-string 1))
7278 (throw 'match t))
7279 (save-excursion
7280 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7281 (setq type "tags"
7282 path (match-string 1))
7283 (while (string-match ":" path)
7284 (setq path (replace-match "+" t t path)))
7285 (throw 'match t))))
7286 (unless path
7287 (error "No link found"))
7288 ;; Remove any trailing spaces in path
7289 (if (string-match " +\\'" path)
7290 (setq path (replace-match "" t t path)))
7291 (if (and org-link-translation-function
7292 (fboundp org-link-translation-function))
7293 ;; Check if we need to translate the link
7294 (let ((tmp (funcall org-link-translation-function type path)))
7295 (setq type (car tmp) path (cdr tmp))))
7297 (cond
7299 ((assoc type org-link-protocols)
7300 (funcall (nth 1 (assoc type org-link-protocols)) path))
7302 ((equal type "mailto")
7303 (let ((cmd (car org-link-mailto-program))
7304 (args (cdr org-link-mailto-program)) args1
7305 (address path) (subject "") a)
7306 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7307 (setq address (match-string 1 path)
7308 subject (org-link-escape (match-string 2 path))))
7309 (while args
7310 (cond
7311 ((not (stringp (car args))) (push (pop args) args1))
7312 (t (setq a (pop args))
7313 (if (string-match "%a" a)
7314 (setq a (replace-match address t t a)))
7315 (if (string-match "%s" a)
7316 (setq a (replace-match subject t t a)))
7317 (push a args1))))
7318 (apply cmd (nreverse args1))))
7320 ((member type '("http" "https" "ftp" "news"))
7321 (browse-url (concat type ":" (org-link-escape
7322 path org-link-escape-chars-browser))))
7324 ((member type '("message"))
7325 (browse-url (concat type ":" path)))
7327 ((string= type "tags")
7328 (org-tags-view in-emacs path))
7329 ((string= type "thisfile")
7330 (if in-emacs
7331 (switch-to-buffer-other-window
7332 (org-get-buffer-for-internal-link (current-buffer)))
7333 (org-mark-ring-push))
7334 (let ((cmd `(org-link-search
7335 ,path
7336 ,(cond ((equal in-emacs '(4)) 'occur)
7337 ((equal in-emacs '(16)) 'org-occur)
7338 (t nil))
7339 ,pos)))
7340 (condition-case nil (eval cmd)
7341 (error (progn (widen) (eval cmd))))))
7343 ((string= type "tree-match")
7344 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7346 ((string= type "file")
7347 (if (string-match "::\\([0-9]+\\)\\'" path)
7348 (setq line (string-to-number (match-string 1 path))
7349 path (substring path 0 (match-beginning 0)))
7350 (if (string-match "::\\(.+\\)\\'" path)
7351 (setq search (match-string 1 path)
7352 path (substring path 0 (match-beginning 0)))))
7353 (if (string-match "[*?{]" (file-name-nondirectory path))
7354 (dired path)
7355 (org-open-file path in-emacs line search)))
7357 ((string= type "news")
7358 (require 'org-gnus)
7359 (org-gnus-follow-link path))
7361 ((string= type "shell")
7362 (let ((cmd path))
7363 (if (or (not org-confirm-shell-link-function)
7364 (funcall org-confirm-shell-link-function
7365 (format "Execute \"%s\" in shell? "
7366 (org-add-props cmd nil
7367 'face 'org-warning))))
7368 (progn
7369 (message "Executing %s" cmd)
7370 (shell-command cmd))
7371 (error "Abort"))))
7373 ((string= type "elisp")
7374 (let ((cmd path))
7375 (if (or (not org-confirm-elisp-link-function)
7376 (funcall org-confirm-elisp-link-function
7377 (format "Execute \"%s\" as elisp? "
7378 (org-add-props cmd nil
7379 'face 'org-warning))))
7380 (message "%s => %s" cmd
7381 (if (equal (string-to-char cmd) ?\()
7382 (eval (read cmd))
7383 (call-interactively (read cmd))))
7384 (error "Abort"))))
7387 (browse-url-at-point))))))
7388 (move-marker org-open-link-marker nil)
7389 (run-hook-with-args 'org-follow-link-hook))
7391 ;;;; Time estimates
7393 (defun org-get-effort (&optional pom)
7394 "Get the effort estimate for the current entry."
7395 (org-entry-get pom org-effort-property))
7397 ;;; File search
7399 (defvar org-create-file-search-functions nil
7400 "List of functions to construct the right search string for a file link.
7401 These functions are called in turn with point at the location to
7402 which the link should point.
7404 A function in the hook should first test if it would like to
7405 handle this file type, for example by checking the major-mode or
7406 the file extension. If it decides not to handle this file, it
7407 should just return nil to give other functions a chance. If it
7408 does handle the file, it must return the search string to be used
7409 when following the link. The search string will be part of the
7410 file link, given after a double colon, and `org-open-at-point'
7411 will automatically search for it. If special measures must be
7412 taken to make the search successful, another function should be
7413 added to the companion hook `org-execute-file-search-functions',
7414 which see.
7416 A function in this hook may also use `setq' to set the variable
7417 `description' to provide a suggestion for the descriptive text to
7418 be used for this link when it gets inserted into an Org-mode
7419 buffer with \\[org-insert-link].")
7421 (defvar org-execute-file-search-functions nil
7422 "List of functions to execute a file search triggered by a link.
7424 Functions added to this hook must accept a single argument, the
7425 search string that was part of the file link, the part after the
7426 double colon. The function must first check if it would like to
7427 handle this search, for example by checking the major-mode or the
7428 file extension. If it decides not to handle this search, it
7429 should just return nil to give other functions a chance. If it
7430 does handle the search, it must return a non-nil value to keep
7431 other functions from trying.
7433 Each function can access the current prefix argument through the
7434 variable `current-prefix-argument'. Note that a single prefix is
7435 used to force opening a link in Emacs, so it may be good to only
7436 use a numeric or double prefix to guide the search function.
7438 In case this is needed, a function in this hook can also restore
7439 the window configuration before `org-open-at-point' was called using:
7441 (set-window-configuration org-window-config-before-follow-link)")
7443 (defun org-link-search (s &optional type avoid-pos)
7444 "Search for a link search option.
7445 If S is surrounded by forward slashes, it is interpreted as a
7446 regular expression. In org-mode files, this will create an `org-occur'
7447 sparse tree. In ordinary files, `occur' will be used to list matches.
7448 If the current buffer is in `dired-mode', grep will be used to search
7449 in all files. If AVOID-POS is given, ignore matches near that position."
7450 (let ((case-fold-search t)
7451 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7452 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7453 (append '(("") (" ") ("\t") ("\n"))
7454 org-emphasis-alist)
7455 "\\|") "\\)"))
7456 (pos (point))
7457 (pre nil) (post nil)
7458 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7459 (cond
7460 ;; First check if there are any special
7461 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7462 ;; Now try the builtin stuff
7463 ((save-excursion
7464 (goto-char (point-min))
7465 (and
7466 (re-search-forward
7467 (concat "<<" (regexp-quote s0) ">>") nil t)
7468 (setq type 'dedicated
7469 pos (match-beginning 0))))
7470 ;; There is an exact target for this
7471 (goto-char pos))
7472 ((and (string-match "^(\\(.*\\))$" s0)
7473 (save-excursion
7474 (goto-char (point-min))
7475 (and
7476 (re-search-forward
7477 (concat "[^[]" (regexp-quote
7478 (format org-coderef-label-format
7479 (match-string 1 s0))))
7480 nil t)
7481 (setq type 'dedicated
7482 pos (1+ (match-beginning 0))))))
7483 ;; There is a coderef target for this
7484 (goto-char pos))
7485 ((string-match "^/\\(.*\\)/$" s)
7486 ;; A regular expression
7487 (cond
7488 ((org-mode-p)
7489 (org-occur (match-string 1 s)))
7490 ;;((eq major-mode 'dired-mode)
7491 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7492 (t (org-do-occur (match-string 1 s)))))
7494 ;; A normal search strings
7495 (when (equal (string-to-char s) ?*)
7496 ;; Anchor on headlines, post may include tags.
7497 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7498 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7499 s (substring s 1)))
7500 (remove-text-properties
7501 0 (length s)
7502 '(face nil mouse-face nil keymap nil fontified nil) s)
7503 ;; Make a series of regular expressions to find a match
7504 (setq words (org-split-string s "[ \n\r\t]+")
7506 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7507 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7508 "\\)" markers)
7509 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7510 re2a (concat "[ \t\r\n]" re2a_)
7511 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7512 re4 (concat "[^a-zA-Z_]" re4_)
7514 re1 (concat pre re2 post)
7515 re3 (concat pre (if pre re4_ re4) post)
7516 re5 (concat pre ".*" re4)
7517 re2 (concat pre re2)
7518 re2a (concat pre (if pre re2a_ re2a))
7519 re4 (concat pre (if pre re4_ re4))
7520 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7521 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7522 re5 "\\)"
7524 (cond
7525 ((eq type 'org-occur) (org-occur reall))
7526 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7527 (t (goto-char (point-min))
7528 (setq type 'fuzzy)
7529 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7530 (org-search-not-self 1 re1 nil t)
7531 (org-search-not-self 1 re2 nil t)
7532 (org-search-not-self 1 re2a nil t)
7533 (org-search-not-self 1 re3 nil t)
7534 (org-search-not-self 1 re4 nil t)
7535 (org-search-not-self 1 re5 nil t)
7537 (goto-char (match-beginning 1))
7538 (goto-char pos)
7539 (error "No match")))))
7541 ;; Normal string-search
7542 (goto-char (point-min))
7543 (if (search-forward s nil t)
7544 (goto-char (match-beginning 0))
7545 (error "No match"))))
7546 (and (org-mode-p) (org-show-context 'link-search))
7547 type))
7549 (defun org-search-not-self (group &rest args)
7550 "Execute `re-search-forward', but only accept matches that do not
7551 enclose the position of `org-open-link-marker'."
7552 (let ((m org-open-link-marker))
7553 (catch 'exit
7554 (while (apply 're-search-forward args)
7555 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7556 (goto-char (match-end group))
7557 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7558 (> (match-beginning 0) (marker-position m))
7559 (< (match-end 0) (marker-position m)))
7560 (save-match-data
7561 (or (not (org-in-regexp
7562 org-bracket-link-analytic-regexp 1))
7563 (not (match-end 4)) ; no description
7564 (and (<= (match-beginning 4) (point))
7565 (>= (match-end 4) (point))))))
7566 (throw 'exit (point))))))))
7568 (defun org-get-buffer-for-internal-link (buffer)
7569 "Return a buffer to be used for displaying the link target of internal links."
7570 (cond
7571 ((not org-display-internal-link-with-indirect-buffer)
7572 buffer)
7573 ((string-match "(Clone)$" (buffer-name buffer))
7574 (message "Buffer is already a clone, not making another one")
7575 ;; we also do not modify visibility in this case
7576 buffer)
7577 (t ; make a new indirect buffer for displaying the link
7578 (let* ((bn (buffer-name buffer))
7579 (ibn (concat bn "(Clone)"))
7580 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7581 (with-current-buffer ib (org-overview))
7582 ib))))
7584 (defun org-do-occur (regexp &optional cleanup)
7585 "Call the Emacs command `occur'.
7586 If CLEANUP is non-nil, remove the printout of the regular expression
7587 in the *Occur* buffer. This is useful if the regex is long and not useful
7588 to read."
7589 (occur regexp)
7590 (when cleanup
7591 (let ((cwin (selected-window)) win beg end)
7592 (when (setq win (get-buffer-window "*Occur*"))
7593 (select-window win))
7594 (goto-char (point-min))
7595 (when (re-search-forward "match[a-z]+" nil t)
7596 (setq beg (match-end 0))
7597 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7598 (setq end (1- (match-beginning 0)))))
7599 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7600 (goto-char (point-min))
7601 (select-window cwin))))
7603 ;;; The mark ring for links jumps
7605 (defvar org-mark-ring nil
7606 "Mark ring for positions before jumps in Org-mode.")
7607 (defvar org-mark-ring-last-goto nil
7608 "Last position in the mark ring used to go back.")
7609 ;; Fill and close the ring
7610 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7611 (loop for i from 1 to org-mark-ring-length do
7612 (push (make-marker) org-mark-ring))
7613 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7614 org-mark-ring)
7616 (defun org-mark-ring-push (&optional pos buffer)
7617 "Put the current position or POS into the mark ring and rotate it."
7618 (interactive)
7619 (setq pos (or pos (point)))
7620 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7621 (move-marker (car org-mark-ring)
7622 (or pos (point))
7623 (or buffer (current-buffer)))
7624 (message "%s"
7625 (substitute-command-keys
7626 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7628 (defun org-mark-ring-goto (&optional n)
7629 "Jump to the previous position in the mark ring.
7630 With prefix arg N, jump back that many stored positions. When
7631 called several times in succession, walk through the entire ring.
7632 Org-mode commands jumping to a different position in the current file,
7633 or to another Org-mode file, automatically push the old position
7634 onto the ring."
7635 (interactive "p")
7636 (let (p m)
7637 (if (eq last-command this-command)
7638 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7639 (setq p org-mark-ring))
7640 (setq org-mark-ring-last-goto p)
7641 (setq m (car p))
7642 (switch-to-buffer (marker-buffer m))
7643 (goto-char m)
7644 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7646 (defun org-remove-angle-brackets (s)
7647 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7648 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7650 (defun org-add-angle-brackets (s)
7651 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7652 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7654 (defun org-remove-double-quotes (s)
7655 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7656 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7659 ;;; Following specific links
7661 (defun org-follow-timestamp-link ()
7662 (cond
7663 ((org-at-date-range-p t)
7664 (let ((org-agenda-start-on-weekday)
7665 (t1 (match-string 1))
7666 (t2 (match-string 2)))
7667 (setq t1 (time-to-days (org-time-string-to-time t1))
7668 t2 (time-to-days (org-time-string-to-time t2)))
7669 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7670 ((org-at-timestamp-p t)
7671 (org-agenda-list nil (time-to-days (org-time-string-to-time
7672 (substring (match-string 1) 0 10)))
7674 (t (error "This should not happen"))))
7677 ;;; Following file links
7678 (defvar org-wait nil)
7679 (defun org-open-file (path &optional in-emacs line search)
7680 "Open the file at PATH.
7681 First, this expands any special file name abbreviations. Then the
7682 configuration variable `org-file-apps' is checked if it contains an
7683 entry for this file type, and if yes, the corresponding command is launched.
7685 If no application is found, Emacs simply visits the file.
7687 With optional prefix argument IN-EMACS, Emacs will visit the file.
7688 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7689 and o use an external application to visit the file.
7691 Optional LINE specifies a line to go to, optional SEARCH a string to
7692 search for. If LINE or SEARCH is given, the file will always be
7693 opened in Emacs.
7694 If the file does not exist, an error is thrown."
7695 (setq in-emacs (or in-emacs line search))
7696 (let* ((file (if (equal path "")
7697 buffer-file-name
7698 (substitute-in-file-name (expand-file-name path))))
7699 (apps (append org-file-apps (org-default-apps)))
7700 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7701 (dirp (if remp nil (file-directory-p file)))
7702 (file (if (and dirp org-open-directory-means-index-dot-org)
7703 (concat (file-name-as-directory file) "index.org")
7704 file))
7705 (a-m-a-p (assq 'auto-mode apps))
7706 (dfile (downcase file))
7707 (old-buffer (current-buffer))
7708 (old-pos (point))
7709 (old-mode major-mode)
7710 ext cmd)
7711 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7712 (setq ext (match-string 1 dfile))
7713 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7714 (setq ext (match-string 1 dfile))))
7715 (cond
7716 ((equal in-emacs '(16))
7717 (setq cmd (cdr (assoc 'system apps))))
7718 (in-emacs (setq cmd 'emacs))
7720 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7721 (and dirp (cdr (assoc 'directory apps)))
7722 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7723 'string-match)
7724 (cdr (assoc ext apps))
7725 (cdr (assoc t apps))))))
7726 (when (eq cmd 'system)
7727 (setq cmd (cdr (assoc 'system apps))))
7728 (when (eq cmd 'default)
7729 (setq cmd (cdr (assoc t apps))))
7730 (when (eq cmd 'mailcap)
7731 (require 'mailcap)
7732 (mailcap-parse-mailcaps)
7733 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7734 (command (mailcap-mime-info mime-type)))
7735 (if (stringp command)
7736 (setq cmd command)
7737 (setq cmd 'emacs))))
7738 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7739 (not (file-exists-p file))
7740 (not org-open-non-existing-files))
7741 (error "No such file: %s" file))
7742 (cond
7743 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7744 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7745 (while (string-match "['\"]%s['\"]" cmd)
7746 (setq cmd (replace-match "%s" t t cmd)))
7747 (while (string-match "%s" cmd)
7748 (setq cmd (replace-match
7749 (save-match-data
7750 (shell-quote-argument
7751 (convert-standard-filename file)))
7752 t t cmd)))
7753 (save-window-excursion
7754 (start-process-shell-command cmd nil cmd)
7755 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7757 ((or (stringp cmd)
7758 (eq cmd 'emacs))
7759 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7760 (widen)
7761 (if line (goto-line line)
7762 (if search (org-link-search search))))
7763 ((consp cmd)
7764 (let ((file (convert-standard-filename file)))
7765 (eval cmd)))
7766 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7767 (and (org-mode-p) (eq old-mode 'org-mode)
7768 (or (not (equal old-buffer (current-buffer)))
7769 (not (equal old-pos (point))))
7770 (org-mark-ring-push old-pos old-buffer))))
7772 (defun org-default-apps ()
7773 "Return the default applications for this operating system."
7774 (cond
7775 ((eq system-type 'darwin)
7776 org-file-apps-defaults-macosx)
7777 ((eq system-type 'windows-nt)
7778 org-file-apps-defaults-windowsnt)
7779 (t org-file-apps-defaults-gnu)))
7781 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7782 "Convert extensions to regular expressions in the cars of LIST.
7783 Also, weed out any non-string entries, because the return value is used
7784 only for regexp matching.
7785 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7786 point to the symbol `emacs', indicating that the file should
7787 be opened in Emacs."
7788 (append
7789 (delq nil
7790 (mapcar (lambda (x)
7791 (if (not (stringp (car x)))
7793 (if (string-match "\\W" (car x))
7795 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7796 list))
7797 (if add-auto-mode
7798 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7800 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7801 (defun org-file-remote-p (file)
7802 "Test whether FILE specifies a location on a remote system.
7803 Return non-nil if the location is indeed remote.
7805 For example, the filename \"/user@host:/foo\" specifies a location
7806 on the system \"/user@host:\"."
7807 (cond ((fboundp 'file-remote-p)
7808 (file-remote-p file))
7809 ((fboundp 'tramp-handle-file-remote-p)
7810 (tramp-handle-file-remote-p file))
7811 ((and (boundp 'ange-ftp-name-format)
7812 (string-match (car ange-ftp-name-format) file))
7814 (t nil)))
7817 ;;;; Refiling
7819 (defun org-get-org-file ()
7820 "Read a filename, with default directory `org-directory'."
7821 (let ((default (or org-default-notes-file remember-data-file)))
7822 (read-file-name (format "File name [%s]: " default)
7823 (file-name-as-directory org-directory)
7824 default)))
7826 (defun org-notes-order-reversed-p ()
7827 "Check if the current file should receive notes in reversed order."
7828 (cond
7829 ((not org-reverse-note-order) nil)
7830 ((eq t org-reverse-note-order) t)
7831 ((not (listp org-reverse-note-order)) nil)
7832 (t (catch 'exit
7833 (let ((all org-reverse-note-order)
7834 entry)
7835 (while (setq entry (pop all))
7836 (if (string-match (car entry) buffer-file-name)
7837 (throw 'exit (cdr entry))))
7838 nil)))))
7840 (defvar org-refile-target-table nil
7841 "The list of refile targets, created by `org-refile'.")
7843 (defvar org-agenda-new-buffers nil
7844 "Buffers created to visit agenda files.")
7846 (defun org-get-refile-targets (&optional default-buffer)
7847 "Produce a table with refile targets."
7848 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7849 targets txt re files f desc descre fast-path-p level)
7850 (message "Getting targets...")
7851 (with-current-buffer (or default-buffer (current-buffer))
7852 (while (setq entry (pop entries))
7853 (setq files (car entry) desc (cdr entry))
7854 (setq fast-path-p nil)
7855 (cond
7856 ((null files) (setq files (list (current-buffer))))
7857 ((eq files 'org-agenda-files)
7858 (setq files (org-agenda-files 'unrestricted)))
7859 ((and (symbolp files) (fboundp files))
7860 (setq files (funcall files)))
7861 ((and (symbolp files) (boundp files))
7862 (setq files (symbol-value files))))
7863 (if (stringp files) (setq files (list files)))
7864 (cond
7865 ((eq (car desc) :tag)
7866 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7867 ((eq (car desc) :todo)
7868 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7869 ((eq (car desc) :regexp)
7870 (setq descre (cdr desc)))
7871 ((eq (car desc) :level)
7872 (setq descre (concat "^\\*\\{" (number-to-string
7873 (if org-odd-levels-only
7874 (1- (* 2 (cdr desc)))
7875 (cdr desc)))
7876 "\\}[ \t]")))
7877 ((eq (car desc) :maxlevel)
7878 (setq fast-path-p t)
7879 (setq descre (concat "^\\*\\{1," (number-to-string
7880 (if org-odd-levels-only
7881 (1- (* 2 (cdr desc)))
7882 (cdr desc)))
7883 "\\}[ \t]")))
7884 (t (error "Bad refiling target description %s" desc)))
7885 (while (setq f (pop files))
7886 (save-excursion
7887 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7888 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7889 (setq f (expand-file-name f))
7890 (save-excursion
7891 (save-restriction
7892 (widen)
7893 (goto-char (point-min))
7894 (while (re-search-forward descre nil t)
7895 (goto-char (point-at-bol))
7896 (when (looking-at org-complex-heading-regexp)
7897 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7898 txt (org-link-display-format (match-string 4))
7899 re (concat "^" (regexp-quote
7900 (buffer-substring (match-beginning 1)
7901 (match-end 4)))))
7902 (if (match-end 5) (setq re (concat re "[ \t]+"
7903 (regexp-quote
7904 (match-string 5)))))
7905 (setq re (concat re "[ \t]*$"))
7906 (when org-refile-use-outline-path
7907 (setq txt (mapconcat 'org-protect-slash
7908 (append
7909 (if (eq org-refile-use-outline-path 'file)
7910 (list (file-name-nondirectory
7911 (buffer-file-name (buffer-base-buffer))))
7912 (if (eq org-refile-use-outline-path 'full-file-path)
7913 (list (buffer-file-name (buffer-base-buffer)))))
7914 (org-get-outline-path fast-path-p level txt)
7915 (list txt))
7916 "/")))
7917 (push (list txt f re (point)) targets))
7918 (goto-char (point-at-eol))))))))
7919 (message "Getting targets...done")
7920 (nreverse targets))))
7922 (defun org-protect-slash (s)
7923 (while (string-match "/" s)
7924 (setq s (replace-match "\\" t t s)))
7927 (defvar org-olpa (make-vector 20 nil))
7929 (defun org-get-outline-path (&optional fastp level heading)
7930 "Return the outline path to the current entry, as a list."
7931 (if fastp
7932 (progn
7933 (if (> level 19)
7934 (error "Outline path failure, more than 19 levels."))
7935 (loop for i from level upto 19 do
7936 (aset org-olpa i nil))
7937 (prog1
7938 (delq nil (append org-olpa nil))
7939 (aset org-olpa level heading)))
7940 (let (rtn)
7941 (save-excursion
7942 (while (org-up-heading-safe)
7943 (when (looking-at org-complex-heading-regexp)
7944 (push (org-match-string-no-properties 4) rtn)))
7945 rtn))))
7947 (defvar org-refile-history nil
7948 "History for refiling operations.")
7950 (defun org-refile (&optional goto default-buffer)
7951 "Move the entry at point to another heading.
7952 The list of target headings is compiled using the information in
7953 `org-refile-targets', which see. This list is created before each use
7954 and will therefore always be up-to-date.
7956 At the target location, the entry is filed as a subitem of the target heading.
7957 Depending on `org-reverse-note-order', the new subitem will either be the
7958 first or the last subitem.
7960 If there is an active region, all entries in that region will be moved.
7961 However, the region must fulfil the requirement that the first heading
7962 is the first one sets the top-level of the moved text - at most siblings
7963 below it are allowed.
7965 With prefix arg GOTO, the command will only visit the target location,
7966 not actually move anything.
7967 With a double prefix `C-u C-u', go to the location where the last refiling
7968 operation has put the subtree."
7969 (interactive "P")
7970 (let* ((cbuf (current-buffer))
7971 (regionp (org-region-active-p))
7972 (region-start (and regionp (region-beginning)))
7973 (region-end (and regionp (region-end)))
7974 (region-length (and regionp (- region-end region-start)))
7975 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7976 pos it nbuf file re level reversed)
7977 (when regionp (goto-char region-start)
7978 (unless (org-kill-is-subtree-p
7979 (buffer-substring region-start region-end))
7980 (error "The region is not a (sequence of) subtree(s)")))
7981 (if (equal goto '(16))
7982 (org-refile-goto-last-stored)
7983 (when (setq it (org-refile-get-location
7984 (if goto "Goto: " "Refile to: ") default-buffer))
7985 (setq file (nth 1 it)
7986 re (nth 2 it)
7987 pos (nth 3 it))
7988 (if (and (equal (buffer-file-name) file)
7989 (if regionp
7990 (and (>= pos region-start)
7991 (<= pos region-end))
7992 (and (>= pos (point))
7993 (< pos (save-excursion
7994 (org-end-of-subtree t t))))))
7995 (error "Cannot refile to position inside the tree or region"))
7997 (setq nbuf (or (find-buffer-visiting file)
7998 (find-file-noselect file)))
7999 (if goto
8000 (progn
8001 (switch-to-buffer nbuf)
8002 (goto-char pos)
8003 (org-show-context 'org-goto))
8004 (if regionp
8005 (progn
8006 (kill-new (buffer-substring region-start region-end))
8007 (org-save-markers-in-region region-start region-end))
8008 (org-copy-subtree 1 nil t))
8009 (save-excursion
8010 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8011 (find-file-noselect file))))
8012 (setq reversed (org-notes-order-reversed-p))
8013 (save-excursion
8014 (save-restriction
8015 (widen)
8016 (goto-char pos)
8017 (looking-at outline-regexp)
8018 (setq level (org-get-valid-level (funcall outline-level) 1))
8019 (goto-char
8020 (if reversed
8021 (or (outline-next-heading) (point-max))
8022 (or (save-excursion (outline-get-next-sibling))
8023 (org-end-of-subtree t t)
8024 (point-max))))
8025 (if (not (bolp)) (newline))
8026 (bookmark-set "org-refile-last-stored")
8027 (org-paste-subtree level))))
8028 (if regionp
8029 (delete-region (point) (+ (point) region-length))
8030 (org-cut-subtree))
8031 (setq org-markers-to-move nil)
8032 (message "Refiled to \"%s\"" (car it)))))))
8034 (defun org-refile-goto-last-stored ()
8035 "Go to the location where the last refile was stored."
8036 (interactive)
8037 (bookmark-jump "org-refile-last-stored")
8038 (message "This is the location of the last refile"))
8040 (defun org-refile-get-location (&optional prompt default-buffer)
8041 "Prompt the user for a refile location, using PROMPT."
8042 (let ((org-refile-targets org-refile-targets)
8043 (org-refile-use-outline-path org-refile-use-outline-path))
8044 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8045 (unless org-refile-target-table
8046 (error "No refile targets"))
8047 (let* ((cbuf (current-buffer))
8048 (partial-completion-mode nil)
8049 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8050 (cfunc (if (and org-refile-use-outline-path
8051 org-outline-path-complete-in-steps)
8052 'org-olpath-completing-read
8053 'org-ido-completing-read))
8054 (extra (if org-refile-use-outline-path "/" ""))
8055 (filename (and cfn (expand-file-name cfn)))
8056 (tbl (mapcar
8057 (lambda (x)
8058 (if (not (equal filename (nth 1 x)))
8059 (cons (concat (car x) extra " ("
8060 (file-name-nondirectory (nth 1 x)) ")")
8061 (cdr x))
8062 (cons (concat (car x) extra) (cdr x))))
8063 org-refile-target-table))
8064 (completion-ignore-case t))
8065 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8066 tbl)))
8068 (defun org-olpath-completing-read (prompt collection &rest args)
8069 "Read an outline path like a file name."
8070 (let ((thetable collection)
8071 (org-completion-use-ido nil)) ; does not work with ido.
8072 (apply
8073 'org-ido-completing-read prompt
8074 (lambda (string predicate &optional flag)
8075 (let (rtn r f (l (length string)))
8076 (cond
8077 ((eq flag nil)
8078 ;; try completion
8079 (try-completion string thetable))
8080 ((eq flag t)
8081 ;; all-completions
8082 (setq rtn (all-completions string thetable predicate))
8083 (mapcar
8084 (lambda (x)
8085 (setq r (substring x l))
8086 (if (string-match " ([^)]*)$" x)
8087 (setq f (match-string 0 x))
8088 (setq f ""))
8089 (if (string-match "/" r)
8090 (concat string (substring r 0 (match-end 0)) f)
8092 rtn))
8093 ((eq flag 'lambda)
8094 ;; exact match?
8095 (assoc string thetable)))
8097 args)))
8099 ;;;; Dynamic blocks
8101 (defun org-find-dblock (name)
8102 "Find the first dynamic block with name NAME in the buffer.
8103 If not found, stay at current position and return nil."
8104 (let (pos)
8105 (save-excursion
8106 (goto-char (point-min))
8107 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8108 nil t)
8109 (match-beginning 0))))
8110 (if pos (goto-char pos))
8111 pos))
8113 (defconst org-dblock-start-re
8114 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8115 "Matches the startline of a dynamic block, with parameters.")
8117 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8118 "Matches the end of a dynamic block.")
8120 (defun org-create-dblock (plist)
8121 "Create a dynamic block section, with parameters taken from PLIST.
8122 PLIST must contain a :name entry which is used as name of the block."
8123 (unless (bolp) (newline))
8124 (let ((name (plist-get plist :name)))
8125 (insert "#+BEGIN: " name)
8126 (while plist
8127 (if (eq (car plist) :name)
8128 (setq plist (cddr plist))
8129 (insert " " (prin1-to-string (pop plist)))))
8130 (insert "\n\n#+END:\n")
8131 (beginning-of-line -2)))
8133 (defun org-prepare-dblock ()
8134 "Prepare dynamic block for refresh.
8135 This empties the block, puts the cursor at the insert position and returns
8136 the property list including an extra property :name with the block name."
8137 (unless (looking-at org-dblock-start-re)
8138 (error "Not at a dynamic block"))
8139 (let* ((begdel (1+ (match-end 0)))
8140 (name (org-no-properties (match-string 1)))
8141 (params (append (list :name name)
8142 (read (concat "(" (match-string 3) ")")))))
8143 (unless (re-search-forward org-dblock-end-re nil t)
8144 (error "Dynamic block not terminated"))
8145 (setq params
8146 (append params
8147 (list :content (buffer-substring
8148 begdel (match-beginning 0)))))
8149 (delete-region begdel (match-beginning 0))
8150 (goto-char begdel)
8151 (open-line 1)
8152 params))
8154 (defun org-map-dblocks (&optional command)
8155 "Apply COMMAND to all dynamic blocks in the current buffer.
8156 If COMMAND is not given, use `org-update-dblock'."
8157 (let ((cmd (or command 'org-update-dblock))
8158 pos)
8159 (save-excursion
8160 (goto-char (point-min))
8161 (while (re-search-forward org-dblock-start-re nil t)
8162 (goto-char (setq pos (match-beginning 0)))
8163 (condition-case nil
8164 (funcall cmd)
8165 (error (message "Error during update of dynamic block")))
8166 (goto-char pos)
8167 (unless (re-search-forward org-dblock-end-re nil t)
8168 (error "Dynamic block not terminated"))))))
8170 (defun org-dblock-update (&optional arg)
8171 "User command for updating dynamic blocks.
8172 Update the dynamic block at point. With prefix ARG, update all dynamic
8173 blocks in the buffer."
8174 (interactive "P")
8175 (if arg
8176 (org-update-all-dblocks)
8177 (or (looking-at org-dblock-start-re)
8178 (org-beginning-of-dblock))
8179 (org-update-dblock)))
8181 (defun org-update-dblock ()
8182 "Update the dynamic block at point
8183 This means to empty the block, parse for parameters and then call
8184 the correct writing function."
8185 (save-window-excursion
8186 (let* ((pos (point))
8187 (line (org-current-line))
8188 (params (org-prepare-dblock))
8189 (name (plist-get params :name))
8190 (cmd (intern (concat "org-dblock-write:" name))))
8191 (message "Updating dynamic block `%s' at line %d..." name line)
8192 (funcall cmd params)
8193 (message "Updating dynamic block `%s' at line %d...done" name line)
8194 (goto-char pos))))
8196 (defun org-beginning-of-dblock ()
8197 "Find the beginning of the dynamic block at point.
8198 Error if there is no such block at point."
8199 (let ((pos (point))
8200 beg)
8201 (end-of-line 1)
8202 (if (and (re-search-backward org-dblock-start-re nil t)
8203 (setq beg (match-beginning 0))
8204 (re-search-forward org-dblock-end-re nil t)
8205 (> (match-end 0) pos))
8206 (goto-char beg)
8207 (goto-char pos)
8208 (error "Not in a dynamic block"))))
8210 (defun org-update-all-dblocks ()
8211 "Update all dynamic blocks in the buffer.
8212 This function can be used in a hook."
8213 (when (org-mode-p)
8214 (org-map-dblocks 'org-update-dblock)))
8217 ;;;; Completion
8219 (defconst org-additional-option-like-keywords
8220 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8221 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8222 "BEGIN_EXAMPLE" "END_EXAMPLE"
8223 "BEGIN_QUOTE" "END_QUOTE"
8224 "BEGIN_VERSE" "END_VERSE"
8225 "BEGIN_SRC" "END_SRC"
8226 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8228 (defcustom org-structure-template-alist
8230 ("s" "#+begin_src ?\n\n#+end_src"
8231 "<src lang=\"?\">\n\n</src>")
8232 ("e" "#+begin_example\n?\n#+end_example"
8233 "<example>\n?\n</example>")
8234 ("q" "#+begin_quote\n?\n#+end_quote"
8235 "<quote>\n?\n</quote>")
8236 ("v" "#+begin_verse\n?\n#+end_verse"
8237 "<verse>\n?\n/verse>")
8238 ("l" "#+begin_latex\n?\n#+end_latex"
8239 "<literal style=\"latex\">\n?\n</literal>")
8240 ("L" "#+latex: "
8241 "<literal style=\"latex\">?</literal>")
8242 ("h" "#+begin_html\n?\n#+end_html"
8243 "<literal style=\"html\">\n?\n</literal>")
8244 ("H" "#+html: "
8245 "<literal style=\"html\">?</literal>")
8246 ("a" "#+begin_ascii\n?\n#+end_ascii")
8247 ("A" "#+ascii: ")
8248 ("i" "#+include %file ?"
8249 "<include file=%file markup=\"?\">")
8251 "Structure completion elements.
8252 This is a list of abbreviation keys and values. The value gets inserted
8253 it you type @samp{.} followed by the key and then the completion key,
8254 usually `M-TAB'. %file will be replaced by a file name after prompting
8255 for the file using completion.
8256 There are two templates for each key, the first uses the original Org syntax,
8257 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8258 the default when the /org-mtags.el/ module has been loaded. See also the
8259 variable `org-mtags-prefer-muse-templates'.
8260 This is an experimental feature, it is undecided if it is going to stay in."
8261 :group 'org-completion
8262 :type '(repeat
8263 (string :tag "Key")
8264 (string :tag "Template")
8265 (string :tag "Muse Template")))
8267 (defun org-try-structure-completion ()
8268 "Try to complete a structure template before point.
8269 This looks for strings like \"<e\" on an otherwise empty line and
8270 expands them."
8271 (let ((l (buffer-substring (point-at-bol) (point)))
8273 (when (and (looking-at "[ \t]*$")
8274 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8275 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8276 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8277 (match-beginning 1)) a)
8278 t)))
8280 (defun org-complete-expand-structure-template (start cell)
8281 "Expand a structure template."
8282 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8283 (rpl (nth (if musep 2 1) cell)))
8284 (delete-region start (point))
8285 (when (string-match "\\`#\\+" rpl)
8286 (cond
8287 ((bolp))
8288 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8289 (delete-region (point-at-bol) (point)))
8290 (t (newline))))
8291 (setq start (point))
8292 (if (string-match "%file" rpl)
8293 (setq rpl (replace-match
8294 (concat
8295 "\""
8296 (save-match-data
8297 (abbreviate-file-name (read-file-name "Include file: ")))
8298 "\"")
8299 t t rpl)))
8300 (insert rpl)
8301 (if (re-search-backward "\\?" start t) (delete-char 1))))
8304 (defun org-complete (&optional arg)
8305 "Perform completion on word at point.
8306 At the beginning of a headline, this completes TODO keywords as given in
8307 `org-todo-keywords'.
8308 If the current word is preceded by a backslash, completes the TeX symbols
8309 that are supported for HTML support.
8310 If the current word is preceded by \"#+\", completes special words for
8311 setting file options.
8312 In the line after \"#+STARTUP:, complete valid keywords.\"
8313 At all other locations, this simply calls the value of
8314 `org-completion-fallback-command'."
8315 (interactive "P")
8316 (org-without-partial-completion
8317 (catch 'exit
8318 (let* ((a nil)
8319 (end (point))
8320 (beg1 (save-excursion
8321 (skip-chars-backward (org-re "[:alnum:]_@"))
8322 (point)))
8323 (beg (save-excursion
8324 (skip-chars-backward "a-zA-Z0-9_:$")
8325 (point)))
8326 (confirm (lambda (x) (stringp (car x))))
8327 (searchhead (equal (char-before beg) ?*))
8328 (struct
8329 (when (and (member (char-before beg1) '(?. ?<))
8330 (setq a (assoc (buffer-substring beg1 (point))
8331 org-structure-template-alist)))
8332 (org-complete-expand-structure-template (1- beg1) a)
8333 (throw 'exit t)))
8334 (tag (and (equal (char-before beg1) ?:)
8335 (equal (char-after (point-at-bol)) ?*)))
8336 (prop (and (equal (char-before beg1) ?:)
8337 (not (equal (char-after (point-at-bol)) ?*))))
8338 (texp (equal (char-before beg) ?\\))
8339 (link (equal (char-before beg) ?\[))
8340 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8341 beg)
8342 "#+"))
8343 (startup (string-match "^#\\+STARTUP:.*"
8344 (buffer-substring (point-at-bol) (point))))
8345 (completion-ignore-case opt)
8346 (type nil)
8347 (tbl nil)
8348 (table (cond
8349 (opt
8350 (setq type :opt)
8351 (require 'org-exp)
8352 (append
8353 (mapcar
8354 (lambda (x)
8355 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8356 (cons (match-string 2 x) (match-string 1 x)))
8357 (org-split-string (org-get-current-options) "\n"))
8358 (mapcar 'list org-additional-option-like-keywords)))
8359 (startup
8360 (setq type :startup)
8361 org-startup-options)
8362 (link (append org-link-abbrev-alist-local
8363 org-link-abbrev-alist))
8364 (texp
8365 (setq type :tex)
8366 org-html-entities)
8367 ((string-match "\\`\\*+[ \t]+\\'"
8368 (buffer-substring (point-at-bol) beg))
8369 (setq type :todo)
8370 (mapcar 'list org-todo-keywords-1))
8371 (searchhead
8372 (setq type :searchhead)
8373 (save-excursion
8374 (goto-char (point-min))
8375 (while (re-search-forward org-todo-line-regexp nil t)
8376 (push (list
8377 (org-make-org-heading-search-string
8378 (match-string 3) t))
8379 tbl)))
8380 tbl)
8381 (tag (setq type :tag beg beg1)
8382 (or org-tag-alist (org-get-buffer-tags)))
8383 (prop (setq type :prop beg beg1)
8384 (mapcar 'list (org-buffer-property-keys nil t t)))
8385 (t (progn
8386 (call-interactively org-completion-fallback-command)
8387 (throw 'exit nil)))))
8388 (pattern (buffer-substring-no-properties beg end))
8389 (completion (try-completion pattern table confirm)))
8390 (cond ((eq completion t)
8391 (if (not (assoc (upcase pattern) table))
8392 (message "Already complete")
8393 (if (and (equal type :opt)
8394 (not (member (car (assoc (upcase pattern) table))
8395 org-additional-option-like-keywords)))
8396 (insert (substring (cdr (assoc (upcase pattern) table))
8397 (length pattern)))
8398 (if (memq type '(:tag :prop)) (insert ":")))))
8399 ((null completion)
8400 (message "Can't find completion for \"%s\"" pattern)
8401 (ding))
8402 ((not (string= pattern completion))
8403 (delete-region beg end)
8404 (if (string-match " +$" completion)
8405 (setq completion (replace-match "" t t completion)))
8406 (insert completion)
8407 (if (get-buffer-window "*Completions*")
8408 (delete-window (get-buffer-window "*Completions*")))
8409 (if (assoc completion table)
8410 (if (eq type :todo) (insert " ")
8411 (if (memq type '(:tag :prop)) (insert ":"))))
8412 (if (and (equal type :opt) (assoc completion table))
8413 (message "%s" (substitute-command-keys
8414 "Press \\[org-complete] again to insert example settings"))))
8416 (message "Making completion list...")
8417 (let ((list (sort (all-completions pattern table confirm)
8418 'string<)))
8419 (with-output-to-temp-buffer "*Completions*"
8420 (condition-case nil
8421 ;; Protection needed for XEmacs and emacs 21
8422 (display-completion-list list pattern)
8423 (error (display-completion-list list)))))
8424 (message "Making completion list...%s" "done")))))))
8426 ;;;; TODO, DEADLINE, Comments
8428 (defun org-toggle-comment ()
8429 "Change the COMMENT state of an entry."
8430 (interactive)
8431 (save-excursion
8432 (org-back-to-heading)
8433 (let (case-fold-search)
8434 (if (looking-at (concat outline-regexp
8435 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8436 (replace-match "" t t nil 1)
8437 (if (looking-at outline-regexp)
8438 (progn
8439 (goto-char (match-end 0))
8440 (insert org-comment-string " ")))))))
8442 (defvar org-last-todo-state-is-todo nil
8443 "This is non-nil when the last TODO state change led to a TODO state.
8444 If the last change removed the TODO tag or switched to DONE, then
8445 this is nil.")
8447 (defvar org-setting-tags nil) ; dynamically skipped
8449 (defun org-parse-local-options (string var)
8450 "Parse STRING for startup setting relevant for variable VAR."
8451 (let ((rtn (symbol-value var))
8452 e opts)
8453 (save-match-data
8454 (if (or (not string) (not (string-match "\\S-" string)))
8456 (setq opts (delq nil (mapcar (lambda (x)
8457 (setq e (assoc x org-startup-options))
8458 (if (eq (nth 1 e) var) e nil))
8459 (org-split-string string "[ \t]+"))))
8460 (if (not opts)
8462 (setq rtn nil)
8463 (while (setq e (pop opts))
8464 (if (not (nth 3 e))
8465 (setq rtn (nth 2 e))
8466 (if (not (listp rtn)) (setq rtn nil))
8467 (push (nth 2 e) rtn)))
8468 rtn)))))
8470 (defvar org-todo-setup-filter-hook nil
8471 "Hook for functions that pre-filter todo specs.
8473 Each function takes a todo spec and returns either `nil' or the spec
8474 transformed into canonical form." )
8476 (defvar org-todo-get-default-hook nil
8477 "Hook for functions that get a default item for todo.
8479 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8480 `nil' or a string to be used for the todo mark." )
8482 (defvar org-agenda-headline-snapshot-before-repeat)
8483 (defun org-todo (&optional arg)
8484 "Change the TODO state of an item.
8485 The state of an item is given by a keyword at the start of the heading,
8486 like
8487 *** TODO Write paper
8488 *** DONE Call mom
8490 The different keywords are specified in the variable `org-todo-keywords'.
8491 By default the available states are \"TODO\" and \"DONE\".
8492 So for this example: when the item starts with TODO, it is changed to DONE.
8493 When it starts with DONE, the DONE is removed. And when neither TODO nor
8494 DONE are present, add TODO at the beginning of the heading.
8496 With C-u prefix arg, use completion to determine the new state.
8497 With numeric prefix arg, switch to that state.
8498 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8499 With a tripple C-u prefix, circumvent any state blocking.
8501 For calling through lisp, arg is also interpreted in the following way:
8502 'none -> empty state
8503 \"\"(empty string) -> switch to empty state
8504 'done -> switch to DONE
8505 'nextset -> switch to the next set of keywords
8506 'previousset -> switch to the previous set of keywords
8507 \"WAITING\" -> switch to the specified keyword, but only if it
8508 really is a member of `org-todo-keywords'."
8509 (interactive "P")
8510 (if (equal arg '(16)) (setq arg 'nextset))
8511 (let ((org-blocker-hook org-blocker-hook))
8512 (when (equal arg '(64))
8513 (setq arg nil org-blocker-hook nil))
8514 (save-excursion
8515 (catch 'exit
8516 (org-back-to-heading)
8517 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8518 (or (looking-at (concat " +" org-todo-regexp " *"))
8519 (looking-at " *"))
8520 (let* ((match-data (match-data))
8521 (startpos (point-at-bol))
8522 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8523 (org-log-done org-log-done)
8524 (org-log-repeat org-log-repeat)
8525 (org-todo-log-states org-todo-log-states)
8526 (this (match-string 1))
8527 (hl-pos (match-beginning 0))
8528 (head (org-get-todo-sequence-head this))
8529 (ass (assoc head org-todo-kwd-alist))
8530 (interpret (nth 1 ass))
8531 (done-word (nth 3 ass))
8532 (final-done-word (nth 4 ass))
8533 (last-state (or this ""))
8534 (completion-ignore-case t)
8535 (member (member this org-todo-keywords-1))
8536 (tail (cdr member))
8537 (state (cond
8538 ((and org-todo-key-trigger
8539 (or (and (equal arg '(4))
8540 (eq org-use-fast-todo-selection 'prefix))
8541 (and (not arg) org-use-fast-todo-selection
8542 (not (eq org-use-fast-todo-selection
8543 'prefix)))))
8544 ;; Use fast selection
8545 (org-fast-todo-selection))
8546 ((and (equal arg '(4))
8547 (or (not org-use-fast-todo-selection)
8548 (not org-todo-key-trigger)))
8549 ;; Read a state with completion
8550 (org-ido-completing-read
8551 "State: " (mapcar (lambda(x) (list x))
8552 org-todo-keywords-1)
8553 nil t))
8554 ((eq arg 'right)
8555 (if this
8556 (if tail (car tail) nil)
8557 (car org-todo-keywords-1)))
8558 ((eq arg 'left)
8559 (if (equal member org-todo-keywords-1)
8561 (if this
8562 (nth (- (length org-todo-keywords-1)
8563 (length tail) 2)
8564 org-todo-keywords-1)
8565 (org-last org-todo-keywords-1))))
8566 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8567 (setq arg nil))) ; hack to fall back to cycling
8568 (arg
8569 ;; user or caller requests a specific state
8570 (cond
8571 ((equal arg "") nil)
8572 ((eq arg 'none) nil)
8573 ((eq arg 'done) (or done-word (car org-done-keywords)))
8574 ((eq arg 'nextset)
8575 (or (car (cdr (member head org-todo-heads)))
8576 (car org-todo-heads)))
8577 ((eq arg 'previousset)
8578 (let ((org-todo-heads (reverse org-todo-heads)))
8579 (or (car (cdr (member head org-todo-heads)))
8580 (car org-todo-heads))))
8581 ((car (member arg org-todo-keywords-1)))
8582 ((nth (1- (prefix-numeric-value arg))
8583 org-todo-keywords-1))))
8584 ((null member) (or head (car org-todo-keywords-1)))
8585 ((equal this final-done-word) nil) ;; -> make empty
8586 ((null tail) nil) ;; -> first entry
8587 ((memq interpret '(type priority))
8588 (if (eq this-command last-command)
8589 (car tail)
8590 (if (> (length tail) 0)
8591 (or done-word (car org-done-keywords))
8592 nil)))
8594 (car tail))))
8595 (state (or
8596 (run-hook-with-args-until-success
8597 'org-todo-get-default-hook state last-state)
8598 state))
8599 (next (if state (concat " " state " ") " "))
8600 (change-plist (list :type 'todo-state-change :from this :to state
8601 :position startpos))
8602 dolog now-done-p)
8603 (when org-blocker-hook
8604 (setq org-last-todo-state-is-todo
8605 (not (member this org-done-keywords)))
8606 (unless (save-excursion
8607 (save-match-data
8608 (run-hook-with-args-until-failure
8609 'org-blocker-hook change-plist)))
8610 (if (interactive-p)
8611 (error "TODO state change from %s to %s blocked" this state)
8612 ;; fail silently
8613 (message "TODO state change from %s to %s blocked" this state)
8614 (throw 'exit nil))))
8615 (store-match-data match-data)
8616 (replace-match next t t)
8617 (unless (pos-visible-in-window-p hl-pos)
8618 (message "TODO state changed to %s" (org-trim next)))
8619 (unless head
8620 (setq head (org-get-todo-sequence-head state)
8621 ass (assoc head org-todo-kwd-alist)
8622 interpret (nth 1 ass)
8623 done-word (nth 3 ass)
8624 final-done-word (nth 4 ass)))
8625 (when (memq arg '(nextset previousset))
8626 (message "Keyword-Set %d/%d: %s"
8627 (- (length org-todo-sets) -1
8628 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8629 (length org-todo-sets)
8630 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8631 (setq org-last-todo-state-is-todo
8632 (not (member state org-done-keywords)))
8633 (setq now-done-p (and (member state org-done-keywords)
8634 (not (member this org-done-keywords))))
8635 (and logging (org-local-logging logging))
8636 (when (and (or org-todo-log-states org-log-done)
8637 (not (memq arg '(nextset previousset))))
8638 ;; we need to look at recording a time and note
8639 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8640 (nth 2 (assoc this org-todo-log-states))))
8641 (when (and state
8642 (member state org-not-done-keywords)
8643 (not (member this org-not-done-keywords)))
8644 ;; This is now a todo state and was not one before
8645 ;; If there was a CLOSED time stamp, get rid of it.
8646 (org-add-planning-info nil nil 'closed))
8647 (when (and now-done-p org-log-done)
8648 ;; It is now done, and it was not done before
8649 (org-add-planning-info 'closed (org-current-time))
8650 (if (and (not dolog) (eq 'note org-log-done))
8651 (org-add-log-setup 'done state this 'findpos 'note)))
8652 (when (and state dolog)
8653 ;; This is a non-nil state, and we need to log it
8654 (org-add-log-setup 'state state this 'findpos dolog)))
8655 ;; Fixup tag positioning
8656 (org-todo-trigger-tag-changes state)
8657 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8658 (when org-provide-todo-statistics
8659 (org-update-parent-todo-statistics))
8660 (run-hooks 'org-after-todo-state-change-hook)
8661 (if (and arg (not (member state org-done-keywords)))
8662 (setq head (org-get-todo-sequence-head state)))
8663 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8664 ;; Do we need to trigger a repeat?
8665 (when now-done-p
8666 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8667 ;; This is for the agenda, take a snapshot of the headline.
8668 (save-match-data
8669 (setq org-agenda-headline-snapshot-before-repeat
8670 (org-get-heading))))
8671 (org-auto-repeat-maybe state))
8672 ;; Fixup cursor location if close to the keyword
8673 (if (and (outline-on-heading-p)
8674 (not (bolp))
8675 (save-excursion (beginning-of-line 1)
8676 (looking-at org-todo-line-regexp))
8677 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8678 (progn
8679 (goto-char (or (match-end 2) (match-end 1)))
8680 (just-one-space)))
8681 (when org-trigger-hook
8682 (save-excursion
8683 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8685 (defun org-block-todo-from-children-or-siblings (change-plist)
8686 "Block turning an entry into a TODO, using the hierarchy.
8687 This checks whether the current task should be blocked from state
8688 changes. Such blocking occurs when:
8690 1. The task has children which are not all in a completed state.
8692 2. A task has a parent with the property :ORDERED:, and there
8693 are siblings prior to the current task with incomplete
8694 status."
8695 (catch 'dont-block
8696 ;; If this is not a todo state change, or if this entry is already DONE,
8697 ;; do not block
8698 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8699 (member (plist-get change-plist :from)
8700 (cons 'done org-done-keywords))
8701 (member (plist-get change-plist :to)
8702 (cons 'todo org-not-done-keywords)))
8703 (throw 'dont-block t))
8704 ;; If this task has children, and any are undone, it's blocked
8705 (save-excursion
8706 (org-back-to-heading t)
8707 (let ((this-level (funcall outline-level)))
8708 (outline-next-heading)
8709 (let ((child-level (funcall outline-level)))
8710 (while (and (not (eobp))
8711 (> child-level this-level))
8712 ;; this todo has children, check whether they are all
8713 ;; completed
8714 (if (and (not (org-entry-is-done-p))
8715 (org-entry-is-todo-p))
8716 (throw 'dont-block nil))
8717 (outline-next-heading)
8718 (setq child-level (funcall outline-level))))))
8719 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8720 ;; any previous siblings are undone, it's blocked
8721 (save-excursion
8722 (org-back-to-heading t)
8723 (when (save-excursion
8724 (ignore-errors
8725 (org-up-heading-all 1)
8726 (org-entry-get (point) "ORDERED")))
8727 (let* ((this-level (funcall outline-level))
8728 (current-level this-level))
8729 (while (and (not (bobp))
8730 (= current-level this-level))
8731 (outline-previous-heading)
8732 (setq current-level (funcall outline-level))
8733 (if (= current-level this-level)
8734 ;; this todo has children, check whether they are all
8735 ;; completed
8736 (if (and (not (org-entry-is-done-p))
8737 (org-entry-is-todo-p))
8738 (throw 'dont-block nil)))))))
8739 t)) ; don't block
8741 (defcustom org-track-ordered-property-with-tag nil
8742 "Should the ORDERED property also be shown as a tag?
8743 The ORDERED property decides if an entry should require subtasks to be
8744 completed in sequence. Since a property is not very visible, setting
8745 this option means that toggling the ORDERED property with the command
8746 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8747 not relevant for the behavior, but it makes things more visible.
8749 Note that toggling the tag with tags commands will not change the property
8750 and therefore not influence behavior!
8752 This can be t, meaning the tag ORDERED should be used, It can also be a
8753 string to select a different tag for this task."
8754 :group 'org-todo
8755 :type '(choice
8756 (const :tag "No tracking" nil)
8757 (const :tag "Track with ORDERED tag" t)
8758 (string :tag "Use other tag")))
8760 (defun org-toggle-ordered-property ()
8761 "Toggle the ORDERED property of the current entry.
8762 For better visibility, you can track the value of this property with a tag.
8763 See variable `org-track-ordered-property-with-tag'."
8764 (interactive)
8765 (let* ((t1 org-track-ordered-property-with-tag)
8766 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8767 (save-excursion
8768 (org-back-to-heading)
8769 (if (org-entry-get nil "ORDERED")
8770 (progn
8771 (org-delete-property "ORDERED")
8772 (and tag (org-toggle-tag tag 'off))
8773 (message "Subtasks can be completed in arbitrary order"))
8774 (org-entry-put nil "ORDERED" "t")
8775 (and tag (org-toggle-tag tag 'on))
8776 (message "Subtasks must be completed in sequence")))))
8778 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8779 (defun org-block-todo-from-checkboxes (change-plist)
8780 "Block turning an entry into a TODO, using checkboxes.
8781 This checks whether the current task should be blocked from state
8782 changes because there are uncheckd boxes in this entry."
8783 (catch 'dont-block
8784 ;; If this is not a todo state change, or if this entry is already DONE,
8785 ;; do not block
8786 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8787 (member (plist-get change-plist :from)
8788 (cons 'done org-done-keywords))
8789 (member (plist-get change-plist :to)
8790 (cons 'todo org-not-done-keywords)))
8791 (throw 'dont-block t))
8792 ;; If this task has checkboxes that are not checked, it's blocked
8793 (save-excursion
8794 (org-back-to-heading t)
8795 (let ((beg (point)) end)
8796 (outline-next-heading)
8797 (setq end (point))
8798 (goto-char beg)
8799 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8800 end t)
8801 (progn
8802 (if (boundp 'org-blocked-by-checkboxes)
8803 (setq org-blocked-by-checkboxes t))
8804 (throw 'dont-block nil)))))
8805 t)) ; do not block
8807 (defun org-update-parent-todo-statistics ()
8808 "Update any statistics cookie in the parent of the current headline."
8809 (interactive)
8810 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8811 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8812 (catch 'exit
8813 (save-excursion
8814 (setq level (org-up-heading-safe))
8815 (unless level
8816 (throw 'exit nil))
8817 (while (re-search-forward box-re (point-at-eol) t)
8818 (setq cnt-all 0 cnt-done 0 cookie-present t)
8819 (setq is-percent (match-end 2))
8820 (save-match-data
8821 (unless (outline-next-heading) (throw 'exit nil))
8822 (while (looking-at org-todo-line-regexp)
8823 (setq kwd (match-string 2))
8824 (and kwd (setq cnt-all (1+ cnt-all)))
8825 (and (member kwd org-done-keywords)
8826 (setq cnt-done (1+ cnt-done)))
8827 (condition-case nil
8828 (org-forward-same-level 1)
8829 (error (end-of-line 1)))))
8830 (replace-match
8831 (if is-percent
8832 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8833 (format "[%d/%d]" cnt-done cnt-all))))
8834 (when cookie-present
8835 (run-hook-with-args 'org-after-todo-statistics-hook
8836 cnt-done (- cnt-all cnt-done)))))))
8838 (defvar org-after-todo-statistics-hook nil
8839 "Hook that is called after a TODO statistics cookie has been updated.
8840 Each function is called with two arguments: the number of not-done entries
8841 and the number of done entries.
8843 For example, the following function, when added to this hook, will switch
8844 an entry to DONE when all children are done, and back to TODO when new
8845 entries are set to a TODO status. Note that this hook is only called
8846 when there is a statistics cookie in the headline!
8848 (defun org-summary-todo (n-done n-not-done)
8849 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8850 (let (org-log-done org-log-states) ; turn off logging
8851 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8854 (defun org-todo-trigger-tag-changes (state)
8855 "Apply the changes defined in `org-todo-state-tags-triggers'."
8856 (let ((l org-todo-state-tags-triggers)
8857 changes)
8858 (when (or (not state) (equal state ""))
8859 (setq changes (append changes (cdr (assoc "" l)))))
8860 (when (and (stringp state) (> (length state) 0))
8861 (setq changes (append changes (cdr (assoc state l)))))
8862 (when (member state org-not-done-keywords)
8863 (setq changes (append changes (cdr (assoc 'todo l)))))
8864 (when (member state org-done-keywords)
8865 (setq changes (append changes (cdr (assoc 'done l)))))
8866 (dolist (c changes)
8867 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8869 (defun org-local-logging (value)
8870 "Get logging settings from a property VALUE."
8871 (let* (words w a)
8872 ;; directly set the variables, they are already local.
8873 (setq org-log-done nil
8874 org-log-repeat nil
8875 org-todo-log-states nil)
8876 (setq words (org-split-string value))
8877 (while (setq w (pop words))
8878 (cond
8879 ((setq a (assoc w org-startup-options))
8880 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8881 (set (nth 1 a) (nth 2 a))))
8882 ((setq a (org-extract-log-state-settings w))
8883 (and (member (car a) org-todo-keywords-1)
8884 (push a org-todo-log-states)))))))
8886 (defun org-get-todo-sequence-head (kwd)
8887 "Return the head of the TODO sequence to which KWD belongs.
8888 If KWD is not set, check if there is a text property remembering the
8889 right sequence."
8890 (let (p)
8891 (cond
8892 ((not kwd)
8893 (or (get-text-property (point-at-bol) 'org-todo-head)
8894 (progn
8895 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8896 nil (point-at-eol)))
8897 (get-text-property p 'org-todo-head))))
8898 ((not (member kwd org-todo-keywords-1))
8899 (car org-todo-keywords-1))
8900 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8902 (defun org-fast-todo-selection ()
8903 "Fast TODO keyword selection with single keys.
8904 Returns the new TODO keyword, or nil if no state change should occur."
8905 (let* ((fulltable org-todo-key-alist)
8906 (done-keywords org-done-keywords) ;; needed for the faces.
8907 (maxlen (apply 'max (mapcar
8908 (lambda (x)
8909 (if (stringp (car x)) (string-width (car x)) 0))
8910 fulltable)))
8911 (expert nil)
8912 (fwidth (+ maxlen 3 1 3))
8913 (ncol (/ (- (window-width) 4) fwidth))
8914 tg cnt e c tbl
8915 groups ingroup)
8916 (save-excursion
8917 (save-window-excursion
8918 (if expert
8919 (set-buffer (get-buffer-create " *Org todo*"))
8920 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8921 (erase-buffer)
8922 (org-set-local 'org-done-keywords done-keywords)
8923 (setq tbl fulltable cnt 0)
8924 (while (setq e (pop tbl))
8925 (cond
8926 ((equal e '(:startgroup))
8927 (push '() groups) (setq ingroup t)
8928 (when (not (= cnt 0))
8929 (setq cnt 0)
8930 (insert "\n"))
8931 (insert "{ "))
8932 ((equal e '(:endgroup))
8933 (setq ingroup nil cnt 0)
8934 (insert "}\n"))
8935 ((equal e '(:newline))
8936 (insert "\n "))
8938 (setq tg (car e) c (cdr e))
8939 (if ingroup (push tg (car groups)))
8940 (setq tg (org-add-props tg nil 'face
8941 (org-get-todo-face tg)))
8942 (if (and (= cnt 0) (not ingroup)) (insert " "))
8943 (insert "[" c "] " tg (make-string
8944 (- fwidth 4 (length tg)) ?\ ))
8945 (when (= (setq cnt (1+ cnt)) ncol)
8946 (insert "\n")
8947 (if ingroup (insert " "))
8948 (setq cnt 0)))))
8949 (insert "\n")
8950 (goto-char (point-min))
8951 (if (not expert) (org-fit-window-to-buffer))
8952 (message "[a-z..]:Set [SPC]:clear")
8953 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8954 (cond
8955 ((or (= c ?\C-g)
8956 (and (= c ?q) (not (rassoc c fulltable))))
8957 (setq quit-flag t))
8958 ((= c ?\ ) nil)
8959 ((setq e (rassoc c fulltable) tg (car e))
8961 (t (setq quit-flag t)))))))
8963 (defun org-entry-is-todo-p ()
8964 (member (org-get-todo-state) org-not-done-keywords))
8966 (defun org-entry-is-done-p ()
8967 (member (org-get-todo-state) org-done-keywords))
8969 (defun org-get-todo-state ()
8970 (save-excursion
8971 (org-back-to-heading t)
8972 (and (looking-at org-todo-line-regexp)
8973 (match-end 2)
8974 (match-string 2))))
8976 (defun org-at-date-range-p (&optional inactive-ok)
8977 "Is the cursor inside a date range?"
8978 (interactive)
8979 (save-excursion
8980 (catch 'exit
8981 (let ((pos (point)))
8982 (skip-chars-backward "^[<\r\n")
8983 (skip-chars-backward "<[")
8984 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8985 (>= (match-end 0) pos)
8986 (throw 'exit t))
8987 (skip-chars-backward "^<[\r\n")
8988 (skip-chars-backward "<[")
8989 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8990 (>= (match-end 0) pos)
8991 (throw 'exit t)))
8992 nil)))
8994 (defun org-get-repeat ()
8995 "Check if there is a deadline/schedule with repeater in this entry."
8996 (save-match-data
8997 (save-excursion
8998 (org-back-to-heading t)
8999 (if (re-search-forward
9000 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9001 (match-string 1)))))
9003 (defvar org-last-changed-timestamp)
9004 (defvar org-last-inserted-timestamp)
9005 (defvar org-log-post-message)
9006 (defvar org-log-note-purpose)
9007 (defvar org-log-note-how)
9008 (defvar org-log-note-extra)
9009 (defun org-auto-repeat-maybe (done-word)
9010 "Check if the current headline contains a repeated deadline/schedule.
9011 If yes, set TODO state back to what it was and change the base date
9012 of repeating deadline/scheduled time stamps to new date.
9013 This function is run automatically after each state change to a DONE state."
9014 ;; last-state is dynamically scoped into this function
9015 (let* ((repeat (org-get-repeat))
9016 (aa (assoc last-state org-todo-kwd-alist))
9017 (interpret (nth 1 aa))
9018 (head (nth 2 aa))
9019 (whata '(("d" . day) ("m" . month) ("y" . year)))
9020 (msg "Entry repeats: ")
9021 (org-log-done nil)
9022 (org-todo-log-states nil)
9023 (nshiftmax 10) (nshift 0)
9024 re type n what ts time)
9025 (when repeat
9026 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9027 (org-todo (if (eq interpret 'type) last-state head))
9028 (when org-log-repeat
9029 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9030 (memq 'org-add-log-note post-command-hook))
9031 ;; OK, we are already setup for some record
9032 (if (eq org-log-repeat 'note)
9033 ;; make sure we take a note, not only a time stamp
9034 (setq org-log-note-how 'note))
9035 ;; Set up for taking a record
9036 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9037 last-state
9038 'findpos org-log-repeat)))
9039 (org-back-to-heading t)
9040 (org-add-planning-info nil nil 'closed)
9041 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9042 org-deadline-time-regexp "\\)\\|\\("
9043 org-ts-regexp "\\)"))
9044 (while (re-search-forward
9045 re (save-excursion (outline-next-heading) (point)) t)
9046 (setq type (if (match-end 1) org-scheduled-string
9047 (if (match-end 3) org-deadline-string "Plain:"))
9048 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9049 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9050 (setq n (string-to-number (match-string 2 ts))
9051 what (match-string 3 ts))
9052 (if (equal what "w") (setq n (* n 7) what "d"))
9053 ;; Preparation, see if we need to modify the start date for the change
9054 (when (match-end 1)
9055 (setq time (save-match-data (org-time-string-to-time ts)))
9056 (cond
9057 ((equal (match-string 1 ts) ".")
9058 ;; Shift starting date to today
9059 (org-timestamp-change
9060 (- (time-to-days (current-time)) (time-to-days time))
9061 'day))
9062 ((equal (match-string 1 ts) "+")
9063 (while (or (= nshift 0)
9064 (<= (time-to-days time) (time-to-days (current-time))))
9065 (when (= (incf nshift) nshiftmax)
9066 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9067 (error "Abort")))
9068 (org-timestamp-change n (cdr (assoc what whata)))
9069 (org-at-timestamp-p t)
9070 (setq ts (match-string 1))
9071 (setq time (save-match-data (org-time-string-to-time ts))))
9072 (org-timestamp-change (- n) (cdr (assoc what whata)))
9073 ;; rematch, so that we have everything in place for the real shift
9074 (org-at-timestamp-p t)
9075 (setq ts (match-string 1))
9076 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9077 (org-timestamp-change n (cdr (assoc what whata)))
9078 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9079 (setq org-log-post-message msg)
9080 (message "%s" msg))))
9082 (defun org-show-todo-tree (arg)
9083 "Make a compact tree which shows all headlines marked with TODO.
9084 The tree will show the lines where the regexp matches, and all higher
9085 headlines above the match.
9086 With a \\[universal-argument] prefix, also show the DONE entries.
9087 With a numeric prefix N, construct a sparse tree for the Nth element
9088 of `org-todo-keywords-1'."
9089 (interactive "P")
9090 (let ((case-fold-search nil)
9091 (kwd-re
9092 (cond ((null arg) org-not-done-regexp)
9093 ((equal arg '(4))
9094 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9095 (mapcar 'list org-todo-keywords-1))))
9096 (concat "\\("
9097 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9098 "\\)\\>")))
9099 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9100 (regexp-quote (nth (1- (prefix-numeric-value arg))
9101 org-todo-keywords-1)))
9102 (t (error "Invalid prefix argument: %s" arg)))))
9103 (message "%d TODO entries found"
9104 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9106 (defun org-deadline (&optional remove time)
9107 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9108 With argument REMOVE, remove any deadline from the item.
9109 When TIME is set, it should be an internal time specification, and the
9110 scheduling will use the corresponding date."
9111 (interactive "P")
9112 (if remove
9113 (progn
9114 (org-remove-timestamp-with-keyword org-deadline-string)
9115 (message "Item no longer has a deadline."))
9116 (if (org-get-repeat)
9117 (error "Cannot change deadline on task with repeater, please do that by hand")
9118 (org-add-planning-info 'deadline time 'closed)
9119 (message "Deadline on %s" org-last-inserted-timestamp))))
9121 (defun org-schedule (&optional remove time)
9122 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9123 With argument REMOVE, remove any scheduling date from the item.
9124 When TIME is set, it should be an internal time specification, and the
9125 scheduling will use the corresponding date."
9126 (interactive "P")
9127 (if remove
9128 (progn
9129 (org-remove-timestamp-with-keyword org-scheduled-string)
9130 (message "Item is no longer scheduled."))
9131 (if (org-get-repeat)
9132 (error "Cannot reschedule task with repeater, please do that by hand")
9133 (org-add-planning-info 'scheduled time 'closed)
9134 (message "Scheduled to %s" org-last-inserted-timestamp))))
9136 (defun org-get-scheduled-time (pom &optional inherit)
9137 "Get the scheduled time as a time tuple, of a format suitable
9138 for calling org-schedule with, or if there is no scheduling,
9139 returns nil."
9140 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9141 (when time
9142 (apply 'encode-time (org-parse-time-string time)))))
9144 (defun org-get-deadline-time (pom &optional inherit)
9145 "Get the deadine as a time tuple, of a format suitable for
9146 calling org-deadlin with, or if there is no scheduling, returns
9147 nil."
9148 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9149 (when time
9150 (apply 'encode-time (org-parse-time-string time)))))
9152 (defun org-remove-timestamp-with-keyword (keyword)
9153 "Remove all time stamps with KEYWORD in the current entry."
9154 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9155 beg)
9156 (save-excursion
9157 (org-back-to-heading t)
9158 (setq beg (point))
9159 (org-end-of-subtree t t)
9160 (while (re-search-backward re beg t)
9161 (replace-match "")
9162 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9163 (equal (char-before) ?\ ))
9164 (backward-delete-char 1)
9165 (if (string-match "^[ \t]*$" (buffer-substring
9166 (point-at-bol) (point-at-eol)))
9167 (delete-region (point-at-bol)
9168 (min (point-max) (1+ (point-at-eol))))))))))
9170 (defun org-add-planning-info (what &optional time &rest remove)
9171 "Insert new timestamp with keyword in the line directly after the headline.
9172 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9173 If non is given, the user is prompted for a date.
9174 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9175 be removed."
9176 (interactive)
9177 (let (org-time-was-given org-end-time-was-given ts
9178 end default-time default-input)
9180 (when (and (not time) (memq what '(scheduled deadline)))
9181 ;; Try to get a default date/time from existing timestamp
9182 (save-excursion
9183 (org-back-to-heading t)
9184 (setq end (save-excursion (outline-next-heading) (point)))
9185 (when (re-search-forward (if (eq what 'scheduled)
9186 org-scheduled-time-regexp
9187 org-deadline-time-regexp)
9188 end t)
9189 (setq ts (match-string 1)
9190 default-time
9191 (apply 'encode-time (org-parse-time-string ts))
9192 default-input (and ts (org-get-compact-tod ts))))))
9193 (when what
9194 ;; If necessary, get the time from the user
9195 (setq time (or time (org-read-date nil 'to-time nil nil
9196 default-time default-input))))
9198 (when (and org-insert-labeled-timestamps-at-point
9199 (member what '(scheduled deadline)))
9200 (insert
9201 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9202 (org-insert-time-stamp time org-time-was-given
9203 nil nil nil (list org-end-time-was-given))
9204 (setq what nil))
9205 (save-excursion
9206 (save-restriction
9207 (let (col list elt ts buffer-invisibility-spec)
9208 (org-back-to-heading t)
9209 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9210 (goto-char (match-end 1))
9211 (setq col (current-column))
9212 (goto-char (match-end 0))
9213 (if (eobp) (insert "\n") (forward-char 1))
9214 (if (and (not (looking-at outline-regexp))
9215 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9216 "[^\r\n]*"))
9217 (not (equal (match-string 1) org-clock-string)))
9218 (narrow-to-region (match-beginning 0) (match-end 0))
9219 (insert-before-markers "\n")
9220 (backward-char 1)
9221 (narrow-to-region (point) (point))
9222 (and org-adapt-indentation (org-indent-to-column col)))
9223 ;; Check if we have to remove something.
9224 (setq list (cons what remove))
9225 (while list
9226 (setq elt (pop list))
9227 (goto-char (point-min))
9228 (when (or (and (eq elt 'scheduled)
9229 (re-search-forward org-scheduled-time-regexp nil t))
9230 (and (eq elt 'deadline)
9231 (re-search-forward org-deadline-time-regexp nil t))
9232 (and (eq elt 'closed)
9233 (re-search-forward org-closed-time-regexp nil t)))
9234 (replace-match "")
9235 (if (looking-at "--+<[^>]+>") (replace-match ""))
9236 (if (looking-at " +") (replace-match ""))))
9237 (goto-char (point-max))
9238 (when what
9239 (insert
9240 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9241 (cond ((eq what 'scheduled) org-scheduled-string)
9242 ((eq what 'deadline) org-deadline-string)
9243 ((eq what 'closed) org-closed-string))
9244 " ")
9245 (setq ts (org-insert-time-stamp
9246 time
9247 (or org-time-was-given
9248 (and (eq what 'closed) org-log-done-with-time))
9249 (eq what 'closed)
9250 nil nil (list org-end-time-was-given)))
9251 (end-of-line 1))
9252 (goto-char (point-min))
9253 (widen)
9254 (if (and (looking-at "[ \t]+\n")
9255 (equal (char-before) ?\n))
9256 (delete-region (1- (point)) (point-at-eol)))
9257 ts)))))
9259 (defvar org-log-note-marker (make-marker))
9260 (defvar org-log-note-purpose nil)
9261 (defvar org-log-note-state nil)
9262 (defvar org-log-note-previous-state nil)
9263 (defvar org-log-note-how nil)
9264 (defvar org-log-note-extra nil)
9265 (defvar org-log-note-window-configuration nil)
9266 (defvar org-log-note-return-to (make-marker))
9267 (defvar org-log-post-message nil
9268 "Message to be displayed after a log note has been stored.
9269 The auto-repeater uses this.")
9271 (defun org-add-note ()
9272 "Add a note to the current entry.
9273 This is done in the same way as adding a state change note."
9274 (interactive)
9275 (org-add-log-setup 'note nil nil 'findpos nil))
9277 (defvar org-property-end-re)
9278 (defun org-add-log-setup (&optional purpose state prev-state
9279 findpos how &optional extra)
9280 "Set up the post command hook to take a note.
9281 If this is about to TODO state change, the new state is expected in STATE.
9282 When FINDPOS is non-nil, find the correct position for the note in
9283 the current entry. If not, assume that it can be inserted at point.
9284 HOW is an indicator what kind of note should be created.
9285 EXTRA is additional text that will be inserted into the notes buffer."
9286 (let ((drawer (cond ((stringp org-log-into-drawer)
9287 org-log-into-drawer)
9288 (org-log-into-drawer "LOGBOOK")
9289 (t nil))))
9290 (save-restriction
9291 (save-excursion
9292 (when findpos
9293 (org-back-to-heading t)
9294 (narrow-to-region (point) (save-excursion
9295 (outline-next-heading) (point)))
9296 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9297 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9298 "[^\r\n]*\\)?"))
9299 (goto-char (match-end 0))
9300 (cond
9301 (drawer
9302 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9303 nil t)
9304 (progn
9305 (goto-char (match-end 0))
9306 (or org-log-states-order-reversed
9307 (and (re-search-forward org-property-end-re nil t)
9308 (goto-char (1- (match-beginning 0))))))
9309 (insert "\n:" drawer ":\n:END:")
9310 (beginning-of-line 0)
9311 (org-indent-line-function)
9312 (beginning-of-line 2)
9313 (org-indent-line-function)
9314 (end-of-line 0)))
9315 ((and org-log-state-notes-insert-after-drawers
9316 (save-excursion
9317 (forward-line) (looking-at org-drawer-regexp)))
9318 (forward-line)
9319 (while (looking-at org-drawer-regexp)
9320 (goto-char (match-end 0))
9321 (re-search-forward org-property-end-re (point-max) t)
9322 (forward-line))
9323 (forward-line -1)))
9324 (unless org-log-states-order-reversed
9325 (and (= (char-after) ?\n) (forward-char 1))
9326 (org-skip-over-state-notes)
9327 (skip-chars-backward " \t\n\r")))
9328 (move-marker org-log-note-marker (point))
9329 (setq org-log-note-purpose purpose
9330 org-log-note-state state
9331 org-log-note-previous-state prev-state
9332 org-log-note-how how
9333 org-log-note-extra extra)
9334 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9336 (defun org-skip-over-state-notes ()
9337 "Skip past the list of State notes in an entry."
9338 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9339 (while (looking-at "[ \t]*- State")
9340 (condition-case nil
9341 (org-next-item)
9342 (error (org-end-of-item)))))
9344 (defun org-add-log-note (&optional purpose)
9345 "Pop up a window for taking a note, and add this note later at point."
9346 (remove-hook 'post-command-hook 'org-add-log-note)
9347 (setq org-log-note-window-configuration (current-window-configuration))
9348 (delete-other-windows)
9349 (move-marker org-log-note-return-to (point))
9350 (switch-to-buffer (marker-buffer org-log-note-marker))
9351 (goto-char org-log-note-marker)
9352 (org-switch-to-buffer-other-window "*Org Note*")
9353 (erase-buffer)
9354 (if (memq org-log-note-how '(time state))
9355 (let (current-prefix-arg) (org-store-log-note))
9356 (let ((org-inhibit-startup t)) (org-mode))
9357 (insert (format "# Insert note for %s.
9358 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9359 (cond
9360 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9361 ((eq org-log-note-purpose 'done) "closed todo item")
9362 ((eq org-log-note-purpose 'state)
9363 (format "state change from \"%s\" to \"%s\""
9364 (or org-log-note-previous-state "")
9365 (or org-log-note-state "")))
9366 ((eq org-log-note-purpose 'note)
9367 "this entry")
9368 (t (error "This should not happen")))))
9369 (if org-log-note-extra (insert org-log-note-extra))
9370 (org-set-local 'org-finish-function 'org-store-log-note)))
9372 (defvar org-note-abort nil) ; dynamically scoped
9373 (defun org-store-log-note ()
9374 "Finish taking a log note, and insert it to where it belongs."
9375 (let ((txt (buffer-string))
9376 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9377 lines ind)
9378 (kill-buffer (current-buffer))
9379 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9380 (setq txt (replace-match "" t t txt)))
9381 (if (string-match "\\s-+\\'" txt)
9382 (setq txt (replace-match "" t t txt)))
9383 (setq lines (org-split-string txt "\n"))
9384 (when (and note (string-match "\\S-" note))
9385 (setq note
9386 (org-replace-escapes
9387 note
9388 (list (cons "%u" (user-login-name))
9389 (cons "%U" user-full-name)
9390 (cons "%t" (format-time-string
9391 (org-time-stamp-format 'long 'inactive)
9392 (current-time)))
9393 (cons "%s" (if org-log-note-state
9394 (concat "\"" org-log-note-state "\"")
9395 ""))
9396 (cons "%S" (if org-log-note-previous-state
9397 (concat "\"" org-log-note-previous-state "\"")
9398 "\"\"")))))
9399 (if lines (setq note (concat note " \\\\")))
9400 (push note lines))
9401 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9402 (when lines
9403 (save-excursion
9404 (set-buffer (marker-buffer org-log-note-marker))
9405 (save-excursion
9406 (goto-char org-log-note-marker)
9407 (move-marker org-log-note-marker nil)
9408 (end-of-line 1)
9409 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9410 (insert "- " (pop lines))
9411 (org-indent-line-function)
9412 (beginning-of-line 1)
9413 (looking-at "[ \t]*")
9414 (setq ind (concat (match-string 0) " "))
9415 (end-of-line 1)
9416 (while lines (insert "\n" ind (pop lines)))
9417 (message "Note stored")
9418 (org-back-to-heading t)
9419 (org-cycle-hide-drawers 'children)))))
9420 (set-window-configuration org-log-note-window-configuration)
9421 (with-current-buffer (marker-buffer org-log-note-return-to)
9422 (goto-char org-log-note-return-to))
9423 (move-marker org-log-note-return-to nil)
9424 (and org-log-post-message (message "%s" org-log-post-message)))
9426 (defun org-sparse-tree (&optional arg)
9427 "Create a sparse tree, prompt for the details.
9428 This command can create sparse trees. You first need to select the type
9429 of match used to create the tree:
9431 t Show entries with a specific TODO keyword.
9432 T Show entries selected by a tags match.
9433 p Enter a property name and its value (both with completion on existing
9434 names/values) and show entries with that property.
9435 r Show entries matching a regular expression
9436 d Show deadlines due within `org-deadline-warning-days'."
9437 (interactive "P")
9438 (let (ans kwd value)
9439 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9440 (setq ans (read-char-exclusive))
9441 (cond
9442 ((equal ans ?d)
9443 (call-interactively 'org-check-deadlines))
9444 ((equal ans ?b)
9445 (call-interactively 'org-check-before-date))
9446 ((equal ans ?t)
9447 (org-show-todo-tree '(4)))
9448 ((equal ans ?T)
9449 (call-interactively 'org-tags-sparse-tree))
9450 ((member ans '(?p ?P))
9451 (setq kwd (org-ido-completing-read "Property: "
9452 (mapcar 'list (org-buffer-property-keys))))
9453 (setq value (org-ido-completing-read "Value: "
9454 (mapcar 'list (org-property-values kwd))))
9455 (unless (string-match "\\`{.*}\\'" value)
9456 (setq value (concat "\"" value "\"")))
9457 (org-tags-sparse-tree arg (concat kwd "=" value)))
9458 ((member ans '(?r ?R ?/))
9459 (call-interactively 'org-occur))
9460 (t (error "No such sparse tree command \"%c\"" ans)))))
9462 (defvar org-occur-highlights nil
9463 "List of overlays used for occur matches.")
9464 (make-variable-buffer-local 'org-occur-highlights)
9465 (defvar org-occur-parameters nil
9466 "Parameters of the active org-occur calls.
9467 This is a list, each call to org-occur pushes as cons cell,
9468 containing the regular expression and the callback, onto the list.
9469 The list can contain several entries if `org-occur' has been called
9470 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9471 will only contain one set of parameters. When the highlights are
9472 removed (for example with `C-c C-c', or with the next edit (depending
9473 on `org-remove-highlights-with-change'), this variable is emptied
9474 as well.")
9475 (make-variable-buffer-local 'org-occur-parameters)
9477 (defun org-occur (regexp &optional keep-previous callback)
9478 "Make a compact tree which shows all matches of REGEXP.
9479 The tree will show the lines where the regexp matches, and all higher
9480 headlines above the match. It will also show the heading after the match,
9481 to make sure editing the matching entry is easy.
9482 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9483 call to `org-occur' will be kept, to allow stacking of calls to this
9484 command.
9485 If CALLBACK is non-nil, it is a function which is called to confirm
9486 that the match should indeed be shown."
9487 (interactive "sRegexp: \nP")
9488 (unless keep-previous
9489 (org-remove-occur-highlights nil nil t))
9490 (push (cons regexp callback) org-occur-parameters)
9491 (let ((cnt 0))
9492 (save-excursion
9493 (goto-char (point-min))
9494 (if (or (not keep-previous) ; do not want to keep
9495 (not org-occur-highlights)) ; no previous matches
9496 ;; hide everything
9497 (org-overview))
9498 (while (re-search-forward regexp nil t)
9499 (when (or (not callback)
9500 (save-match-data (funcall callback)))
9501 (setq cnt (1+ cnt))
9502 (when org-highlight-sparse-tree-matches
9503 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9504 (org-show-context 'occur-tree))))
9505 (when org-remove-highlights-with-change
9506 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9507 nil 'local))
9508 (unless org-sparse-tree-open-archived-trees
9509 (org-hide-archived-subtrees (point-min) (point-max)))
9510 (run-hooks 'org-occur-hook)
9511 (if (interactive-p)
9512 (message "%d match(es) for regexp %s" cnt regexp))
9513 cnt))
9515 (defun org-show-context (&optional key)
9516 "Make sure point and context and visible.
9517 How much context is shown depends upon the variables
9518 `org-show-hierarchy-above', `org-show-following-heading'. and
9519 `org-show-siblings'."
9520 (let ((heading-p (org-on-heading-p t))
9521 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9522 (following-p (org-get-alist-option org-show-following-heading key))
9523 (entry-p (org-get-alist-option org-show-entry-below key))
9524 (siblings-p (org-get-alist-option org-show-siblings key)))
9525 (catch 'exit
9526 ;; Show heading or entry text
9527 (if (and heading-p (not entry-p))
9528 (org-flag-heading nil) ; only show the heading
9529 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9530 (org-show-hidden-entry))) ; show entire entry
9531 (when following-p
9532 ;; Show next sibling, or heading below text
9533 (save-excursion
9534 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9535 (org-flag-heading nil))))
9536 (when siblings-p (org-show-siblings))
9537 (when hierarchy-p
9538 ;; show all higher headings, possibly with siblings
9539 (save-excursion
9540 (while (and (condition-case nil
9541 (progn (org-up-heading-all 1) t)
9542 (error nil))
9543 (not (bobp)))
9544 (org-flag-heading nil)
9545 (when siblings-p (org-show-siblings))))))))
9547 (defun org-reveal (&optional siblings)
9548 "Show current entry, hierarchy above it, and the following headline.
9549 This can be used to show a consistent set of context around locations
9550 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9551 not t for the search context.
9553 With optional argument SIBLINGS, on each level of the hierarchy all
9554 siblings are shown. This repairs the tree structure to what it would
9555 look like when opened with hierarchical calls to `org-cycle'."
9556 (interactive "P")
9557 (let ((org-show-hierarchy-above t)
9558 (org-show-following-heading t)
9559 (org-show-siblings (if siblings t org-show-siblings)))
9560 (org-show-context nil)))
9562 (defun org-highlight-new-match (beg end)
9563 "Highlight from BEG to END and mark the highlight is an occur headline."
9564 (let ((ov (org-make-overlay beg end)))
9565 (org-overlay-put ov 'face 'secondary-selection)
9566 (push ov org-occur-highlights)))
9568 (defun org-remove-occur-highlights (&optional beg end noremove)
9569 "Remove the occur highlights from the buffer.
9570 BEG and END are ignored. If NOREMOVE is nil, remove this function
9571 from the `before-change-functions' in the current buffer."
9572 (interactive)
9573 (unless org-inhibit-highlight-removal
9574 (mapc 'org-delete-overlay org-occur-highlights)
9575 (setq org-occur-highlights nil)
9576 (setq org-occur-parameters nil)
9577 (unless noremove
9578 (remove-hook 'before-change-functions
9579 'org-remove-occur-highlights 'local))))
9581 ;;;; Priorities
9583 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9584 "Regular expression matching the priority indicator.")
9586 (defvar org-remove-priority-next-time nil)
9588 (defun org-priority-up ()
9589 "Increase the priority of the current item."
9590 (interactive)
9591 (org-priority 'up))
9593 (defun org-priority-down ()
9594 "Decrease the priority of the current item."
9595 (interactive)
9596 (org-priority 'down))
9598 (defun org-priority (&optional action)
9599 "Change the priority of an item by ARG.
9600 ACTION can be `set', `up', `down', or a character."
9601 (interactive)
9602 (setq action (or action 'set))
9603 (let (current new news have remove)
9604 (save-excursion
9605 (org-back-to-heading t)
9606 (if (looking-at org-priority-regexp)
9607 (setq current (string-to-char (match-string 2))
9608 have t)
9609 (setq current org-default-priority))
9610 (cond
9611 ((or (eq action 'set)
9612 (if (featurep 'xemacs) (characterp action) (integerp action)))
9613 (if (not (eq action 'set))
9614 (setq new action)
9615 (message "Priority %c-%c, SPC to remove: "
9616 org-highest-priority org-lowest-priority)
9617 (setq new (read-char-exclusive)))
9618 (if (and (= (upcase org-highest-priority) org-highest-priority)
9619 (= (upcase org-lowest-priority) org-lowest-priority))
9620 (setq new (upcase new)))
9621 (cond ((equal new ?\ ) (setq remove t))
9622 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9623 (error "Priority must be between `%c' and `%c'"
9624 org-highest-priority org-lowest-priority))))
9625 ((eq action 'up)
9626 (if (and (not have) (eq last-command this-command))
9627 (setq new org-lowest-priority)
9628 (setq new (if (and org-priority-start-cycle-with-default (not have))
9629 org-default-priority (1- current)))))
9630 ((eq action 'down)
9631 (if (and (not have) (eq last-command this-command))
9632 (setq new org-highest-priority)
9633 (setq new (if (and org-priority-start-cycle-with-default (not have))
9634 org-default-priority (1+ current)))))
9635 (t (error "Invalid action")))
9636 (if (or (< (upcase new) org-highest-priority)
9637 (> (upcase new) org-lowest-priority))
9638 (setq remove t))
9639 (setq news (format "%c" new))
9640 (if have
9641 (if remove
9642 (replace-match "" t t nil 1)
9643 (replace-match news t t nil 2))
9644 (if remove
9645 (error "No priority cookie found in line")
9646 (looking-at org-todo-line-regexp)
9647 (if (match-end 2)
9648 (progn
9649 (goto-char (match-end 2))
9650 (insert " [#" news "]"))
9651 (goto-char (match-beginning 3))
9652 (insert "[#" news "] ")))))
9653 (org-preserve-lc (org-set-tags nil 'align))
9654 (if remove
9655 (message "Priority removed")
9656 (message "Priority of current item set to %s" news))))
9659 (defun org-get-priority (s)
9660 "Find priority cookie and return priority."
9661 (save-match-data
9662 (if (not (string-match org-priority-regexp s))
9663 (* 1000 (- org-lowest-priority org-default-priority))
9664 (* 1000 (- org-lowest-priority
9665 (string-to-char (match-string 2 s)))))))
9667 ;;;; Tags
9669 (defvar org-agenda-archives-mode)
9670 (defun org-scan-tags (action matcher &optional todo-only)
9671 "Scan headline tags with inheritance and produce output ACTION.
9673 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9674 or `agenda' to produce an entry list for an agenda view. It can also be
9675 a Lisp form or a function that should be called at each matched headline, in
9676 this case the return value is a list of all return values from these calls.
9678 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9679 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9680 only lines with a TODO keyword are included in the output."
9681 (require 'org-agenda)
9682 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9683 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9684 (org-re
9685 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9686 (props (list 'face 'default
9687 'done-face 'org-done
9688 'undone-face 'default
9689 'mouse-face 'highlight
9690 'org-not-done-regexp org-not-done-regexp
9691 'org-todo-regexp org-todo-regexp
9692 'keymap org-agenda-keymap
9693 'help-echo
9694 (format "mouse-2 or RET jump to org file %s"
9695 (abbreviate-file-name
9696 (or (buffer-file-name (buffer-base-buffer))
9697 (buffer-name (buffer-base-buffer)))))))
9698 (case-fold-search nil)
9699 lspos tags tags-list
9700 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9701 (llast 0) rtn rtn1 level category i txt
9702 todo marker entry priority)
9703 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9704 (setq action (list 'lambda nil action)))
9705 (save-excursion
9706 (goto-char (point-min))
9707 (when (eq action 'sparse-tree)
9708 (org-overview)
9709 (org-remove-occur-highlights))
9710 (while (re-search-forward re nil t)
9711 (catch :skip
9712 (setq todo (if (match-end 1) (match-string 2))
9713 tags (if (match-end 4) (match-string 4)))
9714 (goto-char (setq lspos (1+ (match-beginning 0))))
9715 (setq level (org-reduced-level (funcall outline-level))
9716 category (org-get-category))
9717 (setq i llast llast level)
9718 ;; remove tag lists from same and sublevels
9719 (while (>= i level)
9720 (when (setq entry (assoc i tags-alist))
9721 (setq tags-alist (delete entry tags-alist)))
9722 (setq i (1- i)))
9723 ;; add the next tags
9724 (when tags
9725 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9726 tags-alist
9727 (cons (cons level tags) tags-alist)))
9728 ;; compile tags for current headline
9729 (setq tags-list
9730 (if org-use-tag-inheritance
9731 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9732 tags))
9733 (when org-use-tag-inheritance
9734 (setcdr (car tags-alist)
9735 (mapcar (lambda (x)
9736 (setq x (copy-sequence x))
9737 (org-add-prop-inherited x))
9738 (cdar tags-alist))))
9739 (when (and tags org-use-tag-inheritance
9740 (not (eq t org-use-tag-inheritance)))
9741 ;; selective inheritance, remove uninherited ones
9742 (setcdr (car tags-alist)
9743 (org-remove-uniherited-tags (cdar tags-alist))))
9744 (when (and (or (not todo-only)
9745 (and (member todo org-not-done-keywords)
9746 (or (not org-agenda-tags-todo-honor-ignore-options)
9747 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9748 (let ((case-fold-search t)) (eval matcher))
9750 (not (member org-archive-tag tags-list))
9751 ;; we have an archive tag, should we use this anyway?
9752 (or (not org-agenda-skip-archived-trees)
9753 (and (eq action 'agenda) org-agenda-archives-mode))))
9754 (unless (eq action 'sparse-tree) (org-agenda-skip))
9756 ;; select this headline
9758 (cond
9759 ((eq action 'sparse-tree)
9760 (and org-highlight-sparse-tree-matches
9761 (org-get-heading) (match-end 0)
9762 (org-highlight-new-match
9763 (match-beginning 0) (match-beginning 1)))
9764 (org-show-context 'tags-tree))
9765 ((eq action 'agenda)
9766 (setq txt (org-format-agenda-item
9768 (concat
9769 (if org-tags-match-list-sublevels
9770 (make-string (1- level) ?.) "")
9771 (org-get-heading))
9772 category (org-get-tags-at))
9773 priority (org-get-priority txt))
9774 (goto-char lspos)
9775 (setq marker (org-agenda-new-marker))
9776 (org-add-props txt props
9777 'org-marker marker 'org-hd-marker marker 'org-category category
9778 'todo-state todo
9779 'priority priority 'type "tagsmatch")
9780 (push txt rtn))
9781 ((functionp action)
9782 (save-excursion
9783 (setq rtn1 (funcall action))
9784 (push rtn1 rtn))
9785 (goto-char (point-at-eol)))
9786 (t (error "Invalid action")))
9788 ;; if we are to skip sublevels, jump to end of subtree
9789 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9790 (when (and (eq action 'sparse-tree)
9791 (not org-sparse-tree-open-archived-trees))
9792 (org-hide-archived-subtrees (point-min) (point-max)))
9793 (nreverse rtn)))
9795 (defun org-remove-uniherited-tags (tags)
9796 "Remove all tags that are not inherited from the list TAGS."
9797 (cond
9798 ((eq org-use-tag-inheritance t)
9799 (if org-tags-exclude-from-inheritance
9800 (org-delete-all org-tags-exclude-from-inheritance tags)
9801 tags))
9802 ((not org-use-tag-inheritance) nil)
9803 ((stringp org-use-tag-inheritance)
9804 (delq nil (mapcar
9805 (lambda (x)
9806 (if (and (string-match org-use-tag-inheritance x)
9807 (not (member x org-tags-exclude-from-inheritance)))
9808 x nil))
9809 tags)))
9810 ((listp org-use-tag-inheritance)
9811 (delq nil (mapcar
9812 (lambda (x)
9813 (if (member x org-use-tag-inheritance) x nil))
9814 tags)))))
9816 (defvar todo-only) ;; dynamically scoped
9818 (defun org-tags-sparse-tree (&optional todo-only match)
9819 "Create a sparse tree according to tags string MATCH.
9820 MATCH can contain positive and negative selection of tags, like
9821 \"+WORK+URGENT-WITHBOSS\".
9822 If optional argument TODO-ONLY is non-nil, only select lines that are
9823 also TODO lines."
9824 (interactive "P")
9825 (org-prepare-agenda-buffers (list (current-buffer)))
9826 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9828 (defvar org-cached-props nil)
9829 (defun org-cached-entry-get (pom property)
9830 (if (or (eq t org-use-property-inheritance)
9831 (and (stringp org-use-property-inheritance)
9832 (string-match org-use-property-inheritance property))
9833 (and (listp org-use-property-inheritance)
9834 (member property org-use-property-inheritance)))
9835 ;; Caching is not possible, check it directly
9836 (org-entry-get pom property 'inherit)
9837 ;; Get all properties, so that we can do complicated checks easily
9838 (cdr (assoc property (or org-cached-props
9839 (setq org-cached-props
9840 (org-entry-properties pom)))))))
9842 (defun org-global-tags-completion-table (&optional files)
9843 "Return the list of all tags in all agenda buffer/files."
9844 (save-excursion
9845 (org-uniquify
9846 (delq nil
9847 (apply 'append
9848 (mapcar
9849 (lambda (file)
9850 (set-buffer (find-file-noselect file))
9851 (append (org-get-buffer-tags)
9852 (mapcar (lambda (x) (if (stringp (car-safe x))
9853 (list (car-safe x)) nil))
9854 org-tag-alist)))
9855 (if (and files (car files))
9856 files
9857 (org-agenda-files))))))))
9859 (defun org-make-tags-matcher (match)
9860 "Create the TAGS//TODO matcher form for the selection string MATCH."
9861 ;; todo-only is scoped dynamically into this function, and the function
9862 ;; may change it if the matcher asks for it.
9863 (unless match
9864 ;; Get a new match request, with completion
9865 (let ((org-last-tags-completion-table
9866 (org-global-tags-completion-table)))
9867 (setq match (org-completing-read-no-ido
9868 "Match: " 'org-tags-completion-function nil nil nil
9869 'org-tags-history))))
9871 ;; Parse the string and create a lisp form
9872 (let ((match0 match)
9873 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9874 minus tag mm
9875 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9876 orterms term orlist re-p str-p level-p level-op time-p
9877 prop-p pn pv po cat-p gv rest)
9878 (if (string-match "/+" match)
9879 ;; match contains also a todo-matching request
9880 (progn
9881 (setq tagsmatch (substring match 0 (match-beginning 0))
9882 todomatch (substring match (match-end 0)))
9883 (if (string-match "^!" todomatch)
9884 (setq todo-only t todomatch (substring todomatch 1)))
9885 (if (string-match "^\\s-*$" todomatch)
9886 (setq todomatch nil)))
9887 ;; only matching tags
9888 (setq tagsmatch match todomatch nil))
9890 ;; Make the tags matcher
9891 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9892 (setq tagsmatcher t)
9893 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9894 (while (setq term (pop orterms))
9895 (while (and (equal (substring term -1) "\\") orterms)
9896 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9897 (while (string-match re term)
9898 (setq rest (substring term (match-end 0))
9899 minus (and (match-end 1)
9900 (equal (match-string 1 term) "-"))
9901 tag (match-string 2 term)
9902 re-p (equal (string-to-char tag) ?{)
9903 level-p (match-end 4)
9904 prop-p (match-end 5)
9905 mm (cond
9906 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9907 (level-p
9908 (setq level-op (org-op-to-function (match-string 3 term)))
9909 `(,level-op level ,(string-to-number
9910 (match-string 4 term))))
9911 (prop-p
9912 (setq pn (match-string 5 term)
9913 po (match-string 6 term)
9914 pv (match-string 7 term)
9915 cat-p (equal pn "CATEGORY")
9916 re-p (equal (string-to-char pv) ?{)
9917 str-p (equal (string-to-char pv) ?\")
9918 time-p (save-match-data
9919 (string-match "^\"[[<].*[]>]\"$" pv))
9920 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9921 (if time-p (setq pv (org-matcher-time pv)))
9922 (setq po (org-op-to-function po (if time-p 'time str-p)))
9923 (cond
9924 ((equal pn "CATEGORY")
9925 (setq gv '(get-text-property (point) 'org-category)))
9926 ((equal pn "TODO")
9927 (setq gv 'todo))
9929 (setq gv `(org-cached-entry-get nil ,pn))))
9930 (if re-p
9931 (if (eq po 'org<>)
9932 `(not (string-match ,pv (or ,gv "")))
9933 `(string-match ,pv (or ,gv "")))
9934 (if str-p
9935 `(,po (or ,gv "") ,pv)
9936 `(,po (string-to-number (or ,gv ""))
9937 ,(string-to-number pv) ))))
9938 (t `(member ,(downcase tag) tags-list)))
9939 mm (if minus (list 'not mm) mm)
9940 term rest)
9941 (push mm tagsmatcher))
9942 (push (if (> (length tagsmatcher) 1)
9943 (cons 'and tagsmatcher)
9944 (car tagsmatcher))
9945 orlist)
9946 (setq tagsmatcher nil))
9947 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9948 (setq tagsmatcher
9949 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9950 ;; Make the todo matcher
9951 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9952 (setq todomatcher t)
9953 (setq orterms (org-split-string todomatch "|") orlist nil)
9954 (while (setq term (pop orterms))
9955 (while (string-match re term)
9956 (setq minus (and (match-end 1)
9957 (equal (match-string 1 term) "-"))
9958 kwd (match-string 2 term)
9959 re-p (equal (string-to-char kwd) ?{)
9960 term (substring term (match-end 0))
9961 mm (if re-p
9962 `(string-match ,(substring kwd 1 -1) todo)
9963 (list 'equal 'todo kwd))
9964 mm (if minus (list 'not mm) mm))
9965 (push mm todomatcher))
9966 (push (if (> (length todomatcher) 1)
9967 (cons 'and todomatcher)
9968 (car todomatcher))
9969 orlist)
9970 (setq todomatcher nil))
9971 (setq todomatcher (if (> (length orlist) 1)
9972 (cons 'or orlist) (car orlist))))
9974 ;; Return the string and lisp forms of the matcher
9975 (setq matcher (if todomatcher
9976 (list 'and tagsmatcher todomatcher)
9977 tagsmatcher))
9978 (cons match0 matcher)))
9980 (defun org-op-to-function (op &optional stringp)
9981 "Turn an operator into the appropriate function."
9982 (setq op
9983 (cond
9984 ((equal op "<" ) '(< string< org-time<))
9985 ((equal op ">" ) '(> org-string> org-time>))
9986 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9987 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9988 ((member op '("=" "==")) '(= string= org-time=))
9989 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9990 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9992 (defun org<> (a b) (not (= a b)))
9993 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9994 (defun org-string>= (a b) (not (string< a b)))
9995 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9996 (defun org-string<> (a b) (not (string= a b)))
9997 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9998 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9999 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10000 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10001 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10002 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10003 (defun org-2ft (s)
10004 "Convert S to a floating point time.
10005 If S is already a number, just return it. If it is a string, parse
10006 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10007 (cond
10008 ((numberp s) s)
10009 ((stringp s)
10010 (condition-case nil
10011 (float-time (apply 'encode-time (org-parse-time-string s)))
10012 (error 0.)))
10013 (t 0.)))
10015 (defun org-time-today ()
10016 "Time in seconds today at 0:00.
10017 Returns the float number of seconds since the beginning of the
10018 epoch to the beginning of today (00:00)."
10019 (float-time (apply 'encode-time
10020 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10022 (defun org-matcher-time (s)
10023 "Interpret a time comparison value."
10024 (save-match-data
10025 (cond
10026 ((string= s "<now>") (float-time))
10027 ((string= s "<today>") (org-time-today))
10028 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10029 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10030 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10031 (+ (org-time-today)
10032 (* (string-to-number (match-string 1 s))
10033 (cdr (assoc (match-string 2 s)
10034 '(("d" . 86400.0) ("w" . 604800.0)
10035 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10036 (t (org-2ft s)))))
10038 (defun org-match-any-p (re list)
10039 "Does re match any element of list?"
10040 (setq list (mapcar (lambda (x) (string-match re x)) list))
10041 (delq nil list))
10043 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10044 (defvar org-tags-overlay (org-make-overlay 1 1))
10045 (org-detach-overlay org-tags-overlay)
10047 (defun org-get-local-tags-at (&optional pos)
10048 "Get a list of tags defined in the current headline."
10049 (org-get-tags-at pos 'local))
10051 (defun org-get-local-tags ()
10052 "Get a list of tags defined in the current headline."
10053 (org-get-tags-at nil 'local))
10055 (defun org-get-tags-at (&optional pos local)
10056 "Get a list of all headline tags applicable at POS.
10057 POS defaults to point. If tags are inherited, the list contains
10058 the targets in the same sequence as the headlines appear, i.e.
10059 the tags of the current headline come last.
10060 When LOCAL is non-nil, only return tags from the current headline,
10061 ignore inherited ones."
10062 (interactive)
10063 (let (tags ltags lastpos parent)
10064 (save-excursion
10065 (save-restriction
10066 (widen)
10067 (goto-char (or pos (point)))
10068 (save-match-data
10069 (catch 'done
10070 (condition-case nil
10071 (progn
10072 (org-back-to-heading t)
10073 (while (not (equal lastpos (point)))
10074 (setq lastpos (point))
10075 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10076 (setq ltags (org-split-string
10077 (org-match-string-no-properties 1) ":"))
10078 (when parent
10079 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10080 (setq tags (append
10081 (if parent
10082 (org-remove-uniherited-tags ltags)
10083 ltags)
10084 tags)))
10085 (or org-use-tag-inheritance (throw 'done t))
10086 (if local (throw 'done t))
10087 (org-up-heading-all 1)
10088 (setq parent t)))
10089 (error nil)))))
10090 (append (org-remove-uniherited-tags org-file-tags) tags))))
10092 (defun org-add-prop-inherited (s)
10093 (add-text-properties 0 (length s) '(inherited t) s)
10096 (defun org-toggle-tag (tag &optional onoff)
10097 "Toggle the tag TAG for the current line.
10098 If ONOFF is `on' or `off', don't toggle but set to this state."
10099 (let (res current)
10100 (save-excursion
10101 (org-back-to-heading t)
10102 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10103 (point-at-eol) t)
10104 (progn
10105 (setq current (match-string 1))
10106 (replace-match ""))
10107 (setq current ""))
10108 (setq current (nreverse (org-split-string current ":")))
10109 (cond
10110 ((eq onoff 'on)
10111 (setq res t)
10112 (or (member tag current) (push tag current)))
10113 ((eq onoff 'off)
10114 (or (not (member tag current)) (setq current (delete tag current))))
10115 (t (if (member tag current)
10116 (setq current (delete tag current))
10117 (setq res t)
10118 (push tag current))))
10119 (end-of-line 1)
10120 (if current
10121 (progn
10122 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10123 (org-set-tags nil t))
10124 (delete-horizontal-space))
10125 (run-hooks 'org-after-tags-change-hook))
10126 res))
10128 (defun org-align-tags-here (to-col)
10129 ;; Assumes that this is a headline
10130 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10131 (beginning-of-line 1)
10132 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10133 (< pos (match-beginning 2)))
10134 (progn
10135 (setq tags-l (- (match-end 2) (match-beginning 2)))
10136 (goto-char (match-beginning 1))
10137 (insert " ")
10138 (delete-region (point) (1+ (match-beginning 2)))
10139 (setq ncol (max (1+ (current-column))
10140 (1+ col)
10141 (if (> to-col 0)
10142 to-col
10143 (- (abs to-col) tags-l))))
10144 (setq p (point))
10145 (insert (make-string (- ncol (current-column)) ?\ ))
10146 (setq ncol (current-column))
10147 (when indent-tabs-mode (tabify p (point-at-eol)))
10148 (org-move-to-column (min ncol col) t))
10149 (goto-char pos))))
10151 (defun org-set-tags-command (&optional arg just-align)
10152 "Call the set-tags command for the current entry."
10153 (interactive "P")
10154 (if (org-on-heading-p)
10155 (org-set-tags arg just-align)
10156 (save-excursion
10157 (org-back-to-heading t)
10158 (org-set-tags arg just-align))))
10160 (defun org-set-tags (&optional arg just-align)
10161 "Set the tags for the current headline.
10162 With prefix ARG, realign all tags in headings in the current buffer."
10163 (interactive "P")
10164 (let* ((re (concat "^" outline-regexp))
10165 (current (org-get-tags-string))
10166 (col (current-column))
10167 (org-setting-tags t)
10168 table current-tags inherited-tags ; computed below when needed
10169 tags p0 c0 c1 rpl)
10170 (if arg
10171 (save-excursion
10172 (goto-char (point-min))
10173 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10174 (while (re-search-forward re nil t)
10175 (org-set-tags nil t)
10176 (end-of-line 1)))
10177 (message "All tags realigned to column %d" org-tags-column))
10178 (if just-align
10179 (setq tags current)
10180 ;; Get a new set of tags from the user
10181 (save-excursion
10182 (setq table (or org-tag-alist (org-get-buffer-tags))
10183 org-last-tags-completion-table table
10184 current-tags (org-split-string current ":")
10185 inherited-tags (nreverse
10186 (nthcdr (length current-tags)
10187 (nreverse (org-get-tags-at))))
10188 tags
10189 (if (or (eq t org-use-fast-tag-selection)
10190 (and org-use-fast-tag-selection
10191 (delq nil (mapcar 'cdr table))))
10192 (org-fast-tag-selection
10193 current-tags inherited-tags table
10194 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10195 (let ((org-add-colon-after-tag-completion t))
10196 (org-trim
10197 (org-without-partial-completion
10198 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10199 nil nil current 'org-tags-history)))))))
10200 (while (string-match "[-+&]+" tags)
10201 ;; No boolean logic, just a list
10202 (setq tags (replace-match ":" t t tags))))
10204 (if (string-match "\\`[\t ]*\\'" tags)
10205 (setq tags "")
10206 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10207 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10209 ;; Insert new tags at the correct column
10210 (beginning-of-line 1)
10211 (cond
10212 ((and (equal current "") (equal tags "")))
10213 ((re-search-forward
10214 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10215 (point-at-eol) t)
10216 (if (equal tags "")
10217 (setq rpl "")
10218 (goto-char (match-beginning 0))
10219 (setq c0 (current-column) p0 (point)
10220 c1 (max (1+ c0) (if (> org-tags-column 0)
10221 org-tags-column
10222 (- (- org-tags-column) (length tags))))
10223 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10224 (replace-match rpl t t)
10225 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10226 tags)
10227 (t (error "Tags alignment failed")))
10228 (org-move-to-column col)
10229 (unless just-align
10230 (run-hooks 'org-after-tags-change-hook)))))
10232 (defun org-change-tag-in-region (beg end tag off)
10233 "Add or remove TAG for each entry in the region.
10234 This works in the agenda, and also in an org-mode buffer."
10235 (interactive
10236 (list (region-beginning) (region-end)
10237 (let ((org-last-tags-completion-table
10238 (if (org-mode-p)
10239 (org-get-buffer-tags)
10240 (org-global-tags-completion-table))))
10241 (org-ido-completing-read
10242 "Tag: " 'org-tags-completion-function nil nil nil
10243 'org-tags-history))
10244 (progn
10245 (message "[s]et or [r]emove? ")
10246 (equal (read-char-exclusive) ?r))))
10247 (if (fboundp 'deactivate-mark) (deactivate-mark))
10248 (let ((agendap (equal major-mode 'org-agenda-mode))
10249 l1 l2 m buf pos newhead (cnt 0))
10250 (goto-char end)
10251 (setq l2 (1- (org-current-line)))
10252 (goto-char beg)
10253 (setq l1 (org-current-line))
10254 (loop for l from l1 to l2 do
10255 (goto-line l)
10256 (setq m (get-text-property (point) 'org-hd-marker))
10257 (when (or (and (org-mode-p) (org-on-heading-p))
10258 (and agendap m))
10259 (setq buf (if agendap (marker-buffer m) (current-buffer))
10260 pos (if agendap m (point)))
10261 (with-current-buffer buf
10262 (save-excursion
10263 (save-restriction
10264 (goto-char pos)
10265 (setq cnt (1+ cnt))
10266 (org-toggle-tag tag (if off 'off 'on))
10267 (setq newhead (org-get-heading)))))
10268 (and agendap (org-agenda-change-all-lines newhead m))))
10269 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10271 (defun org-tags-completion-function (string predicate &optional flag)
10272 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10273 (confirm (lambda (x) (stringp (car x)))))
10274 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10275 (setq s1 (match-string 1 string)
10276 s2 (match-string 2 string))
10277 (setq s1 "" s2 string))
10278 (cond
10279 ((eq flag nil)
10280 ;; try completion
10281 (setq rtn (try-completion s2 ctable confirm))
10282 (if (stringp rtn)
10283 (setq rtn
10284 (concat s1 s2 (substring rtn (length s2))
10285 (if (and org-add-colon-after-tag-completion
10286 (assoc rtn ctable))
10287 ":" ""))))
10288 rtn)
10289 ((eq flag t)
10290 ;; all-completions
10291 (all-completions s2 ctable confirm)
10293 ((eq flag 'lambda)
10294 ;; exact match?
10295 (assoc s2 ctable)))
10298 (defun org-fast-tag-insert (kwd tags face &optional end)
10299 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10300 (insert (format "%-12s" (concat kwd ":"))
10301 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10302 (or end "")))
10304 (defun org-fast-tag-show-exit (flag)
10305 (save-excursion
10306 (goto-line 3)
10307 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10308 (replace-match ""))
10309 (when flag
10310 (end-of-line 1)
10311 (org-move-to-column (- (window-width) 19) t)
10312 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10314 (defun org-set-current-tags-overlay (current prefix)
10315 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10316 (if (featurep 'xemacs)
10317 (org-overlay-display org-tags-overlay (concat prefix s)
10318 'secondary-selection)
10319 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10320 (org-overlay-display org-tags-overlay (concat prefix s)))))
10322 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10323 "Fast tag selection with single keys.
10324 CURRENT is the current list of tags in the headline, INHERITED is the
10325 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10326 possibly with grouping information. TODO-TABLE is a similar table with
10327 TODO keywords, should these have keys assigned to them.
10328 If the keys are nil, a-z are automatically assigned.
10329 Returns the new tags string, or nil to not change the current settings."
10330 (let* ((fulltable (append table todo-table))
10331 (maxlen (apply 'max (mapcar
10332 (lambda (x)
10333 (if (stringp (car x)) (string-width (car x)) 0))
10334 fulltable)))
10335 (buf (current-buffer))
10336 (expert (eq org-fast-tag-selection-single-key 'expert))
10337 (buffer-tags nil)
10338 (fwidth (+ maxlen 3 1 3))
10339 (ncol (/ (- (window-width) 4) fwidth))
10340 (i-face 'org-done)
10341 (c-face 'org-todo)
10342 tg cnt e c char c1 c2 ntable tbl rtn
10343 ov-start ov-end ov-prefix
10344 (exit-after-next org-fast-tag-selection-single-key)
10345 (done-keywords org-done-keywords)
10346 groups ingroup)
10347 (save-excursion
10348 (beginning-of-line 1)
10349 (if (looking-at
10350 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10351 (setq ov-start (match-beginning 1)
10352 ov-end (match-end 1)
10353 ov-prefix "")
10354 (setq ov-start (1- (point-at-eol))
10355 ov-end (1+ ov-start))
10356 (skip-chars-forward "^\n\r")
10357 (setq ov-prefix
10358 (concat
10359 (buffer-substring (1- (point)) (point))
10360 (if (> (current-column) org-tags-column)
10362 (make-string (- org-tags-column (current-column)) ?\ ))))))
10363 (org-move-overlay org-tags-overlay ov-start ov-end)
10364 (save-window-excursion
10365 (if expert
10366 (set-buffer (get-buffer-create " *Org tags*"))
10367 (delete-other-windows)
10368 (split-window-vertically)
10369 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10370 (erase-buffer)
10371 (org-set-local 'org-done-keywords done-keywords)
10372 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10373 (org-fast-tag-insert "Current" current c-face "\n\n")
10374 (org-fast-tag-show-exit exit-after-next)
10375 (org-set-current-tags-overlay current ov-prefix)
10376 (setq tbl fulltable char ?a cnt 0)
10377 (while (setq e (pop tbl))
10378 (cond
10379 ((equal e '(:startgroup))
10380 (push '() groups) (setq ingroup t)
10381 (when (not (= cnt 0))
10382 (setq cnt 0)
10383 (insert "\n"))
10384 (insert "{ "))
10385 ((equal e '(:endgroup))
10386 (setq ingroup nil cnt 0)
10387 (insert "}\n"))
10388 ((equal e '(:newline))
10389 (insert "\n "))
10391 (setq tg (car e) c2 nil)
10392 (if (cdr e)
10393 (setq c (cdr e))
10394 ;; automatically assign a character.
10395 (setq c1 (string-to-char
10396 (downcase (substring
10397 tg (if (= (string-to-char tg) ?@) 1 0)))))
10398 (if (or (rassoc c1 ntable) (rassoc c1 table))
10399 (while (or (rassoc char ntable) (rassoc char table))
10400 (setq char (1+ char)))
10401 (setq c2 c1))
10402 (setq c (or c2 char)))
10403 (if ingroup (push tg (car groups)))
10404 (setq tg (org-add-props tg nil 'face
10405 (cond
10406 ((not (assoc tg table))
10407 (org-get-todo-face tg))
10408 ((member tg current) c-face)
10409 ((member tg inherited) i-face)
10410 (t nil))))
10411 (if (and (= cnt 0) (not ingroup)) (insert " "))
10412 (insert "[" c "] " tg (make-string
10413 (- fwidth 4 (length tg)) ?\ ))
10414 (push (cons tg c) ntable)
10415 (when (= (setq cnt (1+ cnt)) ncol)
10416 (insert "\n")
10417 (if ingroup (insert " "))
10418 (setq cnt 0)))))
10419 (setq ntable (nreverse ntable))
10420 (insert "\n")
10421 (goto-char (point-min))
10422 (if (not expert) (org-fit-window-to-buffer))
10423 (setq rtn
10424 (catch 'exit
10425 (while t
10426 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10427 (if groups " [!] no groups" " [!]groups")
10428 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10429 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10430 (cond
10431 ((= c ?\r) (throw 'exit t))
10432 ((= c ?!)
10433 (setq groups (not groups))
10434 (goto-char (point-min))
10435 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10436 ((= c ?\C-c)
10437 (if (not expert)
10438 (org-fast-tag-show-exit
10439 (setq exit-after-next (not exit-after-next)))
10440 (setq expert nil)
10441 (delete-other-windows)
10442 (split-window-vertically)
10443 (org-switch-to-buffer-other-window " *Org tags*")
10444 (org-fit-window-to-buffer)))
10445 ((or (= c ?\C-g)
10446 (and (= c ?q) (not (rassoc c ntable))))
10447 (org-detach-overlay org-tags-overlay)
10448 (setq quit-flag t))
10449 ((= c ?\ )
10450 (setq current nil)
10451 (if exit-after-next (setq exit-after-next 'now)))
10452 ((= c ?\t)
10453 (condition-case nil
10454 (setq tg (org-ido-completing-read
10455 "Tag: "
10456 (or buffer-tags
10457 (with-current-buffer buf
10458 (org-get-buffer-tags)))))
10459 (quit (setq tg "")))
10460 (when (string-match "\\S-" tg)
10461 (add-to-list 'buffer-tags (list tg))
10462 (if (member tg current)
10463 (setq current (delete tg current))
10464 (push tg current)))
10465 (if exit-after-next (setq exit-after-next 'now)))
10466 ((setq e (rassoc c todo-table) tg (car e))
10467 (with-current-buffer buf
10468 (save-excursion (org-todo tg)))
10469 (if exit-after-next (setq exit-after-next 'now)))
10470 ((setq e (rassoc c ntable) tg (car e))
10471 (if (member tg current)
10472 (setq current (delete tg current))
10473 (loop for g in groups do
10474 (if (member tg g)
10475 (mapc (lambda (x)
10476 (setq current (delete x current)))
10477 g)))
10478 (push tg current))
10479 (if exit-after-next (setq exit-after-next 'now))))
10481 ;; Create a sorted list
10482 (setq current
10483 (sort current
10484 (lambda (a b)
10485 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10486 (if (eq exit-after-next 'now) (throw 'exit t))
10487 (goto-char (point-min))
10488 (beginning-of-line 2)
10489 (delete-region (point) (point-at-eol))
10490 (org-fast-tag-insert "Current" current c-face)
10491 (org-set-current-tags-overlay current ov-prefix)
10492 (while (re-search-forward
10493 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10494 (setq tg (match-string 1))
10495 (add-text-properties
10496 (match-beginning 1) (match-end 1)
10497 (list 'face
10498 (cond
10499 ((member tg current) c-face)
10500 ((member tg inherited) i-face)
10501 (t (get-text-property (match-beginning 1) 'face))))))
10502 (goto-char (point-min)))))
10503 (org-detach-overlay org-tags-overlay)
10504 (if rtn
10505 (mapconcat 'identity current ":")
10506 nil))))
10508 (defun org-get-tags-string ()
10509 "Get the TAGS string in the current headline."
10510 (unless (org-on-heading-p t)
10511 (error "Not on a heading"))
10512 (save-excursion
10513 (beginning-of-line 1)
10514 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10515 (org-match-string-no-properties 1)
10516 "")))
10518 (defun org-get-tags ()
10519 "Get the list of tags specified in the current headline."
10520 (org-split-string (org-get-tags-string) ":"))
10522 (defun org-get-buffer-tags ()
10523 "Get a table of all tags used in the buffer, for completion."
10524 (let (tags)
10525 (save-excursion
10526 (goto-char (point-min))
10527 (while (re-search-forward
10528 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10529 (when (equal (char-after (point-at-bol 0)) ?*)
10530 (mapc (lambda (x) (add-to-list 'tags x))
10531 (org-split-string (org-match-string-no-properties 1) ":")))))
10532 (mapcar 'list tags)))
10534 ;;;; The mapping API
10536 ;;;###autoload
10537 (defun org-map-entries (func &optional match scope &rest skip)
10538 "Call FUNC at each headline selected by MATCH in SCOPE.
10540 FUNC is a function or a lisp form. The function will be called without
10541 arguments, with the cursor positioned at the beginning of the headline.
10542 The return values of all calls to the function will be collected and
10543 returned as a list.
10545 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10546 Only headlines that are matched by this query will be considered during
10547 the iteration. When MATCH is nil or t, all headlines will be
10548 visited by the iteration.
10550 SCOPE determines the scope of this command. It can be any of:
10552 nil The current buffer, respecting the restriction if any
10553 tree The subtree started with the entry at point
10554 file The current buffer, without restriction
10555 file-with-archives
10556 The current buffer, and any archives associated with it
10557 agenda All agenda files
10558 agenda-with-archives
10559 All agenda files with any archive files associated with them
10560 \(file1 file2 ...)
10561 If this is a list, all files in the list will be scanned
10563 The remaining args are treated as settings for the skipping facilities of
10564 the scanner. The following items can be given here:
10566 archive skip trees with the archive tag.
10567 comment skip trees with the COMMENT keyword
10568 function or Emacs Lisp form:
10569 will be used as value for `org-agenda-skip-function', so whenever
10570 the the function returns t, FUNC will not be called for that
10571 entry and search will continue from the point where the
10572 function leaves it."
10573 (let* ((org-agenda-archives-mode nil) ; just to make sure
10574 (org-agenda-skip-archived-trees (memq 'archive skip))
10575 (org-agenda-skip-comment-trees (memq 'comment skip))
10576 (org-agenda-skip-function
10577 (car (org-delete-all '(comment archive) skip)))
10578 (org-tags-match-list-sublevels t)
10579 matcher file res
10580 org-todo-keywords-for-agenda
10581 org-done-keywords-for-agenda
10582 org-todo-keyword-alist-for-agenda
10583 org-tag-alist-for-agenda)
10585 (cond
10586 ((eq match t) (setq matcher t))
10587 ((eq match nil) (setq matcher t))
10588 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10590 (save-excursion
10591 (save-restriction
10592 (when (eq scope 'tree)
10593 (org-back-to-heading t)
10594 (org-narrow-to-subtree)
10595 (setq scope nil))
10597 (if (not scope)
10598 (progn
10599 (org-prepare-agenda-buffers
10600 (list (buffer-file-name (current-buffer))))
10601 (setq res (org-scan-tags func matcher)))
10602 ;; Get the right scope
10603 (cond
10604 ((and scope (listp scope) (symbolp (car scope)))
10605 (setq scope (eval scope)))
10606 ((eq scope 'agenda)
10607 (setq scope (org-agenda-files t)))
10608 ((eq scope 'agenda-with-archives)
10609 (setq scope (org-agenda-files t))
10610 (setq scope (org-add-archive-files scope)))
10611 ((eq scope 'file)
10612 (setq scope (list (buffer-file-name))))
10613 ((eq scope 'file-with-archives)
10614 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10615 (org-prepare-agenda-buffers scope)
10616 (while (setq file (pop scope))
10617 (with-current-buffer (org-find-base-buffer-visiting file)
10618 (save-excursion
10619 (save-restriction
10620 (widen)
10621 (goto-char (point-min))
10622 (setq res (append res (org-scan-tags func matcher))))))))))
10623 res))
10625 ;;;; Properties
10627 ;;; Setting and retrieving properties
10629 (defconst org-special-properties
10630 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10631 "TIMESTAMP" "TIMESTAMP_IA")
10632 "The special properties valid in Org-mode.
10634 These are properties that are not defined in the property drawer,
10635 but in some other way.")
10637 (defconst org-default-properties
10638 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10639 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10640 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10641 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10642 "Some properties that are used by Org-mode for various purposes.
10643 Being in this list makes sure that they are offered for completion.")
10645 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10646 "Regular expression matching the first line of a property drawer.")
10648 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10649 "Regular expression matching the first line of a property drawer.")
10651 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10652 "Regular expression matching the first line of a property drawer.")
10654 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10655 "Regular expression matching the first line of a property drawer.")
10657 (defconst org-property-drawer-re
10658 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10659 org-property-end-re "\\)\n?")
10660 "Matches an entire property drawer.")
10662 (defconst org-clock-drawer-re
10663 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10664 org-property-end-re "\\)\n?")
10665 "Matches an entire clock drawer.")
10667 (defun org-property-action ()
10668 "Do an action on properties."
10669 (interactive)
10670 (let (c)
10671 (org-at-property-p)
10672 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10673 (setq c (read-char-exclusive))
10674 (cond
10675 ((equal c ?s)
10676 (call-interactively 'org-set-property))
10677 ((equal c ?d)
10678 (call-interactively 'org-delete-property))
10679 ((equal c ?D)
10680 (call-interactively 'org-delete-property-globally))
10681 ((equal c ?c)
10682 (call-interactively 'org-compute-property-at-point))
10683 (t (error "No such property action %c" c)))))
10685 (defun org-at-property-p ()
10686 "Is the cursor in a property line?"
10687 ;; FIXME: Does not check if we are actually in the drawer.
10688 ;; FIXME: also returns true on any drawers.....
10689 ;; This is used by C-c C-c for property action.
10690 (save-excursion
10691 (beginning-of-line 1)
10692 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10694 (defun org-get-property-block (&optional beg end force)
10695 "Return the (beg . end) range of the body of the property drawer.
10696 BEG and END can be beginning and end of subtree, if not given
10697 they will be found.
10698 If the drawer does not exist and FORCE is non-nil, create the drawer."
10699 (catch 'exit
10700 (save-excursion
10701 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10702 (end (or end (progn (outline-next-heading) (point)))))
10703 (goto-char beg)
10704 (if (re-search-forward org-property-start-re end t)
10705 (setq beg (1+ (match-end 0)))
10706 (if force
10707 (save-excursion
10708 (org-insert-property-drawer)
10709 (setq end (progn (outline-next-heading) (point))))
10710 (throw 'exit nil))
10711 (goto-char beg)
10712 (if (re-search-forward org-property-start-re end t)
10713 (setq beg (1+ (match-end 0)))))
10714 (if (re-search-forward org-property-end-re end t)
10715 (setq end (match-beginning 0))
10716 (or force (throw 'exit nil))
10717 (goto-char beg)
10718 (setq end beg)
10719 (org-indent-line-function)
10720 (insert ":END:\n"))
10721 (cons beg end)))))
10723 (defun org-entry-properties (&optional pom which)
10724 "Get all properties of the entry at point-or-marker POM.
10725 This includes the TODO keyword, the tags, time strings for deadline,
10726 scheduled, and clocking, and any additional properties defined in the
10727 entry. The return value is an alist, keys may occur multiple times
10728 if the property key was used several times.
10729 POM may also be nil, in which case the current entry is used.
10730 If WHICH is nil or `all', get all properties. If WHICH is
10731 `special' or `standard', only get that subclass."
10732 (setq which (or which 'all))
10733 (org-with-point-at pom
10734 (let ((clockstr (substring org-clock-string 0 -1))
10735 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10736 beg end range props sum-props key value string clocksum)
10737 (save-excursion
10738 (when (condition-case nil
10739 (and (org-mode-p) (org-back-to-heading t))
10740 (error nil))
10741 (setq beg (point))
10742 (setq sum-props (get-text-property (point) 'org-summaries))
10743 (setq clocksum (get-text-property (point) :org-clock-minutes))
10744 (outline-next-heading)
10745 (setq end (point))
10746 (when (memq which '(all special))
10747 ;; Get the special properties, like TODO and tags
10748 (goto-char beg)
10749 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10750 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10751 (when (looking-at org-priority-regexp)
10752 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10753 (when (and (setq value (org-get-tags-string))
10754 (string-match "\\S-" value))
10755 (push (cons "TAGS" value) props))
10756 (when (setq value (org-get-tags-at))
10757 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10758 props))
10759 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10760 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10761 string (if (equal key clockstr)
10762 (org-no-properties
10763 (org-trim
10764 (buffer-substring
10765 (match-beginning 3) (goto-char (point-at-eol)))))
10766 (substring (org-match-string-no-properties 3) 1 -1)))
10767 (unless key
10768 (if (= (char-after (match-beginning 3)) ?\[)
10769 (setq key "TIMESTAMP_IA")
10770 (setq key "TIMESTAMP")))
10771 (when (or (equal key clockstr) (not (assoc key props)))
10772 (push (cons key string) props)))
10776 (when (memq which '(all standard))
10777 ;; Get the standard properties, like :PORP: ...
10778 (setq range (org-get-property-block beg end))
10779 (when range
10780 (goto-char (car range))
10781 (while (re-search-forward
10782 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10783 (cdr range) t)
10784 (setq key (org-match-string-no-properties 1)
10785 value (org-trim (or (org-match-string-no-properties 2) "")))
10786 (unless (member key excluded)
10787 (push (cons key (or value "")) props)))))
10788 (if clocksum
10789 (push (cons "CLOCKSUM"
10790 (org-columns-number-to-string (/ (float clocksum) 60.)
10791 'add_times))
10792 props))
10793 (unless (assoc "CATEGORY" props)
10794 (setq value (or (org-get-category)
10795 (progn (org-refresh-category-properties)
10796 (org-get-category))))
10797 (push (cons "CATEGORY" value) props))
10798 (append sum-props (nreverse props)))))))
10800 (defun org-entry-get (pom property &optional inherit)
10801 "Get value of PROPERTY for entry at point-or-marker POM.
10802 If INHERIT is non-nil and the entry does not have the property,
10803 then also check higher levels of the hierarchy.
10804 If INHERIT is the symbol `selective', use inheritance only if the setting
10805 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10806 If the property is present but empty, the return value is the empty string.
10807 If the property is not present at all, nil is returned."
10808 (org-with-point-at pom
10809 (if (and inherit (if (eq inherit 'selective)
10810 (org-property-inherit-p property)
10812 (org-entry-get-with-inheritance property)
10813 (if (member property org-special-properties)
10814 ;; We need a special property. Use brute force, get all properties.
10815 (cdr (assoc property (org-entry-properties nil 'special)))
10816 (let ((range (org-get-property-block)))
10817 (if (and range
10818 (goto-char (car range))
10819 (re-search-forward
10820 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10821 (cdr range) t))
10822 ;; Found the property, return it.
10823 (if (match-end 1)
10824 (org-match-string-no-properties 1)
10825 "")))))))
10827 (defun org-property-or-variable-value (var &optional inherit)
10828 "Check if there is a property fixing the value of VAR.
10829 If yes, return this value. If not, return the current value of the variable."
10830 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10831 (if (and prop (stringp prop) (string-match "\\S-" prop))
10832 (read prop)
10833 (symbol-value var))))
10835 (defun org-entry-delete (pom property)
10836 "Delete the property PROPERTY from entry at point-or-marker POM."
10837 (org-with-point-at pom
10838 (if (member property org-special-properties)
10839 nil ; cannot delete these properties.
10840 (let ((range (org-get-property-block)))
10841 (if (and range
10842 (goto-char (car range))
10843 (re-search-forward
10844 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10845 (cdr range) t))
10846 (progn
10847 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10849 nil)))))
10851 ;; Multi-values properties are properties that contain multiple values
10852 ;; These values are assumed to be single words, separated by whitespace.
10853 (defun org-entry-add-to-multivalued-property (pom property value)
10854 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10855 (let* ((old (org-entry-get pom property))
10856 (values (and old (org-split-string old "[ \t]"))))
10857 (setq value (org-entry-protect-space value))
10858 (unless (member value values)
10859 (setq values (cons value values))
10860 (org-entry-put pom property
10861 (mapconcat 'identity values " ")))))
10863 (defun org-entry-remove-from-multivalued-property (pom property value)
10864 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10865 (let* ((old (org-entry-get pom property))
10866 (values (and old (org-split-string old "[ \t]"))))
10867 (setq value (org-entry-protect-space value))
10868 (when (member value values)
10869 (setq values (delete value values))
10870 (org-entry-put pom property
10871 (mapconcat 'identity values " ")))))
10873 (defun org-entry-member-in-multivalued-property (pom property value)
10874 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10875 (let* ((old (org-entry-get pom property))
10876 (values (and old (org-split-string old "[ \t]"))))
10877 (setq value (org-entry-protect-space value))
10878 (member value values)))
10880 (defun org-entry-get-multivalued-property (pom property)
10881 "Return a list of values in a multivalued property."
10882 (let* ((value (org-entry-get pom property))
10883 (values (and value (org-split-string value "[ \t]"))))
10884 (mapcar 'org-entry-restore-space values)))
10886 (defun org-entry-put-multivalued-property (pom property &rest values)
10887 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10888 VALUES should be a list of strings. Spaces will be protected."
10889 (org-entry-put pom property
10890 (mapconcat 'org-entry-protect-space values " "))
10891 (let* ((value (org-entry-get pom property))
10892 (values (and value (org-split-string value "[ \t]"))))
10893 (mapcar 'org-entry-restore-space values)))
10895 (defun org-entry-protect-space (s)
10896 "Protect spaces and newline in string S."
10897 (while (string-match " " s)
10898 (setq s (replace-match "%20" t t s)))
10899 (while (string-match "\n" s)
10900 (setq s (replace-match "%0A" t t s)))
10903 (defun org-entry-restore-space (s)
10904 "Restore spaces and newline in string S."
10905 (while (string-match "%20" s)
10906 (setq s (replace-match " " t t s)))
10907 (while (string-match "%0A" s)
10908 (setq s (replace-match "\n" t t s)))
10911 (defvar org-entry-property-inherited-from (make-marker)
10912 "Marker pointing to the entry from where a property was inherited.
10913 Each call to `org-entry-get-with-inheritance' will set this marker to the
10914 location of the entry where the inheritance search matched. If there was
10915 no match, the marker will point nowhere.
10916 Note that also `org-entry-get' calls this function, if the INHERIT flag
10917 is set.")
10919 (defun org-entry-get-with-inheritance (property)
10920 "Get entry property, and search higher levels if not present."
10921 (move-marker org-entry-property-inherited-from nil)
10922 (let (tmp)
10923 (save-excursion
10924 (save-restriction
10925 (widen)
10926 (catch 'ex
10927 (while t
10928 (when (setq tmp (org-entry-get nil property))
10929 (org-back-to-heading t)
10930 (move-marker org-entry-property-inherited-from (point))
10931 (throw 'ex tmp))
10932 (or (org-up-heading-safe) (throw 'ex nil)))))
10933 (or tmp
10934 (cdr (assoc property org-file-properties))
10935 (cdr (assoc property org-global-properties))
10936 (cdr (assoc property org-global-properties-fixed))))))
10938 (defun org-entry-put (pom property value)
10939 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10940 (org-with-point-at pom
10941 (org-back-to-heading t)
10942 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10943 range)
10944 (cond
10945 ((equal property "TODO")
10946 (when (and (stringp value) (string-match "\\S-" value)
10947 (not (member value org-todo-keywords-1)))
10948 (error "\"%s\" is not a valid TODO state" value))
10949 (if (or (not value)
10950 (not (string-match "\\S-" value)))
10951 (setq value 'none))
10952 (org-todo value)
10953 (org-set-tags nil 'align))
10954 ((equal property "PRIORITY")
10955 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10956 (string-to-char value) ?\ ))
10957 (org-set-tags nil 'align))
10958 ((equal property "SCHEDULED")
10959 (if (re-search-forward org-scheduled-time-regexp end t)
10960 (cond
10961 ((eq value 'earlier) (org-timestamp-change -1 'day))
10962 ((eq value 'later) (org-timestamp-change 1 'day))
10963 (t (call-interactively 'org-schedule)))
10964 (call-interactively 'org-schedule)))
10965 ((equal property "DEADLINE")
10966 (if (re-search-forward org-deadline-time-regexp end t)
10967 (cond
10968 ((eq value 'earlier) (org-timestamp-change -1 'day))
10969 ((eq value 'later) (org-timestamp-change 1 'day))
10970 (t (call-interactively 'org-deadline)))
10971 (call-interactively 'org-deadline)))
10972 ((member property org-special-properties)
10973 (error "The %s property can not yet be set with `org-entry-put'"
10974 property))
10975 (t ; a non-special property
10976 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10977 (setq range (org-get-property-block beg end 'force))
10978 (goto-char (car range))
10979 (if (re-search-forward
10980 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10981 (progn
10982 (delete-region (match-beginning 1) (match-end 1))
10983 (goto-char (match-beginning 1)))
10984 (goto-char (cdr range))
10985 (insert "\n")
10986 (backward-char 1)
10987 (org-indent-line-function)
10988 (insert ":" property ":"))
10989 (and value (insert " " value))
10990 (org-indent-line-function)))))))
10992 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10993 "Get all property keys in the current buffer.
10994 With INCLUDE-SPECIALS, also list the special properties that reflect things
10995 like tags and TODO state.
10996 With INCLUDE-DEFAULTS, also include properties that has special meaning
10997 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10998 With INCLUDE-COLUMNS, also include property names given in COLUMN
10999 formats in the current buffer."
11000 (let (rtn range cfmt s p)
11001 (save-excursion
11002 (save-restriction
11003 (widen)
11004 (goto-char (point-min))
11005 (while (re-search-forward org-property-start-re nil t)
11006 (setq range (org-get-property-block))
11007 (goto-char (car range))
11008 (while (re-search-forward
11009 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11010 (cdr range) t)
11011 (add-to-list 'rtn (org-match-string-no-properties 1)))
11012 (outline-next-heading))))
11014 (when include-specials
11015 (setq rtn (append org-special-properties rtn)))
11017 (when include-defaults
11018 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11020 (when include-columns
11021 (save-excursion
11022 (save-restriction
11023 (widen)
11024 (goto-char (point-min))
11025 (while (re-search-forward
11026 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11027 nil t)
11028 (setq cfmt (match-string 2) s 0)
11029 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11030 cfmt s)
11031 (setq s (match-end 0)
11032 p (match-string 1 cfmt))
11033 (unless (or (equal p "ITEM")
11034 (member p org-special-properties))
11035 (add-to-list 'rtn (match-string 1 cfmt))))))))
11037 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11039 (defun org-property-values (key)
11040 "Return a list of all values of property KEY."
11041 (save-excursion
11042 (save-restriction
11043 (widen)
11044 (goto-char (point-min))
11045 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11046 values)
11047 (while (re-search-forward re nil t)
11048 (add-to-list 'values (org-trim (match-string 1))))
11049 (delete "" values)))))
11051 (defun org-insert-property-drawer ()
11052 "Insert a property drawer into the current entry."
11053 (interactive)
11054 (org-back-to-heading t)
11055 (looking-at outline-regexp)
11056 (let ((indent (- (match-end 0)(match-beginning 0)))
11057 (beg (point))
11058 (re (concat "^[ \t]*" org-keyword-time-regexp))
11059 end hiddenp)
11060 (outline-next-heading)
11061 (setq end (point))
11062 (goto-char beg)
11063 (while (re-search-forward re end t))
11064 (setq hiddenp (org-invisible-p))
11065 (end-of-line 1)
11066 (and (equal (char-after) ?\n) (forward-char 1))
11067 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11068 (if (member (match-string 1) '("CLOCK:" ":END:"))
11069 ;; just skip this line
11070 (beginning-of-line 2)
11071 ;; Drawer start, find the end
11072 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11073 (beginning-of-line 1)))
11074 (org-skip-over-state-notes)
11075 (skip-chars-backward " \t\n\r")
11076 (if (eq (char-before) ?*) (forward-char 1))
11077 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11078 (beginning-of-line 0)
11079 (org-indent-to-column indent)
11080 (beginning-of-line 2)
11081 (org-indent-to-column indent)
11082 (beginning-of-line 0)
11083 (if hiddenp
11084 (save-excursion
11085 (org-back-to-heading t)
11086 (hide-entry))
11087 (org-flag-drawer t))))
11089 (defun org-set-property (property value)
11090 "In the current entry, set PROPERTY to VALUE.
11091 When called interactively, this will prompt for a property name, offering
11092 completion on existing and default properties. And then it will prompt
11093 for a value, offering completion either on allowed values (via an inherited
11094 xxx_ALL property) or on existing values in other instances of this property
11095 in the current file."
11096 (interactive
11097 (let* ((completion-ignore-case t)
11098 (keys (org-buffer-property-keys nil t t))
11099 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11100 (prop (if (member prop0 keys)
11101 prop0
11102 (or (cdr (assoc (downcase prop0)
11103 (mapcar (lambda (x) (cons (downcase x) x))
11104 keys)))
11105 prop0)))
11106 (cur (org-entry-get nil prop))
11107 (allowed (org-property-get-allowed-values nil prop 'table))
11108 (existing (mapcar 'list (org-property-values prop)))
11109 (val (if allowed
11110 (org-completing-read "Value: " allowed nil 'req-match)
11111 (let (org-completion-use-ido)
11112 (org-completing-read
11113 (concat "Value" (if (and cur (string-match "\\S-" cur))
11114 (concat "[" cur "]") "")
11115 ": ")
11116 existing nil nil "" nil cur)))))
11117 (list prop (if (equal val "") cur val))))
11118 (unless (equal (org-entry-get nil property) value)
11119 (org-entry-put nil property value)))
11121 (defun org-delete-property (property)
11122 "In the current entry, delete PROPERTY."
11123 (interactive
11124 (let* ((completion-ignore-case t)
11125 (prop (org-ido-completing-read
11126 "Property: " (org-entry-properties nil 'standard))))
11127 (list prop)))
11128 (message "Property %s %s" property
11129 (if (org-entry-delete nil property)
11130 "deleted"
11131 "was not present in the entry")))
11133 (defun org-delete-property-globally (property)
11134 "Remove PROPERTY globally, from all entries."
11135 (interactive
11136 (let* ((completion-ignore-case t)
11137 (prop (org-ido-completing-read
11138 "Globally remove property: "
11139 (mapcar 'list (org-buffer-property-keys)))))
11140 (list prop)))
11141 (save-excursion
11142 (save-restriction
11143 (widen)
11144 (goto-char (point-min))
11145 (let ((cnt 0))
11146 (while (re-search-forward
11147 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11148 nil t)
11149 (setq cnt (1+ cnt))
11150 (replace-match ""))
11151 (message "Property \"%s\" removed from %d entries" property cnt)))))
11153 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11155 (defun org-compute-property-at-point ()
11156 "Compute the property at point.
11157 This looks for an enclosing column format, extracts the operator and
11158 then applies it to the property in the column format's scope."
11159 (interactive)
11160 (unless (org-at-property-p)
11161 (error "Not at a property"))
11162 (let ((prop (org-match-string-no-properties 2)))
11163 (org-columns-get-format-and-top-level)
11164 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11165 (error "No operator defined for property %s" prop))
11166 (org-columns-compute prop)))
11168 (defun org-property-get-allowed-values (pom property &optional table)
11169 "Get allowed values for the property PROPERTY.
11170 When TABLE is non-nil, return an alist that can directly be used for
11171 completion."
11172 (let (vals)
11173 (cond
11174 ((equal property "TODO")
11175 (setq vals (org-with-point-at pom
11176 (append org-todo-keywords-1 '("")))))
11177 ((equal property "PRIORITY")
11178 (let ((n org-lowest-priority))
11179 (while (>= n org-highest-priority)
11180 (push (char-to-string n) vals)
11181 (setq n (1- n)))))
11182 ((member property org-special-properties))
11184 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11186 (when (and vals (string-match "\\S-" vals))
11187 (setq vals (car (read-from-string (concat "(" vals ")"))))
11188 (setq vals (mapcar (lambda (x)
11189 (cond ((stringp x) x)
11190 ((numberp x) (number-to-string x))
11191 ((symbolp x) (symbol-name x))
11192 (t "???")))
11193 vals)))))
11194 (if table (mapcar 'list vals) vals)))
11196 (defun org-property-previous-allowed-value (&optional previous)
11197 "Switch to the next allowed value for this property."
11198 (interactive)
11199 (org-property-next-allowed-value t))
11201 (defun org-property-next-allowed-value (&optional previous)
11202 "Switch to the next allowed value for this property."
11203 (interactive)
11204 (unless (org-at-property-p)
11205 (error "Not at a property"))
11206 (let* ((key (match-string 2))
11207 (value (match-string 3))
11208 (allowed (or (org-property-get-allowed-values (point) key)
11209 (and (member value '("[ ]" "[-]" "[X]"))
11210 '("[ ]" "[X]"))))
11211 nval)
11212 (unless allowed
11213 (error "Allowed values for this property have not been defined"))
11214 (if previous (setq allowed (reverse allowed)))
11215 (if (member value allowed)
11216 (setq nval (car (cdr (member value allowed)))))
11217 (setq nval (or nval (car allowed)))
11218 (if (equal nval value)
11219 (error "Only one allowed value for this property"))
11220 (org-at-property-p)
11221 (replace-match (concat " :" key ": " nval) t t)
11222 (org-indent-line-function)
11223 (beginning-of-line 1)
11224 (skip-chars-forward " \t")))
11226 (defun org-find-entry-with-id (ident)
11227 "Locate the entry that contains the ID property with exact value IDENT.
11228 IDENT can be a string, a symbol or a number, this function will search for
11229 the string representation of it.
11230 Return the position where this entry starts, or nil if there is no such entry."
11231 (interactive "sID: ")
11232 (let ((id (cond
11233 ((stringp ident) ident)
11234 ((symbol-name ident) (symbol-name ident))
11235 ((numberp ident) (number-to-string ident))
11236 (t (error "IDENT %s must be a string, symbol or number" ident))))
11237 (case-fold-search nil))
11238 (save-excursion
11239 (save-restriction
11240 (widen)
11241 (goto-char (point-min))
11242 (when (re-search-forward
11243 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11244 nil t)
11245 (org-back-to-heading)
11246 (point))))))
11248 ;;;; Timestamps
11250 (defvar org-last-changed-timestamp nil)
11251 (defvar org-last-inserted-timestamp nil
11252 "The last time stamp inserted with `org-insert-time-stamp'.")
11253 (defvar org-time-was-given) ; dynamically scoped parameter
11254 (defvar org-end-time-was-given) ; dynamically scoped parameter
11255 (defvar org-ts-what) ; dynamically scoped parameter
11257 (defun org-time-stamp (arg &optional inactive)
11258 "Prompt for a date/time and insert a time stamp.
11259 If the user specifies a time like HH:MM, or if this command is called
11260 with a prefix argument, the time stamp will contain date and time.
11261 Otherwise, only the date will be included. All parts of a date not
11262 specified by the user will be filled in from the current date/time.
11263 So if you press just return without typing anything, the time stamp
11264 will represent the current date/time. If there is already a timestamp
11265 at the cursor, it will be modified."
11266 (interactive "P")
11267 (let* ((ts nil)
11268 (default-time
11269 ;; Default time is either today, or, when entering a range,
11270 ;; the range start.
11271 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11272 (save-excursion
11273 (re-search-backward
11274 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11275 (- (point) 20) t)))
11276 (apply 'encode-time (org-parse-time-string (match-string 1)))
11277 (current-time)))
11278 (default-input (and ts (org-get-compact-tod ts)))
11279 org-time-was-given org-end-time-was-given time)
11280 (cond
11281 ((and (org-at-timestamp-p t)
11282 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11283 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11284 (insert "--")
11285 (setq time (let ((this-command this-command))
11286 (org-read-date arg 'totime nil nil
11287 default-time default-input)))
11288 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11289 ((org-at-timestamp-p t)
11290 (setq time (let ((this-command this-command))
11291 (org-read-date arg 'totime nil nil default-time default-input)))
11292 (when (org-at-timestamp-p t) ; just to get the match data
11293 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11294 (replace-match "")
11295 (setq org-last-changed-timestamp
11296 (org-insert-time-stamp
11297 time (or org-time-was-given arg)
11298 inactive nil nil (list org-end-time-was-given))))
11299 (message "Timestamp updated"))
11301 (setq time (let ((this-command this-command))
11302 (org-read-date arg 'totime nil nil default-time default-input)))
11303 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11304 nil nil (list org-end-time-was-given))))))
11306 ;; FIXME: can we use this for something else, like computing time differences?
11307 (defun org-get-compact-tod (s)
11308 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11309 (let* ((t1 (match-string 1 s))
11310 (h1 (string-to-number (match-string 2 s)))
11311 (m1 (string-to-number (match-string 3 s)))
11312 (t2 (and (match-end 4) (match-string 5 s)))
11313 (h2 (and t2 (string-to-number (match-string 6 s))))
11314 (m2 (and t2 (string-to-number (match-string 7 s))))
11315 dh dm)
11316 (if (not t2)
11318 (setq dh (- h2 h1) dm (- m2 m1))
11319 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11320 (concat t1 "+" (number-to-string dh)
11321 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11323 (defun org-time-stamp-inactive (&optional arg)
11324 "Insert an inactive time stamp.
11325 An inactive time stamp is enclosed in square brackets instead of angle
11326 brackets. It is inactive in the sense that it does not trigger agenda entries,
11327 does not link to the calendar and cannot be changed with the S-cursor keys.
11328 So these are more for recording a certain time/date."
11329 (interactive "P")
11330 (org-time-stamp arg 'inactive))
11332 (defvar org-date-ovl (org-make-overlay 1 1))
11333 (org-overlay-put org-date-ovl 'face 'org-warning)
11334 (org-detach-overlay org-date-ovl)
11336 (defvar org-ans1) ; dynamically scoped parameter
11337 (defvar org-ans2) ; dynamically scoped parameter
11339 (defvar org-plain-time-of-day-regexp) ; defined below
11341 (defvar org-overriding-default-time nil) ; dynamically scoped
11342 (defvar org-read-date-overlay nil)
11343 (defvar org-dcst nil) ; dynamically scoped
11345 (defun org-read-date (&optional with-time to-time from-string prompt
11346 default-time default-input)
11347 "Read a date, possibly a time, and make things smooth for the user.
11348 The prompt will suggest to enter an ISO date, but you can also enter anything
11349 which will at least partially be understood by `parse-time-string'.
11350 Unrecognized parts of the date will default to the current day, month, year,
11351 hour and minute. If this command is called to replace a timestamp at point,
11352 of to enter the second timestamp of a range, the default time is taken from the
11353 existing stamp. For example,
11354 3-2-5 --> 2003-02-05
11355 feb 15 --> currentyear-02-15
11356 sep 12 9 --> 2009-09-12
11357 12:45 --> today 12:45
11358 22 sept 0:34 --> currentyear-09-22 0:34
11359 12 --> currentyear-currentmonth-12
11360 Fri --> nearest Friday (today or later)
11361 etc.
11363 Furthermore you can specify a relative date by giving, as the *first* thing
11364 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11365 change in days weeks, months, years.
11366 With a single plus or minus, the date is relative to today. With a double
11367 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11368 +4d --> four days from today
11369 +4 --> same as above
11370 +2w --> two weeks from today
11371 ++5 --> five days from default date
11373 The function understands only English month and weekday abbreviations,
11374 but this can be configured with the variables `parse-time-months' and
11375 `parse-time-weekdays'.
11377 While prompting, a calendar is popped up - you can also select the
11378 date with the mouse (button 1). The calendar shows a period of three
11379 months. To scroll it to other months, use the keys `>' and `<'.
11380 If you don't like the calendar, turn it off with
11381 \(setq org-read-date-popup-calendar nil)
11383 With optional argument TO-TIME, the date will immediately be converted
11384 to an internal time.
11385 With an optional argument WITH-TIME, the prompt will suggest to also
11386 insert a time. Note that when WITH-TIME is not set, you can still
11387 enter a time, and this function will inform the calling routine about
11388 this change. The calling routine may then choose to change the format
11389 used to insert the time stamp into the buffer to include the time.
11390 With optional argument FROM-STRING, read from this string instead from
11391 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11392 the time/date that is used for everything that is not specified by the
11393 user."
11394 (require 'parse-time)
11395 (let* ((org-time-stamp-rounding-minutes
11396 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11397 (org-dcst org-display-custom-times)
11398 (ct (org-current-time))
11399 (def (or org-overriding-default-time default-time ct))
11400 (defdecode (decode-time def))
11401 (dummy (progn
11402 (when (< (nth 2 defdecode) org-extend-today-until)
11403 (setcar (nthcdr 2 defdecode) -1)
11404 (setcar (nthcdr 1 defdecode) 59)
11405 (setq def (apply 'encode-time defdecode)
11406 defdecode (decode-time def)))))
11407 (calendar-move-hook nil)
11408 (calendar-view-diary-initially-flag nil)
11409 (view-diary-entries-initially nil)
11410 (calendar-view-holidays-initially-flag nil)
11411 (view-calendar-holidays-initially nil)
11412 (timestr (format-time-string
11413 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11414 (prompt (concat (if prompt (concat prompt " ") "")
11415 (format "Date+time [%s]: " timestr)))
11416 ans (org-ans0 "") org-ans1 org-ans2 final)
11418 (cond
11419 (from-string (setq ans from-string))
11420 (org-read-date-popup-calendar
11421 (save-excursion
11422 (save-window-excursion
11423 (calendar)
11424 (calendar-forward-day (- (time-to-days def)
11425 (calendar-absolute-from-gregorian
11426 (calendar-current-date))))
11427 (org-eval-in-calendar nil t)
11428 (let* ((old-map (current-local-map))
11429 (map (copy-keymap calendar-mode-map))
11430 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11431 (org-defkey map (kbd "RET") 'org-calendar-select)
11432 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11433 'org-calendar-select-mouse)
11434 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11435 'org-calendar-select-mouse)
11436 (org-defkey minibuffer-local-map [(meta shift left)]
11437 (lambda () (interactive)
11438 (org-eval-in-calendar '(calendar-backward-month 1))))
11439 (org-defkey minibuffer-local-map [(meta shift right)]
11440 (lambda () (interactive)
11441 (org-eval-in-calendar '(calendar-forward-month 1))))
11442 (org-defkey minibuffer-local-map [(meta shift up)]
11443 (lambda () (interactive)
11444 (org-eval-in-calendar '(calendar-backward-year 1))))
11445 (org-defkey minibuffer-local-map [(meta shift down)]
11446 (lambda () (interactive)
11447 (org-eval-in-calendar '(calendar-forward-year 1))))
11448 (org-defkey minibuffer-local-map [(shift up)]
11449 (lambda () (interactive)
11450 (org-eval-in-calendar '(calendar-backward-week 1))))
11451 (org-defkey minibuffer-local-map [(shift down)]
11452 (lambda () (interactive)
11453 (org-eval-in-calendar '(calendar-forward-week 1))))
11454 (org-defkey minibuffer-local-map [(shift left)]
11455 (lambda () (interactive)
11456 (org-eval-in-calendar '(calendar-backward-day 1))))
11457 (org-defkey minibuffer-local-map [(shift right)]
11458 (lambda () (interactive)
11459 (org-eval-in-calendar '(calendar-forward-day 1))))
11460 (org-defkey minibuffer-local-map ">"
11461 (lambda () (interactive)
11462 (org-eval-in-calendar '(scroll-calendar-left 1))))
11463 (org-defkey minibuffer-local-map "<"
11464 (lambda () (interactive)
11465 (org-eval-in-calendar '(scroll-calendar-right 1))))
11466 (unwind-protect
11467 (progn
11468 (use-local-map map)
11469 (add-hook 'post-command-hook 'org-read-date-display)
11470 (setq org-ans0 (read-string prompt default-input nil nil))
11471 ;; org-ans0: from prompt
11472 ;; org-ans1: from mouse click
11473 ;; org-ans2: from calendar motion
11474 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11475 (remove-hook 'post-command-hook 'org-read-date-display)
11476 (use-local-map old-map)
11477 (when org-read-date-overlay
11478 (org-delete-overlay org-read-date-overlay)
11479 (setq org-read-date-overlay nil)))))))
11481 (t ; Naked prompt only
11482 (unwind-protect
11483 (setq ans (read-string prompt default-input nil timestr))
11484 (when org-read-date-overlay
11485 (org-delete-overlay org-read-date-overlay)
11486 (setq org-read-date-overlay nil)))))
11488 (setq final (org-read-date-analyze ans def defdecode))
11490 (if to-time
11491 (apply 'encode-time final)
11492 (if (and (boundp 'org-time-was-given) org-time-was-given)
11493 (format "%04d-%02d-%02d %02d:%02d"
11494 (nth 5 final) (nth 4 final) (nth 3 final)
11495 (nth 2 final) (nth 1 final))
11496 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11497 (defvar def)
11498 (defvar defdecode)
11499 (defvar with-time)
11500 (defun org-read-date-display ()
11501 "Display the current date prompt interpretation in the minibuffer."
11502 (when org-read-date-display-live
11503 (when org-read-date-overlay
11504 (org-delete-overlay org-read-date-overlay))
11505 (let ((p (point)))
11506 (end-of-line 1)
11507 (while (not (equal (buffer-substring
11508 (max (point-min) (- (point) 4)) (point))
11509 " "))
11510 (insert " "))
11511 (goto-char p))
11512 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11513 " " (or org-ans1 org-ans2)))
11514 (org-end-time-was-given nil)
11515 (f (org-read-date-analyze ans def defdecode))
11516 (fmts (if org-dcst
11517 org-time-stamp-custom-formats
11518 org-time-stamp-formats))
11519 (fmt (if (or with-time
11520 (and (boundp 'org-time-was-given) org-time-was-given))
11521 (cdr fmts)
11522 (car fmts)))
11523 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11524 (when (and org-end-time-was-given
11525 (string-match org-plain-time-of-day-regexp txt))
11526 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11527 org-end-time-was-given
11528 (substring txt (match-end 0)))))
11529 (setq org-read-date-overlay
11530 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11531 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11533 (defun org-read-date-analyze (ans def defdecode)
11534 "Analyse the combined answer of the date prompt."
11535 ;; FIXME: cleanup and comment
11536 (let (delta deltan deltaw deltadef year month day
11537 hour minute second wday pm h2 m2 tl wday1
11538 iso-year iso-weekday iso-week iso-year iso-date)
11540 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11541 (setq ans "+0"))
11543 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11544 (setq ans (replace-match "" t t ans)
11545 deltan (car delta)
11546 deltaw (nth 1 delta)
11547 deltadef (nth 2 delta)))
11549 ;; Check if there is an iso week date in there
11550 ;; If yes, sore the info and postpone interpreting it until the rest
11551 ;; of the parsing is done
11552 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11553 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11554 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11555 iso-week (string-to-number (match-string 2 ans)))
11556 (setq ans (replace-match "" t t ans)))
11558 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11559 (when (string-match
11560 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11561 (setq year (if (match-end 2)
11562 (string-to-number (match-string 2 ans))
11563 (string-to-number (format-time-string "%Y")))
11564 month (string-to-number (match-string 3 ans))
11565 day (string-to-number (match-string 4 ans)))
11566 (if (< year 100) (setq year (+ 2000 year)))
11567 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11568 t nil ans)))
11569 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11570 ;; If there is a time with am/pm, and *no* time without it, we convert
11571 ;; so that matching will be successful.
11572 (loop for i from 1 to 2 do ; twice, for end time as well
11573 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11574 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11575 (setq hour (string-to-number (match-string 1 ans))
11576 minute (if (match-end 3)
11577 (string-to-number (match-string 3 ans))
11579 pm (equal ?p
11580 (string-to-char (downcase (match-string 4 ans)))))
11581 (if (and (= hour 12) (not pm))
11582 (setq hour 0)
11583 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11584 (setq ans (replace-match (format "%02d:%02d" hour minute)
11585 t t ans))))
11587 ;; Check if a time range is given as a duration
11588 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11589 (setq hour (string-to-number (match-string 1 ans))
11590 h2 (+ hour (string-to-number (match-string 3 ans)))
11591 minute (string-to-number (match-string 2 ans))
11592 m2 (+ minute (if (match-end 5) (string-to-number
11593 (match-string 5 ans))0)))
11594 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11595 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11596 t t ans)))
11598 ;; Check if there is a time range
11599 (when (boundp 'org-end-time-was-given)
11600 (setq org-time-was-given nil)
11601 (when (and (string-match org-plain-time-of-day-regexp ans)
11602 (match-end 8))
11603 (setq org-end-time-was-given (match-string 8 ans))
11604 (setq ans (concat (substring ans 0 (match-beginning 7))
11605 (substring ans (match-end 7))))))
11607 (setq tl (parse-time-string ans)
11608 day (or (nth 3 tl) (nth 3 defdecode))
11609 month (or (nth 4 tl)
11610 (if (and org-read-date-prefer-future
11611 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11612 (1+ (nth 4 defdecode))
11613 (nth 4 defdecode)))
11614 year (or (nth 5 tl)
11615 (if (and org-read-date-prefer-future
11616 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11617 (1+ (nth 5 defdecode))
11618 (nth 5 defdecode)))
11619 hour (or (nth 2 tl) (nth 2 defdecode))
11620 minute (or (nth 1 tl) (nth 1 defdecode))
11621 second (or (nth 0 tl) 0)
11622 wday (nth 6 tl))
11624 ;; Special date definitions below
11625 (cond
11626 (iso-week
11627 ;; There was an iso week
11628 (setq year (or iso-year year)
11629 day (or iso-weekday wday 1)
11630 wday nil ; to make sure that the trigger below does not match
11631 iso-date (calendar-gregorian-from-absolute
11632 (calendar-absolute-from-iso
11633 (list iso-week day year))))
11634 ; FIXME: Should we also push ISO weeks into the future?
11635 ; (when (and org-read-date-prefer-future
11636 ; (not iso-year)
11637 ; (< (calendar-absolute-from-gregorian iso-date)
11638 ; (time-to-days (current-time))))
11639 ; (setq year (1+ year)
11640 ; iso-date (calendar-gregorian-from-absolute
11641 ; (calendar-absolute-from-iso
11642 ; (list iso-week day year)))))
11643 (setq month (car iso-date)
11644 year (nth 2 iso-date)
11645 day (nth 1 iso-date)))
11646 (deltan
11647 (unless deltadef
11648 (let ((now (decode-time (current-time))))
11649 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11650 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11651 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11652 ((equal deltaw "m") (setq month (+ month deltan)))
11653 ((equal deltaw "y") (setq year (+ year deltan)))))
11654 ((and wday (not (nth 3 tl)))
11655 ;; Weekday was given, but no day, so pick that day in the week
11656 ;; on or after the derived date.
11657 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11658 (unless (equal wday wday1)
11659 (setq day (+ day (% (- wday wday1 -7) 7))))))
11660 (if (and (boundp 'org-time-was-given)
11661 (nth 2 tl))
11662 (setq org-time-was-given t))
11663 (if (< year 100) (setq year (+ 2000 year)))
11664 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11665 (list second minute hour day month year)))
11667 (defvar parse-time-weekdays)
11669 (defun org-read-date-get-relative (s today default)
11670 "Check string S for special relative date string.
11671 TODAY and DEFAULT are internal times, for today and for a default.
11672 Return shift list (N what def-flag)
11673 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11674 N is the number of WHATs to shift.
11675 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11676 the DEFAULT date rather than TODAY."
11677 (when (and
11678 (string-match
11679 (concat
11680 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11681 "\\([0-9]+\\)?"
11682 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11683 "\\([ \t]\\|$\\)") s)
11684 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11685 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11686 (string-to-char (substring (match-string 1 s) -1))
11687 ?+))
11688 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11689 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11690 (what (if (match-end 3) (match-string 3 s) "d"))
11691 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11692 (date (if rel default today))
11693 (wday (nth 6 (decode-time date)))
11694 delta)
11695 (if wday1
11696 (progn
11697 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11698 (if (= dir ?-) (setq delta (- delta 7)))
11699 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11700 (list delta "d" rel))
11701 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11703 (defun org-eval-in-calendar (form &optional keepdate)
11704 "Eval FORM in the calendar window and return to current window.
11705 Also, store the cursor date in variable org-ans2."
11706 (let ((sw (selected-window)))
11707 (select-window (get-buffer-window "*Calendar*"))
11708 (eval form)
11709 (when (and (not keepdate) (calendar-cursor-to-date))
11710 (let* ((date (calendar-cursor-to-date))
11711 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11712 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11713 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11714 (select-window sw)))
11716 (defun org-calendar-select ()
11717 "Return to `org-read-date' with the date currently selected.
11718 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11719 (interactive)
11720 (when (calendar-cursor-to-date)
11721 (let* ((date (calendar-cursor-to-date))
11722 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11723 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11724 (if (active-minibuffer-window) (exit-minibuffer))))
11726 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11727 "Insert a date stamp for the date given by the internal TIME.
11728 WITH-HM means, use the stamp format that includes the time of the day.
11729 INACTIVE means use square brackets instead of angular ones, so that the
11730 stamp will not contribute to the agenda.
11731 PRE and POST are optional strings to be inserted before and after the
11732 stamp.
11733 The command returns the inserted time stamp."
11734 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11735 stamp)
11736 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11737 (insert-before-markers (or pre ""))
11738 (insert-before-markers (setq stamp (format-time-string fmt time)))
11739 (when (listp extra)
11740 (setq extra (car extra))
11741 (if (and (stringp extra)
11742 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11743 (setq extra (format "-%02d:%02d"
11744 (string-to-number (match-string 1 extra))
11745 (string-to-number (match-string 2 extra))))
11746 (setq extra nil)))
11747 (when extra
11748 (backward-char 1)
11749 (insert-before-markers extra)
11750 (forward-char 1))
11751 (insert-before-markers (or post ""))
11752 (setq org-last-inserted-timestamp stamp)))
11754 (defun org-toggle-time-stamp-overlays ()
11755 "Toggle the use of custom time stamp formats."
11756 (interactive)
11757 (setq org-display-custom-times (not org-display-custom-times))
11758 (unless org-display-custom-times
11759 (let ((p (point-min)) (bmp (buffer-modified-p)))
11760 (while (setq p (next-single-property-change p 'display))
11761 (if (and (get-text-property p 'display)
11762 (eq (get-text-property p 'face) 'org-date))
11763 (remove-text-properties
11764 p (setq p (next-single-property-change p 'display))
11765 '(display t))))
11766 (set-buffer-modified-p bmp)))
11767 (if (featurep 'xemacs)
11768 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11769 (org-restart-font-lock)
11770 (setq org-table-may-need-update t)
11771 (if org-display-custom-times
11772 (message "Time stamps are overlayed with custom format")
11773 (message "Time stamp overlays removed")))
11775 (defun org-display-custom-time (beg end)
11776 "Overlay modified time stamp format over timestamp between BEG and END."
11777 (let* ((ts (buffer-substring beg end))
11778 t1 w1 with-hm tf time str w2 (off 0))
11779 (save-match-data
11780 (setq t1 (org-parse-time-string ts t))
11781 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11782 (setq off (- (match-end 0) (match-beginning 0)))))
11783 (setq end (- end off))
11784 (setq w1 (- end beg)
11785 with-hm (and (nth 1 t1) (nth 2 t1))
11786 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11787 time (org-fix-decoded-time t1)
11788 str (org-add-props
11789 (format-time-string
11790 (substring tf 1 -1) (apply 'encode-time time))
11791 nil 'mouse-face 'highlight)
11792 w2 (length str))
11793 (if (not (= w2 w1))
11794 (add-text-properties (1+ beg) (+ 2 beg)
11795 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11796 (if (featurep 'xemacs)
11797 (progn
11798 (put-text-property beg end 'invisible t)
11799 (put-text-property beg end 'end-glyph (make-glyph str)))
11800 (put-text-property beg end 'display str))))
11802 (defun org-translate-time (string)
11803 "Translate all timestamps in STRING to custom format.
11804 But do this only if the variable `org-display-custom-times' is set."
11805 (when org-display-custom-times
11806 (save-match-data
11807 (let* ((start 0)
11808 (re org-ts-regexp-both)
11809 t1 with-hm inactive tf time str beg end)
11810 (while (setq start (string-match re string start))
11811 (setq beg (match-beginning 0)
11812 end (match-end 0)
11813 t1 (save-match-data
11814 (org-parse-time-string (substring string beg end) t))
11815 with-hm (and (nth 1 t1) (nth 2 t1))
11816 inactive (equal (substring string beg (1+ beg)) "[")
11817 tf (funcall (if with-hm 'cdr 'car)
11818 org-time-stamp-custom-formats)
11819 time (org-fix-decoded-time t1)
11820 str (format-time-string
11821 (concat
11822 (if inactive "[" "<") (substring tf 1 -1)
11823 (if inactive "]" ">"))
11824 (apply 'encode-time time))
11825 string (replace-match str t t string)
11826 start (+ start (length str)))))))
11827 string)
11829 (defun org-fix-decoded-time (time)
11830 "Set 0 instead of nil for the first 6 elements of time.
11831 Don't touch the rest."
11832 (let ((n 0))
11833 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11835 (defun org-days-to-time (timestamp-string)
11836 "Difference between TIMESTAMP-STRING and now in days."
11837 (- (time-to-days (org-time-string-to-time timestamp-string))
11838 (time-to-days (current-time))))
11840 (defun org-deadline-close (timestamp-string &optional ndays)
11841 "Is the time in TIMESTAMP-STRING close to the current date?"
11842 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11843 (and (< (org-days-to-time timestamp-string) ndays)
11844 (not (org-entry-is-done-p))))
11846 (defun org-get-wdays (ts)
11847 "Get the deadline lead time appropriate for timestring TS."
11848 (cond
11849 ((<= org-deadline-warning-days 0)
11850 ;; 0 or negative, enforce this value no matter what
11851 (- org-deadline-warning-days))
11852 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11853 ;; lead time is specified.
11854 (floor (* (string-to-number (match-string 1 ts))
11855 (cdr (assoc (match-string 2 ts)
11856 '(("d" . 1) ("w" . 7)
11857 ("m" . 30.4) ("y" . 365.25)))))))
11858 ;; go for the default.
11859 (t org-deadline-warning-days)))
11861 (defun org-calendar-select-mouse (ev)
11862 "Return to `org-read-date' with the date currently selected.
11863 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11864 (interactive "e")
11865 (mouse-set-point ev)
11866 (when (calendar-cursor-to-date)
11867 (let* ((date (calendar-cursor-to-date))
11868 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11869 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11870 (if (active-minibuffer-window) (exit-minibuffer))))
11872 (defun org-check-deadlines (ndays)
11873 "Check if there are any deadlines due or past due.
11874 A deadline is considered due if it happens within `org-deadline-warning-days'
11875 days from today's date. If the deadline appears in an entry marked DONE,
11876 it is not shown. The prefix arg NDAYS can be used to test that many
11877 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11878 (interactive "P")
11879 (let* ((org-warn-days
11880 (cond
11881 ((equal ndays '(4)) 100000)
11882 (ndays (prefix-numeric-value ndays))
11883 (t (abs org-deadline-warning-days))))
11884 (case-fold-search nil)
11885 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11886 (callback
11887 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11889 (message "%d deadlines past-due or due within %d days"
11890 (org-occur regexp nil callback)
11891 org-warn-days)))
11893 (defun org-check-before-date (date)
11894 "Check if there are deadlines or scheduled entries before DATE."
11895 (interactive (list (org-read-date)))
11896 (let ((case-fold-search nil)
11897 (regexp (concat "\\<\\(" org-deadline-string
11898 "\\|" org-scheduled-string
11899 "\\) *<\\([^>]+\\)>"))
11900 (callback
11901 (lambda () (time-less-p
11902 (org-time-string-to-time (match-string 2))
11903 (org-time-string-to-time date)))))
11904 (message "%d entries before %s"
11905 (org-occur regexp nil callback) date)))
11907 (defun org-evaluate-time-range (&optional to-buffer)
11908 "Evaluate a time range by computing the difference between start and end.
11909 Normally the result is just printed in the echo area, but with prefix arg
11910 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11911 If the time range is actually in a table, the result is inserted into the
11912 next column.
11913 For time difference computation, a year is assumed to be exactly 365
11914 days in order to avoid rounding problems."
11915 (interactive "P")
11917 (org-clock-update-time-maybe)
11918 (save-excursion
11919 (unless (org-at-date-range-p t)
11920 (goto-char (point-at-bol))
11921 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11922 (if (not (org-at-date-range-p t))
11923 (error "Not at a time-stamp range, and none found in current line")))
11924 (let* ((ts1 (match-string 1))
11925 (ts2 (match-string 2))
11926 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11927 (match-end (match-end 0))
11928 (time1 (org-time-string-to-time ts1))
11929 (time2 (org-time-string-to-time ts2))
11930 (t1 (time-to-seconds time1))
11931 (t2 (time-to-seconds time2))
11932 (diff (abs (- t2 t1)))
11933 (negative (< (- t2 t1) 0))
11934 ;; (ys (floor (* 365 24 60 60)))
11935 (ds (* 24 60 60))
11936 (hs (* 60 60))
11937 (fy "%dy %dd %02d:%02d")
11938 (fy1 "%dy %dd")
11939 (fd "%dd %02d:%02d")
11940 (fd1 "%dd")
11941 (fh "%02d:%02d")
11942 y d h m align)
11943 (if havetime
11944 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11946 d (floor (/ diff ds)) diff (mod diff ds)
11947 h (floor (/ diff hs)) diff (mod diff hs)
11948 m (floor (/ diff 60)))
11949 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11951 d (floor (+ (/ diff ds) 0.5))
11952 h 0 m 0))
11953 (if (not to-buffer)
11954 (message "%s" (org-make-tdiff-string y d h m))
11955 (if (org-at-table-p)
11956 (progn
11957 (goto-char match-end)
11958 (setq align t)
11959 (and (looking-at " *|") (goto-char (match-end 0))))
11960 (goto-char match-end))
11961 (if (looking-at
11962 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11963 (replace-match ""))
11964 (if negative (insert " -"))
11965 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11966 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11967 (insert " " (format fh h m))))
11968 (if align (org-table-align))
11969 (message "Time difference inserted")))))
11971 (defun org-make-tdiff-string (y d h m)
11972 (let ((fmt "")
11973 (l nil))
11974 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11975 l (push y l)))
11976 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11977 l (push d l)))
11978 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11979 l (push h l)))
11980 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11981 l (push m l)))
11982 (apply 'format fmt (nreverse l))))
11984 (defun org-time-string-to-time (s)
11985 (apply 'encode-time (org-parse-time-string s)))
11987 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11988 "Convert a time stamp to an absolute day number.
11989 If there is a specifyer for a cyclic time stamp, get the closest date to
11990 DAYNR.
11991 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11992 (cond
11993 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11994 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11995 daynr
11996 (+ daynr 1000)))
11997 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11998 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11999 (time-to-days (current-time))) (match-string 0 s)
12000 prefer show-all))
12001 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12003 (defun org-days-to-iso-week (days)
12004 "Return the iso week number."
12005 (require 'cal-iso)
12006 (car (calendar-iso-from-absolute days)))
12008 (defun org-small-year-to-year (year)
12009 "Convert 2-digit years into 4-digit years.
12010 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12011 The year 2000 cannot be abbreviated. Any year larger than 99
12012 is returned unchanged."
12013 (if (< year 38)
12014 (setq year (+ 2000 year))
12015 (if (< year 100)
12016 (setq year (+ 1900 year))))
12017 year)
12019 (defun org-time-from-absolute (d)
12020 "Return the time corresponding to date D.
12021 D may be an absolute day number, or a calendar-type list (month day year)."
12022 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12023 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12025 (defun org-calendar-holiday ()
12026 "List of holidays, for Diary display in Org-mode."
12027 (require 'holidays)
12028 (let ((hl (funcall
12029 (if (fboundp 'calendar-check-holidays)
12030 'calendar-check-holidays 'check-calendar-holidays) date)))
12031 (if hl (mapconcat 'identity hl "; "))))
12033 (defun org-diary-sexp-entry (sexp entry date)
12034 "Process a SEXP diary ENTRY for DATE."
12035 (require 'diary-lib)
12036 (let ((result (if calendar-debug-sexp
12037 (let ((stack-trace-on-error t))
12038 (eval (car (read-from-string sexp))))
12039 (condition-case nil
12040 (eval (car (read-from-string sexp)))
12041 (error
12042 (beep)
12043 (message "Bad sexp at line %d in %s: %s"
12044 (org-current-line)
12045 (buffer-file-name) sexp)
12046 (sleep-for 2))))))
12047 (cond ((stringp result) result)
12048 ((and (consp result)
12049 (stringp (cdr result))) (cdr result))
12050 (result entry)
12051 (t nil))))
12053 (defun org-diary-to-ical-string (frombuf)
12054 "Get iCalendar entries from diary entries in buffer FROMBUF.
12055 This uses the icalendar.el library."
12056 (let* ((tmpdir (if (featurep 'xemacs)
12057 (temp-directory)
12058 temporary-file-directory))
12059 (tmpfile (make-temp-name
12060 (expand-file-name "orgics" tmpdir)))
12061 buf rtn b e)
12062 (save-excursion
12063 (set-buffer frombuf)
12064 (icalendar-export-region (point-min) (point-max) tmpfile)
12065 (setq buf (find-buffer-visiting tmpfile))
12066 (set-buffer buf)
12067 (goto-char (point-min))
12068 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12069 (setq b (match-beginning 0)))
12070 (goto-char (point-max))
12071 (if (re-search-backward "^END:VEVENT" nil t)
12072 (setq e (match-end 0)))
12073 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12074 (kill-buffer buf)
12075 (delete-file tmpfile)
12076 rtn))
12078 (defun org-closest-date (start current change prefer show-all)
12079 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12080 When PREFER is `past' return a date that is either CURRENT or past.
12081 When PREFER is `future', return a date that is either CURRENT or future.
12082 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12083 ;; Make the proper lists from the dates
12084 (catch 'exit
12085 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12086 dn dw sday cday n1 n2 n0
12087 d m y y1 y2 date1 date2 nmonths nm ny m2)
12089 (setq start (org-date-to-gregorian start)
12090 current (org-date-to-gregorian
12091 (if show-all
12092 current
12093 (time-to-days (current-time))))
12094 sday (calendar-absolute-from-gregorian start)
12095 cday (calendar-absolute-from-gregorian current))
12097 (if (<= cday sday) (throw 'exit sday))
12099 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12100 (setq dn (string-to-number (match-string 1 change))
12101 dw (cdr (assoc (match-string 2 change) a1)))
12102 (error "Invalid change specifyer: %s" change))
12103 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12104 (cond
12105 ((eq dw 'day)
12106 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12107 n2 (+ n1 dn)))
12108 ((eq dw 'year)
12109 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12110 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12111 (setq date1 (list m d y1)
12112 n1 (calendar-absolute-from-gregorian date1)
12113 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12114 n2 (calendar-absolute-from-gregorian date2)))
12115 ((eq dw 'month)
12116 ;; approx number of month between the two dates
12117 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12118 ;; How often does dn fit in there?
12119 (setq d (nth 1 start) m (car start) y (nth 2 start)
12120 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12121 m (+ m nm)
12122 ny (floor (/ m 12))
12123 y (+ y ny)
12124 m (- m (* ny 12)))
12125 (while (> m 12) (setq m (- m 12) y (1+ y)))
12126 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12127 (setq m2 (+ m dn) y2 y)
12128 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12129 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12130 (while (<= n2 cday)
12131 (setq n1 n2 m m2 y y2)
12132 (setq m2 (+ m dn) y2 y)
12133 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12134 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12135 ;; Make sure n1 is the earlier date
12136 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12137 (if show-all
12138 (cond
12139 ((eq prefer 'past) n1)
12140 ((eq prefer 'future) (if (= cday n1) n1 n2))
12141 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12142 (cond
12143 ((eq prefer 'past) n1)
12144 ((eq prefer 'future) (if (= cday n1) n1 n2))
12145 (t (if (= cday n1) n1 n2)))))))
12147 (defun org-date-to-gregorian (date)
12148 "Turn any specification of DATE into a gregorian date for the calendar."
12149 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12150 ((and (listp date) (= (length date) 3)) date)
12151 ((stringp date)
12152 (setq date (org-parse-time-string date))
12153 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12154 ((listp date)
12155 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12157 (defun org-parse-time-string (s &optional nodefault)
12158 "Parse the standard Org-mode time string.
12159 This should be a lot faster than the normal `parse-time-string'.
12160 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12161 hour and minute fields will be nil if not given."
12162 (if (string-match org-ts-regexp0 s)
12163 (list 0
12164 (if (or (match-beginning 8) (not nodefault))
12165 (string-to-number (or (match-string 8 s) "0")))
12166 (if (or (match-beginning 7) (not nodefault))
12167 (string-to-number (or (match-string 7 s) "0")))
12168 (string-to-number (match-string 4 s))
12169 (string-to-number (match-string 3 s))
12170 (string-to-number (match-string 2 s))
12171 nil nil nil)
12172 (make-list 9 0)))
12174 (defun org-timestamp-up (&optional arg)
12175 "Increase the date item at the cursor by one.
12176 If the cursor is on the year, change the year. If it is on the month or
12177 the day, change that.
12178 With prefix ARG, change by that many units."
12179 (interactive "p")
12180 (org-timestamp-change (prefix-numeric-value arg)))
12182 (defun org-timestamp-down (&optional arg)
12183 "Decrease the date item at the cursor by one.
12184 If the cursor is on the year, change the year. If it is on the month or
12185 the day, change that.
12186 With prefix ARG, change by that many units."
12187 (interactive "p")
12188 (org-timestamp-change (- (prefix-numeric-value arg))))
12190 (defun org-timestamp-up-day (&optional arg)
12191 "Increase the date in the time stamp by one day.
12192 With prefix ARG, change that many days."
12193 (interactive "p")
12194 (if (and (not (org-at-timestamp-p t))
12195 (org-on-heading-p))
12196 (org-todo 'up)
12197 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12199 (defun org-timestamp-down-day (&optional arg)
12200 "Decrease the date in the time stamp by one day.
12201 With prefix ARG, change that many days."
12202 (interactive "p")
12203 (if (and (not (org-at-timestamp-p t))
12204 (org-on-heading-p))
12205 (org-todo 'down)
12206 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12208 (defun org-at-timestamp-p (&optional inactive-ok)
12209 "Determine if the cursor is in or at a timestamp."
12210 (interactive)
12211 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12212 (pos (point))
12213 (ans (or (looking-at tsr)
12214 (save-excursion
12215 (skip-chars-backward "^[<\n\r\t")
12216 (if (> (point) (point-min)) (backward-char 1))
12217 (and (looking-at tsr)
12218 (> (- (match-end 0) pos) -1))))))
12219 (and ans
12220 (boundp 'org-ts-what)
12221 (setq org-ts-what
12222 (cond
12223 ((= pos (match-beginning 0)) 'bracket)
12224 ((= pos (1- (match-end 0))) 'bracket)
12225 ((org-pos-in-match-range pos 2) 'year)
12226 ((org-pos-in-match-range pos 3) 'month)
12227 ((org-pos-in-match-range pos 7) 'hour)
12228 ((org-pos-in-match-range pos 8) 'minute)
12229 ((or (org-pos-in-match-range pos 4)
12230 (org-pos-in-match-range pos 5)) 'day)
12231 ((and (> pos (or (match-end 8) (match-end 5)))
12232 (< pos (match-end 0)))
12233 (- pos (or (match-end 8) (match-end 5))))
12234 (t 'day))))
12235 ans))
12237 (defun org-toggle-timestamp-type ()
12238 "Toggle the type (<active> or [inactive]) of a time stamp."
12239 (interactive)
12240 (when (org-at-timestamp-p t)
12241 (let ((beg (match-beginning 0)) (end (match-end 0))
12242 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12243 (save-excursion
12244 (goto-char beg)
12245 (while (re-search-forward "[][<>]" end t)
12246 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12247 t t)))
12248 (message "Timestamp is now %sactive"
12249 (if (equal (char-after beg) ?<) "" "in")))))
12251 (defun org-timestamp-change (n &optional what)
12252 "Change the date in the time stamp at point.
12253 The date will be changed by N times WHAT. WHAT can be `day', `month',
12254 `year', `minute', `second'. If WHAT is not given, the cursor position
12255 in the timestamp determines what will be changed."
12256 (let ((pos (point))
12257 with-hm inactive
12258 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12259 org-ts-what
12260 extra rem
12261 ts time time0)
12262 (if (not (org-at-timestamp-p t))
12263 (error "Not at a timestamp"))
12264 (if (and (not what) (eq org-ts-what 'bracket))
12265 (org-toggle-timestamp-type)
12266 (if (and (not what) (not (eq org-ts-what 'day))
12267 org-display-custom-times
12268 (get-text-property (point) 'display)
12269 (not (get-text-property (1- (point)) 'display)))
12270 (setq org-ts-what 'day))
12271 (setq org-ts-what (or what org-ts-what)
12272 inactive (= (char-after (match-beginning 0)) ?\[)
12273 ts (match-string 0))
12274 (replace-match "")
12275 (if (string-match
12276 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12278 (setq extra (match-string 1 ts)))
12279 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12280 (setq with-hm t))
12281 (setq time0 (org-parse-time-string ts))
12282 (when (and (eq org-ts-what 'minute)
12283 (eq current-prefix-arg nil))
12284 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12285 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12286 (setcar (cdr time0) (+ (nth 1 time0)
12287 (if (> n 0) (- rem) (- dm rem))))))
12288 (setq time
12289 (encode-time (or (car time0) 0)
12290 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12291 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12292 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12293 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12294 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12295 (nthcdr 6 time0)))
12296 (when (integerp org-ts-what)
12297 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12298 (if (eq what 'calendar)
12299 (let ((cal-date (org-get-date-from-calendar)))
12300 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12301 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12302 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12303 (setcar time0 (or (car time0) 0))
12304 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12305 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12306 (setq time (apply 'encode-time time0))))
12307 (setq org-last-changed-timestamp
12308 (org-insert-time-stamp time with-hm inactive nil nil extra))
12309 (org-clock-update-time-maybe)
12310 (goto-char pos)
12311 ;; Try to recenter the calendar window, if any
12312 (if (and org-calendar-follow-timestamp-change
12313 (get-buffer-window "*Calendar*" t)
12314 (memq org-ts-what '(day month year)))
12315 (org-recenter-calendar (time-to-days time))))))
12317 (defun org-modify-ts-extra (s pos n dm)
12318 "Change the different parts of the lead-time and repeat fields in timestamp."
12319 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12320 ng h m new rem)
12321 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12322 (cond
12323 ((or (org-pos-in-match-range pos 2)
12324 (org-pos-in-match-range pos 3))
12325 (setq m (string-to-number (match-string 3 s))
12326 h (string-to-number (match-string 2 s)))
12327 (if (org-pos-in-match-range pos 2)
12328 (setq h (+ h n))
12329 (setq n (* dm (org-no-warnings (signum n))))
12330 (when (not (= 0 (setq rem (% m dm))))
12331 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12332 (setq m (+ m n)))
12333 (if (< m 0) (setq m (+ m 60) h (1- h)))
12334 (if (> m 59) (setq m (- m 60) h (1+ h)))
12335 (setq h (min 24 (max 0 h)))
12336 (setq ng 1 new (format "-%02d:%02d" h m)))
12337 ((org-pos-in-match-range pos 6)
12338 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12339 ((org-pos-in-match-range pos 5)
12340 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12342 ((org-pos-in-match-range pos 9)
12343 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12344 ((org-pos-in-match-range pos 8)
12345 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12347 (when ng
12348 (setq s (concat
12349 (substring s 0 (match-beginning ng))
12351 (substring s (match-end ng))))))
12354 (defun org-recenter-calendar (date)
12355 "If the calendar is visible, recenter it to DATE."
12356 (let* ((win (selected-window))
12357 (cwin (get-buffer-window "*Calendar*" t))
12358 (calendar-move-hook nil))
12359 (when cwin
12360 (select-window cwin)
12361 (calendar-goto-date (if (listp date) date
12362 (calendar-gregorian-from-absolute date)))
12363 (select-window win))))
12365 (defun org-goto-calendar (&optional arg)
12366 "Go to the Emacs calendar at the current date.
12367 If there is a time stamp in the current line, go to that date.
12368 A prefix ARG can be used to force the current date."
12369 (interactive "P")
12370 (let ((tsr org-ts-regexp) diff
12371 (calendar-move-hook nil)
12372 (calendar-view-holidays-initially-flag nil)
12373 (view-calendar-holidays-initially nil)
12374 (calendar-view-diary-initially-flag nil)
12375 (view-diary-entries-initially nil))
12376 (if (or (org-at-timestamp-p)
12377 (save-excursion
12378 (beginning-of-line 1)
12379 (looking-at (concat ".*" tsr))))
12380 (let ((d1 (time-to-days (current-time)))
12381 (d2 (time-to-days
12382 (org-time-string-to-time (match-string 1)))))
12383 (setq diff (- d2 d1))))
12384 (calendar)
12385 (calendar-goto-today)
12386 (if (and diff (not arg)) (calendar-forward-day diff))))
12388 (defun org-get-date-from-calendar ()
12389 "Return a list (month day year) of date at point in calendar."
12390 (with-current-buffer "*Calendar*"
12391 (save-match-data
12392 (calendar-cursor-to-date))))
12394 (defun org-date-from-calendar ()
12395 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12396 If there is already a time stamp at the cursor position, update it."
12397 (interactive)
12398 (if (org-at-timestamp-p t)
12399 (org-timestamp-change 0 'calendar)
12400 (let ((cal-date (org-get-date-from-calendar)))
12401 (org-insert-time-stamp
12402 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12404 (defun org-minutes-to-hh:mm-string (m)
12405 "Compute H:MM from a number of minutes."
12406 (let ((h (/ m 60)))
12407 (setq m (- m (* 60 h)))
12408 (format org-time-clocksum-format h m)))
12410 (defun org-hh:mm-string-to-minutes (s)
12411 "Convert a string H:MM to a number of minutes."
12412 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12413 (+ (* (string-to-number (match-string 1 s)) 60)
12414 (string-to-number (match-string 2 s)))
12417 ;;;; Files
12419 (defun org-save-all-org-buffers ()
12420 "Save all Org-mode buffers without user confirmation."
12421 (interactive)
12422 (message "Saving all Org-mode buffers...")
12423 (save-some-buffers t 'org-mode-p)
12424 (when (featurep 'org-id) (org-id-locations-save))
12425 (message "Saving all Org-mode buffers... done"))
12427 (defun org-revert-all-org-buffers ()
12428 "Revert all Org-mode buffers.
12429 Prompt for confirmation when there are unsaved changes.
12430 Be sure you know what you are doing before letting this function
12431 overwrite your changes.
12433 This function is useful in a setup where one tracks org files
12434 with a version control system, to revert on one machine after pulling
12435 changes from another. I believe the procedure must be like this:
12437 1. M-x org-save-all-org-buffers
12438 2. Pull changes from the other machine, resolve conflicts
12439 3. M-x org-revert-all-org-buffers"
12440 (interactive)
12441 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12442 (error "Abort"))
12443 (save-excursion
12444 (save-window-excursion
12445 (mapc
12446 (lambda (b)
12447 (when (and (with-current-buffer b (org-mode-p))
12448 (with-current-buffer b buffer-file-name))
12449 (switch-to-buffer b)
12450 (revert-buffer t 'no-confirm)))
12451 (buffer-list))
12452 (when (and (featurep 'org-id) org-id-track-globally)
12453 (org-id-locations-load)))))
12455 ;;;; Agenda files
12457 ;;;###autoload
12458 (defun org-iswitchb (&optional arg)
12459 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12460 With a prefix argument, restrict available to files.
12461 With two prefix arguments, restrict available buffers to agenda files.
12463 Due to some yet unresolved reason, the global function
12464 `iswitchb-mode' needs to be active for this function to work."
12465 (interactive "P")
12466 (require 'iswitchb)
12467 (let ((enabled iswitchb-mode) blist)
12468 (or enabled (iswitchb-mode 1))
12469 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12470 ((equal arg '(16)) (org-buffer-list 'agenda))
12471 (t (org-buffer-list))))
12472 (unwind-protect
12473 (let ((iswitchb-make-buflist-hook
12474 (lambda ()
12475 (setq iswitchb-temp-buflist
12476 (mapcar 'buffer-name blist)))))
12477 (switch-to-buffer
12478 (iswitchb-read-buffer
12479 "Switch-to: " nil t))
12480 (or enabled (iswitchb-mode -1))))))
12482 ;;;###autoload
12483 (defun org-ido-switchb (&optional arg)
12484 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12485 With a prefix argument, restrict available to files.
12486 With two prefix arguments, restrict available buffers to agenda files."
12487 (interactive "P")
12488 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12489 ((equal arg '(16)) (org-buffer-list 'agenda))
12490 (t (org-buffer-list)))))
12491 (switch-to-buffer
12492 (org-ido-completing-read "Org buffer: "
12493 (mapcar 'buffer-name blist)
12494 nil t))))
12496 (defun org-buffer-list (&optional predicate exclude-tmp)
12497 "Return a list of Org buffers.
12498 PREDICATE can be `export', `files' or `agenda'.
12500 export restrict the list to Export buffers.
12501 files restrict the list to buffers visiting Org files.
12502 agenda restrict the list to buffers visiting agenda files.
12504 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12505 (let* ((bfn nil)
12506 (agenda-files (and (eq predicate 'agenda)
12507 (mapcar 'file-truename (org-agenda-files t))))
12508 (filter
12509 (cond
12510 ((eq predicate 'files)
12511 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12512 ((eq predicate 'export)
12513 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12514 ((eq predicate 'agenda)
12515 (lambda (b)
12516 (with-current-buffer b
12517 (and (eq major-mode 'org-mode)
12518 (setq bfn (buffer-file-name b))
12519 (member (file-truename bfn) agenda-files)))))
12520 (t (lambda (b) (with-current-buffer b
12521 (or (eq major-mode 'org-mode)
12522 (string-match "\*Org .*Export"
12523 (buffer-name b)))))))))
12524 (delq nil
12525 (mapcar
12526 (lambda(b)
12527 (if (and (funcall filter b)
12528 (or (not exclude-tmp)
12529 (not (string-match "tmp" (buffer-name b)))))
12531 nil))
12532 (buffer-list)))))
12534 (defun org-agenda-files (&optional unrestricted archives)
12535 "Get the list of agenda files.
12536 Optional UNRESTRICTED means return the full list even if a restriction
12537 is currently in place.
12538 When ARCHIVES is t, include all archive files hat are really being
12539 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12540 `org-agenda-archives-mode' is t."
12541 (let ((files
12542 (cond
12543 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12544 ((stringp org-agenda-files) (org-read-agenda-file-list))
12545 ((listp org-agenda-files) org-agenda-files)
12546 (t (error "Invalid value of `org-agenda-files'")))))
12547 (setq files (apply 'append
12548 (mapcar (lambda (f)
12549 (if (file-directory-p f)
12550 (directory-files
12551 f t org-agenda-file-regexp)
12552 (list f)))
12553 files)))
12554 (when org-agenda-skip-unavailable-files
12555 (setq files (delq nil
12556 (mapcar (function
12557 (lambda (file)
12558 (and (file-readable-p file) file)))
12559 files))))
12560 (when (or (eq archives t)
12561 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12562 (setq files (org-add-archive-files files)))
12563 files))
12565 (defun org-edit-agenda-file-list ()
12566 "Edit the list of agenda files.
12567 Depending on setup, this either uses customize to edit the variable
12568 `org-agenda-files', or it visits the file that is holding the list. In the
12569 latter case, the buffer is set up in a way that saving it automatically kills
12570 the buffer and restores the previous window configuration."
12571 (interactive)
12572 (if (stringp org-agenda-files)
12573 (let ((cw (current-window-configuration)))
12574 (find-file org-agenda-files)
12575 (org-set-local 'org-window-configuration cw)
12576 (org-add-hook 'after-save-hook
12577 (lambda ()
12578 (set-window-configuration
12579 (prog1 org-window-configuration
12580 (kill-buffer (current-buffer))))
12581 (org-install-agenda-files-menu)
12582 (message "New agenda file list installed"))
12583 nil 'local)
12584 (message "%s" (substitute-command-keys
12585 "Edit list and finish with \\[save-buffer]")))
12586 (customize-variable 'org-agenda-files)))
12588 (defun org-store-new-agenda-file-list (list)
12589 "Set new value for the agenda file list and save it correctly."
12590 (if (stringp org-agenda-files)
12591 (let ((f org-agenda-files) b)
12592 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12593 (with-temp-file f
12594 (insert (mapconcat 'identity list "\n") "\n")))
12595 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12596 (setq org-agenda-files list)
12597 (customize-save-variable 'org-agenda-files org-agenda-files))))
12599 (defun org-read-agenda-file-list ()
12600 "Read the list of agenda files from a file."
12601 (when (file-directory-p org-agenda-files)
12602 (error "`org-agenda-files' cannot be a single directory"))
12603 (when (stringp org-agenda-files)
12604 (with-temp-buffer
12605 (insert-file-contents org-agenda-files)
12606 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12609 ;;;###autoload
12610 (defun org-cycle-agenda-files ()
12611 "Cycle through the files in `org-agenda-files'.
12612 If the current buffer visits an agenda file, find the next one in the list.
12613 If the current buffer does not, find the first agenda file."
12614 (interactive)
12615 (let* ((fs (org-agenda-files t))
12616 (files (append fs (list (car fs))))
12617 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12618 file)
12619 (unless files (error "No agenda files"))
12620 (catch 'exit
12621 (while (setq file (pop files))
12622 (if (equal (file-truename file) tcf)
12623 (when (car files)
12624 (find-file (car files))
12625 (throw 'exit t))))
12626 (find-file (car fs)))
12627 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12629 (defun org-agenda-file-to-front (&optional to-end)
12630 "Move/add the current file to the top of the agenda file list.
12631 If the file is not present in the list, it is added to the front. If it is
12632 present, it is moved there. With optional argument TO-END, add/move to the
12633 end of the list."
12634 (interactive "P")
12635 (let ((org-agenda-skip-unavailable-files nil)
12636 (file-alist (mapcar (lambda (x)
12637 (cons (file-truename x) x))
12638 (org-agenda-files t)))
12639 (ctf (file-truename buffer-file-name))
12640 x had)
12641 (setq x (assoc ctf file-alist) had x)
12643 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12644 (if to-end
12645 (setq file-alist (append (delq x file-alist) (list x)))
12646 (setq file-alist (cons x (delq x file-alist))))
12647 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12648 (org-install-agenda-files-menu)
12649 (message "File %s to %s of agenda file list"
12650 (if had "moved" "added") (if to-end "end" "front"))))
12652 (defun org-remove-file (&optional file)
12653 "Remove current file from the list of files in variable `org-agenda-files'.
12654 These are the files which are being checked for agenda entries.
12655 Optional argument FILE means, use this file instead of the current."
12656 (interactive)
12657 (let* ((org-agenda-skip-unavailable-files nil)
12658 (file (or file buffer-file-name))
12659 (true-file (file-truename file))
12660 (afile (abbreviate-file-name file))
12661 (files (delq nil (mapcar
12662 (lambda (x)
12663 (if (equal true-file
12664 (file-truename x))
12665 nil x))
12666 (org-agenda-files t)))))
12667 (if (not (= (length files) (length (org-agenda-files t))))
12668 (progn
12669 (org-store-new-agenda-file-list files)
12670 (org-install-agenda-files-menu)
12671 (message "Removed file: %s" afile))
12672 (message "File was not in list: %s (not removed)" afile))))
12674 (defun org-file-menu-entry (file)
12675 (vector file (list 'find-file file) t))
12677 (defun org-check-agenda-file (file)
12678 "Make sure FILE exists. If not, ask user what to do."
12679 (when (not (file-exists-p file))
12680 (message "non-existent file %s. [R]emove from list or [A]bort?"
12681 (abbreviate-file-name file))
12682 (let ((r (downcase (read-char-exclusive))))
12683 (cond
12684 ((equal r ?r)
12685 (org-remove-file file)
12686 (throw 'nextfile t))
12687 (t (error "Abort"))))))
12689 (defun org-get-agenda-file-buffer (file)
12690 "Get a buffer visiting FILE. If the buffer needs to be created, add
12691 it to the list of buffers which might be released later."
12692 (let ((buf (org-find-base-buffer-visiting file)))
12693 (if buf
12694 buf ; just return it
12695 ;; Make a new buffer and remember it
12696 (setq buf (find-file-noselect file))
12697 (if buf (push buf org-agenda-new-buffers))
12698 buf)))
12700 (defun org-release-buffers (blist)
12701 "Release all buffers in list, asking the user for confirmation when needed.
12702 When a buffer is unmodified, it is just killed. When modified, it is saved
12703 \(if the user agrees) and then killed."
12704 (let (buf file)
12705 (while (setq buf (pop blist))
12706 (setq file (buffer-file-name buf))
12707 (when (and (buffer-modified-p buf)
12708 file
12709 (y-or-n-p (format "Save file %s? " file)))
12710 (with-current-buffer buf (save-buffer)))
12711 (kill-buffer buf))))
12713 (defun org-prepare-agenda-buffers (files)
12714 "Create buffers for all agenda files, protect archived trees and comments."
12715 (interactive)
12716 (let ((pa '(:org-archived t))
12717 (pc '(:org-comment t))
12718 (pall '(:org-archived t :org-comment t))
12719 (inhibit-read-only t)
12720 (rea (concat ":" org-archive-tag ":"))
12721 bmp file re)
12722 (save-excursion
12723 (save-restriction
12724 (while (setq file (pop files))
12725 (if (bufferp file)
12726 (set-buffer file)
12727 (org-check-agenda-file file)
12728 (set-buffer (org-get-agenda-file-buffer file)))
12729 (widen)
12730 (setq bmp (buffer-modified-p))
12731 (org-refresh-category-properties)
12732 (setq org-todo-keywords-for-agenda
12733 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12734 (setq org-done-keywords-for-agenda
12735 (append org-done-keywords-for-agenda org-done-keywords))
12736 (setq org-todo-keyword-alist-for-agenda
12737 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12738 (setq org-tag-alist-for-agenda
12739 (append org-tag-alist-for-agenda org-tag-alist))
12741 (save-excursion
12742 (remove-text-properties (point-min) (point-max) pall)
12743 (when org-agenda-skip-archived-trees
12744 (goto-char (point-min))
12745 (while (re-search-forward rea nil t)
12746 (if (org-on-heading-p t)
12747 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12748 (goto-char (point-min))
12749 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12750 (while (re-search-forward re nil t)
12751 (add-text-properties
12752 (match-beginning 0) (org-end-of-subtree t) pc)))
12753 (set-buffer-modified-p bmp))))
12754 (setq org-todo-keyword-alist-for-agenda
12755 (org-uniquify org-todo-keyword-alist-for-agenda)
12756 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12758 ;;;; Embedded LaTeX
12760 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12761 "Keymap for the minor `org-cdlatex-mode'.")
12763 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12764 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12765 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12766 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12767 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12769 (defvar org-cdlatex-texmathp-advice-is-done nil
12770 "Flag remembering if we have applied the advice to texmathp already.")
12772 (define-minor-mode org-cdlatex-mode
12773 "Toggle the minor `org-cdlatex-mode'.
12774 This mode supports entering LaTeX environment and math in LaTeX fragments
12775 in Org-mode.
12776 \\{org-cdlatex-mode-map}"
12777 nil " OCDL" nil
12778 (when org-cdlatex-mode (require 'cdlatex))
12779 (unless org-cdlatex-texmathp-advice-is-done
12780 (setq org-cdlatex-texmathp-advice-is-done t)
12781 (defadvice texmathp (around org-math-always-on activate)
12782 "Always return t in org-mode buffers.
12783 This is because we want to insert math symbols without dollars even outside
12784 the LaTeX math segments. If Orgmode thinks that point is actually inside
12785 an embedded LaTeX fragment, let texmathp do its job.
12786 \\[org-cdlatex-mode-map]"
12787 (interactive)
12788 (let (p)
12789 (cond
12790 ((not (org-mode-p)) ad-do-it)
12791 ((eq this-command 'cdlatex-math-symbol)
12792 (setq ad-return-value t
12793 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12795 (let ((p (org-inside-LaTeX-fragment-p)))
12796 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12797 (setq ad-return-value t
12798 texmathp-why '("Org-mode embedded math" . 0))
12799 (if p ad-do-it)))))))))
12801 (defun turn-on-org-cdlatex ()
12802 "Unconditionally turn on `org-cdlatex-mode'."
12803 (org-cdlatex-mode 1))
12805 (defun org-inside-LaTeX-fragment-p ()
12806 "Test if point is inside a LaTeX fragment.
12807 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12808 sequence appearing also before point.
12809 Even though the matchers for math are configurable, this function assumes
12810 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12811 delimiters are skipped when they have been removed by customization.
12812 The return value is nil, or a cons cell with the delimiter and
12813 and the position of this delimiter.
12815 This function does a reasonably good job, but can locally be fooled by
12816 for example currency specifications. For example it will assume being in
12817 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12818 fragments that are properly closed, but during editing, we have to live
12819 with the uncertainty caused by missing closing delimiters. This function
12820 looks only before point, not after."
12821 (catch 'exit
12822 (let ((pos (point))
12823 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12824 (lim (progn
12825 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12826 (point)))
12827 dd-on str (start 0) m re)
12828 (goto-char pos)
12829 (when dodollar
12830 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12831 re (nth 1 (assoc "$" org-latex-regexps)))
12832 (while (string-match re str start)
12833 (cond
12834 ((= (match-end 0) (length str))
12835 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12836 ((= (match-end 0) (- (length str) 5))
12837 (throw 'exit nil))
12838 (t (setq start (match-end 0))))))
12839 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12840 (goto-char pos)
12841 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12842 (and (match-beginning 2) (throw 'exit nil))
12843 ;; count $$
12844 (while (re-search-backward "\\$\\$" lim t)
12845 (setq dd-on (not dd-on)))
12846 (goto-char pos)
12847 (if dd-on (cons "$$" m))))))
12850 (defun org-try-cdlatex-tab ()
12851 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12852 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12853 - inside a LaTeX fragment, or
12854 - after the first word in a line, where an abbreviation expansion could
12855 insert a LaTeX environment."
12856 (when org-cdlatex-mode
12857 (cond
12858 ((save-excursion
12859 (skip-chars-backward "a-zA-Z0-9*")
12860 (skip-chars-backward " \t")
12861 (bolp))
12862 (cdlatex-tab) t)
12863 ((org-inside-LaTeX-fragment-p)
12864 (cdlatex-tab) t)
12865 (t nil))))
12867 (defun org-cdlatex-underscore-caret (&optional arg)
12868 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12869 Revert to the normal definition outside of these fragments."
12870 (interactive "P")
12871 (if (org-inside-LaTeX-fragment-p)
12872 (call-interactively 'cdlatex-sub-superscript)
12873 (let (org-cdlatex-mode)
12874 (call-interactively (key-binding (vector last-input-event))))))
12876 (defun org-cdlatex-math-modify (&optional arg)
12877 "Execute `cdlatex-math-modify' in LaTeX fragments.
12878 Revert to the normal definition outside of these fragments."
12879 (interactive "P")
12880 (if (org-inside-LaTeX-fragment-p)
12881 (call-interactively 'cdlatex-math-modify)
12882 (let (org-cdlatex-mode)
12883 (call-interactively (key-binding (vector last-input-event))))))
12885 (defvar org-latex-fragment-image-overlays nil
12886 "List of overlays carrying the images of latex fragments.")
12887 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12889 (defun org-remove-latex-fragment-image-overlays ()
12890 "Remove all overlays with LaTeX fragment images in current buffer."
12891 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12892 (setq org-latex-fragment-image-overlays nil))
12894 (defun org-preview-latex-fragment (&optional subtree)
12895 "Preview the LaTeX fragment at point, or all locally or globally.
12896 If the cursor is in a LaTeX fragment, create the image and overlay
12897 it over the source code. If there is no fragment at point, display
12898 all fragments in the current text, from one headline to the next. With
12899 prefix SUBTREE, display all fragments in the current subtree. With a
12900 double prefix `C-u C-u', or when the cursor is before the first headline,
12901 display all fragments in the buffer.
12902 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12903 (interactive "P")
12904 (org-remove-latex-fragment-image-overlays)
12905 (save-excursion
12906 (save-restriction
12907 (let (beg end at msg)
12908 (cond
12909 ((or (equal subtree '(16))
12910 (not (save-excursion
12911 (re-search-backward (concat "^" outline-regexp) nil t))))
12912 (setq beg (point-min) end (point-max)
12913 msg "Creating images for buffer...%s"))
12914 ((equal subtree '(4))
12915 (org-back-to-heading)
12916 (setq beg (point) end (org-end-of-subtree t)
12917 msg "Creating images for subtree...%s"))
12919 (if (setq at (org-inside-LaTeX-fragment-p))
12920 (goto-char (max (point-min) (- (cdr at) 2)))
12921 (org-back-to-heading))
12922 (setq beg (point) end (progn (outline-next-heading) (point))
12923 msg (if at "Creating image...%s"
12924 "Creating images for entry...%s"))))
12925 (message msg "")
12926 (narrow-to-region beg end)
12927 (goto-char beg)
12928 (org-format-latex
12929 (concat "ltxpng/" (file-name-sans-extension
12930 (file-name-nondirectory
12931 buffer-file-name)))
12932 default-directory 'overlays msg at 'forbuffer)
12933 (message msg "done. Use `C-c C-c' to remove images.")))))
12935 (defvar org-latex-regexps
12936 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12937 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12938 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12939 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12940 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12941 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12942 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12943 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12944 "Regular expressions for matching embedded LaTeX.")
12946 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12947 "Replace LaTeX fragments with links to an image, and produce images."
12948 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12949 (let* ((prefixnodir (file-name-nondirectory prefix))
12950 (absprefix (expand-file-name prefix dir))
12951 (todir (file-name-directory absprefix))
12952 (opt org-format-latex-options)
12953 (matchers (plist-get opt :matchers))
12954 (re-list org-latex-regexps)
12955 (cnt 0) txt link beg end re e checkdir
12956 m n block linkfile movefile ov)
12957 ;; Check if there are old images files with this prefix, and remove them
12958 (when (file-directory-p todir)
12959 (mapc 'delete-file
12960 (directory-files
12961 todir 'full
12962 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12963 ;; Check the different regular expressions
12964 (while (setq e (pop re-list))
12965 (setq m (car e) re (nth 1 e) n (nth 2 e)
12966 block (if (nth 3 e) "\n\n" ""))
12967 (when (member m matchers)
12968 (goto-char (point-min))
12969 (while (re-search-forward re nil t)
12970 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12971 (not (get-text-property (match-beginning n)
12972 'org-protected)))
12973 (setq txt (match-string n)
12974 beg (match-beginning n) end (match-end n)
12975 cnt (1+ cnt)
12976 linkfile (format "%s_%04d.png" prefix cnt)
12977 movefile (format "%s_%04d.png" absprefix cnt)
12978 link (concat block "[[file:" linkfile "]]" block))
12979 (if msg (message msg cnt))
12980 (goto-char beg)
12981 (unless checkdir ; make sure the directory exists
12982 (setq checkdir t)
12983 (or (file-directory-p todir) (make-directory todir)))
12984 (org-create-formula-image
12985 txt movefile opt forbuffer)
12986 (if overlays
12987 (progn
12988 (setq ov (org-make-overlay beg end))
12989 (if (featurep 'xemacs)
12990 (progn
12991 (org-overlay-put ov 'invisible t)
12992 (org-overlay-put
12993 ov 'end-glyph
12994 (make-glyph (vector 'png :file movefile))))
12995 (org-overlay-put
12996 ov 'display
12997 (list 'image :type 'png :file movefile :ascent 'center)))
12998 (push ov org-latex-fragment-image-overlays)
12999 (goto-char end))
13000 (delete-region beg end)
13001 (insert link))))))))
13003 ;; This function borrows from Ganesh Swami's latex2png.el
13004 (defun org-create-formula-image (string tofile options buffer)
13005 (let* ((tmpdir (if (featurep 'xemacs)
13006 (temp-directory)
13007 temporary-file-directory))
13008 (texfilebase (make-temp-name
13009 (expand-file-name "orgtex" tmpdir)))
13010 (texfile (concat texfilebase ".tex"))
13011 (dvifile (concat texfilebase ".dvi"))
13012 (pngfile (concat texfilebase ".png"))
13013 (fnh (if (featurep 'xemacs)
13014 (font-height (get-face-font 'default))
13015 (face-attribute 'default :height nil)))
13016 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13017 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13018 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13019 "Black"))
13020 (bg (or (plist-get options (if buffer :background :html-background))
13021 "Transparent")))
13022 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13023 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13024 (with-temp-file texfile
13025 (insert org-format-latex-header
13026 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13027 (let ((dir default-directory))
13028 (condition-case nil
13029 (progn
13030 (cd tmpdir)
13031 (call-process "latex" nil nil nil texfile))
13032 (error nil))
13033 (cd dir))
13034 (if (not (file-exists-p dvifile))
13035 (progn (message "Failed to create dvi file from %s" texfile) nil)
13036 (condition-case nil
13037 (call-process "dvipng" nil nil nil
13038 "-E" "-fg" fg "-bg" bg
13039 "-D" dpi
13040 ;;"-x" scale "-y" scale
13041 "-T" "tight"
13042 "-o" pngfile
13043 dvifile)
13044 (error nil))
13045 (if (not (file-exists-p pngfile))
13046 (progn (message "Failed to create png file from %s" texfile) nil)
13047 ;; Use the requested file name and clean up
13048 (copy-file pngfile tofile 'replace)
13049 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13050 (delete-file (concat texfilebase e)))
13051 pngfile))))
13053 (defun org-dvipng-color (attr)
13054 "Return an rgb color specification for dvipng."
13055 (apply 'format "rgb %s %s %s"
13056 (mapcar 'org-normalize-color
13057 (color-values (face-attribute 'default attr nil)))))
13059 (defun org-normalize-color (value)
13060 "Return string to be used as color value for an RGB component."
13061 (format "%g" (/ value 65535.0)))
13063 ;;;; Key bindings
13065 ;; Make `C-c C-x' a prefix key
13066 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13068 ;; TAB key with modifiers
13069 (org-defkey org-mode-map "\C-i" 'org-cycle)
13070 (org-defkey org-mode-map [(tab)] 'org-cycle)
13071 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13072 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13073 (org-defkey org-mode-map "\M-\t" 'org-complete)
13074 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13075 ;; The following line is necessary under Suse GNU/Linux
13076 (unless (featurep 'xemacs)
13077 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13078 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13079 (define-key org-mode-map [backtab] 'org-shifttab)
13081 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13082 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13083 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13085 ;; Cursor keys with modifiers
13086 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13087 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13088 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13089 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13091 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13092 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13093 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13094 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13096 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13097 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13098 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13099 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13101 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13102 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13104 ;;; Extra keys for tty access.
13105 ;; We only set them when really needed because otherwise the
13106 ;; menus don't show the simple keys
13108 (when (or org-use-extra-keys
13109 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13110 (not window-system))
13111 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13112 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13113 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13114 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13115 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13116 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13117 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13118 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13119 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13120 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13121 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13122 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13123 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13124 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13125 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13126 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13127 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13128 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13129 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13130 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13131 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13132 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13134 ;; All the other keys
13136 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13137 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13138 (if (boundp 'narrow-map)
13139 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13140 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13141 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13142 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13143 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13144 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13145 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13146 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13147 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13148 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13149 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13150 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13151 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13152 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13153 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13154 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13155 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13156 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13157 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13158 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13159 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13160 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13161 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13162 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13163 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13164 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13165 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13166 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13167 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13168 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13169 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13170 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13171 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13172 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13173 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13174 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13175 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13176 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13177 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13178 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13179 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13180 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13181 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13182 (org-defkey org-mode-map "\C-c^" 'org-sort)
13183 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13184 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13185 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13186 (org-defkey org-mode-map "\C-m" 'org-return)
13187 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13188 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13189 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13190 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13191 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13192 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13193 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13194 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13195 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13196 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13197 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13198 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13199 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13200 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13201 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13202 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13203 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13205 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13206 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13207 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13208 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13210 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13211 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13212 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13213 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13214 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13215 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13216 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13217 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13218 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13219 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13220 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13221 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13222 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13224 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13225 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13226 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13227 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13229 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13231 (when (featurep 'xemacs)
13232 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13234 (defvar org-table-auto-blank-field) ; defined in org-table.el
13235 (defun org-self-insert-command (N)
13236 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13237 If the cursor is in a table looking at whitespace, the whitespace is
13238 overwritten, and the table is not marked as requiring realignment."
13239 (interactive "p")
13240 (if (and (org-table-p)
13241 (progn
13242 ;; check if we blank the field, and if that triggers align
13243 (and (featurep 'org-table) org-table-auto-blank-field
13244 (member last-command
13245 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13246 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13247 ;; got extra space, this field does not determine column width
13248 (let (org-table-may-need-update) (org-table-blank-field))
13249 ;; no extra space, this field may determine column width
13250 (org-table-blank-field)))
13252 (eq N 1)
13253 (looking-at "[^|\n]* |"))
13254 (let (org-table-may-need-update)
13255 (goto-char (1- (match-end 0)))
13256 (delete-backward-char 1)
13257 (goto-char (match-beginning 0))
13258 (self-insert-command N))
13259 (setq org-table-may-need-update t)
13260 (self-insert-command N)
13261 (org-fix-tags-on-the-fly)))
13263 (defun org-fix-tags-on-the-fly ()
13264 (when (and (equal (char-after (point-at-bol)) ?*)
13265 (org-on-heading-p))
13266 (org-align-tags-here org-tags-column)))
13268 (defun org-delete-backward-char (N)
13269 "Like `delete-backward-char', insert whitespace at field end in tables.
13270 When deleting backwards, in tables this function will insert whitespace in
13271 front of the next \"|\" separator, to keep the table aligned. The table will
13272 still be marked for re-alignment if the field did fill the entire column,
13273 because, in this case the deletion might narrow the column."
13274 (interactive "p")
13275 (if (and (org-table-p)
13276 (eq N 1)
13277 (string-match "|" (buffer-substring (point-at-bol) (point)))
13278 (looking-at ".*?|"))
13279 (let ((pos (point))
13280 (noalign (looking-at "[^|\n\r]* |"))
13281 (c org-table-may-need-update))
13282 (backward-delete-char N)
13283 (skip-chars-forward "^|")
13284 (insert " ")
13285 (goto-char (1- pos))
13286 ;; noalign: if there were two spaces at the end, this field
13287 ;; does not determine the width of the column.
13288 (if noalign (setq org-table-may-need-update c)))
13289 (backward-delete-char N)
13290 (org-fix-tags-on-the-fly)))
13292 (defun org-delete-char (N)
13293 "Like `delete-char', but insert whitespace at field end in tables.
13294 When deleting characters, in tables this function will insert whitespace in
13295 front of the next \"|\" separator, to keep the table aligned. The table will
13296 still be marked for re-alignment if the field did fill the entire column,
13297 because, in this case the deletion might narrow the column."
13298 (interactive "p")
13299 (if (and (org-table-p)
13300 (not (bolp))
13301 (not (= (char-after) ?|))
13302 (eq N 1))
13303 (if (looking-at ".*?|")
13304 (let ((pos (point))
13305 (noalign (looking-at "[^|\n\r]* |"))
13306 (c org-table-may-need-update))
13307 (replace-match (concat
13308 (substring (match-string 0) 1 -1)
13309 " |"))
13310 (goto-char pos)
13311 ;; noalign: if there were two spaces at the end, this field
13312 ;; does not determine the width of the column.
13313 (if noalign (setq org-table-may-need-update c)))
13314 (delete-char N))
13315 (delete-char N)
13316 (org-fix-tags-on-the-fly)))
13318 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13319 (put 'org-self-insert-command 'delete-selection t)
13320 (put 'orgtbl-self-insert-command 'delete-selection t)
13321 (put 'org-delete-char 'delete-selection 'supersede)
13322 (put 'org-delete-backward-char 'delete-selection 'supersede)
13323 (put 'org-yank 'delete-selection 'yank)
13325 ;; Make `flyspell-mode' delay after some commands
13326 (put 'org-self-insert-command 'flyspell-delayed t)
13327 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13328 (put 'org-delete-char 'flyspell-delayed t)
13329 (put 'org-delete-backward-char 'flyspell-delayed t)
13331 ;; Make pabbrev-mode expand after org-mode commands
13332 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13333 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13335 ;; How to do this: Measure non-white length of current string
13336 ;; If equal to column width, we should realign.
13338 (defun org-remap (map &rest commands)
13339 "In MAP, remap the functions given in COMMANDS.
13340 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13341 (let (new old)
13342 (while commands
13343 (setq old (pop commands) new (pop commands))
13344 (if (fboundp 'command-remapping)
13345 (org-defkey map (vector 'remap old) new)
13346 (substitute-key-definition old new map global-map)))))
13348 (when (eq org-enable-table-editor 'optimized)
13349 ;; If the user wants maximum table support, we need to hijack
13350 ;; some standard editing functions
13351 (org-remap org-mode-map
13352 'self-insert-command 'org-self-insert-command
13353 'delete-char 'org-delete-char
13354 'delete-backward-char 'org-delete-backward-char)
13355 (org-defkey org-mode-map "|" 'org-force-self-insert))
13357 (defvar org-ctrl-c-ctrl-c-hook nil
13358 "Hook for functions attaching themselves to `C-c C-c'.
13359 This can be used to add additional functionality to the C-c C-c key which
13360 executes context-dependent commands.
13361 Each function will be called with no arguments. The function must check
13362 if the context is appropriate for it to act. If yes, it should do its
13363 thing and then return a non-nil value. If the context is wrong,
13364 just do nothing.")
13366 (defvar org-metaleft-hook nil
13367 "Hook for functions attaching themselves to `M-left'.
13368 See `org-ctrl-c-ctrl-c-hook' for more information.")
13369 (defvar org-metaright-hook nil
13370 "Hook for functions attaching themselves to `M-right'.
13371 See `org-ctrl-c-ctrl-c-hook' for more information.")
13372 (defvar org-metaup-hook nil
13373 "Hook for functions attaching themselves to `M-up'.
13374 See `org-ctrl-c-ctrl-c-hook' for more information.")
13375 (defvar org-metadown-hook nil
13376 "Hook for functions attaching themselves to `M-down'.
13377 See `org-ctrl-c-ctrl-c-hook' for more information.")
13378 (defvar org-shiftmetaleft-hook nil
13379 "Hook for functions attaching themselves to `M-S-left'.
13380 See `org-ctrl-c-ctrl-c-hook' for more information.")
13381 (defvar org-shiftmetaright-hook nil
13382 "Hook for functions attaching themselves to `M-S-right'.
13383 See `org-ctrl-c-ctrl-c-hook' for more information.")
13384 (defvar org-shiftmetaup-hook nil
13385 "Hook for functions attaching themselves to `M-S-up'.
13386 See `org-ctrl-c-ctrl-c-hook' for more information.")
13387 (defvar org-shiftmetadown-hook nil
13388 "Hook for functions attaching themselves to `M-S-down'.
13389 See `org-ctrl-c-ctrl-c-hook' for more information.")
13390 (defvar org-metareturn-hook nil
13391 "Hook for functions attaching themselves to `M-RET'.
13392 See `org-ctrl-c-ctrl-c-hook' for more information.")
13394 (defun org-modifier-cursor-error ()
13395 "Throw an error, a modified cursor command was applied in wrong context."
13396 (error "This command is active in special context like tables, headlines or items"))
13398 (defun org-shiftselect-error ()
13399 "Throw an error because Shift-Cursor command was applied in wrong context."
13400 (if (and (boundp 'shift-select-mode) shift-select-mode)
13401 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13402 (error "This command works only in special context like headlines or timestamps.")))
13404 (defun org-call-for-shift-select (cmd)
13405 (let ((this-command-keys-shift-translated t))
13406 (call-interactively cmd)))
13408 (defun org-shifttab (&optional arg)
13409 "Global visibility cycling or move to previous table field.
13410 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13411 on context.
13412 See the individual commands for more information."
13413 (interactive "P")
13414 (cond
13415 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13416 ((integerp arg)
13417 (message "Content view to level: %d" arg)
13418 (org-content (prefix-numeric-value arg))
13419 (setq org-cycle-global-status 'overview))
13420 (t (call-interactively 'org-global-cycle))))
13422 (defun org-shiftmetaleft ()
13423 "Promote subtree or delete table column.
13424 Calls `org-promote-subtree', `org-outdent-item',
13425 or `org-table-delete-column', depending on context.
13426 See the individual commands for more information."
13427 (interactive)
13428 (cond
13429 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13430 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13431 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13432 ((org-at-item-p) (call-interactively 'org-outdent-item))
13433 (t (org-modifier-cursor-error))))
13435 (defun org-shiftmetaright ()
13436 "Demote subtree or insert table column.
13437 Calls `org-demote-subtree', `org-indent-item',
13438 or `org-table-insert-column', depending on context.
13439 See the individual commands for more information."
13440 (interactive)
13441 (cond
13442 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13443 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13444 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13445 ((org-at-item-p) (call-interactively 'org-indent-item))
13446 (t (org-modifier-cursor-error))))
13448 (defun org-shiftmetaup (&optional arg)
13449 "Move subtree up or kill table row.
13450 Calls `org-move-subtree-up' or `org-table-kill-row' or
13451 `org-move-item-up' depending on context. See the individual commands
13452 for more information."
13453 (interactive "P")
13454 (cond
13455 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13456 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13457 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13458 ((org-at-item-p) (call-interactively 'org-move-item-up))
13459 (t (org-modifier-cursor-error))))
13461 (defun org-shiftmetadown (&optional arg)
13462 "Move subtree down or insert table row.
13463 Calls `org-move-subtree-down' or `org-table-insert-row' or
13464 `org-move-item-down', depending on context. See the individual
13465 commands for more information."
13466 (interactive "P")
13467 (cond
13468 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13469 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13470 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13471 ((org-at-item-p) (call-interactively 'org-move-item-down))
13472 (t (org-modifier-cursor-error))))
13474 (defun org-metaleft (&optional arg)
13475 "Promote heading or move table column to left.
13476 Calls `org-do-promote' or `org-table-move-column', depending on context.
13477 With no specific context, calls the Emacs default `backward-word'.
13478 See the individual commands for more information."
13479 (interactive "P")
13480 (cond
13481 ((run-hook-with-args-until-success 'org-metaleft-hook))
13482 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13483 ((or (org-on-heading-p)
13484 (and (org-region-active-p)
13485 (save-excursion
13486 (goto-char (region-beginning))
13487 (org-on-heading-p))))
13488 (call-interactively 'org-do-promote))
13489 ((or (org-at-item-p)
13490 (and (org-region-active-p)
13491 (save-excursion
13492 (goto-char (region-beginning))
13493 (org-at-item-p))))
13494 (call-interactively 'org-outdent-item))
13495 (t (call-interactively 'backward-word))))
13497 (defun org-metaright (&optional arg)
13498 "Demote subtree or move table column to right.
13499 Calls `org-do-demote' or `org-table-move-column', depending on context.
13500 With no specific context, calls the Emacs default `forward-word'.
13501 See the individual commands for more information."
13502 (interactive "P")
13503 (cond
13504 ((run-hook-with-args-until-success 'org-metaright-hook))
13505 ((org-at-table-p) (call-interactively 'org-table-move-column))
13506 ((or (org-on-heading-p)
13507 (and (org-region-active-p)
13508 (save-excursion
13509 (goto-char (region-beginning))
13510 (org-on-heading-p))))
13511 (call-interactively 'org-do-demote))
13512 ((or (org-at-item-p)
13513 (and (org-region-active-p)
13514 (save-excursion
13515 (goto-char (region-beginning))
13516 (org-at-item-p))))
13517 (call-interactively 'org-indent-item))
13518 (t (call-interactively 'forward-word))))
13520 (defun org-metaup (&optional arg)
13521 "Move subtree up or move table row up.
13522 Calls `org-move-subtree-up' or `org-table-move-row' or
13523 `org-move-item-up', depending on context. See the individual commands
13524 for more information."
13525 (interactive "P")
13526 (cond
13527 ((run-hook-with-args-until-success 'org-metaup-hook))
13528 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13529 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13530 ((org-at-item-p) (call-interactively 'org-move-item-up))
13531 (t (transpose-lines 1) (beginning-of-line -1))))
13533 (defun org-metadown (&optional arg)
13534 "Move subtree down or move table row down.
13535 Calls `org-move-subtree-down' or `org-table-move-row' or
13536 `org-move-item-down', depending on context. See the individual
13537 commands for more information."
13538 (interactive "P")
13539 (cond
13540 ((run-hook-with-args-until-success 'org-metadown-hook))
13541 ((org-at-table-p) (call-interactively 'org-table-move-row))
13542 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13543 ((org-at-item-p) (call-interactively 'org-move-item-down))
13544 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13546 (defun org-shiftup (&optional arg)
13547 "Increase item in timestamp or increase priority of current headline.
13548 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13549 depending on context. See the individual commands for more information."
13550 (interactive "P")
13551 (cond
13552 ((and org-support-shift-select (org-region-active-p))
13553 (org-call-for-shift-select 'previous-line))
13554 ((org-at-timestamp-p t)
13555 (call-interactively (if org-edit-timestamp-down-means-later
13556 'org-timestamp-down 'org-timestamp-up)))
13557 ((and (not (eq org-support-shift-select 'always))
13558 (org-on-heading-p))
13559 (call-interactively 'org-priority-up))
13560 ((and (not org-support-shift-select) (org-at-item-p))
13561 (call-interactively 'org-previous-item))
13562 ((org-clocktable-try-shift 'up arg))
13563 (org-support-shift-select
13564 (org-call-for-shift-select 'previous-line))
13565 (t (org-shiftselect-error))))
13567 (defun org-shiftdown (&optional arg)
13568 "Decrease item in timestamp or decrease priority of current headline.
13569 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13570 depending on context. See the individual commands for more information."
13571 (interactive "P")
13572 (cond
13573 ((and org-support-shift-select (org-region-active-p))
13574 (org-call-for-shift-select 'next-line))
13575 ((org-at-timestamp-p t)
13576 (call-interactively (if org-edit-timestamp-down-means-later
13577 'org-timestamp-up 'org-timestamp-down)))
13578 ((and (not (eq org-support-shift-select 'always))
13579 (org-on-heading-p))
13580 (call-interactively 'org-priority-down))
13581 ((and (not org-support-shift-select) (org-at-item-p))
13582 (call-interactively 'org-next-item))
13583 ((org-clocktable-try-shift 'down arg))
13584 (org-support-shift-select
13585 (org-call-for-shift-select 'next-line))
13586 (t (org-shiftselect-error))))
13588 (defun org-shiftright (&optional arg)
13589 "Cycle the thing at point or in the current line, depending on context.
13590 Depending on context, this does one of the following:
13592 - switch a timestamp at point one day into the future
13593 - on a headline, switch to the next TODO keyword.
13594 - on an item, switch entire list to the next bullet type
13595 - on a property line, switch to the next allowed value
13596 - on a clocktable definition line, move time block into the future"
13597 (interactive "P")
13598 (cond
13599 ((and org-support-shift-select (org-region-active-p))
13600 (org-call-for-shift-select 'forward-char))
13601 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13602 ((and (not (eq org-support-shift-select 'always))
13603 (org-on-heading-p))
13604 (org-call-with-arg 'org-todo 'right))
13605 ((or (and org-support-shift-select
13606 (not (eq org-support-shift-select 'always))
13607 (org-at-item-bullet-p))
13608 (and (not org-support-shift-select) (org-at-item-p)))
13609 (org-call-with-arg 'org-cycle-list-bullet nil))
13610 ((and (not (eq org-support-shift-select 'always))
13611 (org-at-property-p))
13612 (call-interactively 'org-property-next-allowed-value))
13613 ((org-clocktable-try-shift 'right arg))
13614 (org-support-shift-select
13615 (org-call-for-shift-select 'forward-char))
13616 (t (org-shiftselect-error))))
13618 (defun org-shiftleft (&optional arg)
13619 "Cycle the thing at point or in the current line, depending on context.
13620 Depending on context, this does one of the following:
13622 - switch a timestamp at point one day into the past
13623 - on a headline, switch to the previous TODO keyword.
13624 - on an item, switch entire list to the previous bullet type
13625 - on a property line, switch to the previous allowed value
13626 - on a clocktable definition line, move time block into the past"
13627 (interactive "P")
13628 (cond
13629 ((and org-support-shift-select (org-region-active-p))
13630 (org-call-for-shift-select 'backward-char))
13631 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13632 ((and (not (eq org-support-shift-select 'always))
13633 (org-on-heading-p))
13634 (org-call-with-arg 'org-todo 'left))
13635 ((or (and org-support-shift-select
13636 (not (eq org-support-shift-select 'always))
13637 (org-at-item-bullet-p))
13638 (and (not org-support-shift-select) (org-at-item-p)))
13639 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13640 ((and (not (eq org-support-shift-select 'always))
13641 (org-at-property-p))
13642 (call-interactively 'org-property-previous-allowed-value))
13643 ((org-clocktable-try-shift 'left arg))
13644 (org-support-shift-select
13645 (org-call-for-shift-select 'backward-char))
13646 (t (org-shiftselect-error))))
13648 (defun org-shiftcontrolright ()
13649 "Switch to next TODO set."
13650 (interactive)
13651 (cond
13652 ((and org-support-shift-select (org-region-active-p))
13653 (org-call-for-shift-select 'forward-word))
13654 ((and (not (eq org-support-shift-select 'always))
13655 (org-on-heading-p))
13656 (org-call-with-arg 'org-todo 'nextset))
13657 (org-support-shift-select
13658 (org-call-for-shift-select 'forward-word))
13659 (t (org-shiftselect-error))))
13661 (defun org-shiftcontrolleft ()
13662 "Switch to previous TODO set."
13663 (interactive)
13664 (cond
13665 ((and org-support-shift-select (org-region-active-p))
13666 (org-call-for-shift-select 'backward-word))
13667 ((and (not (eq org-support-shift-select 'always))
13668 (org-on-heading-p))
13669 (org-call-with-arg 'org-todo 'previousset))
13670 (org-support-shift-select
13671 (org-call-for-shift-select 'backward-word))
13672 (t (org-shiftselect-error))))
13674 (defun org-ctrl-c-ret ()
13675 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13676 (interactive)
13677 (cond
13678 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13679 (t (call-interactively 'org-insert-heading))))
13681 (defun org-copy-special ()
13682 "Copy region in table or copy current subtree.
13683 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13684 See the individual commands for more information."
13685 (interactive)
13686 (call-interactively
13687 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13689 (defun org-cut-special ()
13690 "Cut region in table or cut current subtree.
13691 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13692 See the individual commands for more information."
13693 (interactive)
13694 (call-interactively
13695 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13697 (defun org-paste-special (arg)
13698 "Paste rectangular region into table, or past subtree relative to level.
13699 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13700 See the individual commands for more information."
13701 (interactive "P")
13702 (if (org-at-table-p)
13703 (org-table-paste-rectangle)
13704 (org-paste-subtree arg)))
13706 (defun org-edit-special ()
13707 "Call a special editor for the stuff at point.
13708 When at a table, call the formula editor with `org-table-edit-formulas'.
13709 When at the first line of an src example, call `org-edit-src-code'.
13710 When in an #+include line, visit the include file. Otherwise call
13711 `ffap' to visit the file at point."
13712 (interactive)
13713 (cond
13714 ((org-at-table-p)
13715 (call-interactively 'org-table-edit-formulas))
13716 ((save-excursion
13717 (beginning-of-line 1)
13718 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13719 (find-file (org-trim (match-string 1))))
13720 ((org-edit-src-code))
13721 ((org-edit-fixed-width-region))
13722 (t (call-interactively 'ffap))))
13725 (defun org-ctrl-c-ctrl-c (&optional arg)
13726 "Set tags in headline, or update according to changed information at point.
13728 This command does many different things, depending on context:
13730 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13731 this is what we do.
13733 - If the cursor is in a headline, prompt for tags and insert them
13734 into the current line, aligned to `org-tags-column'. When called
13735 with prefix arg, realign all tags in the current buffer.
13737 - If the cursor is in one of the special #+KEYWORD lines, this
13738 triggers scanning the buffer for these lines and updating the
13739 information.
13741 - If the cursor is inside a table, realign the table. This command
13742 works even if the automatic table editor has been turned off.
13744 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13745 the entire table.
13747 - If the cursor is at a footnote reference or definition, jump to
13748 the corresponding definition or references, respectively.
13750 - If the cursor is a the beginning of a dynamic block, update it.
13752 - If the cursor is inside a table created by the table.el package,
13753 activate that table.
13755 - If the current buffer is a remember buffer, close note and file
13756 it. A prefix argument of 1 files to the default location
13757 without further interaction. A prefix argument of 2 files to
13758 the currently clocking task.
13760 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13761 links in this buffer.
13763 - If the cursor is on a numbered item in a plain list, renumber the
13764 ordered list.
13766 - If the cursor is on a checkbox, toggle it."
13767 (interactive "P")
13768 (let ((org-enable-table-editor t))
13769 (cond
13770 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13771 org-occur-highlights
13772 org-latex-fragment-image-overlays)
13773 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13774 (org-remove-occur-highlights)
13775 (org-remove-latex-fragment-image-overlays)
13776 (message "Temporary highlights/overlays removed from current buffer"))
13777 ((and (local-variable-p 'org-finish-function (current-buffer))
13778 (fboundp org-finish-function))
13779 (funcall org-finish-function))
13780 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13781 ((org-at-property-p)
13782 (call-interactively 'org-property-action))
13783 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13784 ((org-on-heading-p) (call-interactively 'org-set-tags))
13785 ((org-at-table.el-p)
13786 (require 'table)
13787 (beginning-of-line 1)
13788 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13789 (call-interactively 'table-recognize-table))
13790 ((org-at-table-p)
13791 (org-table-maybe-eval-formula)
13792 (if arg
13793 (call-interactively 'org-table-recalculate)
13794 (org-table-maybe-recalculate-line))
13795 (call-interactively 'org-table-align))
13796 ((or (org-footnote-at-reference-p)
13797 (org-footnote-at-definition-p))
13798 (call-interactively 'org-footnote-action))
13799 ((org-at-item-checkbox-p)
13800 (call-interactively 'org-toggle-checkbox))
13801 ((org-at-item-p)
13802 (if arg
13803 (call-interactively 'org-toggle-checkbox)
13804 (call-interactively 'org-maybe-renumber-ordered-list)))
13805 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13806 ;; Dynamic block
13807 (beginning-of-line 1)
13808 (save-excursion (org-update-dblock)))
13809 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13810 (cond
13811 ((equal (match-string 1) "TBLFM")
13812 ;; Recalculate the table before this line
13813 (save-excursion
13814 (beginning-of-line 1)
13815 (skip-chars-backward " \r\n\t")
13816 (if (org-at-table-p)
13817 (org-call-with-arg 'org-table-recalculate t))))
13819 ; (org-set-regexps-and-options)
13820 ; (org-restart-font-lock)
13821 (let ((org-inhibit-startup t)) (org-mode-restart))
13822 (message "Local setup has been refreshed"))))
13823 (t (error "C-c C-c can do nothing useful at this location.")))))
13825 (defun org-mode-restart ()
13826 "Restart Org-mode, to scan again for special lines.
13827 Also updates the keyword regular expressions."
13828 (interactive)
13829 (org-mode)
13830 (message "Org-mode restarted"))
13832 (defun org-kill-note-or-show-branches ()
13833 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13834 (interactive)
13835 (if (not org-finish-function)
13836 (call-interactively 'show-branches)
13837 (let ((org-note-abort t))
13838 (funcall org-finish-function))))
13840 (defun org-return (&optional indent)
13841 "Goto next table row or insert a newline.
13842 Calls `org-table-next-row' or `newline', depending on context.
13843 See the individual commands for more information."
13844 (interactive)
13845 (cond
13846 ((bobp) (if indent (newline-and-indent) (newline)))
13847 ((org-at-table-p)
13848 (org-table-justify-field-maybe)
13849 (call-interactively 'org-table-next-row))
13850 ((and org-return-follows-link
13851 (eq (get-text-property (point) 'face) 'org-link))
13852 (call-interactively 'org-open-at-point))
13853 ((and (org-at-heading-p)
13854 (looking-at
13855 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13856 (org-show-entry)
13857 (end-of-line 1)
13858 (newline))
13859 (t (if indent (newline-and-indent) (newline)))))
13861 (defun org-return-indent ()
13862 "Goto next table row or insert a newline and indent.
13863 Calls `org-table-next-row' or `newline-and-indent', depending on
13864 context. See the individual commands for more information."
13865 (interactive)
13866 (org-return t))
13868 (defun org-ctrl-c-star ()
13869 "Compute table, or change heading status of lines.
13870 Calls `org-table-recalculate' or `org-toggle-heading',
13871 depending on context."
13872 (interactive)
13873 (cond
13874 ((org-at-table-p)
13875 (call-interactively 'org-table-recalculate))
13877 ;; Convert all lines in region to list items
13878 (call-interactively 'org-toggle-heading))))
13880 (defun org-ctrl-c-minus ()
13881 "Insert separator line in table or modify bullet status of line.
13882 Also turns a plain line or a region of lines into list items.
13883 Calls `org-table-insert-hline', `org-toggle-item', or
13884 `org-cycle-list-bullet', depending on context."
13885 (interactive)
13886 (cond
13887 ((org-at-table-p)
13888 (call-interactively 'org-table-insert-hline))
13889 ((org-region-active-p)
13890 (call-interactively 'org-toggle-item))
13891 ((org-in-item-p)
13892 (call-interactively 'org-cycle-list-bullet))
13894 (call-interactively 'org-toggle-item))))
13896 (defun org-toggle-item ()
13897 "Convert headings or normal lines to items, items to normal lines.
13898 If there is no active region, only the current line is considered.
13900 If the first line in the region is a headline, convert all headlines to items.
13902 If the first line in the region is an item, convert all items to normal lines.
13904 If the first line is normal text, add an item bullet to each line."
13905 (interactive)
13906 (let (l2 l beg end)
13907 (if (org-region-active-p)
13908 (setq beg (region-beginning) end (region-end))
13909 (setq beg (point-at-bol)
13910 end (min (1+ (point-at-eol)) (point-max))))
13911 (save-excursion
13912 (goto-char end)
13913 (setq l2 (org-current-line))
13914 (goto-char beg)
13915 (beginning-of-line 1)
13916 (setq l (1- (org-current-line)))
13917 (if (org-at-item-p)
13918 ;; We already have items, de-itemize
13919 (while (< (setq l (1+ l)) l2)
13920 (when (org-at-item-p)
13921 (goto-char (match-beginning 2))
13922 (delete-region (match-beginning 2) (match-end 2))
13923 (and (looking-at "[ \t]+") (replace-match "")))
13924 (beginning-of-line 2))
13925 (if (org-on-heading-p)
13926 ;; Headings, convert to items
13927 (while (< (setq l (1+ l)) l2)
13928 (if (looking-at org-outline-regexp)
13929 (replace-match "- " t t))
13930 (beginning-of-line 2))
13931 ;; normal lines, turn them into items
13932 (while (< (setq l (1+ l)) l2)
13933 (unless (org-at-item-p)
13934 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13935 (replace-match "\\1- \\2")))
13936 (beginning-of-line 2)))))))
13938 (defun org-toggle-heading (&optional nstars)
13939 "Convert headings to normal text, or items or text to headings.
13940 If there is no active region, only the current line is considered.
13942 If the first line is a heading, remove the stars from all headlines
13943 in the region.
13945 If the first line is a plain list item, turn all plain list items into
13946 headings.
13948 If the first line is a normal line, turn each and every line in the region
13949 into a heading.
13951 When converting a line into a heading, the number of stars is chosen
13952 such that the lines become children of the current entry. However, when
13953 a prefix argument is given, its value determines the number of stars to add."
13954 (interactive "P")
13955 (let (l2 l itemp beg end)
13956 (if (org-region-active-p)
13957 (setq beg (region-beginning) end (region-end))
13958 (setq beg (point-at-bol)
13959 end (min (1+ (point-at-eol)) (point-max))))
13960 (save-excursion
13961 (goto-char end)
13962 (setq l2 (org-current-line))
13963 (goto-char beg)
13964 (beginning-of-line 1)
13965 (setq l (1- (org-current-line)))
13966 (if (org-on-heading-p)
13967 ;; We already have headlines, de-star them
13968 (while (< (setq l (1+ l)) l2)
13969 (when (org-on-heading-p t)
13970 (and (looking-at outline-regexp) (replace-match "")))
13971 (beginning-of-line 2))
13972 (setq itemp (org-at-item-p))
13973 (let* ((stars
13974 (if nstars
13975 (make-string (prefix-numeric-value current-prefix-arg)
13977 (save-excursion
13978 (re-search-backward org-complex-heading-regexp nil t)
13979 (or (match-string 1) "*"))))
13980 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13981 (rpl (concat stars add-stars " ")))
13982 (while (< (setq l (1+ l)) l2)
13983 (if itemp
13984 (and (org-at-item-p) (replace-match rpl t t))
13985 (unless (org-on-heading-p)
13986 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13987 (replace-match (concat rpl (match-string 2))))))
13988 (beginning-of-line 2)))))))
13990 (defun org-meta-return (&optional arg)
13991 "Insert a new heading or wrap a region in a table.
13992 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13993 See the individual commands for more information."
13994 (interactive "P")
13995 (cond
13996 ((run-hook-with-args-until-success 'org-metareturn-hook))
13997 ((org-at-table-p)
13998 (call-interactively 'org-table-wrap-region))
13999 (t (call-interactively 'org-insert-heading))))
14001 ;;; Menu entries
14003 ;; Define the Org-mode menus
14004 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14005 '("Tbl"
14006 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14007 ["Next Field" org-cycle (org-at-table-p)]
14008 ["Previous Field" org-shifttab (org-at-table-p)]
14009 ["Next Row" org-return (org-at-table-p)]
14010 "--"
14011 ["Blank Field" org-table-blank-field (org-at-table-p)]
14012 ["Edit Field" org-table-edit-field (org-at-table-p)]
14013 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14014 "--"
14015 ("Column"
14016 ["Move Column Left" org-metaleft (org-at-table-p)]
14017 ["Move Column Right" org-metaright (org-at-table-p)]
14018 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14019 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14020 ("Row"
14021 ["Move Row Up" org-metaup (org-at-table-p)]
14022 ["Move Row Down" org-metadown (org-at-table-p)]
14023 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14024 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14025 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14026 "--"
14027 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14028 ("Rectangle"
14029 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14030 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14031 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14032 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14033 "--"
14034 ("Calculate"
14035 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14036 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14037 ["Edit Formulas" org-edit-special (org-at-table-p)]
14038 "--"
14039 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14040 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14041 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14042 "--"
14043 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14044 "--"
14045 ["Sum Column/Rectangle" org-table-sum
14046 (or (org-at-table-p) (org-region-active-p))]
14047 ["Which Column?" org-table-current-column (org-at-table-p)])
14048 ["Debug Formulas"
14049 org-table-toggle-formula-debugger
14050 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14051 ["Show Col/Row Numbers"
14052 org-table-toggle-coordinate-overlays
14053 :style toggle
14054 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14055 "--"
14056 ["Create" org-table-create (and (not (org-at-table-p))
14057 org-enable-table-editor)]
14058 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14059 ["Import from File" org-table-import (not (org-at-table-p))]
14060 ["Export to File" org-table-export (org-at-table-p)]
14061 "--"
14062 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14064 (easy-menu-define org-org-menu org-mode-map "Org menu"
14065 '("Org"
14066 ("Show/Hide"
14067 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14068 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14069 ["Sparse Tree..." org-sparse-tree t]
14070 ["Reveal Context" org-reveal t]
14071 ["Show All" show-all t]
14072 "--"
14073 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14074 "--"
14075 ["New Heading" org-insert-heading t]
14076 ("Navigate Headings"
14077 ["Up" outline-up-heading t]
14078 ["Next" outline-next-visible-heading t]
14079 ["Previous" outline-previous-visible-heading t]
14080 ["Next Same Level" outline-forward-same-level t]
14081 ["Previous Same Level" outline-backward-same-level t]
14082 "--"
14083 ["Jump" org-goto t])
14084 ("Edit Structure"
14085 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14086 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14087 "--"
14088 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14089 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14090 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14091 "--"
14092 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14093 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14094 ["Demote Heading" org-metaright (not (org-at-table-p))]
14095 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14096 "--"
14097 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14098 "--"
14099 ["Convert to odd levels" org-convert-to-odd-levels t]
14100 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14101 ("Editing"
14102 ["Emphasis..." org-emphasize t]
14103 ["Edit Source Example" org-edit-special t]
14104 "--"
14105 ["Footnote new/jump" org-footnote-action t]
14106 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14107 ("Archive"
14108 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14109 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14110 ; :active t :keys "C-u C-c C-x C-a"]
14111 ["Sparse trees open ARCHIVE trees"
14112 (setq org-sparse-tree-open-archived-trees
14113 (not org-sparse-tree-open-archived-trees))
14114 :style toggle :selected org-sparse-tree-open-archived-trees]
14115 ["Cycling opens ARCHIVE trees"
14116 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14117 :style toggle :selected org-cycle-open-archived-trees]
14118 "--"
14119 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14120 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14121 ; ["Check and Move Children" (org-archive-subtree '(4))
14122 ; :active t :keys "C-u C-c C-x C-s"]
14124 "--"
14125 ("TODO Lists"
14126 ["TODO/DONE/-" org-todo t]
14127 ("Select keyword"
14128 ["Next keyword" org-shiftright (org-on-heading-p)]
14129 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14130 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14131 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14132 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14133 ["Show TODO Tree" org-show-todo-tree t]
14134 ["Global TODO list" org-todo-list t]
14135 "--"
14136 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14137 :selected org-enforce-todo-dependencies :style toggle :active t]
14138 "Settings for tree at point"
14139 ["Do Children sequentially" org-toggle-ordered-property :style radio
14140 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14141 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14142 ["Do Children parallel" org-toggle-ordered-property :style radio
14143 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14144 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14145 "--"
14146 ["Set Priority" org-priority t]
14147 ["Priority Up" org-shiftup t]
14148 ["Priority Down" org-shiftdown t])
14149 ("TAGS and Properties"
14150 ["Set Tags" org-set-tags-command t]
14151 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14152 "--"
14153 ["Set property" org-set-property t]
14154 ["Column view of properties" org-columns t]
14155 ["Insert Column View DBlock" org-insert-columns-dblock t])
14156 ("Dates and Scheduling"
14157 ["Timestamp" org-time-stamp t]
14158 ["Timestamp (inactive)" org-time-stamp-inactive t]
14159 ("Change Date"
14160 ["1 Day Later" org-shiftright t]
14161 ["1 Day Earlier" org-shiftleft t]
14162 ["1 ... Later" org-shiftup t]
14163 ["1 ... Earlier" org-shiftdown t])
14164 ["Compute Time Range" org-evaluate-time-range t]
14165 ["Schedule Item" org-schedule t]
14166 ["Deadline" org-deadline t]
14167 "--"
14168 ["Custom time format" org-toggle-time-stamp-overlays
14169 :style radio :selected org-display-custom-times]
14170 "--"
14171 ["Goto Calendar" org-goto-calendar t]
14172 ["Date from Calendar" org-date-from-calendar t]
14173 "--"
14174 ["Start/Restart Timer" org-timer-start t]
14175 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14176 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14177 ["Insert Timer String" org-timer t]
14178 ["Insert Timer Item" org-timer-item t])
14179 ("Logging work"
14180 ["Clock in" org-clock-in t]
14181 ["Clock out" org-clock-out t]
14182 ["Clock cancel" org-clock-cancel t]
14183 ["Goto running clock" org-clock-goto t]
14184 ["Display times" org-clock-display t]
14185 ["Create clock table" org-clock-report t]
14186 "--"
14187 ["Record DONE time"
14188 (progn (setq org-log-done (not org-log-done))
14189 (message "Switching to %s will %s record a timestamp"
14190 (car org-done-keywords)
14191 (if org-log-done "automatically" "not")))
14192 :style toggle :selected org-log-done])
14193 "--"
14194 ["Agenda Command..." org-agenda t]
14195 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14196 ("File List for Agenda")
14197 ("Special views current file"
14198 ["TODO Tree" org-show-todo-tree t]
14199 ["Check Deadlines" org-check-deadlines t]
14200 ["Timeline" org-timeline t]
14201 ["Tags Tree" org-tags-sparse-tree t])
14202 "--"
14203 ("Hyperlinks"
14204 ["Store Link (Global)" org-store-link t]
14205 ["Insert Link" org-insert-link t]
14206 ["Follow Link" org-open-at-point t]
14207 "--"
14208 ["Next link" org-next-link t]
14209 ["Previous link" org-previous-link t]
14210 "--"
14211 ["Descriptive Links"
14212 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14213 :style radio
14214 :selected (member '(org-link) buffer-invisibility-spec)]
14215 ["Literal Links"
14216 (progn
14217 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14218 :style radio
14219 :selected (not (member '(org-link) buffer-invisibility-spec))])
14220 "--"
14221 ["Export/Publish..." org-export t]
14222 ("LaTeX"
14223 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14224 :selected org-cdlatex-mode]
14225 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14226 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14227 ["Modify math symbol" org-cdlatex-math-modify
14228 (org-inside-LaTeX-fragment-p)]
14229 ["Export LaTeX fragments as images"
14230 (if (featurep 'org-exp)
14231 (setq org-export-with-LaTeX-fragments
14232 (not org-export-with-LaTeX-fragments))
14233 (require 'org-exp))
14234 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14235 org-export-with-LaTeX-fragments)])
14236 "--"
14237 ("Documentation"
14238 ["Show Version" org-version t]
14239 ["Info Documentation" org-info t])
14240 ("Customize"
14241 ["Browse Org Group" org-customize t]
14242 "--"
14243 ["Expand This Menu" org-create-customize-menu
14244 (fboundp 'customize-menu-create)])
14245 "--"
14246 ["Refresh setup" org-mode-restart t]
14249 (defun org-info (&optional node)
14250 "Read documentation for Org-mode in the info system.
14251 With optional NODE, go directly to that node."
14252 (interactive)
14253 (info (format "(org)%s" (or node ""))))
14255 (defun org-install-agenda-files-menu ()
14256 (let ((bl (buffer-list)))
14257 (save-excursion
14258 (while bl
14259 (set-buffer (pop bl))
14260 (if (org-mode-p) (setq bl nil)))
14261 (when (org-mode-p)
14262 (easy-menu-change
14263 '("Org") "File List for Agenda"
14264 (append
14265 (list
14266 ["Edit File List" (org-edit-agenda-file-list) t]
14267 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14268 ["Remove Current File from List" org-remove-file t]
14269 ["Cycle through agenda files" org-cycle-agenda-files t]
14270 ["Occur in all agenda files" org-occur-in-agenda-files t]
14271 "--")
14272 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14274 ;;;; Documentation
14276 ;;;###autoload
14277 (defun org-require-autoloaded-modules ()
14278 (interactive)
14279 (mapc 'require
14280 '(org-agenda org-archive org-attach org-clock org-colview
14281 org-exp org-id org-export-latex org-publish
14282 org-remember org-table org-timer)))
14284 ;;;###autoload
14285 (defun org-reload (&optional uncompiled)
14286 "Reload all org lisp files.
14287 With prefix arg UNCOMPILED, load the uncompiled versions."
14288 (interactive "P")
14289 (require 'find-func)
14290 (let* ((dir (file-name-directory (find-library-name "org")))
14291 (files (directory-files dir t "\\.el\\'"))
14292 (remove-re (concat (if (featurep 'xemacs)
14293 "org-colview" "org-colview-xemacs")
14294 "\\'")))
14295 (setq files (mapcar 'file-name-sans-extension files))
14296 (setq files (mapcar
14297 (lambda (x) (if (string-match remove-re x) nil x))
14298 files))
14299 (setq files (delq nil files))
14300 (mapc
14301 (lambda (f)
14302 (if (and (not uncompiled)
14303 (file-exists-p (concat f ".elc")))
14304 (load (concat f ".elc") nil nil t)
14305 (load (concat f ".el") nil nil t)))
14306 files)))
14308 ;;;###autoload
14309 (defun org-customize ()
14310 "Call the customize function with org as argument."
14311 (interactive)
14312 (org-load-modules-maybe)
14313 (org-require-autoloaded-modules)
14314 (customize-browse 'org))
14316 (defun org-create-customize-menu ()
14317 "Create a full customization menu for Org-mode, insert it into the menu."
14318 (interactive)
14319 (org-load-modules-maybe)
14320 (org-require-autoloaded-modules)
14321 (if (fboundp 'customize-menu-create)
14322 (progn
14323 (easy-menu-change
14324 '("Org") "Customize"
14325 `(["Browse Org group" org-customize t]
14326 "--"
14327 ,(customize-menu-create 'org)
14328 ["Set" Custom-set t]
14329 ["Save" Custom-save t]
14330 ["Reset to Current" Custom-reset-current t]
14331 ["Reset to Saved" Custom-reset-saved t]
14332 ["Reset to Standard Settings" Custom-reset-standard t]))
14333 (message "\"Org\"-menu now contains full customization menu"))
14334 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14336 ;;;; Miscellaneous stuff
14338 ;;; Generally useful functions
14340 (defun org-find-text-property-in-string (prop s)
14341 "Return the first non-nil value of property PROP in string S."
14342 (or (get-text-property 0 prop s)
14343 (get-text-property (or (next-single-property-change 0 prop s) 0)
14344 prop s)))
14346 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14347 "Display the given MESSAGE as a warning."
14348 (if (fboundp 'display-warning)
14349 (display-warning 'org message
14350 (if (featurep 'xemacs)
14351 'warning
14352 :warning))
14353 (let ((buf (get-buffer-create "*Org warnings*")))
14354 (with-current-buffer buf
14355 (goto-char (point-max))
14356 (insert "Warning (Org): " message)
14357 (unless (bolp)
14358 (newline)))
14359 (display-buffer buf)
14360 (sit-for 0))))
14362 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14363 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14364 (if (and marker (marker-buffer marker)
14365 (buffer-live-p (marker-buffer marker)))
14366 (progn
14367 (switch-to-buffer (marker-buffer marker))
14368 (if (or (> marker (point-max)) (< marker (point-min)))
14369 (widen))
14370 (goto-char marker)
14371 (org-show-context 'org-goto))
14372 (if bookmark
14373 (bookmark-jump bookmark)
14374 (error "Cannot find location"))))
14376 (defun org-quote-csv-field (s)
14377 "Quote field for inclusion in CSV material."
14378 (if (string-match "[\",]" s)
14379 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14382 (defun org-plist-delete (plist property)
14383 "Delete PROPERTY from PLIST.
14384 This is in contrast to merely setting it to 0."
14385 (let (p)
14386 (while plist
14387 (if (not (eq property (car plist)))
14388 (setq p (plist-put p (car plist) (nth 1 plist))))
14389 (setq plist (cddr plist)))
14392 (defun org-force-self-insert (N)
14393 "Needed to enforce self-insert under remapping."
14394 (interactive "p")
14395 (self-insert-command N))
14397 (defun org-string-width (s)
14398 "Compute width of string, ignoring invisible characters.
14399 This ignores character with invisibility property `org-link', and also
14400 characters with property `org-cwidth', because these will become invisible
14401 upon the next fontification round."
14402 (let (b l)
14403 (when (or (eq t buffer-invisibility-spec)
14404 (assq 'org-link buffer-invisibility-spec))
14405 (while (setq b (text-property-any 0 (length s)
14406 'invisible 'org-link s))
14407 (setq s (concat (substring s 0 b)
14408 (substring s (or (next-single-property-change
14409 b 'invisible s) (length s)))))))
14410 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14411 (setq s (concat (substring s 0 b)
14412 (substring s (or (next-single-property-change
14413 b 'org-cwidth s) (length s))))))
14414 (setq l (string-width s) b -1)
14415 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14416 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14419 (defun org-get-indentation (&optional line)
14420 "Get the indentation of the current line, interpreting tabs.
14421 When LINE is given, assume it represents a line and compute its indentation."
14422 (if line
14423 (if (string-match "^ *" (org-remove-tabs line))
14424 (match-end 0))
14425 (save-excursion
14426 (beginning-of-line 1)
14427 (skip-chars-forward " \t")
14428 (current-column))))
14430 (defun org-remove-tabs (s &optional width)
14431 "Replace tabulators in S with spaces.
14432 Assumes that s is a single line, starting in column 0."
14433 (setq width (or width tab-width))
14434 (while (string-match "\t" s)
14435 (setq s (replace-match
14436 (make-string
14437 (- (* width (/ (+ (match-beginning 0) width) width))
14438 (match-beginning 0)) ?\ )
14439 t t s)))
14442 (defun org-fix-indentation (line ind)
14443 "Fix indentation in LINE.
14444 IND is a cons cell with target and minimum indentation.
14445 If the current indentation in LINE is smaller than the minimum,
14446 leave it alone. If it is larger than ind, set it to the target."
14447 (let* ((l (org-remove-tabs line))
14448 (i (org-get-indentation l))
14449 (i1 (car ind)) (i2 (cdr ind)))
14450 (if (>= i i2) (setq l (substring line i2)))
14451 (if (> i1 0)
14452 (concat (make-string i1 ?\ ) l)
14453 l)))
14455 (defun org-base-buffer (buffer)
14456 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14457 (if (not buffer)
14458 buffer
14459 (or (buffer-base-buffer buffer)
14460 buffer)))
14462 (defun org-trim (s)
14463 "Remove whitespace at beginning and end of string."
14464 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14465 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14468 (defun org-wrap (string &optional width lines)
14469 "Wrap string to either a number of lines, or a width in characters.
14470 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14471 that costs. If there is a word longer than WIDTH, the text is actually
14472 wrapped to the length of that word.
14473 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14474 many lines, whatever width that takes.
14475 The return value is a list of lines, without newlines at the end."
14476 (let* ((words (org-split-string string "[ \t\n]+"))
14477 (maxword (apply 'max (mapcar 'org-string-width words)))
14478 w ll)
14479 (cond (width
14480 (org-do-wrap words (max maxword width)))
14481 (lines
14482 (setq w maxword)
14483 (setq ll (org-do-wrap words maxword))
14484 (if (<= (length ll) lines)
14486 (setq ll words)
14487 (while (> (length ll) lines)
14488 (setq w (1+ w))
14489 (setq ll (org-do-wrap words w)))
14490 ll))
14491 (t (error "Cannot wrap this")))))
14493 (defun org-do-wrap (words width)
14494 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14495 (let (lines line)
14496 (while words
14497 (setq line (pop words))
14498 (while (and words (< (+ (length line) (length (car words))) width))
14499 (setq line (concat line " " (pop words))))
14500 (setq lines (push line lines)))
14501 (nreverse lines)))
14503 (defun org-split-string (string &optional separators)
14504 "Splits STRING into substrings at SEPARATORS.
14505 No empty strings are returned if there are matches at the beginning
14506 and end of string."
14507 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14508 (start 0)
14509 notfirst
14510 (list nil))
14511 (while (and (string-match rexp string
14512 (if (and notfirst
14513 (= start (match-beginning 0))
14514 (< start (length string)))
14515 (1+ start) start))
14516 (< (match-beginning 0) (length string)))
14517 (setq notfirst t)
14518 (or (eq (match-beginning 0) 0)
14519 (and (eq (match-beginning 0) (match-end 0))
14520 (eq (match-beginning 0) start))
14521 (setq list
14522 (cons (substring string start (match-beginning 0))
14523 list)))
14524 (setq start (match-end 0)))
14525 (or (eq start (length string))
14526 (setq list
14527 (cons (substring string start)
14528 list)))
14529 (nreverse list)))
14531 (defun org-context ()
14532 "Return a list of contexts of the current cursor position.
14533 If several contexts apply, all are returned.
14534 Each context entry is a list with a symbol naming the context, and
14535 two positions indicating start and end of the context. Possible
14536 contexts are:
14538 :headline anywhere in a headline
14539 :headline-stars on the leading stars in a headline
14540 :todo-keyword on a TODO keyword (including DONE) in a headline
14541 :tags on the TAGS in a headline
14542 :priority on the priority cookie in a headline
14543 :item on the first line of a plain list item
14544 :item-bullet on the bullet/number of a plain list item
14545 :checkbox on the checkbox in a plain list item
14546 :table in an org-mode table
14547 :table-special on a special filed in a table
14548 :table-table in a table.el table
14549 :link on a hyperlink
14550 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14551 :target on a <<target>>
14552 :radio-target on a <<<radio-target>>>
14553 :latex-fragment on a LaTeX fragment
14554 :latex-preview on a LaTeX fragment with overlayed preview image
14556 This function expects the position to be visible because it uses font-lock
14557 faces as a help to recognize the following contexts: :table-special, :link,
14558 and :keyword."
14559 (let* ((f (get-text-property (point) 'face))
14560 (faces (if (listp f) f (list f)))
14561 (p (point)) clist o)
14562 ;; First the large context
14563 (cond
14564 ((org-on-heading-p t)
14565 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14566 (when (progn
14567 (beginning-of-line 1)
14568 (looking-at org-todo-line-tags-regexp))
14569 (push (org-point-in-group p 1 :headline-stars) clist)
14570 (push (org-point-in-group p 2 :todo-keyword) clist)
14571 (push (org-point-in-group p 4 :tags) clist))
14572 (goto-char p)
14573 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14574 (if (looking-at "\\[#[A-Z0-9]\\]")
14575 (push (org-point-in-group p 0 :priority) clist)))
14577 ((org-at-item-p)
14578 (push (org-point-in-group p 2 :item-bullet) clist)
14579 (push (list :item (point-at-bol)
14580 (save-excursion (org-end-of-item) (point)))
14581 clist)
14582 (and (org-at-item-checkbox-p)
14583 (push (org-point-in-group p 0 :checkbox) clist)))
14585 ((org-at-table-p)
14586 (push (list :table (org-table-begin) (org-table-end)) clist)
14587 (if (memq 'org-formula faces)
14588 (push (list :table-special
14589 (previous-single-property-change p 'face)
14590 (next-single-property-change p 'face)) clist)))
14591 ((org-at-table-p 'any)
14592 (push (list :table-table) clist)))
14593 (goto-char p)
14595 ;; Now the small context
14596 (cond
14597 ((org-at-timestamp-p)
14598 (push (org-point-in-group p 0 :timestamp) clist))
14599 ((memq 'org-link faces)
14600 (push (list :link
14601 (previous-single-property-change p 'face)
14602 (next-single-property-change p 'face)) clist))
14603 ((memq 'org-special-keyword faces)
14604 (push (list :keyword
14605 (previous-single-property-change p 'face)
14606 (next-single-property-change p 'face)) clist))
14607 ((org-on-target-p)
14608 (push (org-point-in-group p 0 :target) clist)
14609 (goto-char (1- (match-beginning 0)))
14610 (if (looking-at org-radio-target-regexp)
14611 (push (org-point-in-group p 0 :radio-target) clist))
14612 (goto-char p))
14613 ((setq o (car (delq nil
14614 (mapcar
14615 (lambda (x)
14616 (if (memq x org-latex-fragment-image-overlays) x))
14617 (org-overlays-at (point))))))
14618 (push (list :latex-fragment
14619 (org-overlay-start o) (org-overlay-end o)) clist)
14620 (push (list :latex-preview
14621 (org-overlay-start o) (org-overlay-end o)) clist))
14622 ((org-inside-LaTeX-fragment-p)
14623 ;; FIXME: positions wrong.
14624 (push (list :latex-fragment (point) (point)) clist)))
14626 (setq clist (nreverse (delq nil clist)))
14627 clist))
14629 ;; FIXME: Compare with at-regexp-p Do we need both?
14630 (defun org-in-regexp (re &optional nlines visually)
14631 "Check if point is inside a match of regexp.
14632 Normally only the current line is checked, but you can include NLINES extra
14633 lines both before and after point into the search.
14634 If VISUALLY is set, require that the cursor is not after the match but
14635 really on, so that the block visually is on the match."
14636 (catch 'exit
14637 (let ((pos (point))
14638 (eol (point-at-eol (+ 1 (or nlines 0))))
14639 (inc (if visually 1 0)))
14640 (save-excursion
14641 (beginning-of-line (- 1 (or nlines 0)))
14642 (while (re-search-forward re eol t)
14643 (if (and (<= (match-beginning 0) pos)
14644 (>= (+ inc (match-end 0)) pos))
14645 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14647 (defun org-at-regexp-p (regexp)
14648 "Is point inside a match of REGEXP in the current line?"
14649 (catch 'exit
14650 (save-excursion
14651 (let ((pos (point)) (end (point-at-eol)))
14652 (beginning-of-line 1)
14653 (while (re-search-forward regexp end t)
14654 (if (and (<= (match-beginning 0) pos)
14655 (>= (match-end 0) pos))
14656 (throw 'exit t)))
14657 nil))))
14659 (defun org-occur-in-agenda-files (regexp &optional nlines)
14660 "Call `multi-occur' with buffers for all agenda files."
14661 (interactive "sOrg-files matching: \np")
14662 (let* ((files (org-agenda-files))
14663 (tnames (mapcar 'file-truename files))
14664 (extra org-agenda-text-search-extra-files)
14666 (when (eq (car extra) 'agenda-archives)
14667 (setq extra (cdr extra))
14668 (setq files (org-add-archive-files files)))
14669 (while (setq f (pop extra))
14670 (unless (member (file-truename f) tnames)
14671 (add-to-list 'files f 'append)
14672 (add-to-list 'tnames (file-truename f) 'append)))
14673 (multi-occur
14674 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14675 regexp)))
14677 (if (boundp 'occur-mode-find-occurrence-hook)
14678 ;; Emacs 23
14679 (add-hook 'occur-mode-find-occurrence-hook
14680 (lambda ()
14681 (when (org-mode-p)
14682 (org-reveal))))
14683 ;; Emacs 22
14684 (defadvice occur-mode-goto-occurrence
14685 (after org-occur-reveal activate)
14686 (and (org-mode-p) (org-reveal)))
14687 (defadvice occur-mode-goto-occurrence-other-window
14688 (after org-occur-reveal activate)
14689 (and (org-mode-p) (org-reveal)))
14690 (defadvice occur-mode-display-occurrence
14691 (after org-occur-reveal activate)
14692 (when (org-mode-p)
14693 (let ((pos (occur-mode-find-occurrence)))
14694 (with-current-buffer (marker-buffer pos)
14695 (save-excursion
14696 (goto-char pos)
14697 (org-reveal)))))))
14699 (defun org-uniquify (list)
14700 "Remove duplicate elements from LIST."
14701 (let (res)
14702 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14703 res))
14705 (defun org-delete-all (elts list)
14706 "Remove all elements in ELTS from LIST."
14707 (while elts
14708 (setq list (delete (pop elts) list)))
14709 list)
14711 (defun org-back-over-empty-lines ()
14712 "Move backwards over whitespace, to the beginning of the first empty line.
14713 Returns the number of empty lines passed."
14714 (let ((pos (point)))
14715 (skip-chars-backward " \t\n\r")
14716 (beginning-of-line 2)
14717 (goto-char (min (point) pos))
14718 (count-lines (point) pos)))
14720 (defun org-skip-whitespace ()
14721 (skip-chars-forward " \t\n\r"))
14723 (defun org-point-in-group (point group &optional context)
14724 "Check if POINT is in match-group GROUP.
14725 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14726 match. If the match group does ot exist or point is not inside it,
14727 return nil."
14728 (and (match-beginning group)
14729 (>= point (match-beginning group))
14730 (<= point (match-end group))
14731 (if context
14732 (list context (match-beginning group) (match-end group))
14733 t)))
14735 (defun org-switch-to-buffer-other-window (&rest args)
14736 "Switch to buffer in a second window on the current frame.
14737 In particular, do not allow pop-up frames."
14738 (let (pop-up-frames special-display-buffer-names special-display-regexps
14739 special-display-function)
14740 (apply 'switch-to-buffer-other-window args)))
14742 (defun org-combine-plists (&rest plists)
14743 "Create a single property list from all plists in PLISTS.
14744 The process starts by copying the first list, and then setting properties
14745 from the other lists. Settings in the last list are the most significant
14746 ones and overrule settings in the other lists."
14747 (let ((rtn (copy-sequence (pop plists)))
14748 p v ls)
14749 (while plists
14750 (setq ls (pop plists))
14751 (while ls
14752 (setq p (pop ls) v (pop ls))
14753 (setq rtn (plist-put rtn p v))))
14754 rtn))
14756 (defun org-move-line-down (arg)
14757 "Move the current line down. With prefix argument, move it past ARG lines."
14758 (interactive "p")
14759 (let ((col (current-column))
14760 beg end pos)
14761 (beginning-of-line 1) (setq beg (point))
14762 (beginning-of-line 2) (setq end (point))
14763 (beginning-of-line (+ 1 arg))
14764 (setq pos (move-marker (make-marker) (point)))
14765 (insert (delete-and-extract-region beg end))
14766 (goto-char pos)
14767 (org-move-to-column col)))
14769 (defun org-move-line-up (arg)
14770 "Move the current line up. With prefix argument, move it past ARG lines."
14771 (interactive "p")
14772 (let ((col (current-column))
14773 beg end pos)
14774 (beginning-of-line 1) (setq beg (point))
14775 (beginning-of-line 2) (setq end (point))
14776 (beginning-of-line (- arg))
14777 (setq pos (move-marker (make-marker) (point)))
14778 (insert (delete-and-extract-region beg end))
14779 (goto-char pos)
14780 (org-move-to-column col)))
14782 (defun org-replace-escapes (string table)
14783 "Replace %-escapes in STRING with values in TABLE.
14784 TABLE is an association list with keys like \"%a\" and string values.
14785 The sequences in STRING may contain normal field width and padding information,
14786 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14787 so values can contain further %-escapes if they are define later in TABLE."
14788 (let ((case-fold-search nil)
14789 e re rpl)
14790 (while (setq e (pop table))
14791 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14792 (while (string-match re string)
14793 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14794 (cdr e)))
14795 (setq string (replace-match rpl t t string))))
14796 string))
14799 (defun org-sublist (list start end)
14800 "Return a section of LIST, from START to END.
14801 Counting starts at 1."
14802 (let (rtn (c start))
14803 (setq list (nthcdr (1- start) list))
14804 (while (and list (<= c end))
14805 (push (pop list) rtn)
14806 (setq c (1+ c)))
14807 (nreverse rtn)))
14809 (defun org-find-base-buffer-visiting (file)
14810 "Like `find-buffer-visiting' but alway return the base buffer and
14811 not an indirect buffer."
14812 (let ((buf (find-buffer-visiting file)))
14813 (if buf
14814 (or (buffer-base-buffer buf) buf)
14815 nil)))
14817 (defun org-image-file-name-regexp (&optional extensions)
14818 "Return regexp matching the file names of images.
14819 If EXTENSIONS is given, only match these."
14820 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14821 (image-file-name-regexp)
14822 (let ((image-file-name-extensions
14823 (or extensions
14824 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14825 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14826 (concat "\\."
14827 (regexp-opt (nconc (mapcar 'upcase
14828 image-file-name-extensions)
14829 image-file-name-extensions)
14831 "\\'"))))
14833 (defun org-file-image-p (file &optional extensions)
14834 "Return non-nil if FILE is an image."
14835 (save-match-data
14836 (string-match (org-image-file-name-regexp extensions) file)))
14838 (defun org-get-cursor-date ()
14839 "Return the date at cursor in as a time.
14840 This works in the calendar and in the agenda, anywhere else it just
14841 returns the current time."
14842 (let (date day defd)
14843 (cond
14844 ((eq major-mode 'calendar-mode)
14845 (setq date (calendar-cursor-to-date)
14846 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14847 ((eq major-mode 'org-agenda-mode)
14848 (setq day (get-text-property (point) 'day))
14849 (if day
14850 (setq date (calendar-gregorian-from-absolute day)
14851 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14852 (nth 2 date))))))
14853 (or defd (current-time))))
14855 (defvar org-agenda-action-marker (make-marker)
14856 "Marker pointing to the entry for the next agenda action.")
14858 (defun org-mark-entry-for-agenda-action ()
14859 "Mark the current entry as target of an agenda action.
14860 Agenda actions are actions executed from the agenda with the key `k',
14861 which make use of the date at the cursor."
14862 (interactive)
14863 (move-marker org-agenda-action-marker
14864 (save-excursion (org-back-to-heading t) (point))
14865 (current-buffer))
14866 (message
14867 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14869 ;;; Paragraph filling stuff.
14870 ;; We want this to be just right, so use the full arsenal.
14872 (defun org-indent-line-function ()
14873 "Indent line like previous, but further if previous was headline or item."
14874 (interactive)
14875 (let* ((pos (point))
14876 (itemp (org-at-item-p))
14877 (org-drawer-regexp (or org-drawer-regexp "\000"))
14878 column bpos bcol tpos tcol bullet btype bullet-type)
14879 ;; Find the previous relevant line
14880 (beginning-of-line 1)
14881 (cond
14882 ((looking-at "#") (setq column 0))
14883 ((looking-at "\\*+ ") (setq column 0))
14884 ((and (looking-at "[ \t]*:END:")
14885 (save-excursion (re-search-backward org-drawer-regexp nil t)))
14886 (save-excursion
14887 (goto-char (1- (match-beginning 1)))
14888 (setq column (current-column))))
14890 (beginning-of-line 0)
14891 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
14892 (not (looking-at "[ \t]*:END:"))
14893 (not (looking-at org-drawer-regexp)))
14894 (beginning-of-line 0))
14895 (cond
14896 ((looking-at "\\*+[ \t]+")
14897 (if (not org-adapt-indentation)
14898 (setq column 0)
14899 (goto-char (match-end 0))
14900 (setq column (current-column))))
14901 ((looking-at org-drawer-regexp)
14902 (goto-char (1- (match-beginning 1)))
14903 (setq column (current-column)))
14904 ((looking-at "\\([ \t]*\\):END:")
14905 (goto-char (match-end 1))
14906 (setq column (current-column)))
14907 ((org-in-item-p)
14908 (org-beginning-of-item)
14909 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14910 (setq bpos (match-beginning 1) tpos (match-end 0)
14911 bcol (progn (goto-char bpos) (current-column))
14912 tcol (progn (goto-char tpos) (current-column))
14913 bullet (match-string 1)
14914 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14915 (if (> tcol (+ bcol org-description-max-indent))
14916 (setq tcol (+ bcol 5)))
14917 (if (not itemp)
14918 (setq column tcol)
14919 (goto-char pos)
14920 (beginning-of-line 1)
14921 (if (looking-at "\\S-")
14922 (progn
14923 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14924 (setq bullet (match-string 1)
14925 btype (if (string-match "[0-9]" bullet) "n" bullet))
14926 (setq column (if (equal btype bullet-type) bcol tcol)))
14927 (setq column (org-get-indentation)))))
14928 (t (setq column (org-get-indentation))))))
14929 (goto-char pos)
14930 (if (<= (current-column) (current-indentation))
14931 (org-indent-line-to column)
14932 (save-excursion (org-indent-line-to column)))
14933 (setq column (current-column))
14934 (beginning-of-line 1)
14935 (if (looking-at
14936 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14937 (replace-match (concat "\\1" (format org-property-format
14938 (match-string 2) (match-string 3)))
14939 t nil))
14940 (org-move-to-column column)))
14942 (defun org-set-autofill-regexps ()
14943 (interactive)
14944 ;; In the paragraph separator we include headlines, because filling
14945 ;; text in a line directly attached to a headline would otherwise
14946 ;; fill the headline as well.
14947 (org-set-local 'comment-start-skip "^#+[ \t]*")
14948 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14949 ;; The paragraph starter includes hand-formatted lists.
14950 (org-set-local 'paragraph-start
14951 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14952 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14953 ;; But only if the user has not turned off tables or fixed-width regions
14954 (org-set-local
14955 'auto-fill-inhibit-regexp
14956 (concat "\\*+ \\|#\\+"
14957 "\\|[ \t]*" org-keyword-time-regexp
14958 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14959 (concat
14960 "\\|[ \t]*["
14961 (if org-enable-table-editor "|" "")
14962 (if org-enable-fixed-width-editor ":" "")
14963 "]"))))
14964 ;; We use our own fill-paragraph function, to make sure that tables
14965 ;; and fixed-width regions are not wrapped. That function will pass
14966 ;; through to `fill-paragraph' when appropriate.
14967 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14968 ; Adaptive filling: To get full control, first make sure that
14969 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14970 (org-set-local 'adaptive-fill-regexp "\000")
14971 (org-set-local 'adaptive-fill-function
14972 'org-adaptive-fill-function)
14973 (org-set-local
14974 'align-mode-rules-list
14975 '((org-in-buffer-settings
14976 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14977 (modes . '(org-mode))))))
14979 (defun org-fill-paragraph (&optional justify)
14980 "Re-align a table, pass through to fill-paragraph if no table."
14981 (let ((table-p (org-at-table-p))
14982 (table.el-p (org-at-table.el-p)))
14983 (cond ((and (equal (char-after (point-at-bol)) ?*)
14984 (save-excursion (goto-char (point-at-bol))
14985 (looking-at outline-regexp)))
14986 t) ; skip headlines
14987 (table.el-p t) ; skip table.el tables
14988 (table-p (org-table-align) t) ; align org-mode tables
14989 (t nil)))) ; call paragraph-fill
14991 ;; For reference, this is the default value of adaptive-fill-regexp
14992 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14994 (defun org-adaptive-fill-function ()
14995 "Return a fill prefix for org-mode files.
14996 In particular, this makes sure hanging paragraphs for hand-formatted lists
14997 work correctly."
14998 (cond ((looking-at "#[ \t]+")
14999 (match-string 0))
15000 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15001 (save-excursion
15002 (if (> (match-end 1) (+ (match-beginning 1)
15003 org-description-max-indent))
15004 (goto-char (+ (match-beginning 1) 5))
15005 (goto-char (match-end 0)))
15006 (make-string (current-column) ?\ )))
15007 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15008 (save-excursion
15009 (goto-char (match-end 0))
15010 (make-string (current-column) ?\ )))
15011 (t nil)))
15013 ;;; Other stuff.
15015 (defun org-toggle-fixed-width-section (arg)
15016 "Toggle the fixed-width export.
15017 If there is no active region, the QUOTE keyword at the current headline is
15018 inserted or removed. When present, it causes the text between this headline
15019 and the next to be exported as fixed-width text, and unmodified.
15020 If there is an active region, this command adds or removes a colon as the
15021 first character of this line. If the first character of a line is a colon,
15022 this line is also exported in fixed-width font."
15023 (interactive "P")
15024 (let* ((cc 0)
15025 (regionp (org-region-active-p))
15026 (beg (if regionp (region-beginning) (point)))
15027 (end (if regionp (region-end)))
15028 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15029 (case-fold-search nil)
15030 (re "[ \t]*\\(:\\)")
15031 off)
15032 (if regionp
15033 (save-excursion
15034 (goto-char beg)
15035 (setq cc (current-column))
15036 (beginning-of-line 1)
15037 (setq off (looking-at re))
15038 (while (> nlines 0)
15039 (setq nlines (1- nlines))
15040 (beginning-of-line 1)
15041 (cond
15042 (arg
15043 (org-move-to-column cc t)
15044 (insert ":\n")
15045 (forward-line -1))
15046 ((and off (looking-at re))
15047 (replace-match "" t t nil 1))
15048 ((not off) (org-move-to-column cc t) (insert ":")))
15049 (forward-line 1)))
15050 (save-excursion
15051 (org-back-to-heading)
15052 (if (looking-at (concat outline-regexp
15053 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15054 (replace-match "" t t nil 1)
15055 (if (looking-at outline-regexp)
15056 (progn
15057 (goto-char (match-end 0))
15058 (insert org-quote-string " "))))))))
15060 ;;;; Functions extending outline functionality
15062 (defun org-beginning-of-line (&optional arg)
15063 "Go to the beginning of the current line. If that is invisible, continue
15064 to a visible line beginning. This makes the function of C-a more intuitive.
15065 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15066 first attempt, and only move to after the tags when the cursor is already
15067 beyond the end of the headline."
15068 (interactive "P")
15069 (let ((pos (point)) refpos)
15070 (beginning-of-line 1)
15071 (if (and arg (fboundp 'move-beginning-of-line))
15072 (call-interactively 'move-beginning-of-line)
15073 (if (bobp)
15075 (backward-char 1)
15076 (if (org-invisible-p)
15077 (while (and (not (bobp)) (org-invisible-p))
15078 (backward-char 1)
15079 (beginning-of-line 1))
15080 (forward-char 1))))
15081 (when org-special-ctrl-a/e
15082 (cond
15083 ((and (looking-at org-complex-heading-regexp)
15084 (= (char-after (match-end 1)) ?\ ))
15085 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15086 (point-at-eol)))
15087 (goto-char
15088 (if (eq org-special-ctrl-a/e t)
15089 (cond ((> pos refpos) refpos)
15090 ((= pos (point)) refpos)
15091 (t (point)))
15092 (cond ((> pos (point)) (point))
15093 ((not (eq last-command this-command)) (point))
15094 (t refpos)))))
15095 ((org-at-item-p)
15096 (goto-char
15097 (if (eq org-special-ctrl-a/e t)
15098 (cond ((> pos (match-end 4)) (match-end 4))
15099 ((= pos (point)) (match-end 4))
15100 (t (point)))
15101 (cond ((> pos (point)) (point))
15102 ((not (eq last-command this-command)) (point))
15103 (t (match-end 4))))))))
15104 (org-no-warnings
15105 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15107 (defun org-end-of-line (&optional arg)
15108 "Go to the end of the line.
15109 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15110 first attempt, and only move to after the tags when the cursor is already
15111 beyond the end of the headline."
15112 (interactive "P")
15113 (if (or (not org-special-ctrl-a/e)
15114 (not (org-on-heading-p))
15115 arg)
15116 (call-interactively (if (fboundp 'move-end-of-line)
15117 'move-end-of-line
15118 'end-of-line))
15119 (let ((pos (point)))
15120 (beginning-of-line 1)
15121 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15122 (if (eq org-special-ctrl-a/e t)
15123 (if (or (< pos (match-beginning 1))
15124 (= pos (match-end 0)))
15125 (goto-char (match-beginning 1))
15126 (goto-char (match-end 0)))
15127 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15128 (goto-char (match-end 0))
15129 (goto-char (match-beginning 1))))
15130 (call-interactively (if (fboundp 'move-end-of-line)
15131 'move-end-of-line
15132 'end-of-line)))))
15133 (org-no-warnings
15134 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
15137 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15138 (define-key org-mode-map "\C-e" 'org-end-of-line)
15140 (defun org-kill-line (&optional arg)
15141 "Kill line, to tags or end of line."
15142 (interactive "P")
15143 (cond
15144 ((or (not org-special-ctrl-k)
15145 (bolp)
15146 (not (org-on-heading-p)))
15147 (call-interactively 'kill-line))
15148 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15149 (kill-region (point) (match-beginning 1))
15150 (org-set-tags nil t))
15151 (t (kill-region (point) (point-at-eol)))))
15153 (define-key org-mode-map "\C-k" 'org-kill-line)
15155 (defun org-yank (&optional arg)
15156 "Yank. If the kill is a subtree, treat it specially.
15157 This command will look at the current kill and check if is a single
15158 subtree, or a series of subtrees[1]. If it passes the test, and if the
15159 cursor is at the beginning of a line or after the stars of a currently
15160 empty headline, then the yank is handled specially. How exactly depends
15161 on the value of the following variables, both set by default.
15163 org-yank-folded-subtrees
15164 When set, the subtree(s) will be folded after insertion, but only
15165 if doing so would now swallow text after the yanked text.
15167 org-yank-adjusted-subtrees
15168 When set, the subtree will be promoted or demoted in order to
15169 fit into the local outline tree structure, which means that the level
15170 will be adjusted so that it becomes the smaller one of the two
15171 *visible* surrounding headings.
15173 Any prefix to this command will cause `yank' to be called directly with
15174 no special treatment. In particular, a simple `C-u' prefix will just
15175 plainly yank the text as it is.
15177 \[1] Basically, the test checks if the first non-white line is a heading
15178 and if there are no other headings with fewer stars."
15179 (interactive "P")
15180 (setq this-command 'yank)
15181 (if arg
15182 (call-interactively 'yank)
15183 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15184 (and (org-kill-is-subtree-p)
15185 (or (bolp)
15186 (and (looking-at "[ \t]*$")
15187 (string-match
15188 "\\`\\*+\\'"
15189 (buffer-substring (point-at-bol) (point)))))))
15190 swallowp)
15191 (cond
15192 ((and subtreep org-yank-folded-subtrees)
15193 (let ((beg (point))
15194 end)
15195 (if (and subtreep org-yank-adjusted-subtrees)
15196 (org-paste-subtree nil nil 'for-yank)
15197 (call-interactively 'yank))
15198 (setq end (point))
15199 (goto-char beg)
15200 (when (and (bolp) subtreep
15201 (not (setq swallowp
15202 (org-yank-folding-would-swallow-text beg end))))
15203 (or (looking-at outline-regexp)
15204 (re-search-forward (concat "^" outline-regexp) end t))
15205 (while (and (< (point) end) (looking-at outline-regexp))
15206 (hide-subtree)
15207 (org-cycle-show-empty-lines 'folded)
15208 (condition-case nil
15209 (outline-forward-same-level 1)
15210 (error (goto-char end)))))
15211 (when swallowp
15212 (message
15213 "Yanked text not folded because that would swallow text"))
15214 (goto-char end)
15215 (skip-chars-forward " \t\n\r")
15216 (beginning-of-line 1)
15217 (push-mark beg 'nomsg)))
15218 ((and subtreep org-yank-adjusted-subtrees)
15219 (let ((beg (point-at-bol)))
15220 (org-paste-subtree nil nil 'for-yank)
15221 (push-mark beg 'nomsg)))
15223 (call-interactively 'yank))))))
15225 (defun org-yank-folding-would-swallow-text (beg end)
15226 "Would hide-subtree at BEG swallow any text after END?"
15227 (let (level)
15228 (save-excursion
15229 (goto-char beg)
15230 (when (or (looking-at outline-regexp)
15231 (re-search-forward (concat "^" outline-regexp) end t))
15232 (setq level (org-outline-level)))
15233 (goto-char end)
15234 (skip-chars-forward " \t\r\n\v\f")
15235 (if (or (eobp)
15236 (and (bolp) (looking-at org-outline-regexp)
15237 (<= (org-outline-level) level)))
15238 nil ; Nothing would be swallowed
15239 t)))) ; something would swallow
15241 (define-key org-mode-map "\C-y" 'org-yank)
15243 (defun org-invisible-p ()
15244 "Check if point is at a character currently not visible."
15245 ;; Early versions of noutline don't have `outline-invisible-p'.
15246 (if (fboundp 'outline-invisible-p)
15247 (outline-invisible-p)
15248 (get-char-property (point) 'invisible)))
15250 (defun org-invisible-p2 ()
15251 "Check if point is at a character currently not visible."
15252 (save-excursion
15253 (if (and (eolp) (not (bobp))) (backward-char 1))
15254 ;; Early versions of noutline don't have `outline-invisible-p'.
15255 (if (fboundp 'outline-invisible-p)
15256 (outline-invisible-p)
15257 (get-char-property (point) 'invisible))))
15259 (defun org-back-to-heading (&optional invisible-ok)
15260 "Call `outline-back-to-heading', but provide a better error message."
15261 (condition-case nil
15262 (outline-back-to-heading invisible-ok)
15263 (error (error "Before first headline at position %d in buffer %s"
15264 (point) (current-buffer)))))
15266 (defun org-before-first-heading-p ()
15267 "Before first heading?"
15268 (save-excursion
15269 (null (re-search-backward "^\\*+ " nil t))))
15271 (defalias 'org-on-heading-p 'outline-on-heading-p)
15272 (defalias 'org-at-heading-p 'outline-on-heading-p)
15273 (defun org-at-heading-or-item-p ()
15274 (or (org-on-heading-p) (org-at-item-p)))
15276 (defun org-on-target-p ()
15277 (or (org-in-regexp org-radio-target-regexp)
15278 (org-in-regexp org-target-regexp)))
15280 (defun org-up-heading-all (arg)
15281 "Move to the heading line of which the present line is a subheading.
15282 This function considers both visible and invisible heading lines.
15283 With argument, move up ARG levels."
15284 (if (fboundp 'outline-up-heading-all)
15285 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15286 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15288 (defun org-up-heading-safe ()
15289 "Move to the heading line of which the present line is a subheading.
15290 This version will not throw an error. It will return the level of the
15291 headline found, or nil if no higher level is found."
15292 (let (start-level re)
15293 (org-back-to-heading t)
15294 (setq start-level (funcall outline-level))
15295 (if (equal start-level 1)
15297 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15298 (if (re-search-backward re nil t)
15299 (funcall outline-level)))))
15301 (defun org-first-sibling-p ()
15302 "Is this heading the first child of its parents?"
15303 (interactive)
15304 (let ((re (concat "^" outline-regexp))
15305 level l)
15306 (unless (org-at-heading-p t)
15307 (error "Not at a heading"))
15308 (setq level (funcall outline-level))
15309 (save-excursion
15310 (if (not (re-search-backward re nil t))
15312 (setq l (funcall outline-level))
15313 (< l level)))))
15315 (defun org-goto-sibling (&optional previous)
15316 "Goto the next sibling, even if it is invisible.
15317 When PREVIOUS is set, go to the previous sibling instead. Returns t
15318 when a sibling was found. When none is found, return nil and don't
15319 move point."
15320 (let ((fun (if previous 're-search-backward 're-search-forward))
15321 (pos (point))
15322 (re (concat "^" outline-regexp))
15323 level l)
15324 (when (condition-case nil (org-back-to-heading t) (error nil))
15325 (setq level (funcall outline-level))
15326 (catch 'exit
15327 (or previous (forward-char 1))
15328 (while (funcall fun re nil t)
15329 (setq l (funcall outline-level))
15330 (when (< l level) (goto-char pos) (throw 'exit nil))
15331 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15332 (goto-char pos)
15333 nil))))
15335 (defun org-show-siblings ()
15336 "Show all siblings of the current headline."
15337 (save-excursion
15338 (while (org-goto-sibling) (org-flag-heading nil)))
15339 (save-excursion
15340 (while (org-goto-sibling 'previous)
15341 (org-flag-heading nil))))
15343 (defun org-show-hidden-entry ()
15344 "Show an entry where even the heading is hidden."
15345 (save-excursion
15346 (org-show-entry)))
15348 (defun org-flag-heading (flag &optional entry)
15349 "Flag the current heading. FLAG non-nil means make invisible.
15350 When ENTRY is non-nil, show the entire entry."
15351 (save-excursion
15352 (org-back-to-heading t)
15353 ;; Check if we should show the entire entry
15354 (if entry
15355 (progn
15356 (org-show-entry)
15357 (save-excursion
15358 (and (outline-next-heading)
15359 (org-flag-heading nil))))
15360 (outline-flag-region (max (point-min) (1- (point)))
15361 (save-excursion (outline-end-of-heading) (point))
15362 flag))))
15364 (defun org-forward-same-level (arg)
15365 "Move forward to the ARG'th subheading at same level as this one.
15366 Stop at the first and last subheadings of a superior heading.
15367 This is like outline-forward-same-level, but invisible headings are ok."
15368 (interactive "p")
15369 (org-back-to-heading t)
15370 (while (> arg 0)
15371 (let ((point-to-move-to (save-excursion
15372 (org-get-next-sibling))))
15373 (if point-to-move-to
15374 (progn
15375 (goto-char point-to-move-to)
15376 (setq arg (1- arg)))
15377 (progn
15378 (setq arg 0)
15379 (error "No following same-level heading"))))))
15381 (defun org-get-next-sibling ()
15382 "Move to next heading of the same level, and return point.
15383 If there is no such heading, return nil.
15384 This is like outline-next-sibling, but invisible headings are ok."
15385 (let ((level (funcall outline-level)))
15386 (outline-next-heading)
15387 (while (and (not (eobp)) (> (funcall outline-level) level))
15388 (outline-next-heading))
15389 (if (or (eobp) (< (funcall outline-level) level))
15391 (point))))
15393 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15394 ;; This is an exact copy of the original function, but it uses
15395 ;; `org-back-to-heading', to make it work also in invisible
15396 ;; trees. And is uses an invisible-OK argument.
15397 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15398 (org-back-to-heading invisible-OK)
15399 (let ((first t)
15400 (level (funcall outline-level)))
15401 (while (and (not (eobp))
15402 (or first (> (funcall outline-level) level)))
15403 (setq first nil)
15404 (outline-next-heading))
15405 (unless to-heading
15406 (if (memq (preceding-char) '(?\n ?\^M))
15407 (progn
15408 ;; Go to end of line before heading
15409 (forward-char -1)
15410 (if (memq (preceding-char) '(?\n ?\^M))
15411 ;; leave blank line before heading
15412 (forward-char -1))))))
15413 (point))
15415 (defun org-show-subtree ()
15416 "Show everything after this heading at deeper levels."
15417 (outline-flag-region
15418 (point)
15419 (save-excursion
15420 (outline-end-of-subtree) (outline-next-heading) (point))
15421 nil))
15423 (defun org-show-entry ()
15424 "Show the body directly following this heading.
15425 Show the heading too, if it is currently invisible."
15426 (interactive)
15427 (save-excursion
15428 (condition-case nil
15429 (progn
15430 (org-back-to-heading t)
15431 (outline-flag-region
15432 (max (point-min) (1- (point)))
15433 (save-excursion
15434 (if (re-search-forward
15435 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15436 (match-beginning 1)
15437 (point-max)))
15438 nil))
15439 (error nil))))
15441 (defun org-make-options-regexp (kwds &optional extra)
15442 "Make a regular expression for keyword lines."
15443 (concat
15445 "#?[ \t]*\\+\\("
15446 (mapconcat 'regexp-quote kwds "\\|")
15447 (if extra (concat "\\|" extra))
15448 "\\):[ \t]*"
15449 "\\(.+\\)"))
15451 ;; Make isearch reveal the necessary context
15452 (defun org-isearch-end ()
15453 "Reveal context after isearch exits."
15454 (when isearch-success ; only if search was successful
15455 (if (featurep 'xemacs)
15456 ;; Under XEmacs, the hook is run in the correct place,
15457 ;; we directly show the context.
15458 (org-show-context 'isearch)
15459 ;; In Emacs the hook runs *before* restoring the overlays.
15460 ;; So we have to use a one-time post-command-hook to do this.
15461 ;; (Emacs 22 has a special variable, see function `org-mode')
15462 (unless (and (boundp 'isearch-mode-end-hook-quit)
15463 isearch-mode-end-hook-quit)
15464 ;; Only when the isearch was not quitted.
15465 (org-add-hook 'post-command-hook 'org-isearch-post-command
15466 'append 'local)))))
15468 (defun org-isearch-post-command ()
15469 "Remove self from hook, and show context."
15470 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15471 (org-show-context 'isearch))
15474 ;;;; Integration with and fixes for other packages
15476 ;;; Imenu support
15478 (defvar org-imenu-markers nil
15479 "All markers currently used by Imenu.")
15480 (make-variable-buffer-local 'org-imenu-markers)
15482 (defun org-imenu-new-marker (&optional pos)
15483 "Return a new marker for use by Imenu, and remember the marker."
15484 (let ((m (make-marker)))
15485 (move-marker m (or pos (point)))
15486 (push m org-imenu-markers)
15489 (defun org-imenu-get-tree ()
15490 "Produce the index for Imenu."
15491 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15492 (setq org-imenu-markers nil)
15493 (let* ((n org-imenu-depth)
15494 (re (concat "^" outline-regexp))
15495 (subs (make-vector (1+ n) nil))
15496 (last-level 0)
15497 m level head)
15498 (save-excursion
15499 (save-restriction
15500 (widen)
15501 (goto-char (point-max))
15502 (while (re-search-backward re nil t)
15503 (setq level (org-reduced-level (funcall outline-level)))
15504 (when (<= level n)
15505 (looking-at org-complex-heading-regexp)
15506 (setq head (org-link-display-format
15507 (org-match-string-no-properties 4))
15508 m (org-imenu-new-marker))
15509 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15510 (if (>= level last-level)
15511 (push (cons head m) (aref subs level))
15512 (push (cons head (aref subs (1+ level))) (aref subs level))
15513 (loop for i from (1+ level) to n do (aset subs i nil)))
15514 (setq last-level level)))))
15515 (aref subs 1)))
15517 (eval-after-load "imenu"
15518 '(progn
15519 (add-hook 'imenu-after-jump-hook
15520 (lambda ()
15521 (if (eq major-mode 'org-mode)
15522 (org-show-context 'org-goto))))))
15524 (defun org-link-display-format (link)
15525 "Replace a link with either the description, or the link target
15526 if no description is present"
15527 (save-match-data
15528 (if (string-match org-bracket-link-analytic-regexp link)
15529 (replace-match (or (match-string 5 link)
15530 (concat (match-string 1 link)
15531 (match-string 3 link)))
15532 nil nil link)
15533 link)))
15535 ;; Speedbar support
15537 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15538 "Overlay marking the agenda restriction line in speedbar.")
15539 (org-overlay-put org-speedbar-restriction-lock-overlay
15540 'face 'org-agenda-restriction-lock)
15541 (org-overlay-put org-speedbar-restriction-lock-overlay
15542 'help-echo "Agendas are currently limited to this item.")
15543 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15545 (defun org-speedbar-set-agenda-restriction ()
15546 "Restrict future agenda commands to the location at point in speedbar.
15547 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15548 (interactive)
15549 (require 'org-agenda)
15550 (let (p m tp np dir txt)
15551 (cond
15552 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15553 'org-imenu t))
15554 (setq m (get-text-property p 'org-imenu-marker))
15555 (save-excursion
15556 (save-restriction
15557 (set-buffer (marker-buffer m))
15558 (goto-char m)
15559 (org-agenda-set-restriction-lock 'subtree))))
15560 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15561 'speedbar-function 'speedbar-find-file))
15562 (setq tp (previous-single-property-change
15563 (1+ p) 'speedbar-function)
15564 np (next-single-property-change
15565 tp 'speedbar-function)
15566 dir (speedbar-line-directory)
15567 txt (buffer-substring-no-properties (or tp (point-min))
15568 (or np (point-max))))
15569 (save-excursion
15570 (save-restriction
15571 (set-buffer (find-file-noselect
15572 (let ((default-directory dir))
15573 (expand-file-name txt))))
15574 (unless (org-mode-p)
15575 (error "Cannot restrict to non-Org-mode file"))
15576 (org-agenda-set-restriction-lock 'file))))
15577 (t (error "Don't know how to restrict Org-mode's agenda")))
15578 (org-move-overlay org-speedbar-restriction-lock-overlay
15579 (point-at-bol) (point-at-eol))
15580 (setq current-prefix-arg nil)
15581 (org-agenda-maybe-redo)))
15583 (eval-after-load "speedbar"
15584 '(progn
15585 (speedbar-add-supported-extension ".org")
15586 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15587 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15588 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15589 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15590 (add-hook 'speedbar-visiting-tag-hook
15591 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15594 ;;; Fixes and Hacks for problems with other packages
15596 ;; Make flyspell not check words in links, to not mess up our keymap
15597 (defun org-mode-flyspell-verify ()
15598 "Don't let flyspell put overlays at active buttons."
15599 (not (get-text-property (point) 'keymap)))
15601 ;; Make `bookmark-jump' show the jump location if it was hidden.
15602 (eval-after-load "bookmark"
15603 '(if (boundp 'bookmark-after-jump-hook)
15604 ;; We can use the hook
15605 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15606 ;; Hook not available, use advice
15607 (defadvice bookmark-jump (after org-make-visible activate)
15608 "Make the position visible."
15609 (org-bookmark-jump-unhide))))
15611 ;; Make sure saveplace show the location if it was hidden
15612 (eval-after-load "saveplace"
15613 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15614 "Make the position visible."
15615 (org-bookmark-jump-unhide)))
15617 (defun org-bookmark-jump-unhide ()
15618 "Unhide the current position, to show the bookmark location."
15619 (and (org-mode-p)
15620 (or (org-invisible-p)
15621 (save-excursion (goto-char (max (point-min) (1- (point))))
15622 (org-invisible-p)))
15623 (org-show-context 'bookmark-jump)))
15625 ;; Make session.el ignore our circular variable
15626 (eval-after-load "session"
15627 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15629 ;;;; Experimental code
15631 (defun org-closed-in-range ()
15632 "Sparse tree of items closed in a certain time range.
15633 Still experimental, may disappear in the future."
15634 (interactive)
15635 ;; Get the time interval from the user.
15636 (let* ((time1 (time-to-seconds
15637 (org-read-date nil 'to-time nil "Starting date: ")))
15638 (time2 (time-to-seconds
15639 (org-read-date nil 'to-time nil "End date:")))
15640 ;; callback function
15641 (callback (lambda ()
15642 (let ((time
15643 (time-to-seconds
15644 (apply 'encode-time
15645 (org-parse-time-string
15646 (match-string 1))))))
15647 ;; check if time in interval
15648 (and (>= time time1) (<= time time2))))))
15649 ;; make tree, check each match with the callback
15650 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15653 ;;;; Finish up
15655 (provide 'org)
15657 (run-hooks 'org-load-hook)
15659 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15661 ;;; org.el ends here