Lists: No automatic empty lines if empty lines terminate the list
[org-mode.git] / lisp / org.el
blobabb9395456f370544e942c69dfb05ee40b605b42
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.23trans
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.23trans"
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.
654 When t, `C-a' will bring back the cursor to the beginning of the
655 headline text, i.e. after the stars and after a possible TODO keyword.
656 In an item, this will be the position after the bullet.
657 When the cursor is already at that position, another `C-a' will bring
658 it to the beginning of the line.
660 `C-e' will jump to the end of the headline, ignoring the presence of tags
661 in the headline. A second `C-e' will then jump to the true end of the
662 line, after any tags.
664 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
665 and only a directly following, identical keypress will bring the cursor
666 to the special positions.
668 This may also be a cons cell where the behavior for `C-a' and `C-e' is
669 set separately."
670 :group 'org-edit-structure
671 :type '(choice
672 (const :tag "off" nil)
673 (const :tag "after stars/bullet and before tags first" t)
674 (const :tag "true line boundary first" reversed)
675 (cons :tag "Set C-a and C-e separately"
676 (choice :tag "Special C-a"
677 (const :tag "off" nil)
678 (const :tag "after stars/bullet first" t)
679 (const :tag "before stars/bullet first" reversed))
680 (choice :tag "Special C-e"
681 (const :tag "off" nil)
682 (const :tag "before tags first" t)
683 (const :tag "after tags first" reversed)))))
684 (if (fboundp 'defvaralias)
685 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
687 (defcustom org-special-ctrl-k nil
688 "Non-nil means `C-k' will behave specially in headlines.
689 When nil, `C-k' will call the default `kill-line' command.
690 When t, the following will happen while the cursor is in the headline:
692 - When the cursor is at the beginning of a headline, kill the entire
693 line and possible the folded subtree below the line.
694 - When in the middle of the headline text, kill the headline up to the tags.
695 - When after the headline text, kill the tags."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-yank-folded-subtrees t
700 "Non-nil means, when yanking subtrees, fold them.
701 If the kill is a single subtree, or a sequence of subtrees, i.e. if
702 it starts with a heading and all other headings in it are either children
703 or siblings, then fold all the subtrees. However, do this only if no
704 text after the yank would be swallowed into a folded tree by this action."
705 :group 'org-edit-structure
706 :type 'boolean)
708 (defcustom org-yank-adjusted-subtrees nil
709 "Non-nil means, when yanking subtrees, adjust the level.
710 With this setting, `org-paste-subtree' is used to insert the subtree, see
711 this function for details."
712 :group 'org-edit-structure
713 :type 'boolean)
715 (defcustom org-M-RET-may-split-line '((default . t))
716 "Non-nil means, M-RET will split the line at the cursor position.
717 When nil, it will go to the end of the line before making a
718 new line.
719 You may also set this option in a different way for different
720 contexts. Valid contexts are:
722 headline when creating a new headline
723 item when creating a new item
724 table in a table field
725 default the value to be used for all contexts not explicitly
726 customized"
727 :group 'org-structure
728 :group 'org-table
729 :type '(choice
730 (const :tag "Always" t)
731 (const :tag "Never" nil)
732 (repeat :greedy t :tag "Individual contexts"
733 (cons
734 (choice :tag "Context"
735 (const headline)
736 (const item)
737 (const table)
738 (const default))
739 (boolean)))))
742 (defcustom org-insert-heading-respect-content nil
743 "Non-nil means, insert new headings after the current subtree.
744 When nil, the new heading is created directly after the current line.
745 The commands \\[org-insert-heading-respect-content] and
746 \\[org-insert-todo-heading-respect-content] turn this variable on
747 for the duration of the command."
748 :group 'org-structure
749 :type 'boolean)
751 (defcustom org-blank-before-new-entry '((heading . auto)
752 (plain-list-item . auto))
753 "Should `org-insert-heading' leave a blank line before new heading/item?
754 The value is an alist, with `heading' and `plain-list-item' as car,
755 and a boolean flag as cdr. For plain lists, if the variable
756 `org-empty-line-terminates-plain-lists' is set, the setting here
757 is ignored and no empty line is inserted, to keep the list in tact."
758 :group 'org-edit-structure
759 :type '(list
760 (cons (const heading)
761 (choice (const :tag "Never" nil)
762 (const :tag "Always" t)
763 (const :tag "Auto" auto)))
764 (cons (const plain-list-item)
765 (choice (const :tag "Never" nil)
766 (const :tag "Always" t)
767 (const :tag "Auto" auto)))))
769 (defcustom org-insert-heading-hook nil
770 "Hook being run after inserting a new heading."
771 :group 'org-edit-structure
772 :type 'hook)
774 (defcustom org-enable-fixed-width-editor t
775 "Non-nil means, lines starting with \":\" are treated as fixed-width.
776 This currently only means, they are never auto-wrapped.
777 When nil, such lines will be treated like ordinary lines.
778 See also the QUOTE keyword."
779 :group 'org-edit-structure
780 :type 'boolean)
782 (defcustom org-edit-src-region-extra nil
783 "Additional regexps to identify regions for editing with `org-edit-src-code'.
784 For examples see the function `org-edit-src-find-region-and-lang'.
785 The regular expression identifying the begin marker should end with a newline,
786 and the regexp marking the end line should start with a newline, to make sure
787 there are kept outside the narrowed region."
788 :group 'org-edit-structure
789 :type '(repeat
790 (list
791 (regexp :tag "begin regexp")
792 (regexp :tag "end regexp")
793 (choice :tag "language"
794 (string :tag "specify")
795 (integer :tag "from match group")
796 (const :tag "from `lang' element")
797 (const :tag "from `style' element")))))
799 (defcustom org-coderef-label-format "(ref:%s)"
800 "The default coderef format.
801 This format string will be used to search for coderef labels in literal
802 examples (EXAMPLE and SRC blocks). The format can be overwritten
803 an individual literal example with the -f option, like
805 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
807 #+END_SRC
809 If you want to use this for HTML export, make sure that the format does
810 not introduce special font-locking, and avoid the HTML special
811 characters `<', `>', and `&'. The reason for this restriction is that
812 the labels are searched for only after htmlize has done its job."
813 :group 'org-edit-structure ; FIXME this is not in the right group
814 :type 'string)
816 (defcustom org-edit-fixed-width-region-mode 'artist-mode
817 "The mode that should be used to edit fixed-width regions.
818 These are the regions where each line starts with a colon."
819 :group 'org-edit-structure
820 :type '(choice
821 (const artist-mode)
822 (const picture-mode)
823 (const fundamental-mode)
824 (function :tag "Other (specify)")))
826 (defcustom org-goto-auto-isearch t
827 "Non-nil means, typing characters in org-goto starts incremental search."
828 :group 'org-edit-structure
829 :type 'boolean)
831 (defgroup org-sparse-trees nil
832 "Options concerning sparse trees in Org-mode."
833 :tag "Org Sparse Trees"
834 :group 'org-structure)
836 (defcustom org-highlight-sparse-tree-matches t
837 "Non-nil means, highlight all matches that define a sparse tree.
838 The highlights will automatically disappear the next time the buffer is
839 changed by an edit command."
840 :group 'org-sparse-trees
841 :type 'boolean)
843 (defcustom org-remove-highlights-with-change t
844 "Non-nil means, any change to the buffer will remove temporary highlights.
845 Such highlights are created by `org-occur' and `org-clock-display'.
846 When nil, `C-c C-c needs to be used to get rid of the highlights.
847 The highlights created by `org-preview-latex-fragment' always need
848 `C-c C-c' to be removed."
849 :group 'org-sparse-trees
850 :group 'org-time
851 :type 'boolean)
854 (defcustom org-occur-hook '(org-first-headline-recenter)
855 "Hook that is run after `org-occur' has constructed a sparse tree.
856 This can be used to recenter the window to show as much of the structure
857 as possible."
858 :group 'org-sparse-trees
859 :type 'hook)
861 (defgroup org-imenu-and-speedbar nil
862 "Options concerning imenu and speedbar in Org-mode."
863 :tag "Org Imenu and Speedbar"
864 :group 'org-structure)
866 (defcustom org-imenu-depth 2
867 "The maximum level for Imenu access to Org-mode headlines.
868 This also applied for speedbar access."
869 :group 'org-imenu-and-speedbar
870 :type 'number)
872 (defgroup org-table nil
873 "Options concerning tables in Org-mode."
874 :tag "Org Table"
875 :group 'org)
877 (defcustom org-enable-table-editor 'optimized
878 "Non-nil means, lines starting with \"|\" are handled by the table editor.
879 When nil, such lines will be treated like ordinary lines.
881 When equal to the symbol `optimized', the table editor will be optimized to
882 do the following:
883 - Automatic overwrite mode in front of whitespace in table fields.
884 This makes the structure of the table stay in tact as long as the edited
885 field does not exceed the column width.
886 - Minimize the number of realigns. Normally, the table is aligned each time
887 TAB or RET are pressed to move to another field. With optimization this
888 happens only if changes to a field might have changed the column width.
889 Optimization requires replacing the functions `self-insert-command',
890 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
891 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
892 very good at guessing when a re-align will be necessary, but you can always
893 force one with \\[org-ctrl-c-ctrl-c].
895 If you would like to use the optimized version in Org-mode, but the
896 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
898 This variable can be used to turn on and off the table editor during a session,
899 but in order to toggle optimization, a restart is required.
901 See also the variable `org-table-auto-blank-field'."
902 :group 'org-table
903 :type '(choice
904 (const :tag "off" nil)
905 (const :tag "on" t)
906 (const :tag "on, optimized" optimized)))
908 (defcustom org-self-insert-cluster-for-undo t
909 "Non-nil means cluster self-insert commands for undo when possible.
910 If this is set, then, like in the Emacs command loop, 20 consequtive
911 characters will be undone together.
912 This is configurable, because there is some impact on typing performance."
913 :group 'org-table
914 :type 'boolean)
916 (defcustom org-table-tab-recognizes-table.el t
917 "Non-nil means, TAB will automatically notice a table.el table.
918 When it sees such a table, it moves point into it and - if necessary -
919 calls `table-recognize-table'."
920 :group 'org-table-editing
921 :type 'boolean)
923 (defgroup org-link nil
924 "Options concerning links in Org-mode."
925 :tag "Org Link"
926 :group 'org)
928 (defvar org-link-abbrev-alist-local nil
929 "Buffer-local version of `org-link-abbrev-alist', which see.
930 The value of this is taken from the #+LINK lines.")
931 (make-variable-buffer-local 'org-link-abbrev-alist-local)
933 (defcustom org-link-abbrev-alist nil
934 "Alist of link abbreviations.
935 The car of each element is a string, to be replaced at the start of a link.
936 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
937 links in Org-mode buffers can have an optional tag after a double colon, e.g.
939 [[linkkey:tag][description]]
941 The 'linkkey' must be a word word, starting with a letter, followed
942 by letters, numbers, '-' or '_'.
944 If REPLACE is a string, the tag will simply be appended to create the link.
945 If the string contains \"%s\", the tag will be inserted there. Alternatively,
946 the placeholder \"%h\" will cause a url-encoded version of the tag to
947 be inserted at that point (see the function `url-hexify-string').
949 REPLACE may also be a function that will be called with the tag as the
950 only argument to create the link, which should be returned as a string.
952 See the manual for examples."
953 :group 'org-link
954 :type '(repeat
955 (cons
956 (string :tag "Protocol")
957 (choice
958 (string :tag "Format")
959 (function)))))
961 (defcustom org-descriptive-links t
962 "Non-nil means, hide link part and only show description of bracket links.
963 Bracket links are like [[link][description]]. This variable sets the initial
964 state in new org-mode buffers. The setting can then be toggled on a
965 per-buffer basis from the Org->Hyperlinks menu."
966 :group 'org-link
967 :type 'boolean)
969 (defcustom org-link-file-path-type 'adaptive
970 "How the path name in file links should be stored.
971 Valid values are:
973 relative Relative to the current directory, i.e. the directory of the file
974 into which the link is being inserted.
975 absolute Absolute path, if possible with ~ for home directory.
976 noabbrev Absolute path, no abbreviation of home directory.
977 adaptive Use relative path for files in the current directory and sub-
978 directories of it. For other files, use an absolute path."
979 :group 'org-link
980 :type '(choice
981 (const relative)
982 (const absolute)
983 (const noabbrev)
984 (const adaptive)))
986 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
987 "Types of links that should be activated in Org-mode files.
988 This is a list of symbols, each leading to the activation of a certain link
989 type. In principle, it does not hurt to turn on most link types - there may
990 be a small gain when turning off unused link types. The types are:
992 bracket The recommended [[link][description]] or [[link]] links with hiding.
993 angular Links in angular brackets that may contain whitespace like
994 <bbdb:Carsten Dominik>.
995 plain Plain links in normal text, no whitespace, like http://google.com.
996 radio Text that is matched by a radio target, see manual for details.
997 tag Tag settings in a headline (link to tag search).
998 date Time stamps (link to calendar).
999 footnote Footnote labels.
1001 Changing this variable requires a restart of Emacs to become effective."
1002 :group 'org-link
1003 :type '(set :greedy t
1004 (const :tag "Double bracket links (new style)" bracket)
1005 (const :tag "Angular bracket links (old style)" angular)
1006 (const :tag "Plain text links" plain)
1007 (const :tag "Radio target matches" radio)
1008 (const :tag "Tags" tag)
1009 (const :tag "Timestamps" date)
1010 (const :tag "Footnotes" footnote)))
1012 (defcustom org-make-link-description-function nil
1013 "Function to use to generate link descriptions from links. If
1014 nil the link location will be used. This function must take two
1015 parameters; the first is the link and the second the description
1016 org-insert-link has generated, and should return the description
1017 to use."
1018 :group 'org-link
1019 :type 'function)
1021 (defgroup org-link-store nil
1022 "Options concerning storing links in Org-mode."
1023 :tag "Org Store Link"
1024 :group 'org-link)
1026 (defcustom org-email-link-description-format "Email %c: %.30s"
1027 "Format of the description part of a link to an email or usenet message.
1028 The following %-escapes will be replaced by corresponding information:
1030 %F full \"From\" field
1031 %f name, taken from \"From\" field, address if no name
1032 %T full \"To\" field
1033 %t first name in \"To\" field, address if no name
1034 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1035 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1036 %s subject
1037 %m message-id.
1039 You may use normal field width specification between the % and the letter.
1040 This is for example useful to limit the length of the subject.
1042 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1043 :group 'org-link-store
1044 :type 'string)
1046 (defcustom org-from-is-user-regexp
1047 (let (r1 r2)
1048 (when (and user-mail-address (not (string= user-mail-address "")))
1049 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1050 (when (and user-full-name (not (string= user-full-name "")))
1051 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1052 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1053 "Regexp matched against the \"From:\" header of an email or usenet message.
1054 It should match if the message is from the user him/herself."
1055 :group 'org-link-store
1056 :type 'regexp)
1058 (defcustom org-link-to-org-use-id 'create-if-interactive
1059 "Non-nil means, storing a link to an Org file will use entry IDs.
1061 Note that before this variable is even considered, org-id must be loaded,
1062 to please customize `org-modules' and turn it on.
1064 The variable can have the following values:
1066 t Create an ID if needed to make a link to the current entry.
1068 create-if-interactive
1069 If `org-store-link' is called directly (interactively, as a user
1070 command), do create an ID to support the link. But when doing the
1071 job for remember, only use the ID if it already exists. The
1072 purpose of this setting is to avoid proliferation of unwanted
1073 IDs, just because you happen to be in an Org file when you
1074 call `org-remember' that automatically and preemptively
1075 creates a link. If you do want to get an ID link in a remember
1076 template to an entry not having an ID, create it first by
1077 explicitly creating a link to it, using `C-c C-l' first.
1079 use-existing
1080 Use existing ID, do not create one.
1082 nil Never use an ID to make a link, instead link using a text search for
1083 the headline text."
1084 :group 'org-link-store
1085 :type '(choice
1086 (const :tag "Create ID to make link" t)
1087 (const :tag "Create if string link interactively"
1088 'create-if-interactive)
1089 (const :tag "Only use existing" 'use-existing)
1090 (const :tag "Do not use ID to create link" nil)))
1092 (defcustom org-context-in-file-links t
1093 "Non-nil means, file links from `org-store-link' contain context.
1094 A search string will be added to the file name with :: as separator and
1095 used to find the context when the link is activated by the command
1096 `org-open-at-point'.
1097 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1098 negates this setting for the duration of the command."
1099 :group 'org-link-store
1100 :type 'boolean)
1102 (defcustom org-keep-stored-link-after-insertion nil
1103 "Non-nil means, keep link in list for entire session.
1105 The command `org-store-link' adds a link pointing to the current
1106 location to an internal list. These links accumulate during a session.
1107 The command `org-insert-link' can be used to insert links into any
1108 Org-mode file (offering completion for all stored links). When this
1109 option is nil, every link which has been inserted once using \\[org-insert-link]
1110 will be removed from the list, to make completing the unused links
1111 more efficient."
1112 :group 'org-link-store
1113 :type 'boolean)
1115 (defgroup org-link-follow nil
1116 "Options concerning following links in Org-mode."
1117 :tag "Org Follow Link"
1118 :group 'org-link)
1120 (defcustom org-link-translation-function nil
1121 "Function to translate links with different syntax to Org syntax.
1122 This can be used to translate links created for example by the Planner
1123 or emacs-wiki packages to Org syntax.
1124 The function must accept two parameters, a TYPE containing the link
1125 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1126 which is everything after the link protocol. It should return a cons
1127 with possibly modified values of type and path.
1128 Org contains a function for this, so if you set this variable to
1129 `org-translate-link-from-planner', you should be able follow many
1130 links created by planner."
1131 :group 'org-link-follow
1132 :type 'function)
1134 (defcustom org-follow-link-hook nil
1135 "Hook that is run after a link has been followed."
1136 :group 'org-link-follow
1137 :type 'hook)
1139 (defcustom org-tab-follows-link nil
1140 "Non-nil means, on links TAB will follow the link.
1141 Needs to be set before org.el is loaded.
1142 This really should not be used, it does not make sense, and the
1143 implementation is bad."
1144 :group 'org-link-follow
1145 :type 'boolean)
1147 (defcustom org-return-follows-link nil
1148 "Non-nil means, on links RET will follow the link.
1149 Needs to be set before org.el is loaded."
1150 :group 'org-link-follow
1151 :type 'boolean)
1153 (defcustom org-mouse-1-follows-link
1154 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1155 "Non-nil means, mouse-1 on a link will follow the link.
1156 A longer mouse click will still set point. Does not work on XEmacs.
1157 Needs to be set before org.el is loaded."
1158 :group 'org-link-follow
1159 :type 'boolean)
1161 (defcustom org-mark-ring-length 4
1162 "Number of different positions to be recorded in the ring
1163 Changing this requires a restart of Emacs to work correctly."
1164 :group 'org-link-follow
1165 :type 'integer)
1167 (defcustom org-link-frame-setup
1168 '((vm . vm-visit-folder-other-frame)
1169 (gnus . gnus-other-frame)
1170 (file . find-file-other-window))
1171 "Setup the frame configuration for following links.
1172 When following a link with Emacs, it may often be useful to display
1173 this link in another window or frame. This variable can be used to
1174 set this up for the different types of links.
1175 For VM, use any of
1176 `vm-visit-folder'
1177 `vm-visit-folder-other-frame'
1178 For Gnus, use any of
1179 `gnus'
1180 `gnus-other-frame'
1181 `org-gnus-no-new-news'
1182 For FILE, use any of
1183 `find-file'
1184 `find-file-other-window'
1185 `find-file-other-frame'
1186 For the calendar, use the variable `calendar-setup'.
1187 For BBDB, it is currently only possible to display the matches in
1188 another window."
1189 :group 'org-link-follow
1190 :type '(list
1191 (cons (const vm)
1192 (choice
1193 (const vm-visit-folder)
1194 (const vm-visit-folder-other-window)
1195 (const vm-visit-folder-other-frame)))
1196 (cons (const gnus)
1197 (choice
1198 (const gnus)
1199 (const gnus-other-frame)
1200 (const org-gnus-no-new-news)))
1201 (cons (const file)
1202 (choice
1203 (const find-file)
1204 (const find-file-other-window)
1205 (const find-file-other-frame)))))
1207 (defcustom org-display-internal-link-with-indirect-buffer nil
1208 "Non-nil means, use indirect buffer to display infile links.
1209 Activating internal links (from one location in a file to another location
1210 in the same file) normally just jumps to the location. When the link is
1211 activated with a C-u prefix (or with mouse-3), the link is displayed in
1212 another window. When this option is set, the other window actually displays
1213 an indirect buffer clone of the current buffer, to avoid any visibility
1214 changes to the current buffer."
1215 :group 'org-link-follow
1216 :type 'boolean)
1218 (defcustom org-open-non-existing-files nil
1219 "Non-nil means, `org-open-file' will open non-existing files.
1220 When nil, an error will be generated."
1221 :group 'org-link-follow
1222 :type 'boolean)
1224 (defcustom org-open-directory-means-index-dot-org nil
1225 "Non-nil means, a link to a directory really means to index.org.
1226 When nil, following a directory link will run dired or open a finder/explorer
1227 window on that directory."
1228 :group 'org-link-follow
1229 :type 'boolean)
1231 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1232 "Function and arguments to call for following mailto links.
1233 This is a list with the first element being a lisp function, and the
1234 remaining elements being arguments to the function. In string arguments,
1235 %a will be replaced by the address, and %s will be replaced by the subject
1236 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1237 :group 'org-link-follow
1238 :type '(choice
1239 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1240 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1241 (const :tag "message-mail" (message-mail "%a" "%s"))
1242 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1244 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1245 "Non-nil means, ask for confirmation before executing shell links.
1246 Shell links can be dangerous: just think about a link
1248 [[shell:rm -rf ~/*][Google Search]]
1250 This link would show up in your Org-mode document as \"Google Search\",
1251 but really it would remove your entire home directory.
1252 Therefore we advise against setting this variable to nil.
1253 Just change it to `y-or-n-p' of you want to confirm with a
1254 single keystroke rather than having to type \"yes\"."
1255 :group 'org-link-follow
1256 :type '(choice
1257 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1258 (const :tag "with y-or-n (faster)" y-or-n-p)
1259 (const :tag "no confirmation (dangerous)" nil)))
1261 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1262 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1263 Elisp links can be dangerous: just think about a link
1265 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1267 This link would show up in your Org-mode document as \"Google Search\",
1268 but really it would remove your entire home directory.
1269 Therefore we advise against setting this variable to nil.
1270 Just change it to `y-or-n-p' of you want to confirm with a
1271 single keystroke rather than having to type \"yes\"."
1272 :group 'org-link-follow
1273 :type '(choice
1274 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1275 (const :tag "with y-or-n (faster)" y-or-n-p)
1276 (const :tag "no confirmation (dangerous)" nil)))
1278 (defconst org-file-apps-defaults-gnu
1279 '((remote . emacs)
1280 (system . mailcap)
1281 (t . mailcap))
1282 "Default file applications on a UNIX or GNU/Linux system.
1283 See `org-file-apps'.")
1285 (defconst org-file-apps-defaults-macosx
1286 '((remote . emacs)
1287 (t . "open %s")
1288 (system . "open %s")
1289 ("ps.gz" . "gv %s")
1290 ("eps.gz" . "gv %s")
1291 ("dvi" . "xdvi %s")
1292 ("fig" . "xfig %s"))
1293 "Default file applications on a MacOS X system.
1294 The system \"open\" is known as a default, but we use X11 applications
1295 for some files for which the OS does not have a good default.
1296 See `org-file-apps'.")
1298 (defconst org-file-apps-defaults-windowsnt
1299 (list
1300 '(remote . emacs)
1301 (cons t
1302 (list (if (featurep 'xemacs)
1303 'mswindows-shell-execute
1304 'w32-shell-execute)
1305 "open" 'file))
1306 (cons 'system
1307 (list (if (featurep 'xemacs)
1308 'mswindows-shell-execute
1309 'w32-shell-execute)
1310 "open" 'file)))
1311 "Default file applications on a Windows NT system.
1312 The system \"open\" is used for most files.
1313 See `org-file-apps'.")
1315 (defcustom org-file-apps
1317 (auto-mode . emacs)
1318 ("\\.x?html?\\'" . default)
1319 ("\\.pdf\\'" . default)
1321 "External applications for opening `file:path' items in a document.
1322 Org-mode uses system defaults for different file types, but
1323 you can use this variable to set the application for a given file
1324 extension. The entries in this list are cons cells where the car identifies
1325 files and the cdr the corresponding command. Possible values for the
1326 file identifier are
1327 \"regex\" Regular expression matched against the file name. For backward
1328 compatibility, this can also be a string with only alphanumeric
1329 characters, which is then interpreted as an extension.
1330 `directory' Matches a directory
1331 `remote' Matches a remote file, accessible through tramp or efs.
1332 Remote files most likely should be visited through Emacs
1333 because external applications cannot handle such paths.
1334 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1335 so all files Emacs knows how to handle. Using this with
1336 command `emacs' will open most files in Emacs. Beware that this
1337 will also open html files inside Emacs, unless you add
1338 (\"html\" . default) to the list as well.
1339 t Default for files not matched by any of the other options.
1340 `system' The system command to open files, like `open' on Windows
1341 and Mac OS X, and mailcap under GNU/Linux. This is the command
1342 that will be selected if you call `C-c C-o' with a double
1343 `C-u C-u' prefix.
1345 Possible values for the command are:
1346 `emacs' The file will be visited by the current Emacs process.
1347 `default' Use the default application for this file type, which is the
1348 association for t in the list, most likely in the system-specific
1349 part.
1350 This can be used to overrule an unwanted setting in the
1351 system-specific variable.
1352 `system' Use the system command for opening files, like \"open\".
1353 This command is specified by the entry whose car is `system'.
1354 Most likely, the system-specific version of this variable
1355 does define this command, but you can overrule/replace it
1356 here.
1357 string A command to be executed by a shell; %s will be replaced
1358 by the path to the file.
1359 sexp A Lisp form which will be evaluated. The file path will
1360 be available in the Lisp variable `file'.
1361 For more examples, see the system specific constants
1362 `org-file-apps-defaults-macosx'
1363 `org-file-apps-defaults-windowsnt'
1364 `org-file-apps-defaults-gnu'."
1365 :group 'org-link-follow
1366 :type '(repeat
1367 (cons (choice :value ""
1368 (string :tag "Extension")
1369 (const :tag "System command to open files" system)
1370 (const :tag "Default for unrecognized files" t)
1371 (const :tag "Remote file" remote)
1372 (const :tag "Links to a directory" directory)
1373 (const :tag "Any files that have Emacs modes"
1374 auto-mode))
1375 (choice :value ""
1376 (const :tag "Visit with Emacs" emacs)
1377 (const :tag "Use default" default)
1378 (const :tag "Use the system command" system)
1379 (string :tag "Command")
1380 (sexp :tag "Lisp form")))))
1382 (defgroup org-refile nil
1383 "Options concerning refiling entries in Org-mode."
1384 :tag "Org Refile"
1385 :group 'org)
1387 (defcustom org-directory "~/org"
1388 "Directory with org files.
1389 This is just a default location to look for Org files. There is no need
1390 at all to put your files into this directory. It is only used in the
1391 following situations:
1393 1. When a remember template specifies a target file that is not an
1394 absolute path. The path will then be interpreted relative to
1395 `org-directory'
1396 2. When a remember note is filed away in an interactive way (when exiting the
1397 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1398 with `org-directory' as the default path."
1399 :group 'org-refile
1400 :group 'org-remember
1401 :type 'directory)
1403 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1404 "Default target for storing notes.
1405 Used by the hooks for remember.el. This can be a string, or nil to mean
1406 the value of `remember-data-file'.
1407 You can set this on a per-template basis with the variable
1408 `org-remember-templates'."
1409 :group 'org-refile
1410 :group 'org-remember
1411 :type '(choice
1412 (const :tag "Default from remember-data-file" nil)
1413 file))
1415 (defcustom org-goto-interface 'outline
1416 "The default interface to be used for `org-goto'.
1417 Allowed values are:
1418 outline The interface shows an outline of the relevant file
1419 and the correct heading is found by moving through
1420 the outline or by searching with incremental search.
1421 outline-path-completion Headlines in the current buffer are offered via
1422 completion. This is the interface also used by
1423 the refile command."
1424 :group 'org-refile
1425 :type '(choice
1426 (const :tag "Outline" outline)
1427 (const :tag "Outline-path-completion" outline-path-completion)))
1429 (defcustom org-goto-max-level 5
1430 "Maximum level to be considered when running org-goto with refile interface."
1431 :group 'org-refile
1432 :type 'number)
1434 (defcustom org-reverse-note-order nil
1435 "Non-nil means, store new notes at the beginning of a file or entry.
1436 When nil, new notes will be filed to the end of a file or entry.
1437 This can also be a list with cons cells of regular expressions that
1438 are matched against file names, and values."
1439 :group 'org-remember
1440 :group 'org-refile
1441 :type '(choice
1442 (const :tag "Reverse always" t)
1443 (const :tag "Reverse never" nil)
1444 (repeat :tag "By file name regexp"
1445 (cons regexp boolean))))
1447 (defcustom org-refile-targets nil
1448 "Targets for refiling entries with \\[org-refile].
1449 This is list of cons cells. Each cell contains:
1450 - a specification of the files to be considered, either a list of files,
1451 or a symbol whose function or variable value will be used to retrieve
1452 a file name or a list of file names. If you use `org-agenda-files' for
1453 that, all agenda files will be scanned for targets. Nil means, consider
1454 headings in the current buffer.
1455 - A specification of how to find candidate refile targets. This may be
1456 any of:
1457 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1458 This tag has to be present in all target headlines, inheritance will
1459 not be considered.
1460 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1461 todo keyword.
1462 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1463 headlines that are refiling targets.
1464 - a cons cell (:level . N). Any headline of level N is considered a target.
1465 Note that, when `org-odd-levels-only' is set, level corresponds to
1466 order in hierarchy, not to the number of stars.
1467 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1468 Note that, when `org-odd-levels-only' is set, level corresponds to
1469 order in hierarchy, not to the number of stars.
1471 When this variable is nil, all top-level headlines in the current buffer
1472 are used, equivalent to the value `((nil . (:level . 1))'."
1473 :group 'org-refile
1474 :type '(repeat
1475 (cons
1476 (choice :value org-agenda-files
1477 (const :tag "All agenda files" org-agenda-files)
1478 (const :tag "Current buffer" nil)
1479 (function) (variable) (file))
1480 (choice :tag "Identify target headline by"
1481 (cons :tag "Specific tag" (const :value :tag) (string))
1482 (cons :tag "TODO keyword" (const :value :todo) (string))
1483 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1484 (cons :tag "Level number" (const :value :level) (integer))
1485 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1487 (defcustom org-refile-use-outline-path nil
1488 "Non-nil means, provide refile targets as paths.
1489 So a level 3 headline will be available as level1/level2/level3.
1490 When the value is `file', also include the file name (without directory)
1491 into the path. When `full-file-path', include the full file path."
1492 :group 'org-refile
1493 :type '(choice
1494 (const :tag "Not" nil)
1495 (const :tag "Yes" t)
1496 (const :tag "Start with file name" file)
1497 (const :tag "Start with full file path" full-file-path)))
1499 (defcustom org-outline-path-complete-in-steps t
1500 "Non-nil means, complete the outline path in hierarchical steps.
1501 When Org-mode uses the refile interface to select an outline path
1502 \(see variable `org-refile-use-outline-path'), the completion of
1503 the path can be done is a single go, or if can be done in steps down
1504 the headline hierarchy. Going in steps is probably the best if you
1505 do not use a special completion package like `ido' or `icicles'.
1506 However, when using these packages, going in one step can be very
1507 fast, while still showing the whole path to the entry."
1508 :group 'org-refile
1509 :type 'boolean)
1511 (defgroup org-todo nil
1512 "Options concerning TODO items in Org-mode."
1513 :tag "Org TODO"
1514 :group 'org)
1516 (defgroup org-progress nil
1517 "Options concerning Progress logging in Org-mode."
1518 :tag "Org Progress"
1519 :group 'org-time)
1521 (defvar org-todo-interpretation-widgets
1523 (:tag "Sequence (cycling hits every state)" sequence)
1524 (:tag "Type (cycling directly to DONE)" type))
1525 "The available interpretation symbols for customizing
1526 `org-todo-keywords'.
1527 Interested libraries should add to this list.")
1529 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1530 "List of TODO entry keyword sequences and their interpretation.
1531 \\<org-mode-map>This is a list of sequences.
1533 Each sequence starts with a symbol, either `sequence' or `type',
1534 indicating if the keywords should be interpreted as a sequence of
1535 action steps, or as different types of TODO items. The first
1536 keywords are states requiring action - these states will select a headline
1537 for inclusion into the global TODO list Org-mode produces. If one of
1538 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1539 signify that no further action is necessary. If \"|\" is not found,
1540 the last keyword is treated as the only DONE state of the sequence.
1542 The command \\[org-todo] cycles an entry through these states, and one
1543 additional state where no keyword is present. For details about this
1544 cycling, see the manual.
1546 TODO keywords and interpretation can also be set on a per-file basis with
1547 the special #+SEQ_TODO and #+TYP_TODO lines.
1549 Each keyword can optionally specify a character for fast state selection
1550 \(in combination with the variable `org-use-fast-todo-selection')
1551 and specifiers for state change logging, using the same syntax
1552 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1553 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1554 indicates to record a time stamp each time this state is selected.
1556 Each keyword may also specify if a timestamp or a note should be
1557 recorded when entering or leaving the state, by adding additional
1558 characters in the parenthesis after the keyword. This looks like this:
1559 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1560 record only the time of the state change. With X and Y being either
1561 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1562 Y when leaving the state if and only if the *target* state does not
1563 define X. You may omit any of the fast-selection key or X or /Y,
1564 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1566 For backward compatibility, this variable may also be just a list
1567 of keywords - in this case the interpretation (sequence or type) will be
1568 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1569 :group 'org-todo
1570 :group 'org-keywords
1571 :type '(choice
1572 (repeat :tag "Old syntax, just keywords"
1573 (string :tag "Keyword"))
1574 (repeat :tag "New syntax"
1575 (cons
1576 (choice
1577 :tag "Interpretation"
1578 ;;Quick and dirty way to see
1579 ;;`org-todo-interpretations'. This takes the
1580 ;;place of item arguments
1581 :convert-widget
1582 (lambda (widget)
1583 (widget-put widget
1584 :args (mapcar
1585 #'(lambda (x)
1586 (widget-convert
1587 (cons 'const x)))
1588 org-todo-interpretation-widgets))
1589 widget))
1590 (repeat
1591 (string :tag "Keyword"))))))
1593 (defvar org-todo-keywords-1 nil
1594 "All TODO and DONE keywords active in a buffer.")
1595 (make-variable-buffer-local 'org-todo-keywords-1)
1596 (defvar org-todo-keywords-for-agenda nil)
1597 (defvar org-done-keywords-for-agenda nil)
1598 (defvar org-todo-keyword-alist-for-agenda nil)
1599 (defvar org-tag-alist-for-agenda nil)
1600 (defvar org-agenda-contributing-files nil)
1601 (defvar org-not-done-keywords nil)
1602 (make-variable-buffer-local 'org-not-done-keywords)
1603 (defvar org-done-keywords nil)
1604 (make-variable-buffer-local 'org-done-keywords)
1605 (defvar org-todo-heads nil)
1606 (make-variable-buffer-local 'org-todo-heads)
1607 (defvar org-todo-sets nil)
1608 (make-variable-buffer-local 'org-todo-sets)
1609 (defvar org-todo-log-states nil)
1610 (make-variable-buffer-local 'org-todo-log-states)
1611 (defvar org-todo-kwd-alist nil)
1612 (make-variable-buffer-local 'org-todo-kwd-alist)
1613 (defvar org-todo-key-alist nil)
1614 (make-variable-buffer-local 'org-todo-key-alist)
1615 (defvar org-todo-key-trigger nil)
1616 (make-variable-buffer-local 'org-todo-key-trigger)
1618 (defcustom org-todo-interpretation 'sequence
1619 "Controls how TODO keywords are interpreted.
1620 This variable is in principle obsolete and is only used for
1621 backward compatibility, if the interpretation of todo keywords is
1622 not given already in `org-todo-keywords'. See that variable for
1623 more information."
1624 :group 'org-todo
1625 :group 'org-keywords
1626 :type '(choice (const sequence)
1627 (const type)))
1629 (defcustom org-use-fast-todo-selection t
1630 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1631 This variable describes if and under what circumstances the cycling
1632 mechanism for TODO keywords will be replaced by a single-key, direct
1633 selection scheme.
1635 When nil, fast selection is never used.
1637 When the symbol `prefix', it will be used when `org-todo' is called with
1638 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1639 in an agenda buffer.
1641 When t, fast selection is used by default. In this case, the prefix
1642 argument forces cycling instead.
1644 In all cases, the special interface is only used if access keys have actually
1645 been assigned by the user, i.e. if keywords in the configuration are followed
1646 by a letter in parenthesis, like TODO(t)."
1647 :group 'org-todo
1648 :type '(choice
1649 (const :tag "Never" nil)
1650 (const :tag "By default" t)
1651 (const :tag "Only with C-u C-c C-t" prefix)))
1653 (defcustom org-provide-todo-statistics t
1654 "Non-nil means, update todo statistics after insert and toggle.
1655 When this is set, todo statistics is updated in the parent of the current
1656 entry each time a todo state is changed."
1657 :group 'org-todo
1658 :type 'boolean)
1660 (defcustom org-after-todo-state-change-hook nil
1661 "Hook which is run after the state of a TODO item was changed.
1662 The new state (a string with a TODO keyword, or nil) is available in the
1663 Lisp variable `state'."
1664 :group 'org-todo
1665 :type 'hook)
1667 (defvar org-blocker-hook nil
1668 "Hook for functions that are allowed to block a state change.
1670 Each function gets as its single argument a property list, see
1671 `org-trigger-hook' for more information about this list.
1673 If any of the functions in this hook returns nil, the state change
1674 is blocked.")
1676 (defvar org-trigger-hook nil
1677 "Hook for functions that are triggered by a state change.
1679 Each function gets as its single argument a property list with at least
1680 the following elements:
1682 (:type type-of-change :position pos-at-entry-start
1683 :from old-state :to new-state)
1685 Depending on the type, more properties may be present.
1687 This mechanism is currently implemented for:
1689 TODO state changes
1690 ------------------
1691 :type todo-state-change
1692 :from previous state (keyword as a string), or nil, or a symbol
1693 'todo' or 'done', to indicate the general type of state.
1694 :to new state, like in :from")
1696 (defcustom org-enforce-todo-dependencies nil
1697 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1698 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1699 be blocked if any prior sibling is not yet done.
1700 This variable needs to be set before org.el is loaded, and you need to
1701 restart Emacs after a change to make the change effective. The only way
1702 to change is while Emacs is running is through the customize interface."
1703 :set (lambda (var val)
1704 (set var val)
1705 (if val
1706 (add-hook 'org-blocker-hook
1707 'org-block-todo-from-children-or-siblings)
1708 (remove-hook 'org-blocker-hook
1709 'org-block-todo-from-children-or-siblings)))
1710 :group 'org-todo
1711 :type 'boolean)
1713 (defcustom org-enforce-todo-checkbox-dependencies nil
1714 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1715 When this is nil, checkboxes have no influence on switching TODO states.
1716 When non-nil, you first need to check off all check boxes before the TODO
1717 entry can be switched to DONE.
1718 This variable needs to be set before org.el is loaded, and you need to
1719 restart Emacs after a change to make the change effective. The only way
1720 to change is while Emacs is running is through the customize interface."
1721 :set (lambda (var val)
1722 (set var val)
1723 (if val
1724 (add-hook 'org-blocker-hook
1725 'org-block-todo-from-checkboxes)
1726 (remove-hook 'org-blocker-hook
1727 'org-block-todo-from-checkboxes)))
1728 :group 'org-todo
1729 :type 'boolean)
1731 (defcustom org-todo-state-tags-triggers nil
1732 "Tag changes that should be triggered by TODO state changes.
1733 This is a list. Each entry is
1735 (state-change (tag . flag) .......)
1737 State-change can be a string with a state, and empty string to indicate the
1738 state that has no TODO keyword, or it can be one of the symbols `todo'
1739 or `done', meaning any not-done or done state, respectively."
1740 :group 'org-todo
1741 :group 'org-tags
1742 :type '(repeat
1743 (cons (choice :tag "When changing to"
1744 (const :tag "Not-done state" todo)
1745 (const :tag "Done state" done)
1746 (string :tag "State"))
1747 (repeat
1748 (cons :tag "Tag action"
1749 (string :tag "Tag")
1750 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1752 (defcustom org-log-done nil
1753 "Information to record when a task moves to the DONE state.
1755 Possible values are:
1757 nil Don't add anything, just change the keyword
1758 time Add a time stamp to the task
1759 note Prompt a closing note and add it with template `org-log-note-headings'
1761 This option can also be set with on a per-file-basis with
1763 #+STARTUP: nologdone
1764 #+STARTUP: logdone
1765 #+STARTUP: lognotedone
1767 You can have local logging settings for a subtree by setting the LOGGING
1768 property to one or more of these keywords."
1769 :group 'org-todo
1770 :group 'org-progress
1771 :type '(choice
1772 (const :tag "No logging" nil)
1773 (const :tag "Record CLOSED timestamp" time)
1774 (const :tag "Record CLOSED timestamp with closing note." note)))
1776 ;; Normalize old uses of org-log-done.
1777 (cond
1778 ((eq org-log-done t) (setq org-log-done 'time))
1779 ((and (listp org-log-done) (memq 'done org-log-done))
1780 (setq org-log-done 'note)))
1782 (defcustom org-log-note-clock-out nil
1783 "Non-nil means, record a note when clocking out of an item.
1784 This can also be configured on a per-file basis by adding one of
1785 the following lines anywhere in the buffer:
1787 #+STARTUP: lognoteclock-out
1788 #+STARTUP: nolognoteclock-out"
1789 :group 'org-todo
1790 :group 'org-progress
1791 :type 'boolean)
1793 (defcustom org-log-done-with-time t
1794 "Non-nil means, the CLOSED time stamp will contain date and time.
1795 When nil, only the date will be recorded."
1796 :group 'org-progress
1797 :type 'boolean)
1799 (defcustom org-log-note-headings
1800 '((done . "CLOSING NOTE %t")
1801 (state . "State %-12s from %-12S %t")
1802 (note . "Note taken on %t")
1803 (clock-out . ""))
1804 "Headings for notes added to entries.
1805 The value is an alist, with the car being a symbol indicating the note
1806 context, and the cdr is the heading to be used. The heading may also be the
1807 empty string.
1808 %t in the heading will be replaced by a time stamp.
1809 %s will be replaced by the new TODO state, in double quotes.
1810 %S will be replaced by the old TODO state, in double quotes.
1811 %u will be replaced by the user name.
1812 %U will be replaced by the full user name."
1813 :group 'org-todo
1814 :group 'org-progress
1815 :type '(list :greedy t
1816 (cons (const :tag "Heading when closing an item" done) string)
1817 (cons (const :tag
1818 "Heading when changing todo state (todo sequence only)"
1819 state) string)
1820 (cons (const :tag "Heading when just taking a note" note) string)
1821 (cons (const :tag "Heading when clocking out" clock-out) string)))
1823 (unless (assq 'note org-log-note-headings)
1824 (push '(note . "%t") org-log-note-headings))
1826 (defcustom org-log-into-drawer nil
1827 "Non-nil means, insert state change notes and time stamps into a drawer.
1828 When nil, state changes notes will be inserted after the headline and
1829 any scheduling and clock lines, but not inside a drawer.
1831 The value of this variable should be the name of the drawer to use.
1832 LOGBOOK is proposed at the default drawer for this purpose, you can
1833 also set this to a string to define the drawer of your choice.
1835 A value of t is also allowed, representing \"LOGBOOK\".
1837 If this variable is set, `org-log-state-notes-insert-after-drawers'
1838 will be ognored."
1839 :group 'org-todo
1840 :group 'org-progress
1841 :type '(choice
1842 (const :tag "Not into a drawer" nil)
1843 (const :tag "LOGBOOK" t)
1844 (string :tag "Other")))
1846 (if (fboundp 'defvaralias)
1847 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1849 (defcustom org-log-state-notes-insert-after-drawers nil
1850 "Non-nil means, insert state change notes after any drawers in entry.
1851 Only the drawers that *immediately* follow the headline and the
1852 deadline/scheduled line are skipped.
1853 When nil, insert notes right after the heading and perhaps the line
1854 with deadline/scheduling if present.
1856 This variable will have no effect if `org-log-into-drawer' is
1857 set."
1858 :group 'org-todo
1859 :group 'org-progress
1860 :type 'boolean)
1862 (defcustom org-log-states-order-reversed t
1863 "Non-nil means, the latest state change note will be directly after heading.
1864 When nil, the notes will be orderer according to time."
1865 :group 'org-todo
1866 :group 'org-progress
1867 :type 'boolean)
1869 (defcustom org-log-repeat 'time
1870 "Non-nil means, record moving through the DONE state when triggering repeat.
1871 An auto-repeating tasks is immediately switched back to TODO when marked
1872 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1873 the TODO keyword definition, or recording a closing note by setting
1874 `org-log-done', there will be no record of the task moving through DONE.
1875 This variable forces taking a note anyway. Possible values are:
1877 nil Don't force a record
1878 time Record a time stamp
1879 note Record a note
1881 This option can also be set with on a per-file-basis with
1883 #+STARTUP: logrepeat
1884 #+STARTUP: lognoterepeat
1885 #+STARTUP: nologrepeat
1887 You can have local logging settings for a subtree by setting the LOGGING
1888 property to one or more of these keywords."
1889 :group 'org-todo
1890 :group 'org-progress
1891 :type '(choice
1892 (const :tag "Don't force a record" nil)
1893 (const :tag "Force recording the DONE state" time)
1894 (const :tag "Force recording a note with the DONE state" note)))
1897 (defgroup org-priorities nil
1898 "Priorities in Org-mode."
1899 :tag "Org Priorities"
1900 :group 'org-todo)
1902 (defcustom org-highest-priority ?A
1903 "The highest priority of TODO items. A character like ?A, ?B etc.
1904 Must have a smaller ASCII number than `org-lowest-priority'."
1905 :group 'org-priorities
1906 :type 'character)
1908 (defcustom org-lowest-priority ?C
1909 "The lowest priority of TODO items. A character like ?A, ?B etc.
1910 Must have a larger ASCII number than `org-highest-priority'."
1911 :group 'org-priorities
1912 :type 'character)
1914 (defcustom org-default-priority ?B
1915 "The default priority of TODO items.
1916 This is the priority an item get if no explicit priority is given."
1917 :group 'org-priorities
1918 :type 'character)
1920 (defcustom org-priority-start-cycle-with-default t
1921 "Non-nil means, start with default priority when starting to cycle.
1922 When this is nil, the first step in the cycle will be (depending on the
1923 command used) one higher or lower that the default priority."
1924 :group 'org-priorities
1925 :type 'boolean)
1927 (defgroup org-time nil
1928 "Options concerning time stamps and deadlines in Org-mode."
1929 :tag "Org Time"
1930 :group 'org)
1932 (defcustom org-insert-labeled-timestamps-at-point nil
1933 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1934 When nil, these labeled time stamps are forces into the second line of an
1935 entry, just after the headline. When scheduling from the global TODO list,
1936 the time stamp will always be forced into the second line."
1937 :group 'org-time
1938 :type 'boolean)
1940 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1941 "Formats for `format-time-string' which are used for time stamps.
1942 It is not recommended to change this constant.")
1944 (defcustom org-time-stamp-rounding-minutes '(0 5)
1945 "Number of minutes to round time stamps to.
1946 These are two values, the first applies when first creating a time stamp.
1947 The second applies when changing it with the commands `S-up' and `S-down'.
1948 When changing the time stamp, this means that it will change in steps
1949 of N minutes, as given by the second value.
1951 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1952 numbers should be factors of 60, so for example 5, 10, 15.
1954 When this is larger than 1, you can still force an exact time-stamp by using
1955 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1956 and by using a prefix arg to `S-up/down' to specify the exact number
1957 of minutes to shift."
1958 :group 'org-time
1959 :get '(lambda (var) ; Make sure all entries have 5 elements
1960 (if (integerp (default-value var))
1961 (list (default-value var) 5)
1962 (default-value var)))
1963 :type '(list
1964 (integer :tag "when inserting times")
1965 (integer :tag "when modifying times")))
1967 ;; Normalize old customizations of this variable.
1968 (when (integerp org-time-stamp-rounding-minutes)
1969 (setq org-time-stamp-rounding-minutes
1970 (list org-time-stamp-rounding-minutes
1971 org-time-stamp-rounding-minutes)))
1973 (defcustom org-display-custom-times nil
1974 "Non-nil means, overlay custom formats over all time stamps.
1975 The formats are defined through the variable `org-time-stamp-custom-formats'.
1976 To turn this on on a per-file basis, insert anywhere in the file:
1977 #+STARTUP: customtime"
1978 :group 'org-time
1979 :set 'set-default
1980 :type 'sexp)
1981 (make-variable-buffer-local 'org-display-custom-times)
1983 (defcustom org-time-stamp-custom-formats
1984 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1985 "Custom formats for time stamps. See `format-time-string' for the syntax.
1986 These are overlayed over the default ISO format if the variable
1987 `org-display-custom-times' is set. Time like %H:%M should be at the
1988 end of the second format."
1989 :group 'org-time
1990 :type 'sexp)
1992 (defun org-time-stamp-format (&optional long inactive)
1993 "Get the right format for a time string."
1994 (let ((f (if long (cdr org-time-stamp-formats)
1995 (car org-time-stamp-formats))))
1996 (if inactive
1997 (concat "[" (substring f 1 -1) "]")
1998 f)))
2000 (defcustom org-time-clocksum-format "%d:%02d"
2001 "The format string used when creating CLOCKSUM lines, or when
2002 org-mode generates a time duration."
2003 :group 'org-time
2004 :type 'string)
2006 (defcustom org-deadline-warning-days 14
2007 "No. of days before expiration during which a deadline becomes active.
2008 This variable governs the display in sparse trees and in the agenda.
2009 When 0 or negative, it means use this number (the absolute value of it)
2010 even if a deadline has a different individual lead time specified."
2011 :group 'org-time
2012 :group 'org-agenda-daily/weekly
2013 :type 'number)
2015 (defcustom org-read-date-prefer-future t
2016 "Non-nil means, assume future for incomplete date input from user.
2017 This affects the following situations:
2018 1. The user gives a day, but no month.
2019 For example, if today is the 15th, and you enter \"3\", Org-mode will
2020 read this as the third of *next* month. However, if you enter \"17\",
2021 it will be considered as *this* month.
2022 2. The user gives a month but not a year.
2023 For example, if it is april and you enter \"feb 2\", this will be read
2024 as feb 2, *next* year. \"May 5\", however, will be this year.
2026 Currently this does not work for ISO week specifications.
2028 When this option is nil, the current month and year will always be used
2029 as defaults."
2030 :group 'org-time
2031 :type 'boolean)
2033 (defcustom org-read-date-display-live t
2034 "Non-nil means, display current interpretation of date prompt live.
2035 This display will be in an overlay, in the minibuffer."
2036 :group 'org-time
2037 :type 'boolean)
2039 (defcustom org-read-date-popup-calendar t
2040 "Non-nil means, pop up a calendar when prompting for a date.
2041 In the calendar, the date can be selected with mouse-1. However, the
2042 minibuffer will also be active, and you can simply enter the date as well.
2043 When nil, only the minibuffer will be available."
2044 :group 'org-time
2045 :type 'boolean)
2046 (if (fboundp 'defvaralias)
2047 (defvaralias 'org-popup-calendar-for-date-prompt
2048 'org-read-date-popup-calendar))
2050 (defcustom org-extend-today-until 0
2051 "The hour when your day really ends. Must be an integer.
2052 This has influence for the following applications:
2053 - When switching the agenda to \"today\". It it is still earlier than
2054 the time given here, the day recognized as TODAY is actually yesterday.
2055 - When a date is read from the user and it is still before the time given
2056 here, the current date and time will be assumed to be yesterday, 23:59.
2057 Also, timestamps inserted in remember templates follow this rule.
2059 IMPORTANT: This is a feature whose implementation is and likely will
2060 remain incomplete. Really, it is only here because past midnight seems to
2061 be the favorite working time of John Wiegley :-)"
2062 :group 'org-time
2063 :type 'number)
2065 (defcustom org-edit-timestamp-down-means-later nil
2066 "Non-nil means, S-down will increase the time in a time stamp.
2067 When nil, S-up will increase."
2068 :group 'org-time
2069 :type 'boolean)
2071 (defcustom org-calendar-follow-timestamp-change t
2072 "Non-nil means, make the calendar window follow timestamp changes.
2073 When a timestamp is modified and the calendar window is visible, it will be
2074 moved to the new date."
2075 :group 'org-time
2076 :type 'boolean)
2078 (defgroup org-tags nil
2079 "Options concerning tags in Org-mode."
2080 :tag "Org Tags"
2081 :group 'org)
2083 (defcustom org-tag-alist nil
2084 "List of tags allowed in Org-mode files.
2085 When this list is nil, Org-mode will base TAG input on what is already in the
2086 buffer.
2087 The value of this variable is an alist, the car of each entry must be a
2088 keyword as a string, the cdr may be a character that is used to select
2089 that tag through the fast-tag-selection interface.
2090 See the manual for details."
2091 :group 'org-tags
2092 :type '(repeat
2093 (choice
2094 (cons (string :tag "Tag name")
2095 (character :tag "Access char"))
2096 (const :tag "Start radio group" (:startgroup))
2097 (const :tag "End radio group" (:endgroup))
2098 (const :tag "New line" (:newline)))))
2100 (defvar org-file-tags nil
2101 "List of tags that can be inherited by all entries in the file.
2102 The tags will be inherited if the variable `org-use-tag-inheritance'
2103 says they should be.
2104 This variable is populated from #+TAG lines.")
2106 (defcustom org-use-fast-tag-selection 'auto
2107 "Non-nil means, use fast tag selection scheme.
2108 This is a special interface to select and deselect tags with single keys.
2109 When nil, fast selection is never used.
2110 When the symbol `auto', fast selection is used if and only if selection
2111 characters for tags have been configured, either through the variable
2112 `org-tag-alist' or through a #+TAGS line in the buffer.
2113 When t, fast selection is always used and selection keys are assigned
2114 automatically if necessary."
2115 :group 'org-tags
2116 :type '(choice
2117 (const :tag "Always" t)
2118 (const :tag "Never" nil)
2119 (const :tag "When selection characters are configured" 'auto)))
2121 (defcustom org-fast-tag-selection-single-key nil
2122 "Non-nil means, fast tag selection exits after first change.
2123 When nil, you have to press RET to exit it.
2124 During fast tag selection, you can toggle this flag with `C-c'.
2125 This variable can also have the value `expert'. In this case, the window
2126 displaying the tags menu is not even shown, until you press C-c again."
2127 :group 'org-tags
2128 :type '(choice
2129 (const :tag "No" nil)
2130 (const :tag "Yes" t)
2131 (const :tag "Expert" expert)))
2133 (defvar org-fast-tag-selection-include-todo nil
2134 "Non-nil means, fast tags selection interface will also offer TODO states.
2135 This is an undocumented feature, you should not rely on it.")
2137 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2138 "The column to which tags should be indented in a headline.
2139 If this number is positive, it specifies the column. If it is negative,
2140 it means that the tags should be flushright to that column. For example,
2141 -80 works well for a normal 80 character screen."
2142 :group 'org-tags
2143 :type 'integer)
2145 (defcustom org-auto-align-tags t
2146 "Non-nil means, realign tags after pro/demotion of TODO state change.
2147 These operations change the length of a headline and therefore shift
2148 the tags around. With this options turned on, after each such operation
2149 the tags are again aligned to `org-tags-column'."
2150 :group 'org-tags
2151 :type 'boolean)
2153 (defcustom org-use-tag-inheritance t
2154 "Non-nil means, tags in levels apply also for sublevels.
2155 When nil, only the tags directly given in a specific line apply there.
2156 This may also be a list of tags that should be inherited, or a regexp that
2157 matches tags that should be inherited. Additional control is possible
2158 with the variable `org-tags-exclude-from-inheritance' which gives an
2159 explicit list of tags to be excluded from inheritance., even if the value of
2160 `org-use-tag-inheritance' would select it for inheritance.
2162 If this option is t, a match early-on in a tree can lead to a large
2163 number of matches in the subtree when constructing the agenda or creating
2164 a sparse tree. If you only want to see the first match in a tree during
2165 a search, check out the variable `org-tags-match-list-sublevels'."
2166 :group 'org-tags
2167 :type '(choice
2168 (const :tag "Not" nil)
2169 (const :tag "Always" t)
2170 (repeat :tag "Specific tags" (string :tag "Tag"))
2171 (regexp :tag "Tags matched by regexp")))
2173 (defcustom org-tags-exclude-from-inheritance nil
2174 "List of tags that should never be inherited.
2175 This is a way to exclude a few tags from inheritance. For way to do
2176 the opposite, to actively allow inheritance for selected tags,
2177 see the variable `org-use-tag-inheritance'."
2178 :group 'org-tags
2179 :type '(repeat (string :tag "Tag")))
2181 (defun org-tag-inherit-p (tag)
2182 "Check if TAG is one that should be inherited."
2183 (cond
2184 ((member tag org-tags-exclude-from-inheritance) nil)
2185 ((eq org-use-tag-inheritance t) t)
2186 ((not org-use-tag-inheritance) nil)
2187 ((stringp org-use-tag-inheritance)
2188 (string-match org-use-tag-inheritance tag))
2189 ((listp org-use-tag-inheritance)
2190 (member tag org-use-tag-inheritance))
2191 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2193 (defcustom org-tags-match-list-sublevels t
2194 "Non-nil means list also sublevels of headlines matching tag search.
2195 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2196 the sublevels of a headline matching a tag search often also match
2197 the same search. Listing all of them can create very long lists.
2198 Setting this variable to nil causes subtrees of a match to be skipped.
2199 This option is off by default, because inheritance in on. If you turn
2200 inheritance off, you very likely want to turn this option on.
2202 As a special case, if the tag search is restricted to TODO items, the
2203 value of this variable is ignored and sublevels are always checked, to
2204 make sure all corresponding TODO items find their way into the list.
2206 This variable is semi-obsolete and probably should always be true. It
2207 is better to limit inheritance to certain tags using the variables
2208 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2209 :group 'org-tags
2210 :type 'boolean)
2212 (defvar org-tags-history nil
2213 "History of minibuffer reads for tags.")
2214 (defvar org-last-tags-completion-table nil
2215 "The last used completion table for tags.")
2216 (defvar org-after-tags-change-hook nil
2217 "Hook that is run after the tags in a line have changed.")
2219 (defgroup org-properties nil
2220 "Options concerning properties in Org-mode."
2221 :tag "Org Properties"
2222 :group 'org)
2224 (defcustom org-property-format "%-10s %s"
2225 "How property key/value pairs should be formatted by `indent-line'.
2226 When `indent-line' hits a property definition, it will format the line
2227 according to this format, mainly to make sure that the values are
2228 lined-up with respect to each other."
2229 :group 'org-properties
2230 :type 'string)
2232 (defcustom org-use-property-inheritance nil
2233 "Non-nil means, properties apply also for sublevels.
2235 This setting is chiefly used during property searches. Turning it on can
2236 cause significant overhead when doing a search, which is why it is not
2237 on by default.
2239 When nil, only the properties directly given in the current entry count.
2240 When t, every property is inherited. The value may also be a list of
2241 properties that should have inheritance, or a regular expression matching
2242 properties that should be inherited.
2244 However, note that some special properties use inheritance under special
2245 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2246 and the properties ending in \"_ALL\" when they are used as descriptor
2247 for valid values of a property.
2249 Note for programmers:
2250 When querying an entry with `org-entry-get', you can control if inheritance
2251 should be used. By default, `org-entry-get' looks only at the local
2252 properties. You can request inheritance by setting the inherit argument
2253 to t (to force inheritance) or to `selective' (to respect the setting
2254 in this variable)."
2255 :group 'org-properties
2256 :type '(choice
2257 (const :tag "Not" nil)
2258 (const :tag "Always" t)
2259 (repeat :tag "Specific properties" (string :tag "Property"))
2260 (regexp :tag "Properties matched by regexp")))
2262 (defun org-property-inherit-p (property)
2263 "Check if PROPERTY is one that should be inherited."
2264 (cond
2265 ((eq org-use-property-inheritance t) t)
2266 ((not org-use-property-inheritance) nil)
2267 ((stringp org-use-property-inheritance)
2268 (string-match org-use-property-inheritance property))
2269 ((listp org-use-property-inheritance)
2270 (member property org-use-property-inheritance))
2271 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2273 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2274 "The default column format, if no other format has been defined.
2275 This variable can be set on the per-file basis by inserting a line
2277 #+COLUMNS: %25ITEM ....."
2278 :group 'org-properties
2279 :type 'string)
2281 (defcustom org-columns-ellipses ".."
2282 "The ellipses to be used when a field in column view is truncated.
2283 When this is the empty string, as many characters as possible are shown,
2284 but then there will be no visual indication that the field has been truncated.
2285 When this is a string of length N, the last N characters of a truncated
2286 field are replaced by this string. If the column is narrower than the
2287 ellipses string, only part of the ellipses string will be shown."
2288 :group 'org-properties
2289 :type 'string)
2291 (defcustom org-columns-modify-value-for-display-function nil
2292 "Function that modifies values for display in column view.
2293 For example, it can be used to cut out a certain part from a time stamp.
2294 The function must take 2 arguments:
2296 column-title The title of the column (*not* the property name)
2297 value The value that should be modified.
2299 The function should return the value that should be displayed,
2300 or nil if the normal value should be used."
2301 :group 'org-properties
2302 :type 'function)
2304 (defcustom org-effort-property "Effort"
2305 "The property that is being used to keep track of effort estimates.
2306 Effort estimates given in this property need to have the format H:MM."
2307 :group 'org-properties
2308 :group 'org-progress
2309 :type '(string :tag "Property"))
2311 (defconst org-global-properties-fixed
2312 '(("VISIBILITY_ALL" . "folded children content all"))
2313 "List of property/value pairs that can be inherited by any entry.
2315 These are fixed values, for the preset properties. The user variable
2316 that can be used to add to this list is `org-global-properties'.
2318 The entries in this list are cons cells where the car is a property
2319 name and cdr is a string with the value. If the value represents
2320 multiple items like an \"_ALL\" property, separate the items by
2321 spaces.")
2323 (defcustom org-global-properties nil
2324 "List of property/value pairs that can be inherited by any entry.
2326 This list will be combined with the constant `org-global-properties-fixed'.
2328 The entries in this list are cons cells where the car is a property
2329 name and cdr is a string with the value.
2331 You can set buffer-local values for the same purpose in the variable
2332 `org-file-properties' this by adding lines like
2334 #+PROPERTY: NAME VALUE"
2335 :group 'org-properties
2336 :type '(repeat
2337 (cons (string :tag "Property")
2338 (string :tag "Value"))))
2340 (defvar org-file-properties nil
2341 "List of property/value pairs that can be inherited by any entry.
2342 Valid for the current buffer.
2343 This variable is populated from #+PROPERTY lines.")
2344 (make-variable-buffer-local 'org-file-properties)
2346 (defgroup org-agenda nil
2347 "Options concerning agenda views in Org-mode."
2348 :tag "Org Agenda"
2349 :group 'org)
2351 (defvar org-category nil
2352 "Variable used by org files to set a category for agenda display.
2353 Such files should use a file variable to set it, for example
2355 # -*- mode: org; org-category: \"ELisp\"
2357 or contain a special line
2359 #+CATEGORY: ELisp
2361 If the file does not specify a category, then file's base name
2362 is used instead.")
2363 (make-variable-buffer-local 'org-category)
2364 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2366 (defcustom org-agenda-files nil
2367 "The files to be used for agenda display.
2368 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2369 \\[org-remove-file]. You can also use customize to edit the list.
2371 If an entry is a directory, all files in that directory that are matched by
2372 `org-agenda-file-regexp' will be part of the file list.
2374 If the value of the variable is not a list but a single file name, then
2375 the list of agenda files is actually stored and maintained in that file, one
2376 agenda file per line."
2377 :group 'org-agenda
2378 :type '(choice
2379 (repeat :tag "List of files and directories" file)
2380 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2382 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2383 "Regular expression to match files for `org-agenda-files'.
2384 If any element in the list in that variable contains a directory instead
2385 of a normal file, all files in that directory that are matched by this
2386 regular expression will be included."
2387 :group 'org-agenda
2388 :type 'regexp)
2390 (defcustom org-agenda-text-search-extra-files nil
2391 "List of extra files to be searched by text search commands.
2392 These files will be search in addition to the agenda files by the
2393 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2394 Note that these files will only be searched for text search commands,
2395 not for the other agenda views like todo lists, tag searches or the weekly
2396 agenda. This variable is intended to list notes and possibly archive files
2397 that should also be searched by these two commands.
2398 In fact, if the first element in the list is the symbol `agenda-archives',
2399 than all archive files of all agenda files will be added to the search
2400 scope."
2401 :group 'org-agenda
2402 :type '(set :greedy t
2403 (const :tag "Agenda Archives" agenda-archives)
2404 (repeat :inline t (file))))
2406 (if (fboundp 'defvaralias)
2407 (defvaralias 'org-agenda-multi-occur-extra-files
2408 'org-agenda-text-search-extra-files))
2410 (defcustom org-agenda-skip-unavailable-files nil
2411 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2412 A nil value means to remove them, after a query, from the list."
2413 :group 'org-agenda
2414 :type 'boolean)
2416 (defcustom org-calendar-to-agenda-key [?c]
2417 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2418 The command `org-calendar-goto-agenda' will be bound to this key. The
2419 default is the character `c' because then `c' can be used to switch back and
2420 forth between agenda and calendar."
2421 :group 'org-agenda
2422 :type 'sexp)
2424 (defcustom org-calendar-agenda-action-key [?k]
2425 "The key to be installed in `calendar-mode-map' for agenda-action.
2426 The command `org-agenda-action' will be bound to this key. The
2427 default is the character `k' because we use the same key in the agenda."
2428 :group 'org-agenda
2429 :type 'sexp)
2431 (eval-after-load "calendar"
2432 '(progn
2433 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2434 'org-calendar-goto-agenda)
2435 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2436 'org-agenda-action)))
2438 (defgroup org-latex nil
2439 "Options for embedding LaTeX code into Org-mode."
2440 :tag "Org LaTeX"
2441 :group 'org)
2443 (defcustom org-format-latex-options
2444 '(:foreground default :background default :scale 1.0
2445 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2446 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2447 "Options for creating images from LaTeX fragments.
2448 This is a property list with the following properties:
2449 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2450 `default' means use the foreground of the default face.
2451 :background the background color, or \"Transparent\".
2452 `default' means use the background of the default face.
2453 :scale a scaling factor for the size of the images.
2454 :html-foreground, :html-background, :html-scale
2455 the same numbers for HTML export.
2456 :matchers a list indicating which matchers should be used to
2457 find LaTeX fragments. Valid members of this list are:
2458 \"begin\" find environments
2459 \"$1\" find single characters surrounded by $.$
2460 \"$\" find math expressions surrounded by $...$
2461 \"$$\" find math expressions surrounded by $$....$$
2462 \"\\(\" find math expressions surrounded by \\(...\\)
2463 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2464 :group 'org-latex
2465 :type 'plist)
2467 (defcustom org-format-latex-header "\\documentclass{article}
2468 \\usepackage{fullpage} % do not remove
2469 \\usepackage{amssymb}
2470 \\usepackage[usenames]{color}
2471 \\usepackage{amsmath}
2472 \\usepackage{latexsym}
2473 \\usepackage[mathscr]{eucal}
2474 \\pagestyle{empty} % do not remove"
2475 "The document header used for processing LaTeX fragments."
2476 :group 'org-latex
2477 :type 'string)
2480 (defgroup org-font-lock nil
2481 "Font-lock settings for highlighting in Org-mode."
2482 :tag "Org Font Lock"
2483 :group 'org)
2485 (defcustom org-level-color-stars-only nil
2486 "Non-nil means fontify only the stars in each headline.
2487 When nil, the entire headline is fontified.
2488 Changing it requires restart of `font-lock-mode' to become effective
2489 also in regions already fontified."
2490 :group 'org-font-lock
2491 :type 'boolean)
2493 (defcustom org-hide-leading-stars nil
2494 "Non-nil means, hide the first N-1 stars in a headline.
2495 This works by using the face `org-hide' for these stars. This
2496 face is white for a light background, and black for a dark
2497 background. You may have to customize the face `org-hide' to
2498 make this work.
2499 Changing it requires restart of `font-lock-mode' to become effective
2500 also in regions already fontified.
2501 You may also set this on a per-file basis by adding one of the following
2502 lines to the buffer:
2504 #+STARTUP: hidestars
2505 #+STARTUP: showstars"
2506 :group 'org-font-lock
2507 :type 'boolean)
2509 (defcustom org-fontify-done-headline nil
2510 "Non-nil means, change the face of a headline if it is marked DONE.
2511 Normally, only the TODO/DONE keyword indicates the state of a headline.
2512 When this is non-nil, the headline after the keyword is set to the
2513 `org-headline-done' as an additional indication."
2514 :group 'org-font-lock
2515 :type 'boolean)
2517 (defcustom org-fontify-emphasized-text t
2518 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2519 Changing this variable requires a restart of Emacs to take effect."
2520 :group 'org-font-lock
2521 :type 'boolean)
2523 (defcustom org-highlight-latex-fragments-and-specials nil
2524 "Non-nil means, fontify what is treated specially by the exporters."
2525 :group 'org-font-lock
2526 :type 'boolean)
2528 (defcustom org-hide-emphasis-markers nil
2529 "Non-nil mean font-lock should hide the emphasis marker characters."
2530 :group 'org-font-lock
2531 :type 'boolean)
2533 (defvar org-emph-re nil
2534 "Regular expression for matching emphasis.")
2535 (defvar org-verbatim-re nil
2536 "Regular expression for matching verbatim text.")
2537 (defvar org-emphasis-regexp-components) ; defined just below
2538 (defvar org-emphasis-alist) ; defined just below
2539 (defun org-set-emph-re (var val)
2540 "Set variable and compute the emphasis regular expression."
2541 (set var val)
2542 (when (and (boundp 'org-emphasis-alist)
2543 (boundp 'org-emphasis-regexp-components)
2544 org-emphasis-alist org-emphasis-regexp-components)
2545 (let* ((e org-emphasis-regexp-components)
2546 (pre (car e))
2547 (post (nth 1 e))
2548 (border (nth 2 e))
2549 (body (nth 3 e))
2550 (nl (nth 4 e))
2551 (body1 (concat body "*?"))
2552 (markers (mapconcat 'car org-emphasis-alist ""))
2553 (vmarkers (mapconcat
2554 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2555 org-emphasis-alist "")))
2556 ;; make sure special characters appear at the right position in the class
2557 (if (string-match "\\^" markers)
2558 (setq markers (concat (replace-match "" t t markers) "^")))
2559 (if (string-match "-" markers)
2560 (setq markers (concat (replace-match "" t t markers) "-")))
2561 (if (string-match "\\^" vmarkers)
2562 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2563 (if (string-match "-" vmarkers)
2564 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2565 (if (> nl 0)
2566 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2567 (int-to-string nl) "\\}")))
2568 ;; Make the regexp
2569 (setq org-emph-re
2570 (concat "\\([" pre "]\\|^\\)"
2571 "\\("
2572 "\\([" markers "]\\)"
2573 "\\("
2574 "[^" border "]\\|"
2575 "[^" border "]"
2576 body1
2577 "[^" border "]"
2578 "\\)"
2579 "\\3\\)"
2580 "\\([" post "]\\|$\\)"))
2581 (setq org-verbatim-re
2582 (concat "\\([" pre "]\\|^\\)"
2583 "\\("
2584 "\\([" vmarkers "]\\)"
2585 "\\("
2586 "[^" border "]\\|"
2587 "[^" border "]"
2588 body1
2589 "[^" border "]"
2590 "\\)"
2591 "\\3\\)"
2592 "\\([" post "]\\|$\\)")))))
2594 (defcustom org-emphasis-regexp-components
2595 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2596 "Components used to build the regular expression for emphasis.
2597 This is a list with 6 entries. Terminology: In an emphasis string
2598 like \" *strong word* \", we call the initial space PREMATCH, the final
2599 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2600 and \"trong wor\" is the body. The different components in this variable
2601 specify what is allowed/forbidden in each part:
2603 pre Chars allowed as prematch. Beginning of line will be allowed too.
2604 post Chars allowed as postmatch. End of line will be allowed too.
2605 border The chars *forbidden* as border characters.
2606 body-regexp A regexp like \".\" to match a body character. Don't use
2607 non-shy groups here, and don't allow newline here.
2608 newline The maximum number of newlines allowed in an emphasis exp.
2610 Use customize to modify this, or restart Emacs after changing it."
2611 :group 'org-font-lock
2612 :set 'org-set-emph-re
2613 :type '(list
2614 (sexp :tag "Allowed chars in pre ")
2615 (sexp :tag "Allowed chars in post ")
2616 (sexp :tag "Forbidden chars in border ")
2617 (sexp :tag "Regexp for body ")
2618 (integer :tag "number of newlines allowed")
2619 (option (boolean :tag "Please ignore this button"))))
2621 (defcustom org-emphasis-alist
2622 `(("*" bold "<b>" "</b>")
2623 ("/" italic "<i>" "</i>")
2624 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2625 ("=" org-code "<code>" "</code>" verbatim)
2626 ("~" org-verbatim "<code>" "</code>" verbatim)
2627 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2628 "<del>" "</del>")
2630 "Special syntax for emphasized text.
2631 Text starting and ending with a special character will be emphasized, for
2632 example *bold*, _underlined_ and /italic/. This variable sets the marker
2633 characters, the face to be used by font-lock for highlighting in Org-mode
2634 Emacs buffers, and the HTML tags to be used for this.
2635 Use customize to modify this, or restart Emacs after changing it."
2636 :group 'org-font-lock
2637 :set 'org-set-emph-re
2638 :type '(repeat
2639 (list
2640 (string :tag "Marker character")
2641 (choice
2642 (face :tag "Font-lock-face")
2643 (plist :tag "Face property list"))
2644 (string :tag "HTML start tag")
2645 (string :tag "HTML end tag")
2646 (option (const verbatim)))))
2648 ;;; Miscellaneous options
2650 (defgroup org-completion nil
2651 "Completion in Org-mode."
2652 :tag "Org Completion"
2653 :group 'org)
2655 (defcustom org-completion-use-ido nil
2656 "Non-nil means, use ido completion wherever possible.
2657 Note that `ido-mode' must be active for this variable to be relevant.
2658 If you decide to turn this variable on, you might well want to turn off
2659 `org-outline-path-complete-in-steps'."
2660 :group 'org-completion
2661 :type 'boolean)
2663 (defcustom org-completion-fallback-command 'hippie-expand
2664 "The expansion command called by \\[org-complete] in normal context.
2665 Normal means, no org-mode-specific context."
2666 :group 'org-completion
2667 :type 'function)
2669 ;;; Functions and variables from ther packages
2670 ;; Declared here to avoid compiler warnings
2672 ;; XEmacs only
2673 (defvar outline-mode-menu-heading)
2674 (defvar outline-mode-menu-show)
2675 (defvar outline-mode-menu-hide)
2676 (defvar zmacs-regions) ; XEmacs regions
2678 ;; Emacs only
2679 (defvar mark-active)
2681 ;; Various packages
2682 (declare-function find-library-name "find-func" (library))
2683 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2684 (declare-function calendar-forward-day "cal-move" (arg))
2685 (declare-function calendar-goto-date "cal-move" (date))
2686 (declare-function calendar-goto-today "cal-move" ())
2687 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2688 (defvar calc-embedded-close-formula)
2689 (defvar calc-embedded-open-formula)
2690 (declare-function cdlatex-tab "ext:cdlatex" ())
2691 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2692 (defvar font-lock-unfontify-region-function)
2693 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2694 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2695 (defvar iswitchb-temp-buflist)
2696 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2697 (defvar org-agenda-tags-todo-honor-ignore-options)
2698 (declare-function org-agenda-skip "org-agenda" ())
2699 (declare-function org-format-agenda-item "org-agenda"
2700 (extra txt &optional category tags dotime noprefix remove-re))
2701 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2702 (declare-function org-agenda-change-all-lines "org-agenda"
2703 (newhead hdmarker &optional fixface just-this))
2704 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2705 (declare-function org-agenda-maybe-redo "org-agenda" ())
2706 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2707 (beg end))
2708 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2709 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2710 "org-agenda" (&optional end))
2712 (declare-function parse-time-string "parse-time" (string))
2713 (declare-function remember "remember" (&optional initial))
2714 (declare-function remember-buffer-desc "remember" ())
2715 (declare-function remember-finalize "remember" ())
2716 (defvar remember-save-after-remembering)
2717 (defvar remember-data-file)
2718 (defvar remember-register)
2719 (defvar remember-buffer)
2720 (defvar remember-handler-functions)
2721 (defvar remember-annotation-functions)
2722 (defvar texmathp-why)
2723 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2724 (declare-function table--at-cell-p "table" (position &optional object at-column))
2726 (defvar w3m-current-url)
2727 (defvar w3m-current-title)
2729 (defvar org-latex-regexps)
2731 ;;; Autoload and prepare some org modules
2733 ;; Some table stuff that needs to be defined here, because it is used
2734 ;; by the functions setting up org-mode or checking for table context.
2736 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2737 "Detects an org-type or table-type table.")
2738 (defconst org-table-line-regexp "^[ \t]*|"
2739 "Detects an org-type table line.")
2740 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2741 "Detects an org-type table line.")
2742 (defconst org-table-hline-regexp "^[ \t]*|-"
2743 "Detects an org-type table hline.")
2744 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2745 "Detects a table-type table hline.")
2746 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2747 "Searching from within a table (any type) this finds the first line
2748 outside the table.")
2750 ;; Autoload the functions in org-table.el that are needed by functions here.
2752 (eval-and-compile
2753 (org-autoload "org-table"
2754 '(org-table-align org-table-begin org-table-blank-field
2755 org-table-convert org-table-convert-region org-table-copy-down
2756 org-table-copy-region org-table-create
2757 org-table-create-or-convert-from-region
2758 org-table-create-with-table.el org-table-current-dline
2759 org-table-cut-region org-table-delete-column org-table-edit-field
2760 org-table-edit-formulas org-table-end org-table-eval-formula
2761 org-table-export org-table-field-info
2762 org-table-get-stored-formulas org-table-goto-column
2763 org-table-hline-and-move org-table-import org-table-insert-column
2764 org-table-insert-hline org-table-insert-row org-table-iterate
2765 org-table-justify-field-maybe org-table-kill-row
2766 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2767 org-table-move-column org-table-move-column-left
2768 org-table-move-column-right org-table-move-row
2769 org-table-move-row-down org-table-move-row-up
2770 org-table-next-field org-table-next-row org-table-paste-rectangle
2771 org-table-previous-field org-table-recalculate
2772 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2773 org-table-toggle-coordinate-overlays
2774 org-table-toggle-formula-debugger org-table-wrap-region
2775 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2777 (defun org-at-table-p (&optional table-type)
2778 "Return t if the cursor is inside an org-type table.
2779 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2780 (if org-enable-table-editor
2781 (save-excursion
2782 (beginning-of-line 1)
2783 (looking-at (if table-type org-table-any-line-regexp
2784 org-table-line-regexp)))
2785 nil))
2786 (defsubst org-table-p () (org-at-table-p))
2788 (defun org-at-table.el-p ()
2789 "Return t if and only if we are at a table.el table."
2790 (and (org-at-table-p 'any)
2791 (save-excursion
2792 (goto-char (org-table-begin 'any))
2793 (looking-at org-table1-hline-regexp))))
2794 (defun org-table-recognize-table.el ()
2795 "If there is a table.el table nearby, recognize it and move into it."
2796 (if org-table-tab-recognizes-table.el
2797 (if (org-at-table.el-p)
2798 (progn
2799 (beginning-of-line 1)
2800 (if (looking-at org-table-dataline-regexp)
2802 (if (looking-at org-table1-hline-regexp)
2803 (progn
2804 (beginning-of-line 2)
2805 (if (looking-at org-table-any-border-regexp)
2806 (beginning-of-line -1)))))
2807 (if (re-search-forward "|" (org-table-end t) t)
2808 (progn
2809 (require 'table)
2810 (if (table--at-cell-p (point))
2812 (message "recognizing table.el table...")
2813 (table-recognize-table)
2814 (message "recognizing table.el table...done")))
2815 (error "This should not happen..."))
2817 nil)
2818 nil))
2820 (defun org-at-table-hline-p ()
2821 "Return t if the cursor is inside a hline in a table."
2822 (if org-enable-table-editor
2823 (save-excursion
2824 (beginning-of-line 1)
2825 (looking-at org-table-hline-regexp))
2826 nil))
2828 (defvar org-table-clean-did-remove-column nil)
2830 (defun org-table-map-tables (function)
2831 "Apply FUNCTION to the start of all tables in the buffer."
2832 (save-excursion
2833 (save-restriction
2834 (widen)
2835 (goto-char (point-min))
2836 (while (re-search-forward org-table-any-line-regexp nil t)
2837 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2838 (beginning-of-line 1)
2839 (if (looking-at org-table-line-regexp)
2840 (save-excursion (funcall function)))
2841 (re-search-forward org-table-any-border-regexp nil 1))))
2842 (message "Mapping tables: done"))
2844 ;; Declare and autoload functions from org-exp.el
2846 (declare-function org-default-export-plist "org-exp")
2847 (declare-function org-infile-export-plist "org-exp")
2848 (declare-function org-get-current-options "org-exp")
2849 (eval-and-compile
2850 (org-autoload "org-exp"
2851 '(org-export org-export-as-ascii org-export-visible
2852 org-insert-export-options-template org-export-as-html-and-open
2853 org-export-as-html-batch org-export-as-html-to-buffer
2854 org-replace-region-by-html org-export-region-as-html
2855 org-export-as-html org-export-icalendar-this-file
2856 org-export-icalendar-all-agenda-files
2857 org-table-clean-before-export
2858 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2860 ;; Declare and autoload functions from org-agenda.el
2862 (eval-and-compile
2863 (org-autoload "org-agenda"
2864 '(org-agenda org-agenda-list org-search-view
2865 org-todo-list org-tags-view org-agenda-list-stuck-projects
2866 org-diary org-agenda-to-appt
2867 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2869 ;; Autoload org-remember
2871 (eval-and-compile
2872 (org-autoload "org-remember"
2873 '(org-remember-insinuate org-remember-annotation
2874 org-remember-apply-template org-remember org-remember-handler)))
2876 ;; Autoload org-clock.el
2879 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2880 (beg end))
2881 (declare-function org-clock-update-mode-line "org-clock" ())
2882 (defvar org-clock-start-time)
2883 (defvar org-clock-marker (make-marker)
2884 "Marker recording the last clock-in.")
2886 (eval-and-compile
2887 (org-autoload
2888 "org-clock"
2889 '(org-clock-in org-clock-out org-clock-cancel
2890 org-clock-goto org-clock-sum org-clock-display
2891 org-clock-remove-overlays org-clock-report
2892 org-clocktable-shift org-dblock-write:clocktable
2893 org-get-clocktable)))
2895 (defun org-clock-update-time-maybe ()
2896 "If this is a CLOCK line, update it and return t.
2897 Otherwise, return nil."
2898 (interactive)
2899 (save-excursion
2900 (beginning-of-line 1)
2901 (skip-chars-forward " \t")
2902 (when (looking-at org-clock-string)
2903 (let ((re (concat "[ \t]*" org-clock-string
2904 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2905 "\\([ \t]*=>.*\\)?\\)?"))
2906 ts te h m s neg)
2907 (cond
2908 ((not (looking-at re))
2909 nil)
2910 ((not (match-end 2))
2911 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2912 (> org-clock-marker (point))
2913 (<= org-clock-marker (point-at-eol)))
2914 ;; The clock is running here
2915 (setq org-clock-start-time
2916 (apply 'encode-time
2917 (org-parse-time-string (match-string 1))))
2918 (org-clock-update-mode-line)))
2920 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2921 (end-of-line 1)
2922 (setq ts (match-string 1)
2923 te (match-string 3))
2924 (setq s (- (time-to-seconds
2925 (apply 'encode-time (org-parse-time-string te)))
2926 (time-to-seconds
2927 (apply 'encode-time (org-parse-time-string ts))))
2928 neg (< s 0)
2929 s (abs s)
2930 h (floor (/ s 3600))
2931 s (- s (* 3600 h))
2932 m (floor (/ s 60))
2933 s (- s (* 60 s)))
2934 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2935 t))))))
2937 (defun org-check-running-clock ()
2938 "Check if the current buffer contains the running clock.
2939 If yes, offer to stop it and to save the buffer with the changes."
2940 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2941 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2942 (buffer-name))))
2943 (org-clock-out)
2944 (when (y-or-n-p "Save changed buffer?")
2945 (save-buffer))))
2947 (defun org-clocktable-try-shift (dir n)
2948 "Check if this line starts a clock table, if yes, shift the time block."
2949 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2950 (org-clocktable-shift dir n)))
2952 ;; Autoload org-timer.el
2954 ;(declare-function org-timer "org-timer")
2956 (eval-and-compile
2957 (org-autoload
2958 "org-timer"
2959 '(org-timer-start org-timer org-timer-item
2960 org-timer-change-times-in-region)))
2963 ;; Autoload archiving code
2964 ;; The stuff that is needed for cycling and tags has to be defined here.
2966 (defgroup org-archive nil
2967 "Options concerning archiving in Org-mode."
2968 :tag "Org Archive"
2969 :group 'org-structure)
2971 (defcustom org-archive-location "%s_archive::"
2972 "The location where subtrees should be archived.
2974 The value of this variable is a string, consisting of two parts,
2975 separated by a double-colon. The first part is a filename and
2976 the second part is a headline.
2978 When the filename is omitted, archiving happens in the same file.
2979 %s in the filename will be replaced by the current file
2980 name (without the directory part). Archiving to a different file
2981 is useful to keep archived entries from contributing to the
2982 Org-mode Agenda.
2984 The archived entries will be filed as subtrees of the specified
2985 headline. When the headline is omitted, the subtrees are simply
2986 filed away at the end of the file, as top-level entries. Also in
2987 the heading you can use %s to represent the file name, this can be
2988 useful when using the same archive for a number of different files.
2990 Here are a few examples:
2991 \"%s_archive::\"
2992 If the current file is Projects.org, archive in file
2993 Projects.org_archive, as top-level trees. This is the default.
2995 \"::* Archived Tasks\"
2996 Archive in the current file, under the top-level headline
2997 \"* Archived Tasks\".
2999 \"~/org/archive.org::\"
3000 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3002 \"~/org/archive.org::From %s\"
3003 Archive in file ~/org/archive.org (absolute path), und headlines
3004 \"From FILENAME\" where file name is the current file name.
3006 \"basement::** Finished Tasks\"
3007 Archive in file ./basement (relative path), as level 3 trees
3008 below the level 2 heading \"** Finished Tasks\".
3010 You may set this option on a per-file basis by adding to the buffer a
3011 line like
3013 #+ARCHIVE: basement::** Finished Tasks
3015 You may also define it locally for a subtree by setting an ARCHIVE property
3016 in the entry. If such a property is found in an entry, or anywhere up
3017 the hierarchy, it will be used."
3018 :group 'org-archive
3019 :type 'string)
3021 (defcustom org-archive-tag "ARCHIVE"
3022 "The tag that marks a subtree as archived.
3023 An archived subtree does not open during visibility cycling, and does
3024 not contribute to the agenda listings.
3025 After changing this, font-lock must be restarted in the relevant buffers to
3026 get the proper fontification."
3027 :group 'org-archive
3028 :group 'org-keywords
3029 :type 'string)
3031 (defcustom org-agenda-skip-archived-trees t
3032 "Non-nil means, the agenda will skip any items located in archived trees.
3033 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3034 variable is no longer recommended, you should leave it at the value t.
3035 Instead, use the key `v' to cycle the archives-mode in the agenda."
3036 :group 'org-archive
3037 :group 'org-agenda-skip
3038 :type 'boolean)
3040 (defcustom org-cycle-open-archived-trees nil
3041 "Non-nil means, `org-cycle' will open archived trees.
3042 An archived tree is a tree marked with the tag ARCHIVE.
3043 When nil, archived trees will stay folded. You can still open them with
3044 normal outline commands like `show-all', but not with the cycling commands."
3045 :group 'org-archive
3046 :group 'org-cycle
3047 :type 'boolean)
3049 (defcustom org-sparse-tree-open-archived-trees nil
3050 "Non-nil means sparse tree construction shows matches in archived trees.
3051 When nil, matches in these trees are highlighted, but the trees are kept in
3052 collapsed state."
3053 :group 'org-archive
3054 :group 'org-sparse-trees
3055 :type 'boolean)
3057 (defun org-cycle-hide-archived-subtrees (state)
3058 "Re-hide all archived subtrees after a visibility state change."
3059 (when (and (not org-cycle-open-archived-trees)
3060 (not (memq state '(overview folded))))
3061 (save-excursion
3062 (let* ((globalp (memq state '(contents all)))
3063 (beg (if globalp (point-min) (point)))
3064 (end (if globalp (point-max) (org-end-of-subtree t))))
3065 (org-hide-archived-subtrees beg end)
3066 (goto-char beg)
3067 (if (looking-at (concat ".*:" org-archive-tag ":"))
3068 (message "%s" (substitute-command-keys
3069 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3071 (defun org-force-cycle-archived ()
3072 "Cycle subtree even if it is archived."
3073 (interactive)
3074 (setq this-command 'org-cycle)
3075 (let ((org-cycle-open-archived-trees t))
3076 (call-interactively 'org-cycle)))
3078 (defun org-hide-archived-subtrees (beg end)
3079 "Re-hide all archived subtrees after a visibility state change."
3080 (save-excursion
3081 (let* ((re (concat ":" org-archive-tag ":")))
3082 (goto-char beg)
3083 (while (re-search-forward re end t)
3084 (and (org-on-heading-p) (hide-subtree))
3085 (org-end-of-subtree t)))))
3087 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3089 (eval-and-compile
3090 (org-autoload "org-archive"
3091 '(org-add-archive-files org-archive-subtree
3092 org-archive-to-archive-sibling org-toggle-archive-tag)))
3094 ;; Autoload Column View Code
3096 (declare-function org-columns-number-to-string "org-colview")
3097 (declare-function org-columns-get-format-and-top-level "org-colview")
3098 (declare-function org-columns-compute "org-colview")
3100 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3101 '(org-columns-number-to-string org-columns-get-format-and-top-level
3102 org-columns-compute org-agenda-columns org-columns-remove-overlays
3103 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3105 ;; Autoload ID code
3107 (declare-function org-id-store-link "org-id")
3108 (declare-function org-id-locations-load "org-id")
3109 (declare-function org-id-locations-save "org-id")
3110 (defvar org-id-track-globally)
3111 (org-autoload "org-id"
3112 '(org-id-get-create org-id-new org-id-copy org-id-get
3113 org-id-get-with-outline-path-completion
3114 org-id-get-with-outline-drilling
3115 org-id-goto org-id-find org-id-store-link))
3117 ;; Autoload Plotting Code
3119 (org-autoload "org-plot"
3120 '(org-plot/gnuplot))
3122 ;;; Variables for pre-computed regular expressions, all buffer local
3124 (defvar org-drawer-regexp nil
3125 "Matches first line of a hidden block.")
3126 (make-variable-buffer-local 'org-drawer-regexp)
3127 (defvar org-todo-regexp nil
3128 "Matches any of the TODO state keywords.")
3129 (make-variable-buffer-local 'org-todo-regexp)
3130 (defvar org-not-done-regexp nil
3131 "Matches any of the TODO state keywords except the last one.")
3132 (make-variable-buffer-local 'org-not-done-regexp)
3133 (defvar org-todo-line-regexp nil
3134 "Matches a headline and puts TODO state into group 2 if present.")
3135 (make-variable-buffer-local 'org-todo-line-regexp)
3136 (defvar org-complex-heading-regexp nil
3137 "Matches a headline and puts everything into groups:
3138 group 1: the stars
3139 group 2: The todo keyword, maybe
3140 group 3: Priority cookie
3141 group 4: True headline
3142 group 5: Tags")
3143 (make-variable-buffer-local 'org-complex-heading-regexp)
3144 (defvar org-todo-line-tags-regexp nil
3145 "Matches a headline and puts TODO state into group 2 if present.
3146 Also put tags into group 4 if tags are present.")
3147 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3148 (defvar org-nl-done-regexp nil
3149 "Matches newline followed by a headline with the DONE keyword.")
3150 (make-variable-buffer-local 'org-nl-done-regexp)
3151 (defvar org-looking-at-done-regexp nil
3152 "Matches the DONE keyword a point.")
3153 (make-variable-buffer-local 'org-looking-at-done-regexp)
3154 (defvar org-ds-keyword-length 12
3155 "Maximum length of the Deadline and SCHEDULED keywords.")
3156 (make-variable-buffer-local 'org-ds-keyword-length)
3157 (defvar org-deadline-regexp nil
3158 "Matches the DEADLINE keyword.")
3159 (make-variable-buffer-local 'org-deadline-regexp)
3160 (defvar org-deadline-time-regexp nil
3161 "Matches the DEADLINE keyword together with a time stamp.")
3162 (make-variable-buffer-local 'org-deadline-time-regexp)
3163 (defvar org-deadline-line-regexp nil
3164 "Matches the DEADLINE keyword and the rest of the line.")
3165 (make-variable-buffer-local 'org-deadline-line-regexp)
3166 (defvar org-scheduled-regexp nil
3167 "Matches the SCHEDULED keyword.")
3168 (make-variable-buffer-local 'org-scheduled-regexp)
3169 (defvar org-scheduled-time-regexp nil
3170 "Matches the SCHEDULED keyword together with a time stamp.")
3171 (make-variable-buffer-local 'org-scheduled-time-regexp)
3172 (defvar org-closed-time-regexp nil
3173 "Matches the CLOSED keyword together with a time stamp.")
3174 (make-variable-buffer-local 'org-closed-time-regexp)
3176 (defvar org-keyword-time-regexp nil
3177 "Matches any of the 4 keywords, together with the time stamp.")
3178 (make-variable-buffer-local 'org-keyword-time-regexp)
3179 (defvar org-keyword-time-not-clock-regexp nil
3180 "Matches any of the 3 keywords, together with the time stamp.")
3181 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3182 (defvar org-maybe-keyword-time-regexp nil
3183 "Matches a timestamp, possibly preceeded by a keyword.")
3184 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3185 (defvar org-planning-or-clock-line-re nil
3186 "Matches a line with planning or clock info.")
3187 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3189 (defconst org-plain-time-of-day-regexp
3190 (concat
3191 "\\(\\<[012]?[0-9]"
3192 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3193 "\\(--?"
3194 "\\(\\<[012]?[0-9]"
3195 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3196 "\\)?")
3197 "Regular expression to match a plain time or time range.
3198 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3199 groups carry important information:
3200 0 the full match
3201 1 the first time, range or not
3202 8 the second time, if it is a range.")
3204 (defconst org-plain-time-extension-regexp
3205 (concat
3206 "\\(\\<[012]?[0-9]"
3207 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3208 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3209 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3210 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3211 groups carry important information:
3212 0 the full match
3213 7 hours of duration
3214 9 minutes of duration")
3216 (defconst org-stamp-time-of-day-regexp
3217 (concat
3218 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3219 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3220 "\\(--?"
3221 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3222 "Regular expression to match a timestamp time or time range.
3223 After a match, the following groups carry important information:
3224 0 the full match
3225 1 date plus weekday, for backreferencing to make sure both times on same day
3226 2 the first time, range or not
3227 4 the second time, if it is a range.")
3229 (defconst org-startup-options
3230 '(("fold" org-startup-folded t)
3231 ("overview" org-startup-folded t)
3232 ("nofold" org-startup-folded nil)
3233 ("showall" org-startup-folded nil)
3234 ("content" org-startup-folded content)
3235 ("hidestars" org-hide-leading-stars t)
3236 ("showstars" org-hide-leading-stars nil)
3237 ("odd" org-odd-levels-only t)
3238 ("oddeven" org-odd-levels-only nil)
3239 ("align" org-startup-align-all-tables t)
3240 ("noalign" org-startup-align-all-tables nil)
3241 ("customtime" org-display-custom-times t)
3242 ("logdone" org-log-done time)
3243 ("lognotedone" org-log-done note)
3244 ("nologdone" org-log-done nil)
3245 ("lognoteclock-out" org-log-note-clock-out t)
3246 ("nolognoteclock-out" org-log-note-clock-out nil)
3247 ("logrepeat" org-log-repeat state)
3248 ("lognoterepeat" org-log-repeat note)
3249 ("nologrepeat" org-log-repeat nil)
3250 ("fninline" org-footnote-define-inline t)
3251 ("nofninline" org-footnote-define-inline nil)
3252 ("fnlocal" org-footnote-section nil)
3253 ("fnauto" org-footnote-auto-label t)
3254 ("fnprompt" org-footnote-auto-label nil)
3255 ("fnconfirm" org-footnote-auto-label confirm)
3256 ("fnplain" org-footnote-auto-label plain)
3257 ("constcgs" constants-unit-system cgs)
3258 ("constSI" constants-unit-system SI))
3259 "Variable associated with STARTUP options for org-mode.
3260 Each element is a list of three items: The startup options as written
3261 in the #+STARTUP line, the corresponding variable, and the value to
3262 set this variable to if the option is found. An optional forth element PUSH
3263 means to push this value onto the list in the variable.")
3265 (defun org-set-regexps-and-options ()
3266 "Precompute regular expressions for current buffer."
3267 (when (org-mode-p)
3268 (org-set-local 'org-todo-kwd-alist nil)
3269 (org-set-local 'org-todo-key-alist nil)
3270 (org-set-local 'org-todo-key-trigger nil)
3271 (org-set-local 'org-todo-keywords-1 nil)
3272 (org-set-local 'org-done-keywords nil)
3273 (org-set-local 'org-todo-heads nil)
3274 (org-set-local 'org-todo-sets nil)
3275 (org-set-local 'org-todo-log-states nil)
3276 (org-set-local 'org-file-properties nil)
3277 (org-set-local 'org-file-tags nil)
3278 (let ((re (org-make-options-regexp
3279 '("CATEGORY" "TODO" "COLUMNS"
3280 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3281 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3282 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3283 (splitre "[ \t]+")
3284 kwds kws0 kwsa key log value cat arch tags const links hw dws
3285 tail sep kws1 prio props ftags drawers
3286 ext-setup-or-nil setup-contents (start 0))
3287 (save-excursion
3288 (save-restriction
3289 (widen)
3290 (goto-char (point-min))
3291 (while (or (and ext-setup-or-nil
3292 (string-match re ext-setup-or-nil start)
3293 (setq start (match-end 0)))
3294 (and (setq ext-setup-or-nil nil start 0)
3295 (re-search-forward re nil t)))
3296 (setq key (upcase (match-string 1 ext-setup-or-nil))
3297 value (org-match-string-no-properties 2 ext-setup-or-nil))
3298 (cond
3299 ((equal key "CATEGORY")
3300 (if (string-match "[ \t]+$" value)
3301 (setq value (replace-match "" t t value)))
3302 (setq cat value))
3303 ((member key '("SEQ_TODO" "TODO"))
3304 (push (cons 'sequence (org-split-string value splitre)) kwds))
3305 ((equal key "TYP_TODO")
3306 (push (cons 'type (org-split-string value splitre)) kwds))
3307 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3308 ;; general TODO-like setup
3309 (push (cons (intern (downcase (match-string 1 key)))
3310 (org-split-string value splitre)) kwds))
3311 ((equal key "TAGS")
3312 (setq tags (append tags (if tags '("\\n") nil)
3313 (org-split-string value splitre))))
3314 ((equal key "COLUMNS")
3315 (org-set-local 'org-columns-default-format value))
3316 ((equal key "LINK")
3317 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3318 (push (cons (match-string 1 value)
3319 (org-trim (match-string 2 value)))
3320 links)))
3321 ((equal key "PRIORITIES")
3322 (setq prio (org-split-string value " +")))
3323 ((equal key "PROPERTY")
3324 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3325 (push (cons (match-string 1 value) (match-string 2 value))
3326 props)))
3327 ((equal key "FILETAGS")
3328 (when (string-match "\\S-" value)
3329 (setq ftags
3330 (append
3331 ftags
3332 (apply 'append
3333 (mapcar (lambda (x) (org-split-string x ":"))
3334 (org-split-string value)))))))
3335 ((equal key "DRAWERS")
3336 (setq drawers (org-split-string value splitre)))
3337 ((equal key "CONSTANTS")
3338 (setq const (append const (org-split-string value splitre))))
3339 ((equal key "STARTUP")
3340 (let ((opts (org-split-string value splitre))
3341 l var val)
3342 (while (setq l (pop opts))
3343 (when (setq l (assoc l org-startup-options))
3344 (setq var (nth 1 l) val (nth 2 l))
3345 (if (not (nth 3 l))
3346 (set (make-local-variable var) val)
3347 (if (not (listp (symbol-value var)))
3348 (set (make-local-variable var) nil))
3349 (set (make-local-variable var) (symbol-value var))
3350 (add-to-list var val))))))
3351 ((equal key "ARCHIVE")
3352 (string-match " *$" value)
3353 (setq arch (replace-match "" t t value))
3354 (remove-text-properties 0 (length arch)
3355 '(face t fontified t) arch))
3356 ((equal key "SETUPFILE")
3357 (setq setup-contents (org-file-contents
3358 (expand-file-name
3359 (org-remove-double-quotes value))
3360 'noerror))
3361 (if (not ext-setup-or-nil)
3362 (setq ext-setup-or-nil setup-contents start 0)
3363 (setq ext-setup-or-nil
3364 (concat (substring ext-setup-or-nil 0 start)
3365 "\n" setup-contents "\n"
3366 (substring ext-setup-or-nil start)))))
3367 ))))
3368 (when cat
3369 (org-set-local 'org-category (intern cat))
3370 (push (cons "CATEGORY" cat) props))
3371 (when prio
3372 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3373 (setq prio (mapcar 'string-to-char prio))
3374 (org-set-local 'org-highest-priority (nth 0 prio))
3375 (org-set-local 'org-lowest-priority (nth 1 prio))
3376 (org-set-local 'org-default-priority (nth 2 prio)))
3377 (and props (org-set-local 'org-file-properties (nreverse props)))
3378 (and ftags (org-set-local 'org-file-tags ftags))
3379 (and drawers (org-set-local 'org-drawers drawers))
3380 (and arch (org-set-local 'org-archive-location arch))
3381 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3382 ;; Process the TODO keywords
3383 (unless kwds
3384 ;; Use the global values as if they had been given locally.
3385 (setq kwds (default-value 'org-todo-keywords))
3386 (if (stringp (car kwds))
3387 (setq kwds (list (cons org-todo-interpretation
3388 (default-value 'org-todo-keywords)))))
3389 (setq kwds (reverse kwds)))
3390 (setq kwds (nreverse kwds))
3391 (let (inter kws kw)
3392 (while (setq kws (pop kwds))
3393 (let ((kws (or
3394 (run-hook-with-args-until-success
3395 'org-todo-setup-filter-hook kws)
3396 kws)))
3397 (setq inter (pop kws) sep (member "|" kws)
3398 kws0 (delete "|" (copy-sequence kws))
3399 kwsa nil
3400 kws1 (mapcar
3401 (lambda (x)
3402 ;; 1 2
3403 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3404 (progn
3405 (setq kw (match-string 1 x)
3406 key (and (match-end 2) (match-string 2 x))
3407 log (org-extract-log-state-settings x))
3408 (push (cons kw (and key (string-to-char key))) kwsa)
3409 (and log (push log org-todo-log-states))
3411 (error "Invalid TODO keyword %s" x)))
3412 kws0)
3413 kwsa (if kwsa (append '((:startgroup))
3414 (nreverse kwsa)
3415 '((:endgroup))))
3416 hw (car kws1)
3417 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3418 tail (list inter hw (car dws) (org-last dws))))
3419 (add-to-list 'org-todo-heads hw 'append)
3420 (push kws1 org-todo-sets)
3421 (setq org-done-keywords (append org-done-keywords dws nil))
3422 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3423 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3424 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3425 (setq org-todo-sets (nreverse org-todo-sets)
3426 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3427 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3428 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3429 ;; Process the constants
3430 (when const
3431 (let (e cst)
3432 (while (setq e (pop const))
3433 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3434 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3435 (setq org-table-formula-constants-local cst)))
3437 ;; Process the tags.
3438 (when tags
3439 (let (e tgs)
3440 (while (setq e (pop tags))
3441 (cond
3442 ((equal e "{") (push '(:startgroup) tgs))
3443 ((equal e "}") (push '(:endgroup) tgs))
3444 ((equal e "\\n") (push '(:newline) tgs))
3445 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3446 (push (cons (match-string 1 e)
3447 (string-to-char (match-string 2 e)))
3448 tgs))
3449 (t (push (list e) tgs))))
3450 (org-set-local 'org-tag-alist nil)
3451 (while (setq e (pop tgs))
3452 (or (and (stringp (car e))
3453 (assoc (car e) org-tag-alist))
3454 (push e org-tag-alist)))))
3456 ;; Compute the regular expressions and other local variables
3457 (if (not org-done-keywords)
3458 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3459 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3460 (length org-scheduled-string)
3461 (length org-clock-string)
3462 (length org-closed-string)))
3463 org-drawer-regexp
3464 (concat "^[ \t]*:\\("
3465 (mapconcat 'regexp-quote org-drawers "\\|")
3466 "\\):[ \t]*$")
3467 org-not-done-keywords
3468 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3469 org-todo-regexp
3470 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3471 "\\|") "\\)\\>")
3472 org-not-done-regexp
3473 (concat "\\<\\("
3474 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3475 "\\)\\>")
3476 org-todo-line-regexp
3477 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3478 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3479 "\\)\\>\\)?[ \t]*\\(.*\\)")
3480 org-complex-heading-regexp
3481 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3482 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3483 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3484 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3485 org-nl-done-regexp
3486 (concat "\n\\*+[ \t]+"
3487 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3488 "\\)" "\\>")
3489 org-todo-line-tags-regexp
3490 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3491 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3492 (org-re
3493 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3494 org-looking-at-done-regexp
3495 (concat "^" "\\(?:"
3496 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3497 "\\>")
3498 org-deadline-regexp (concat "\\<" org-deadline-string)
3499 org-deadline-time-regexp
3500 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3501 org-deadline-line-regexp
3502 (concat "\\<\\(" org-deadline-string "\\).*")
3503 org-scheduled-regexp
3504 (concat "\\<" org-scheduled-string)
3505 org-scheduled-time-regexp
3506 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3507 org-closed-time-regexp
3508 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3509 org-keyword-time-regexp
3510 (concat "\\<\\(" org-scheduled-string
3511 "\\|" org-deadline-string
3512 "\\|" org-closed-string
3513 "\\|" org-clock-string "\\)"
3514 " *[[<]\\([^]>]+\\)[]>]")
3515 org-keyword-time-not-clock-regexp
3516 (concat "\\<\\(" org-scheduled-string
3517 "\\|" org-deadline-string
3518 "\\|" org-closed-string
3519 "\\)"
3520 " *[[<]\\([^]>]+\\)[]>]")
3521 org-maybe-keyword-time-regexp
3522 (concat "\\(\\<\\(" org-scheduled-string
3523 "\\|" org-deadline-string
3524 "\\|" org-closed-string
3525 "\\|" org-clock-string "\\)\\)?"
3526 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3527 org-planning-or-clock-line-re
3528 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3529 "\\|" org-deadline-string
3530 "\\|" org-closed-string "\\|" org-clock-string
3531 "\\)\\>\\)")
3533 (org-compute-latex-and-specials-regexp)
3534 (org-set-font-lock-defaults))))
3536 (defun org-file-contents (file &optional noerror)
3537 "Return the contents of FILE, as a string."
3538 (if (or (not file)
3539 (not (file-readable-p file)))
3540 (if noerror
3541 (progn
3542 (message "Cannot read file %s" file)
3543 (ding) (sit-for 2)
3545 (error "Cannot read file %s" file))
3546 (with-temp-buffer
3547 (insert-file-contents file)
3548 (buffer-string))))
3550 (defun org-extract-log-state-settings (x)
3551 "Extract the log state setting from a TODO keyword string.
3552 This will extract info from a string like \"WAIT(w@/!)\"."
3553 (let (kw key log1 log2)
3554 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3555 (setq kw (match-string 1 x)
3556 key (and (match-end 2) (match-string 2 x))
3557 log1 (and (match-end 3) (match-string 3 x))
3558 log2 (and (match-end 4) (match-string 4 x)))
3559 (and (or log1 log2)
3560 (list kw
3561 (and log1 (if (equal log1 "!") 'time 'note))
3562 (and log2 (if (equal log2 "!") 'time 'note)))))))
3564 (defun org-remove-keyword-keys (list)
3565 "Remove a pair of parenthesis at the end of each string in LIST."
3566 (mapcar (lambda (x)
3567 (if (string-match "(.*)$" x)
3568 (substring x 0 (match-beginning 0))
3570 list))
3572 ;; FIXME: this could be done much better, using second characters etc.
3573 (defun org-assign-fast-keys (alist)
3574 "Assign fast keys to a keyword-key alist.
3575 Respect keys that are already there."
3576 (let (new e k c c1 c2 (char ?a))
3577 (while (setq e (pop alist))
3578 (cond
3579 ((equal e '(:startgroup)) (push e new))
3580 ((equal e '(:endgroup)) (push e new))
3581 ((equal e '(:newline)) (push e new))
3583 (setq k (car e) c2 nil)
3584 (if (cdr e)
3585 (setq c (cdr e))
3586 ;; automatically assign a character.
3587 (setq c1 (string-to-char
3588 (downcase (substring
3589 k (if (= (string-to-char k) ?@) 1 0)))))
3590 (if (or (rassoc c1 new) (rassoc c1 alist))
3591 (while (or (rassoc char new) (rassoc char alist))
3592 (setq char (1+ char)))
3593 (setq c2 c1))
3594 (setq c (or c2 char)))
3595 (push (cons k c) new))))
3596 (nreverse new)))
3598 ;;; Some variables used in various places
3600 (defvar org-window-configuration nil
3601 "Used in various places to store a window configuration.")
3602 (defvar org-finish-function nil
3603 "Function to be called when `C-c C-c' is used.
3604 This is for getting out of special buffers like remember.")
3607 ;; FIXME: Occasionally check by commenting these, to make sure
3608 ;; no other functions uses these, forgetting to let-bind them.
3609 (defvar entry)
3610 (defvar state)
3611 (defvar last-state)
3612 (defvar date)
3613 (defvar description)
3615 ;; Defined somewhere in this file, but used before definition.
3616 (defvar org-html-entities)
3617 (defvar org-struct-menu)
3618 (defvar org-org-menu)
3619 (defvar org-tbl-menu)
3620 (defvar org-agenda-keymap)
3622 ;;;; Define the Org-mode
3624 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3625 (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."))
3628 ;; We use a before-change function to check if a table might need
3629 ;; an update.
3630 (defvar org-table-may-need-update t
3631 "Indicates that a table might need an update.
3632 This variable is set by `org-before-change-function'.
3633 `org-table-align' sets it back to nil.")
3634 (defun org-before-change-function (beg end)
3635 "Every change indicates that a table might need an update."
3636 (setq org-table-may-need-update t))
3637 (defvar org-mode-map)
3638 (defvar org-mode-hook nil
3639 "Mode hook for Org-mode, run after the mode was turned on.")
3640 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3641 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3642 (defvar org-table-buffer-is-an nil)
3643 (defconst org-outline-regexp "\\*+ ")
3645 ;;;###autoload
3646 (define-derived-mode org-mode outline-mode "Org"
3647 "Outline-based notes management and organizer, alias
3648 \"Carsten's outline-mode for keeping track of everything.\"
3650 Org-mode develops organizational tasks around a NOTES file which
3651 contains information about projects as plain text. Org-mode is
3652 implemented on top of outline-mode, which is ideal to keep the content
3653 of large files well structured. It supports ToDo items, deadlines and
3654 time stamps, which magically appear in the diary listing of the Emacs
3655 calendar. Tables are easily created with a built-in table editor.
3656 Plain text URL-like links connect to websites, emails (VM), Usenet
3657 messages (Gnus), BBDB entries, and any files related to the project.
3658 For printing and sharing of notes, an Org-mode file (or a part of it)
3659 can be exported as a structured ASCII or HTML file.
3661 The following commands are available:
3663 \\{org-mode-map}"
3665 ;; Get rid of Outline menus, they are not needed
3666 ;; Need to do this here because define-derived-mode sets up
3667 ;; the keymap so late. Still, it is a waste to call this each time
3668 ;; we switch another buffer into org-mode.
3669 (if (featurep 'xemacs)
3670 (when (boundp 'outline-mode-menu-heading)
3671 ;; Assume this is Greg's port, it used easymenu
3672 (easy-menu-remove outline-mode-menu-heading)
3673 (easy-menu-remove outline-mode-menu-show)
3674 (easy-menu-remove outline-mode-menu-hide))
3675 (define-key org-mode-map [menu-bar headings] 'undefined)
3676 (define-key org-mode-map [menu-bar hide] 'undefined)
3677 (define-key org-mode-map [menu-bar show] 'undefined))
3679 (org-load-modules-maybe)
3680 (easy-menu-add org-org-menu)
3681 (easy-menu-add org-tbl-menu)
3682 (org-install-agenda-files-menu)
3683 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3684 (org-add-to-invisibility-spec '(org-cwidth))
3685 (when (featurep 'xemacs)
3686 (org-set-local 'line-move-ignore-invisible t))
3687 (org-set-local 'outline-regexp org-outline-regexp)
3688 (org-set-local 'outline-level 'org-outline-level)
3689 (when (and org-ellipsis
3690 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3691 (fboundp 'make-glyph-code))
3692 (unless org-display-table
3693 (setq org-display-table (make-display-table)))
3694 (set-display-table-slot
3695 org-display-table 4
3696 (vconcat (mapcar
3697 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3698 org-ellipsis)))
3699 (if (stringp org-ellipsis) org-ellipsis "..."))))
3700 (setq buffer-display-table org-display-table))
3701 (org-set-regexps-and-options)
3702 (when (and org-tag-faces (not org-tags-special-faces-re))
3703 ;; tag faces set outside customize.... force initialization.
3704 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3705 ;; Calc embedded
3706 (org-set-local 'calc-embedded-open-mode "# ")
3707 (modify-syntax-entry ?# "<")
3708 (modify-syntax-entry ?@ "w")
3709 (if org-startup-truncated (setq truncate-lines t))
3710 (org-set-local 'font-lock-unfontify-region-function
3711 'org-unfontify-region)
3712 ;; Activate before-change-function
3713 (org-set-local 'org-table-may-need-update t)
3714 (org-add-hook 'before-change-functions 'org-before-change-function nil
3715 'local)
3716 ;; Check for running clock before killing a buffer
3717 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3718 ;; Paragraphs and auto-filling
3719 (org-set-autofill-regexps)
3720 (setq indent-line-function 'org-indent-line-function)
3721 (org-update-radio-target-regexp)
3722 ;; Make sure dependence stuff works reliably, even for users who set it
3723 ;; too late :-(
3724 (if org-enforce-todo-dependencies
3725 (add-hook 'org-blocker-hook
3726 'org-block-todo-from-children-or-siblings)
3727 (remove-hook 'org-blocker-hook
3728 'org-block-todo-from-children-or-siblings))
3729 (if org-enforce-todo-checkbox-dependencies
3730 (add-hook 'org-blocker-hook
3731 'org-block-todo-from-checkboxes)
3732 (remove-hook 'org-blocker-hook
3733 'org-block-todo-from-checkboxes))
3735 ;; Comment characters
3736 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3737 (org-set-local 'comment-padding " ")
3739 ;; Align options lines
3740 (org-set-local
3741 'align-mode-rules-list
3742 '((org-in-buffer-settings
3743 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3744 (modes . '(org-mode)))))
3746 ;; Imenu
3747 (org-set-local 'imenu-create-index-function
3748 'org-imenu-get-tree)
3750 ;; Make isearch reveal context
3751 (if (or (featurep 'xemacs)
3752 (not (boundp 'outline-isearch-open-invisible-function)))
3753 ;; Emacs 21 and XEmacs make use of the hook
3754 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3755 ;; Emacs 22 deals with this through a special variable
3756 (org-set-local 'outline-isearch-open-invisible-function
3757 (lambda (&rest ignore) (org-show-context 'isearch))))
3759 ;; If empty file that did not turn on org-mode automatically, make it to.
3760 (if (and org-insert-mode-line-in-empty-file
3761 (interactive-p)
3762 (= (point-min) (point-max)))
3763 (insert "# -*- mode: org -*-\n\n"))
3765 (unless org-inhibit-startup
3766 (when org-startup-align-all-tables
3767 (let ((bmp (buffer-modified-p)))
3768 (org-table-map-tables 'org-table-align)
3769 (set-buffer-modified-p bmp)))
3770 (org-set-startup-visibility)))
3772 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3774 (defun org-current-time ()
3775 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3776 (if (> (car org-time-stamp-rounding-minutes) 1)
3777 (let ((r (car org-time-stamp-rounding-minutes))
3778 (time (decode-time)))
3779 (apply 'encode-time
3780 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3781 (nthcdr 2 time))))
3782 (current-time)))
3784 ;;;; Font-Lock stuff, including the activators
3786 (defvar org-mouse-map (make-sparse-keymap))
3787 (org-defkey org-mouse-map
3788 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3789 (org-defkey org-mouse-map
3790 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3791 (when org-mouse-1-follows-link
3792 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3793 (when org-tab-follows-link
3794 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3795 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3797 (require 'font-lock)
3799 (defconst org-non-link-chars "]\t\n\r<>")
3800 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3801 "shell" "elisp"))
3802 (defvar org-link-types-re nil
3803 "Matches a link that has a url-like prefix like \"http:\"")
3804 (defvar org-link-re-with-space nil
3805 "Matches a link with spaces, optional angular brackets around it.")
3806 (defvar org-link-re-with-space2 nil
3807 "Matches a link with spaces, optional angular brackets around it.")
3808 (defvar org-link-re-with-space3 nil
3809 "Matches a link with spaces, only for internal part in bracket links.")
3810 (defvar org-angle-link-re nil
3811 "Matches link with angular brackets, spaces are allowed.")
3812 (defvar org-plain-link-re nil
3813 "Matches plain link, without spaces.")
3814 (defvar org-bracket-link-regexp nil
3815 "Matches a link in double brackets.")
3816 (defvar org-bracket-link-analytic-regexp nil
3817 "Regular expression used to analyze links.
3818 Here is what the match groups contain after a match:
3819 1: http:
3820 2: http
3821 3: path
3822 4: [desc]
3823 5: desc")
3824 (defvar org-bracket-link-analytic-regexp++ nil
3825 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3826 (defvar org-any-link-re nil
3827 "Regular expression matching any link.")
3829 (defun org-make-link-regexps ()
3830 "Update the link regular expressions.
3831 This should be called after the variable `org-link-types' has changed."
3832 (setq org-link-types-re
3833 (concat
3834 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3835 org-link-re-with-space
3836 (concat
3837 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3838 "\\([^" org-non-link-chars " ]"
3839 "[^" org-non-link-chars "]*"
3840 "[^" org-non-link-chars " ]\\)>?")
3841 org-link-re-with-space2
3842 (concat
3843 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3844 "\\([^" org-non-link-chars " ]"
3845 "[^\t\n\r]*"
3846 "[^" org-non-link-chars " ]\\)>?")
3847 org-link-re-with-space3
3848 (concat
3849 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3850 "\\([^" org-non-link-chars " ]"
3851 "[^\t\n\r]*\\)")
3852 org-angle-link-re
3853 (concat
3854 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3855 "\\([^" org-non-link-chars " ]"
3856 "[^" org-non-link-chars "]*"
3857 "\\)>")
3858 org-plain-link-re
3859 (concat
3860 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3861 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3862 org-bracket-link-regexp
3863 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3864 org-bracket-link-analytic-regexp
3865 (concat
3866 "\\[\\["
3867 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3868 "\\([^]]+\\)"
3869 "\\]"
3870 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3871 "\\]")
3872 org-bracket-link-analytic-regexp++
3873 (concat
3874 "\\[\\["
3875 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3876 "\\([^]]+\\)"
3877 "\\]"
3878 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3879 "\\]")
3880 org-any-link-re
3881 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3882 org-angle-link-re "\\)\\|\\("
3883 org-plain-link-re "\\)")))
3885 (org-make-link-regexps)
3887 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3888 "Regular expression for fast time stamp matching.")
3889 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3890 "Regular expression for fast time stamp matching.")
3891 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3892 "Regular expression matching time strings for analysis.
3893 This one does not require the space after the date, so it can be used
3894 on a string that terminates immediately after the date.")
3895 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3896 "Regular expression matching time strings for analysis.")
3897 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3898 "Regular expression matching time stamps, with groups.")
3899 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3900 "Regular expression matching time stamps (also [..]), with groups.")
3901 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3902 "Regular expression matching a time stamp range.")
3903 (defconst org-tr-regexp-both
3904 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3905 "Regular expression matching a time stamp range.")
3906 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3907 org-ts-regexp "\\)?")
3908 "Regular expression matching a time stamp or time stamp range.")
3909 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3910 org-ts-regexp-both "\\)?")
3911 "Regular expression matching a time stamp or time stamp range.
3912 The time stamps may be either active or inactive.")
3914 (defvar org-emph-face nil)
3916 (defun org-do-emphasis-faces (limit)
3917 "Run through the buffer and add overlays to links."
3918 (let (rtn)
3919 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3920 (if (not (= (char-after (match-beginning 3))
3921 (char-after (match-beginning 4))))
3922 (progn
3923 (setq rtn t)
3924 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3925 'face
3926 (nth 1 (assoc (match-string 3)
3927 org-emphasis-alist)))
3928 (add-text-properties (match-beginning 2) (match-end 2)
3929 '(font-lock-multiline t))
3930 (when org-hide-emphasis-markers
3931 (add-text-properties (match-end 4) (match-beginning 5)
3932 '(invisible org-link))
3933 (add-text-properties (match-beginning 3) (match-end 3)
3934 '(invisible org-link)))))
3935 (backward-char 1))
3936 rtn))
3938 (defun org-emphasize (&optional char)
3939 "Insert or change an emphasis, i.e. a font like bold or italic.
3940 If there is an active region, change that region to a new emphasis.
3941 If there is no region, just insert the marker characters and position
3942 the cursor between them.
3943 CHAR should be either the marker character, or the first character of the
3944 HTML tag associated with that emphasis. If CHAR is a space, the means
3945 to remove the emphasis of the selected region.
3946 If char is not given (for example in an interactive call) it
3947 will be prompted for."
3948 (interactive)
3949 (let ((eal org-emphasis-alist) e det
3950 (erc org-emphasis-regexp-components)
3951 (prompt "")
3952 (string "") beg end move tag c s)
3953 (if (org-region-active-p)
3954 (setq beg (region-beginning) end (region-end)
3955 string (buffer-substring beg end))
3956 (setq move t))
3958 (while (setq e (pop eal))
3959 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3960 c (aref tag 0))
3961 (push (cons c (string-to-char (car e))) det)
3962 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3963 (substring tag 1)))))
3964 (setq det (nreverse det))
3965 (unless char
3966 (message "%s" (concat "Emphasis marker or tag:" prompt))
3967 (setq char (read-char-exclusive)))
3968 (setq char (or (cdr (assoc char det)) char))
3969 (if (equal char ?\ )
3970 (setq s "" move nil)
3971 (unless (assoc (char-to-string char) org-emphasis-alist)
3972 (error "No such emphasis marker: \"%c\"" char))
3973 (setq s (char-to-string char)))
3974 (while (and (> (length string) 1)
3975 (equal (substring string 0 1) (substring string -1))
3976 (assoc (substring string 0 1) org-emphasis-alist))
3977 (setq string (substring string 1 -1)))
3978 (setq string (concat s string s))
3979 (if beg (delete-region beg end))
3980 (unless (or (bolp)
3981 (string-match (concat "[" (nth 0 erc) "\n]")
3982 (char-to-string (char-before (point)))))
3983 (insert " "))
3984 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3985 (char-to-string (char-after (point))))
3986 (insert " ") (backward-char 1))
3987 (insert string)
3988 (and move (backward-char 1))))
3990 (defconst org-nonsticky-props
3991 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3994 (defun org-activate-plain-links (limit)
3995 "Run through the buffer and add overlays to links."
3996 (catch 'exit
3997 (let (f)
3998 (while (re-search-forward org-plain-link-re limit t)
3999 (setq f (get-text-property (match-beginning 0) 'face))
4000 (if (or (eq f 'org-tag)
4001 (and (listp f) (memq 'org-tag f)))
4003 (add-text-properties (match-beginning 0) (match-end 0)
4004 (list 'mouse-face 'highlight
4005 'rear-nonsticky org-nonsticky-props
4006 'keymap org-mouse-map
4008 (throw 'exit t))))))
4010 (defun org-activate-code (limit)
4011 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4012 (progn
4013 (remove-text-properties (match-beginning 0) (match-end 0)
4014 '(display t invisible t intangible t))
4015 t)))
4017 (defun org-activate-angle-links (limit)
4018 "Run through the buffer and add overlays to links."
4019 (if (re-search-forward org-angle-link-re limit t)
4020 (progn
4021 (add-text-properties (match-beginning 0) (match-end 0)
4022 (list 'mouse-face 'highlight
4023 'rear-nonsticky org-nonsticky-props
4024 'keymap org-mouse-map
4026 t)))
4028 (defun org-activate-footnote-links (limit)
4029 "Run through the buffer and add overlays to links."
4030 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4031 limit t)
4032 (progn
4033 (add-text-properties (match-beginning 2) (match-end 2)
4034 (list 'mouse-face 'highlight
4035 'rear-nonsticky org-nonsticky-props
4036 'keymap org-mouse-map
4037 'help-echo
4038 (if (= (point-at-bol) (match-beginning 2))
4039 "Footnote definition"
4040 "Footnote reference")
4042 t)))
4044 (defun org-activate-bracket-links (limit)
4045 "Run through the buffer and add overlays to bracketed links."
4046 (if (re-search-forward org-bracket-link-regexp limit t)
4047 (let* ((help (concat "LINK: "
4048 (org-match-string-no-properties 1)))
4049 ;; FIXME: above we should remove the escapes.
4050 ;; but that requires another match, protecting match data,
4051 ;; a lot of overhead for font-lock.
4052 (ip (org-maybe-intangible
4053 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4054 'keymap org-mouse-map 'mouse-face 'highlight
4055 'font-lock-multiline t 'help-echo help)))
4056 (vp (list 'rear-nonsticky org-nonsticky-props
4057 'keymap org-mouse-map 'mouse-face 'highlight
4058 ' font-lock-multiline t 'help-echo help)))
4059 ;; We need to remove the invisible property here. Table narrowing
4060 ;; may have made some of this invisible.
4061 (remove-text-properties (match-beginning 0) (match-end 0)
4062 '(invisible nil))
4063 (if (match-end 3)
4064 (progn
4065 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4066 (add-text-properties (match-beginning 3) (match-end 3) vp)
4067 (add-text-properties (match-end 3) (match-end 0) ip))
4068 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4069 (add-text-properties (match-beginning 1) (match-end 1) vp)
4070 (add-text-properties (match-end 1) (match-end 0) ip))
4071 t)))
4073 (defun org-activate-dates (limit)
4074 "Run through the buffer and add overlays to dates."
4075 (if (re-search-forward org-tsr-regexp-both limit t)
4076 (progn
4077 (add-text-properties (match-beginning 0) (match-end 0)
4078 (list 'mouse-face 'highlight
4079 'rear-nonsticky org-nonsticky-props
4080 'keymap org-mouse-map))
4081 (when org-display-custom-times
4082 (if (match-end 3)
4083 (org-display-custom-time (match-beginning 3) (match-end 3)))
4084 (org-display-custom-time (match-beginning 1) (match-end 1)))
4085 t)))
4087 (defvar org-target-link-regexp nil
4088 "Regular expression matching radio targets in plain text.")
4089 (make-variable-buffer-local 'org-target-link-regexp)
4090 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4091 "Regular expression matching a link target.")
4092 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4093 "Regular expression matching a radio target.")
4094 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4095 "Regular expression matching any target.")
4097 (defun org-activate-target-links (limit)
4098 "Run through the buffer and add overlays to target matches."
4099 (when org-target-link-regexp
4100 (let ((case-fold-search t))
4101 (if (re-search-forward org-target-link-regexp limit t)
4102 (progn
4103 (add-text-properties (match-beginning 0) (match-end 0)
4104 (list 'mouse-face 'highlight
4105 'rear-nonsticky org-nonsticky-props
4106 'keymap org-mouse-map
4107 'help-echo "Radio target link"
4108 'org-linked-text t))
4109 t)))))
4111 (defun org-update-radio-target-regexp ()
4112 "Find all radio targets in this file and update the regular expression."
4113 (interactive)
4114 (when (memq 'radio org-activate-links)
4115 (setq org-target-link-regexp
4116 (org-make-target-link-regexp (org-all-targets 'radio)))
4117 (org-restart-font-lock)))
4119 (defun org-hide-wide-columns (limit)
4120 (let (s e)
4121 (setq s (text-property-any (point) (or limit (point-max))
4122 'org-cwidth t))
4123 (when s
4124 (setq e (next-single-property-change s 'org-cwidth))
4125 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4126 (goto-char e)
4127 t)))
4129 (defvar org-latex-and-specials-regexp nil
4130 "Regular expression for highlighting export special stuff.")
4131 (defvar org-match-substring-regexp)
4132 (defvar org-match-substring-with-braces-regexp)
4133 (defvar org-export-html-special-string-regexps)
4135 (defun org-compute-latex-and-specials-regexp ()
4136 "Compute regular expression for stuff treated specially by exporters."
4137 (if (not org-highlight-latex-fragments-and-specials)
4138 (org-set-local 'org-latex-and-specials-regexp nil)
4139 (require 'org-exp)
4140 (let*
4141 ((matchers (plist-get org-format-latex-options :matchers))
4142 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4143 org-latex-regexps)))
4144 (options (org-combine-plists (org-default-export-plist)
4145 (org-infile-export-plist)))
4146 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4147 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4148 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4149 (org-export-html-expand (plist-get options :expand-quoted-html))
4150 (org-export-with-special-strings (plist-get options :special-strings))
4151 (re-sub
4152 (cond
4153 ((equal org-export-with-sub-superscripts '{})
4154 (list org-match-substring-with-braces-regexp))
4155 (org-export-with-sub-superscripts
4156 (list org-match-substring-regexp))
4157 (t nil)))
4158 (re-latex
4159 (if org-export-with-LaTeX-fragments
4160 (mapcar (lambda (x) (nth 1 x)) latexs)))
4161 (re-macros
4162 (if org-export-with-TeX-macros
4163 (list (concat "\\\\"
4164 (regexp-opt
4165 (append (mapcar 'car org-html-entities)
4166 (if (boundp 'org-latex-entities)
4167 org-latex-entities nil))
4168 'words))) ; FIXME
4170 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4171 (re-special (if org-export-with-special-strings
4172 (mapcar (lambda (x) (car x))
4173 org-export-html-special-string-regexps)))
4174 (re-rest
4175 (delq nil
4176 (list
4177 (if org-export-html-expand "@<[^>\n]+>")
4178 ))))
4179 (org-set-local
4180 'org-latex-and-specials-regexp
4181 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4182 re-rest) "\\|")))))
4184 (defun org-do-latex-and-special-faces (limit)
4185 "Run through the buffer and add overlays to links."
4186 (when org-latex-and-specials-regexp
4187 (let (rtn d)
4188 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4189 limit t))
4190 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4191 'face))
4192 '(org-code org-verbatim underline)))
4193 (progn
4194 (setq rtn t
4195 d (cond ((member (char-after (1+ (match-beginning 0)))
4196 '(?_ ?^)) 1)
4197 (t 0)))
4198 (font-lock-prepend-text-property
4199 (+ d (match-beginning 0)) (match-end 0)
4200 'face 'org-latex-and-export-specials)
4201 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4202 '(font-lock-multiline t)))))
4203 rtn)))
4205 (defun org-restart-font-lock ()
4206 "Restart font-lock-mode, to force refontification."
4207 (when (and (boundp 'font-lock-mode) font-lock-mode)
4208 (font-lock-mode -1)
4209 (font-lock-mode 1)))
4211 (defun org-all-targets (&optional radio)
4212 "Return a list of all targets in this file.
4213 With optional argument RADIO, only find radio targets."
4214 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4215 rtn)
4216 (save-excursion
4217 (goto-char (point-min))
4218 (while (re-search-forward re nil t)
4219 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4220 rtn)))
4222 (defun org-make-target-link-regexp (targets)
4223 "Make regular expression matching all strings in TARGETS.
4224 The regular expression finds the targets also if there is a line break
4225 between words."
4226 (and targets
4227 (concat
4228 "\\<\\("
4229 (mapconcat
4230 (lambda (x)
4231 (while (string-match " +" x)
4232 (setq x (replace-match "\\s-+" t t x)))
4234 targets
4235 "\\|")
4236 "\\)\\>")))
4238 (defun org-activate-tags (limit)
4239 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4240 (progn
4241 (add-text-properties (match-beginning 1) (match-end 1)
4242 (list 'mouse-face 'highlight
4243 'rear-nonsticky org-nonsticky-props
4244 'keymap org-mouse-map))
4245 t)))
4247 (defun org-outline-level ()
4248 (save-excursion
4249 (looking-at outline-regexp)
4250 (if (match-beginning 1)
4251 (+ (org-get-string-indentation (match-string 1)) 1000)
4252 (1- (- (match-end 0) (match-beginning 0))))))
4254 (defvar org-font-lock-keywords nil)
4256 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4257 "Regular expression matching a property line.")
4259 (defvar org-font-lock-hook nil
4260 "Functions to be called for special font lock stuff.")
4262 (defun org-font-lock-hook (limit)
4263 (run-hook-with-args 'org-font-lock-hook limit))
4265 (defun org-set-font-lock-defaults ()
4266 (let* ((em org-fontify-emphasized-text)
4267 (lk org-activate-links)
4268 (org-font-lock-extra-keywords
4269 (list
4270 ;; Call the hook
4271 '(org-font-lock-hook)
4272 ;; Headlines
4273 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4274 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4275 ;; Table lines
4276 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4277 (1 'org-table t))
4278 ;; Table internals
4279 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4280 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4281 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4282 ;; Drawers
4283 (list org-drawer-regexp '(0 'org-special-keyword t))
4284 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4285 ;; Properties
4286 (list org-property-re
4287 '(1 'org-special-keyword t)
4288 '(3 'org-property-value t))
4289 (if org-format-transports-properties-p
4290 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4291 ;; Links
4292 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4293 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4294 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4295 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4296 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4297 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4298 (if (memq 'footnote lk) '(org-activate-footnote-links
4299 (2 'org-footnote t)))
4300 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4301 '(org-hide-wide-columns (0 nil append))
4302 ;; TODO lines
4303 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4304 '(1 (org-get-todo-face 1) t))
4305 ;; DONE
4306 (if org-fontify-done-headline
4307 (list (concat "^[*]+ +\\<\\("
4308 (mapconcat 'regexp-quote org-done-keywords "\\|")
4309 "\\)\\(.*\\)")
4310 '(2 'org-headline-done t))
4311 nil)
4312 ;; Priorities
4313 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4314 ;; Tags
4315 '(org-font-lock-add-tag-faces)
4316 ;; Special keywords
4317 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4318 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4319 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4320 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4321 ;; Emphasis
4322 (if em
4323 (if (featurep 'xemacs)
4324 '(org-do-emphasis-faces (0 nil append))
4325 '(org-do-emphasis-faces)))
4326 ;; Checkboxes
4327 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4328 2 'bold prepend)
4329 (if org-provide-checkbox-statistics
4330 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4331 (0 (org-get-checkbox-statistics-face) t)))
4332 ;; Description list items
4333 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4334 2 'bold prepend)
4335 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4336 '(1 'org-archived prepend))
4337 ;; Specials
4338 '(org-do-latex-and-special-faces)
4339 ;; Code
4340 '(org-activate-code (1 'org-code t))
4341 ;; COMMENT
4342 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4343 "\\|" org-quote-string "\\)\\>")
4344 '(1 'org-special-keyword t))
4345 '("^#.*" (0 'font-lock-comment-face t))
4347 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4348 ;; Now set the full font-lock-keywords
4349 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4350 (org-set-local 'font-lock-defaults
4351 '(org-font-lock-keywords t nil nil backward-paragraph))
4352 (kill-local-variable 'font-lock-keywords) nil))
4354 (defvar org-m nil)
4355 (defvar org-l nil)
4356 (defvar org-f nil)
4357 (defun org-get-level-face (n)
4358 "Get the right face for match N in font-lock matching of headlines."
4359 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4360 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4361 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4362 (cond
4363 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4364 ((eq n 2) org-f)
4365 (t (if org-level-color-stars-only nil org-f))))
4367 (defun org-get-todo-face (kwd)
4368 "Get the right face for a TODO keyword KWD.
4369 If KWD is a number, get the corresponding match group."
4370 (if (numberp kwd) (setq kwd (match-string kwd)))
4371 (or (cdr (assoc kwd org-todo-keyword-faces))
4372 (and (member kwd org-done-keywords) 'org-done)
4373 'org-todo))
4375 (defun org-font-lock-add-tag-faces (limit)
4376 "Add the special tag faces."
4377 (when (and org-tag-faces org-tags-special-faces-re)
4378 (while (re-search-forward org-tags-special-faces-re limit t)
4379 (add-text-properties (match-beginning 1) (match-end 1)
4380 (list 'face (org-get-tag-face 1)
4381 'font-lock-fontified t))
4382 (backward-char 1))))
4384 (defun org-get-tag-face (kwd)
4385 "Get the right face for a TODO keyword KWD.
4386 If KWD is a number, get the corresponding match group."
4387 (if (numberp kwd) (setq kwd (match-string kwd)))
4388 (or (cdr (assoc kwd org-tag-faces))
4389 'org-tag))
4391 (defun org-unfontify-region (beg end &optional maybe_loudly)
4392 "Remove fontification and activation overlays from links."
4393 (font-lock-default-unfontify-region beg end)
4394 (let* ((buffer-undo-list t)
4395 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4396 (inhibit-modification-hooks t)
4397 deactivate-mark buffer-file-name buffer-file-truename)
4398 (remove-text-properties beg end
4399 '(mouse-face t keymap t org-linked-text t
4400 invisible t intangible t))))
4402 ;;;; Visibility cycling, including org-goto and indirect buffer
4404 ;;; Cycling
4406 (defvar org-cycle-global-status nil)
4407 (make-variable-buffer-local 'org-cycle-global-status)
4408 (defvar org-cycle-subtree-status nil)
4409 (make-variable-buffer-local 'org-cycle-subtree-status)
4411 ;;;###autoload
4412 (defun org-cycle (&optional arg)
4413 "Visibility cycling for Org-mode.
4415 - When this function is called with a prefix argument, rotate the entire
4416 buffer through 3 states (global cycling)
4417 1. OVERVIEW: Show only top-level headlines.
4418 2. CONTENTS: Show all headlines of all levels, but no body text.
4419 3. SHOW ALL: Show everything.
4420 When called with two C-u C-u prefixes, switch to the startup visibility,
4421 determined by the variable `org-startup-folded', and by any VISIBILITY
4422 properties in the buffer.
4423 When called with three C-u C-u C-u prefixed, show the entire buffer,
4424 including drawers.
4426 - When point is at the beginning of a headline, rotate the subtree started
4427 by this line through 3 different states (local cycling)
4428 1. FOLDED: Only the main headline is shown.
4429 2. CHILDREN: The main headline and the direct children are shown.
4430 From this state, you can move to one of the children
4431 and zoom in further.
4432 3. SUBTREE: Show the entire subtree, including body text.
4434 - When there is a numeric prefix, go up to a heading with level ARG, do
4435 a `show-subtree' and return to the previous cursor position. If ARG
4436 is negative, go up that many levels.
4438 - When point is not at the beginning of a headline, execute the global
4439 binding for TAB, which is re-indenting the line. See the option
4440 `org-cycle-emulate-tab' for details.
4442 - Special case: if point is at the beginning of the buffer and there is
4443 no headline in line 1, this function will act as if called with prefix arg.
4444 But only if also the variable `org-cycle-global-at-bob' is t."
4445 (interactive "P")
4446 (org-load-modules-maybe)
4447 (let* ((outline-regexp
4448 (if (and (org-mode-p) org-cycle-include-plain-lists)
4449 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4450 outline-regexp))
4451 (bob-special (and org-cycle-global-at-bob (bobp)
4452 (not (looking-at outline-regexp))))
4453 (org-cycle-hook
4454 (if bob-special
4455 (delq 'org-optimize-window-after-visibility-change
4456 (copy-sequence org-cycle-hook))
4457 org-cycle-hook))
4458 (pos (point)))
4460 (if (or bob-special (equal arg '(4)))
4461 ;; special case: use global cycling
4462 (setq arg t))
4464 (cond
4466 ((equal arg '(16))
4467 (org-set-startup-visibility)
4468 (message "Startup visibility, plus VISIBILITY properties"))
4470 ((equal arg '(64))
4471 (show-all)
4472 (message "Entire buffer visible, including drawers"))
4474 ((org-at-table-p 'any)
4475 ;; Enter the table or move to the next field in the table
4476 (or (org-table-recognize-table.el)
4477 (progn
4478 (if arg (org-table-edit-field t)
4479 (org-table-justify-field-maybe)
4480 (call-interactively 'org-table-next-field)))))
4482 ((eq arg t) ;; Global cycling
4484 (cond
4485 ((and (eq last-command this-command)
4486 (eq org-cycle-global-status 'overview))
4487 ;; We just created the overview - now do table of contents
4488 ;; This can be slow in very large buffers, so indicate action
4489 (message "CONTENTS...")
4490 (org-content)
4491 (message "CONTENTS...done")
4492 (setq org-cycle-global-status 'contents)
4493 (run-hook-with-args 'org-cycle-hook 'contents))
4495 ((and (eq last-command this-command)
4496 (eq org-cycle-global-status 'contents))
4497 ;; We just showed the table of contents - now show everything
4498 (show-all)
4499 (message "SHOW ALL")
4500 (setq org-cycle-global-status 'all)
4501 (run-hook-with-args 'org-cycle-hook 'all))
4504 ;; Default action: go to overview
4505 (org-overview)
4506 (message "OVERVIEW")
4507 (setq org-cycle-global-status 'overview)
4508 (run-hook-with-args 'org-cycle-hook 'overview))))
4510 ((and org-drawers org-drawer-regexp
4511 (save-excursion
4512 (beginning-of-line 1)
4513 (looking-at org-drawer-regexp)))
4514 ;; Toggle block visibility
4515 (org-flag-drawer
4516 (not (get-char-property (match-end 0) 'invisible))))
4518 ((integerp arg)
4519 ;; Show-subtree, ARG levels up from here.
4520 (save-excursion
4521 (org-back-to-heading)
4522 (outline-up-heading (if (< arg 0) (- arg)
4523 (- (funcall outline-level) arg)))
4524 (org-show-subtree)))
4526 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4527 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4528 ;; At a heading: rotate between three different views
4529 (org-back-to-heading)
4530 (let ((goal-column 0) eoh eol eos)
4531 ;; First, some boundaries
4532 (save-excursion
4533 (org-back-to-heading)
4534 (save-excursion
4535 (beginning-of-line 2)
4536 (while (and (not (eobp)) ;; this is like `next-line'
4537 (get-char-property (1- (point)) 'invisible))
4538 (beginning-of-line 2)) (setq eol (point)))
4539 (outline-end-of-heading) (setq eoh (point))
4540 (org-end-of-subtree t)
4541 (unless (eobp)
4542 (skip-chars-forward " \t\n")
4543 (beginning-of-line 1) ; in case this is an item
4545 (setq eos (1- (point))))
4546 ;; Find out what to do next and set `this-command'
4547 (cond
4548 ((= eos eoh)
4549 ;; Nothing is hidden behind this heading
4550 (message "EMPTY ENTRY")
4551 (setq org-cycle-subtree-status nil)
4552 (save-excursion
4553 (goto-char eos)
4554 (outline-next-heading)
4555 (if (org-invisible-p) (org-flag-heading nil))))
4556 ((or (>= eol eos)
4557 (not (string-match "\\S-" (buffer-substring eol eos))))
4558 ;; Entire subtree is hidden in one line: open it
4559 (org-show-entry)
4560 (show-children)
4561 (message "CHILDREN")
4562 (save-excursion
4563 (goto-char eos)
4564 (outline-next-heading)
4565 (if (org-invisible-p) (org-flag-heading nil)))
4566 (setq org-cycle-subtree-status 'children)
4567 (run-hook-with-args 'org-cycle-hook 'children))
4568 ((and (eq last-command this-command)
4569 (eq org-cycle-subtree-status 'children))
4570 ;; We just showed the children, now show everything.
4571 (org-show-subtree)
4572 (message "SUBTREE")
4573 (setq org-cycle-subtree-status 'subtree)
4574 (run-hook-with-args 'org-cycle-hook 'subtree))
4576 ;; Default action: hide the subtree.
4577 (hide-subtree)
4578 (message "FOLDED")
4579 (setq org-cycle-subtree-status 'folded)
4580 (run-hook-with-args 'org-cycle-hook 'folded)))))
4582 ;; TAB emulation and template completion
4583 (buffer-read-only (org-back-to-heading))
4585 ((org-try-structure-completion))
4587 ((org-try-cdlatex-tab))
4589 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4590 (or (not (bolp))
4591 (not (looking-at outline-regexp))))
4592 (call-interactively (global-key-binding "\t")))
4594 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4595 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4596 (or (and (eq org-cycle-emulate-tab 'white)
4597 (= (match-end 0) (point-at-eol)))
4598 (and (eq org-cycle-emulate-tab 'whitestart)
4599 (>= (match-end 0) pos))))
4601 (eq org-cycle-emulate-tab t))
4602 (call-interactively (global-key-binding "\t")))
4604 (t (save-excursion
4605 (org-back-to-heading)
4606 (org-cycle))))))
4608 ;;;###autoload
4609 (defun org-global-cycle (&optional arg)
4610 "Cycle the global visibility. For details see `org-cycle'.
4611 With C-u prefix arg, switch to startup visibility.
4612 With a numeric prefix, show all headlines up to that level."
4613 (interactive "P")
4614 (let ((org-cycle-include-plain-lists
4615 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4616 (cond
4617 ((integerp arg)
4618 (show-all)
4619 (hide-sublevels arg)
4620 (setq org-cycle-global-status 'contents))
4621 ((equal arg '(4))
4622 (org-set-startup-visibility)
4623 (message "Startup visibility, plus VISIBILITY properties."))
4625 (org-cycle '(4))))))
4627 (defun org-set-startup-visibility ()
4628 "Set the visibility required by startup options and properties."
4629 (cond
4630 ((eq org-startup-folded t)
4631 (org-cycle '(4)))
4632 ((eq org-startup-folded 'content)
4633 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4634 (org-cycle '(4)) (org-cycle '(4)))))
4635 (org-set-visibility-according-to-property 'no-cleanup)
4636 (org-cycle-hide-archived-subtrees 'all)
4637 (org-cycle-hide-drawers 'all)
4638 (org-cycle-show-empty-lines 'all))
4640 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4641 "Switch subtree visibilities according to :VISIBILITY: property."
4642 (interactive)
4643 (let (org-show-entry-below state)
4644 (save-excursion
4645 (goto-char (point-min))
4646 (while (re-search-forward
4647 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4648 nil t)
4649 (setq state (match-string 1))
4650 (save-excursion
4651 (org-back-to-heading t)
4652 (hide-subtree)
4653 (org-reveal)
4654 (cond
4655 ((equal state '("fold" "folded"))
4656 (hide-subtree))
4657 ((equal state "children")
4658 (org-show-hidden-entry)
4659 (show-children))
4660 ((equal state "content")
4661 (save-excursion
4662 (save-restriction
4663 (org-narrow-to-subtree)
4664 (org-content))))
4665 ((member state '("all" "showall"))
4666 (show-subtree)))))
4667 (unless no-cleanup
4668 (org-cycle-hide-archived-subtrees 'all)
4669 (org-cycle-hide-drawers 'all)
4670 (org-cycle-show-empty-lines 'all)))))
4672 (defun org-overview ()
4673 "Switch to overview mode, showing only top-level headlines.
4674 Really, this shows all headlines with level equal or greater than the level
4675 of the first headline in the buffer. This is important, because if the
4676 first headline is not level one, then (hide-sublevels 1) gives confusing
4677 results."
4678 (interactive)
4679 (let ((level (save-excursion
4680 (goto-char (point-min))
4681 (if (re-search-forward (concat "^" outline-regexp) nil t)
4682 (progn
4683 (goto-char (match-beginning 0))
4684 (funcall outline-level))))))
4685 (and level (hide-sublevels level))))
4687 (defun org-content (&optional arg)
4688 "Show all headlines in the buffer, like a table of contents.
4689 With numerical argument N, show content up to level N."
4690 (interactive "P")
4691 (save-excursion
4692 ;; Visit all headings and show their offspring
4693 (and (integerp arg) (org-overview))
4694 (goto-char (point-max))
4695 (catch 'exit
4696 (while (and (progn (condition-case nil
4697 (outline-previous-visible-heading 1)
4698 (error (goto-char (point-min))))
4700 (looking-at outline-regexp))
4701 (if (integerp arg)
4702 (show-children (1- arg))
4703 (show-branches))
4704 (if (bobp) (throw 'exit nil))))))
4707 (defun org-optimize-window-after-visibility-change (state)
4708 "Adjust the window after a change in outline visibility.
4709 This function is the default value of the hook `org-cycle-hook'."
4710 (when (get-buffer-window (current-buffer))
4711 (cond
4712 ((eq state 'content) nil)
4713 ((eq state 'all) nil)
4714 ((eq state 'folded) nil)
4715 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4716 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4718 (defun org-compact-display-after-subtree-move ()
4719 "Show a compacter version of the tree of the entry's parent."
4720 (save-excursion
4721 (if (org-up-heading-safe)
4722 (progn
4723 (hide-subtree)
4724 (show-entry)
4725 (show-children)
4726 (org-cycle-show-empty-lines 'children)
4727 (org-cycle-hide-drawers 'children))
4728 (org-overview))))
4730 (defun org-cycle-show-empty-lines (state)
4731 "Show empty lines above all visible headlines.
4732 The region to be covered depends on STATE when called through
4733 `org-cycle-hook'. Lisp program can use t for STATE to get the
4734 entire buffer covered. Note that an empty line is only shown if there
4735 are at least `org-cycle-separator-lines' empty lines before the headline."
4736 (when (> org-cycle-separator-lines 0)
4737 (save-excursion
4738 (let* ((n org-cycle-separator-lines)
4739 (re (cond
4740 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4741 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4742 (t (let ((ns (number-to-string (- n 2))))
4743 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4744 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4745 beg end)
4746 (cond
4747 ((memq state '(overview contents t))
4748 (setq beg (point-min) end (point-max)))
4749 ((memq state '(children folded))
4750 (setq beg (point) end (progn (org-end-of-subtree t t)
4751 (beginning-of-line 2)
4752 (point)))))
4753 (when beg
4754 (goto-char beg)
4755 (while (re-search-forward re end t)
4756 (if (not (get-char-property (match-end 1) 'invisible))
4757 (outline-flag-region
4758 (match-beginning 1) (match-end 1) nil)))))))
4759 ;; Never hide empty lines at the end of the file.
4760 (save-excursion
4761 (goto-char (point-max))
4762 (outline-previous-heading)
4763 (outline-end-of-heading)
4764 (if (and (looking-at "[ \t\n]+")
4765 (= (match-end 0) (point-max)))
4766 (outline-flag-region (point) (match-end 0) nil))))
4768 (defun org-show-empty-lines-in-parent ()
4769 "Move to the parent and re-show empty lines before visible headlines."
4770 (save-excursion
4771 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4772 (org-cycle-show-empty-lines context))))
4774 (defun org-cycle-hide-drawers (state)
4775 "Re-hide all drawers after a visibility state change."
4776 (when (and (org-mode-p)
4777 (not (memq state '(overview folded))))
4778 (save-excursion
4779 (let* ((globalp (memq state '(contents all)))
4780 (beg (if globalp (point-min) (point)))
4781 (end (if globalp (point-max) (org-end-of-subtree t))))
4782 (goto-char beg)
4783 (while (re-search-forward org-drawer-regexp end t)
4784 (org-flag-drawer t))))))
4786 (defun org-flag-drawer (flag)
4787 (save-excursion
4788 (beginning-of-line 1)
4789 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4790 (let ((b (match-end 0))
4791 (outline-regexp org-outline-regexp))
4792 (if (re-search-forward
4793 "^[ \t]*:END:"
4794 (save-excursion (outline-next-heading) (point)) t)
4795 (outline-flag-region b (point-at-eol) flag)
4796 (error ":END: line missing"))))))
4798 (defun org-subtree-end-visible-p ()
4799 "Is the end of the current subtree visible?"
4800 (pos-visible-in-window-p
4801 (save-excursion (org-end-of-subtree t) (point))))
4803 (defun org-first-headline-recenter (&optional N)
4804 "Move cursor to the first headline and recenter the headline.
4805 Optional argument N means, put the headline into the Nth line of the window."
4806 (goto-char (point-min))
4807 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4808 (beginning-of-line)
4809 (recenter (prefix-numeric-value N))))
4811 ;;; Org-goto
4813 (defvar org-goto-window-configuration nil)
4814 (defvar org-goto-marker nil)
4815 (defvar org-goto-map
4816 (let ((map (make-sparse-keymap)))
4817 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4818 (while (setq cmd (pop cmds))
4819 (substitute-key-definition cmd cmd map global-map)))
4820 (suppress-keymap map)
4821 (org-defkey map "\C-m" 'org-goto-ret)
4822 (org-defkey map [(return)] 'org-goto-ret)
4823 (org-defkey map [(left)] 'org-goto-left)
4824 (org-defkey map [(right)] 'org-goto-right)
4825 (org-defkey map [(control ?g)] 'org-goto-quit)
4826 (org-defkey map "\C-i" 'org-cycle)
4827 (org-defkey map [(tab)] 'org-cycle)
4828 (org-defkey map [(down)] 'outline-next-visible-heading)
4829 (org-defkey map [(up)] 'outline-previous-visible-heading)
4830 (if org-goto-auto-isearch
4831 (if (fboundp 'define-key-after)
4832 (define-key-after map [t] 'org-goto-local-auto-isearch)
4833 nil)
4834 (org-defkey map "q" 'org-goto-quit)
4835 (org-defkey map "n" 'outline-next-visible-heading)
4836 (org-defkey map "p" 'outline-previous-visible-heading)
4837 (org-defkey map "f" 'outline-forward-same-level)
4838 (org-defkey map "b" 'outline-backward-same-level)
4839 (org-defkey map "u" 'outline-up-heading))
4840 (org-defkey map "/" 'org-occur)
4841 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4842 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4843 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4844 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4845 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4846 map))
4848 (defconst org-goto-help
4849 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4850 RET=jump to location [Q]uit and return to previous location
4851 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4853 (defvar org-goto-start-pos) ; dynamically scoped parameter
4855 ;; FIXME: Docstring doe not mention both interfaces
4856 (defun org-goto (&optional alternative-interface)
4857 "Look up a different location in the current file, keeping current visibility.
4859 When you want look-up or go to a different location in a document, the
4860 fastest way is often to fold the entire buffer and then dive into the tree.
4861 This method has the disadvantage, that the previous location will be folded,
4862 which may not be what you want.
4864 This command works around this by showing a copy of the current buffer
4865 in an indirect buffer, in overview mode. You can dive into the tree in
4866 that copy, use org-occur and incremental search to find a location.
4867 When pressing RET or `Q', the command returns to the original buffer in
4868 which the visibility is still unchanged. After RET is will also jump to
4869 the location selected in the indirect buffer and expose the
4870 the headline hierarchy above."
4871 (interactive "P")
4872 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4873 (org-refile-use-outline-path t)
4874 (interface
4875 (if (not alternative-interface)
4876 org-goto-interface
4877 (if (eq org-goto-interface 'outline)
4878 'outline-path-completion
4879 'outline)))
4880 (org-goto-start-pos (point))
4881 (selected-point
4882 (if (eq interface 'outline)
4883 (car (org-get-location (current-buffer) org-goto-help))
4884 (nth 3 (org-refile-get-location "Goto: ")))))
4885 (if selected-point
4886 (progn
4887 (org-mark-ring-push org-goto-start-pos)
4888 (goto-char selected-point)
4889 (if (or (org-invisible-p) (org-invisible-p2))
4890 (org-show-context 'org-goto)))
4891 (message "Quit"))))
4893 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4894 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4895 (defvar org-goto-local-auto-isearch-map) ; defined below
4897 (defun org-get-location (buf help)
4898 "Let the user select a location in the Org-mode buffer BUF.
4899 This function uses a recursive edit. It returns the selected position
4900 or nil."
4901 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4902 (isearch-hide-immediately nil)
4903 (isearch-search-fun-function
4904 (lambda () 'org-goto-local-search-headings))
4905 (org-goto-selected-point org-goto-exit-command))
4906 (save-excursion
4907 (save-window-excursion
4908 (delete-other-windows)
4909 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4910 (switch-to-buffer
4911 (condition-case nil
4912 (make-indirect-buffer (current-buffer) "*org-goto*")
4913 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4914 (with-output-to-temp-buffer "*Help*"
4915 (princ help))
4916 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4917 (setq buffer-read-only nil)
4918 (let ((org-startup-truncated t)
4919 (org-startup-folded nil)
4920 (org-startup-align-all-tables nil))
4921 (org-mode)
4922 (org-overview))
4923 (setq buffer-read-only t)
4924 (if (and (boundp 'org-goto-start-pos)
4925 (integer-or-marker-p org-goto-start-pos))
4926 (let ((org-show-hierarchy-above t)
4927 (org-show-siblings t)
4928 (org-show-following-heading t))
4929 (goto-char org-goto-start-pos)
4930 (and (org-invisible-p) (org-show-context)))
4931 (goto-char (point-min)))
4932 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4933 (message "Select location and press RET")
4934 (use-local-map org-goto-map)
4935 (recursive-edit)
4937 (kill-buffer "*org-goto*")
4938 (cons org-goto-selected-point org-goto-exit-command)))
4940 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4941 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4942 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4943 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4945 (defun org-goto-local-search-headings (string bound noerror)
4946 "Search and make sure that any matches are in headlines."
4947 (catch 'return
4948 (while (if isearch-forward
4949 (search-forward string bound noerror)
4950 (search-backward string bound noerror))
4951 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4952 (and (member :headline context)
4953 (not (member :tags context))))
4954 (throw 'return (point))))))
4956 (defun org-goto-local-auto-isearch ()
4957 "Start isearch."
4958 (interactive)
4959 (goto-char (point-min))
4960 (let ((keys (this-command-keys)))
4961 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4962 (isearch-mode t)
4963 (isearch-process-search-char (string-to-char keys)))))
4965 (defun org-goto-ret (&optional arg)
4966 "Finish `org-goto' by going to the new location."
4967 (interactive "P")
4968 (setq org-goto-selected-point (point)
4969 org-goto-exit-command 'return)
4970 (throw 'exit nil))
4972 (defun org-goto-left ()
4973 "Finish `org-goto' by going to the new location."
4974 (interactive)
4975 (if (org-on-heading-p)
4976 (progn
4977 (beginning-of-line 1)
4978 (setq org-goto-selected-point (point)
4979 org-goto-exit-command 'left)
4980 (throw 'exit nil))
4981 (error "Not on a heading")))
4983 (defun org-goto-right ()
4984 "Finish `org-goto' by going to the new location."
4985 (interactive)
4986 (if (org-on-heading-p)
4987 (progn
4988 (setq org-goto-selected-point (point)
4989 org-goto-exit-command 'right)
4990 (throw 'exit nil))
4991 (error "Not on a heading")))
4993 (defun org-goto-quit ()
4994 "Finish `org-goto' without cursor motion."
4995 (interactive)
4996 (setq org-goto-selected-point nil)
4997 (setq org-goto-exit-command 'quit)
4998 (throw 'exit nil))
5000 ;;; Indirect buffer display of subtrees
5002 (defvar org-indirect-dedicated-frame nil
5003 "This is the frame being used for indirect tree display.")
5004 (defvar org-last-indirect-buffer nil)
5006 (defun org-tree-to-indirect-buffer (&optional arg)
5007 "Create indirect buffer and narrow it to current subtree.
5008 With numerical prefix ARG, go up to this level and then take that tree.
5009 If ARG is negative, go up that many levels.
5010 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5011 indirect buffer previously made with this command, to avoid proliferation of
5012 indirect buffers. However, when you call the command with a `C-u' prefix, or
5013 when `org-indirect-buffer-display' is `new-frame', the last buffer
5014 is kept so that you can work with several indirect buffers at the same time.
5015 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5016 requests that a new frame be made for the new buffer, so that the dedicated
5017 frame is not changed."
5018 (interactive "P")
5019 (let ((cbuf (current-buffer))
5020 (cwin (selected-window))
5021 (pos (point))
5022 beg end level heading ibuf)
5023 (save-excursion
5024 (org-back-to-heading t)
5025 (when (numberp arg)
5026 (setq level (org-outline-level))
5027 (if (< arg 0) (setq arg (+ level arg)))
5028 (while (> (setq level (org-outline-level)) arg)
5029 (outline-up-heading 1 t)))
5030 (setq beg (point)
5031 heading (org-get-heading))
5032 (org-end-of-subtree t) (setq end (point)))
5033 (if (and (buffer-live-p org-last-indirect-buffer)
5034 (not (eq org-indirect-buffer-display 'new-frame))
5035 (not arg))
5036 (kill-buffer org-last-indirect-buffer))
5037 (setq ibuf (org-get-indirect-buffer cbuf)
5038 org-last-indirect-buffer ibuf)
5039 (cond
5040 ((or (eq org-indirect-buffer-display 'new-frame)
5041 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5042 (select-frame (make-frame))
5043 (delete-other-windows)
5044 (switch-to-buffer ibuf)
5045 (org-set-frame-title heading))
5046 ((eq org-indirect-buffer-display 'dedicated-frame)
5047 (raise-frame
5048 (select-frame (or (and org-indirect-dedicated-frame
5049 (frame-live-p org-indirect-dedicated-frame)
5050 org-indirect-dedicated-frame)
5051 (setq org-indirect-dedicated-frame (make-frame)))))
5052 (delete-other-windows)
5053 (switch-to-buffer ibuf)
5054 (org-set-frame-title (concat "Indirect: " heading)))
5055 ((eq org-indirect-buffer-display 'current-window)
5056 (switch-to-buffer ibuf))
5057 ((eq org-indirect-buffer-display 'other-window)
5058 (pop-to-buffer ibuf))
5059 (t (error "Invalid value.")))
5060 (if (featurep 'xemacs)
5061 (save-excursion (org-mode) (turn-on-font-lock)))
5062 (narrow-to-region beg end)
5063 (show-all)
5064 (goto-char pos)
5065 (and (window-live-p cwin) (select-window cwin))))
5067 (defun org-get-indirect-buffer (&optional buffer)
5068 (setq buffer (or buffer (current-buffer)))
5069 (let ((n 1) (base (buffer-name buffer)) bname)
5070 (while (buffer-live-p
5071 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5072 (setq n (1+ n)))
5073 (condition-case nil
5074 (make-indirect-buffer buffer bname 'clone)
5075 (error (make-indirect-buffer buffer bname)))))
5077 (defun org-set-frame-title (title)
5078 "Set the title of the current frame to the string TITLE."
5079 ;; FIXME: how to name a single frame in XEmacs???
5080 (unless (featurep 'xemacs)
5081 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5083 ;;;; Structure editing
5085 ;;; Inserting headlines
5087 (defun org-previous-line-empty-p ()
5088 (save-excursion
5089 (and (not (bobp))
5090 (or (beginning-of-line 0) t)
5091 (save-match-data
5092 (looking-at "[ \t]*$")))))
5094 (defun org-insert-heading (&optional force-heading)
5095 "Insert a new heading or item with same depth at point.
5096 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5097 If point is at the beginning of a headline, insert a sibling before the
5098 current headline. If point is not at the beginning, do not split the line,
5099 but create the new headline after the current line."
5100 (interactive "P")
5101 (if (= (buffer-size) 0)
5102 (insert "\n* ")
5103 (when (or force-heading (not (org-insert-item)))
5104 (let* ((empty-line-p nil)
5105 (head (save-excursion
5106 (condition-case nil
5107 (progn
5108 (org-back-to-heading)
5109 (setq empty-line-p (org-previous-line-empty-p))
5110 (match-string 0))
5111 (error "*"))))
5112 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5113 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5114 pos hide-previous previous-pos)
5115 (cond
5116 ((and (org-on-heading-p) (bolp)
5117 (or (bobp)
5118 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5119 ;; insert before the current line
5120 (open-line (if blank 2 1)))
5121 ((and (bolp)
5122 (or (bobp)
5123 (save-excursion
5124 (backward-char 1) (not (org-invisible-p)))))
5125 ;; insert right here
5126 nil)
5128 ;; somewhere in the line
5129 (save-excursion
5130 (setq previous-pos (point-at-bol))
5131 (end-of-line)
5132 (setq hide-previous (org-invisible-p)))
5133 (and org-insert-heading-respect-content (org-show-subtree))
5134 (let ((split
5135 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5136 (save-excursion
5137 (let ((p (point)))
5138 (goto-char (point-at-bol))
5139 (and (looking-at org-complex-heading-regexp)
5140 (> p (match-beginning 4)))))))
5141 tags pos)
5142 (cond
5143 (org-insert-heading-respect-content
5144 (org-end-of-subtree nil t)
5145 (or (bolp) (newline))
5146 (or (org-previous-line-empty-p)
5147 (and blank (newline)))
5148 (open-line 1))
5149 ((org-on-heading-p)
5150 (when hide-previous
5151 (show-children)
5152 (org-show-entry))
5153 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5154 (setq tags (and (match-end 2) (match-string 2)))
5155 (and (match-end 1)
5156 (delete-region (match-beginning 1) (match-end 1)))
5157 (setq pos (point-at-bol))
5158 (or split (end-of-line 1))
5159 (delete-horizontal-space)
5160 (newline (if blank 2 1))
5161 (when tags
5162 (save-excursion
5163 (goto-char pos)
5164 (end-of-line 1)
5165 (insert " " tags)
5166 (org-set-tags nil 'align))))
5168 (or split (end-of-line 1))
5169 (newline (if blank 2 1)))))))
5170 (insert head) (just-one-space)
5171 (setq pos (point))
5172 (end-of-line 1)
5173 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5174 (when (and org-insert-heading-respect-content hide-previous)
5175 (save-excursion
5176 (goto-char previous-pos)
5177 (hide-subtree)))
5178 (run-hooks 'org-insert-heading-hook)))))
5180 (defun org-get-heading (&optional no-tags)
5181 "Return the heading of the current entry, without the stars."
5182 (save-excursion
5183 (org-back-to-heading t)
5184 (if (looking-at
5185 (if no-tags
5186 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5187 "\\*+[ \t]+\\([^\r\n]*\\)"))
5188 (match-string 1) "")))
5190 (defun org-heading-components ()
5191 "Return the components of the current heading.
5192 This is a list with the following elements:
5193 - the level as an integer
5194 - the reduced level, different if `org-odd-levels-only' is set.
5195 - the TODO keyword, or nil
5196 - the priority character, like ?A, or nil if no priority is given
5197 - the headline text itself, or the tags string if no headline text
5198 - the tags string, or nil."
5199 (save-excursion
5200 (org-back-to-heading t)
5201 (if (looking-at org-complex-heading-regexp)
5202 (list (length (match-string 1))
5203 (org-reduced-level (length (match-string 1)))
5204 (org-match-string-no-properties 2)
5205 (and (match-end 3) (aref (match-string 3) 2))
5206 (org-match-string-no-properties 4)
5207 (org-match-string-no-properties 5)))))
5209 (defun org-insert-heading-after-current ()
5210 "Insert a new heading with same level as current, after current subtree."
5211 (interactive)
5212 (org-back-to-heading)
5213 (org-insert-heading)
5214 (org-move-subtree-down)
5215 (end-of-line 1))
5217 (defun org-insert-heading-respect-content ()
5218 (interactive)
5219 (let ((org-insert-heading-respect-content t))
5220 (org-insert-heading t)))
5222 (defun org-insert-todo-heading-respect-content (&optional force-state)
5223 (interactive "P")
5224 (let ((org-insert-heading-respect-content t))
5225 (org-insert-todo-heading force-state t)))
5227 (defun org-insert-todo-heading (arg &optional force-heading)
5228 "Insert a new heading with the same level and TODO state as current heading.
5229 If the heading has no TODO state, or if the state is DONE, use the first
5230 state (TODO by default). Also with prefix arg, force first state."
5231 (interactive "P")
5232 (when (or force-heading (not (org-insert-item 'checkbox)))
5233 (org-insert-heading force-heading)
5234 (save-excursion
5235 (org-back-to-heading)
5236 (outline-previous-heading)
5237 (looking-at org-todo-line-regexp))
5238 (let*
5239 ((new-mark-x
5240 (if (or arg
5241 (not (match-beginning 2))
5242 (member (match-string 2) org-done-keywords))
5243 (car org-todo-keywords-1)
5244 (match-string 2)))
5245 (new-mark
5247 (run-hook-with-args-until-success
5248 'org-todo-get-default-hook new-mark-x nil)
5249 new-mark-x)))
5250 (insert new-mark " "))
5251 (when org-provide-todo-statistics
5252 (org-update-parent-todo-statistics))))
5254 (defun org-insert-subheading (arg)
5255 "Insert a new subheading and demote it.
5256 Works for outline headings and for plain lists alike."
5257 (interactive "P")
5258 (org-insert-heading arg)
5259 (cond
5260 ((org-on-heading-p) (org-do-demote))
5261 ((org-at-item-p) (org-indent-item 1))))
5263 (defun org-insert-todo-subheading (arg)
5264 "Insert a new subheading with TODO keyword or checkbox and demote it.
5265 Works for outline headings and for plain lists alike."
5266 (interactive "P")
5267 (org-insert-todo-heading arg)
5268 (cond
5269 ((org-on-heading-p) (org-do-demote))
5270 ((org-at-item-p) (org-indent-item 1))))
5272 ;;; Promotion and Demotion
5274 (defun org-promote-subtree ()
5275 "Promote the entire subtree.
5276 See also `org-promote'."
5277 (interactive)
5278 (save-excursion
5279 (org-map-tree 'org-promote))
5280 (org-fix-position-after-promote))
5282 (defun org-demote-subtree ()
5283 "Demote the entire subtree. See `org-demote'.
5284 See also `org-promote'."
5285 (interactive)
5286 (save-excursion
5287 (org-map-tree 'org-demote))
5288 (org-fix-position-after-promote))
5291 (defun org-do-promote ()
5292 "Promote the current heading higher up the tree.
5293 If the region is active in `transient-mark-mode', promote all headings
5294 in the region."
5295 (interactive)
5296 (save-excursion
5297 (if (org-region-active-p)
5298 (org-map-region 'org-promote (region-beginning) (region-end))
5299 (org-promote)))
5300 (org-fix-position-after-promote))
5302 (defun org-do-demote ()
5303 "Demote the current heading lower down the tree.
5304 If the region is active in `transient-mark-mode', demote all headings
5305 in the region."
5306 (interactive)
5307 (save-excursion
5308 (if (org-region-active-p)
5309 (org-map-region 'org-demote (region-beginning) (region-end))
5310 (org-demote)))
5311 (org-fix-position-after-promote))
5313 (defun org-fix-position-after-promote ()
5314 "Make sure that after pro/demotion cursor position is right."
5315 (let ((pos (point)))
5316 (when (save-excursion
5317 (beginning-of-line 1)
5318 (looking-at org-todo-line-regexp)
5319 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5320 (cond ((eobp) (insert " "))
5321 ((eolp) (insert " "))
5322 ((equal (char-after) ?\ ) (forward-char 1))))))
5324 (defun org-reduced-level (l)
5325 "Compute the effective level of a heading.
5326 This takes into account the setting of `org-odd-levels-only'."
5327 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5329 (defun org-get-valid-level (level &optional change)
5330 "Rectify a level change under the influence of `org-odd-levels-only'
5331 LEVEL is a current level, CHANGE is by how much the level should be
5332 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5333 even level numbers will become the next higher odd number."
5334 (if org-odd-levels-only
5335 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5336 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5337 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5338 (max 1 (+ level change))))
5340 (if (boundp 'define-obsolete-function-alias)
5341 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5342 (define-obsolete-function-alias 'org-get-legal-level
5343 'org-get-valid-level)
5344 (define-obsolete-function-alias 'org-get-legal-level
5345 'org-get-valid-level "23.1")))
5347 (defun org-promote ()
5348 "Promote the current heading higher up the tree.
5349 If the region is active in `transient-mark-mode', promote all headings
5350 in the region."
5351 (org-back-to-heading t)
5352 (let* ((level (save-match-data (funcall outline-level)))
5353 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5354 (diff (abs (- level (length up-head) -1))))
5355 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5356 (replace-match up-head nil t)
5357 ;; Fixup tag positioning
5358 (and org-auto-align-tags (org-set-tags nil t))
5359 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5361 (defun org-demote ()
5362 "Demote the current heading lower down the tree.
5363 If the region is active in `transient-mark-mode', demote all headings
5364 in the region."
5365 (org-back-to-heading t)
5366 (let* ((level (save-match-data (funcall outline-level)))
5367 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5368 (diff (abs (- level (length down-head) -1))))
5369 (replace-match down-head nil t)
5370 ;; Fixup tag positioning
5371 (and org-auto-align-tags (org-set-tags nil t))
5372 (if org-adapt-indentation (org-fixup-indentation diff))))
5374 (defun org-map-tree (fun)
5375 "Call FUN for every heading underneath the current one."
5376 (org-back-to-heading)
5377 (let ((level (funcall outline-level)))
5378 (save-excursion
5379 (funcall fun)
5380 (while (and (progn
5381 (outline-next-heading)
5382 (> (funcall outline-level) level))
5383 (not (eobp)))
5384 (funcall fun)))))
5386 (defun org-map-region (fun beg end)
5387 "Call FUN for every heading between BEG and END."
5388 (let ((org-ignore-region t))
5389 (save-excursion
5390 (setq end (copy-marker end))
5391 (goto-char beg)
5392 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5393 (< (point) end))
5394 (funcall fun))
5395 (while (and (progn
5396 (outline-next-heading)
5397 (< (point) end))
5398 (not (eobp)))
5399 (funcall fun)))))
5401 (defun org-fixup-indentation (diff)
5402 "Change the indentation in the current entry by DIFF
5403 However, if any line in the current entry has no indentation, or if it
5404 would end up with no indentation after the change, nothing at all is done."
5405 (save-excursion
5406 (let ((end (save-excursion (outline-next-heading)
5407 (point-marker)))
5408 (prohibit (if (> diff 0)
5409 "^\\S-"
5410 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5411 col)
5412 (unless (save-excursion (end-of-line 1)
5413 (re-search-forward prohibit end t))
5414 (while (and (< (point) end)
5415 (re-search-forward "^[ \t]+" end t))
5416 (goto-char (match-end 0))
5417 (setq col (current-column))
5418 (if (< diff 0) (replace-match ""))
5419 (org-indent-to-column (+ diff col))))
5420 (move-marker end nil))))
5422 (defun org-convert-to-odd-levels ()
5423 "Convert an org-mode file with all levels allowed to one with odd levels.
5424 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5425 level 5 etc."
5426 (interactive)
5427 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5428 (let ((org-odd-levels-only nil) n)
5429 (save-excursion
5430 (goto-char (point-min))
5431 (while (re-search-forward "^\\*\\*+ " nil t)
5432 (setq n (- (length (match-string 0)) 2))
5433 (while (>= (setq n (1- n)) 0)
5434 (org-demote))
5435 (end-of-line 1))))))
5438 (defun org-convert-to-oddeven-levels ()
5439 "Convert an org-mode file with only odd levels to one with odd and even levels.
5440 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5441 section with an even level, conversion would destroy the structure of the file. An error
5442 is signaled in this case."
5443 (interactive)
5444 (goto-char (point-min))
5445 ;; First check if there are no even levels
5446 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5447 (org-show-context t)
5448 (error "Not all levels are odd in this file. Conversion not possible."))
5449 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5450 (let ((org-odd-levels-only nil) n)
5451 (save-excursion
5452 (goto-char (point-min))
5453 (while (re-search-forward "^\\*\\*+ " nil t)
5454 (setq n (/ (1- (length (match-string 0))) 2))
5455 (while (>= (setq n (1- n)) 0)
5456 (org-promote))
5457 (end-of-line 1))))))
5459 (defun org-tr-level (n)
5460 "Make N odd if required."
5461 (if org-odd-levels-only (1+ (/ n 2)) n))
5463 ;;; Vertical tree motion, cutting and pasting of subtrees
5465 (defun org-move-subtree-up (&optional arg)
5466 "Move the current subtree up past ARG headlines of the same level."
5467 (interactive "p")
5468 (org-move-subtree-down (- (prefix-numeric-value arg))))
5470 (defun org-move-subtree-down (&optional arg)
5471 "Move the current subtree down past ARG headlines of the same level."
5472 (interactive "p")
5473 (setq arg (prefix-numeric-value arg))
5474 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5475 'outline-get-last-sibling))
5476 (ins-point (make-marker))
5477 (cnt (abs arg))
5478 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5479 ;; Select the tree
5480 (org-back-to-heading)
5481 (setq beg0 (point))
5482 (save-excursion
5483 (setq ne-beg (org-back-over-empty-lines))
5484 (setq beg (point)))
5485 (save-match-data
5486 (save-excursion (outline-end-of-heading)
5487 (setq folded (org-invisible-p)))
5488 (outline-end-of-subtree))
5489 (outline-next-heading)
5490 (setq ne-end (org-back-over-empty-lines))
5491 (setq end (point))
5492 (goto-char beg0)
5493 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5494 ;; include less whitespace
5495 (save-excursion
5496 (goto-char beg)
5497 (forward-line (- ne-beg ne-end))
5498 (setq beg (point))))
5499 ;; Find insertion point, with error handling
5500 (while (> cnt 0)
5501 (or (and (funcall movfunc) (looking-at outline-regexp))
5502 (progn (goto-char beg0)
5503 (error "Cannot move past superior level or buffer limit")))
5504 (setq cnt (1- cnt)))
5505 (if (> arg 0)
5506 ;; Moving forward - still need to move over subtree
5507 (progn (org-end-of-subtree t t)
5508 (save-excursion
5509 (org-back-over-empty-lines)
5510 (or (bolp) (newline)))))
5511 (setq ne-ins (org-back-over-empty-lines))
5512 (move-marker ins-point (point))
5513 (setq txt (buffer-substring beg end))
5514 (org-save-markers-in-region beg end)
5515 (delete-region beg end)
5516 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5517 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5518 (let ((bbb (point)))
5519 (insert-before-markers txt)
5520 (org-reinstall-markers-in-region bbb)
5521 (move-marker ins-point bbb))
5522 (or (bolp) (insert "\n"))
5523 (setq ins-end (point))
5524 (goto-char ins-point)
5525 (org-skip-whitespace)
5526 (when (and (< arg 0)
5527 (org-first-sibling-p)
5528 (> ne-ins ne-beg))
5529 ;; Move whitespace back to beginning
5530 (save-excursion
5531 (goto-char ins-end)
5532 (let ((kill-whole-line t))
5533 (kill-line (- ne-ins ne-beg)) (point)))
5534 (insert (make-string (- ne-ins ne-beg) ?\n)))
5535 (move-marker ins-point nil)
5536 (org-compact-display-after-subtree-move)
5537 (org-show-empty-lines-in-parent)
5538 (unless folded
5539 (org-show-entry)
5540 (show-children)
5541 (org-cycle-hide-drawers 'children))))
5543 (defvar org-subtree-clip ""
5544 "Clipboard for cut and paste of subtrees.
5545 This is actually only a copy of the kill, because we use the normal kill
5546 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5548 (defvar org-subtree-clip-folded nil
5549 "Was the last copied subtree folded?
5550 This is used to fold the tree back after pasting.")
5552 (defun org-cut-subtree (&optional n)
5553 "Cut the current subtree into the clipboard.
5554 With prefix arg N, cut this many sequential subtrees.
5555 This is a short-hand for marking the subtree and then cutting it."
5556 (interactive "p")
5557 (org-copy-subtree n 'cut))
5559 (defun org-copy-subtree (&optional n cut force-store-markers)
5560 "Cut the current subtree into the clipboard.
5561 With prefix arg N, cut this many sequential subtrees.
5562 This is a short-hand for marking the subtree and then copying it.
5563 If CUT is non-nil, actually cut the subtree.
5564 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5565 of some markers in the region, even if CUT is non-nil. This is
5566 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5567 (interactive "p")
5568 (let (beg end folded (beg0 (point)))
5569 (if (interactive-p)
5570 (org-back-to-heading nil) ; take what looks like a subtree
5571 (org-back-to-heading t)) ; take what is really there
5572 (org-back-over-empty-lines)
5573 (setq beg (point))
5574 (skip-chars-forward " \t\r\n")
5575 (save-match-data
5576 (save-excursion (outline-end-of-heading)
5577 (setq folded (org-invisible-p)))
5578 (condition-case nil
5579 (outline-forward-same-level (1- n))
5580 (error nil))
5581 (org-end-of-subtree t t))
5582 (org-back-over-empty-lines)
5583 (setq end (point))
5584 (goto-char beg0)
5585 (when (> end beg)
5586 (setq org-subtree-clip-folded folded)
5587 (when (or cut force-store-markers)
5588 (org-save-markers-in-region beg end))
5589 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5590 (setq org-subtree-clip (current-kill 0))
5591 (message "%s: Subtree(s) with %d characters"
5592 (if cut "Cut" "Copied")
5593 (length org-subtree-clip)))))
5595 (defun org-paste-subtree (&optional level tree for-yank)
5596 "Paste the clipboard as a subtree, with modification of headline level.
5597 The entire subtree is promoted or demoted in order to match a new headline
5598 level.
5600 If the cursor is at the beginning of a headline, the same level as
5601 that headline is used to paste the tree
5603 If not, the new level is derived from the *visible* headings
5604 before and after the insertion point, and taken to be the inferior headline
5605 level of the two. So if the previous visible heading is level 3 and the
5606 next is level 4 (or vice versa), level 4 will be used for insertion.
5607 This makes sure that the subtree remains an independent subtree and does
5608 not swallow low level entries.
5610 You can also force a different level, either by using a numeric prefix
5611 argument, or by inserting the heading marker by hand. For example, if the
5612 cursor is after \"*****\", then the tree will be shifted to level 5.
5614 If optional TREE is given, use this text instead of the kill ring.
5616 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5617 move back over whitespace before inserting, and move point to the end of
5618 the inserted text when done."
5619 (interactive "P")
5620 (unless (org-kill-is-subtree-p tree)
5621 (error "%s"
5622 (substitute-command-keys
5623 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5624 (let* ((visp (not (org-invisible-p)))
5625 (txt (or tree (and kill-ring (current-kill 0))))
5626 (^re (concat "^\\(" outline-regexp "\\)"))
5627 (re (concat "\\(" outline-regexp "\\)"))
5628 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5630 (old-level (if (string-match ^re txt)
5631 (- (match-end 0) (match-beginning 0) 1)
5632 -1))
5633 (force-level (cond (level (prefix-numeric-value level))
5634 ((and (looking-at "[ \t]*$")
5635 (string-match
5636 ^re_ (buffer-substring
5637 (point-at-bol) (point))))
5638 (- (match-end 1) (match-beginning 1)))
5639 ((and (bolp)
5640 (looking-at org-outline-regexp))
5641 (- (match-end 0) (point) 1))
5642 (t nil)))
5643 (previous-level (save-excursion
5644 (condition-case nil
5645 (progn
5646 (outline-previous-visible-heading 1)
5647 (if (looking-at re)
5648 (- (match-end 0) (match-beginning 0) 1)
5650 (error 1))))
5651 (next-level (save-excursion
5652 (condition-case nil
5653 (progn
5654 (or (looking-at outline-regexp)
5655 (outline-next-visible-heading 1))
5656 (if (looking-at re)
5657 (- (match-end 0) (match-beginning 0) 1)
5659 (error 1))))
5660 (new-level (or force-level (max previous-level next-level)))
5661 (shift (if (or (= old-level -1)
5662 (= new-level -1)
5663 (= old-level new-level))
5665 (- new-level old-level)))
5666 (delta (if (> shift 0) -1 1))
5667 (func (if (> shift 0) 'org-demote 'org-promote))
5668 (org-odd-levels-only nil)
5669 beg end newend)
5670 ;; Remove the forced level indicator
5671 (if force-level
5672 (delete-region (point-at-bol) (point)))
5673 ;; Paste
5674 (beginning-of-line 1)
5675 (unless for-yank (org-back-over-empty-lines))
5676 (setq beg (point))
5677 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5678 (insert-before-markers txt)
5679 (unless (string-match "\n\\'" txt) (insert "\n"))
5680 (setq newend (point))
5681 (org-reinstall-markers-in-region beg)
5682 (setq end (point))
5683 (goto-char beg)
5684 (skip-chars-forward " \t\n\r")
5685 (setq beg (point))
5686 (if (and (org-invisible-p) visp)
5687 (save-excursion (outline-show-heading)))
5688 ;; Shift if necessary
5689 (unless (= shift 0)
5690 (save-restriction
5691 (narrow-to-region beg end)
5692 (while (not (= shift 0))
5693 (org-map-region func (point-min) (point-max))
5694 (setq shift (+ delta shift)))
5695 (goto-char (point-min))
5696 (setq newend (point-max))))
5697 (when (or (interactive-p) for-yank)
5698 (message "Clipboard pasted as level %d subtree" new-level))
5699 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5700 kill-ring
5701 (eq org-subtree-clip (current-kill 0))
5702 org-subtree-clip-folded)
5703 ;; The tree was folded before it was killed/copied
5704 (hide-subtree))
5705 (and for-yank (goto-char newend))))
5707 (defun org-kill-is-subtree-p (&optional txt)
5708 "Check if the current kill is an outline subtree, or a set of trees.
5709 Returns nil if kill does not start with a headline, or if the first
5710 headline level is not the largest headline level in the tree.
5711 So this will actually accept several entries of equal levels as well,
5712 which is OK for `org-paste-subtree'.
5713 If optional TXT is given, check this string instead of the current kill."
5714 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5715 (start-level (and kill
5716 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5717 org-outline-regexp "\\)")
5718 kill)
5719 (- (match-end 2) (match-beginning 2) 1)))
5720 (re (concat "^" org-outline-regexp))
5721 (start (1+ (or (match-beginning 2) -1))))
5722 (if (not start-level)
5723 (progn
5724 nil) ;; does not even start with a heading
5725 (catch 'exit
5726 (while (setq start (string-match re kill (1+ start)))
5727 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5728 (throw 'exit nil)))
5729 t))))
5731 (defvar org-markers-to-move nil
5732 "Markers that should be moved with a cut-and-paste operation.
5733 Those markers are stored together with their positions relative to
5734 the start of the region.")
5736 (defun org-save-markers-in-region (beg end)
5737 "Check markers in region.
5738 If these markers are between BEG and END, record their position relative
5739 to BEG, so that after moving the block of text, we can put the markers back
5740 into place.
5741 This function gets called just before an entry or tree gets cut from the
5742 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5743 called immediately, to move the markers with the entries."
5744 (setq org-markers-to-move nil)
5745 (when (featurep 'org-clock)
5746 (org-clock-save-markers-for-cut-and-paste beg end))
5747 (when (featurep 'org-agenda)
5748 (org-agenda-save-markers-for-cut-and-paste beg end)))
5750 (defun org-check-and-save-marker (marker beg end)
5751 "Check if MARKER is between BEG and END.
5752 If yes, remember the marker and the distance to BEG."
5753 (when (and (marker-buffer marker)
5754 (equal (marker-buffer marker) (current-buffer)))
5755 (if (and (>= marker beg) (< marker end))
5756 (push (cons marker (- marker beg)) org-markers-to-move))))
5758 (defun org-reinstall-markers-in-region (beg)
5759 "Move all remembered markers to their position relative to BEG."
5760 (mapc (lambda (x)
5761 (move-marker (car x) (+ beg (cdr x))))
5762 org-markers-to-move)
5763 (setq org-markers-to-move nil))
5765 (defun org-narrow-to-subtree ()
5766 "Narrow buffer to the current subtree."
5767 (interactive)
5768 (save-excursion
5769 (save-match-data
5770 (narrow-to-region
5771 (progn (org-back-to-heading) (point))
5772 (progn (org-end-of-subtree t) (point))))))
5775 ;;; Outline Sorting
5777 (defun org-sort (with-case)
5778 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5779 Optional argument WITH-CASE means sort case-sensitively.
5780 With a double prefix argument, also remove duplicate entries."
5781 (interactive "P")
5782 (if (org-at-table-p)
5783 (org-call-with-arg 'org-table-sort-lines with-case)
5784 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5786 (defun org-sort-remove-invisible (s)
5787 (remove-text-properties 0 (length s) org-rm-props s)
5788 (while (string-match org-bracket-link-regexp s)
5789 (setq s (replace-match (if (match-end 2)
5790 (match-string 3 s)
5791 (match-string 1 s)) t t s)))
5794 (defvar org-priority-regexp) ; defined later in the file
5796 (defun org-sort-entries-or-items
5797 (&optional with-case sorting-type getkey-func compare-func property)
5798 "Sort entries on a certain level of an outline tree.
5799 If there is an active region, the entries in the region are sorted.
5800 Else, if the cursor is before the first entry, sort the top-level items.
5801 Else, the children of the entry at point are sorted.
5803 Sorting can be alphabetically, numerically, and by date/time as given by
5804 the first time stamp in the entry. The command prompts for the sorting
5805 type unless it has been given to the function through the SORTING-TYPE
5806 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5807 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5808 called with point at the beginning of the record. It must return either
5809 a string or a number that should serve as the sorting key for that record.
5811 Comparing entries ignores case by default. However, with an optional argument
5812 WITH-CASE, the sorting considers case as well."
5813 (interactive "P")
5814 (let ((case-func (if with-case 'identity 'downcase))
5815 start beg end stars re re2
5816 txt what tmp plain-list-p)
5817 ;; Find beginning and end of region to sort
5818 (cond
5819 ((org-region-active-p)
5820 ;; we will sort the region
5821 (setq end (region-end)
5822 what "region")
5823 (goto-char (region-beginning))
5824 (if (not (org-on-heading-p)) (outline-next-heading))
5825 (setq start (point)))
5826 ((org-at-item-p)
5827 ;; we will sort this plain list
5828 (org-beginning-of-item-list) (setq start (point))
5829 (org-end-of-item-list) (setq end (point))
5830 (goto-char start)
5831 (setq plain-list-p t
5832 what "plain list"))
5833 ((or (org-on-heading-p)
5834 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5835 ;; we will sort the children of the current headline
5836 (org-back-to-heading)
5837 (setq start (point)
5838 end (progn (org-end-of-subtree t t)
5839 (org-back-over-empty-lines)
5840 (point))
5841 what "children")
5842 (goto-char start)
5843 (show-subtree)
5844 (outline-next-heading))
5846 ;; we will sort the top-level entries in this file
5847 (goto-char (point-min))
5848 (or (org-on-heading-p) (outline-next-heading))
5849 (setq start (point) end (point-max) what "top-level")
5850 (goto-char start)
5851 (show-all)))
5853 (setq beg (point))
5854 (if (>= beg end) (error "Nothing to sort"))
5856 (unless plain-list-p
5857 (looking-at "\\(\\*+\\)")
5858 (setq stars (match-string 1)
5859 re (concat "^" (regexp-quote stars) " +")
5860 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5861 txt (buffer-substring beg end))
5862 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5863 (if (and (not (equal stars "*")) (string-match re2 txt))
5864 (error "Region to sort contains a level above the first entry")))
5866 (unless sorting-type
5867 (message
5868 (if plain-list-p
5869 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5870 "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:")
5871 what)
5872 (setq sorting-type (read-char-exclusive))
5874 (and (= (downcase sorting-type) ?f)
5875 (setq getkey-func
5876 (org-ido-completing-read "Sort using function: "
5877 obarray 'fboundp t nil nil))
5878 (setq getkey-func (intern getkey-func)))
5880 (and (= (downcase sorting-type) ?r)
5881 (setq property
5882 (org-ido-completing-read "Property: "
5883 (mapcar 'list (org-buffer-property-keys t))
5884 nil t))))
5886 (message "Sorting entries...")
5888 (save-restriction
5889 (narrow-to-region start end)
5891 (let ((dcst (downcase sorting-type))
5892 (now (current-time)))
5893 (sort-subr
5894 (/= dcst sorting-type)
5895 ;; This function moves to the beginning character of the "record" to
5896 ;; be sorted.
5897 (if plain-list-p
5898 (lambda nil
5899 (if (org-at-item-p) t (goto-char (point-max))))
5900 (lambda nil
5901 (if (re-search-forward re nil t)
5902 (goto-char (match-beginning 0))
5903 (goto-char (point-max)))))
5904 ;; This function moves to the last character of the "record" being
5905 ;; sorted.
5906 (if plain-list-p
5907 'org-end-of-item
5908 (lambda nil
5909 (save-match-data
5910 (condition-case nil
5911 (outline-forward-same-level 1)
5912 (error
5913 (goto-char (point-max)))))))
5915 ;; This function returns the value that gets sorted against.
5916 (if plain-list-p
5917 (lambda nil
5918 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5919 (cond
5920 ((= dcst ?n)
5921 (string-to-number (buffer-substring (match-end 0)
5922 (point-at-eol))))
5923 ((= dcst ?a)
5924 (buffer-substring (match-end 0) (point-at-eol)))
5925 ((= dcst ?t)
5926 (if (re-search-forward org-ts-regexp
5927 (point-at-eol) t)
5928 (org-time-string-to-time (match-string 0))
5929 now))
5930 ((= dcst ?f)
5931 (if getkey-func
5932 (progn
5933 (setq tmp (funcall getkey-func))
5934 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5935 tmp)
5936 (error "Invalid key function `%s'" getkey-func)))
5937 (t (error "Invalid sorting type `%c'" sorting-type)))))
5938 (lambda nil
5939 (cond
5940 ((= dcst ?n)
5941 (if (looking-at org-complex-heading-regexp)
5942 (string-to-number (match-string 4))
5943 nil))
5944 ((= dcst ?a)
5945 (if (looking-at org-complex-heading-regexp)
5946 (funcall case-func (match-string 4))
5947 nil))
5948 ((= dcst ?t)
5949 (if (re-search-forward org-ts-regexp
5950 (save-excursion
5951 (forward-line 2)
5952 (point)) t)
5953 (org-time-string-to-time (match-string 0))
5954 now))
5955 ((= dcst ?p)
5956 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5957 (string-to-char (match-string 2))
5958 org-default-priority))
5959 ((= dcst ?r)
5960 (or (org-entry-get nil property) ""))
5961 ((= dcst ?o)
5962 (if (looking-at org-complex-heading-regexp)
5963 (- 9999 (length (member (match-string 2)
5964 org-todo-keywords-1)))))
5965 ((= dcst ?f)
5966 (if getkey-func
5967 (progn
5968 (setq tmp (funcall getkey-func))
5969 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5970 tmp)
5971 (error "Invalid key function `%s'" getkey-func)))
5972 (t (error "Invalid sorting type `%c'" sorting-type)))))
5974 (cond
5975 ((= dcst ?a) 'string<)
5976 ((= dcst ?t) 'time-less-p)
5977 ((= dcst ?f) compare-func)
5978 (t nil)))))
5979 (message "Sorting entries...done")))
5981 (defun org-do-sort (table what &optional with-case sorting-type)
5982 "Sort TABLE of WHAT according to SORTING-TYPE.
5983 The user will be prompted for the SORTING-TYPE if the call to this
5984 function does not specify it. WHAT is only for the prompt, to indicate
5985 what is being sorted. The sorting key will be extracted from
5986 the car of the elements of the table.
5987 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5988 (unless sorting-type
5989 (message
5990 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5991 what)
5992 (setq sorting-type (read-char-exclusive)))
5993 (let ((dcst (downcase sorting-type))
5994 extractfun comparefun)
5995 ;; Define the appropriate functions
5996 (cond
5997 ((= dcst ?n)
5998 (setq extractfun 'string-to-number
5999 comparefun (if (= dcst sorting-type) '< '>)))
6000 ((= dcst ?a)
6001 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6002 (lambda(x) (downcase (org-sort-remove-invisible x))))
6003 comparefun (if (= dcst sorting-type)
6004 'string<
6005 (lambda (a b) (and (not (string< a b))
6006 (not (string= a b)))))))
6007 ((= dcst ?t)
6008 (setq extractfun
6009 (lambda (x)
6010 (if (or (string-match org-ts-regexp x)
6011 (string-match org-ts-regexp-both x))
6012 (time-to-seconds
6013 (org-time-string-to-time (match-string 0 x)))
6015 comparefun (if (= dcst sorting-type) '< '>)))
6016 (t (error "Invalid sorting type `%c'" sorting-type)))
6018 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6019 table)
6020 (lambda (a b) (funcall comparefun (car a) (car b))))))
6022 ;;; Editing source examples
6024 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6025 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6026 (defvar org-edit-src-force-single-line nil)
6027 (defvar org-edit-src-from-org-mode nil)
6028 (defvar org-edit-src-picture nil)
6030 (define-minor-mode org-exit-edit-mode
6031 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6033 (defun org-edit-src-code ()
6034 "Edit the source code example at point.
6035 An indirect buffer is created, and that buffer is then narrowed to the
6036 example at point and switched to the correct language mode. When done,
6037 exit by killing the buffer with \\[org-edit-src-exit]."
6038 (interactive)
6039 (let ((line (org-current-line))
6040 (case-fold-search t)
6041 (msg (substitute-command-keys
6042 "Edit, then exit with C-c ' (C-c and single quote)"))
6043 (info (org-edit-src-find-region-and-lang))
6044 (org-mode-p (eq major-mode 'org-mode))
6045 beg end lang lang-f single lfmt)
6046 (if (not info)
6048 (setq beg (nth 0 info)
6049 end (nth 1 info)
6050 lang (nth 2 info)
6051 single (nth 3 info)
6052 lfmt (nth 4 info)
6053 lang-f (intern (concat lang "-mode")))
6054 (unless (functionp lang-f)
6055 (error "No such language mode: %s" lang-f))
6056 (goto-line line)
6057 (if (get-buffer "*Org Edit Src Example*")
6058 (kill-buffer "*Org Edit Src Example*"))
6059 (switch-to-buffer (make-indirect-buffer (current-buffer)
6060 "*Org Edit Src Example*"))
6061 (narrow-to-region beg end)
6062 (remove-text-properties beg end '(display nil invisible nil
6063 intangible nil))
6064 (let ((org-inhibit-startup t))
6065 (funcall lang-f))
6066 (set (make-local-variable 'org-edit-src-force-single-line) single)
6067 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6068 (when lfmt
6069 (set (make-local-variable 'org-coderef-label-format) lfmt))
6070 (when org-mode-p
6071 (goto-char (point-min))
6072 (while (re-search-forward "^," nil t)
6073 (replace-match "")))
6074 (goto-line line)
6075 (org-exit-edit-mode)
6076 (org-set-local 'header-line-format msg)
6077 (message "%s" msg)
6078 t)))
6080 (defun org-edit-fixed-width-region ()
6081 "Edit the fixed-width ascii drawing at point.
6082 This must be a region where each line starts with a colon followed by
6083 a space character.
6084 An indirect buffer is created, and that buffer is then narrowed to the
6085 example at point and switched to artist-mode. When done,
6086 exit by killing the buffer with \\[org-edit-src-exit]."
6087 (interactive)
6088 (let ((line (org-current-line))
6089 (case-fold-search t)
6090 (msg (substitute-command-keys
6091 "Edit, then exit with C-c ' (C-c and single quote)"))
6092 (org-mode-p (eq major-mode 'org-mode))
6093 beg end)
6094 (beginning-of-line 1)
6095 (if (looking-at "[ \t]*[^:\n \t]")
6097 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6098 (setq beg (point) end beg)
6099 (save-excursion
6100 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6101 (setq beg (point-at-bol 2))
6102 (setq beg (point))))
6103 (save-excursion
6104 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6105 (setq end (1- (match-beginning 0)))
6106 (setq end (point))))
6107 (goto-line line))
6108 (if (get-buffer "*Org Edit Picture*")
6109 (kill-buffer "*Org Edit Picture*"))
6110 (switch-to-buffer (make-indirect-buffer (current-buffer)
6111 "*Org Edit Picture*"))
6112 (narrow-to-region beg end)
6113 (remove-text-properties beg end '(display nil invisible nil
6114 intangible nil))
6115 (when (fboundp 'font-lock-unfontify-region)
6116 (font-lock-unfontify-region (point-min) (point-max)))
6117 (cond
6118 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6119 (fundamental-mode)
6120 (artist-mode 1))
6121 (t (funcall org-edit-fixed-width-region-mode)))
6122 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6123 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6124 (set (make-local-variable 'org-edit-src-picture) t)
6125 (goto-char (point-min))
6126 (while (re-search-forward "^[ \t]*: ?" nil t)
6127 (replace-match ""))
6128 (goto-line line)
6129 (org-exit-edit-mode)
6130 (org-set-local 'header-line-format msg)
6131 (message "%s" msg)
6132 t)))
6135 (defun org-edit-src-find-region-and-lang ()
6136 "Find the region and language for a local edit.
6137 Return a list with beginning and end of the region, a string representing
6138 the language, a switch telling of the content should be in a single line."
6139 (let ((re-list
6140 (append
6141 org-edit-src-region-extra
6143 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6144 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6145 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6146 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6147 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6148 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6149 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6150 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6151 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6152 ("^#\\+html:" "\n" "html" single-line)
6153 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6154 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6155 ("^#\\+latex:" "\n" "latex" single-line)
6156 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6157 ("^#\\+ascii:" "\n" "ascii" single-line)
6159 (pos (point))
6160 re1 re2 single beg end lang lfmt match-re1)
6161 (catch 'exit
6162 (while (setq entry (pop re-list))
6163 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6164 single (nth 3 entry))
6165 (save-excursion
6166 (if (or (looking-at re1)
6167 (re-search-backward re1 nil t))
6168 (progn
6169 (setq match-re1 (match-string 0))
6170 (setq beg (match-end 0)
6171 lang (org-edit-src-get-lang lang)
6172 lfmt (org-edit-src-get-label-format match-re1))
6173 (if (and (re-search-forward re2 nil t)
6174 (>= (match-end 0) pos))
6175 (throw 'exit (list beg (match-beginning 0)
6176 lang single lfmt))))
6177 (if (or (looking-at re2)
6178 (re-search-forward re2 nil t))
6179 (progn
6180 (setq end (match-beginning 0))
6181 (if (and (re-search-backward re1 nil t)
6182 (<= (match-beginning 0) pos))
6183 (progn
6184 (setq lfmt (org-edit-src-get-label-format
6185 (match-string 0)))
6186 (throw 'exit
6187 (list (match-end 0) end
6188 (org-edit-src-get-lang lang)
6189 single lfmt))))))))))))
6191 (defun org-edit-src-get-lang (lang)
6192 "Extract the src language."
6193 (let ((m (match-string 0)))
6194 (cond
6195 ((stringp lang) lang)
6196 ((integerp lang) (match-string lang))
6197 ((and (eq lang 'lang)
6198 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6199 (match-string 1 m))
6200 ((and (eq lang 'style)
6201 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6202 (match-string 1 m))
6203 (t "fundamental"))))
6205 (defun org-edit-src-get-label-format (s)
6206 "Extract the label format."
6207 (save-match-data
6208 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6209 (match-string 1 s))))
6211 (defun org-edit-src-exit ()
6212 "Exit special edit and protect problematic lines."
6213 (interactive)
6214 (unless (buffer-base-buffer (current-buffer))
6215 (error "This is not an indirect buffer, something is wrong..."))
6216 (unless (> (point-min) 1)
6217 (error "This buffer is not narrowed, something is wrong..."))
6218 (goto-char (point-min))
6219 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6220 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6221 (when (org-bound-and-true-p org-edit-src-force-single-line)
6222 (goto-char (point-min))
6223 (while (re-search-forward "\n" nil t)
6224 (replace-match " "))
6225 (goto-char (point-min))
6226 (if (looking-at "\\s-*") (replace-match " "))
6227 (if (re-search-forward "\\s-+\\'" nil t)
6228 (replace-match "")))
6229 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6230 (goto-char (point-min))
6231 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6232 (replace-match ",\\1"))
6233 (when font-lock-mode
6234 (font-lock-unfontify-region (point-min) (point-max)))
6235 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6236 (when (org-bound-and-true-p org-edit-src-picture)
6237 (untabify (point-min) (point-max))
6238 (goto-char (point-min))
6239 (while (re-search-forward "^" nil t)
6240 (replace-match ": "))
6241 (when font-lock-mode
6242 (font-lock-unfontify-region (point-min) (point-max)))
6243 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6244 (kill-buffer (current-buffer))
6245 (and (org-mode-p) (org-restart-font-lock)))
6248 ;;; The orgstruct minor mode
6250 ;; Define a minor mode which can be used in other modes in order to
6251 ;; integrate the org-mode structure editing commands.
6253 ;; This is really a hack, because the org-mode structure commands use
6254 ;; keys which normally belong to the major mode. Here is how it
6255 ;; works: The minor mode defines all the keys necessary to operate the
6256 ;; structure commands, but wraps the commands into a function which
6257 ;; tests if the cursor is currently at a headline or a plain list
6258 ;; item. If that is the case, the structure command is used,
6259 ;; temporarily setting many Org-mode variables like regular
6260 ;; expressions for filling etc. However, when any of those keys is
6261 ;; used at a different location, function uses `key-binding' to look
6262 ;; up if the key has an associated command in another currently active
6263 ;; keymap (minor modes, major mode, global), and executes that
6264 ;; command. There might be problems if any of the keys is otherwise
6265 ;; used as a prefix key.
6267 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6268 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6269 ;; addresses this by checking explicitly for both bindings.
6271 (defvar orgstruct-mode-map (make-sparse-keymap)
6272 "Keymap for the minor `orgstruct-mode'.")
6274 (defvar org-local-vars nil
6275 "List of local variables, for use by `orgstruct-mode'")
6277 ;;;###autoload
6278 (define-minor-mode orgstruct-mode
6279 "Toggle the minor more `orgstruct-mode'.
6280 This mode is for using Org-mode structure commands in other modes.
6281 The following key behave as if Org-mode was active, if the cursor
6282 is on a headline, or on a plain list item (both in the definition
6283 of Org-mode).
6285 M-up Move entry/item up
6286 M-down Move entry/item down
6287 M-left Promote
6288 M-right Demote
6289 M-S-up Move entry/item up
6290 M-S-down Move entry/item down
6291 M-S-left Promote subtree
6292 M-S-right Demote subtree
6293 M-q Fill paragraph and items like in Org-mode
6294 C-c ^ Sort entries
6295 C-c - Cycle list bullet
6296 TAB Cycle item visibility
6297 M-RET Insert new heading/item
6298 S-M-RET Insert new TODO heading / Checkbox item
6299 C-c C-c Set tags / toggle checkbox"
6300 nil " OrgStruct" nil
6301 (org-load-modules-maybe)
6302 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6304 ;;;###autoload
6305 (defun turn-on-orgstruct ()
6306 "Unconditionally turn on `orgstruct-mode'."
6307 (orgstruct-mode 1))
6309 (defun orgstruct++-mode (&optional arg)
6310 "Toggle `orgstruct-mode', the enhanced version of it.
6311 In addition to setting orgstruct-mode, this also exports all indentation and
6312 autofilling variables from org-mode into the buffer. It will also
6313 recognize item context in multiline items.
6314 Note that turning off orgstruct-mode will *not* remove the
6315 indentation/paragraph settings. This can only be done by refreshing the
6316 major mode, for example with \[normal-mode]."
6317 (interactive "P")
6318 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6319 (if (< arg 1)
6320 (orgstruct-mode -1)
6321 (orgstruct-mode 1)
6322 (let (var val)
6323 (mapc
6324 (lambda (x)
6325 (when (string-match
6326 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6327 (symbol-name (car x)))
6328 (setq var (car x) val (nth 1 x))
6329 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6330 org-local-vars)
6331 (org-set-local 'orgstruct-is-++ t))))
6333 (defvar orgstruct-is-++ nil
6334 "Is orgstruct-mode in ++ version in the current-buffer?")
6335 (make-variable-buffer-local 'orgstruct-is-++)
6337 ;;;###autoload
6338 (defun turn-on-orgstruct++ ()
6339 "Unconditionally turn on `orgstruct++-mode'."
6340 (orgstruct++-mode 1))
6342 (defun orgstruct-error ()
6343 "Error when there is no default binding for a structure key."
6344 (interactive)
6345 (error "This key has no function outside structure elements"))
6347 (defun orgstruct-setup ()
6348 "Setup orgstruct keymaps."
6349 (let ((nfunc 0)
6350 (bindings
6351 (list
6352 '([(meta up)] org-metaup)
6353 '([(meta down)] org-metadown)
6354 '([(meta left)] org-metaleft)
6355 '([(meta right)] org-metaright)
6356 '([(meta shift up)] org-shiftmetaup)
6357 '([(meta shift down)] org-shiftmetadown)
6358 '([(meta shift left)] org-shiftmetaleft)
6359 '([(meta shift right)] org-shiftmetaright)
6360 '([(shift up)] org-shiftup)
6361 '([(shift down)] org-shiftdown)
6362 '([(shift left)] org-shiftleft)
6363 '([(shift right)] org-shiftright)
6364 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6365 '("\M-q" fill-paragraph)
6366 '("\C-c^" org-sort)
6367 '("\C-c-" org-cycle-list-bullet)))
6368 elt key fun cmd)
6369 (while (setq elt (pop bindings))
6370 (setq nfunc (1+ nfunc))
6371 (setq key (org-key (car elt))
6372 fun (nth 1 elt)
6373 cmd (orgstruct-make-binding fun nfunc key))
6374 (org-defkey orgstruct-mode-map key cmd))
6376 ;; Special treatment needed for TAB and RET
6377 (org-defkey orgstruct-mode-map [(tab)]
6378 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6379 (org-defkey orgstruct-mode-map "\C-i"
6380 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6382 (org-defkey orgstruct-mode-map "\M-\C-m"
6383 (orgstruct-make-binding 'org-insert-heading 105
6384 "\M-\C-m" [(meta return)]))
6385 (org-defkey orgstruct-mode-map [(meta return)]
6386 (orgstruct-make-binding 'org-insert-heading 106
6387 [(meta return)] "\M-\C-m"))
6389 (org-defkey orgstruct-mode-map [(shift meta return)]
6390 (orgstruct-make-binding 'org-insert-todo-heading 107
6391 [(meta return)] "\M-\C-m"))
6393 (unless org-local-vars
6394 (setq org-local-vars (org-get-local-variables)))
6398 (defun orgstruct-make-binding (fun n &rest keys)
6399 "Create a function for binding in the structure minor mode.
6400 FUN is the command to call inside a table. N is used to create a unique
6401 command name. KEYS are keys that should be checked in for a command
6402 to execute outside of tables."
6403 (eval
6404 (list 'defun
6405 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6406 '(arg)
6407 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6408 "Outside of structure, run the binding of `"
6409 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6410 "'.")
6411 '(interactive "p")
6412 (list 'if
6413 `(org-context-p 'headline 'item
6414 (and orgstruct-is-++
6415 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6416 'item-body))
6417 (list 'org-run-like-in-org-mode (list 'quote fun))
6418 (list 'let '(orgstruct-mode)
6419 (list 'call-interactively
6420 (append '(or)
6421 (mapcar (lambda (k)
6422 (list 'key-binding k))
6423 keys)
6424 '('orgstruct-error))))))))
6426 (defun org-context-p (&rest contexts)
6427 "Check if local context is any of CONTEXTS.
6428 Possible values in the list of contexts are `table', `headline', and `item'."
6429 (let ((pos (point)))
6430 (goto-char (point-at-bol))
6431 (prog1 (or (and (memq 'table contexts)
6432 (looking-at "[ \t]*|"))
6433 (and (memq 'headline contexts)
6434 ;;????????? (looking-at "\\*+"))
6435 (looking-at outline-regexp))
6436 (and (memq 'item contexts)
6437 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6438 (and (memq 'item-body contexts)
6439 (org-in-item-p)))
6440 (goto-char pos))))
6442 (defun org-get-local-variables ()
6443 "Return a list of all local variables in an org-mode buffer."
6444 (let (varlist)
6445 (with-current-buffer (get-buffer-create "*Org tmp*")
6446 (erase-buffer)
6447 (org-mode)
6448 (setq varlist (buffer-local-variables)))
6449 (kill-buffer "*Org tmp*")
6450 (delq nil
6451 (mapcar
6452 (lambda (x)
6453 (setq x
6454 (if (symbolp x)
6455 (list x)
6456 (list (car x) (list 'quote (cdr x)))))
6457 (if (string-match
6458 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6459 (symbol-name (car x)))
6460 x nil))
6461 varlist))))
6463 ;;;###autoload
6464 (defun org-run-like-in-org-mode (cmd)
6465 "Run a command, pretending that the current buffer is in Org-mode.
6466 This will temporarily bind local variables that are typically bound in
6467 Org-mode to the values they have in Org-mode, and then interactively
6468 call CMD."
6469 (org-load-modules-maybe)
6470 (unless org-local-vars
6471 (setq org-local-vars (org-get-local-variables)))
6472 (eval (list 'let org-local-vars
6473 (list 'call-interactively (list 'quote cmd)))))
6475 ;;;; Archiving
6477 (defun org-get-category (&optional pos)
6478 "Get the category applying to position POS."
6479 (get-text-property (or pos (point)) 'org-category))
6481 (defun org-refresh-category-properties ()
6482 "Refresh category text properties in the buffer."
6483 (let ((def-cat (cond
6484 ((null org-category)
6485 (if buffer-file-name
6486 (file-name-sans-extension
6487 (file-name-nondirectory buffer-file-name))
6488 "???"))
6489 ((symbolp org-category) (symbol-name org-category))
6490 (t org-category)))
6491 beg end cat pos optionp)
6492 (org-unmodified
6493 (save-excursion
6494 (save-restriction
6495 (widen)
6496 (goto-char (point-min))
6497 (put-text-property (point) (point-max) 'org-category def-cat)
6498 (while (re-search-forward
6499 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6500 (setq pos (match-end 0)
6501 optionp (equal (char-after (match-beginning 0)) ?#)
6502 cat (org-trim (match-string 2)))
6503 (if optionp
6504 (setq beg (point-at-bol) end (point-max))
6505 (org-back-to-heading t)
6506 (setq beg (point) end (org-end-of-subtree t t)))
6507 (put-text-property beg end 'org-category cat)
6508 (goto-char pos)))))))
6511 ;;;; Link Stuff
6513 ;;; Link abbreviations
6515 (defun org-link-expand-abbrev (link)
6516 "Apply replacements as defined in `org-link-abbrev-alist."
6517 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6518 (let* ((key (match-string 1 link))
6519 (as (or (assoc key org-link-abbrev-alist-local)
6520 (assoc key org-link-abbrev-alist)))
6521 (tag (and (match-end 2) (match-string 3 link)))
6522 rpl)
6523 (if (not as)
6524 link
6525 (setq rpl (cdr as))
6526 (cond
6527 ((symbolp rpl) (funcall rpl tag))
6528 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6529 ((string-match "%h" rpl)
6530 (replace-match (url-hexify-string (or tag "")) t t rpl))
6531 (t (concat rpl tag)))))
6532 link))
6534 ;;; Storing and inserting links
6536 (defvar org-insert-link-history nil
6537 "Minibuffer history for links inserted with `org-insert-link'.")
6539 (defvar org-stored-links nil
6540 "Contains the links stored with `org-store-link'.")
6542 (defvar org-store-link-plist nil
6543 "Plist with info about the most recently link created with `org-store-link'.")
6545 (defvar org-link-protocols nil
6546 "Link protocols added to Org-mode using `org-add-link-type'.")
6548 (defvar org-store-link-functions nil
6549 "List of functions that are called to create and store a link.
6550 Each function will be called in turn until one returns a non-nil
6551 value. Each function should check if it is responsible for creating
6552 this link (for example by looking at the major mode).
6553 If not, it must exit and return nil.
6554 If yes, it should return a non-nil value after a calling
6555 `org-store-link-props' with a list of properties and values.
6556 Special properties are:
6558 :type The link prefix. like \"http\". This must be given.
6559 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6560 This is obligatory as well.
6561 :description Optional default description for the second pair
6562 of brackets in an Org-mode link. The user can still change
6563 this when inserting this link into an Org-mode buffer.
6565 In addition to these, any additional properties can be specified
6566 and then used in remember templates.")
6568 (defun org-add-link-type (type &optional follow export)
6569 "Add TYPE to the list of `org-link-types'.
6570 Re-compute all regular expressions depending on `org-link-types'
6572 FOLLOW and EXPORT are two functions.
6574 FOLLOW should take the link path as the single argument and do whatever
6575 is necessary to follow the link, for example find a file or display
6576 a mail message.
6578 EXPORT should format the link path for export to one of the export formats.
6579 It should be a function accepting three arguments:
6581 path the path of the link, the text after the prefix (like \"http:\")
6582 desc the description of the link, if any, nil if there was no description
6583 format the export format, a symbol like `html' or `latex'.
6585 The function may use the FORMAT information to return different values
6586 depending on the format. The return value will be put literally into
6587 the exported file.
6588 Org-mode has a built-in default for exporting links. If you are happy with
6589 this default, there is no need to define an export function for the link
6590 type. For a simple example of an export function, see `org-bbdb.el'."
6591 (add-to-list 'org-link-types type t)
6592 (org-make-link-regexps)
6593 (if (assoc type org-link-protocols)
6594 (setcdr (assoc type org-link-protocols) (list follow export))
6595 (push (list type follow export) org-link-protocols)))
6597 ;;;###autoload
6598 (defun org-store-link (arg)
6599 "\\<org-mode-map>Store an org-link to the current location.
6600 This link is added to `org-stored-links' and can later be inserted
6601 into an org-buffer with \\[org-insert-link].
6603 For some link types, a prefix arg is interpreted:
6604 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6605 For file links, arg negates `org-context-in-file-links'."
6606 (interactive "P")
6607 (org-load-modules-maybe)
6608 (setq org-store-link-plist nil) ; reset
6609 (let (link cpltxt desc description search txt)
6610 (cond
6612 ((run-hook-with-args-until-success 'org-store-link-functions)
6613 (setq link (plist-get org-store-link-plist :link)
6614 desc (or (plist-get org-store-link-plist :description) link)))
6616 ((equal (buffer-name) "*Org Edit Src Example*")
6617 (let (label gc)
6618 (while (or (not label)
6619 (save-excursion
6620 (save-restriction
6621 (widen)
6622 (goto-char (point-min))
6623 (re-search-forward
6624 (regexp-quote (format org-coderef-label-format label))
6625 nil t))))
6626 (when label (message "Label exists already") (sit-for 2))
6627 (setq label (read-string "Code line label: " label)))
6628 (end-of-line 1)
6629 (setq link (format org-coderef-label-format label))
6630 (setq gc (- 79 (length link)))
6631 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6632 (insert link)
6633 (setq link (concat "(" label ")") desc nil)))
6635 ((eq major-mode 'calendar-mode)
6636 (let ((cd (calendar-cursor-to-date)))
6637 (setq link
6638 (format-time-string
6639 (car org-time-stamp-formats)
6640 (apply 'encode-time
6641 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6642 nil nil nil))))
6643 (org-store-link-props :type "calendar" :date cd)))
6645 ((eq major-mode 'w3-mode)
6646 (setq cpltxt (url-view-url t)
6647 link (org-make-link cpltxt))
6648 (org-store-link-props :type "w3" :url (url-view-url t)))
6650 ((eq major-mode 'w3m-mode)
6651 (setq cpltxt (or w3m-current-title w3m-current-url)
6652 link (org-make-link w3m-current-url))
6653 (org-store-link-props :type "w3m" :url (url-view-url t)))
6655 ((setq search (run-hook-with-args-until-success
6656 'org-create-file-search-functions))
6657 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6658 "::" search))
6659 (setq cpltxt (or description link)))
6661 ((eq major-mode 'image-mode)
6662 (setq cpltxt (concat "file:"
6663 (abbreviate-file-name buffer-file-name))
6664 link (org-make-link cpltxt))
6665 (org-store-link-props :type "image" :file buffer-file-name))
6667 ((eq major-mode 'dired-mode)
6668 ;; link to the file in the current line
6669 (setq cpltxt (concat "file:"
6670 (abbreviate-file-name
6671 (expand-file-name
6672 (dired-get-filename nil t))))
6673 link (org-make-link cpltxt)))
6675 ((and buffer-file-name (org-mode-p))
6676 (cond
6677 ((org-in-regexp "<<\\(.*?\\)>>")
6678 (setq cpltxt
6679 (concat "file:"
6680 (abbreviate-file-name buffer-file-name)
6681 "::" (match-string 1))
6682 link (org-make-link cpltxt)))
6683 ((and (featurep 'org-id)
6684 (or (eq org-link-to-org-use-id t)
6685 (and (eq org-link-to-org-use-id 'create-if-interactive)
6686 (interactive-p))
6687 (and org-link-to-org-use-id
6688 (condition-case nil
6689 (org-entry-get nil "ID")
6690 (error nil)))))
6691 ;; We can make a link using the ID.
6692 (setq link (condition-case nil
6693 (prog1 (org-id-store-link)
6694 (setq desc (plist-get org-store-link-plist
6695 :description)))
6696 (error
6697 ;; probably before first headline, link to file only
6698 (concat "file:"
6699 (abbreviate-file-name buffer-file-name))))))
6701 ;; Just link to current headline
6702 (setq cpltxt (concat "file:"
6703 (abbreviate-file-name buffer-file-name)))
6704 ;; Add a context search string
6705 (when (org-xor org-context-in-file-links arg)
6706 (setq txt (cond
6707 ((org-on-heading-p) nil)
6708 ((org-region-active-p)
6709 (buffer-substring (region-beginning) (region-end)))
6710 (t nil)))
6711 (when (or (null txt) (string-match "\\S-" txt))
6712 (setq cpltxt
6713 (concat cpltxt "::"
6714 (condition-case nil
6715 (org-make-org-heading-search-string txt)
6716 (error "")))
6717 desc "NONE")))
6718 (if (string-match "::\\'" cpltxt)
6719 (setq cpltxt (substring cpltxt 0 -2)))
6720 (setq link (org-make-link cpltxt)))))
6722 ((buffer-file-name (buffer-base-buffer))
6723 ;; Just link to this file here.
6724 (setq cpltxt (concat "file:"
6725 (abbreviate-file-name
6726 (buffer-file-name (buffer-base-buffer)))))
6727 ;; Add a context string
6728 (when (org-xor org-context-in-file-links arg)
6729 (setq txt (if (org-region-active-p)
6730 (buffer-substring (region-beginning) (region-end))
6731 (buffer-substring (point-at-bol) (point-at-eol))))
6732 ;; Only use search option if there is some text.
6733 (when (string-match "\\S-" txt)
6734 (setq cpltxt
6735 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6736 desc "NONE")))
6737 (setq link (org-make-link cpltxt)))
6739 ((interactive-p)
6740 (error "Cannot link to a buffer which is not visiting a file"))
6742 (t (setq link nil)))
6744 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6745 (setq link (or link cpltxt)
6746 desc (or desc cpltxt))
6747 (if (equal desc "NONE") (setq desc nil))
6749 (if (and (interactive-p) link)
6750 (progn
6751 (setq org-stored-links
6752 (cons (list link desc) org-stored-links))
6753 (message "Stored: %s" (or desc link)))
6754 (and link (org-make-link-string link desc)))))
6756 (defun org-store-link-props (&rest plist)
6757 "Store link properties, extract names and addresses."
6758 (let (x adr)
6759 (when (setq x (plist-get plist :from))
6760 (setq adr (mail-extract-address-components x))
6761 (setq plist (plist-put plist :fromname (car adr)))
6762 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6763 (when (setq x (plist-get plist :to))
6764 (setq adr (mail-extract-address-components x))
6765 (setq plist (plist-put plist :toname (car adr)))
6766 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6767 (let ((from (plist-get plist :from))
6768 (to (plist-get plist :to)))
6769 (when (and from to org-from-is-user-regexp)
6770 (setq plist
6771 (plist-put plist :fromto
6772 (if (string-match org-from-is-user-regexp from)
6773 (concat "to %t")
6774 (concat "from %f"))))))
6775 (setq org-store-link-plist plist))
6777 (defun org-add-link-props (&rest plist)
6778 "Add these properties to the link property list."
6779 (let (key value)
6780 (while plist
6781 (setq key (pop plist) value (pop plist))
6782 (setq org-store-link-plist
6783 (plist-put org-store-link-plist key value)))))
6785 (defun org-email-link-description (&optional fmt)
6786 "Return the description part of an email link.
6787 This takes information from `org-store-link-plist' and formats it
6788 according to FMT (default from `org-email-link-description-format')."
6789 (setq fmt (or fmt org-email-link-description-format))
6790 (let* ((p org-store-link-plist)
6791 (to (plist-get p :toaddress))
6792 (from (plist-get p :fromaddress))
6793 (table
6794 (list
6795 (cons "%c" (plist-get p :fromto))
6796 (cons "%F" (plist-get p :from))
6797 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6798 (cons "%T" (plist-get p :to))
6799 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6800 (cons "%s" (plist-get p :subject))
6801 (cons "%m" (plist-get p :message-id)))))
6802 (when (string-match "%c" fmt)
6803 ;; Check if the user wrote this message
6804 (if (and org-from-is-user-regexp from to
6805 (save-match-data (string-match org-from-is-user-regexp from)))
6806 (setq fmt (replace-match "to %t" t t fmt))
6807 (setq fmt (replace-match "from %f" t t fmt))))
6808 (org-replace-escapes fmt table)))
6810 (defun org-make-org-heading-search-string (&optional string heading)
6811 "Make search string for STRING or current headline."
6812 (interactive)
6813 (let ((s (or string (org-get-heading))))
6814 (unless (and string (not heading))
6815 ;; We are using a headline, clean up garbage in there.
6816 (if (string-match org-todo-regexp s)
6817 (setq s (replace-match "" t t s)))
6818 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6819 (setq s (replace-match "" t t s)))
6820 (setq s (org-trim s))
6821 (if (string-match (concat "^\\(" org-quote-string "\\|"
6822 org-comment-string "\\)") s)
6823 (setq s (replace-match "" t t s)))
6824 (while (string-match org-ts-regexp s)
6825 (setq s (replace-match "" t t s))))
6826 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6827 (setq s (replace-match " " t t s)))
6828 (or string (setq s (concat "*" s))) ; Add * for headlines
6829 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6831 (defun org-make-link (&rest strings)
6832 "Concatenate STRINGS."
6833 (apply 'concat strings))
6835 (defun org-make-link-string (link &optional description)
6836 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6837 (unless (string-match "\\S-" link)
6838 (error "Empty link"))
6839 (when (stringp description)
6840 ;; Remove brackets from the description, they are fatal.
6841 (while (string-match "\\[" description)
6842 (setq description (replace-match "{" t t description)))
6843 (while (string-match "\\]" description)
6844 (setq description (replace-match "}" t t description))))
6845 (when (equal (org-link-escape link) description)
6846 ;; No description needed, it is identical
6847 (setq description nil))
6848 (when (and (not description)
6849 (not (equal link (org-link-escape link))))
6850 (setq description (org-extract-attributes link)))
6851 (concat "[[" (org-link-escape link) "]"
6852 (if description (concat "[" description "]") "")
6853 "]"))
6855 (defconst org-link-escape-chars
6856 '((?\ . "%20")
6857 (?\[ . "%5B")
6858 (?\] . "%5D")
6859 (?\340 . "%E0") ; `a
6860 (?\342 . "%E2") ; ^a
6861 (?\347 . "%E7") ; ,c
6862 (?\350 . "%E8") ; `e
6863 (?\351 . "%E9") ; 'e
6864 (?\352 . "%EA") ; ^e
6865 (?\356 . "%EE") ; ^i
6866 (?\364 . "%F4") ; ^o
6867 (?\371 . "%F9") ; `u
6868 (?\373 . "%FB") ; ^u
6869 (?\; . "%3B")
6870 (?? . "%3F")
6871 (?= . "%3D")
6872 (?+ . "%2B")
6874 "Association list of escapes for some characters problematic in links.
6875 This is the list that is used for internal purposes.")
6877 (defconst org-link-escape-chars-browser
6878 '((?\ . "%20")) ; 32 for the SPC char
6879 "Association list of escapes for some characters problematic in links.
6880 This is the list that is used before handing over to the browser.")
6882 (defun org-link-escape (text &optional table)
6883 "Escape characters in TEXT that are problematic for links."
6884 (setq table (or table org-link-escape-chars))
6885 (when text
6886 (let ((re (mapconcat (lambda (x) (regexp-quote
6887 (char-to-string (car x))))
6888 table "\\|")))
6889 (while (string-match re text)
6890 (setq text
6891 (replace-match
6892 (cdr (assoc (string-to-char (match-string 0 text))
6893 table))
6894 t t text)))
6895 text)))
6897 (defun org-link-unescape (text &optional table)
6898 "Reverse the action of `org-link-escape'."
6899 (setq table (or table org-link-escape-chars))
6900 (when text
6901 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6902 table "\\|")))
6903 (while (string-match re text)
6904 (setq text
6905 (replace-match
6906 (char-to-string (car (rassoc (match-string 0 text) table)))
6907 t t text)))
6908 text)))
6910 (defun org-xor (a b)
6911 "Exclusive or."
6912 (if a (not b) b))
6914 (defun org-fixup-message-id-for-http (s)
6915 "Replace special characters in a message id, so it can be used in an http query."
6916 (while (string-match "<" s)
6917 (setq s (replace-match "%3C" t t s)))
6918 (while (string-match ">" s)
6919 (setq s (replace-match "%3E" t t s)))
6920 (while (string-match "@" s)
6921 (setq s (replace-match "%40" t t s)))
6924 ;;;###autoload
6925 (defun org-insert-link-global ()
6926 "Insert a link like Org-mode does.
6927 This command can be called in any mode to insert a link in Org-mode syntax."
6928 (interactive)
6929 (org-load-modules-maybe)
6930 (org-run-like-in-org-mode 'org-insert-link))
6932 (defun org-insert-link (&optional complete-file link-location)
6933 "Insert a link. At the prompt, enter the link.
6935 Completion can be used to insert any of the link protocol prefixes like
6936 http or ftp in use.
6938 The history can be used to select a link previously stored with
6939 `org-store-link'. When the empty string is entered (i.e. if you just
6940 press RET at the prompt), the link defaults to the most recently
6941 stored link. As SPC triggers completion in the minibuffer, you need to
6942 use M-SPC or C-q SPC to force the insertion of a space character.
6944 You will also be prompted for a description, and if one is given, it will
6945 be displayed in the buffer instead of the link.
6947 If there is already a link at point, this command will allow you to edit link
6948 and description parts.
6950 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6951 be selected using completion. The path to the file will be relative to the
6952 current directory if the file is in the current directory or a subdirectory.
6953 Otherwise, the link will be the absolute path as completed in the minibuffer
6954 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6955 option `org-link-file-path-type'.
6957 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6958 the current directory or below.
6960 With three \\[universal-argument] prefixes, negate the meaning of
6961 `org-keep-stored-link-after-insertion'.
6963 If `org-make-link-description-function' is non-nil, this function will be
6964 called with the link target, and the result will be the default
6965 link description.
6967 If the LINK-LOCATION parameter is non-nil, this value will be
6968 used as the link location instead of reading one interactively."
6969 (interactive "P")
6970 (let* ((wcf (current-window-configuration))
6971 (region (if (org-region-active-p)
6972 (buffer-substring (region-beginning) (region-end))))
6973 (remove (and region (list (region-beginning) (region-end))))
6974 (desc region)
6975 tmphist ; byte-compile incorrectly complains about this
6976 (link link-location)
6977 entry file)
6978 (cond
6979 (link-location) ; specified by arg, just use it.
6980 ((org-in-regexp org-bracket-link-regexp 1)
6981 ;; We do have a link at point, and we are going to edit it.
6982 (setq remove (list (match-beginning 0) (match-end 0)))
6983 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6984 (setq link (read-string "Link: "
6985 (org-link-unescape
6986 (org-match-string-no-properties 1)))))
6987 ((or (org-in-regexp org-angle-link-re)
6988 (org-in-regexp org-plain-link-re))
6989 ;; Convert to bracket link
6990 (setq remove (list (match-beginning 0) (match-end 0))
6991 link (read-string "Link: "
6992 (org-remove-angle-brackets (match-string 0)))))
6993 ((member complete-file '((4) (16)))
6994 ;; Completing read for file names.
6995 (setq file (read-file-name "File: "))
6996 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6997 (pwd1 (file-name-as-directory (abbreviate-file-name
6998 (expand-file-name ".")))))
6999 (cond
7000 ((equal complete-file '(16))
7001 (setq link (org-make-link
7002 "file:"
7003 (abbreviate-file-name (expand-file-name file)))))
7004 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7005 (setq link (org-make-link "file:" (match-string 1 file))))
7006 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7007 (expand-file-name file))
7008 (setq link (org-make-link
7009 "file:" (match-string 1 (expand-file-name file)))))
7010 (t (setq link (org-make-link "file:" file))))))
7012 ;; Read link, with completion for stored links.
7013 (with-output-to-temp-buffer "*Org Links*"
7014 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7015 (when org-stored-links
7016 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7017 (princ (mapconcat
7018 (lambda (x)
7019 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7020 (reverse org-stored-links) "\n"))))
7021 (let ((cw (selected-window)))
7022 (select-window (get-buffer-window "*Org Links*"))
7023 (setq truncate-lines t)
7024 (org-fit-window-to-buffer)
7025 (select-window cw))
7026 ;; Fake a link history, containing the stored links.
7027 (setq tmphist (append (mapcar 'car org-stored-links)
7028 org-insert-link-history))
7029 (unwind-protect
7030 (setq link
7031 (let ((org-completion-use-ido nil))
7032 (org-completing-read
7033 "Link: "
7034 (append
7035 (mapcar (lambda (x) (list (concat (car x) ":")))
7036 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7037 (mapcar (lambda (x) (list (concat x ":")))
7038 org-link-types))
7039 nil nil nil
7040 'tmphist
7041 (or (car (car org-stored-links))))))
7042 (set-window-configuration wcf)
7043 (kill-buffer "*Org Links*"))
7044 (setq entry (assoc link org-stored-links))
7045 (or entry (push link org-insert-link-history))
7046 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7047 (not org-keep-stored-link-after-insertion))
7048 (setq org-stored-links (delq (assoc link org-stored-links)
7049 org-stored-links)))
7050 (setq desc (or desc (nth 1 entry)))))
7052 (if (string-match org-plain-link-re link)
7053 ;; URL-like link, normalize the use of angular brackets.
7054 (setq link (org-make-link (org-remove-angle-brackets link))))
7056 ;; Check if we are linking to the current file with a search option
7057 ;; If yes, simplify the link by using only the search option.
7058 (when (and buffer-file-name
7059 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7060 (let* ((path (match-string 1 link))
7061 (case-fold-search nil)
7062 (search (match-string 2 link)))
7063 (save-match-data
7064 (if (equal (file-truename buffer-file-name) (file-truename path))
7065 ;; We are linking to this same file, with a search option
7066 (setq link search)))))
7068 ;; Check if we can/should use a relative path. If yes, simplify the link
7069 (when (string-match "^file:\\(.*\\)" link)
7070 (let* ((path (match-string 1 link))
7071 (origpath path)
7072 (case-fold-search nil))
7073 (cond
7074 ((or (eq org-link-file-path-type 'absolute)
7075 (equal complete-file '(16)))
7076 (setq path (abbreviate-file-name (expand-file-name path))))
7077 ((eq org-link-file-path-type 'noabbrev)
7078 (setq path (expand-file-name path)))
7079 ((eq org-link-file-path-type 'relative)
7080 (setq path (file-relative-name path)))
7082 (save-match-data
7083 (if (string-match (concat "^" (regexp-quote
7084 (file-name-as-directory
7085 (expand-file-name "."))))
7086 (expand-file-name path))
7087 ;; We are linking a file with relative path name.
7088 (setq path (substring (expand-file-name path)
7089 (match-end 0)))
7090 (setq path (abbreviate-file-name (expand-file-name path)))))))
7091 (setq link (concat "file:" path))
7092 (if (equal desc origpath)
7093 (setq desc path))))
7095 (if org-make-link-description-function
7096 (setq desc (funcall org-make-link-description-function link desc)))
7098 (setq desc (read-string "Description: " desc))
7099 (unless (string-match "\\S-" desc) (setq desc nil))
7100 (if remove (apply 'delete-region remove))
7101 (insert (org-make-link-string link desc))))
7103 (defun org-completing-read (&rest args)
7104 "Completing-read with SPACE being a normal character."
7105 (let ((minibuffer-local-completion-map
7106 (copy-keymap minibuffer-local-completion-map)))
7107 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7108 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7109 (apply 'org-ido-completing-read args)))
7111 (defun org-completing-read-no-ido (&rest args)
7112 (let (org-completion-use-ido)
7113 (apply 'org-completing-read args)))
7115 (defun org-ido-completing-read (&rest args)
7116 "Completing-read using `ido-mode' speedups if available"
7117 (if (and org-completion-use-ido
7118 (fboundp 'ido-completing-read)
7119 (boundp 'ido-mode) ido-mode
7120 (listp (second args)))
7121 (let ((ido-enter-matching-directory nil))
7122 (apply 'ido-completing-read (concat (car args))
7123 (mapcar (lambda (x) (car x)) (nth 1 args))
7124 (cddr args)))
7125 (apply 'completing-read args)))
7128 (defun org-extract-attributes (s)
7129 "Extract the attributes cookie from a string and set as text property."
7130 (let (a attr (start 0) key value)
7131 (save-match-data
7132 (when (string-match "{{\\([^}]+\\)}}$" s)
7133 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7134 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7135 (setq key (match-string 1 a) value (match-string 2 a)
7136 start (match-end 0)
7137 attr (plist-put attr (intern key) value))))
7138 (org-add-props s nil 'org-attr attr))
7141 (defun org-attributes-to-string (plist)
7142 "Format a property list into an HTML attribute list."
7143 (let ((s "") key value)
7144 (while plist
7145 (setq key (pop plist) value (pop plist))
7146 (and value
7147 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7150 ;;; Opening/following a link
7152 (defvar org-link-search-failed nil)
7154 (defun org-next-link ()
7155 "Move forward to the next link.
7156 If the link is in hidden text, expose it."
7157 (interactive)
7158 (when (and org-link-search-failed (eq this-command last-command))
7159 (goto-char (point-min))
7160 (message "Link search wrapped back to beginning of buffer"))
7161 (setq org-link-search-failed nil)
7162 (let* ((pos (point))
7163 (ct (org-context))
7164 (a (assoc :link ct)))
7165 (if a (goto-char (nth 2 a)))
7166 (if (re-search-forward org-any-link-re nil t)
7167 (progn
7168 (goto-char (match-beginning 0))
7169 (if (org-invisible-p) (org-show-context)))
7170 (goto-char pos)
7171 (setq org-link-search-failed t)
7172 (error "No further link found"))))
7174 (defun org-previous-link ()
7175 "Move backward to the previous link.
7176 If the link is in hidden text, expose it."
7177 (interactive)
7178 (when (and org-link-search-failed (eq this-command last-command))
7179 (goto-char (point-max))
7180 (message "Link search wrapped back to end of buffer"))
7181 (setq org-link-search-failed nil)
7182 (let* ((pos (point))
7183 (ct (org-context))
7184 (a (assoc :link ct)))
7185 (if a (goto-char (nth 1 a)))
7186 (if (re-search-backward org-any-link-re nil t)
7187 (progn
7188 (goto-char (match-beginning 0))
7189 (if (org-invisible-p) (org-show-context)))
7190 (goto-char pos)
7191 (setq org-link-search-failed t)
7192 (error "No further link found"))))
7194 (defun org-translate-link (s)
7195 "Translate a link string if a translation function has been defined."
7196 (if (and org-link-translation-function
7197 (fboundp org-link-translation-function)
7198 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7199 (progn
7200 (setq s (funcall org-link-translation-function
7201 (match-string 1) (match-string 2)))
7202 (concat (car s) ":" (cdr s)))
7205 (defun org-translate-link-from-planner (type path)
7206 "Translate a link from Emacs Planner syntax so that Org can follow it.
7207 This is still an experimental function, your mileage may vary."
7208 (cond
7209 ((member type '("http" "https" "news" "ftp"))
7210 ;; standard Internet links are the same.
7211 nil)
7212 ((and (equal type "irc") (string-match "^//" path))
7213 ;; Planner has two / at the beginning of an irc link, we have 1.
7214 ;; We should have zero, actually....
7215 (setq path (substring path 1)))
7216 ((and (equal type "lisp") (string-match "^/" path))
7217 ;; Planner has a slash, we do not.
7218 (setq type "elisp" path (substring path 1)))
7219 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7220 ;; A typical message link. Planner has the id after the fina slash,
7221 ;; we separate it with a hash mark
7222 (setq path (concat (match-string 1 path) "#"
7223 (org-remove-angle-brackets (match-string 2 path)))))
7225 (cons type path))
7227 (defun org-find-file-at-mouse (ev)
7228 "Open file link or URL at mouse."
7229 (interactive "e")
7230 (mouse-set-point ev)
7231 (org-open-at-point 'in-emacs))
7233 (defun org-open-at-mouse (ev)
7234 "Open file link or URL at mouse."
7235 (interactive "e")
7236 (mouse-set-point ev)
7237 (if (eq major-mode 'org-agenda-mode)
7238 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7239 (org-open-at-point))
7241 (defvar org-window-config-before-follow-link nil
7242 "The window configuration before following a link.
7243 This is saved in case the need arises to restore it.")
7245 (defvar org-open-link-marker (make-marker)
7246 "Marker pointing to the location where `org-open-at-point; was called.")
7248 ;;;###autoload
7249 (defun org-open-at-point-global ()
7250 "Follow a link like Org-mode does.
7251 This command can be called in any mode to follow a link that has
7252 Org-mode syntax."
7253 (interactive)
7254 (org-run-like-in-org-mode 'org-open-at-point))
7256 ;;;###autoload
7257 (defun org-open-link-from-string (s &optional arg)
7258 "Open a link in the string S, as if it was in Org-mode."
7259 (interactive "sLink: \nP")
7260 (with-temp-buffer
7261 (let ((org-inhibit-startup t))
7262 (org-mode)
7263 (insert s)
7264 (goto-char (point-min))
7265 (org-open-at-point arg))))
7267 (defun org-open-at-point (&optional in-emacs)
7268 "Open link at or after point.
7269 If there is no link at point, this function will search forward up to
7270 the end of the current subtree.
7271 Normally, files will be opened by an appropriate application. If the
7272 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7273 With a double prefix argument, try to open outside of Emacs, in the
7274 application the system uses for this file type."
7275 (interactive "P")
7276 (org-load-modules-maybe)
7277 (move-marker org-open-link-marker (point))
7278 (setq org-window-config-before-follow-link (current-window-configuration))
7279 (org-remove-occur-highlights nil nil t)
7280 (cond
7281 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7282 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7283 (org-footnote-action))
7285 (let (type path link line search (pos (point)))
7286 (catch 'match
7287 (save-excursion
7288 (skip-chars-forward "^]\n\r")
7289 (when (org-in-regexp org-bracket-link-regexp)
7290 (setq link (org-extract-attributes
7291 (org-link-unescape (org-match-string-no-properties 1))))
7292 (while (string-match " *\n *" link)
7293 (setq link (replace-match " " t t link)))
7294 (setq link (org-link-expand-abbrev link))
7295 (cond
7296 ((or (file-name-absolute-p link)
7297 (string-match "^\\.\\.?/" link))
7298 (setq type "file" path link))
7299 ((string-match org-link-re-with-space3 link)
7300 (setq type (match-string 1 link) path (match-string 2 link)))
7301 (t (setq type "thisfile" path link)))
7302 (throw 'match t)))
7304 (when (get-text-property (point) 'org-linked-text)
7305 (setq type "thisfile"
7306 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7307 (1+ (point)) (point))
7308 path (buffer-substring
7309 (previous-single-property-change pos 'org-linked-text)
7310 (next-single-property-change pos 'org-linked-text)))
7311 (throw 'match t))
7313 (save-excursion
7314 (when (or (org-in-regexp org-angle-link-re)
7315 (org-in-regexp org-plain-link-re))
7316 (setq type (match-string 1) path (match-string 2))
7317 (throw 'match t)))
7318 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7319 (setq type "tree-match"
7320 path (match-string 1))
7321 (throw 'match t))
7322 (save-excursion
7323 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7324 (setq type "tags"
7325 path (match-string 1))
7326 (while (string-match ":" path)
7327 (setq path (replace-match "+" t t path)))
7328 (throw 'match t))))
7329 (unless path
7330 (error "No link found"))
7331 ;; Remove any trailing spaces in path
7332 (if (string-match " +\\'" path)
7333 (setq path (replace-match "" t t path)))
7334 (if (and org-link-translation-function
7335 (fboundp org-link-translation-function))
7336 ;; Check if we need to translate the link
7337 (let ((tmp (funcall org-link-translation-function type path)))
7338 (setq type (car tmp) path (cdr tmp))))
7340 (cond
7342 ((assoc type org-link-protocols)
7343 (funcall (nth 1 (assoc type org-link-protocols)) path))
7345 ((equal type "mailto")
7346 (let ((cmd (car org-link-mailto-program))
7347 (args (cdr org-link-mailto-program)) args1
7348 (address path) (subject "") a)
7349 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7350 (setq address (match-string 1 path)
7351 subject (org-link-escape (match-string 2 path))))
7352 (while args
7353 (cond
7354 ((not (stringp (car args))) (push (pop args) args1))
7355 (t (setq a (pop args))
7356 (if (string-match "%a" a)
7357 (setq a (replace-match address t t a)))
7358 (if (string-match "%s" a)
7359 (setq a (replace-match subject t t a)))
7360 (push a args1))))
7361 (apply cmd (nreverse args1))))
7363 ((member type '("http" "https" "ftp" "news"))
7364 (browse-url (concat type ":" (org-link-escape
7365 path org-link-escape-chars-browser))))
7367 ((member type '("message"))
7368 (browse-url (concat type ":" path)))
7370 ((string= type "tags")
7371 (org-tags-view in-emacs path))
7372 ((string= type "thisfile")
7373 (if in-emacs
7374 (switch-to-buffer-other-window
7375 (org-get-buffer-for-internal-link (current-buffer)))
7376 (org-mark-ring-push))
7377 (let ((cmd `(org-link-search
7378 ,path
7379 ,(cond ((equal in-emacs '(4)) 'occur)
7380 ((equal in-emacs '(16)) 'org-occur)
7381 (t nil))
7382 ,pos)))
7383 (condition-case nil (eval cmd)
7384 (error (progn (widen) (eval cmd))))))
7386 ((string= type "tree-match")
7387 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7389 ((string= type "file")
7390 (if (string-match "::\\([0-9]+\\)\\'" path)
7391 (setq line (string-to-number (match-string 1 path))
7392 path (substring path 0 (match-beginning 0)))
7393 (if (string-match "::\\(.+\\)\\'" path)
7394 (setq search (match-string 1 path)
7395 path (substring path 0 (match-beginning 0)))))
7396 (if (string-match "[*?{]" (file-name-nondirectory path))
7397 (dired path)
7398 (org-open-file path in-emacs line search)))
7400 ((string= type "news")
7401 (require 'org-gnus)
7402 (org-gnus-follow-link path))
7404 ((string= type "shell")
7405 (let ((cmd path))
7406 (if (or (not org-confirm-shell-link-function)
7407 (funcall org-confirm-shell-link-function
7408 (format "Execute \"%s\" in shell? "
7409 (org-add-props cmd nil
7410 'face 'org-warning))))
7411 (progn
7412 (message "Executing %s" cmd)
7413 (shell-command cmd))
7414 (error "Abort"))))
7416 ((string= type "elisp")
7417 (let ((cmd path))
7418 (if (or (not org-confirm-elisp-link-function)
7419 (funcall org-confirm-elisp-link-function
7420 (format "Execute \"%s\" as elisp? "
7421 (org-add-props cmd nil
7422 'face 'org-warning))))
7423 (message "%s => %s" cmd
7424 (if (equal (string-to-char cmd) ?\()
7425 (eval (read cmd))
7426 (call-interactively (read cmd))))
7427 (error "Abort"))))
7430 (browse-url-at-point))))))
7431 (move-marker org-open-link-marker nil)
7432 (run-hook-with-args 'org-follow-link-hook))
7434 ;;;; Time estimates
7436 (defun org-get-effort (&optional pom)
7437 "Get the effort estimate for the current entry."
7438 (org-entry-get pom org-effort-property))
7440 ;;; File search
7442 (defvar org-create-file-search-functions nil
7443 "List of functions to construct the right search string for a file link.
7444 These functions are called in turn with point at the location to
7445 which the link should point.
7447 A function in the hook should first test if it would like to
7448 handle this file type, for example by checking the major-mode or
7449 the file extension. If it decides not to handle this file, it
7450 should just return nil to give other functions a chance. If it
7451 does handle the file, it must return the search string to be used
7452 when following the link. The search string will be part of the
7453 file link, given after a double colon, and `org-open-at-point'
7454 will automatically search for it. If special measures must be
7455 taken to make the search successful, another function should be
7456 added to the companion hook `org-execute-file-search-functions',
7457 which see.
7459 A function in this hook may also use `setq' to set the variable
7460 `description' to provide a suggestion for the descriptive text to
7461 be used for this link when it gets inserted into an Org-mode
7462 buffer with \\[org-insert-link].")
7464 (defvar org-execute-file-search-functions nil
7465 "List of functions to execute a file search triggered by a link.
7467 Functions added to this hook must accept a single argument, the
7468 search string that was part of the file link, the part after the
7469 double colon. The function must first check if it would like to
7470 handle this search, for example by checking the major-mode or the
7471 file extension. If it decides not to handle this search, it
7472 should just return nil to give other functions a chance. If it
7473 does handle the search, it must return a non-nil value to keep
7474 other functions from trying.
7476 Each function can access the current prefix argument through the
7477 variable `current-prefix-argument'. Note that a single prefix is
7478 used to force opening a link in Emacs, so it may be good to only
7479 use a numeric or double prefix to guide the search function.
7481 In case this is needed, a function in this hook can also restore
7482 the window configuration before `org-open-at-point' was called using:
7484 (set-window-configuration org-window-config-before-follow-link)")
7486 (defun org-link-search (s &optional type avoid-pos)
7487 "Search for a link search option.
7488 If S is surrounded by forward slashes, it is interpreted as a
7489 regular expression. In org-mode files, this will create an `org-occur'
7490 sparse tree. In ordinary files, `occur' will be used to list matches.
7491 If the current buffer is in `dired-mode', grep will be used to search
7492 in all files. If AVOID-POS is given, ignore matches near that position."
7493 (let ((case-fold-search t)
7494 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7495 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7496 (append '(("") (" ") ("\t") ("\n"))
7497 org-emphasis-alist)
7498 "\\|") "\\)"))
7499 (pos (point))
7500 (pre nil) (post nil)
7501 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7502 (cond
7503 ;; First check if there are any special
7504 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7505 ;; Now try the builtin stuff
7506 ((save-excursion
7507 (goto-char (point-min))
7508 (and
7509 (re-search-forward
7510 (concat "<<" (regexp-quote s0) ">>") nil t)
7511 (setq type 'dedicated
7512 pos (match-beginning 0))))
7513 ;; There is an exact target for this
7514 (goto-char pos))
7515 ((and (string-match "^(\\(.*\\))$" s0)
7516 (save-excursion
7517 (goto-char (point-min))
7518 (and
7519 (re-search-forward
7520 (concat "[^[]" (regexp-quote
7521 (format org-coderef-label-format
7522 (match-string 1 s0))))
7523 nil t)
7524 (setq type 'dedicated
7525 pos (1+ (match-beginning 0))))))
7526 ;; There is a coderef target for this
7527 (goto-char pos))
7528 ((string-match "^/\\(.*\\)/$" s)
7529 ;; A regular expression
7530 (cond
7531 ((org-mode-p)
7532 (org-occur (match-string 1 s)))
7533 ;;((eq major-mode 'dired-mode)
7534 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7535 (t (org-do-occur (match-string 1 s)))))
7537 ;; A normal search strings
7538 (when (equal (string-to-char s) ?*)
7539 ;; Anchor on headlines, post may include tags.
7540 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7541 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7542 s (substring s 1)))
7543 (remove-text-properties
7544 0 (length s)
7545 '(face nil mouse-face nil keymap nil fontified nil) s)
7546 ;; Make a series of regular expressions to find a match
7547 (setq words (org-split-string s "[ \n\r\t]+")
7549 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7550 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7551 "\\)" markers)
7552 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7553 re2a (concat "[ \t\r\n]" re2a_)
7554 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7555 re4 (concat "[^a-zA-Z_]" re4_)
7557 re1 (concat pre re2 post)
7558 re3 (concat pre (if pre re4_ re4) post)
7559 re5 (concat pre ".*" re4)
7560 re2 (concat pre re2)
7561 re2a (concat pre (if pre re2a_ re2a))
7562 re4 (concat pre (if pre re4_ re4))
7563 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7564 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7565 re5 "\\)"
7567 (cond
7568 ((eq type 'org-occur) (org-occur reall))
7569 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7570 (t (goto-char (point-min))
7571 (setq type 'fuzzy)
7572 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7573 (org-search-not-self 1 re1 nil t)
7574 (org-search-not-self 1 re2 nil t)
7575 (org-search-not-self 1 re2a nil t)
7576 (org-search-not-self 1 re3 nil t)
7577 (org-search-not-self 1 re4 nil t)
7578 (org-search-not-self 1 re5 nil t)
7580 (goto-char (match-beginning 1))
7581 (goto-char pos)
7582 (error "No match")))))
7584 ;; Normal string-search
7585 (goto-char (point-min))
7586 (if (search-forward s nil t)
7587 (goto-char (match-beginning 0))
7588 (error "No match"))))
7589 (and (org-mode-p) (org-show-context 'link-search))
7590 type))
7592 (defun org-search-not-self (group &rest args)
7593 "Execute `re-search-forward', but only accept matches that do not
7594 enclose the position of `org-open-link-marker'."
7595 (let ((m org-open-link-marker))
7596 (catch 'exit
7597 (while (apply 're-search-forward args)
7598 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7599 (goto-char (match-end group))
7600 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7601 (> (match-beginning 0) (marker-position m))
7602 (< (match-end 0) (marker-position m)))
7603 (save-match-data
7604 (or (not (org-in-regexp
7605 org-bracket-link-analytic-regexp 1))
7606 (not (match-end 4)) ; no description
7607 (and (<= (match-beginning 4) (point))
7608 (>= (match-end 4) (point))))))
7609 (throw 'exit (point))))))))
7611 (defun org-get-buffer-for-internal-link (buffer)
7612 "Return a buffer to be used for displaying the link target of internal links."
7613 (cond
7614 ((not org-display-internal-link-with-indirect-buffer)
7615 buffer)
7616 ((string-match "(Clone)$" (buffer-name buffer))
7617 (message "Buffer is already a clone, not making another one")
7618 ;; we also do not modify visibility in this case
7619 buffer)
7620 (t ; make a new indirect buffer for displaying the link
7621 (let* ((bn (buffer-name buffer))
7622 (ibn (concat bn "(Clone)"))
7623 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7624 (with-current-buffer ib (org-overview))
7625 ib))))
7627 (defun org-do-occur (regexp &optional cleanup)
7628 "Call the Emacs command `occur'.
7629 If CLEANUP is non-nil, remove the printout of the regular expression
7630 in the *Occur* buffer. This is useful if the regex is long and not useful
7631 to read."
7632 (occur regexp)
7633 (when cleanup
7634 (let ((cwin (selected-window)) win beg end)
7635 (when (setq win (get-buffer-window "*Occur*"))
7636 (select-window win))
7637 (goto-char (point-min))
7638 (when (re-search-forward "match[a-z]+" nil t)
7639 (setq beg (match-end 0))
7640 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7641 (setq end (1- (match-beginning 0)))))
7642 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7643 (goto-char (point-min))
7644 (select-window cwin))))
7646 ;;; The mark ring for links jumps
7648 (defvar org-mark-ring nil
7649 "Mark ring for positions before jumps in Org-mode.")
7650 (defvar org-mark-ring-last-goto nil
7651 "Last position in the mark ring used to go back.")
7652 ;; Fill and close the ring
7653 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7654 (loop for i from 1 to org-mark-ring-length do
7655 (push (make-marker) org-mark-ring))
7656 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7657 org-mark-ring)
7659 (defun org-mark-ring-push (&optional pos buffer)
7660 "Put the current position or POS into the mark ring and rotate it."
7661 (interactive)
7662 (setq pos (or pos (point)))
7663 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7664 (move-marker (car org-mark-ring)
7665 (or pos (point))
7666 (or buffer (current-buffer)))
7667 (message "%s"
7668 (substitute-command-keys
7669 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7671 (defun org-mark-ring-goto (&optional n)
7672 "Jump to the previous position in the mark ring.
7673 With prefix arg N, jump back that many stored positions. When
7674 called several times in succession, walk through the entire ring.
7675 Org-mode commands jumping to a different position in the current file,
7676 or to another Org-mode file, automatically push the old position
7677 onto the ring."
7678 (interactive "p")
7679 (let (p m)
7680 (if (eq last-command this-command)
7681 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7682 (setq p org-mark-ring))
7683 (setq org-mark-ring-last-goto p)
7684 (setq m (car p))
7685 (switch-to-buffer (marker-buffer m))
7686 (goto-char m)
7687 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7689 (defun org-remove-angle-brackets (s)
7690 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7691 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7693 (defun org-add-angle-brackets (s)
7694 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7695 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7697 (defun org-remove-double-quotes (s)
7698 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7699 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7702 ;;; Following specific links
7704 (defun org-follow-timestamp-link ()
7705 (cond
7706 ((org-at-date-range-p t)
7707 (let ((org-agenda-start-on-weekday)
7708 (t1 (match-string 1))
7709 (t2 (match-string 2)))
7710 (setq t1 (time-to-days (org-time-string-to-time t1))
7711 t2 (time-to-days (org-time-string-to-time t2)))
7712 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7713 ((org-at-timestamp-p t)
7714 (org-agenda-list nil (time-to-days (org-time-string-to-time
7715 (substring (match-string 1) 0 10)))
7717 (t (error "This should not happen"))))
7720 ;;; Following file links
7721 (defvar org-wait nil)
7722 (defun org-open-file (path &optional in-emacs line search)
7723 "Open the file at PATH.
7724 First, this expands any special file name abbreviations. Then the
7725 configuration variable `org-file-apps' is checked if it contains an
7726 entry for this file type, and if yes, the corresponding command is launched.
7728 If no application is found, Emacs simply visits the file.
7730 With optional prefix argument IN-EMACS, Emacs will visit the file.
7731 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7732 and o use an external application to visit the file.
7734 Optional LINE specifies a line to go to, optional SEARCH a string to
7735 search for. If LINE or SEARCH is given, the file will always be
7736 opened in Emacs.
7737 If the file does not exist, an error is thrown."
7738 (setq in-emacs (or in-emacs line search))
7739 (let* ((file (if (equal path "")
7740 buffer-file-name
7741 (substitute-in-file-name (expand-file-name path))))
7742 (apps (append org-file-apps (org-default-apps)))
7743 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7744 (dirp (if remp nil (file-directory-p file)))
7745 (file (if (and dirp org-open-directory-means-index-dot-org)
7746 (concat (file-name-as-directory file) "index.org")
7747 file))
7748 (a-m-a-p (assq 'auto-mode apps))
7749 (dfile (downcase file))
7750 (old-buffer (current-buffer))
7751 (old-pos (point))
7752 (old-mode major-mode)
7753 ext cmd)
7754 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7755 (setq ext (match-string 1 dfile))
7756 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7757 (setq ext (match-string 1 dfile))))
7758 (cond
7759 ((equal in-emacs '(16))
7760 (setq cmd (cdr (assoc 'system apps))))
7761 (in-emacs (setq cmd 'emacs))
7763 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7764 (and dirp (cdr (assoc 'directory apps)))
7765 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7766 'string-match)
7767 (cdr (assoc ext apps))
7768 (cdr (assoc t apps))))))
7769 (when (eq cmd 'system)
7770 (setq cmd (cdr (assoc 'system apps))))
7771 (when (eq cmd 'default)
7772 (setq cmd (cdr (assoc t apps))))
7773 (when (eq cmd 'mailcap)
7774 (require 'mailcap)
7775 (mailcap-parse-mailcaps)
7776 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7777 (command (mailcap-mime-info mime-type)))
7778 (if (stringp command)
7779 (setq cmd command)
7780 (setq cmd 'emacs))))
7781 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7782 (not (file-exists-p file))
7783 (not org-open-non-existing-files))
7784 (error "No such file: %s" file))
7785 (cond
7786 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7787 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7788 (while (string-match "['\"]%s['\"]" cmd)
7789 (setq cmd (replace-match "%s" t t cmd)))
7790 (while (string-match "%s" cmd)
7791 (setq cmd (replace-match
7792 (save-match-data
7793 (shell-quote-argument
7794 (convert-standard-filename file)))
7795 t t cmd)))
7796 (save-window-excursion
7797 (start-process-shell-command cmd nil cmd)
7798 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7800 ((or (stringp cmd)
7801 (eq cmd 'emacs))
7802 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7803 (widen)
7804 (if line (goto-line line)
7805 (if search (org-link-search search))))
7806 ((consp cmd)
7807 (let ((file (convert-standard-filename file)))
7808 (eval cmd)))
7809 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7810 (and (org-mode-p) (eq old-mode 'org-mode)
7811 (or (not (equal old-buffer (current-buffer)))
7812 (not (equal old-pos (point))))
7813 (org-mark-ring-push old-pos old-buffer))))
7815 (defun org-default-apps ()
7816 "Return the default applications for this operating system."
7817 (cond
7818 ((eq system-type 'darwin)
7819 org-file-apps-defaults-macosx)
7820 ((eq system-type 'windows-nt)
7821 org-file-apps-defaults-windowsnt)
7822 (t org-file-apps-defaults-gnu)))
7824 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7825 "Convert extensions to regular expressions in the cars of LIST.
7826 Also, weed out any non-string entries, because the return value is used
7827 only for regexp matching.
7828 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7829 point to the symbol `emacs', indicating that the file should
7830 be opened in Emacs."
7831 (append
7832 (delq nil
7833 (mapcar (lambda (x)
7834 (if (not (stringp (car x)))
7836 (if (string-match "\\W" (car x))
7838 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7839 list))
7840 (if add-auto-mode
7841 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7843 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7844 (defun org-file-remote-p (file)
7845 "Test whether FILE specifies a location on a remote system.
7846 Return non-nil if the location is indeed remote.
7848 For example, the filename \"/user@host:/foo\" specifies a location
7849 on the system \"/user@host:\"."
7850 (cond ((fboundp 'file-remote-p)
7851 (file-remote-p file))
7852 ((fboundp 'tramp-handle-file-remote-p)
7853 (tramp-handle-file-remote-p file))
7854 ((and (boundp 'ange-ftp-name-format)
7855 (string-match (car ange-ftp-name-format) file))
7857 (t nil)))
7860 ;;;; Refiling
7862 (defun org-get-org-file ()
7863 "Read a filename, with default directory `org-directory'."
7864 (let ((default (or org-default-notes-file remember-data-file)))
7865 (read-file-name (format "File name [%s]: " default)
7866 (file-name-as-directory org-directory)
7867 default)))
7869 (defun org-notes-order-reversed-p ()
7870 "Check if the current file should receive notes in reversed order."
7871 (cond
7872 ((not org-reverse-note-order) nil)
7873 ((eq t org-reverse-note-order) t)
7874 ((not (listp org-reverse-note-order)) nil)
7875 (t (catch 'exit
7876 (let ((all org-reverse-note-order)
7877 entry)
7878 (while (setq entry (pop all))
7879 (if (string-match (car entry) buffer-file-name)
7880 (throw 'exit (cdr entry))))
7881 nil)))))
7883 (defvar org-refile-target-table nil
7884 "The list of refile targets, created by `org-refile'.")
7886 (defvar org-agenda-new-buffers nil
7887 "Buffers created to visit agenda files.")
7889 (defun org-get-refile-targets (&optional default-buffer)
7890 "Produce a table with refile targets."
7891 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7892 targets txt re files f desc descre fast-path-p level)
7893 (message "Getting targets...")
7894 (with-current-buffer (or default-buffer (current-buffer))
7895 (while (setq entry (pop entries))
7896 (setq files (car entry) desc (cdr entry))
7897 (setq fast-path-p nil)
7898 (cond
7899 ((null files) (setq files (list (current-buffer))))
7900 ((eq files 'org-agenda-files)
7901 (setq files (org-agenda-files 'unrestricted)))
7902 ((and (symbolp files) (fboundp files))
7903 (setq files (funcall files)))
7904 ((and (symbolp files) (boundp files))
7905 (setq files (symbol-value files))))
7906 (if (stringp files) (setq files (list files)))
7907 (cond
7908 ((eq (car desc) :tag)
7909 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7910 ((eq (car desc) :todo)
7911 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7912 ((eq (car desc) :regexp)
7913 (setq descre (cdr desc)))
7914 ((eq (car desc) :level)
7915 (setq descre (concat "^\\*\\{" (number-to-string
7916 (if org-odd-levels-only
7917 (1- (* 2 (cdr desc)))
7918 (cdr desc)))
7919 "\\}[ \t]")))
7920 ((eq (car desc) :maxlevel)
7921 (setq fast-path-p t)
7922 (setq descre (concat "^\\*\\{1," (number-to-string
7923 (if org-odd-levels-only
7924 (1- (* 2 (cdr desc)))
7925 (cdr desc)))
7926 "\\}[ \t]")))
7927 (t (error "Bad refiling target description %s" desc)))
7928 (while (setq f (pop files))
7929 (save-excursion
7930 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7931 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7932 (setq f (expand-file-name f))
7933 (save-excursion
7934 (save-restriction
7935 (widen)
7936 (goto-char (point-min))
7937 (while (re-search-forward descre nil t)
7938 (goto-char (point-at-bol))
7939 (when (looking-at org-complex-heading-regexp)
7940 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7941 txt (org-link-display-format (match-string 4))
7942 re (concat "^" (regexp-quote
7943 (buffer-substring (match-beginning 1)
7944 (match-end 4)))))
7945 (if (match-end 5) (setq re (concat re "[ \t]+"
7946 (regexp-quote
7947 (match-string 5)))))
7948 (setq re (concat re "[ \t]*$"))
7949 (when org-refile-use-outline-path
7950 (setq txt (mapconcat 'org-protect-slash
7951 (append
7952 (if (eq org-refile-use-outline-path 'file)
7953 (list (file-name-nondirectory
7954 (buffer-file-name (buffer-base-buffer))))
7955 (if (eq org-refile-use-outline-path 'full-file-path)
7956 (list (buffer-file-name (buffer-base-buffer)))))
7957 (org-get-outline-path fast-path-p level txt)
7958 (list txt))
7959 "/")))
7960 (push (list txt f re (point)) targets))
7961 (goto-char (point-at-eol))))))))
7962 (message "Getting targets...done")
7963 (nreverse targets))))
7965 (defun org-protect-slash (s)
7966 (while (string-match "/" s)
7967 (setq s (replace-match "\\" t t s)))
7970 (defvar org-olpa (make-vector 20 nil))
7972 (defun org-get-outline-path (&optional fastp level heading)
7973 "Return the outline path to the current entry, as a list."
7974 (if fastp
7975 (progn
7976 (if (> level 19)
7977 (error "Outline path failure, more than 19 levels."))
7978 (loop for i from level upto 19 do
7979 (aset org-olpa i nil))
7980 (prog1
7981 (delq nil (append org-olpa nil))
7982 (aset org-olpa level heading)))
7983 (let (rtn)
7984 (save-excursion
7985 (while (org-up-heading-safe)
7986 (when (looking-at org-complex-heading-regexp)
7987 (push (org-match-string-no-properties 4) rtn)))
7988 rtn))))
7990 (defvar org-refile-history nil
7991 "History for refiling operations.")
7993 (defun org-refile (&optional goto default-buffer)
7994 "Move the entry at point to another heading.
7995 The list of target headings is compiled using the information in
7996 `org-refile-targets', which see. This list is created before each use
7997 and will therefore always be up-to-date.
7999 At the target location, the entry is filed as a subitem of the target heading.
8000 Depending on `org-reverse-note-order', the new subitem will either be the
8001 first or the last subitem.
8003 If there is an active region, all entries in that region will be moved.
8004 However, the region must fulfil the requirement that the first heading
8005 is the first one sets the top-level of the moved text - at most siblings
8006 below it are allowed.
8008 With prefix arg GOTO, the command will only visit the target location,
8009 not actually move anything.
8010 With a double prefix `C-u C-u', go to the location where the last refiling
8011 operation has put the subtree."
8012 (interactive "P")
8013 (let* ((cbuf (current-buffer))
8014 (regionp (org-region-active-p))
8015 (region-start (and regionp (region-beginning)))
8016 (region-end (and regionp (region-end)))
8017 (region-length (and regionp (- region-end region-start)))
8018 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8019 pos it nbuf file re level reversed)
8020 (when regionp (goto-char region-start)
8021 (unless (org-kill-is-subtree-p
8022 (buffer-substring region-start region-end))
8023 (error "The region is not a (sequence of) subtree(s)")))
8024 (if (equal goto '(16))
8025 (org-refile-goto-last-stored)
8026 (when (setq it (org-refile-get-location
8027 (if goto "Goto: " "Refile to: ") default-buffer))
8028 (setq file (nth 1 it)
8029 re (nth 2 it)
8030 pos (nth 3 it))
8031 (if (and (equal (buffer-file-name) file)
8032 (if regionp
8033 (and (>= pos region-start)
8034 (<= pos region-end))
8035 (and (>= pos (point))
8036 (< pos (save-excursion
8037 (org-end-of-subtree t t))))))
8038 (error "Cannot refile to position inside the tree or region"))
8040 (setq nbuf (or (find-buffer-visiting file)
8041 (find-file-noselect file)))
8042 (if goto
8043 (progn
8044 (switch-to-buffer nbuf)
8045 (goto-char pos)
8046 (org-show-context 'org-goto))
8047 (if regionp
8048 (progn
8049 (kill-new (buffer-substring region-start region-end))
8050 (org-save-markers-in-region region-start region-end))
8051 (org-copy-subtree 1 nil t))
8052 (save-excursion
8053 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8054 (find-file-noselect file))))
8055 (setq reversed (org-notes-order-reversed-p))
8056 (save-excursion
8057 (save-restriction
8058 (widen)
8059 (goto-char pos)
8060 (looking-at outline-regexp)
8061 (setq level (org-get-valid-level (funcall outline-level) 1))
8062 (goto-char
8063 (if reversed
8064 (or (outline-next-heading) (point-max))
8065 (or (save-excursion (outline-get-next-sibling))
8066 (org-end-of-subtree t t)
8067 (point-max))))
8068 (if (not (bolp)) (newline))
8069 (bookmark-set "org-refile-last-stored")
8070 (org-paste-subtree level))))
8071 (if regionp
8072 (delete-region (point) (+ (point) region-length))
8073 (org-cut-subtree))
8074 (setq org-markers-to-move nil)
8075 (message "Refiled to \"%s\"" (car it)))))))
8077 (defun org-refile-goto-last-stored ()
8078 "Go to the location where the last refile was stored."
8079 (interactive)
8080 (bookmark-jump "org-refile-last-stored")
8081 (message "This is the location of the last refile"))
8083 (defun org-refile-get-location (&optional prompt default-buffer)
8084 "Prompt the user for a refile location, using PROMPT."
8085 (let ((org-refile-targets org-refile-targets)
8086 (org-refile-use-outline-path org-refile-use-outline-path))
8087 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8088 (unless org-refile-target-table
8089 (error "No refile targets"))
8090 (let* ((cbuf (current-buffer))
8091 (partial-completion-mode nil)
8092 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8093 (cfunc (if (and org-refile-use-outline-path
8094 org-outline-path-complete-in-steps)
8095 'org-olpath-completing-read
8096 'org-ido-completing-read))
8097 (extra (if org-refile-use-outline-path "/" ""))
8098 (filename (and cfn (expand-file-name cfn)))
8099 (tbl (mapcar
8100 (lambda (x)
8101 (if (not (equal filename (nth 1 x)))
8102 (cons (concat (car x) extra " ("
8103 (file-name-nondirectory (nth 1 x)) ")")
8104 (cdr x))
8105 (cons (concat (car x) extra) (cdr x))))
8106 org-refile-target-table))
8107 (completion-ignore-case t))
8108 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8109 tbl)))
8111 (defun org-olpath-completing-read (prompt collection &rest args)
8112 "Read an outline path like a file name."
8113 (let ((thetable collection)
8114 (org-completion-use-ido nil)) ; does not work with ido.
8115 (apply
8116 'org-ido-completing-read prompt
8117 (lambda (string predicate &optional flag)
8118 (let (rtn r f (l (length string)))
8119 (cond
8120 ((eq flag nil)
8121 ;; try completion
8122 (try-completion string thetable))
8123 ((eq flag t)
8124 ;; all-completions
8125 (setq rtn (all-completions string thetable predicate))
8126 (mapcar
8127 (lambda (x)
8128 (setq r (substring x l))
8129 (if (string-match " ([^)]*)$" x)
8130 (setq f (match-string 0 x))
8131 (setq f ""))
8132 (if (string-match "/" r)
8133 (concat string (substring r 0 (match-end 0)) f)
8135 rtn))
8136 ((eq flag 'lambda)
8137 ;; exact match?
8138 (assoc string thetable)))
8140 args)))
8142 ;;;; Dynamic blocks
8144 (defun org-find-dblock (name)
8145 "Find the first dynamic block with name NAME in the buffer.
8146 If not found, stay at current position and return nil."
8147 (let (pos)
8148 (save-excursion
8149 (goto-char (point-min))
8150 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8151 nil t)
8152 (match-beginning 0))))
8153 (if pos (goto-char pos))
8154 pos))
8156 (defconst org-dblock-start-re
8157 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8158 "Matches the startline of a dynamic block, with parameters.")
8160 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8161 "Matches the end of a dynamic block.")
8163 (defun org-create-dblock (plist)
8164 "Create a dynamic block section, with parameters taken from PLIST.
8165 PLIST must contain a :name entry which is used as name of the block."
8166 (unless (bolp) (newline))
8167 (let ((name (plist-get plist :name)))
8168 (insert "#+BEGIN: " name)
8169 (while plist
8170 (if (eq (car plist) :name)
8171 (setq plist (cddr plist))
8172 (insert " " (prin1-to-string (pop plist)))))
8173 (insert "\n\n#+END:\n")
8174 (beginning-of-line -2)))
8176 (defun org-prepare-dblock ()
8177 "Prepare dynamic block for refresh.
8178 This empties the block, puts the cursor at the insert position and returns
8179 the property list including an extra property :name with the block name."
8180 (unless (looking-at org-dblock-start-re)
8181 (error "Not at a dynamic block"))
8182 (let* ((begdel (1+ (match-end 0)))
8183 (name (org-no-properties (match-string 1)))
8184 (params (append (list :name name)
8185 (read (concat "(" (match-string 3) ")")))))
8186 (unless (re-search-forward org-dblock-end-re nil t)
8187 (error "Dynamic block not terminated"))
8188 (setq params
8189 (append params
8190 (list :content (buffer-substring
8191 begdel (match-beginning 0)))))
8192 (delete-region begdel (match-beginning 0))
8193 (goto-char begdel)
8194 (open-line 1)
8195 params))
8197 (defun org-map-dblocks (&optional command)
8198 "Apply COMMAND to all dynamic blocks in the current buffer.
8199 If COMMAND is not given, use `org-update-dblock'."
8200 (let ((cmd (or command 'org-update-dblock))
8201 pos)
8202 (save-excursion
8203 (goto-char (point-min))
8204 (while (re-search-forward org-dblock-start-re nil t)
8205 (goto-char (setq pos (match-beginning 0)))
8206 (condition-case nil
8207 (funcall cmd)
8208 (error (message "Error during update of dynamic block")))
8209 (goto-char pos)
8210 (unless (re-search-forward org-dblock-end-re nil t)
8211 (error "Dynamic block not terminated"))))))
8213 (defun org-dblock-update (&optional arg)
8214 "User command for updating dynamic blocks.
8215 Update the dynamic block at point. With prefix ARG, update all dynamic
8216 blocks in the buffer."
8217 (interactive "P")
8218 (if arg
8219 (org-update-all-dblocks)
8220 (or (looking-at org-dblock-start-re)
8221 (org-beginning-of-dblock))
8222 (org-update-dblock)))
8224 (defun org-update-dblock ()
8225 "Update the dynamic block at point
8226 This means to empty the block, parse for parameters and then call
8227 the correct writing function."
8228 (save-window-excursion
8229 (let* ((pos (point))
8230 (line (org-current-line))
8231 (params (org-prepare-dblock))
8232 (name (plist-get params :name))
8233 (cmd (intern (concat "org-dblock-write:" name))))
8234 (message "Updating dynamic block `%s' at line %d..." name line)
8235 (funcall cmd params)
8236 (message "Updating dynamic block `%s' at line %d...done" name line)
8237 (goto-char pos))))
8239 (defun org-beginning-of-dblock ()
8240 "Find the beginning of the dynamic block at point.
8241 Error if there is no such block at point."
8242 (let ((pos (point))
8243 beg)
8244 (end-of-line 1)
8245 (if (and (re-search-backward org-dblock-start-re nil t)
8246 (setq beg (match-beginning 0))
8247 (re-search-forward org-dblock-end-re nil t)
8248 (> (match-end 0) pos))
8249 (goto-char beg)
8250 (goto-char pos)
8251 (error "Not in a dynamic block"))))
8253 (defun org-update-all-dblocks ()
8254 "Update all dynamic blocks in the buffer.
8255 This function can be used in a hook."
8256 (when (org-mode-p)
8257 (org-map-dblocks 'org-update-dblock)))
8260 ;;;; Completion
8262 (defconst org-additional-option-like-keywords
8263 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8264 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8265 "BEGIN_EXAMPLE" "END_EXAMPLE"
8266 "BEGIN_QUOTE" "END_QUOTE"
8267 "BEGIN_VERSE" "END_VERSE"
8268 "BEGIN_SRC" "END_SRC"
8269 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8271 (defcustom org-structure-template-alist
8273 ("s" "#+begin_src ?\n\n#+end_src"
8274 "<src lang=\"?\">\n\n</src>")
8275 ("e" "#+begin_example\n?\n#+end_example"
8276 "<example>\n?\n</example>")
8277 ("q" "#+begin_quote\n?\n#+end_quote"
8278 "<quote>\n?\n</quote>")
8279 ("v" "#+begin_verse\n?\n#+end_verse"
8280 "<verse>\n?\n/verse>")
8281 ("l" "#+begin_latex\n?\n#+end_latex"
8282 "<literal style=\"latex\">\n?\n</literal>")
8283 ("L" "#+latex: "
8284 "<literal style=\"latex\">?</literal>")
8285 ("h" "#+begin_html\n?\n#+end_html"
8286 "<literal style=\"html\">\n?\n</literal>")
8287 ("H" "#+html: "
8288 "<literal style=\"html\">?</literal>")
8289 ("a" "#+begin_ascii\n?\n#+end_ascii")
8290 ("A" "#+ascii: ")
8291 ("i" "#+include %file ?"
8292 "<include file=%file markup=\"?\">")
8294 "Structure completion elements.
8295 This is a list of abbreviation keys and values. The value gets inserted
8296 it you type @samp{.} followed by the key and then the completion key,
8297 usually `M-TAB'. %file will be replaced by a file name after prompting
8298 for the file using completion.
8299 There are two templates for each key, the first uses the original Org syntax,
8300 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8301 the default when the /org-mtags.el/ module has been loaded. See also the
8302 variable `org-mtags-prefer-muse-templates'.
8303 This is an experimental feature, it is undecided if it is going to stay in."
8304 :group 'org-completion
8305 :type '(repeat
8306 (string :tag "Key")
8307 (string :tag "Template")
8308 (string :tag "Muse Template")))
8310 (defun org-try-structure-completion ()
8311 "Try to complete a structure template before point.
8312 This looks for strings like \"<e\" on an otherwise empty line and
8313 expands them."
8314 (let ((l (buffer-substring (point-at-bol) (point)))
8316 (when (and (looking-at "[ \t]*$")
8317 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8318 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8319 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8320 (match-beginning 1)) a)
8321 t)))
8323 (defun org-complete-expand-structure-template (start cell)
8324 "Expand a structure template."
8325 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8326 (rpl (nth (if musep 2 1) cell)))
8327 (delete-region start (point))
8328 (when (string-match "\\`#\\+" rpl)
8329 (cond
8330 ((bolp))
8331 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8332 (delete-region (point-at-bol) (point)))
8333 (t (newline))))
8334 (setq start (point))
8335 (if (string-match "%file" rpl)
8336 (setq rpl (replace-match
8337 (concat
8338 "\""
8339 (save-match-data
8340 (abbreviate-file-name (read-file-name "Include file: ")))
8341 "\"")
8342 t t rpl)))
8343 (insert rpl)
8344 (if (re-search-backward "\\?" start t) (delete-char 1))))
8347 (defun org-complete (&optional arg)
8348 "Perform completion on word at point.
8349 At the beginning of a headline, this completes TODO keywords as given in
8350 `org-todo-keywords'.
8351 If the current word is preceded by a backslash, completes the TeX symbols
8352 that are supported for HTML support.
8353 If the current word is preceded by \"#+\", completes special words for
8354 setting file options.
8355 In the line after \"#+STARTUP:, complete valid keywords.\"
8356 At all other locations, this simply calls the value of
8357 `org-completion-fallback-command'."
8358 (interactive "P")
8359 (org-without-partial-completion
8360 (catch 'exit
8361 (let* ((a nil)
8362 (end (point))
8363 (beg1 (save-excursion
8364 (skip-chars-backward (org-re "[:alnum:]_@"))
8365 (point)))
8366 (beg (save-excursion
8367 (skip-chars-backward "a-zA-Z0-9_:$")
8368 (point)))
8369 (confirm (lambda (x) (stringp (car x))))
8370 (searchhead (equal (char-before beg) ?*))
8371 (struct
8372 (when (and (member (char-before beg1) '(?. ?<))
8373 (setq a (assoc (buffer-substring beg1 (point))
8374 org-structure-template-alist)))
8375 (org-complete-expand-structure-template (1- beg1) a)
8376 (throw 'exit t)))
8377 (tag (and (equal (char-before beg1) ?:)
8378 (equal (char-after (point-at-bol)) ?*)))
8379 (prop (and (equal (char-before beg1) ?:)
8380 (not (equal (char-after (point-at-bol)) ?*))))
8381 (texp (equal (char-before beg) ?\\))
8382 (link (equal (char-before beg) ?\[))
8383 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8384 beg)
8385 "#+"))
8386 (startup (string-match "^#\\+STARTUP:.*"
8387 (buffer-substring (point-at-bol) (point))))
8388 (completion-ignore-case opt)
8389 (type nil)
8390 (tbl nil)
8391 (table (cond
8392 (opt
8393 (setq type :opt)
8394 (require 'org-exp)
8395 (append
8396 (mapcar
8397 (lambda (x)
8398 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8399 (cons (match-string 2 x) (match-string 1 x)))
8400 (org-split-string (org-get-current-options) "\n"))
8401 (mapcar 'list org-additional-option-like-keywords)))
8402 (startup
8403 (setq type :startup)
8404 org-startup-options)
8405 (link (append org-link-abbrev-alist-local
8406 org-link-abbrev-alist))
8407 (texp
8408 (setq type :tex)
8409 org-html-entities)
8410 ((string-match "\\`\\*+[ \t]+\\'"
8411 (buffer-substring (point-at-bol) beg))
8412 (setq type :todo)
8413 (mapcar 'list org-todo-keywords-1))
8414 (searchhead
8415 (setq type :searchhead)
8416 (save-excursion
8417 (goto-char (point-min))
8418 (while (re-search-forward org-todo-line-regexp nil t)
8419 (push (list
8420 (org-make-org-heading-search-string
8421 (match-string 3) t))
8422 tbl)))
8423 tbl)
8424 (tag (setq type :tag beg beg1)
8425 (or org-tag-alist (org-get-buffer-tags)))
8426 (prop (setq type :prop beg beg1)
8427 (mapcar 'list (org-buffer-property-keys nil t t)))
8428 (t (progn
8429 (call-interactively org-completion-fallback-command)
8430 (throw 'exit nil)))))
8431 (pattern (buffer-substring-no-properties beg end))
8432 (completion (try-completion pattern table confirm)))
8433 (cond ((eq completion t)
8434 (if (not (assoc (upcase pattern) table))
8435 (message "Already complete")
8436 (if (and (equal type :opt)
8437 (not (member (car (assoc (upcase pattern) table))
8438 org-additional-option-like-keywords)))
8439 (insert (substring (cdr (assoc (upcase pattern) table))
8440 (length pattern)))
8441 (if (memq type '(:tag :prop)) (insert ":")))))
8442 ((null completion)
8443 (message "Can't find completion for \"%s\"" pattern)
8444 (ding))
8445 ((not (string= pattern completion))
8446 (delete-region beg end)
8447 (if (string-match " +$" completion)
8448 (setq completion (replace-match "" t t completion)))
8449 (insert completion)
8450 (if (get-buffer-window "*Completions*")
8451 (delete-window (get-buffer-window "*Completions*")))
8452 (if (assoc completion table)
8453 (if (eq type :todo) (insert " ")
8454 (if (memq type '(:tag :prop)) (insert ":"))))
8455 (if (and (equal type :opt) (assoc completion table))
8456 (message "%s" (substitute-command-keys
8457 "Press \\[org-complete] again to insert example settings"))))
8459 (message "Making completion list...")
8460 (let ((list (sort (all-completions pattern table confirm)
8461 'string<)))
8462 (with-output-to-temp-buffer "*Completions*"
8463 (condition-case nil
8464 ;; Protection needed for XEmacs and emacs 21
8465 (display-completion-list list pattern)
8466 (error (display-completion-list list)))))
8467 (message "Making completion list...%s" "done")))))))
8469 ;;;; TODO, DEADLINE, Comments
8471 (defun org-toggle-comment ()
8472 "Change the COMMENT state of an entry."
8473 (interactive)
8474 (save-excursion
8475 (org-back-to-heading)
8476 (let (case-fold-search)
8477 (if (looking-at (concat outline-regexp
8478 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8479 (replace-match "" t t nil 1)
8480 (if (looking-at outline-regexp)
8481 (progn
8482 (goto-char (match-end 0))
8483 (insert org-comment-string " ")))))))
8485 (defvar org-last-todo-state-is-todo nil
8486 "This is non-nil when the last TODO state change led to a TODO state.
8487 If the last change removed the TODO tag or switched to DONE, then
8488 this is nil.")
8490 (defvar org-setting-tags nil) ; dynamically skipped
8492 (defun org-parse-local-options (string var)
8493 "Parse STRING for startup setting relevant for variable VAR."
8494 (let ((rtn (symbol-value var))
8495 e opts)
8496 (save-match-data
8497 (if (or (not string) (not (string-match "\\S-" string)))
8499 (setq opts (delq nil (mapcar (lambda (x)
8500 (setq e (assoc x org-startup-options))
8501 (if (eq (nth 1 e) var) e nil))
8502 (org-split-string string "[ \t]+"))))
8503 (if (not opts)
8505 (setq rtn nil)
8506 (while (setq e (pop opts))
8507 (if (not (nth 3 e))
8508 (setq rtn (nth 2 e))
8509 (if (not (listp rtn)) (setq rtn nil))
8510 (push (nth 2 e) rtn)))
8511 rtn)))))
8513 (defvar org-todo-setup-filter-hook nil
8514 "Hook for functions that pre-filter todo specs.
8516 Each function takes a todo spec and returns either `nil' or the spec
8517 transformed into canonical form." )
8519 (defvar org-todo-get-default-hook nil
8520 "Hook for functions that get a default item for todo.
8522 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8523 `nil' or a string to be used for the todo mark." )
8525 (defvar org-agenda-headline-snapshot-before-repeat)
8526 (defun org-todo (&optional arg)
8527 "Change the TODO state of an item.
8528 The state of an item is given by a keyword at the start of the heading,
8529 like
8530 *** TODO Write paper
8531 *** DONE Call mom
8533 The different keywords are specified in the variable `org-todo-keywords'.
8534 By default the available states are \"TODO\" and \"DONE\".
8535 So for this example: when the item starts with TODO, it is changed to DONE.
8536 When it starts with DONE, the DONE is removed. And when neither TODO nor
8537 DONE are present, add TODO at the beginning of the heading.
8539 With C-u prefix arg, use completion to determine the new state.
8540 With numeric prefix arg, switch to that state.
8541 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8542 With a tripple C-u prefix, circumvent any state blocking.
8544 For calling through lisp, arg is also interpreted in the following way:
8545 'none -> empty state
8546 \"\"(empty string) -> switch to empty state
8547 'done -> switch to DONE
8548 'nextset -> switch to the next set of keywords
8549 'previousset -> switch to the previous set of keywords
8550 \"WAITING\" -> switch to the specified keyword, but only if it
8551 really is a member of `org-todo-keywords'."
8552 (interactive "P")
8553 (if (equal arg '(16)) (setq arg 'nextset))
8554 (let ((org-blocker-hook org-blocker-hook))
8555 (when (equal arg '(64))
8556 (setq arg nil org-blocker-hook nil))
8557 (save-excursion
8558 (catch 'exit
8559 (org-back-to-heading)
8560 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8561 (or (looking-at (concat " +" org-todo-regexp " *"))
8562 (looking-at " *"))
8563 (let* ((match-data (match-data))
8564 (startpos (point-at-bol))
8565 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8566 (org-log-done org-log-done)
8567 (org-log-repeat org-log-repeat)
8568 (org-todo-log-states org-todo-log-states)
8569 (this (match-string 1))
8570 (hl-pos (match-beginning 0))
8571 (head (org-get-todo-sequence-head this))
8572 (ass (assoc head org-todo-kwd-alist))
8573 (interpret (nth 1 ass))
8574 (done-word (nth 3 ass))
8575 (final-done-word (nth 4 ass))
8576 (last-state (or this ""))
8577 (completion-ignore-case t)
8578 (member (member this org-todo-keywords-1))
8579 (tail (cdr member))
8580 (state (cond
8581 ((and org-todo-key-trigger
8582 (or (and (equal arg '(4))
8583 (eq org-use-fast-todo-selection 'prefix))
8584 (and (not arg) org-use-fast-todo-selection
8585 (not (eq org-use-fast-todo-selection
8586 'prefix)))))
8587 ;; Use fast selection
8588 (org-fast-todo-selection))
8589 ((and (equal arg '(4))
8590 (or (not org-use-fast-todo-selection)
8591 (not org-todo-key-trigger)))
8592 ;; Read a state with completion
8593 (org-ido-completing-read
8594 "State: " (mapcar (lambda(x) (list x))
8595 org-todo-keywords-1)
8596 nil t))
8597 ((eq arg 'right)
8598 (if this
8599 (if tail (car tail) nil)
8600 (car org-todo-keywords-1)))
8601 ((eq arg 'left)
8602 (if (equal member org-todo-keywords-1)
8604 (if this
8605 (nth (- (length org-todo-keywords-1)
8606 (length tail) 2)
8607 org-todo-keywords-1)
8608 (org-last org-todo-keywords-1))))
8609 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8610 (setq arg nil))) ; hack to fall back to cycling
8611 (arg
8612 ;; user or caller requests a specific state
8613 (cond
8614 ((equal arg "") nil)
8615 ((eq arg 'none) nil)
8616 ((eq arg 'done) (or done-word (car org-done-keywords)))
8617 ((eq arg 'nextset)
8618 (or (car (cdr (member head org-todo-heads)))
8619 (car org-todo-heads)))
8620 ((eq arg 'previousset)
8621 (let ((org-todo-heads (reverse org-todo-heads)))
8622 (or (car (cdr (member head org-todo-heads)))
8623 (car org-todo-heads))))
8624 ((car (member arg org-todo-keywords-1)))
8625 ((nth (1- (prefix-numeric-value arg))
8626 org-todo-keywords-1))))
8627 ((null member) (or head (car org-todo-keywords-1)))
8628 ((equal this final-done-word) nil) ;; -> make empty
8629 ((null tail) nil) ;; -> first entry
8630 ((memq interpret '(type priority))
8631 (if (eq this-command last-command)
8632 (car tail)
8633 (if (> (length tail) 0)
8634 (or done-word (car org-done-keywords))
8635 nil)))
8637 (car tail))))
8638 (state (or
8639 (run-hook-with-args-until-success
8640 'org-todo-get-default-hook state last-state)
8641 state))
8642 (next (if state (concat " " state " ") " "))
8643 (change-plist (list :type 'todo-state-change :from this :to state
8644 :position startpos))
8645 dolog now-done-p)
8646 (when org-blocker-hook
8647 (setq org-last-todo-state-is-todo
8648 (not (member this org-done-keywords)))
8649 (unless (save-excursion
8650 (save-match-data
8651 (run-hook-with-args-until-failure
8652 'org-blocker-hook change-plist)))
8653 (if (interactive-p)
8654 (error "TODO state change from %s to %s blocked" this state)
8655 ;; fail silently
8656 (message "TODO state change from %s to %s blocked" this state)
8657 (throw 'exit nil))))
8658 (store-match-data match-data)
8659 (replace-match next t t)
8660 (unless (pos-visible-in-window-p hl-pos)
8661 (message "TODO state changed to %s" (org-trim next)))
8662 (unless head
8663 (setq head (org-get-todo-sequence-head state)
8664 ass (assoc head org-todo-kwd-alist)
8665 interpret (nth 1 ass)
8666 done-word (nth 3 ass)
8667 final-done-word (nth 4 ass)))
8668 (when (memq arg '(nextset previousset))
8669 (message "Keyword-Set %d/%d: %s"
8670 (- (length org-todo-sets) -1
8671 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8672 (length org-todo-sets)
8673 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8674 (setq org-last-todo-state-is-todo
8675 (not (member state org-done-keywords)))
8676 (setq now-done-p (and (member state org-done-keywords)
8677 (not (member this org-done-keywords))))
8678 (and logging (org-local-logging logging))
8679 (when (and (or org-todo-log-states org-log-done)
8680 (not (memq arg '(nextset previousset))))
8681 ;; we need to look at recording a time and note
8682 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8683 (nth 2 (assoc this org-todo-log-states))))
8684 (when (and state
8685 (member state org-not-done-keywords)
8686 (not (member this org-not-done-keywords)))
8687 ;; This is now a todo state and was not one before
8688 ;; If there was a CLOSED time stamp, get rid of it.
8689 (org-add-planning-info nil nil 'closed))
8690 (when (and now-done-p org-log-done)
8691 ;; It is now done, and it was not done before
8692 (org-add-planning-info 'closed (org-current-time))
8693 (if (and (not dolog) (eq 'note org-log-done))
8694 (org-add-log-setup 'done state this 'findpos 'note)))
8695 (when (and state dolog)
8696 ;; This is a non-nil state, and we need to log it
8697 (org-add-log-setup 'state state this 'findpos dolog)))
8698 ;; Fixup tag positioning
8699 (org-todo-trigger-tag-changes state)
8700 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8701 (when org-provide-todo-statistics
8702 (org-update-parent-todo-statistics))
8703 (run-hooks 'org-after-todo-state-change-hook)
8704 (if (and arg (not (member state org-done-keywords)))
8705 (setq head (org-get-todo-sequence-head state)))
8706 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8707 ;; Do we need to trigger a repeat?
8708 (when now-done-p
8709 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8710 ;; This is for the agenda, take a snapshot of the headline.
8711 (save-match-data
8712 (setq org-agenda-headline-snapshot-before-repeat
8713 (org-get-heading))))
8714 (org-auto-repeat-maybe state))
8715 ;; Fixup cursor location if close to the keyword
8716 (if (and (outline-on-heading-p)
8717 (not (bolp))
8718 (save-excursion (beginning-of-line 1)
8719 (looking-at org-todo-line-regexp))
8720 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8721 (progn
8722 (goto-char (or (match-end 2) (match-end 1)))
8723 (just-one-space)))
8724 (when org-trigger-hook
8725 (save-excursion
8726 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8728 (defun org-block-todo-from-children-or-siblings (change-plist)
8729 "Block turning an entry into a TODO, using the hierarchy.
8730 This checks whether the current task should be blocked from state
8731 changes. Such blocking occurs when:
8733 1. The task has children which are not all in a completed state.
8735 2. A task has a parent with the property :ORDERED:, and there
8736 are siblings prior to the current task with incomplete
8737 status."
8738 (catch 'dont-block
8739 ;; If this is not a todo state change, or if this entry is already DONE,
8740 ;; do not block
8741 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8742 (member (plist-get change-plist :from)
8743 (cons 'done org-done-keywords))
8744 (member (plist-get change-plist :to)
8745 (cons 'todo org-not-done-keywords)))
8746 (throw 'dont-block t))
8747 ;; If this task has children, and any are undone, it's blocked
8748 (save-excursion
8749 (org-back-to-heading t)
8750 (let ((this-level (funcall outline-level)))
8751 (outline-next-heading)
8752 (let ((child-level (funcall outline-level)))
8753 (while (and (not (eobp))
8754 (> child-level this-level))
8755 ;; this todo has children, check whether they are all
8756 ;; completed
8757 (if (and (not (org-entry-is-done-p))
8758 (org-entry-is-todo-p))
8759 (throw 'dont-block nil))
8760 (outline-next-heading)
8761 (setq child-level (funcall outline-level))))))
8762 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8763 ;; any previous siblings are undone, it's blocked
8764 (save-excursion
8765 (org-back-to-heading t)
8766 (when (save-excursion
8767 (ignore-errors
8768 (org-up-heading-all 1)
8769 (org-entry-get (point) "ORDERED")))
8770 (let* ((this-level (funcall outline-level))
8771 (current-level this-level))
8772 (while (and (not (bobp))
8773 (= current-level this-level))
8774 (outline-previous-heading)
8775 (setq current-level (funcall outline-level))
8776 (if (= current-level this-level)
8777 ;; this todo has children, check whether they are all
8778 ;; completed
8779 (if (and (not (org-entry-is-done-p))
8780 (org-entry-is-todo-p))
8781 (throw 'dont-block nil)))))))
8782 t)) ; don't block
8784 (defcustom org-track-ordered-property-with-tag nil
8785 "Should the ORDERED property also be shown as a tag?
8786 The ORDERED property decides if an entry should require subtasks to be
8787 completed in sequence. Since a property is not very visible, setting
8788 this option means that toggling the ORDERED property with the command
8789 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8790 not relevant for the behavior, but it makes things more visible.
8792 Note that toggling the tag with tags commands will not change the property
8793 and therefore not influence behavior!
8795 This can be t, meaning the tag ORDERED should be used, It can also be a
8796 string to select a different tag for this task."
8797 :group 'org-todo
8798 :type '(choice
8799 (const :tag "No tracking" nil)
8800 (const :tag "Track with ORDERED tag" t)
8801 (string :tag "Use other tag")))
8803 (defun org-toggle-ordered-property ()
8804 "Toggle the ORDERED property of the current entry.
8805 For better visibility, you can track the value of this property with a tag.
8806 See variable `org-track-ordered-property-with-tag'."
8807 (interactive)
8808 (let* ((t1 org-track-ordered-property-with-tag)
8809 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8810 (save-excursion
8811 (org-back-to-heading)
8812 (if (org-entry-get nil "ORDERED")
8813 (progn
8814 (org-delete-property "ORDERED")
8815 (and tag (org-toggle-tag tag 'off))
8816 (message "Subtasks can be completed in arbitrary order"))
8817 (org-entry-put nil "ORDERED" "t")
8818 (and tag (org-toggle-tag tag 'on))
8819 (message "Subtasks must be completed in sequence")))))
8821 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8822 (defun org-block-todo-from-checkboxes (change-plist)
8823 "Block turning an entry into a TODO, using checkboxes.
8824 This checks whether the current task should be blocked from state
8825 changes because there are uncheckd boxes in this entry."
8826 (catch 'dont-block
8827 ;; If this is not a todo state change, or if this entry is already DONE,
8828 ;; do not block
8829 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8830 (member (plist-get change-plist :from)
8831 (cons 'done org-done-keywords))
8832 (member (plist-get change-plist :to)
8833 (cons 'todo org-not-done-keywords)))
8834 (throw 'dont-block t))
8835 ;; If this task has checkboxes that are not checked, it's blocked
8836 (save-excursion
8837 (org-back-to-heading t)
8838 (let ((beg (point)) end)
8839 (outline-next-heading)
8840 (setq end (point))
8841 (goto-char beg)
8842 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8843 end t)
8844 (progn
8845 (if (boundp 'org-blocked-by-checkboxes)
8846 (setq org-blocked-by-checkboxes t))
8847 (throw 'dont-block nil)))))
8848 t)) ; do not block
8850 (defun org-update-parent-todo-statistics ()
8851 "Update any statistics cookie in the parent of the current headline."
8852 (interactive)
8853 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8854 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8855 (catch 'exit
8856 (save-excursion
8857 (setq level (org-up-heading-safe))
8858 (unless level
8859 (throw 'exit nil))
8860 (while (re-search-forward box-re (point-at-eol) t)
8861 (setq cnt-all 0 cnt-done 0 cookie-present t)
8862 (setq is-percent (match-end 2))
8863 (save-match-data
8864 (unless (outline-next-heading) (throw 'exit nil))
8865 (while (looking-at org-todo-line-regexp)
8866 (setq kwd (match-string 2))
8867 (and kwd (setq cnt-all (1+ cnt-all)))
8868 (and (member kwd org-done-keywords)
8869 (setq cnt-done (1+ cnt-done)))
8870 (condition-case nil
8871 (org-forward-same-level 1)
8872 (error (end-of-line 1)))))
8873 (replace-match
8874 (if is-percent
8875 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8876 (format "[%d/%d]" cnt-done cnt-all))))
8877 (when cookie-present
8878 (run-hook-with-args 'org-after-todo-statistics-hook
8879 cnt-done (- cnt-all cnt-done)))))))
8881 (defvar org-after-todo-statistics-hook nil
8882 "Hook that is called after a TODO statistics cookie has been updated.
8883 Each function is called with two arguments: the number of not-done entries
8884 and the number of done entries.
8886 For example, the following function, when added to this hook, will switch
8887 an entry to DONE when all children are done, and back to TODO when new
8888 entries are set to a TODO status. Note that this hook is only called
8889 when there is a statistics cookie in the headline!
8891 (defun org-summary-todo (n-done n-not-done)
8892 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8893 (let (org-log-done org-log-states) ; turn off logging
8894 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8897 (defun org-todo-trigger-tag-changes (state)
8898 "Apply the changes defined in `org-todo-state-tags-triggers'."
8899 (let ((l org-todo-state-tags-triggers)
8900 changes)
8901 (when (or (not state) (equal state ""))
8902 (setq changes (append changes (cdr (assoc "" l)))))
8903 (when (and (stringp state) (> (length state) 0))
8904 (setq changes (append changes (cdr (assoc state l)))))
8905 (when (member state org-not-done-keywords)
8906 (setq changes (append changes (cdr (assoc 'todo l)))))
8907 (when (member state org-done-keywords)
8908 (setq changes (append changes (cdr (assoc 'done l)))))
8909 (dolist (c changes)
8910 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8912 (defun org-local-logging (value)
8913 "Get logging settings from a property VALUE."
8914 (let* (words w a)
8915 ;; directly set the variables, they are already local.
8916 (setq org-log-done nil
8917 org-log-repeat nil
8918 org-todo-log-states nil)
8919 (setq words (org-split-string value))
8920 (while (setq w (pop words))
8921 (cond
8922 ((setq a (assoc w org-startup-options))
8923 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8924 (set (nth 1 a) (nth 2 a))))
8925 ((setq a (org-extract-log-state-settings w))
8926 (and (member (car a) org-todo-keywords-1)
8927 (push a org-todo-log-states)))))))
8929 (defun org-get-todo-sequence-head (kwd)
8930 "Return the head of the TODO sequence to which KWD belongs.
8931 If KWD is not set, check if there is a text property remembering the
8932 right sequence."
8933 (let (p)
8934 (cond
8935 ((not kwd)
8936 (or (get-text-property (point-at-bol) 'org-todo-head)
8937 (progn
8938 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8939 nil (point-at-eol)))
8940 (get-text-property p 'org-todo-head))))
8941 ((not (member kwd org-todo-keywords-1))
8942 (car org-todo-keywords-1))
8943 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8945 (defun org-fast-todo-selection ()
8946 "Fast TODO keyword selection with single keys.
8947 Returns the new TODO keyword, or nil if no state change should occur."
8948 (let* ((fulltable org-todo-key-alist)
8949 (done-keywords org-done-keywords) ;; needed for the faces.
8950 (maxlen (apply 'max (mapcar
8951 (lambda (x)
8952 (if (stringp (car x)) (string-width (car x)) 0))
8953 fulltable)))
8954 (expert nil)
8955 (fwidth (+ maxlen 3 1 3))
8956 (ncol (/ (- (window-width) 4) fwidth))
8957 tg cnt e c tbl
8958 groups ingroup)
8959 (save-excursion
8960 (save-window-excursion
8961 (if expert
8962 (set-buffer (get-buffer-create " *Org todo*"))
8963 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8964 (erase-buffer)
8965 (org-set-local 'org-done-keywords done-keywords)
8966 (setq tbl fulltable cnt 0)
8967 (while (setq e (pop tbl))
8968 (cond
8969 ((equal e '(:startgroup))
8970 (push '() groups) (setq ingroup t)
8971 (when (not (= cnt 0))
8972 (setq cnt 0)
8973 (insert "\n"))
8974 (insert "{ "))
8975 ((equal e '(:endgroup))
8976 (setq ingroup nil cnt 0)
8977 (insert "}\n"))
8978 ((equal e '(:newline))
8979 (insert "\n "))
8981 (setq tg (car e) c (cdr e))
8982 (if ingroup (push tg (car groups)))
8983 (setq tg (org-add-props tg nil 'face
8984 (org-get-todo-face tg)))
8985 (if (and (= cnt 0) (not ingroup)) (insert " "))
8986 (insert "[" c "] " tg (make-string
8987 (- fwidth 4 (length tg)) ?\ ))
8988 (when (= (setq cnt (1+ cnt)) ncol)
8989 (insert "\n")
8990 (if ingroup (insert " "))
8991 (setq cnt 0)))))
8992 (insert "\n")
8993 (goto-char (point-min))
8994 (if (not expert) (org-fit-window-to-buffer))
8995 (message "[a-z..]:Set [SPC]:clear")
8996 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8997 (cond
8998 ((or (= c ?\C-g)
8999 (and (= c ?q) (not (rassoc c fulltable))))
9000 (setq quit-flag t))
9001 ((= c ?\ ) nil)
9002 ((setq e (rassoc c fulltable) tg (car e))
9004 (t (setq quit-flag t)))))))
9006 (defun org-entry-is-todo-p ()
9007 (member (org-get-todo-state) org-not-done-keywords))
9009 (defun org-entry-is-done-p ()
9010 (member (org-get-todo-state) org-done-keywords))
9012 (defun org-get-todo-state ()
9013 (save-excursion
9014 (org-back-to-heading t)
9015 (and (looking-at org-todo-line-regexp)
9016 (match-end 2)
9017 (match-string 2))))
9019 (defun org-at-date-range-p (&optional inactive-ok)
9020 "Is the cursor inside a date range?"
9021 (interactive)
9022 (save-excursion
9023 (catch 'exit
9024 (let ((pos (point)))
9025 (skip-chars-backward "^[<\r\n")
9026 (skip-chars-backward "<[")
9027 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9028 (>= (match-end 0) pos)
9029 (throw 'exit t))
9030 (skip-chars-backward "^<[\r\n")
9031 (skip-chars-backward "<[")
9032 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9033 (>= (match-end 0) pos)
9034 (throw 'exit t)))
9035 nil)))
9037 (defun org-get-repeat ()
9038 "Check if there is a deadline/schedule with repeater in this entry."
9039 (save-match-data
9040 (save-excursion
9041 (org-back-to-heading t)
9042 (if (re-search-forward
9043 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9044 (match-string 1)))))
9046 (defvar org-last-changed-timestamp)
9047 (defvar org-last-inserted-timestamp)
9048 (defvar org-log-post-message)
9049 (defvar org-log-note-purpose)
9050 (defvar org-log-note-how)
9051 (defvar org-log-note-extra)
9052 (defun org-auto-repeat-maybe (done-word)
9053 "Check if the current headline contains a repeated deadline/schedule.
9054 If yes, set TODO state back to what it was and change the base date
9055 of repeating deadline/scheduled time stamps to new date.
9056 This function is run automatically after each state change to a DONE state."
9057 ;; last-state is dynamically scoped into this function
9058 (let* ((repeat (org-get-repeat))
9059 (aa (assoc last-state org-todo-kwd-alist))
9060 (interpret (nth 1 aa))
9061 (head (nth 2 aa))
9062 (whata '(("d" . day) ("m" . month) ("y" . year)))
9063 (msg "Entry repeats: ")
9064 (org-log-done nil)
9065 (org-todo-log-states nil)
9066 (nshiftmax 10) (nshift 0)
9067 re type n what ts time)
9068 (when repeat
9069 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9070 (org-todo (if (eq interpret 'type) last-state head))
9071 (when org-log-repeat
9072 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9073 (memq 'org-add-log-note post-command-hook))
9074 ;; OK, we are already setup for some record
9075 (if (eq org-log-repeat 'note)
9076 ;; make sure we take a note, not only a time stamp
9077 (setq org-log-note-how 'note))
9078 ;; Set up for taking a record
9079 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9080 last-state
9081 'findpos org-log-repeat)))
9082 (org-back-to-heading t)
9083 (org-add-planning-info nil nil 'closed)
9084 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9085 org-deadline-time-regexp "\\)\\|\\("
9086 org-ts-regexp "\\)"))
9087 (while (re-search-forward
9088 re (save-excursion (outline-next-heading) (point)) t)
9089 (setq type (if (match-end 1) org-scheduled-string
9090 (if (match-end 3) org-deadline-string "Plain:"))
9091 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9092 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9093 (setq n (string-to-number (match-string 2 ts))
9094 what (match-string 3 ts))
9095 (if (equal what "w") (setq n (* n 7) what "d"))
9096 ;; Preparation, see if we need to modify the start date for the change
9097 (when (match-end 1)
9098 (setq time (save-match-data (org-time-string-to-time ts)))
9099 (cond
9100 ((equal (match-string 1 ts) ".")
9101 ;; Shift starting date to today
9102 (org-timestamp-change
9103 (- (time-to-days (current-time)) (time-to-days time))
9104 'day))
9105 ((equal (match-string 1 ts) "+")
9106 (while (or (= nshift 0)
9107 (<= (time-to-days time) (time-to-days (current-time))))
9108 (when (= (incf nshift) nshiftmax)
9109 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9110 (error "Abort")))
9111 (org-timestamp-change n (cdr (assoc what whata)))
9112 (org-at-timestamp-p t)
9113 (setq ts (match-string 1))
9114 (setq time (save-match-data (org-time-string-to-time ts))))
9115 (org-timestamp-change (- n) (cdr (assoc what whata)))
9116 ;; rematch, so that we have everything in place for the real shift
9117 (org-at-timestamp-p t)
9118 (setq ts (match-string 1))
9119 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9120 (org-timestamp-change n (cdr (assoc what whata)))
9121 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9122 (setq org-log-post-message msg)
9123 (message "%s" msg))))
9125 (defun org-show-todo-tree (arg)
9126 "Make a compact tree which shows all headlines marked with TODO.
9127 The tree will show the lines where the regexp matches, and all higher
9128 headlines above the match.
9129 With a \\[universal-argument] prefix, also show the DONE entries.
9130 With a numeric prefix N, construct a sparse tree for the Nth element
9131 of `org-todo-keywords-1'."
9132 (interactive "P")
9133 (let ((case-fold-search nil)
9134 (kwd-re
9135 (cond ((null arg) org-not-done-regexp)
9136 ((equal arg '(4))
9137 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9138 (mapcar 'list org-todo-keywords-1))))
9139 (concat "\\("
9140 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9141 "\\)\\>")))
9142 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9143 (regexp-quote (nth (1- (prefix-numeric-value arg))
9144 org-todo-keywords-1)))
9145 (t (error "Invalid prefix argument: %s" arg)))))
9146 (message "%d TODO entries found"
9147 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9149 (defun org-deadline (&optional remove time)
9150 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9151 With argument REMOVE, remove any deadline from the item.
9152 When TIME is set, it should be an internal time specification, and the
9153 scheduling will use the corresponding date."
9154 (interactive "P")
9155 (if remove
9156 (progn
9157 (org-remove-timestamp-with-keyword org-deadline-string)
9158 (message "Item no longer has a deadline."))
9159 (if (org-get-repeat)
9160 (error "Cannot change deadline on task with repeater, please do that by hand")
9161 (org-add-planning-info 'deadline time 'closed)
9162 (message "Deadline on %s" org-last-inserted-timestamp))))
9164 (defun org-schedule (&optional remove time)
9165 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9166 With argument REMOVE, remove any scheduling date from the item.
9167 When TIME is set, it should be an internal time specification, and the
9168 scheduling will use the corresponding date."
9169 (interactive "P")
9170 (if remove
9171 (progn
9172 (org-remove-timestamp-with-keyword org-scheduled-string)
9173 (message "Item is no longer scheduled."))
9174 (if (org-get-repeat)
9175 (error "Cannot reschedule task with repeater, please do that by hand")
9176 (org-add-planning-info 'scheduled time 'closed)
9177 (message "Scheduled to %s" org-last-inserted-timestamp))))
9179 (defun org-get-scheduled-time (pom &optional inherit)
9180 "Get the scheduled time as a time tuple, of a format suitable
9181 for calling org-schedule with, or if there is no scheduling,
9182 returns nil."
9183 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9184 (when time
9185 (apply 'encode-time (org-parse-time-string time)))))
9187 (defun org-get-deadline-time (pom &optional inherit)
9188 "Get the deadine as a time tuple, of a format suitable for
9189 calling org-deadlin with, or if there is no scheduling, returns
9190 nil."
9191 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9192 (when time
9193 (apply 'encode-time (org-parse-time-string time)))))
9195 (defun org-remove-timestamp-with-keyword (keyword)
9196 "Remove all time stamps with KEYWORD in the current entry."
9197 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9198 beg)
9199 (save-excursion
9200 (org-back-to-heading t)
9201 (setq beg (point))
9202 (org-end-of-subtree t t)
9203 (while (re-search-backward re beg t)
9204 (replace-match "")
9205 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9206 (equal (char-before) ?\ ))
9207 (backward-delete-char 1)
9208 (if (string-match "^[ \t]*$" (buffer-substring
9209 (point-at-bol) (point-at-eol)))
9210 (delete-region (point-at-bol)
9211 (min (point-max) (1+ (point-at-eol))))))))))
9213 (defun org-add-planning-info (what &optional time &rest remove)
9214 "Insert new timestamp with keyword in the line directly after the headline.
9215 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9216 If non is given, the user is prompted for a date.
9217 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9218 be removed."
9219 (interactive)
9220 (let (org-time-was-given org-end-time-was-given ts
9221 end default-time default-input)
9223 (catch 'exit
9224 (when (and (not time) (memq what '(scheduled deadline)))
9225 ;; Try to get a default date/time from existing timestamp
9226 (save-excursion
9227 (org-back-to-heading t)
9228 (setq end (save-excursion (outline-next-heading) (point)))
9229 (when (re-search-forward (if (eq what 'scheduled)
9230 org-scheduled-time-regexp
9231 org-deadline-time-regexp)
9232 end t)
9233 (setq ts (match-string 1)
9234 default-time
9235 (apply 'encode-time (org-parse-time-string ts))
9236 default-input (and ts (org-get-compact-tod ts))))))
9237 (when what
9238 ;; If necessary, get the time from the user
9239 (setq time (or time (org-read-date nil 'to-time nil nil
9240 default-time default-input))))
9242 (when (and org-insert-labeled-timestamps-at-point
9243 (member what '(scheduled deadline)))
9244 (insert
9245 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9246 (org-insert-time-stamp time org-time-was-given
9247 nil nil nil (list org-end-time-was-given))
9248 (setq what nil))
9249 (save-excursion
9250 (save-restriction
9251 (let (col list elt ts buffer-invisibility-spec)
9252 (org-back-to-heading t)
9253 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9254 (goto-char (match-end 1))
9255 (setq col (current-column))
9256 (goto-char (match-end 0))
9257 (if (eobp) (insert "\n") (forward-char 1))
9258 (when (and (not what)
9259 (not (looking-at org-keyword-time-not-clock-regexp)))
9260 ;; Nothing to add, nothing to remove...... :-)
9261 (throw 'exit nil))
9262 (if (and (not (looking-at outline-regexp))
9263 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9264 "[^\r\n]*"))
9265 (not (equal (match-string 1) org-clock-string)))
9266 (narrow-to-region (match-beginning 0) (match-end 0))
9267 (insert-before-markers "\n")
9268 (backward-char 1)
9269 (narrow-to-region (point) (point))
9270 (and org-adapt-indentation (org-indent-to-column col)))
9271 ;; Check if we have to remove something.
9272 (setq list (cons what remove))
9273 (while list
9274 (setq elt (pop list))
9275 (goto-char (point-min))
9276 (when (or (and (eq elt 'scheduled)
9277 (re-search-forward org-scheduled-time-regexp nil t))
9278 (and (eq elt 'deadline)
9279 (re-search-forward org-deadline-time-regexp nil t))
9280 (and (eq elt 'closed)
9281 (re-search-forward org-closed-time-regexp nil t)))
9282 (replace-match "")
9283 (if (looking-at "--+<[^>]+>") (replace-match ""))
9284 (if (looking-at " +") (replace-match ""))))
9285 (goto-char (point-max))
9286 (when what
9287 (insert
9288 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9289 (cond ((eq what 'scheduled) org-scheduled-string)
9290 ((eq what 'deadline) org-deadline-string)
9291 ((eq what 'closed) org-closed-string))
9292 " ")
9293 (setq ts (org-insert-time-stamp
9294 time
9295 (or org-time-was-given
9296 (and (eq what 'closed) org-log-done-with-time))
9297 (eq what 'closed)
9298 nil nil (list org-end-time-was-given)))
9299 (end-of-line 1))
9300 (goto-char (point-min))
9301 (widen)
9302 (if (and (looking-at "[ \t]+\n")
9303 (equal (char-before) ?\n))
9304 (delete-region (1- (point)) (point-at-eol)))
9305 ts))))))
9307 (defvar org-log-note-marker (make-marker))
9308 (defvar org-log-note-purpose nil)
9309 (defvar org-log-note-state nil)
9310 (defvar org-log-note-previous-state nil)
9311 (defvar org-log-note-how nil)
9312 (defvar org-log-note-extra nil)
9313 (defvar org-log-note-window-configuration nil)
9314 (defvar org-log-note-return-to (make-marker))
9315 (defvar org-log-post-message nil
9316 "Message to be displayed after a log note has been stored.
9317 The auto-repeater uses this.")
9319 (defun org-add-note ()
9320 "Add a note to the current entry.
9321 This is done in the same way as adding a state change note."
9322 (interactive)
9323 (org-add-log-setup 'note nil nil 'findpos nil))
9325 (defvar org-property-end-re)
9326 (defun org-add-log-setup (&optional purpose state prev-state
9327 findpos how &optional extra)
9328 "Set up the post command hook to take a note.
9329 If this is about to TODO state change, the new state is expected in STATE.
9330 When FINDPOS is non-nil, find the correct position for the note in
9331 the current entry. If not, assume that it can be inserted at point.
9332 HOW is an indicator what kind of note should be created.
9333 EXTRA is additional text that will be inserted into the notes buffer."
9334 (let ((drawer (cond ((stringp org-log-into-drawer)
9335 org-log-into-drawer)
9336 (org-log-into-drawer "LOGBOOK")
9337 (t nil))))
9338 (save-restriction
9339 (save-excursion
9340 (when findpos
9341 (org-back-to-heading t)
9342 (narrow-to-region (point) (save-excursion
9343 (outline-next-heading) (point)))
9344 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9345 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9346 "[^\r\n]*\\)?"))
9347 (goto-char (match-end 0))
9348 (cond
9349 (drawer
9350 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9351 nil t)
9352 (progn
9353 (goto-char (match-end 0))
9354 (or org-log-states-order-reversed
9355 (and (re-search-forward org-property-end-re nil t)
9356 (goto-char (1- (match-beginning 0))))))
9357 (insert "\n:" drawer ":\n:END:")
9358 (beginning-of-line 0)
9359 (org-indent-line-function)
9360 (beginning-of-line 2)
9361 (org-indent-line-function)
9362 (end-of-line 0)))
9363 ((and org-log-state-notes-insert-after-drawers
9364 (save-excursion
9365 (forward-line) (looking-at org-drawer-regexp)))
9366 (forward-line)
9367 (while (looking-at org-drawer-regexp)
9368 (goto-char (match-end 0))
9369 (re-search-forward org-property-end-re (point-max) t)
9370 (forward-line))
9371 (forward-line -1)))
9372 (unless org-log-states-order-reversed
9373 (and (= (char-after) ?\n) (forward-char 1))
9374 (org-skip-over-state-notes)
9375 (skip-chars-backward " \t\n\r")))
9376 (move-marker org-log-note-marker (point))
9377 (setq org-log-note-purpose purpose
9378 org-log-note-state state
9379 org-log-note-previous-state prev-state
9380 org-log-note-how how
9381 org-log-note-extra extra)
9382 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9384 (defun org-skip-over-state-notes ()
9385 "Skip past the list of State notes in an entry."
9386 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9387 (while (looking-at "[ \t]*- State")
9388 (condition-case nil
9389 (org-next-item)
9390 (error (org-end-of-item)))))
9392 (defun org-add-log-note (&optional purpose)
9393 "Pop up a window for taking a note, and add this note later at point."
9394 (remove-hook 'post-command-hook 'org-add-log-note)
9395 (setq org-log-note-window-configuration (current-window-configuration))
9396 (delete-other-windows)
9397 (move-marker org-log-note-return-to (point))
9398 (switch-to-buffer (marker-buffer org-log-note-marker))
9399 (goto-char org-log-note-marker)
9400 (org-switch-to-buffer-other-window "*Org Note*")
9401 (erase-buffer)
9402 (if (memq org-log-note-how '(time state))
9403 (let (current-prefix-arg) (org-store-log-note))
9404 (let ((org-inhibit-startup t)) (org-mode))
9405 (insert (format "# Insert note for %s.
9406 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9407 (cond
9408 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9409 ((eq org-log-note-purpose 'done) "closed todo item")
9410 ((eq org-log-note-purpose 'state)
9411 (format "state change from \"%s\" to \"%s\""
9412 (or org-log-note-previous-state "")
9413 (or org-log-note-state "")))
9414 ((eq org-log-note-purpose 'note)
9415 "this entry")
9416 (t (error "This should not happen")))))
9417 (if org-log-note-extra (insert org-log-note-extra))
9418 (org-set-local 'org-finish-function 'org-store-log-note)))
9420 (defvar org-note-abort nil) ; dynamically scoped
9421 (defun org-store-log-note ()
9422 "Finish taking a log note, and insert it to where it belongs."
9423 (let ((txt (buffer-string))
9424 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9425 lines ind)
9426 (kill-buffer (current-buffer))
9427 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9428 (setq txt (replace-match "" t t txt)))
9429 (if (string-match "\\s-+\\'" txt)
9430 (setq txt (replace-match "" t t txt)))
9431 (setq lines (org-split-string txt "\n"))
9432 (when (and note (string-match "\\S-" note))
9433 (setq note
9434 (org-replace-escapes
9435 note
9436 (list (cons "%u" (user-login-name))
9437 (cons "%U" user-full-name)
9438 (cons "%t" (format-time-string
9439 (org-time-stamp-format 'long 'inactive)
9440 (current-time)))
9441 (cons "%s" (if org-log-note-state
9442 (concat "\"" org-log-note-state "\"")
9443 ""))
9444 (cons "%S" (if org-log-note-previous-state
9445 (concat "\"" org-log-note-previous-state "\"")
9446 "\"\"")))))
9447 (if lines (setq note (concat note " \\\\")))
9448 (push note lines))
9449 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9450 (when lines
9451 (save-excursion
9452 (set-buffer (marker-buffer org-log-note-marker))
9453 (save-excursion
9454 (goto-char org-log-note-marker)
9455 (move-marker org-log-note-marker nil)
9456 (end-of-line 1)
9457 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9458 (insert "- " (pop lines))
9459 (org-indent-line-function)
9460 (beginning-of-line 1)
9461 (looking-at "[ \t]*")
9462 (setq ind (concat (match-string 0) " "))
9463 (end-of-line 1)
9464 (while lines (insert "\n" ind (pop lines)))
9465 (message "Note stored")
9466 (org-back-to-heading t)
9467 (org-cycle-hide-drawers 'children)))))
9468 (set-window-configuration org-log-note-window-configuration)
9469 (with-current-buffer (marker-buffer org-log-note-return-to)
9470 (goto-char org-log-note-return-to))
9471 (move-marker org-log-note-return-to nil)
9472 (and org-log-post-message (message "%s" org-log-post-message)))
9474 (defun org-sparse-tree (&optional arg)
9475 "Create a sparse tree, prompt for the details.
9476 This command can create sparse trees. You first need to select the type
9477 of match used to create the tree:
9479 t Show entries with a specific TODO keyword.
9480 T Show entries selected by a tags match.
9481 p Enter a property name and its value (both with completion on existing
9482 names/values) and show entries with that property.
9483 r Show entries matching a regular expression
9484 d Show deadlines due within `org-deadline-warning-days'."
9485 (interactive "P")
9486 (let (ans kwd value)
9487 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9488 (setq ans (read-char-exclusive))
9489 (cond
9490 ((equal ans ?d)
9491 (call-interactively 'org-check-deadlines))
9492 ((equal ans ?b)
9493 (call-interactively 'org-check-before-date))
9494 ((equal ans ?t)
9495 (org-show-todo-tree '(4)))
9496 ((equal ans ?T)
9497 (call-interactively 'org-tags-sparse-tree))
9498 ((member ans '(?p ?P))
9499 (setq kwd (org-ido-completing-read "Property: "
9500 (mapcar 'list (org-buffer-property-keys))))
9501 (setq value (org-ido-completing-read "Value: "
9502 (mapcar 'list (org-property-values kwd))))
9503 (unless (string-match "\\`{.*}\\'" value)
9504 (setq value (concat "\"" value "\"")))
9505 (org-tags-sparse-tree arg (concat kwd "=" value)))
9506 ((member ans '(?r ?R ?/))
9507 (call-interactively 'org-occur))
9508 (t (error "No such sparse tree command \"%c\"" ans)))))
9510 (defvar org-occur-highlights nil
9511 "List of overlays used for occur matches.")
9512 (make-variable-buffer-local 'org-occur-highlights)
9513 (defvar org-occur-parameters nil
9514 "Parameters of the active org-occur calls.
9515 This is a list, each call to org-occur pushes as cons cell,
9516 containing the regular expression and the callback, onto the list.
9517 The list can contain several entries if `org-occur' has been called
9518 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9519 will only contain one set of parameters. When the highlights are
9520 removed (for example with `C-c C-c', or with the next edit (depending
9521 on `org-remove-highlights-with-change'), this variable is emptied
9522 as well.")
9523 (make-variable-buffer-local 'org-occur-parameters)
9525 (defun org-occur (regexp &optional keep-previous callback)
9526 "Make a compact tree which shows all matches of REGEXP.
9527 The tree will show the lines where the regexp matches, and all higher
9528 headlines above the match. It will also show the heading after the match,
9529 to make sure editing the matching entry is easy.
9530 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9531 call to `org-occur' will be kept, to allow stacking of calls to this
9532 command.
9533 If CALLBACK is non-nil, it is a function which is called to confirm
9534 that the match should indeed be shown."
9535 (interactive "sRegexp: \nP")
9536 (unless keep-previous
9537 (org-remove-occur-highlights nil nil t))
9538 (push (cons regexp callback) org-occur-parameters)
9539 (let ((cnt 0))
9540 (save-excursion
9541 (goto-char (point-min))
9542 (if (or (not keep-previous) ; do not want to keep
9543 (not org-occur-highlights)) ; no previous matches
9544 ;; hide everything
9545 (org-overview))
9546 (while (re-search-forward regexp nil t)
9547 (when (or (not callback)
9548 (save-match-data (funcall callback)))
9549 (setq cnt (1+ cnt))
9550 (when org-highlight-sparse-tree-matches
9551 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9552 (org-show-context 'occur-tree))))
9553 (when org-remove-highlights-with-change
9554 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9555 nil 'local))
9556 (unless org-sparse-tree-open-archived-trees
9557 (org-hide-archived-subtrees (point-min) (point-max)))
9558 (run-hooks 'org-occur-hook)
9559 (if (interactive-p)
9560 (message "%d match(es) for regexp %s" cnt regexp))
9561 cnt))
9563 (defun org-show-context (&optional key)
9564 "Make sure point and context and visible.
9565 How much context is shown depends upon the variables
9566 `org-show-hierarchy-above', `org-show-following-heading'. and
9567 `org-show-siblings'."
9568 (let ((heading-p (org-on-heading-p t))
9569 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9570 (following-p (org-get-alist-option org-show-following-heading key))
9571 (entry-p (org-get-alist-option org-show-entry-below key))
9572 (siblings-p (org-get-alist-option org-show-siblings key)))
9573 (catch 'exit
9574 ;; Show heading or entry text
9575 (if (and heading-p (not entry-p))
9576 (org-flag-heading nil) ; only show the heading
9577 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9578 (org-show-hidden-entry))) ; show entire entry
9579 (when following-p
9580 ;; Show next sibling, or heading below text
9581 (save-excursion
9582 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9583 (org-flag-heading nil))))
9584 (when siblings-p (org-show-siblings))
9585 (when hierarchy-p
9586 ;; show all higher headings, possibly with siblings
9587 (save-excursion
9588 (while (and (condition-case nil
9589 (progn (org-up-heading-all 1) t)
9590 (error nil))
9591 (not (bobp)))
9592 (org-flag-heading nil)
9593 (when siblings-p (org-show-siblings))))))))
9595 (defun org-reveal (&optional siblings)
9596 "Show current entry, hierarchy above it, and the following headline.
9597 This can be used to show a consistent set of context around locations
9598 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9599 not t for the search context.
9601 With optional argument SIBLINGS, on each level of the hierarchy all
9602 siblings are shown. This repairs the tree structure to what it would
9603 look like when opened with hierarchical calls to `org-cycle'."
9604 (interactive "P")
9605 (let ((org-show-hierarchy-above t)
9606 (org-show-following-heading t)
9607 (org-show-siblings (if siblings t org-show-siblings)))
9608 (org-show-context nil)))
9610 (defun org-highlight-new-match (beg end)
9611 "Highlight from BEG to END and mark the highlight is an occur headline."
9612 (let ((ov (org-make-overlay beg end)))
9613 (org-overlay-put ov 'face 'secondary-selection)
9614 (push ov org-occur-highlights)))
9616 (defun org-remove-occur-highlights (&optional beg end noremove)
9617 "Remove the occur highlights from the buffer.
9618 BEG and END are ignored. If NOREMOVE is nil, remove this function
9619 from the `before-change-functions' in the current buffer."
9620 (interactive)
9621 (unless org-inhibit-highlight-removal
9622 (mapc 'org-delete-overlay org-occur-highlights)
9623 (setq org-occur-highlights nil)
9624 (setq org-occur-parameters nil)
9625 (unless noremove
9626 (remove-hook 'before-change-functions
9627 'org-remove-occur-highlights 'local))))
9629 ;;;; Priorities
9631 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9632 "Regular expression matching the priority indicator.")
9634 (defvar org-remove-priority-next-time nil)
9636 (defun org-priority-up ()
9637 "Increase the priority of the current item."
9638 (interactive)
9639 (org-priority 'up))
9641 (defun org-priority-down ()
9642 "Decrease the priority of the current item."
9643 (interactive)
9644 (org-priority 'down))
9646 (defun org-priority (&optional action)
9647 "Change the priority of an item by ARG.
9648 ACTION can be `set', `up', `down', or a character."
9649 (interactive)
9650 (setq action (or action 'set))
9651 (let (current new news have remove)
9652 (save-excursion
9653 (org-back-to-heading t)
9654 (if (looking-at org-priority-regexp)
9655 (setq current (string-to-char (match-string 2))
9656 have t)
9657 (setq current org-default-priority))
9658 (cond
9659 ((or (eq action 'set)
9660 (if (featurep 'xemacs) (characterp action) (integerp action)))
9661 (if (not (eq action 'set))
9662 (setq new action)
9663 (message "Priority %c-%c, SPC to remove: "
9664 org-highest-priority org-lowest-priority)
9665 (setq new (read-char-exclusive)))
9666 (if (and (= (upcase org-highest-priority) org-highest-priority)
9667 (= (upcase org-lowest-priority) org-lowest-priority))
9668 (setq new (upcase new)))
9669 (cond ((equal new ?\ ) (setq remove t))
9670 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9671 (error "Priority must be between `%c' and `%c'"
9672 org-highest-priority org-lowest-priority))))
9673 ((eq action 'up)
9674 (if (and (not have) (eq last-command this-command))
9675 (setq new org-lowest-priority)
9676 (setq new (if (and org-priority-start-cycle-with-default (not have))
9677 org-default-priority (1- current)))))
9678 ((eq action 'down)
9679 (if (and (not have) (eq last-command this-command))
9680 (setq new org-highest-priority)
9681 (setq new (if (and org-priority-start-cycle-with-default (not have))
9682 org-default-priority (1+ current)))))
9683 (t (error "Invalid action")))
9684 (if (or (< (upcase new) org-highest-priority)
9685 (> (upcase new) org-lowest-priority))
9686 (setq remove t))
9687 (setq news (format "%c" new))
9688 (if have
9689 (if remove
9690 (replace-match "" t t nil 1)
9691 (replace-match news t t nil 2))
9692 (if remove
9693 (error "No priority cookie found in line")
9694 (looking-at org-todo-line-regexp)
9695 (if (match-end 2)
9696 (progn
9697 (goto-char (match-end 2))
9698 (insert " [#" news "]"))
9699 (goto-char (match-beginning 3))
9700 (insert "[#" news "] ")))))
9701 (org-preserve-lc (org-set-tags nil 'align))
9702 (if remove
9703 (message "Priority removed")
9704 (message "Priority of current item set to %s" news))))
9707 (defun org-get-priority (s)
9708 "Find priority cookie and return priority."
9709 (save-match-data
9710 (if (not (string-match org-priority-regexp s))
9711 (* 1000 (- org-lowest-priority org-default-priority))
9712 (* 1000 (- org-lowest-priority
9713 (string-to-char (match-string 2 s)))))))
9715 ;;;; Tags
9717 (defvar org-agenda-archives-mode)
9718 (defun org-scan-tags (action matcher &optional todo-only)
9719 "Scan headline tags with inheritance and produce output ACTION.
9721 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9722 or `agenda' to produce an entry list for an agenda view. It can also be
9723 a Lisp form or a function that should be called at each matched headline, in
9724 this case the return value is a list of all return values from these calls.
9726 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9727 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9728 only lines with a TODO keyword are included in the output."
9729 (require 'org-agenda)
9730 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9731 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9732 (org-re
9733 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9734 (props (list 'face 'default
9735 'done-face 'org-done
9736 'undone-face 'default
9737 'mouse-face 'highlight
9738 'org-not-done-regexp org-not-done-regexp
9739 'org-todo-regexp org-todo-regexp
9740 'keymap org-agenda-keymap
9741 'help-echo
9742 (format "mouse-2 or RET jump to org file %s"
9743 (abbreviate-file-name
9744 (or (buffer-file-name (buffer-base-buffer))
9745 (buffer-name (buffer-base-buffer)))))))
9746 (case-fold-search nil)
9747 lspos tags tags-list
9748 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9749 (llast 0) rtn rtn1 level category i txt
9750 todo marker entry priority)
9751 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9752 (setq action (list 'lambda nil action)))
9753 (save-excursion
9754 (goto-char (point-min))
9755 (when (eq action 'sparse-tree)
9756 (org-overview)
9757 (org-remove-occur-highlights))
9758 (while (re-search-forward re nil t)
9759 (catch :skip
9760 (setq todo (if (match-end 1) (match-string 2))
9761 tags (if (match-end 4) (match-string 4)))
9762 (goto-char (setq lspos (1+ (match-beginning 0))))
9763 (setq level (org-reduced-level (funcall outline-level))
9764 category (org-get-category))
9765 (setq i llast llast level)
9766 ;; remove tag lists from same and sublevels
9767 (while (>= i level)
9768 (when (setq entry (assoc i tags-alist))
9769 (setq tags-alist (delete entry tags-alist)))
9770 (setq i (1- i)))
9771 ;; add the next tags
9772 (when tags
9773 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9774 tags-alist
9775 (cons (cons level tags) tags-alist)))
9776 ;; compile tags for current headline
9777 (setq tags-list
9778 (if org-use-tag-inheritance
9779 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9780 tags))
9781 (when org-use-tag-inheritance
9782 (setcdr (car tags-alist)
9783 (mapcar (lambda (x)
9784 (setq x (copy-sequence x))
9785 (org-add-prop-inherited x))
9786 (cdar tags-alist))))
9787 (when (and tags org-use-tag-inheritance
9788 (not (eq t org-use-tag-inheritance)))
9789 ;; selective inheritance, remove uninherited ones
9790 (setcdr (car tags-alist)
9791 (org-remove-uniherited-tags (cdar tags-alist))))
9792 (when (and (or (not todo-only)
9793 (and (member todo org-not-done-keywords)
9794 (or (not org-agenda-tags-todo-honor-ignore-options)
9795 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9796 (let ((case-fold-search t)) (eval matcher))
9798 (not (member org-archive-tag tags-list))
9799 ;; we have an archive tag, should we use this anyway?
9800 (or (not org-agenda-skip-archived-trees)
9801 (and (eq action 'agenda) org-agenda-archives-mode))))
9802 (unless (eq action 'sparse-tree) (org-agenda-skip))
9804 ;; select this headline
9806 (cond
9807 ((eq action 'sparse-tree)
9808 (and org-highlight-sparse-tree-matches
9809 (org-get-heading) (match-end 0)
9810 (org-highlight-new-match
9811 (match-beginning 0) (match-beginning 1)))
9812 (org-show-context 'tags-tree))
9813 ((eq action 'agenda)
9814 (setq txt (org-format-agenda-item
9816 (concat
9817 (if org-tags-match-list-sublevels
9818 (make-string (1- level) ?.) "")
9819 (org-get-heading))
9820 category (org-get-tags-at))
9821 priority (org-get-priority txt))
9822 (goto-char lspos)
9823 (setq marker (org-agenda-new-marker))
9824 (org-add-props txt props
9825 'org-marker marker 'org-hd-marker marker 'org-category category
9826 'todo-state todo
9827 'priority priority 'type "tagsmatch")
9828 (push txt rtn))
9829 ((functionp action)
9830 (save-excursion
9831 (setq rtn1 (funcall action))
9832 (push rtn1 rtn))
9833 (goto-char (point-at-eol)))
9834 (t (error "Invalid action")))
9836 ;; if we are to skip sublevels, jump to end of subtree
9837 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9838 (when (and (eq action 'sparse-tree)
9839 (not org-sparse-tree-open-archived-trees))
9840 (org-hide-archived-subtrees (point-min) (point-max)))
9841 (nreverse rtn)))
9843 (defun org-remove-uniherited-tags (tags)
9844 "Remove all tags that are not inherited from the list TAGS."
9845 (cond
9846 ((eq org-use-tag-inheritance t)
9847 (if org-tags-exclude-from-inheritance
9848 (org-delete-all org-tags-exclude-from-inheritance tags)
9849 tags))
9850 ((not org-use-tag-inheritance) nil)
9851 ((stringp org-use-tag-inheritance)
9852 (delq nil (mapcar
9853 (lambda (x)
9854 (if (and (string-match org-use-tag-inheritance x)
9855 (not (member x org-tags-exclude-from-inheritance)))
9856 x nil))
9857 tags)))
9858 ((listp org-use-tag-inheritance)
9859 (delq nil (mapcar
9860 (lambda (x)
9861 (if (member x org-use-tag-inheritance) x nil))
9862 tags)))))
9864 (defvar todo-only) ;; dynamically scoped
9866 (defun org-tags-sparse-tree (&optional todo-only match)
9867 "Create a sparse tree according to tags string MATCH.
9868 MATCH can contain positive and negative selection of tags, like
9869 \"+WORK+URGENT-WITHBOSS\".
9870 If optional argument TODO-ONLY is non-nil, only select lines that are
9871 also TODO lines."
9872 (interactive "P")
9873 (org-prepare-agenda-buffers (list (current-buffer)))
9874 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9876 (defvar org-cached-props nil)
9877 (defun org-cached-entry-get (pom property)
9878 (if (or (eq t org-use-property-inheritance)
9879 (and (stringp org-use-property-inheritance)
9880 (string-match org-use-property-inheritance property))
9881 (and (listp org-use-property-inheritance)
9882 (member property org-use-property-inheritance)))
9883 ;; Caching is not possible, check it directly
9884 (org-entry-get pom property 'inherit)
9885 ;; Get all properties, so that we can do complicated checks easily
9886 (cdr (assoc property (or org-cached-props
9887 (setq org-cached-props
9888 (org-entry-properties pom)))))))
9890 (defun org-global-tags-completion-table (&optional files)
9891 "Return the list of all tags in all agenda buffer/files."
9892 (save-excursion
9893 (org-uniquify
9894 (delq nil
9895 (apply 'append
9896 (mapcar
9897 (lambda (file)
9898 (set-buffer (find-file-noselect file))
9899 (append (org-get-buffer-tags)
9900 (mapcar (lambda (x) (if (stringp (car-safe x))
9901 (list (car-safe x)) nil))
9902 org-tag-alist)))
9903 (if (and files (car files))
9904 files
9905 (org-agenda-files))))))))
9907 (defun org-make-tags-matcher (match)
9908 "Create the TAGS//TODO matcher form for the selection string MATCH."
9909 ;; todo-only is scoped dynamically into this function, and the function
9910 ;; may change it if the matcher asks for it.
9911 (unless match
9912 ;; Get a new match request, with completion
9913 (let ((org-last-tags-completion-table
9914 (org-global-tags-completion-table)))
9915 (setq match (org-completing-read-no-ido
9916 "Match: " 'org-tags-completion-function nil nil nil
9917 'org-tags-history))))
9919 ;; Parse the string and create a lisp form
9920 (let ((match0 match)
9921 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9922 minus tag mm
9923 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9924 orterms term orlist re-p str-p level-p level-op time-p
9925 prop-p pn pv po cat-p gv rest)
9926 (if (string-match "/+" match)
9927 ;; match contains also a todo-matching request
9928 (progn
9929 (setq tagsmatch (substring match 0 (match-beginning 0))
9930 todomatch (substring match (match-end 0)))
9931 (if (string-match "^!" todomatch)
9932 (setq todo-only t todomatch (substring todomatch 1)))
9933 (if (string-match "^\\s-*$" todomatch)
9934 (setq todomatch nil)))
9935 ;; only matching tags
9936 (setq tagsmatch match todomatch nil))
9938 ;; Make the tags matcher
9939 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9940 (setq tagsmatcher t)
9941 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9942 (while (setq term (pop orterms))
9943 (while (and (equal (substring term -1) "\\") orterms)
9944 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9945 (while (string-match re term)
9946 (setq rest (substring term (match-end 0))
9947 minus (and (match-end 1)
9948 (equal (match-string 1 term) "-"))
9949 tag (match-string 2 term)
9950 re-p (equal (string-to-char tag) ?{)
9951 level-p (match-end 4)
9952 prop-p (match-end 5)
9953 mm (cond
9954 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9955 (level-p
9956 (setq level-op (org-op-to-function (match-string 3 term)))
9957 `(,level-op level ,(string-to-number
9958 (match-string 4 term))))
9959 (prop-p
9960 (setq pn (match-string 5 term)
9961 po (match-string 6 term)
9962 pv (match-string 7 term)
9963 cat-p (equal pn "CATEGORY")
9964 re-p (equal (string-to-char pv) ?{)
9965 str-p (equal (string-to-char pv) ?\")
9966 time-p (save-match-data
9967 (string-match "^\"[[<].*[]>]\"$" pv))
9968 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9969 (if time-p (setq pv (org-matcher-time pv)))
9970 (setq po (org-op-to-function po (if time-p 'time str-p)))
9971 (cond
9972 ((equal pn "CATEGORY")
9973 (setq gv '(get-text-property (point) 'org-category)))
9974 ((equal pn "TODO")
9975 (setq gv 'todo))
9977 (setq gv `(org-cached-entry-get nil ,pn))))
9978 (if re-p
9979 (if (eq po 'org<>)
9980 `(not (string-match ,pv (or ,gv "")))
9981 `(string-match ,pv (or ,gv "")))
9982 (if str-p
9983 `(,po (or ,gv "") ,pv)
9984 `(,po (string-to-number (or ,gv ""))
9985 ,(string-to-number pv) ))))
9986 (t `(member ,(downcase tag) tags-list)))
9987 mm (if minus (list 'not mm) mm)
9988 term rest)
9989 (push mm tagsmatcher))
9990 (push (if (> (length tagsmatcher) 1)
9991 (cons 'and tagsmatcher)
9992 (car tagsmatcher))
9993 orlist)
9994 (setq tagsmatcher nil))
9995 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9996 (setq tagsmatcher
9997 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9998 ;; Make the todo matcher
9999 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10000 (setq todomatcher t)
10001 (setq orterms (org-split-string todomatch "|") orlist nil)
10002 (while (setq term (pop orterms))
10003 (while (string-match re term)
10004 (setq minus (and (match-end 1)
10005 (equal (match-string 1 term) "-"))
10006 kwd (match-string 2 term)
10007 re-p (equal (string-to-char kwd) ?{)
10008 term (substring term (match-end 0))
10009 mm (if re-p
10010 `(string-match ,(substring kwd 1 -1) todo)
10011 (list 'equal 'todo kwd))
10012 mm (if minus (list 'not mm) mm))
10013 (push mm todomatcher))
10014 (push (if (> (length todomatcher) 1)
10015 (cons 'and todomatcher)
10016 (car todomatcher))
10017 orlist)
10018 (setq todomatcher nil))
10019 (setq todomatcher (if (> (length orlist) 1)
10020 (cons 'or orlist) (car orlist))))
10022 ;; Return the string and lisp forms of the matcher
10023 (setq matcher (if todomatcher
10024 (list 'and tagsmatcher todomatcher)
10025 tagsmatcher))
10026 (cons match0 matcher)))
10028 (defun org-op-to-function (op &optional stringp)
10029 "Turn an operator into the appropriate function."
10030 (setq op
10031 (cond
10032 ((equal op "<" ) '(< string< org-time<))
10033 ((equal op ">" ) '(> org-string> org-time>))
10034 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10035 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10036 ((member op '("=" "==")) '(= string= org-time=))
10037 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10038 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10040 (defun org<> (a b) (not (= a b)))
10041 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10042 (defun org-string>= (a b) (not (string< a b)))
10043 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10044 (defun org-string<> (a b) (not (string= a b)))
10045 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10046 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10047 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10048 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10049 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10050 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10051 (defun org-2ft (s)
10052 "Convert S to a floating point time.
10053 If S is already a number, just return it. If it is a string, parse
10054 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10055 (cond
10056 ((numberp s) s)
10057 ((stringp s)
10058 (condition-case nil
10059 (float-time (apply 'encode-time (org-parse-time-string s)))
10060 (error 0.)))
10061 (t 0.)))
10063 (defun org-time-today ()
10064 "Time in seconds today at 0:00.
10065 Returns the float number of seconds since the beginning of the
10066 epoch to the beginning of today (00:00)."
10067 (float-time (apply 'encode-time
10068 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10070 (defun org-matcher-time (s)
10071 "Interpret a time comparison value."
10072 (save-match-data
10073 (cond
10074 ((string= s "<now>") (float-time))
10075 ((string= s "<today>") (org-time-today))
10076 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10077 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10078 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10079 (+ (org-time-today)
10080 (* (string-to-number (match-string 1 s))
10081 (cdr (assoc (match-string 2 s)
10082 '(("d" . 86400.0) ("w" . 604800.0)
10083 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10084 (t (org-2ft s)))))
10086 (defun org-match-any-p (re list)
10087 "Does re match any element of list?"
10088 (setq list (mapcar (lambda (x) (string-match re x)) list))
10089 (delq nil list))
10091 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10092 (defvar org-tags-overlay (org-make-overlay 1 1))
10093 (org-detach-overlay org-tags-overlay)
10095 (defun org-get-local-tags-at (&optional pos)
10096 "Get a list of tags defined in the current headline."
10097 (org-get-tags-at pos 'local))
10099 (defun org-get-local-tags ()
10100 "Get a list of tags defined in the current headline."
10101 (org-get-tags-at nil 'local))
10103 (defun org-get-tags-at (&optional pos local)
10104 "Get a list of all headline tags applicable at POS.
10105 POS defaults to point. If tags are inherited, the list contains
10106 the targets in the same sequence as the headlines appear, i.e.
10107 the tags of the current headline come last.
10108 When LOCAL is non-nil, only return tags from the current headline,
10109 ignore inherited ones."
10110 (interactive)
10111 (let (tags ltags lastpos parent)
10112 (save-excursion
10113 (save-restriction
10114 (widen)
10115 (goto-char (or pos (point)))
10116 (save-match-data
10117 (catch 'done
10118 (condition-case nil
10119 (progn
10120 (org-back-to-heading t)
10121 (while (not (equal lastpos (point)))
10122 (setq lastpos (point))
10123 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10124 (setq ltags (org-split-string
10125 (org-match-string-no-properties 1) ":"))
10126 (when parent
10127 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10128 (setq tags (append
10129 (if parent
10130 (org-remove-uniherited-tags ltags)
10131 ltags)
10132 tags)))
10133 (or org-use-tag-inheritance (throw 'done t))
10134 (if local (throw 'done t))
10135 (org-up-heading-all 1)
10136 (setq parent t)))
10137 (error nil)))))
10138 (append (org-remove-uniherited-tags org-file-tags) tags))))
10140 (defun org-add-prop-inherited (s)
10141 (add-text-properties 0 (length s) '(inherited t) s)
10144 (defun org-toggle-tag (tag &optional onoff)
10145 "Toggle the tag TAG for the current line.
10146 If ONOFF is `on' or `off', don't toggle but set to this state."
10147 (let (res current)
10148 (save-excursion
10149 (org-back-to-heading t)
10150 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10151 (point-at-eol) t)
10152 (progn
10153 (setq current (match-string 1))
10154 (replace-match ""))
10155 (setq current ""))
10156 (setq current (nreverse (org-split-string current ":")))
10157 (cond
10158 ((eq onoff 'on)
10159 (setq res t)
10160 (or (member tag current) (push tag current)))
10161 ((eq onoff 'off)
10162 (or (not (member tag current)) (setq current (delete tag current))))
10163 (t (if (member tag current)
10164 (setq current (delete tag current))
10165 (setq res t)
10166 (push tag current))))
10167 (end-of-line 1)
10168 (if current
10169 (progn
10170 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10171 (org-set-tags nil t))
10172 (delete-horizontal-space))
10173 (run-hooks 'org-after-tags-change-hook))
10174 res))
10176 (defun org-align-tags-here (to-col)
10177 ;; Assumes that this is a headline
10178 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10179 (beginning-of-line 1)
10180 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10181 (< pos (match-beginning 2)))
10182 (progn
10183 (setq tags-l (- (match-end 2) (match-beginning 2)))
10184 (goto-char (match-beginning 1))
10185 (insert " ")
10186 (delete-region (point) (1+ (match-beginning 2)))
10187 (setq ncol (max (1+ (current-column))
10188 (1+ col)
10189 (if (> to-col 0)
10190 to-col
10191 (- (abs to-col) tags-l))))
10192 (setq p (point))
10193 (insert (make-string (- ncol (current-column)) ?\ ))
10194 (setq ncol (current-column))
10195 (when indent-tabs-mode (tabify p (point-at-eol)))
10196 (org-move-to-column (min ncol col) t))
10197 (goto-char pos))))
10199 (defun org-set-tags-command (&optional arg just-align)
10200 "Call the set-tags command for the current entry."
10201 (interactive "P")
10202 (if (org-on-heading-p)
10203 (org-set-tags arg just-align)
10204 (save-excursion
10205 (org-back-to-heading t)
10206 (org-set-tags arg just-align))))
10208 (defun org-set-tags (&optional arg just-align)
10209 "Set the tags for the current headline.
10210 With prefix ARG, realign all tags in headings in the current buffer."
10211 (interactive "P")
10212 (let* ((re (concat "^" outline-regexp))
10213 (current (org-get-tags-string))
10214 (col (current-column))
10215 (org-setting-tags t)
10216 table current-tags inherited-tags ; computed below when needed
10217 tags p0 c0 c1 rpl)
10218 (if arg
10219 (save-excursion
10220 (goto-char (point-min))
10221 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10222 (while (re-search-forward re nil t)
10223 (org-set-tags nil t)
10224 (end-of-line 1)))
10225 (message "All tags realigned to column %d" org-tags-column))
10226 (if just-align
10227 (setq tags current)
10228 ;; Get a new set of tags from the user
10229 (save-excursion
10230 (setq table (or org-tag-alist (org-get-buffer-tags))
10231 org-last-tags-completion-table table
10232 current-tags (org-split-string current ":")
10233 inherited-tags (nreverse
10234 (nthcdr (length current-tags)
10235 (nreverse (org-get-tags-at))))
10236 tags
10237 (if (or (eq t org-use-fast-tag-selection)
10238 (and org-use-fast-tag-selection
10239 (delq nil (mapcar 'cdr table))))
10240 (org-fast-tag-selection
10241 current-tags inherited-tags table
10242 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10243 (let ((org-add-colon-after-tag-completion t))
10244 (org-trim
10245 (org-without-partial-completion
10246 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10247 nil nil current 'org-tags-history)))))))
10248 (while (string-match "[-+&]+" tags)
10249 ;; No boolean logic, just a list
10250 (setq tags (replace-match ":" t t tags))))
10252 (if (string-match "\\`[\t ]*\\'" tags)
10253 (setq tags "")
10254 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10255 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10257 ;; Insert new tags at the correct column
10258 (beginning-of-line 1)
10259 (cond
10260 ((and (equal current "") (equal tags "")))
10261 ((re-search-forward
10262 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10263 (point-at-eol) t)
10264 (if (equal tags "")
10265 (setq rpl "")
10266 (goto-char (match-beginning 0))
10267 (setq c0 (current-column) p0 (point)
10268 c1 (max (1+ c0) (if (> org-tags-column 0)
10269 org-tags-column
10270 (- (- org-tags-column) (length tags))))
10271 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10272 (replace-match rpl t t)
10273 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10274 tags)
10275 (t (error "Tags alignment failed")))
10276 (org-move-to-column col)
10277 (unless just-align
10278 (run-hooks 'org-after-tags-change-hook)))))
10280 (defun org-change-tag-in-region (beg end tag off)
10281 "Add or remove TAG for each entry in the region.
10282 This works in the agenda, and also in an org-mode buffer."
10283 (interactive
10284 (list (region-beginning) (region-end)
10285 (let ((org-last-tags-completion-table
10286 (if (org-mode-p)
10287 (org-get-buffer-tags)
10288 (org-global-tags-completion-table))))
10289 (org-ido-completing-read
10290 "Tag: " 'org-tags-completion-function nil nil nil
10291 'org-tags-history))
10292 (progn
10293 (message "[s]et or [r]emove? ")
10294 (equal (read-char-exclusive) ?r))))
10295 (if (fboundp 'deactivate-mark) (deactivate-mark))
10296 (let ((agendap (equal major-mode 'org-agenda-mode))
10297 l1 l2 m buf pos newhead (cnt 0))
10298 (goto-char end)
10299 (setq l2 (1- (org-current-line)))
10300 (goto-char beg)
10301 (setq l1 (org-current-line))
10302 (loop for l from l1 to l2 do
10303 (goto-line l)
10304 (setq m (get-text-property (point) 'org-hd-marker))
10305 (when (or (and (org-mode-p) (org-on-heading-p))
10306 (and agendap m))
10307 (setq buf (if agendap (marker-buffer m) (current-buffer))
10308 pos (if agendap m (point)))
10309 (with-current-buffer buf
10310 (save-excursion
10311 (save-restriction
10312 (goto-char pos)
10313 (setq cnt (1+ cnt))
10314 (org-toggle-tag tag (if off 'off 'on))
10315 (setq newhead (org-get-heading)))))
10316 (and agendap (org-agenda-change-all-lines newhead m))))
10317 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10319 (defun org-tags-completion-function (string predicate &optional flag)
10320 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10321 (confirm (lambda (x) (stringp (car x)))))
10322 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10323 (setq s1 (match-string 1 string)
10324 s2 (match-string 2 string))
10325 (setq s1 "" s2 string))
10326 (cond
10327 ((eq flag nil)
10328 ;; try completion
10329 (setq rtn (try-completion s2 ctable confirm))
10330 (if (stringp rtn)
10331 (setq rtn
10332 (concat s1 s2 (substring rtn (length s2))
10333 (if (and org-add-colon-after-tag-completion
10334 (assoc rtn ctable))
10335 ":" ""))))
10336 rtn)
10337 ((eq flag t)
10338 ;; all-completions
10339 (all-completions s2 ctable confirm)
10341 ((eq flag 'lambda)
10342 ;; exact match?
10343 (assoc s2 ctable)))
10346 (defun org-fast-tag-insert (kwd tags face &optional end)
10347 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10348 (insert (format "%-12s" (concat kwd ":"))
10349 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10350 (or end "")))
10352 (defun org-fast-tag-show-exit (flag)
10353 (save-excursion
10354 (goto-line 3)
10355 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10356 (replace-match ""))
10357 (when flag
10358 (end-of-line 1)
10359 (org-move-to-column (- (window-width) 19) t)
10360 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10362 (defun org-set-current-tags-overlay (current prefix)
10363 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10364 (if (featurep 'xemacs)
10365 (org-overlay-display org-tags-overlay (concat prefix s)
10366 'secondary-selection)
10367 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10368 (org-overlay-display org-tags-overlay (concat prefix s)))))
10370 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10371 "Fast tag selection with single keys.
10372 CURRENT is the current list of tags in the headline, INHERITED is the
10373 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10374 possibly with grouping information. TODO-TABLE is a similar table with
10375 TODO keywords, should these have keys assigned to them.
10376 If the keys are nil, a-z are automatically assigned.
10377 Returns the new tags string, or nil to not change the current settings."
10378 (let* ((fulltable (append table todo-table))
10379 (maxlen (apply 'max (mapcar
10380 (lambda (x)
10381 (if (stringp (car x)) (string-width (car x)) 0))
10382 fulltable)))
10383 (buf (current-buffer))
10384 (expert (eq org-fast-tag-selection-single-key 'expert))
10385 (buffer-tags nil)
10386 (fwidth (+ maxlen 3 1 3))
10387 (ncol (/ (- (window-width) 4) fwidth))
10388 (i-face 'org-done)
10389 (c-face 'org-todo)
10390 tg cnt e c char c1 c2 ntable tbl rtn
10391 ov-start ov-end ov-prefix
10392 (exit-after-next org-fast-tag-selection-single-key)
10393 (done-keywords org-done-keywords)
10394 groups ingroup)
10395 (save-excursion
10396 (beginning-of-line 1)
10397 (if (looking-at
10398 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10399 (setq ov-start (match-beginning 1)
10400 ov-end (match-end 1)
10401 ov-prefix "")
10402 (setq ov-start (1- (point-at-eol))
10403 ov-end (1+ ov-start))
10404 (skip-chars-forward "^\n\r")
10405 (setq ov-prefix
10406 (concat
10407 (buffer-substring (1- (point)) (point))
10408 (if (> (current-column) org-tags-column)
10410 (make-string (- org-tags-column (current-column)) ?\ ))))))
10411 (org-move-overlay org-tags-overlay ov-start ov-end)
10412 (save-window-excursion
10413 (if expert
10414 (set-buffer (get-buffer-create " *Org tags*"))
10415 (delete-other-windows)
10416 (split-window-vertically)
10417 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10418 (erase-buffer)
10419 (org-set-local 'org-done-keywords done-keywords)
10420 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10421 (org-fast-tag-insert "Current" current c-face "\n\n")
10422 (org-fast-tag-show-exit exit-after-next)
10423 (org-set-current-tags-overlay current ov-prefix)
10424 (setq tbl fulltable char ?a cnt 0)
10425 (while (setq e (pop tbl))
10426 (cond
10427 ((equal e '(:startgroup))
10428 (push '() groups) (setq ingroup t)
10429 (when (not (= cnt 0))
10430 (setq cnt 0)
10431 (insert "\n"))
10432 (insert "{ "))
10433 ((equal e '(:endgroup))
10434 (setq ingroup nil cnt 0)
10435 (insert "}\n"))
10436 ((equal e '(:newline))
10437 (insert "\n "))
10439 (setq tg (car e) c2 nil)
10440 (if (cdr e)
10441 (setq c (cdr e))
10442 ;; automatically assign a character.
10443 (setq c1 (string-to-char
10444 (downcase (substring
10445 tg (if (= (string-to-char tg) ?@) 1 0)))))
10446 (if (or (rassoc c1 ntable) (rassoc c1 table))
10447 (while (or (rassoc char ntable) (rassoc char table))
10448 (setq char (1+ char)))
10449 (setq c2 c1))
10450 (setq c (or c2 char)))
10451 (if ingroup (push tg (car groups)))
10452 (setq tg (org-add-props tg nil 'face
10453 (cond
10454 ((not (assoc tg table))
10455 (org-get-todo-face tg))
10456 ((member tg current) c-face)
10457 ((member tg inherited) i-face)
10458 (t nil))))
10459 (if (and (= cnt 0) (not ingroup)) (insert " "))
10460 (insert "[" c "] " tg (make-string
10461 (- fwidth 4 (length tg)) ?\ ))
10462 (push (cons tg c) ntable)
10463 (when (= (setq cnt (1+ cnt)) ncol)
10464 (insert "\n")
10465 (if ingroup (insert " "))
10466 (setq cnt 0)))))
10467 (setq ntable (nreverse ntable))
10468 (insert "\n")
10469 (goto-char (point-min))
10470 (if (not expert) (org-fit-window-to-buffer))
10471 (setq rtn
10472 (catch 'exit
10473 (while t
10474 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10475 (if groups " [!] no groups" " [!]groups")
10476 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10477 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10478 (cond
10479 ((= c ?\r) (throw 'exit t))
10480 ((= c ?!)
10481 (setq groups (not groups))
10482 (goto-char (point-min))
10483 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10484 ((= c ?\C-c)
10485 (if (not expert)
10486 (org-fast-tag-show-exit
10487 (setq exit-after-next (not exit-after-next)))
10488 (setq expert nil)
10489 (delete-other-windows)
10490 (split-window-vertically)
10491 (org-switch-to-buffer-other-window " *Org tags*")
10492 (org-fit-window-to-buffer)))
10493 ((or (= c ?\C-g)
10494 (and (= c ?q) (not (rassoc c ntable))))
10495 (org-detach-overlay org-tags-overlay)
10496 (setq quit-flag t))
10497 ((= c ?\ )
10498 (setq current nil)
10499 (if exit-after-next (setq exit-after-next 'now)))
10500 ((= c ?\t)
10501 (condition-case nil
10502 (setq tg (org-ido-completing-read
10503 "Tag: "
10504 (or buffer-tags
10505 (with-current-buffer buf
10506 (org-get-buffer-tags)))))
10507 (quit (setq tg "")))
10508 (when (string-match "\\S-" tg)
10509 (add-to-list 'buffer-tags (list tg))
10510 (if (member tg current)
10511 (setq current (delete tg current))
10512 (push tg current)))
10513 (if exit-after-next (setq exit-after-next 'now)))
10514 ((setq e (rassoc c todo-table) tg (car e))
10515 (with-current-buffer buf
10516 (save-excursion (org-todo tg)))
10517 (if exit-after-next (setq exit-after-next 'now)))
10518 ((setq e (rassoc c ntable) tg (car e))
10519 (if (member tg current)
10520 (setq current (delete tg current))
10521 (loop for g in groups do
10522 (if (member tg g)
10523 (mapc (lambda (x)
10524 (setq current (delete x current)))
10525 g)))
10526 (push tg current))
10527 (if exit-after-next (setq exit-after-next 'now))))
10529 ;; Create a sorted list
10530 (setq current
10531 (sort current
10532 (lambda (a b)
10533 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10534 (if (eq exit-after-next 'now) (throw 'exit t))
10535 (goto-char (point-min))
10536 (beginning-of-line 2)
10537 (delete-region (point) (point-at-eol))
10538 (org-fast-tag-insert "Current" current c-face)
10539 (org-set-current-tags-overlay current ov-prefix)
10540 (while (re-search-forward
10541 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10542 (setq tg (match-string 1))
10543 (add-text-properties
10544 (match-beginning 1) (match-end 1)
10545 (list 'face
10546 (cond
10547 ((member tg current) c-face)
10548 ((member tg inherited) i-face)
10549 (t (get-text-property (match-beginning 1) 'face))))))
10550 (goto-char (point-min)))))
10551 (org-detach-overlay org-tags-overlay)
10552 (if rtn
10553 (mapconcat 'identity current ":")
10554 nil))))
10556 (defun org-get-tags-string ()
10557 "Get the TAGS string in the current headline."
10558 (unless (org-on-heading-p t)
10559 (error "Not on a heading"))
10560 (save-excursion
10561 (beginning-of-line 1)
10562 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10563 (org-match-string-no-properties 1)
10564 "")))
10566 (defun org-get-tags ()
10567 "Get the list of tags specified in the current headline."
10568 (org-split-string (org-get-tags-string) ":"))
10570 (defun org-get-buffer-tags ()
10571 "Get a table of all tags used in the buffer, for completion."
10572 (let (tags)
10573 (save-excursion
10574 (goto-char (point-min))
10575 (while (re-search-forward
10576 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10577 (when (equal (char-after (point-at-bol 0)) ?*)
10578 (mapc (lambda (x) (add-to-list 'tags x))
10579 (org-split-string (org-match-string-no-properties 1) ":")))))
10580 (mapcar 'list tags)))
10582 ;;;; The mapping API
10584 ;;;###autoload
10585 (defun org-map-entries (func &optional match scope &rest skip)
10586 "Call FUNC at each headline selected by MATCH in SCOPE.
10588 FUNC is a function or a lisp form. The function will be called without
10589 arguments, with the cursor positioned at the beginning of the headline.
10590 The return values of all calls to the function will be collected and
10591 returned as a list.
10593 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10594 Only headlines that are matched by this query will be considered during
10595 the iteration. When MATCH is nil or t, all headlines will be
10596 visited by the iteration.
10598 SCOPE determines the scope of this command. It can be any of:
10600 nil The current buffer, respecting the restriction if any
10601 tree The subtree started with the entry at point
10602 file The current buffer, without restriction
10603 file-with-archives
10604 The current buffer, and any archives associated with it
10605 agenda All agenda files
10606 agenda-with-archives
10607 All agenda files with any archive files associated with them
10608 \(file1 file2 ...)
10609 If this is a list, all files in the list will be scanned
10611 The remaining args are treated as settings for the skipping facilities of
10612 the scanner. The following items can be given here:
10614 archive skip trees with the archive tag.
10615 comment skip trees with the COMMENT keyword
10616 function or Emacs Lisp form:
10617 will be used as value for `org-agenda-skip-function', so whenever
10618 the the function returns t, FUNC will not be called for that
10619 entry and search will continue from the point where the
10620 function leaves it."
10621 (let* ((org-agenda-archives-mode nil) ; just to make sure
10622 (org-agenda-skip-archived-trees (memq 'archive skip))
10623 (org-agenda-skip-comment-trees (memq 'comment skip))
10624 (org-agenda-skip-function
10625 (car (org-delete-all '(comment archive) skip)))
10626 (org-tags-match-list-sublevels t)
10627 matcher file res
10628 org-todo-keywords-for-agenda
10629 org-done-keywords-for-agenda
10630 org-todo-keyword-alist-for-agenda
10631 org-tag-alist-for-agenda)
10633 (cond
10634 ((eq match t) (setq matcher t))
10635 ((eq match nil) (setq matcher t))
10636 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10638 (save-excursion
10639 (save-restriction
10640 (when (eq scope 'tree)
10641 (org-back-to-heading t)
10642 (org-narrow-to-subtree)
10643 (setq scope nil))
10645 (if (not scope)
10646 (progn
10647 (org-prepare-agenda-buffers
10648 (list (buffer-file-name (current-buffer))))
10649 (setq res (org-scan-tags func matcher)))
10650 ;; Get the right scope
10651 (cond
10652 ((and scope (listp scope) (symbolp (car scope)))
10653 (setq scope (eval scope)))
10654 ((eq scope 'agenda)
10655 (setq scope (org-agenda-files t)))
10656 ((eq scope 'agenda-with-archives)
10657 (setq scope (org-agenda-files t))
10658 (setq scope (org-add-archive-files scope)))
10659 ((eq scope 'file)
10660 (setq scope (list (buffer-file-name))))
10661 ((eq scope 'file-with-archives)
10662 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10663 (org-prepare-agenda-buffers scope)
10664 (while (setq file (pop scope))
10665 (with-current-buffer (org-find-base-buffer-visiting file)
10666 (save-excursion
10667 (save-restriction
10668 (widen)
10669 (goto-char (point-min))
10670 (setq res (append res (org-scan-tags func matcher))))))))))
10671 res))
10673 ;;;; Properties
10675 ;;; Setting and retrieving properties
10677 (defconst org-special-properties
10678 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10679 "TIMESTAMP" "TIMESTAMP_IA")
10680 "The special properties valid in Org-mode.
10682 These are properties that are not defined in the property drawer,
10683 but in some other way.")
10685 (defconst org-default-properties
10686 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10687 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10688 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10689 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10690 "Some properties that are used by Org-mode for various purposes.
10691 Being in this list makes sure that they are offered for completion.")
10693 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10694 "Regular expression matching the first line of a property drawer.")
10696 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10697 "Regular expression matching the first line of a property drawer.")
10699 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10700 "Regular expression matching the first line of a property drawer.")
10702 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10703 "Regular expression matching the first line of a property drawer.")
10705 (defconst org-property-drawer-re
10706 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10707 org-property-end-re "\\)\n?")
10708 "Matches an entire property drawer.")
10710 (defconst org-clock-drawer-re
10711 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10712 org-property-end-re "\\)\n?")
10713 "Matches an entire clock drawer.")
10715 (defun org-property-action ()
10716 "Do an action on properties."
10717 (interactive)
10718 (let (c)
10719 (org-at-property-p)
10720 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10721 (setq c (read-char-exclusive))
10722 (cond
10723 ((equal c ?s)
10724 (call-interactively 'org-set-property))
10725 ((equal c ?d)
10726 (call-interactively 'org-delete-property))
10727 ((equal c ?D)
10728 (call-interactively 'org-delete-property-globally))
10729 ((equal c ?c)
10730 (call-interactively 'org-compute-property-at-point))
10731 (t (error "No such property action %c" c)))))
10733 (defun org-at-property-p ()
10734 "Is the cursor in a property line?"
10735 ;; FIXME: Does not check if we are actually in the drawer.
10736 ;; FIXME: also returns true on any drawers.....
10737 ;; This is used by C-c C-c for property action.
10738 (save-excursion
10739 (beginning-of-line 1)
10740 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10742 (defun org-get-property-block (&optional beg end force)
10743 "Return the (beg . end) range of the body of the property drawer.
10744 BEG and END can be beginning and end of subtree, if not given
10745 they will be found.
10746 If the drawer does not exist and FORCE is non-nil, create the drawer."
10747 (catch 'exit
10748 (save-excursion
10749 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10750 (end (or end (progn (outline-next-heading) (point)))))
10751 (goto-char beg)
10752 (if (re-search-forward org-property-start-re end t)
10753 (setq beg (1+ (match-end 0)))
10754 (if force
10755 (save-excursion
10756 (org-insert-property-drawer)
10757 (setq end (progn (outline-next-heading) (point))))
10758 (throw 'exit nil))
10759 (goto-char beg)
10760 (if (re-search-forward org-property-start-re end t)
10761 (setq beg (1+ (match-end 0)))))
10762 (if (re-search-forward org-property-end-re end t)
10763 (setq end (match-beginning 0))
10764 (or force (throw 'exit nil))
10765 (goto-char beg)
10766 (setq end beg)
10767 (org-indent-line-function)
10768 (insert ":END:\n"))
10769 (cons beg end)))))
10771 (defun org-entry-properties (&optional pom which)
10772 "Get all properties of the entry at point-or-marker POM.
10773 This includes the TODO keyword, the tags, time strings for deadline,
10774 scheduled, and clocking, and any additional properties defined in the
10775 entry. The return value is an alist, keys may occur multiple times
10776 if the property key was used several times.
10777 POM may also be nil, in which case the current entry is used.
10778 If WHICH is nil or `all', get all properties. If WHICH is
10779 `special' or `standard', only get that subclass."
10780 (setq which (or which 'all))
10781 (org-with-point-at pom
10782 (let ((clockstr (substring org-clock-string 0 -1))
10783 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10784 beg end range props sum-props key value string clocksum)
10785 (save-excursion
10786 (when (condition-case nil
10787 (and (org-mode-p) (org-back-to-heading t))
10788 (error nil))
10789 (setq beg (point))
10790 (setq sum-props (get-text-property (point) 'org-summaries))
10791 (setq clocksum (get-text-property (point) :org-clock-minutes))
10792 (outline-next-heading)
10793 (setq end (point))
10794 (when (memq which '(all special))
10795 ;; Get the special properties, like TODO and tags
10796 (goto-char beg)
10797 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10798 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10799 (when (looking-at org-priority-regexp)
10800 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10801 (when (and (setq value (org-get-tags-string))
10802 (string-match "\\S-" value))
10803 (push (cons "TAGS" value) props))
10804 (when (setq value (org-get-tags-at))
10805 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10806 props))
10807 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10808 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10809 string (if (equal key clockstr)
10810 (org-no-properties
10811 (org-trim
10812 (buffer-substring
10813 (match-beginning 3) (goto-char (point-at-eol)))))
10814 (substring (org-match-string-no-properties 3) 1 -1)))
10815 (unless key
10816 (if (= (char-after (match-beginning 3)) ?\[)
10817 (setq key "TIMESTAMP_IA")
10818 (setq key "TIMESTAMP")))
10819 (when (or (equal key clockstr) (not (assoc key props)))
10820 (push (cons key string) props)))
10824 (when (memq which '(all standard))
10825 ;; Get the standard properties, like :PORP: ...
10826 (setq range (org-get-property-block beg end))
10827 (when range
10828 (goto-char (car range))
10829 (while (re-search-forward
10830 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10831 (cdr range) t)
10832 (setq key (org-match-string-no-properties 1)
10833 value (org-trim (or (org-match-string-no-properties 2) "")))
10834 (unless (member key excluded)
10835 (push (cons key (or value "")) props)))))
10836 (if clocksum
10837 (push (cons "CLOCKSUM"
10838 (org-columns-number-to-string (/ (float clocksum) 60.)
10839 'add_times))
10840 props))
10841 (unless (assoc "CATEGORY" props)
10842 (setq value (or (org-get-category)
10843 (progn (org-refresh-category-properties)
10844 (org-get-category))))
10845 (push (cons "CATEGORY" value) props))
10846 (append sum-props (nreverse props)))))))
10848 (defun org-entry-get (pom property &optional inherit)
10849 "Get value of PROPERTY for entry at point-or-marker POM.
10850 If INHERIT is non-nil and the entry does not have the property,
10851 then also check higher levels of the hierarchy.
10852 If INHERIT is the symbol `selective', use inheritance only if the setting
10853 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10854 If the property is present but empty, the return value is the empty string.
10855 If the property is not present at all, nil is returned."
10856 (org-with-point-at pom
10857 (if (and inherit (if (eq inherit 'selective)
10858 (org-property-inherit-p property)
10860 (org-entry-get-with-inheritance property)
10861 (if (member property org-special-properties)
10862 ;; We need a special property. Use brute force, get all properties.
10863 (cdr (assoc property (org-entry-properties nil 'special)))
10864 (let ((range (org-get-property-block)))
10865 (if (and range
10866 (goto-char (car range))
10867 (re-search-forward
10868 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10869 (cdr range) t))
10870 ;; Found the property, return it.
10871 (if (match-end 1)
10872 (org-match-string-no-properties 1)
10873 "")))))))
10875 (defun org-property-or-variable-value (var &optional inherit)
10876 "Check if there is a property fixing the value of VAR.
10877 If yes, return this value. If not, return the current value of the variable."
10878 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10879 (if (and prop (stringp prop) (string-match "\\S-" prop))
10880 (read prop)
10881 (symbol-value var))))
10883 (defun org-entry-delete (pom property)
10884 "Delete the property PROPERTY from entry at point-or-marker POM."
10885 (org-with-point-at pom
10886 (if (member property org-special-properties)
10887 nil ; cannot delete these properties.
10888 (let ((range (org-get-property-block)))
10889 (if (and range
10890 (goto-char (car range))
10891 (re-search-forward
10892 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10893 (cdr range) t))
10894 (progn
10895 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10897 nil)))))
10899 ;; Multi-values properties are properties that contain multiple values
10900 ;; These values are assumed to be single words, separated by whitespace.
10901 (defun org-entry-add-to-multivalued-property (pom property value)
10902 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10903 (let* ((old (org-entry-get pom property))
10904 (values (and old (org-split-string old "[ \t]"))))
10905 (setq value (org-entry-protect-space value))
10906 (unless (member value values)
10907 (setq values (cons value values))
10908 (org-entry-put pom property
10909 (mapconcat 'identity values " ")))))
10911 (defun org-entry-remove-from-multivalued-property (pom property value)
10912 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10913 (let* ((old (org-entry-get pom property))
10914 (values (and old (org-split-string old "[ \t]"))))
10915 (setq value (org-entry-protect-space value))
10916 (when (member value values)
10917 (setq values (delete value values))
10918 (org-entry-put pom property
10919 (mapconcat 'identity values " ")))))
10921 (defun org-entry-member-in-multivalued-property (pom property value)
10922 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10923 (let* ((old (org-entry-get pom property))
10924 (values (and old (org-split-string old "[ \t]"))))
10925 (setq value (org-entry-protect-space value))
10926 (member value values)))
10928 (defun org-entry-get-multivalued-property (pom property)
10929 "Return a list of values in a multivalued property."
10930 (let* ((value (org-entry-get pom property))
10931 (values (and value (org-split-string value "[ \t]"))))
10932 (mapcar 'org-entry-restore-space values)))
10934 (defun org-entry-put-multivalued-property (pom property &rest values)
10935 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10936 VALUES should be a list of strings. Spaces will be protected."
10937 (org-entry-put pom property
10938 (mapconcat 'org-entry-protect-space values " "))
10939 (let* ((value (org-entry-get pom property))
10940 (values (and value (org-split-string value "[ \t]"))))
10941 (mapcar 'org-entry-restore-space values)))
10943 (defun org-entry-protect-space (s)
10944 "Protect spaces and newline in string S."
10945 (while (string-match " " s)
10946 (setq s (replace-match "%20" t t s)))
10947 (while (string-match "\n" s)
10948 (setq s (replace-match "%0A" t t s)))
10951 (defun org-entry-restore-space (s)
10952 "Restore spaces and newline in string S."
10953 (while (string-match "%20" s)
10954 (setq s (replace-match " " t t s)))
10955 (while (string-match "%0A" s)
10956 (setq s (replace-match "\n" t t s)))
10959 (defvar org-entry-property-inherited-from (make-marker)
10960 "Marker pointing to the entry from where a property was inherited.
10961 Each call to `org-entry-get-with-inheritance' will set this marker to the
10962 location of the entry where the inheritance search matched. If there was
10963 no match, the marker will point nowhere.
10964 Note that also `org-entry-get' calls this function, if the INHERIT flag
10965 is set.")
10967 (defun org-entry-get-with-inheritance (property)
10968 "Get entry property, and search higher levels if not present."
10969 (move-marker org-entry-property-inherited-from nil)
10970 (let (tmp)
10971 (save-excursion
10972 (save-restriction
10973 (widen)
10974 (catch 'ex
10975 (while t
10976 (when (setq tmp (org-entry-get nil property))
10977 (org-back-to-heading t)
10978 (move-marker org-entry-property-inherited-from (point))
10979 (throw 'ex tmp))
10980 (or (org-up-heading-safe) (throw 'ex nil)))))
10981 (or tmp
10982 (cdr (assoc property org-file-properties))
10983 (cdr (assoc property org-global-properties))
10984 (cdr (assoc property org-global-properties-fixed))))))
10986 (defun org-entry-put (pom property value)
10987 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10988 (org-with-point-at pom
10989 (org-back-to-heading t)
10990 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10991 range)
10992 (cond
10993 ((equal property "TODO")
10994 (when (and (stringp value) (string-match "\\S-" value)
10995 (not (member value org-todo-keywords-1)))
10996 (error "\"%s\" is not a valid TODO state" value))
10997 (if (or (not value)
10998 (not (string-match "\\S-" value)))
10999 (setq value 'none))
11000 (org-todo value)
11001 (org-set-tags nil 'align))
11002 ((equal property "PRIORITY")
11003 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11004 (string-to-char value) ?\ ))
11005 (org-set-tags nil 'align))
11006 ((equal property "SCHEDULED")
11007 (if (re-search-forward org-scheduled-time-regexp end t)
11008 (cond
11009 ((eq value 'earlier) (org-timestamp-change -1 'day))
11010 ((eq value 'later) (org-timestamp-change 1 'day))
11011 (t (call-interactively 'org-schedule)))
11012 (call-interactively 'org-schedule)))
11013 ((equal property "DEADLINE")
11014 (if (re-search-forward org-deadline-time-regexp end t)
11015 (cond
11016 ((eq value 'earlier) (org-timestamp-change -1 'day))
11017 ((eq value 'later) (org-timestamp-change 1 'day))
11018 (t (call-interactively 'org-deadline)))
11019 (call-interactively 'org-deadline)))
11020 ((member property org-special-properties)
11021 (error "The %s property can not yet be set with `org-entry-put'"
11022 property))
11023 (t ; a non-special property
11024 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11025 (setq range (org-get-property-block beg end 'force))
11026 (goto-char (car range))
11027 (if (re-search-forward
11028 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11029 (progn
11030 (delete-region (match-beginning 1) (match-end 1))
11031 (goto-char (match-beginning 1)))
11032 (goto-char (cdr range))
11033 (insert "\n")
11034 (backward-char 1)
11035 (org-indent-line-function)
11036 (insert ":" property ":"))
11037 (and value (insert " " value))
11038 (org-indent-line-function)))))))
11040 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11041 "Get all property keys in the current buffer.
11042 With INCLUDE-SPECIALS, also list the special properties that reflect things
11043 like tags and TODO state.
11044 With INCLUDE-DEFAULTS, also include properties that has special meaning
11045 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11046 With INCLUDE-COLUMNS, also include property names given in COLUMN
11047 formats in the current buffer."
11048 (let (rtn range cfmt s p)
11049 (save-excursion
11050 (save-restriction
11051 (widen)
11052 (goto-char (point-min))
11053 (while (re-search-forward org-property-start-re nil t)
11054 (setq range (org-get-property-block))
11055 (goto-char (car range))
11056 (while (re-search-forward
11057 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11058 (cdr range) t)
11059 (add-to-list 'rtn (org-match-string-no-properties 1)))
11060 (outline-next-heading))))
11062 (when include-specials
11063 (setq rtn (append org-special-properties rtn)))
11065 (when include-defaults
11066 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11068 (when include-columns
11069 (save-excursion
11070 (save-restriction
11071 (widen)
11072 (goto-char (point-min))
11073 (while (re-search-forward
11074 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11075 nil t)
11076 (setq cfmt (match-string 2) s 0)
11077 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11078 cfmt s)
11079 (setq s (match-end 0)
11080 p (match-string 1 cfmt))
11081 (unless (or (equal p "ITEM")
11082 (member p org-special-properties))
11083 (add-to-list 'rtn (match-string 1 cfmt))))))))
11085 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11087 (defun org-property-values (key)
11088 "Return a list of all values of property KEY."
11089 (save-excursion
11090 (save-restriction
11091 (widen)
11092 (goto-char (point-min))
11093 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11094 values)
11095 (while (re-search-forward re nil t)
11096 (add-to-list 'values (org-trim (match-string 1))))
11097 (delete "" values)))))
11099 (defun org-insert-property-drawer ()
11100 "Insert a property drawer into the current entry."
11101 (interactive)
11102 (org-back-to-heading t)
11103 (looking-at outline-regexp)
11104 (let ((indent (- (match-end 0)(match-beginning 0)))
11105 (beg (point))
11106 (re (concat "^[ \t]*" org-keyword-time-regexp))
11107 end hiddenp)
11108 (outline-next-heading)
11109 (setq end (point))
11110 (goto-char beg)
11111 (while (re-search-forward re end t))
11112 (setq hiddenp (org-invisible-p))
11113 (end-of-line 1)
11114 (and (equal (char-after) ?\n) (forward-char 1))
11115 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11116 (if (member (match-string 1) '("CLOCK:" ":END:"))
11117 ;; just skip this line
11118 (beginning-of-line 2)
11119 ;; Drawer start, find the end
11120 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11121 (beginning-of-line 1)))
11122 (org-skip-over-state-notes)
11123 (skip-chars-backward " \t\n\r")
11124 (if (eq (char-before) ?*) (forward-char 1))
11125 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11126 (beginning-of-line 0)
11127 (org-indent-to-column indent)
11128 (beginning-of-line 2)
11129 (org-indent-to-column indent)
11130 (beginning-of-line 0)
11131 (if hiddenp
11132 (save-excursion
11133 (org-back-to-heading t)
11134 (hide-entry))
11135 (org-flag-drawer t))))
11137 (defun org-set-property (property value)
11138 "In the current entry, set PROPERTY to VALUE.
11139 When called interactively, this will prompt for a property name, offering
11140 completion on existing and default properties. And then it will prompt
11141 for a value, offering completion either on allowed values (via an inherited
11142 xxx_ALL property) or on existing values in other instances of this property
11143 in the current file."
11144 (interactive
11145 (let* ((completion-ignore-case t)
11146 (keys (org-buffer-property-keys nil t t))
11147 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11148 (prop (if (member prop0 keys)
11149 prop0
11150 (or (cdr (assoc (downcase prop0)
11151 (mapcar (lambda (x) (cons (downcase x) x))
11152 keys)))
11153 prop0)))
11154 (cur (org-entry-get nil prop))
11155 (allowed (org-property-get-allowed-values nil prop 'table))
11156 (existing (mapcar 'list (org-property-values prop)))
11157 (val (if allowed
11158 (org-completing-read "Value: " allowed nil 'req-match)
11159 (let (org-completion-use-ido)
11160 (org-completing-read
11161 (concat "Value" (if (and cur (string-match "\\S-" cur))
11162 (concat "[" cur "]") "")
11163 ": ")
11164 existing nil nil "" nil cur)))))
11165 (list prop (if (equal val "") cur val))))
11166 (unless (equal (org-entry-get nil property) value)
11167 (org-entry-put nil property value)))
11169 (defun org-delete-property (property)
11170 "In the current entry, delete PROPERTY."
11171 (interactive
11172 (let* ((completion-ignore-case t)
11173 (prop (org-ido-completing-read
11174 "Property: " (org-entry-properties nil 'standard))))
11175 (list prop)))
11176 (message "Property %s %s" property
11177 (if (org-entry-delete nil property)
11178 "deleted"
11179 "was not present in the entry")))
11181 (defun org-delete-property-globally (property)
11182 "Remove PROPERTY globally, from all entries."
11183 (interactive
11184 (let* ((completion-ignore-case t)
11185 (prop (org-ido-completing-read
11186 "Globally remove property: "
11187 (mapcar 'list (org-buffer-property-keys)))))
11188 (list prop)))
11189 (save-excursion
11190 (save-restriction
11191 (widen)
11192 (goto-char (point-min))
11193 (let ((cnt 0))
11194 (while (re-search-forward
11195 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11196 nil t)
11197 (setq cnt (1+ cnt))
11198 (replace-match ""))
11199 (message "Property \"%s\" removed from %d entries" property cnt)))))
11201 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11203 (defun org-compute-property-at-point ()
11204 "Compute the property at point.
11205 This looks for an enclosing column format, extracts the operator and
11206 then applies it to the property in the column format's scope."
11207 (interactive)
11208 (unless (org-at-property-p)
11209 (error "Not at a property"))
11210 (let ((prop (org-match-string-no-properties 2)))
11211 (org-columns-get-format-and-top-level)
11212 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11213 (error "No operator defined for property %s" prop))
11214 (org-columns-compute prop)))
11216 (defun org-property-get-allowed-values (pom property &optional table)
11217 "Get allowed values for the property PROPERTY.
11218 When TABLE is non-nil, return an alist that can directly be used for
11219 completion."
11220 (let (vals)
11221 (cond
11222 ((equal property "TODO")
11223 (setq vals (org-with-point-at pom
11224 (append org-todo-keywords-1 '("")))))
11225 ((equal property "PRIORITY")
11226 (let ((n org-lowest-priority))
11227 (while (>= n org-highest-priority)
11228 (push (char-to-string n) vals)
11229 (setq n (1- n)))))
11230 ((member property org-special-properties))
11232 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11234 (when (and vals (string-match "\\S-" vals))
11235 (setq vals (car (read-from-string (concat "(" vals ")"))))
11236 (setq vals (mapcar (lambda (x)
11237 (cond ((stringp x) x)
11238 ((numberp x) (number-to-string x))
11239 ((symbolp x) (symbol-name x))
11240 (t "???")))
11241 vals)))))
11242 (if table (mapcar 'list vals) vals)))
11244 (defun org-property-previous-allowed-value (&optional previous)
11245 "Switch to the next allowed value for this property."
11246 (interactive)
11247 (org-property-next-allowed-value t))
11249 (defun org-property-next-allowed-value (&optional previous)
11250 "Switch to the next allowed value for this property."
11251 (interactive)
11252 (unless (org-at-property-p)
11253 (error "Not at a property"))
11254 (let* ((key (match-string 2))
11255 (value (match-string 3))
11256 (allowed (or (org-property-get-allowed-values (point) key)
11257 (and (member value '("[ ]" "[-]" "[X]"))
11258 '("[ ]" "[X]"))))
11259 nval)
11260 (unless allowed
11261 (error "Allowed values for this property have not been defined"))
11262 (if previous (setq allowed (reverse allowed)))
11263 (if (member value allowed)
11264 (setq nval (car (cdr (member value allowed)))))
11265 (setq nval (or nval (car allowed)))
11266 (if (equal nval value)
11267 (error "Only one allowed value for this property"))
11268 (org-at-property-p)
11269 (replace-match (concat " :" key ": " nval) t t)
11270 (org-indent-line-function)
11271 (beginning-of-line 1)
11272 (skip-chars-forward " \t")))
11274 (defun org-find-entry-with-id (ident)
11275 "Locate the entry that contains the ID property with exact value IDENT.
11276 IDENT can be a string, a symbol or a number, this function will search for
11277 the string representation of it.
11278 Return the position where this entry starts, or nil if there is no such entry."
11279 (interactive "sID: ")
11280 (let ((id (cond
11281 ((stringp ident) ident)
11282 ((symbol-name ident) (symbol-name ident))
11283 ((numberp ident) (number-to-string ident))
11284 (t (error "IDENT %s must be a string, symbol or number" ident))))
11285 (case-fold-search nil))
11286 (save-excursion
11287 (save-restriction
11288 (widen)
11289 (goto-char (point-min))
11290 (when (re-search-forward
11291 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11292 nil t)
11293 (org-back-to-heading)
11294 (point))))))
11296 ;;;; Timestamps
11298 (defvar org-last-changed-timestamp nil)
11299 (defvar org-last-inserted-timestamp nil
11300 "The last time stamp inserted with `org-insert-time-stamp'.")
11301 (defvar org-time-was-given) ; dynamically scoped parameter
11302 (defvar org-end-time-was-given) ; dynamically scoped parameter
11303 (defvar org-ts-what) ; dynamically scoped parameter
11305 (defun org-time-stamp (arg &optional inactive)
11306 "Prompt for a date/time and insert a time stamp.
11307 If the user specifies a time like HH:MM, or if this command is called
11308 with a prefix argument, the time stamp will contain date and time.
11309 Otherwise, only the date will be included. All parts of a date not
11310 specified by the user will be filled in from the current date/time.
11311 So if you press just return without typing anything, the time stamp
11312 will represent the current date/time. If there is already a timestamp
11313 at the cursor, it will be modified."
11314 (interactive "P")
11315 (let* ((ts nil)
11316 (default-time
11317 ;; Default time is either today, or, when entering a range,
11318 ;; the range start.
11319 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11320 (save-excursion
11321 (re-search-backward
11322 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11323 (- (point) 20) t)))
11324 (apply 'encode-time (org-parse-time-string (match-string 1)))
11325 (current-time)))
11326 (default-input (and ts (org-get-compact-tod ts)))
11327 org-time-was-given org-end-time-was-given time)
11328 (cond
11329 ((and (org-at-timestamp-p t)
11330 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11331 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11332 (insert "--")
11333 (setq time (let ((this-command this-command))
11334 (org-read-date arg 'totime nil nil
11335 default-time default-input)))
11336 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11337 ((org-at-timestamp-p t)
11338 (setq time (let ((this-command this-command))
11339 (org-read-date arg 'totime nil nil default-time default-input)))
11340 (when (org-at-timestamp-p t) ; just to get the match data
11341 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11342 (replace-match "")
11343 (setq org-last-changed-timestamp
11344 (org-insert-time-stamp
11345 time (or org-time-was-given arg)
11346 inactive nil nil (list org-end-time-was-given))))
11347 (message "Timestamp updated"))
11349 (setq time (let ((this-command this-command))
11350 (org-read-date arg 'totime nil nil default-time default-input)))
11351 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11352 nil nil (list org-end-time-was-given))))))
11354 ;; FIXME: can we use this for something else, like computing time differences?
11355 (defun org-get-compact-tod (s)
11356 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11357 (let* ((t1 (match-string 1 s))
11358 (h1 (string-to-number (match-string 2 s)))
11359 (m1 (string-to-number (match-string 3 s)))
11360 (t2 (and (match-end 4) (match-string 5 s)))
11361 (h2 (and t2 (string-to-number (match-string 6 s))))
11362 (m2 (and t2 (string-to-number (match-string 7 s))))
11363 dh dm)
11364 (if (not t2)
11366 (setq dh (- h2 h1) dm (- m2 m1))
11367 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11368 (concat t1 "+" (number-to-string dh)
11369 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11371 (defun org-time-stamp-inactive (&optional arg)
11372 "Insert an inactive time stamp.
11373 An inactive time stamp is enclosed in square brackets instead of angle
11374 brackets. It is inactive in the sense that it does not trigger agenda entries,
11375 does not link to the calendar and cannot be changed with the S-cursor keys.
11376 So these are more for recording a certain time/date."
11377 (interactive "P")
11378 (org-time-stamp arg 'inactive))
11380 (defvar org-date-ovl (org-make-overlay 1 1))
11381 (org-overlay-put org-date-ovl 'face 'org-warning)
11382 (org-detach-overlay org-date-ovl)
11384 (defvar org-ans1) ; dynamically scoped parameter
11385 (defvar org-ans2) ; dynamically scoped parameter
11387 (defvar org-plain-time-of-day-regexp) ; defined below
11389 (defvar org-overriding-default-time nil) ; dynamically scoped
11390 (defvar org-read-date-overlay nil)
11391 (defvar org-dcst nil) ; dynamically scoped
11393 (defun org-read-date (&optional with-time to-time from-string prompt
11394 default-time default-input)
11395 "Read a date, possibly a time, and make things smooth for the user.
11396 The prompt will suggest to enter an ISO date, but you can also enter anything
11397 which will at least partially be understood by `parse-time-string'.
11398 Unrecognized parts of the date will default to the current day, month, year,
11399 hour and minute. If this command is called to replace a timestamp at point,
11400 of to enter the second timestamp of a range, the default time is taken from the
11401 existing stamp. For example,
11402 3-2-5 --> 2003-02-05
11403 feb 15 --> currentyear-02-15
11404 sep 12 9 --> 2009-09-12
11405 12:45 --> today 12:45
11406 22 sept 0:34 --> currentyear-09-22 0:34
11407 12 --> currentyear-currentmonth-12
11408 Fri --> nearest Friday (today or later)
11409 etc.
11411 Furthermore you can specify a relative date by giving, as the *first* thing
11412 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11413 change in days weeks, months, years.
11414 With a single plus or minus, the date is relative to today. With a double
11415 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11416 +4d --> four days from today
11417 +4 --> same as above
11418 +2w --> two weeks from today
11419 ++5 --> five days from default date
11421 The function understands only English month and weekday abbreviations,
11422 but this can be configured with the variables `parse-time-months' and
11423 `parse-time-weekdays'.
11425 While prompting, a calendar is popped up - you can also select the
11426 date with the mouse (button 1). The calendar shows a period of three
11427 months. To scroll it to other months, use the keys `>' and `<'.
11428 If you don't like the calendar, turn it off with
11429 \(setq org-read-date-popup-calendar nil)
11431 With optional argument TO-TIME, the date will immediately be converted
11432 to an internal time.
11433 With an optional argument WITH-TIME, the prompt will suggest to also
11434 insert a time. Note that when WITH-TIME is not set, you can still
11435 enter a time, and this function will inform the calling routine about
11436 this change. The calling routine may then choose to change the format
11437 used to insert the time stamp into the buffer to include the time.
11438 With optional argument FROM-STRING, read from this string instead from
11439 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11440 the time/date that is used for everything that is not specified by the
11441 user."
11442 (require 'parse-time)
11443 (let* ((org-time-stamp-rounding-minutes
11444 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11445 (org-dcst org-display-custom-times)
11446 (ct (org-current-time))
11447 (def (or org-overriding-default-time default-time ct))
11448 (defdecode (decode-time def))
11449 (dummy (progn
11450 (when (< (nth 2 defdecode) org-extend-today-until)
11451 (setcar (nthcdr 2 defdecode) -1)
11452 (setcar (nthcdr 1 defdecode) 59)
11453 (setq def (apply 'encode-time defdecode)
11454 defdecode (decode-time def)))))
11455 (calendar-move-hook nil)
11456 (calendar-view-diary-initially-flag nil)
11457 (view-diary-entries-initially nil)
11458 (calendar-view-holidays-initially-flag nil)
11459 (view-calendar-holidays-initially nil)
11460 (timestr (format-time-string
11461 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11462 (prompt (concat (if prompt (concat prompt " ") "")
11463 (format "Date+time [%s]: " timestr)))
11464 ans (org-ans0 "") org-ans1 org-ans2 final)
11466 (cond
11467 (from-string (setq ans from-string))
11468 (org-read-date-popup-calendar
11469 (save-excursion
11470 (save-window-excursion
11471 (calendar)
11472 (calendar-forward-day (- (time-to-days def)
11473 (calendar-absolute-from-gregorian
11474 (calendar-current-date))))
11475 (org-eval-in-calendar nil t)
11476 (let* ((old-map (current-local-map))
11477 (map (copy-keymap calendar-mode-map))
11478 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11479 (org-defkey map (kbd "RET") 'org-calendar-select)
11480 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11481 'org-calendar-select-mouse)
11482 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11483 'org-calendar-select-mouse)
11484 (org-defkey minibuffer-local-map [(meta shift left)]
11485 (lambda () (interactive)
11486 (org-eval-in-calendar '(calendar-backward-month 1))))
11487 (org-defkey minibuffer-local-map [(meta shift right)]
11488 (lambda () (interactive)
11489 (org-eval-in-calendar '(calendar-forward-month 1))))
11490 (org-defkey minibuffer-local-map [(meta shift up)]
11491 (lambda () (interactive)
11492 (org-eval-in-calendar '(calendar-backward-year 1))))
11493 (org-defkey minibuffer-local-map [(meta shift down)]
11494 (lambda () (interactive)
11495 (org-eval-in-calendar '(calendar-forward-year 1))))
11496 (org-defkey minibuffer-local-map [(shift up)]
11497 (lambda () (interactive)
11498 (org-eval-in-calendar '(calendar-backward-week 1))))
11499 (org-defkey minibuffer-local-map [(shift down)]
11500 (lambda () (interactive)
11501 (org-eval-in-calendar '(calendar-forward-week 1))))
11502 (org-defkey minibuffer-local-map [(shift left)]
11503 (lambda () (interactive)
11504 (org-eval-in-calendar '(calendar-backward-day 1))))
11505 (org-defkey minibuffer-local-map [(shift right)]
11506 (lambda () (interactive)
11507 (org-eval-in-calendar '(calendar-forward-day 1))))
11508 (org-defkey minibuffer-local-map ">"
11509 (lambda () (interactive)
11510 (org-eval-in-calendar '(scroll-calendar-left 1))))
11511 (org-defkey minibuffer-local-map "<"
11512 (lambda () (interactive)
11513 (org-eval-in-calendar '(scroll-calendar-right 1))))
11514 (unwind-protect
11515 (progn
11516 (use-local-map map)
11517 (add-hook 'post-command-hook 'org-read-date-display)
11518 (setq org-ans0 (read-string prompt default-input nil nil))
11519 ;; org-ans0: from prompt
11520 ;; org-ans1: from mouse click
11521 ;; org-ans2: from calendar motion
11522 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11523 (remove-hook 'post-command-hook 'org-read-date-display)
11524 (use-local-map old-map)
11525 (when org-read-date-overlay
11526 (org-delete-overlay org-read-date-overlay)
11527 (setq org-read-date-overlay nil)))))))
11529 (t ; Naked prompt only
11530 (unwind-protect
11531 (setq ans (read-string prompt default-input nil timestr))
11532 (when org-read-date-overlay
11533 (org-delete-overlay org-read-date-overlay)
11534 (setq org-read-date-overlay nil)))))
11536 (setq final (org-read-date-analyze ans def defdecode))
11538 (if to-time
11539 (apply 'encode-time final)
11540 (if (and (boundp 'org-time-was-given) org-time-was-given)
11541 (format "%04d-%02d-%02d %02d:%02d"
11542 (nth 5 final) (nth 4 final) (nth 3 final)
11543 (nth 2 final) (nth 1 final))
11544 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11545 (defvar def)
11546 (defvar defdecode)
11547 (defvar with-time)
11548 (defun org-read-date-display ()
11549 "Display the current date prompt interpretation in the minibuffer."
11550 (when org-read-date-display-live
11551 (when org-read-date-overlay
11552 (org-delete-overlay org-read-date-overlay))
11553 (let ((p (point)))
11554 (end-of-line 1)
11555 (while (not (equal (buffer-substring
11556 (max (point-min) (- (point) 4)) (point))
11557 " "))
11558 (insert " "))
11559 (goto-char p))
11560 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11561 " " (or org-ans1 org-ans2)))
11562 (org-end-time-was-given nil)
11563 (f (org-read-date-analyze ans def defdecode))
11564 (fmts (if org-dcst
11565 org-time-stamp-custom-formats
11566 org-time-stamp-formats))
11567 (fmt (if (or with-time
11568 (and (boundp 'org-time-was-given) org-time-was-given))
11569 (cdr fmts)
11570 (car fmts)))
11571 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11572 (when (and org-end-time-was-given
11573 (string-match org-plain-time-of-day-regexp txt))
11574 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11575 org-end-time-was-given
11576 (substring txt (match-end 0)))))
11577 (setq org-read-date-overlay
11578 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11579 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11581 (defun org-read-date-analyze (ans def defdecode)
11582 "Analyse the combined answer of the date prompt."
11583 ;; FIXME: cleanup and comment
11584 (let (delta deltan deltaw deltadef year month day
11585 hour minute second wday pm h2 m2 tl wday1
11586 iso-year iso-weekday iso-week iso-year iso-date)
11588 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11589 (setq ans "+0"))
11591 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11592 (setq ans (replace-match "" t t ans)
11593 deltan (car delta)
11594 deltaw (nth 1 delta)
11595 deltadef (nth 2 delta)))
11597 ;; Check if there is an iso week date in there
11598 ;; If yes, sore the info and postpone interpreting it until the rest
11599 ;; of the parsing is done
11600 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11601 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11602 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11603 iso-week (string-to-number (match-string 2 ans)))
11604 (setq ans (replace-match "" t t ans)))
11606 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11607 (when (string-match
11608 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11609 (setq year (if (match-end 2)
11610 (string-to-number (match-string 2 ans))
11611 (string-to-number (format-time-string "%Y")))
11612 month (string-to-number (match-string 3 ans))
11613 day (string-to-number (match-string 4 ans)))
11614 (if (< year 100) (setq year (+ 2000 year)))
11615 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11616 t nil ans)))
11617 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11618 ;; If there is a time with am/pm, and *no* time without it, we convert
11619 ;; so that matching will be successful.
11620 (loop for i from 1 to 2 do ; twice, for end time as well
11621 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11622 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11623 (setq hour (string-to-number (match-string 1 ans))
11624 minute (if (match-end 3)
11625 (string-to-number (match-string 3 ans))
11627 pm (equal ?p
11628 (string-to-char (downcase (match-string 4 ans)))))
11629 (if (and (= hour 12) (not pm))
11630 (setq hour 0)
11631 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11632 (setq ans (replace-match (format "%02d:%02d" hour minute)
11633 t t ans))))
11635 ;; Check if a time range is given as a duration
11636 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11637 (setq hour (string-to-number (match-string 1 ans))
11638 h2 (+ hour (string-to-number (match-string 3 ans)))
11639 minute (string-to-number (match-string 2 ans))
11640 m2 (+ minute (if (match-end 5) (string-to-number
11641 (match-string 5 ans))0)))
11642 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11643 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11644 t t ans)))
11646 ;; Check if there is a time range
11647 (when (boundp 'org-end-time-was-given)
11648 (setq org-time-was-given nil)
11649 (when (and (string-match org-plain-time-of-day-regexp ans)
11650 (match-end 8))
11651 (setq org-end-time-was-given (match-string 8 ans))
11652 (setq ans (concat (substring ans 0 (match-beginning 7))
11653 (substring ans (match-end 7))))))
11655 (setq tl (parse-time-string ans)
11656 day (or (nth 3 tl) (nth 3 defdecode))
11657 month (or (nth 4 tl)
11658 (if (and org-read-date-prefer-future
11659 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11660 (1+ (nth 4 defdecode))
11661 (nth 4 defdecode)))
11662 year (or (nth 5 tl)
11663 (if (and org-read-date-prefer-future
11664 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11665 (1+ (nth 5 defdecode))
11666 (nth 5 defdecode)))
11667 hour (or (nth 2 tl) (nth 2 defdecode))
11668 minute (or (nth 1 tl) (nth 1 defdecode))
11669 second (or (nth 0 tl) 0)
11670 wday (nth 6 tl))
11672 ;; Special date definitions below
11673 (cond
11674 (iso-week
11675 ;; There was an iso week
11676 (setq year (or iso-year year)
11677 day (or iso-weekday wday 1)
11678 wday nil ; to make sure that the trigger below does not match
11679 iso-date (calendar-gregorian-from-absolute
11680 (calendar-absolute-from-iso
11681 (list iso-week day year))))
11682 ; FIXME: Should we also push ISO weeks into the future?
11683 ; (when (and org-read-date-prefer-future
11684 ; (not iso-year)
11685 ; (< (calendar-absolute-from-gregorian iso-date)
11686 ; (time-to-days (current-time))))
11687 ; (setq year (1+ year)
11688 ; iso-date (calendar-gregorian-from-absolute
11689 ; (calendar-absolute-from-iso
11690 ; (list iso-week day year)))))
11691 (setq month (car iso-date)
11692 year (nth 2 iso-date)
11693 day (nth 1 iso-date)))
11694 (deltan
11695 (unless deltadef
11696 (let ((now (decode-time (current-time))))
11697 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11698 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11699 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11700 ((equal deltaw "m") (setq month (+ month deltan)))
11701 ((equal deltaw "y") (setq year (+ year deltan)))))
11702 ((and wday (not (nth 3 tl)))
11703 ;; Weekday was given, but no day, so pick that day in the week
11704 ;; on or after the derived date.
11705 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11706 (unless (equal wday wday1)
11707 (setq day (+ day (% (- wday wday1 -7) 7))))))
11708 (if (and (boundp 'org-time-was-given)
11709 (nth 2 tl))
11710 (setq org-time-was-given t))
11711 (if (< year 100) (setq year (+ 2000 year)))
11712 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11713 (list second minute hour day month year)))
11715 (defvar parse-time-weekdays)
11717 (defun org-read-date-get-relative (s today default)
11718 "Check string S for special relative date string.
11719 TODAY and DEFAULT are internal times, for today and for a default.
11720 Return shift list (N what def-flag)
11721 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11722 N is the number of WHATs to shift.
11723 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11724 the DEFAULT date rather than TODAY."
11725 (when (and
11726 (string-match
11727 (concat
11728 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11729 "\\([0-9]+\\)?"
11730 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11731 "\\([ \t]\\|$\\)") s)
11732 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11733 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11734 (string-to-char (substring (match-string 1 s) -1))
11735 ?+))
11736 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11737 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11738 (what (if (match-end 3) (match-string 3 s) "d"))
11739 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11740 (date (if rel default today))
11741 (wday (nth 6 (decode-time date)))
11742 delta)
11743 (if wday1
11744 (progn
11745 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11746 (if (= dir ?-) (setq delta (- delta 7)))
11747 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11748 (list delta "d" rel))
11749 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11751 (defun org-eval-in-calendar (form &optional keepdate)
11752 "Eval FORM in the calendar window and return to current window.
11753 Also, store the cursor date in variable org-ans2."
11754 (let ((sw (selected-window)))
11755 (select-window (get-buffer-window "*Calendar*"))
11756 (eval form)
11757 (when (and (not keepdate) (calendar-cursor-to-date))
11758 (let* ((date (calendar-cursor-to-date))
11759 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11760 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11761 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11762 (select-window sw)))
11764 (defun org-calendar-select ()
11765 "Return to `org-read-date' with the date currently selected.
11766 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11767 (interactive)
11768 (when (calendar-cursor-to-date)
11769 (let* ((date (calendar-cursor-to-date))
11770 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11771 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11772 (if (active-minibuffer-window) (exit-minibuffer))))
11774 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11775 "Insert a date stamp for the date given by the internal TIME.
11776 WITH-HM means, use the stamp format that includes the time of the day.
11777 INACTIVE means use square brackets instead of angular ones, so that the
11778 stamp will not contribute to the agenda.
11779 PRE and POST are optional strings to be inserted before and after the
11780 stamp.
11781 The command returns the inserted time stamp."
11782 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11783 stamp)
11784 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11785 (insert-before-markers (or pre ""))
11786 (insert-before-markers (setq stamp (format-time-string fmt time)))
11787 (when (listp extra)
11788 (setq extra (car extra))
11789 (if (and (stringp extra)
11790 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11791 (setq extra (format "-%02d:%02d"
11792 (string-to-number (match-string 1 extra))
11793 (string-to-number (match-string 2 extra))))
11794 (setq extra nil)))
11795 (when extra
11796 (backward-char 1)
11797 (insert-before-markers extra)
11798 (forward-char 1))
11799 (insert-before-markers (or post ""))
11800 (setq org-last-inserted-timestamp stamp)))
11802 (defun org-toggle-time-stamp-overlays ()
11803 "Toggle the use of custom time stamp formats."
11804 (interactive)
11805 (setq org-display-custom-times (not org-display-custom-times))
11806 (unless org-display-custom-times
11807 (let ((p (point-min)) (bmp (buffer-modified-p)))
11808 (while (setq p (next-single-property-change p 'display))
11809 (if (and (get-text-property p 'display)
11810 (eq (get-text-property p 'face) 'org-date))
11811 (remove-text-properties
11812 p (setq p (next-single-property-change p 'display))
11813 '(display t))))
11814 (set-buffer-modified-p bmp)))
11815 (if (featurep 'xemacs)
11816 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11817 (org-restart-font-lock)
11818 (setq org-table-may-need-update t)
11819 (if org-display-custom-times
11820 (message "Time stamps are overlayed with custom format")
11821 (message "Time stamp overlays removed")))
11823 (defun org-display-custom-time (beg end)
11824 "Overlay modified time stamp format over timestamp between BEG and END."
11825 (let* ((ts (buffer-substring beg end))
11826 t1 w1 with-hm tf time str w2 (off 0))
11827 (save-match-data
11828 (setq t1 (org-parse-time-string ts t))
11829 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11830 (setq off (- (match-end 0) (match-beginning 0)))))
11831 (setq end (- end off))
11832 (setq w1 (- end beg)
11833 with-hm (and (nth 1 t1) (nth 2 t1))
11834 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11835 time (org-fix-decoded-time t1)
11836 str (org-add-props
11837 (format-time-string
11838 (substring tf 1 -1) (apply 'encode-time time))
11839 nil 'mouse-face 'highlight)
11840 w2 (length str))
11841 (if (not (= w2 w1))
11842 (add-text-properties (1+ beg) (+ 2 beg)
11843 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11844 (if (featurep 'xemacs)
11845 (progn
11846 (put-text-property beg end 'invisible t)
11847 (put-text-property beg end 'end-glyph (make-glyph str)))
11848 (put-text-property beg end 'display str))))
11850 (defun org-translate-time (string)
11851 "Translate all timestamps in STRING to custom format.
11852 But do this only if the variable `org-display-custom-times' is set."
11853 (when org-display-custom-times
11854 (save-match-data
11855 (let* ((start 0)
11856 (re org-ts-regexp-both)
11857 t1 with-hm inactive tf time str beg end)
11858 (while (setq start (string-match re string start))
11859 (setq beg (match-beginning 0)
11860 end (match-end 0)
11861 t1 (save-match-data
11862 (org-parse-time-string (substring string beg end) t))
11863 with-hm (and (nth 1 t1) (nth 2 t1))
11864 inactive (equal (substring string beg (1+ beg)) "[")
11865 tf (funcall (if with-hm 'cdr 'car)
11866 org-time-stamp-custom-formats)
11867 time (org-fix-decoded-time t1)
11868 str (format-time-string
11869 (concat
11870 (if inactive "[" "<") (substring tf 1 -1)
11871 (if inactive "]" ">"))
11872 (apply 'encode-time time))
11873 string (replace-match str t t string)
11874 start (+ start (length str)))))))
11875 string)
11877 (defun org-fix-decoded-time (time)
11878 "Set 0 instead of nil for the first 6 elements of time.
11879 Don't touch the rest."
11880 (let ((n 0))
11881 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11883 (defun org-days-to-time (timestamp-string)
11884 "Difference between TIMESTAMP-STRING and now in days."
11885 (- (time-to-days (org-time-string-to-time timestamp-string))
11886 (time-to-days (current-time))))
11888 (defun org-deadline-close (timestamp-string &optional ndays)
11889 "Is the time in TIMESTAMP-STRING close to the current date?"
11890 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11891 (and (< (org-days-to-time timestamp-string) ndays)
11892 (not (org-entry-is-done-p))))
11894 (defun org-get-wdays (ts)
11895 "Get the deadline lead time appropriate for timestring TS."
11896 (cond
11897 ((<= org-deadline-warning-days 0)
11898 ;; 0 or negative, enforce this value no matter what
11899 (- org-deadline-warning-days))
11900 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11901 ;; lead time is specified.
11902 (floor (* (string-to-number (match-string 1 ts))
11903 (cdr (assoc (match-string 2 ts)
11904 '(("d" . 1) ("w" . 7)
11905 ("m" . 30.4) ("y" . 365.25)))))))
11906 ;; go for the default.
11907 (t org-deadline-warning-days)))
11909 (defun org-calendar-select-mouse (ev)
11910 "Return to `org-read-date' with the date currently selected.
11911 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11912 (interactive "e")
11913 (mouse-set-point ev)
11914 (when (calendar-cursor-to-date)
11915 (let* ((date (calendar-cursor-to-date))
11916 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11917 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11918 (if (active-minibuffer-window) (exit-minibuffer))))
11920 (defun org-check-deadlines (ndays)
11921 "Check if there are any deadlines due or past due.
11922 A deadline is considered due if it happens within `org-deadline-warning-days'
11923 days from today's date. If the deadline appears in an entry marked DONE,
11924 it is not shown. The prefix arg NDAYS can be used to test that many
11925 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11926 (interactive "P")
11927 (let* ((org-warn-days
11928 (cond
11929 ((equal ndays '(4)) 100000)
11930 (ndays (prefix-numeric-value ndays))
11931 (t (abs org-deadline-warning-days))))
11932 (case-fold-search nil)
11933 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11934 (callback
11935 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11937 (message "%d deadlines past-due or due within %d days"
11938 (org-occur regexp nil callback)
11939 org-warn-days)))
11941 (defun org-check-before-date (date)
11942 "Check if there are deadlines or scheduled entries before DATE."
11943 (interactive (list (org-read-date)))
11944 (let ((case-fold-search nil)
11945 (regexp (concat "\\<\\(" org-deadline-string
11946 "\\|" org-scheduled-string
11947 "\\) *<\\([^>]+\\)>"))
11948 (callback
11949 (lambda () (time-less-p
11950 (org-time-string-to-time (match-string 2))
11951 (org-time-string-to-time date)))))
11952 (message "%d entries before %s"
11953 (org-occur regexp nil callback) date)))
11955 (defun org-evaluate-time-range (&optional to-buffer)
11956 "Evaluate a time range by computing the difference between start and end.
11957 Normally the result is just printed in the echo area, but with prefix arg
11958 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11959 If the time range is actually in a table, the result is inserted into the
11960 next column.
11961 For time difference computation, a year is assumed to be exactly 365
11962 days in order to avoid rounding problems."
11963 (interactive "P")
11965 (org-clock-update-time-maybe)
11966 (save-excursion
11967 (unless (org-at-date-range-p t)
11968 (goto-char (point-at-bol))
11969 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11970 (if (not (org-at-date-range-p t))
11971 (error "Not at a time-stamp range, and none found in current line")))
11972 (let* ((ts1 (match-string 1))
11973 (ts2 (match-string 2))
11974 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11975 (match-end (match-end 0))
11976 (time1 (org-time-string-to-time ts1))
11977 (time2 (org-time-string-to-time ts2))
11978 (t1 (time-to-seconds time1))
11979 (t2 (time-to-seconds time2))
11980 (diff (abs (- t2 t1)))
11981 (negative (< (- t2 t1) 0))
11982 ;; (ys (floor (* 365 24 60 60)))
11983 (ds (* 24 60 60))
11984 (hs (* 60 60))
11985 (fy "%dy %dd %02d:%02d")
11986 (fy1 "%dy %dd")
11987 (fd "%dd %02d:%02d")
11988 (fd1 "%dd")
11989 (fh "%02d:%02d")
11990 y d h m align)
11991 (if havetime
11992 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11994 d (floor (/ diff ds)) diff (mod diff ds)
11995 h (floor (/ diff hs)) diff (mod diff hs)
11996 m (floor (/ diff 60)))
11997 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11999 d (floor (+ (/ diff ds) 0.5))
12000 h 0 m 0))
12001 (if (not to-buffer)
12002 (message "%s" (org-make-tdiff-string y d h m))
12003 (if (org-at-table-p)
12004 (progn
12005 (goto-char match-end)
12006 (setq align t)
12007 (and (looking-at " *|") (goto-char (match-end 0))))
12008 (goto-char match-end))
12009 (if (looking-at
12010 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12011 (replace-match ""))
12012 (if negative (insert " -"))
12013 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12014 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12015 (insert " " (format fh h m))))
12016 (if align (org-table-align))
12017 (message "Time difference inserted")))))
12019 (defun org-make-tdiff-string (y d h m)
12020 (let ((fmt "")
12021 (l nil))
12022 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12023 l (push y l)))
12024 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12025 l (push d l)))
12026 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12027 l (push h l)))
12028 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12029 l (push m l)))
12030 (apply 'format fmt (nreverse l))))
12032 (defun org-time-string-to-time (s)
12033 (apply 'encode-time (org-parse-time-string s)))
12035 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12036 "Convert a time stamp to an absolute day number.
12037 If there is a specifyer for a cyclic time stamp, get the closest date to
12038 DAYNR.
12039 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12040 (cond
12041 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12042 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12043 daynr
12044 (+ daynr 1000)))
12045 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12046 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12047 (time-to-days (current-time))) (match-string 0 s)
12048 prefer show-all))
12049 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12051 (defun org-days-to-iso-week (days)
12052 "Return the iso week number."
12053 (require 'cal-iso)
12054 (car (calendar-iso-from-absolute days)))
12056 (defun org-small-year-to-year (year)
12057 "Convert 2-digit years into 4-digit years.
12058 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12059 The year 2000 cannot be abbreviated. Any year larger than 99
12060 is returned unchanged."
12061 (if (< year 38)
12062 (setq year (+ 2000 year))
12063 (if (< year 100)
12064 (setq year (+ 1900 year))))
12065 year)
12067 (defun org-time-from-absolute (d)
12068 "Return the time corresponding to date D.
12069 D may be an absolute day number, or a calendar-type list (month day year)."
12070 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12071 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12073 (defun org-calendar-holiday ()
12074 "List of holidays, for Diary display in Org-mode."
12075 (require 'holidays)
12076 (let ((hl (funcall
12077 (if (fboundp 'calendar-check-holidays)
12078 'calendar-check-holidays 'check-calendar-holidays) date)))
12079 (if hl (mapconcat 'identity hl "; "))))
12081 (defun org-diary-sexp-entry (sexp entry date)
12082 "Process a SEXP diary ENTRY for DATE."
12083 (require 'diary-lib)
12084 (let ((result (if calendar-debug-sexp
12085 (let ((stack-trace-on-error t))
12086 (eval (car (read-from-string sexp))))
12087 (condition-case nil
12088 (eval (car (read-from-string sexp)))
12089 (error
12090 (beep)
12091 (message "Bad sexp at line %d in %s: %s"
12092 (org-current-line)
12093 (buffer-file-name) sexp)
12094 (sleep-for 2))))))
12095 (cond ((stringp result) result)
12096 ((and (consp result)
12097 (stringp (cdr result))) (cdr result))
12098 (result entry)
12099 (t nil))))
12101 (defun org-diary-to-ical-string (frombuf)
12102 "Get iCalendar entries from diary entries in buffer FROMBUF.
12103 This uses the icalendar.el library."
12104 (let* ((tmpdir (if (featurep 'xemacs)
12105 (temp-directory)
12106 temporary-file-directory))
12107 (tmpfile (make-temp-name
12108 (expand-file-name "orgics" tmpdir)))
12109 buf rtn b e)
12110 (save-excursion
12111 (set-buffer frombuf)
12112 (icalendar-export-region (point-min) (point-max) tmpfile)
12113 (setq buf (find-buffer-visiting tmpfile))
12114 (set-buffer buf)
12115 (goto-char (point-min))
12116 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12117 (setq b (match-beginning 0)))
12118 (goto-char (point-max))
12119 (if (re-search-backward "^END:VEVENT" nil t)
12120 (setq e (match-end 0)))
12121 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12122 (kill-buffer buf)
12123 (delete-file tmpfile)
12124 rtn))
12126 (defun org-closest-date (start current change prefer show-all)
12127 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12128 When PREFER is `past' return a date that is either CURRENT or past.
12129 When PREFER is `future', return a date that is either CURRENT or future.
12130 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12131 ;; Make the proper lists from the dates
12132 (catch 'exit
12133 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12134 dn dw sday cday n1 n2 n0
12135 d m y y1 y2 date1 date2 nmonths nm ny m2)
12137 (setq start (org-date-to-gregorian start)
12138 current (org-date-to-gregorian
12139 (if show-all
12140 current
12141 (time-to-days (current-time))))
12142 sday (calendar-absolute-from-gregorian start)
12143 cday (calendar-absolute-from-gregorian current))
12145 (if (<= cday sday) (throw 'exit sday))
12147 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12148 (setq dn (string-to-number (match-string 1 change))
12149 dw (cdr (assoc (match-string 2 change) a1)))
12150 (error "Invalid change specifyer: %s" change))
12151 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12152 (cond
12153 ((eq dw 'day)
12154 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12155 n2 (+ n1 dn)))
12156 ((eq dw 'year)
12157 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12158 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12159 (setq date1 (list m d y1)
12160 n1 (calendar-absolute-from-gregorian date1)
12161 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12162 n2 (calendar-absolute-from-gregorian date2)))
12163 ((eq dw 'month)
12164 ;; approx number of month between the two dates
12165 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12166 ;; How often does dn fit in there?
12167 (setq d (nth 1 start) m (car start) y (nth 2 start)
12168 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12169 m (+ m nm)
12170 ny (floor (/ m 12))
12171 y (+ y ny)
12172 m (- m (* ny 12)))
12173 (while (> m 12) (setq m (- m 12) y (1+ y)))
12174 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12175 (setq m2 (+ m dn) y2 y)
12176 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12177 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12178 (while (<= n2 cday)
12179 (setq n1 n2 m m2 y y2)
12180 (setq m2 (+ m dn) y2 y)
12181 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12182 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12183 ;; Make sure n1 is the earlier date
12184 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12185 (if show-all
12186 (cond
12187 ((eq prefer 'past) n1)
12188 ((eq prefer 'future) (if (= cday n1) n1 n2))
12189 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12190 (cond
12191 ((eq prefer 'past) n1)
12192 ((eq prefer 'future) (if (= cday n1) n1 n2))
12193 (t (if (= cday n1) n1 n2)))))))
12195 (defun org-date-to-gregorian (date)
12196 "Turn any specification of DATE into a gregorian date for the calendar."
12197 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12198 ((and (listp date) (= (length date) 3)) date)
12199 ((stringp date)
12200 (setq date (org-parse-time-string date))
12201 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12202 ((listp date)
12203 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12205 (defun org-parse-time-string (s &optional nodefault)
12206 "Parse the standard Org-mode time string.
12207 This should be a lot faster than the normal `parse-time-string'.
12208 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12209 hour and minute fields will be nil if not given."
12210 (if (string-match org-ts-regexp0 s)
12211 (list 0
12212 (if (or (match-beginning 8) (not nodefault))
12213 (string-to-number (or (match-string 8 s) "0")))
12214 (if (or (match-beginning 7) (not nodefault))
12215 (string-to-number (or (match-string 7 s) "0")))
12216 (string-to-number (match-string 4 s))
12217 (string-to-number (match-string 3 s))
12218 (string-to-number (match-string 2 s))
12219 nil nil nil)
12220 (make-list 9 0)))
12222 (defun org-timestamp-up (&optional arg)
12223 "Increase the date item at the cursor by one.
12224 If the cursor is on the year, change the year. If it is on the month or
12225 the day, change that.
12226 With prefix ARG, change by that many units."
12227 (interactive "p")
12228 (org-timestamp-change (prefix-numeric-value arg)))
12230 (defun org-timestamp-down (&optional arg)
12231 "Decrease the date item at the cursor by one.
12232 If the cursor is on the year, change the year. If it is on the month or
12233 the day, change that.
12234 With prefix ARG, change by that many units."
12235 (interactive "p")
12236 (org-timestamp-change (- (prefix-numeric-value arg))))
12238 (defun org-timestamp-up-day (&optional arg)
12239 "Increase the date in the time stamp by one day.
12240 With prefix ARG, change that many days."
12241 (interactive "p")
12242 (if (and (not (org-at-timestamp-p t))
12243 (org-on-heading-p))
12244 (org-todo 'up)
12245 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12247 (defun org-timestamp-down-day (&optional arg)
12248 "Decrease the date in the time stamp by one day.
12249 With prefix ARG, change that many days."
12250 (interactive "p")
12251 (if (and (not (org-at-timestamp-p t))
12252 (org-on-heading-p))
12253 (org-todo 'down)
12254 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12256 (defun org-at-timestamp-p (&optional inactive-ok)
12257 "Determine if the cursor is in or at a timestamp."
12258 (interactive)
12259 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12260 (pos (point))
12261 (ans (or (looking-at tsr)
12262 (save-excursion
12263 (skip-chars-backward "^[<\n\r\t")
12264 (if (> (point) (point-min)) (backward-char 1))
12265 (and (looking-at tsr)
12266 (> (- (match-end 0) pos) -1))))))
12267 (and ans
12268 (boundp 'org-ts-what)
12269 (setq org-ts-what
12270 (cond
12271 ((= pos (match-beginning 0)) 'bracket)
12272 ((= pos (1- (match-end 0))) 'bracket)
12273 ((org-pos-in-match-range pos 2) 'year)
12274 ((org-pos-in-match-range pos 3) 'month)
12275 ((org-pos-in-match-range pos 7) 'hour)
12276 ((org-pos-in-match-range pos 8) 'minute)
12277 ((or (org-pos-in-match-range pos 4)
12278 (org-pos-in-match-range pos 5)) 'day)
12279 ((and (> pos (or (match-end 8) (match-end 5)))
12280 (< pos (match-end 0)))
12281 (- pos (or (match-end 8) (match-end 5))))
12282 (t 'day))))
12283 ans))
12285 (defun org-toggle-timestamp-type ()
12286 "Toggle the type (<active> or [inactive]) of a time stamp."
12287 (interactive)
12288 (when (org-at-timestamp-p t)
12289 (let ((beg (match-beginning 0)) (end (match-end 0))
12290 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12291 (save-excursion
12292 (goto-char beg)
12293 (while (re-search-forward "[][<>]" end t)
12294 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12295 t t)))
12296 (message "Timestamp is now %sactive"
12297 (if (equal (char-after beg) ?<) "" "in")))))
12299 (defun org-timestamp-change (n &optional what)
12300 "Change the date in the time stamp at point.
12301 The date will be changed by N times WHAT. WHAT can be `day', `month',
12302 `year', `minute', `second'. If WHAT is not given, the cursor position
12303 in the timestamp determines what will be changed."
12304 (let ((pos (point))
12305 with-hm inactive
12306 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12307 org-ts-what
12308 extra rem
12309 ts time time0)
12310 (if (not (org-at-timestamp-p t))
12311 (error "Not at a timestamp"))
12312 (if (and (not what) (eq org-ts-what 'bracket))
12313 (org-toggle-timestamp-type)
12314 (if (and (not what) (not (eq org-ts-what 'day))
12315 org-display-custom-times
12316 (get-text-property (point) 'display)
12317 (not (get-text-property (1- (point)) 'display)))
12318 (setq org-ts-what 'day))
12319 (setq org-ts-what (or what org-ts-what)
12320 inactive (= (char-after (match-beginning 0)) ?\[)
12321 ts (match-string 0))
12322 (replace-match "")
12323 (if (string-match
12324 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12326 (setq extra (match-string 1 ts)))
12327 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12328 (setq with-hm t))
12329 (setq time0 (org-parse-time-string ts))
12330 (when (and (eq org-ts-what 'minute)
12331 (eq current-prefix-arg nil))
12332 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12333 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12334 (setcar (cdr time0) (+ (nth 1 time0)
12335 (if (> n 0) (- rem) (- dm rem))))))
12336 (setq time
12337 (encode-time (or (car time0) 0)
12338 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12339 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12340 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12341 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12342 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12343 (nthcdr 6 time0)))
12344 (when (integerp org-ts-what)
12345 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12346 (if (eq what 'calendar)
12347 (let ((cal-date (org-get-date-from-calendar)))
12348 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12349 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12350 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12351 (setcar time0 (or (car time0) 0))
12352 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12353 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12354 (setq time (apply 'encode-time time0))))
12355 (setq org-last-changed-timestamp
12356 (org-insert-time-stamp time with-hm inactive nil nil extra))
12357 (org-clock-update-time-maybe)
12358 (goto-char pos)
12359 ;; Try to recenter the calendar window, if any
12360 (if (and org-calendar-follow-timestamp-change
12361 (get-buffer-window "*Calendar*" t)
12362 (memq org-ts-what '(day month year)))
12363 (org-recenter-calendar (time-to-days time))))))
12365 (defun org-modify-ts-extra (s pos n dm)
12366 "Change the different parts of the lead-time and repeat fields in timestamp."
12367 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12368 ng h m new rem)
12369 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12370 (cond
12371 ((or (org-pos-in-match-range pos 2)
12372 (org-pos-in-match-range pos 3))
12373 (setq m (string-to-number (match-string 3 s))
12374 h (string-to-number (match-string 2 s)))
12375 (if (org-pos-in-match-range pos 2)
12376 (setq h (+ h n))
12377 (setq n (* dm (org-no-warnings (signum n))))
12378 (when (not (= 0 (setq rem (% m dm))))
12379 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12380 (setq m (+ m n)))
12381 (if (< m 0) (setq m (+ m 60) h (1- h)))
12382 (if (> m 59) (setq m (- m 60) h (1+ h)))
12383 (setq h (min 24 (max 0 h)))
12384 (setq ng 1 new (format "-%02d:%02d" h m)))
12385 ((org-pos-in-match-range pos 6)
12386 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12387 ((org-pos-in-match-range pos 5)
12388 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12390 ((org-pos-in-match-range pos 9)
12391 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12392 ((org-pos-in-match-range pos 8)
12393 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12395 (when ng
12396 (setq s (concat
12397 (substring s 0 (match-beginning ng))
12399 (substring s (match-end ng))))))
12402 (defun org-recenter-calendar (date)
12403 "If the calendar is visible, recenter it to DATE."
12404 (let* ((win (selected-window))
12405 (cwin (get-buffer-window "*Calendar*" t))
12406 (calendar-move-hook nil))
12407 (when cwin
12408 (select-window cwin)
12409 (calendar-goto-date (if (listp date) date
12410 (calendar-gregorian-from-absolute date)))
12411 (select-window win))))
12413 (defun org-goto-calendar (&optional arg)
12414 "Go to the Emacs calendar at the current date.
12415 If there is a time stamp in the current line, go to that date.
12416 A prefix ARG can be used to force the current date."
12417 (interactive "P")
12418 (let ((tsr org-ts-regexp) diff
12419 (calendar-move-hook nil)
12420 (calendar-view-holidays-initially-flag nil)
12421 (view-calendar-holidays-initially nil)
12422 (calendar-view-diary-initially-flag nil)
12423 (view-diary-entries-initially nil))
12424 (if (or (org-at-timestamp-p)
12425 (save-excursion
12426 (beginning-of-line 1)
12427 (looking-at (concat ".*" tsr))))
12428 (let ((d1 (time-to-days (current-time)))
12429 (d2 (time-to-days
12430 (org-time-string-to-time (match-string 1)))))
12431 (setq diff (- d2 d1))))
12432 (calendar)
12433 (calendar-goto-today)
12434 (if (and diff (not arg)) (calendar-forward-day diff))))
12436 (defun org-get-date-from-calendar ()
12437 "Return a list (month day year) of date at point in calendar."
12438 (with-current-buffer "*Calendar*"
12439 (save-match-data
12440 (calendar-cursor-to-date))))
12442 (defun org-date-from-calendar ()
12443 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12444 If there is already a time stamp at the cursor position, update it."
12445 (interactive)
12446 (if (org-at-timestamp-p t)
12447 (org-timestamp-change 0 'calendar)
12448 (let ((cal-date (org-get-date-from-calendar)))
12449 (org-insert-time-stamp
12450 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12452 (defun org-minutes-to-hh:mm-string (m)
12453 "Compute H:MM from a number of minutes."
12454 (let ((h (/ m 60)))
12455 (setq m (- m (* 60 h)))
12456 (format org-time-clocksum-format h m)))
12458 (defun org-hh:mm-string-to-minutes (s)
12459 "Convert a string H:MM to a number of minutes."
12460 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12461 (+ (* (string-to-number (match-string 1 s)) 60)
12462 (string-to-number (match-string 2 s)))
12465 ;;;; Files
12467 (defun org-save-all-org-buffers ()
12468 "Save all Org-mode buffers without user confirmation."
12469 (interactive)
12470 (message "Saving all Org-mode buffers...")
12471 (save-some-buffers t 'org-mode-p)
12472 (when (featurep 'org-id) (org-id-locations-save))
12473 (message "Saving all Org-mode buffers... done"))
12475 (defun org-revert-all-org-buffers ()
12476 "Revert all Org-mode buffers.
12477 Prompt for confirmation when there are unsaved changes.
12478 Be sure you know what you are doing before letting this function
12479 overwrite your changes.
12481 This function is useful in a setup where one tracks org files
12482 with a version control system, to revert on one machine after pulling
12483 changes from another. I believe the procedure must be like this:
12485 1. M-x org-save-all-org-buffers
12486 2. Pull changes from the other machine, resolve conflicts
12487 3. M-x org-revert-all-org-buffers"
12488 (interactive)
12489 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12490 (error "Abort"))
12491 (save-excursion
12492 (save-window-excursion
12493 (mapc
12494 (lambda (b)
12495 (when (and (with-current-buffer b (org-mode-p))
12496 (with-current-buffer b buffer-file-name))
12497 (switch-to-buffer b)
12498 (revert-buffer t 'no-confirm)))
12499 (buffer-list))
12500 (when (and (featurep 'org-id) org-id-track-globally)
12501 (org-id-locations-load)))))
12503 ;;;; Agenda files
12505 ;;;###autoload
12506 (defun org-iswitchb (&optional arg)
12507 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12508 With a prefix argument, restrict available to files.
12509 With two prefix arguments, restrict available buffers to agenda files.
12511 Due to some yet unresolved reason, the global function
12512 `iswitchb-mode' needs to be active for this function to work."
12513 (interactive "P")
12514 (require 'iswitchb)
12515 (let ((enabled iswitchb-mode) blist)
12516 (or enabled (iswitchb-mode 1))
12517 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12518 ((equal arg '(16)) (org-buffer-list 'agenda))
12519 (t (org-buffer-list))))
12520 (unwind-protect
12521 (let ((iswitchb-make-buflist-hook
12522 (lambda ()
12523 (setq iswitchb-temp-buflist
12524 (mapcar 'buffer-name blist)))))
12525 (switch-to-buffer
12526 (iswitchb-read-buffer
12527 "Switch-to: " nil t))
12528 (or enabled (iswitchb-mode -1))))))
12530 ;;;###autoload
12531 (defun org-ido-switchb (&optional arg)
12532 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12533 With a prefix argument, restrict available to files.
12534 With two prefix arguments, restrict available buffers to agenda files."
12535 (interactive "P")
12536 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12537 ((equal arg '(16)) (org-buffer-list 'agenda))
12538 (t (org-buffer-list)))))
12539 (switch-to-buffer
12540 (org-ido-completing-read "Org buffer: "
12541 (mapcar 'buffer-name blist)
12542 nil t))))
12544 (defun org-buffer-list (&optional predicate exclude-tmp)
12545 "Return a list of Org buffers.
12546 PREDICATE can be `export', `files' or `agenda'.
12548 export restrict the list to Export buffers.
12549 files restrict the list to buffers visiting Org files.
12550 agenda restrict the list to buffers visiting agenda files.
12552 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12553 (let* ((bfn nil)
12554 (agenda-files (and (eq predicate 'agenda)
12555 (mapcar 'file-truename (org-agenda-files t))))
12556 (filter
12557 (cond
12558 ((eq predicate 'files)
12559 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12560 ((eq predicate 'export)
12561 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12562 ((eq predicate 'agenda)
12563 (lambda (b)
12564 (with-current-buffer b
12565 (and (eq major-mode 'org-mode)
12566 (setq bfn (buffer-file-name b))
12567 (member (file-truename bfn) agenda-files)))))
12568 (t (lambda (b) (with-current-buffer b
12569 (or (eq major-mode 'org-mode)
12570 (string-match "\*Org .*Export"
12571 (buffer-name b)))))))))
12572 (delq nil
12573 (mapcar
12574 (lambda(b)
12575 (if (and (funcall filter b)
12576 (or (not exclude-tmp)
12577 (not (string-match "tmp" (buffer-name b)))))
12579 nil))
12580 (buffer-list)))))
12582 (defun org-agenda-files (&optional unrestricted archives)
12583 "Get the list of agenda files.
12584 Optional UNRESTRICTED means return the full list even if a restriction
12585 is currently in place.
12586 When ARCHIVES is t, include all archive files hat are really being
12587 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12588 `org-agenda-archives-mode' is t."
12589 (let ((files
12590 (cond
12591 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12592 ((stringp org-agenda-files) (org-read-agenda-file-list))
12593 ((listp org-agenda-files) org-agenda-files)
12594 (t (error "Invalid value of `org-agenda-files'")))))
12595 (setq files (apply 'append
12596 (mapcar (lambda (f)
12597 (if (file-directory-p f)
12598 (directory-files
12599 f t org-agenda-file-regexp)
12600 (list f)))
12601 files)))
12602 (when org-agenda-skip-unavailable-files
12603 (setq files (delq nil
12604 (mapcar (function
12605 (lambda (file)
12606 (and (file-readable-p file) file)))
12607 files))))
12608 (when (or (eq archives t)
12609 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12610 (setq files (org-add-archive-files files)))
12611 files))
12613 (defun org-edit-agenda-file-list ()
12614 "Edit the list of agenda files.
12615 Depending on setup, this either uses customize to edit the variable
12616 `org-agenda-files', or it visits the file that is holding the list. In the
12617 latter case, the buffer is set up in a way that saving it automatically kills
12618 the buffer and restores the previous window configuration."
12619 (interactive)
12620 (if (stringp org-agenda-files)
12621 (let ((cw (current-window-configuration)))
12622 (find-file org-agenda-files)
12623 (org-set-local 'org-window-configuration cw)
12624 (org-add-hook 'after-save-hook
12625 (lambda ()
12626 (set-window-configuration
12627 (prog1 org-window-configuration
12628 (kill-buffer (current-buffer))))
12629 (org-install-agenda-files-menu)
12630 (message "New agenda file list installed"))
12631 nil 'local)
12632 (message "%s" (substitute-command-keys
12633 "Edit list and finish with \\[save-buffer]")))
12634 (customize-variable 'org-agenda-files)))
12636 (defun org-store-new-agenda-file-list (list)
12637 "Set new value for the agenda file list and save it correctly."
12638 (if (stringp org-agenda-files)
12639 (let ((f org-agenda-files) b)
12640 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12641 (with-temp-file f
12642 (insert (mapconcat 'identity list "\n") "\n")))
12643 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12644 (setq org-agenda-files list)
12645 (customize-save-variable 'org-agenda-files org-agenda-files))))
12647 (defun org-read-agenda-file-list ()
12648 "Read the list of agenda files from a file."
12649 (when (file-directory-p org-agenda-files)
12650 (error "`org-agenda-files' cannot be a single directory"))
12651 (when (stringp org-agenda-files)
12652 (with-temp-buffer
12653 (insert-file-contents org-agenda-files)
12654 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12657 ;;;###autoload
12658 (defun org-cycle-agenda-files ()
12659 "Cycle through the files in `org-agenda-files'.
12660 If the current buffer visits an agenda file, find the next one in the list.
12661 If the current buffer does not, find the first agenda file."
12662 (interactive)
12663 (let* ((fs (org-agenda-files t))
12664 (files (append fs (list (car fs))))
12665 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12666 file)
12667 (unless files (error "No agenda files"))
12668 (catch 'exit
12669 (while (setq file (pop files))
12670 (if (equal (file-truename file) tcf)
12671 (when (car files)
12672 (find-file (car files))
12673 (throw 'exit t))))
12674 (find-file (car fs)))
12675 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12677 (defun org-agenda-file-to-front (&optional to-end)
12678 "Move/add the current file to the top of the agenda file list.
12679 If the file is not present in the list, it is added to the front. If it is
12680 present, it is moved there. With optional argument TO-END, add/move to the
12681 end of the list."
12682 (interactive "P")
12683 (let ((org-agenda-skip-unavailable-files nil)
12684 (file-alist (mapcar (lambda (x)
12685 (cons (file-truename x) x))
12686 (org-agenda-files t)))
12687 (ctf (file-truename buffer-file-name))
12688 x had)
12689 (setq x (assoc ctf file-alist) had x)
12691 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12692 (if to-end
12693 (setq file-alist (append (delq x file-alist) (list x)))
12694 (setq file-alist (cons x (delq x file-alist))))
12695 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12696 (org-install-agenda-files-menu)
12697 (message "File %s to %s of agenda file list"
12698 (if had "moved" "added") (if to-end "end" "front"))))
12700 (defun org-remove-file (&optional file)
12701 "Remove current file from the list of files in variable `org-agenda-files'.
12702 These are the files which are being checked for agenda entries.
12703 Optional argument FILE means, use this file instead of the current."
12704 (interactive)
12705 (let* ((org-agenda-skip-unavailable-files nil)
12706 (file (or file buffer-file-name))
12707 (true-file (file-truename file))
12708 (afile (abbreviate-file-name file))
12709 (files (delq nil (mapcar
12710 (lambda (x)
12711 (if (equal true-file
12712 (file-truename x))
12713 nil x))
12714 (org-agenda-files t)))))
12715 (if (not (= (length files) (length (org-agenda-files t))))
12716 (progn
12717 (org-store-new-agenda-file-list files)
12718 (org-install-agenda-files-menu)
12719 (message "Removed file: %s" afile))
12720 (message "File was not in list: %s (not removed)" afile))))
12722 (defun org-file-menu-entry (file)
12723 (vector file (list 'find-file file) t))
12725 (defun org-check-agenda-file (file)
12726 "Make sure FILE exists. If not, ask user what to do."
12727 (when (not (file-exists-p file))
12728 (message "non-existent file %s. [R]emove from list or [A]bort?"
12729 (abbreviate-file-name file))
12730 (let ((r (downcase (read-char-exclusive))))
12731 (cond
12732 ((equal r ?r)
12733 (org-remove-file file)
12734 (throw 'nextfile t))
12735 (t (error "Abort"))))))
12737 (defun org-get-agenda-file-buffer (file)
12738 "Get a buffer visiting FILE. If the buffer needs to be created, add
12739 it to the list of buffers which might be released later."
12740 (let ((buf (org-find-base-buffer-visiting file)))
12741 (if buf
12742 buf ; just return it
12743 ;; Make a new buffer and remember it
12744 (setq buf (find-file-noselect file))
12745 (if buf (push buf org-agenda-new-buffers))
12746 buf)))
12748 (defun org-release-buffers (blist)
12749 "Release all buffers in list, asking the user for confirmation when needed.
12750 When a buffer is unmodified, it is just killed. When modified, it is saved
12751 \(if the user agrees) and then killed."
12752 (let (buf file)
12753 (while (setq buf (pop blist))
12754 (setq file (buffer-file-name buf))
12755 (when (and (buffer-modified-p buf)
12756 file
12757 (y-or-n-p (format "Save file %s? " file)))
12758 (with-current-buffer buf (save-buffer)))
12759 (kill-buffer buf))))
12761 (defun org-prepare-agenda-buffers (files)
12762 "Create buffers for all agenda files, protect archived trees and comments."
12763 (interactive)
12764 (let ((pa '(:org-archived t))
12765 (pc '(:org-comment t))
12766 (pall '(:org-archived t :org-comment t))
12767 (inhibit-read-only t)
12768 (rea (concat ":" org-archive-tag ":"))
12769 bmp file re)
12770 (save-excursion
12771 (save-restriction
12772 (while (setq file (pop files))
12773 (if (bufferp file)
12774 (set-buffer file)
12775 (org-check-agenda-file file)
12776 (set-buffer (org-get-agenda-file-buffer file)))
12777 (widen)
12778 (setq bmp (buffer-modified-p))
12779 (org-refresh-category-properties)
12780 (setq org-todo-keywords-for-agenda
12781 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12782 (setq org-done-keywords-for-agenda
12783 (append org-done-keywords-for-agenda org-done-keywords))
12784 (setq org-todo-keyword-alist-for-agenda
12785 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12786 (setq org-tag-alist-for-agenda
12787 (append org-tag-alist-for-agenda org-tag-alist))
12789 (save-excursion
12790 (remove-text-properties (point-min) (point-max) pall)
12791 (when org-agenda-skip-archived-trees
12792 (goto-char (point-min))
12793 (while (re-search-forward rea nil t)
12794 (if (org-on-heading-p t)
12795 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12796 (goto-char (point-min))
12797 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12798 (while (re-search-forward re nil t)
12799 (add-text-properties
12800 (match-beginning 0) (org-end-of-subtree t) pc)))
12801 (set-buffer-modified-p bmp))))
12802 (setq org-todo-keyword-alist-for-agenda
12803 (org-uniquify org-todo-keyword-alist-for-agenda)
12804 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12806 ;;;; Embedded LaTeX
12808 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12809 "Keymap for the minor `org-cdlatex-mode'.")
12811 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12812 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12813 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12814 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12815 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12817 (defvar org-cdlatex-texmathp-advice-is-done nil
12818 "Flag remembering if we have applied the advice to texmathp already.")
12820 (define-minor-mode org-cdlatex-mode
12821 "Toggle the minor `org-cdlatex-mode'.
12822 This mode supports entering LaTeX environment and math in LaTeX fragments
12823 in Org-mode.
12824 \\{org-cdlatex-mode-map}"
12825 nil " OCDL" nil
12826 (when org-cdlatex-mode (require 'cdlatex))
12827 (unless org-cdlatex-texmathp-advice-is-done
12828 (setq org-cdlatex-texmathp-advice-is-done t)
12829 (defadvice texmathp (around org-math-always-on activate)
12830 "Always return t in org-mode buffers.
12831 This is because we want to insert math symbols without dollars even outside
12832 the LaTeX math segments. If Orgmode thinks that point is actually inside
12833 an embedded LaTeX fragment, let texmathp do its job.
12834 \\[org-cdlatex-mode-map]"
12835 (interactive)
12836 (let (p)
12837 (cond
12838 ((not (org-mode-p)) ad-do-it)
12839 ((eq this-command 'cdlatex-math-symbol)
12840 (setq ad-return-value t
12841 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12843 (let ((p (org-inside-LaTeX-fragment-p)))
12844 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12845 (setq ad-return-value t
12846 texmathp-why '("Org-mode embedded math" . 0))
12847 (if p ad-do-it)))))))))
12849 (defun turn-on-org-cdlatex ()
12850 "Unconditionally turn on `org-cdlatex-mode'."
12851 (org-cdlatex-mode 1))
12853 (defun org-inside-LaTeX-fragment-p ()
12854 "Test if point is inside a LaTeX fragment.
12855 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12856 sequence appearing also before point.
12857 Even though the matchers for math are configurable, this function assumes
12858 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12859 delimiters are skipped when they have been removed by customization.
12860 The return value is nil, or a cons cell with the delimiter and
12861 and the position of this delimiter.
12863 This function does a reasonably good job, but can locally be fooled by
12864 for example currency specifications. For example it will assume being in
12865 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12866 fragments that are properly closed, but during editing, we have to live
12867 with the uncertainty caused by missing closing delimiters. This function
12868 looks only before point, not after."
12869 (catch 'exit
12870 (let ((pos (point))
12871 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12872 (lim (progn
12873 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12874 (point)))
12875 dd-on str (start 0) m re)
12876 (goto-char pos)
12877 (when dodollar
12878 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12879 re (nth 1 (assoc "$" org-latex-regexps)))
12880 (while (string-match re str start)
12881 (cond
12882 ((= (match-end 0) (length str))
12883 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12884 ((= (match-end 0) (- (length str) 5))
12885 (throw 'exit nil))
12886 (t (setq start (match-end 0))))))
12887 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12888 (goto-char pos)
12889 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12890 (and (match-beginning 2) (throw 'exit nil))
12891 ;; count $$
12892 (while (re-search-backward "\\$\\$" lim t)
12893 (setq dd-on (not dd-on)))
12894 (goto-char pos)
12895 (if dd-on (cons "$$" m))))))
12898 (defun org-try-cdlatex-tab ()
12899 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12900 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12901 - inside a LaTeX fragment, or
12902 - after the first word in a line, where an abbreviation expansion could
12903 insert a LaTeX environment."
12904 (when org-cdlatex-mode
12905 (cond
12906 ((save-excursion
12907 (skip-chars-backward "a-zA-Z0-9*")
12908 (skip-chars-backward " \t")
12909 (bolp))
12910 (cdlatex-tab) t)
12911 ((org-inside-LaTeX-fragment-p)
12912 (cdlatex-tab) t)
12913 (t nil))))
12915 (defun org-cdlatex-underscore-caret (&optional arg)
12916 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12917 Revert to the normal definition outside of these fragments."
12918 (interactive "P")
12919 (if (org-inside-LaTeX-fragment-p)
12920 (call-interactively 'cdlatex-sub-superscript)
12921 (let (org-cdlatex-mode)
12922 (call-interactively (key-binding (vector last-input-event))))))
12924 (defun org-cdlatex-math-modify (&optional arg)
12925 "Execute `cdlatex-math-modify' in LaTeX fragments.
12926 Revert to the normal definition outside of these fragments."
12927 (interactive "P")
12928 (if (org-inside-LaTeX-fragment-p)
12929 (call-interactively 'cdlatex-math-modify)
12930 (let (org-cdlatex-mode)
12931 (call-interactively (key-binding (vector last-input-event))))))
12933 (defvar org-latex-fragment-image-overlays nil
12934 "List of overlays carrying the images of latex fragments.")
12935 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12937 (defun org-remove-latex-fragment-image-overlays ()
12938 "Remove all overlays with LaTeX fragment images in current buffer."
12939 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12940 (setq org-latex-fragment-image-overlays nil))
12942 (defun org-preview-latex-fragment (&optional subtree)
12943 "Preview the LaTeX fragment at point, or all locally or globally.
12944 If the cursor is in a LaTeX fragment, create the image and overlay
12945 it over the source code. If there is no fragment at point, display
12946 all fragments in the current text, from one headline to the next. With
12947 prefix SUBTREE, display all fragments in the current subtree. With a
12948 double prefix `C-u C-u', or when the cursor is before the first headline,
12949 display all fragments in the buffer.
12950 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12951 (interactive "P")
12952 (org-remove-latex-fragment-image-overlays)
12953 (save-excursion
12954 (save-restriction
12955 (let (beg end at msg)
12956 (cond
12957 ((or (equal subtree '(16))
12958 (not (save-excursion
12959 (re-search-backward (concat "^" outline-regexp) nil t))))
12960 (setq beg (point-min) end (point-max)
12961 msg "Creating images for buffer...%s"))
12962 ((equal subtree '(4))
12963 (org-back-to-heading)
12964 (setq beg (point) end (org-end-of-subtree t)
12965 msg "Creating images for subtree...%s"))
12967 (if (setq at (org-inside-LaTeX-fragment-p))
12968 (goto-char (max (point-min) (- (cdr at) 2)))
12969 (org-back-to-heading))
12970 (setq beg (point) end (progn (outline-next-heading) (point))
12971 msg (if at "Creating image...%s"
12972 "Creating images for entry...%s"))))
12973 (message msg "")
12974 (narrow-to-region beg end)
12975 (goto-char beg)
12976 (org-format-latex
12977 (concat "ltxpng/" (file-name-sans-extension
12978 (file-name-nondirectory
12979 buffer-file-name)))
12980 default-directory 'overlays msg at 'forbuffer)
12981 (message msg "done. Use `C-c C-c' to remove images.")))))
12983 (defvar org-latex-regexps
12984 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12985 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12986 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12987 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12988 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12989 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12990 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12991 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12992 "Regular expressions for matching embedded LaTeX.")
12994 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12995 "Replace LaTeX fragments with links to an image, and produce images."
12996 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12997 (let* ((prefixnodir (file-name-nondirectory prefix))
12998 (absprefix (expand-file-name prefix dir))
12999 (todir (file-name-directory absprefix))
13000 (opt org-format-latex-options)
13001 (matchers (plist-get opt :matchers))
13002 (re-list org-latex-regexps)
13003 (cnt 0) txt link beg end re e checkdir
13004 m n block linkfile movefile ov)
13005 ;; Check if there are old images files with this prefix, and remove them
13006 (when (file-directory-p todir)
13007 (mapc 'delete-file
13008 (directory-files
13009 todir 'full
13010 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13011 ;; Check the different regular expressions
13012 (while (setq e (pop re-list))
13013 (setq m (car e) re (nth 1 e) n (nth 2 e)
13014 block (if (nth 3 e) "\n\n" ""))
13015 (when (member m matchers)
13016 (goto-char (point-min))
13017 (while (re-search-forward re nil t)
13018 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13019 (not (get-text-property (match-beginning n)
13020 'org-protected)))
13021 (setq txt (match-string n)
13022 beg (match-beginning n) end (match-end n)
13023 cnt (1+ cnt)
13024 linkfile (format "%s_%04d.png" prefix cnt)
13025 movefile (format "%s_%04d.png" absprefix cnt)
13026 link (concat block "[[file:" linkfile "]]" block))
13027 (if msg (message msg cnt))
13028 (goto-char beg)
13029 (unless checkdir ; make sure the directory exists
13030 (setq checkdir t)
13031 (or (file-directory-p todir) (make-directory todir)))
13032 (org-create-formula-image
13033 txt movefile opt forbuffer)
13034 (if overlays
13035 (progn
13036 (setq ov (org-make-overlay beg end))
13037 (if (featurep 'xemacs)
13038 (progn
13039 (org-overlay-put ov 'invisible t)
13040 (org-overlay-put
13041 ov 'end-glyph
13042 (make-glyph (vector 'png :file movefile))))
13043 (org-overlay-put
13044 ov 'display
13045 (list 'image :type 'png :file movefile :ascent 'center)))
13046 (push ov org-latex-fragment-image-overlays)
13047 (goto-char end))
13048 (delete-region beg end)
13049 (insert link))))))))
13051 ;; This function borrows from Ganesh Swami's latex2png.el
13052 (defun org-create-formula-image (string tofile options buffer)
13053 (let* ((tmpdir (if (featurep 'xemacs)
13054 (temp-directory)
13055 temporary-file-directory))
13056 (texfilebase (make-temp-name
13057 (expand-file-name "orgtex" tmpdir)))
13058 (texfile (concat texfilebase ".tex"))
13059 (dvifile (concat texfilebase ".dvi"))
13060 (pngfile (concat texfilebase ".png"))
13061 (fnh (if (featurep 'xemacs)
13062 (font-height (get-face-font 'default))
13063 (face-attribute 'default :height nil)))
13064 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13065 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13066 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13067 "Black"))
13068 (bg (or (plist-get options (if buffer :background :html-background))
13069 "Transparent")))
13070 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13071 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13072 (with-temp-file texfile
13073 (insert org-format-latex-header
13074 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13075 (let ((dir default-directory))
13076 (condition-case nil
13077 (progn
13078 (cd tmpdir)
13079 (call-process "latex" nil nil nil texfile))
13080 (error nil))
13081 (cd dir))
13082 (if (not (file-exists-p dvifile))
13083 (progn (message "Failed to create dvi file from %s" texfile) nil)
13084 (condition-case nil
13085 (call-process "dvipng" nil nil nil
13086 "-E" "-fg" fg "-bg" bg
13087 "-D" dpi
13088 ;;"-x" scale "-y" scale
13089 "-T" "tight"
13090 "-o" pngfile
13091 dvifile)
13092 (error nil))
13093 (if (not (file-exists-p pngfile))
13094 (progn (message "Failed to create png file from %s" texfile) nil)
13095 ;; Use the requested file name and clean up
13096 (copy-file pngfile tofile 'replace)
13097 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13098 (delete-file (concat texfilebase e)))
13099 pngfile))))
13101 (defun org-dvipng-color (attr)
13102 "Return an rgb color specification for dvipng."
13103 (apply 'format "rgb %s %s %s"
13104 (mapcar 'org-normalize-color
13105 (color-values (face-attribute 'default attr nil)))))
13107 (defun org-normalize-color (value)
13108 "Return string to be used as color value for an RGB component."
13109 (format "%g" (/ value 65535.0)))
13111 ;;;; Key bindings
13113 ;; Make `C-c C-x' a prefix key
13114 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13116 ;; TAB key with modifiers
13117 (org-defkey org-mode-map "\C-i" 'org-cycle)
13118 (org-defkey org-mode-map [(tab)] 'org-cycle)
13119 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13120 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13121 (org-defkey org-mode-map "\M-\t" 'org-complete)
13122 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13123 ;; The following line is necessary under Suse GNU/Linux
13124 (unless (featurep 'xemacs)
13125 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13126 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13127 (define-key org-mode-map [backtab] 'org-shifttab)
13129 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13130 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13131 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13133 ;; Cursor keys with modifiers
13134 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13135 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13136 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13137 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13139 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13140 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13141 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13142 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13144 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13145 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13146 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13147 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13149 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13150 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13152 ;;; Extra keys for tty access.
13153 ;; We only set them when really needed because otherwise the
13154 ;; menus don't show the simple keys
13156 (when (or org-use-extra-keys
13157 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13158 (not window-system))
13159 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13160 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13161 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13162 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13163 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13164 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13165 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13166 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13167 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13168 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13169 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13170 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13171 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13172 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13173 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13174 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13175 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13176 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13177 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13178 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13179 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13180 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13182 ;; All the other keys
13184 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13185 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13186 (if (boundp 'narrow-map)
13187 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13188 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13189 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13190 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13191 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13192 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13193 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13194 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13195 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13196 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13197 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13198 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13199 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13200 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13201 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13202 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13203 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13204 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13205 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13206 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13207 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13208 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13209 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13210 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13211 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13212 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13213 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13214 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13215 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13216 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13217 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13218 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13219 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13220 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13221 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13222 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13223 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13224 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13225 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13226 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13227 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13228 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13229 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13230 (org-defkey org-mode-map "\C-c^" 'org-sort)
13231 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13232 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13233 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13234 (org-defkey org-mode-map "\C-m" 'org-return)
13235 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13236 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13237 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13238 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13239 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13240 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13241 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13242 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13243 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13244 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13245 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13246 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13247 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13248 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13249 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13250 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13251 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13253 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13254 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13255 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13256 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13258 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13259 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13260 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13261 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13262 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13263 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13264 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13265 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13266 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13267 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13268 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13269 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13270 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13272 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13273 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13274 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13275 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13277 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13279 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13281 (when (featurep 'xemacs)
13282 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13285 (defvar org-self-insert-command-undo-counter 0)
13287 (defvar org-table-auto-blank-field) ; defined in org-table.el
13288 (defun org-self-insert-command (N)
13289 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13290 If the cursor is in a table looking at whitespace, the whitespace is
13291 overwritten, and the table is not marked as requiring realignment."
13292 (interactive "p")
13293 (if (and
13294 (org-table-p)
13295 (progn
13296 ;; check if we blank the field, and if that triggers align
13297 (and (featurep 'org-table) org-table-auto-blank-field
13298 (member last-command
13299 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13300 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13301 ;; got extra space, this field does not determine column width
13302 (let (org-table-may-need-update) (org-table-blank-field))
13303 ;; no extra space, this field may determine column width
13304 (org-table-blank-field)))
13306 (eq N 1)
13307 (looking-at "[^|\n]* |"))
13308 (let (org-table-may-need-update)
13309 (goto-char (1- (match-end 0)))
13310 (delete-backward-char 1)
13311 (goto-char (match-beginning 0))
13312 (self-insert-command N))
13313 (setq org-table-may-need-update t)
13314 (self-insert-command N)
13315 (org-fix-tags-on-the-fly)
13316 (if org-self-insert-cluster-for-undo
13317 (if (not (eq last-command 'org-self-insert-command))
13318 (setq org-self-insert-command-undo-counter 1)
13319 (if (>= org-self-insert-command-undo-counter 20)
13320 (setq org-self-insert-command-undo-counter 1)
13321 (and (> org-self-insert-command-undo-counter 0)
13322 buffer-undo-list
13323 (not (cadr buffer-undo-list)) ; remove nil entry
13324 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13325 (setq org-self-insert-command-undo-counter
13326 (1+ org-self-insert-command-undo-counter)))))))
13328 (defun org-fix-tags-on-the-fly ()
13329 (when (and (equal (char-after (point-at-bol)) ?*)
13330 (org-on-heading-p))
13331 (org-align-tags-here org-tags-column)))
13333 (defun org-delete-backward-char (N)
13334 "Like `delete-backward-char', insert whitespace at field end in tables.
13335 When deleting backwards, in tables this function will insert whitespace in
13336 front of the next \"|\" separator, to keep the table aligned. The table will
13337 still be marked for re-alignment if the field did fill the entire column,
13338 because, in this case the deletion might narrow the column."
13339 (interactive "p")
13340 (if (and (org-table-p)
13341 (eq N 1)
13342 (string-match "|" (buffer-substring (point-at-bol) (point)))
13343 (looking-at ".*?|"))
13344 (let ((pos (point))
13345 (noalign (looking-at "[^|\n\r]* |"))
13346 (c org-table-may-need-update))
13347 (backward-delete-char N)
13348 (skip-chars-forward "^|")
13349 (insert " ")
13350 (goto-char (1- pos))
13351 ;; noalign: if there were two spaces at the end, this field
13352 ;; does not determine the width of the column.
13353 (if noalign (setq org-table-may-need-update c)))
13354 (backward-delete-char N)
13355 (org-fix-tags-on-the-fly)))
13357 (defun org-delete-char (N)
13358 "Like `delete-char', but insert whitespace at field end in tables.
13359 When deleting characters, in tables this function will insert whitespace in
13360 front of the next \"|\" separator, to keep the table aligned. The table will
13361 still be marked for re-alignment if the field did fill the entire column,
13362 because, in this case the deletion might narrow the column."
13363 (interactive "p")
13364 (if (and (org-table-p)
13365 (not (bolp))
13366 (not (= (char-after) ?|))
13367 (eq N 1))
13368 (if (looking-at ".*?|")
13369 (let ((pos (point))
13370 (noalign (looking-at "[^|\n\r]* |"))
13371 (c org-table-may-need-update))
13372 (replace-match (concat
13373 (substring (match-string 0) 1 -1)
13374 " |"))
13375 (goto-char pos)
13376 ;; noalign: if there were two spaces at the end, this field
13377 ;; does not determine the width of the column.
13378 (if noalign (setq org-table-may-need-update c)))
13379 (delete-char N))
13380 (delete-char N)
13381 (org-fix-tags-on-the-fly)))
13383 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13384 (put 'org-self-insert-command 'delete-selection t)
13385 (put 'orgtbl-self-insert-command 'delete-selection t)
13386 (put 'org-delete-char 'delete-selection 'supersede)
13387 (put 'org-delete-backward-char 'delete-selection 'supersede)
13388 (put 'org-yank 'delete-selection 'yank)
13390 ;; Make `flyspell-mode' delay after some commands
13391 (put 'org-self-insert-command 'flyspell-delayed t)
13392 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13393 (put 'org-delete-char 'flyspell-delayed t)
13394 (put 'org-delete-backward-char 'flyspell-delayed t)
13396 ;; Make pabbrev-mode expand after org-mode commands
13397 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13398 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13400 ;; How to do this: Measure non-white length of current string
13401 ;; If equal to column width, we should realign.
13403 (defun org-remap (map &rest commands)
13404 "In MAP, remap the functions given in COMMANDS.
13405 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13406 (let (new old)
13407 (while commands
13408 (setq old (pop commands) new (pop commands))
13409 (if (fboundp 'command-remapping)
13410 (org-defkey map (vector 'remap old) new)
13411 (substitute-key-definition old new map global-map)))))
13413 (when (eq org-enable-table-editor 'optimized)
13414 ;; If the user wants maximum table support, we need to hijack
13415 ;; some standard editing functions
13416 (org-remap org-mode-map
13417 'self-insert-command 'org-self-insert-command
13418 'delete-char 'org-delete-char
13419 'delete-backward-char 'org-delete-backward-char)
13420 (org-defkey org-mode-map "|" 'org-force-self-insert))
13422 (defvar org-ctrl-c-ctrl-c-hook nil
13423 "Hook for functions attaching themselves to `C-c C-c'.
13424 This can be used to add additional functionality to the C-c C-c key which
13425 executes context-dependent commands.
13426 Each function will be called with no arguments. The function must check
13427 if the context is appropriate for it to act. If yes, it should do its
13428 thing and then return a non-nil value. If the context is wrong,
13429 just do nothing.")
13431 (defvar org-metaleft-hook nil
13432 "Hook for functions attaching themselves to `M-left'.
13433 See `org-ctrl-c-ctrl-c-hook' for more information.")
13434 (defvar org-metaright-hook nil
13435 "Hook for functions attaching themselves to `M-right'.
13436 See `org-ctrl-c-ctrl-c-hook' for more information.")
13437 (defvar org-metaup-hook nil
13438 "Hook for functions attaching themselves to `M-up'.
13439 See `org-ctrl-c-ctrl-c-hook' for more information.")
13440 (defvar org-metadown-hook nil
13441 "Hook for functions attaching themselves to `M-down'.
13442 See `org-ctrl-c-ctrl-c-hook' for more information.")
13443 (defvar org-shiftmetaleft-hook nil
13444 "Hook for functions attaching themselves to `M-S-left'.
13445 See `org-ctrl-c-ctrl-c-hook' for more information.")
13446 (defvar org-shiftmetaright-hook nil
13447 "Hook for functions attaching themselves to `M-S-right'.
13448 See `org-ctrl-c-ctrl-c-hook' for more information.")
13449 (defvar org-shiftmetaup-hook nil
13450 "Hook for functions attaching themselves to `M-S-up'.
13451 See `org-ctrl-c-ctrl-c-hook' for more information.")
13452 (defvar org-shiftmetadown-hook nil
13453 "Hook for functions attaching themselves to `M-S-down'.
13454 See `org-ctrl-c-ctrl-c-hook' for more information.")
13455 (defvar org-metareturn-hook nil
13456 "Hook for functions attaching themselves to `M-RET'.
13457 See `org-ctrl-c-ctrl-c-hook' for more information.")
13459 (defun org-modifier-cursor-error ()
13460 "Throw an error, a modified cursor command was applied in wrong context."
13461 (error "This command is active in special context like tables, headlines or items"))
13463 (defun org-shiftselect-error ()
13464 "Throw an error because Shift-Cursor command was applied in wrong context."
13465 (if (and (boundp 'shift-select-mode) shift-select-mode)
13466 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13467 (error "This command works only in special context like headlines or timestamps.")))
13469 (defun org-call-for-shift-select (cmd)
13470 (let ((this-command-keys-shift-translated t))
13471 (call-interactively cmd)))
13473 (defun org-shifttab (&optional arg)
13474 "Global visibility cycling or move to previous table field.
13475 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13476 on context.
13477 See the individual commands for more information."
13478 (interactive "P")
13479 (cond
13480 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13481 ((integerp arg)
13482 (message "Content view to level: %d" arg)
13483 (org-content (prefix-numeric-value arg))
13484 (setq org-cycle-global-status 'overview))
13485 (t (call-interactively 'org-global-cycle))))
13487 (defun org-shiftmetaleft ()
13488 "Promote subtree or delete table column.
13489 Calls `org-promote-subtree', `org-outdent-item',
13490 or `org-table-delete-column', depending on context.
13491 See the individual commands for more information."
13492 (interactive)
13493 (cond
13494 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13495 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13496 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13497 ((org-at-item-p) (call-interactively 'org-outdent-item))
13498 (t (org-modifier-cursor-error))))
13500 (defun org-shiftmetaright ()
13501 "Demote subtree or insert table column.
13502 Calls `org-demote-subtree', `org-indent-item',
13503 or `org-table-insert-column', depending on context.
13504 See the individual commands for more information."
13505 (interactive)
13506 (cond
13507 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13508 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13509 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13510 ((org-at-item-p) (call-interactively 'org-indent-item))
13511 (t (org-modifier-cursor-error))))
13513 (defun org-shiftmetaup (&optional arg)
13514 "Move subtree up or kill table row.
13515 Calls `org-move-subtree-up' or `org-table-kill-row' or
13516 `org-move-item-up' depending on context. See the individual commands
13517 for more information."
13518 (interactive "P")
13519 (cond
13520 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13521 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13522 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13523 ((org-at-item-p) (call-interactively 'org-move-item-up))
13524 (t (org-modifier-cursor-error))))
13526 (defun org-shiftmetadown (&optional arg)
13527 "Move subtree down or insert table row.
13528 Calls `org-move-subtree-down' or `org-table-insert-row' or
13529 `org-move-item-down', depending on context. See the individual
13530 commands for more information."
13531 (interactive "P")
13532 (cond
13533 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13534 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13535 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13536 ((org-at-item-p) (call-interactively 'org-move-item-down))
13537 (t (org-modifier-cursor-error))))
13539 (defun org-metaleft (&optional arg)
13540 "Promote heading or move table column to left.
13541 Calls `org-do-promote' or `org-table-move-column', depending on context.
13542 With no specific context, calls the Emacs default `backward-word'.
13543 See the individual commands for more information."
13544 (interactive "P")
13545 (cond
13546 ((run-hook-with-args-until-success 'org-metaleft-hook))
13547 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13548 ((or (org-on-heading-p)
13549 (and (org-region-active-p)
13550 (save-excursion
13551 (goto-char (region-beginning))
13552 (org-on-heading-p))))
13553 (call-interactively 'org-do-promote))
13554 ((or (org-at-item-p)
13555 (and (org-region-active-p)
13556 (save-excursion
13557 (goto-char (region-beginning))
13558 (org-at-item-p))))
13559 (call-interactively 'org-outdent-item))
13560 (t (call-interactively 'backward-word))))
13562 (defun org-metaright (&optional arg)
13563 "Demote subtree or move table column to right.
13564 Calls `org-do-demote' or `org-table-move-column', depending on context.
13565 With no specific context, calls the Emacs default `forward-word'.
13566 See the individual commands for more information."
13567 (interactive "P")
13568 (cond
13569 ((run-hook-with-args-until-success 'org-metaright-hook))
13570 ((org-at-table-p) (call-interactively 'org-table-move-column))
13571 ((or (org-on-heading-p)
13572 (and (org-region-active-p)
13573 (save-excursion
13574 (goto-char (region-beginning))
13575 (org-on-heading-p))))
13576 (call-interactively 'org-do-demote))
13577 ((or (org-at-item-p)
13578 (and (org-region-active-p)
13579 (save-excursion
13580 (goto-char (region-beginning))
13581 (org-at-item-p))))
13582 (call-interactively 'org-indent-item))
13583 (t (call-interactively 'forward-word))))
13585 (defun org-metaup (&optional arg)
13586 "Move subtree up or move table row up.
13587 Calls `org-move-subtree-up' or `org-table-move-row' or
13588 `org-move-item-up', depending on context. See the individual commands
13589 for more information."
13590 (interactive "P")
13591 (cond
13592 ((run-hook-with-args-until-success 'org-metaup-hook))
13593 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13594 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13595 ((org-at-item-p) (call-interactively 'org-move-item-up))
13596 (t (transpose-lines 1) (beginning-of-line -1))))
13598 (defun org-metadown (&optional arg)
13599 "Move subtree down or move table row down.
13600 Calls `org-move-subtree-down' or `org-table-move-row' or
13601 `org-move-item-down', depending on context. See the individual
13602 commands for more information."
13603 (interactive "P")
13604 (cond
13605 ((run-hook-with-args-until-success 'org-metadown-hook))
13606 ((org-at-table-p) (call-interactively 'org-table-move-row))
13607 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13608 ((org-at-item-p) (call-interactively 'org-move-item-down))
13609 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13611 (defun org-shiftup (&optional arg)
13612 "Increase item in timestamp or increase priority of current headline.
13613 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13614 depending on context. See the individual commands for more information."
13615 (interactive "P")
13616 (cond
13617 ((and org-support-shift-select (org-region-active-p))
13618 (org-call-for-shift-select 'previous-line))
13619 ((org-at-timestamp-p t)
13620 (call-interactively (if org-edit-timestamp-down-means-later
13621 'org-timestamp-down 'org-timestamp-up)))
13622 ((and (not (eq org-support-shift-select 'always))
13623 (org-on-heading-p))
13624 (call-interactively 'org-priority-up))
13625 ((and (not org-support-shift-select) (org-at-item-p))
13626 (call-interactively 'org-previous-item))
13627 ((org-clocktable-try-shift 'up arg))
13628 (org-support-shift-select
13629 (org-call-for-shift-select 'previous-line))
13630 (t (org-shiftselect-error))))
13632 (defun org-shiftdown (&optional arg)
13633 "Decrease item in timestamp or decrease priority of current headline.
13634 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13635 depending on context. See the individual commands for more information."
13636 (interactive "P")
13637 (cond
13638 ((and org-support-shift-select (org-region-active-p))
13639 (org-call-for-shift-select 'next-line))
13640 ((org-at-timestamp-p t)
13641 (call-interactively (if org-edit-timestamp-down-means-later
13642 'org-timestamp-up 'org-timestamp-down)))
13643 ((and (not (eq org-support-shift-select 'always))
13644 (org-on-heading-p))
13645 (call-interactively 'org-priority-down))
13646 ((and (not org-support-shift-select) (org-at-item-p))
13647 (call-interactively 'org-next-item))
13648 ((org-clocktable-try-shift 'down arg))
13649 (org-support-shift-select
13650 (org-call-for-shift-select 'next-line))
13651 (t (org-shiftselect-error))))
13653 (defun org-shiftright (&optional arg)
13654 "Cycle the thing at point or in the current line, depending on context.
13655 Depending on context, this does one of the following:
13657 - switch a timestamp at point one day into the future
13658 - on a headline, switch to the next TODO keyword.
13659 - on an item, switch entire list to the next bullet type
13660 - on a property line, switch to the next allowed value
13661 - on a clocktable definition line, move time block into the future"
13662 (interactive "P")
13663 (cond
13664 ((and org-support-shift-select (org-region-active-p))
13665 (org-call-for-shift-select 'forward-char))
13666 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13667 ((and (not (eq org-support-shift-select 'always))
13668 (org-on-heading-p))
13669 (org-call-with-arg 'org-todo 'right))
13670 ((or (and org-support-shift-select
13671 (not (eq org-support-shift-select 'always))
13672 (org-at-item-bullet-p))
13673 (and (not org-support-shift-select) (org-at-item-p)))
13674 (org-call-with-arg 'org-cycle-list-bullet nil))
13675 ((and (not (eq org-support-shift-select 'always))
13676 (org-at-property-p))
13677 (call-interactively 'org-property-next-allowed-value))
13678 ((org-clocktable-try-shift 'right arg))
13679 (org-support-shift-select
13680 (org-call-for-shift-select 'forward-char))
13681 (t (org-shiftselect-error))))
13683 (defun org-shiftleft (&optional arg)
13684 "Cycle the thing at point or in the current line, depending on context.
13685 Depending on context, this does one of the following:
13687 - switch a timestamp at point one day into the past
13688 - on a headline, switch to the previous TODO keyword.
13689 - on an item, switch entire list to the previous bullet type
13690 - on a property line, switch to the previous allowed value
13691 - on a clocktable definition line, move time block into the past"
13692 (interactive "P")
13693 (cond
13694 ((and org-support-shift-select (org-region-active-p))
13695 (org-call-for-shift-select 'backward-char))
13696 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13697 ((and (not (eq org-support-shift-select 'always))
13698 (org-on-heading-p))
13699 (org-call-with-arg 'org-todo 'left))
13700 ((or (and org-support-shift-select
13701 (not (eq org-support-shift-select 'always))
13702 (org-at-item-bullet-p))
13703 (and (not org-support-shift-select) (org-at-item-p)))
13704 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13705 ((and (not (eq org-support-shift-select 'always))
13706 (org-at-property-p))
13707 (call-interactively 'org-property-previous-allowed-value))
13708 ((org-clocktable-try-shift 'left arg))
13709 (org-support-shift-select
13710 (org-call-for-shift-select 'backward-char))
13711 (t (org-shiftselect-error))))
13713 (defun org-shiftcontrolright ()
13714 "Switch to next TODO set."
13715 (interactive)
13716 (cond
13717 ((and org-support-shift-select (org-region-active-p))
13718 (org-call-for-shift-select 'forward-word))
13719 ((and (not (eq org-support-shift-select 'always))
13720 (org-on-heading-p))
13721 (org-call-with-arg 'org-todo 'nextset))
13722 (org-support-shift-select
13723 (org-call-for-shift-select 'forward-word))
13724 (t (org-shiftselect-error))))
13726 (defun org-shiftcontrolleft ()
13727 "Switch to previous TODO set."
13728 (interactive)
13729 (cond
13730 ((and org-support-shift-select (org-region-active-p))
13731 (org-call-for-shift-select 'backward-word))
13732 ((and (not (eq org-support-shift-select 'always))
13733 (org-on-heading-p))
13734 (org-call-with-arg 'org-todo 'previousset))
13735 (org-support-shift-select
13736 (org-call-for-shift-select 'backward-word))
13737 (t (org-shiftselect-error))))
13739 (defun org-ctrl-c-ret ()
13740 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13741 (interactive)
13742 (cond
13743 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13744 (t (call-interactively 'org-insert-heading))))
13746 (defun org-copy-special ()
13747 "Copy region in table or copy current subtree.
13748 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13749 See the individual commands for more information."
13750 (interactive)
13751 (call-interactively
13752 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13754 (defun org-cut-special ()
13755 "Cut region in table or cut current subtree.
13756 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13757 See the individual commands for more information."
13758 (interactive)
13759 (call-interactively
13760 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13762 (defun org-paste-special (arg)
13763 "Paste rectangular region into table, or past subtree relative to level.
13764 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13765 See the individual commands for more information."
13766 (interactive "P")
13767 (if (org-at-table-p)
13768 (org-table-paste-rectangle)
13769 (org-paste-subtree arg)))
13771 (defun org-edit-special ()
13772 "Call a special editor for the stuff at point.
13773 When at a table, call the formula editor with `org-table-edit-formulas'.
13774 When at the first line of an src example, call `org-edit-src-code'.
13775 When in an #+include line, visit the include file. Otherwise call
13776 `ffap' to visit the file at point."
13777 (interactive)
13778 (cond
13779 ((org-at-table-p)
13780 (call-interactively 'org-table-edit-formulas))
13781 ((save-excursion
13782 (beginning-of-line 1)
13783 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13784 (find-file (org-trim (match-string 1))))
13785 ((org-edit-src-code))
13786 ((org-edit-fixed-width-region))
13787 (t (call-interactively 'ffap))))
13790 (defun org-ctrl-c-ctrl-c (&optional arg)
13791 "Set tags in headline, or update according to changed information at point.
13793 This command does many different things, depending on context:
13795 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13796 this is what we do.
13798 - If the cursor is in a headline, prompt for tags and insert them
13799 into the current line, aligned to `org-tags-column'. When called
13800 with prefix arg, realign all tags in the current buffer.
13802 - If the cursor is in one of the special #+KEYWORD lines, this
13803 triggers scanning the buffer for these lines and updating the
13804 information.
13806 - If the cursor is inside a table, realign the table. This command
13807 works even if the automatic table editor has been turned off.
13809 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13810 the entire table.
13812 - If the cursor is at a footnote reference or definition, jump to
13813 the corresponding definition or references, respectively.
13815 - If the cursor is a the beginning of a dynamic block, update it.
13817 - If the cursor is inside a table created by the table.el package,
13818 activate that table.
13820 - If the current buffer is a remember buffer, close note and file
13821 it. A prefix argument of 1 files to the default location
13822 without further interaction. A prefix argument of 2 files to
13823 the currently clocking task.
13825 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13826 links in this buffer.
13828 - If the cursor is on a numbered item in a plain list, renumber the
13829 ordered list.
13831 - If the cursor is on a checkbox, toggle it."
13832 (interactive "P")
13833 (let ((org-enable-table-editor t))
13834 (cond
13835 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13836 org-occur-highlights
13837 org-latex-fragment-image-overlays)
13838 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13839 (org-remove-occur-highlights)
13840 (org-remove-latex-fragment-image-overlays)
13841 (message "Temporary highlights/overlays removed from current buffer"))
13842 ((and (local-variable-p 'org-finish-function (current-buffer))
13843 (fboundp org-finish-function))
13844 (funcall org-finish-function))
13845 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13846 ((org-at-property-p)
13847 (call-interactively 'org-property-action))
13848 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13849 ((org-on-heading-p) (call-interactively 'org-set-tags))
13850 ((org-at-table.el-p)
13851 (require 'table)
13852 (beginning-of-line 1)
13853 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13854 (call-interactively 'table-recognize-table))
13855 ((org-at-table-p)
13856 (org-table-maybe-eval-formula)
13857 (if arg
13858 (call-interactively 'org-table-recalculate)
13859 (org-table-maybe-recalculate-line))
13860 (call-interactively 'org-table-align))
13861 ((or (org-footnote-at-reference-p)
13862 (org-footnote-at-definition-p))
13863 (call-interactively 'org-footnote-action))
13864 ((org-at-item-checkbox-p)
13865 (call-interactively 'org-toggle-checkbox))
13866 ((org-at-item-p)
13867 (if arg
13868 (call-interactively 'org-toggle-checkbox)
13869 (call-interactively 'org-maybe-renumber-ordered-list)))
13870 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13871 ;; Dynamic block
13872 (beginning-of-line 1)
13873 (save-excursion (org-update-dblock)))
13874 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13875 (cond
13876 ((equal (match-string 1) "TBLFM")
13877 ;; Recalculate the table before this line
13878 (save-excursion
13879 (beginning-of-line 1)
13880 (skip-chars-backward " \r\n\t")
13881 (if (org-at-table-p)
13882 (org-call-with-arg 'org-table-recalculate t))))
13884 ; (org-set-regexps-and-options)
13885 ; (org-restart-font-lock)
13886 (let ((org-inhibit-startup t)) (org-mode-restart))
13887 (message "Local setup has been refreshed"))))
13888 (t (error "C-c C-c can do nothing useful at this location.")))))
13890 (defun org-mode-restart ()
13891 "Restart Org-mode, to scan again for special lines.
13892 Also updates the keyword regular expressions."
13893 (interactive)
13894 (org-mode)
13895 (message "Org-mode restarted"))
13897 (defun org-kill-note-or-show-branches ()
13898 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13899 (interactive)
13900 (if (not org-finish-function)
13901 (call-interactively 'show-branches)
13902 (let ((org-note-abort t))
13903 (funcall org-finish-function))))
13905 (defun org-return (&optional indent)
13906 "Goto next table row or insert a newline.
13907 Calls `org-table-next-row' or `newline', depending on context.
13908 See the individual commands for more information."
13909 (interactive)
13910 (cond
13911 ((bobp) (if indent (newline-and-indent) (newline)))
13912 ((org-at-table-p)
13913 (org-table-justify-field-maybe)
13914 (call-interactively 'org-table-next-row))
13915 ((and org-return-follows-link
13916 (eq (get-text-property (point) 'face) 'org-link))
13917 (call-interactively 'org-open-at-point))
13918 ((and (org-at-heading-p)
13919 (looking-at
13920 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13921 (org-show-entry)
13922 (end-of-line 1)
13923 (newline))
13924 (t (if indent (newline-and-indent) (newline)))))
13926 (defun org-return-indent ()
13927 "Goto next table row or insert a newline and indent.
13928 Calls `org-table-next-row' or `newline-and-indent', depending on
13929 context. See the individual commands for more information."
13930 (interactive)
13931 (org-return t))
13933 (defun org-ctrl-c-star ()
13934 "Compute table, or change heading status of lines.
13935 Calls `org-table-recalculate' or `org-toggle-heading',
13936 depending on context."
13937 (interactive)
13938 (cond
13939 ((org-at-table-p)
13940 (call-interactively 'org-table-recalculate))
13942 ;; Convert all lines in region to list items
13943 (call-interactively 'org-toggle-heading))))
13945 (defun org-ctrl-c-minus ()
13946 "Insert separator line in table or modify bullet status of line.
13947 Also turns a plain line or a region of lines into list items.
13948 Calls `org-table-insert-hline', `org-toggle-item', or
13949 `org-cycle-list-bullet', depending on context."
13950 (interactive)
13951 (cond
13952 ((org-at-table-p)
13953 (call-interactively 'org-table-insert-hline))
13954 ((org-region-active-p)
13955 (call-interactively 'org-toggle-item))
13956 ((org-in-item-p)
13957 (call-interactively 'org-cycle-list-bullet))
13959 (call-interactively 'org-toggle-item))))
13961 (defun org-toggle-item ()
13962 "Convert headings or normal lines to items, items to normal lines.
13963 If there is no active region, only the current line is considered.
13965 If the first line in the region is a headline, convert all headlines to items.
13967 If the first line in the region is an item, convert all items to normal lines.
13969 If the first line is normal text, add an item bullet to each line."
13970 (interactive)
13971 (let (l2 l beg end)
13972 (if (org-region-active-p)
13973 (setq beg (region-beginning) end (region-end))
13974 (setq beg (point-at-bol)
13975 end (min (1+ (point-at-eol)) (point-max))))
13976 (save-excursion
13977 (goto-char end)
13978 (setq l2 (org-current-line))
13979 (goto-char beg)
13980 (beginning-of-line 1)
13981 (setq l (1- (org-current-line)))
13982 (if (org-at-item-p)
13983 ;; We already have items, de-itemize
13984 (while (< (setq l (1+ l)) l2)
13985 (when (org-at-item-p)
13986 (goto-char (match-beginning 2))
13987 (delete-region (match-beginning 2) (match-end 2))
13988 (and (looking-at "[ \t]+") (replace-match "")))
13989 (beginning-of-line 2))
13990 (if (org-on-heading-p)
13991 ;; Headings, convert to items
13992 (while (< (setq l (1+ l)) l2)
13993 (if (looking-at org-outline-regexp)
13994 (replace-match "- " t t))
13995 (beginning-of-line 2))
13996 ;; normal lines, turn them into items
13997 (while (< (setq l (1+ l)) l2)
13998 (unless (org-at-item-p)
13999 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14000 (replace-match "\\1- \\2")))
14001 (beginning-of-line 2)))))))
14003 (defun org-toggle-heading (&optional nstars)
14004 "Convert headings to normal text, or items or text to headings.
14005 If there is no active region, only the current line is considered.
14007 If the first line is a heading, remove the stars from all headlines
14008 in the region.
14010 If the first line is a plain list item, turn all plain list items into
14011 headings.
14013 If the first line is a normal line, turn each and every line in the region
14014 into a heading.
14016 When converting a line into a heading, the number of stars is chosen
14017 such that the lines become children of the current entry. However, when
14018 a prefix argument is given, its value determines the number of stars to add."
14019 (interactive "P")
14020 (let (l2 l itemp beg end)
14021 (if (org-region-active-p)
14022 (setq beg (region-beginning) end (region-end))
14023 (setq beg (point-at-bol)
14024 end (min (1+ (point-at-eol)) (point-max))))
14025 (save-excursion
14026 (goto-char end)
14027 (setq l2 (org-current-line))
14028 (goto-char beg)
14029 (beginning-of-line 1)
14030 (setq l (1- (org-current-line)))
14031 (if (org-on-heading-p)
14032 ;; We already have headlines, de-star them
14033 (while (< (setq l (1+ l)) l2)
14034 (when (org-on-heading-p t)
14035 (and (looking-at outline-regexp) (replace-match "")))
14036 (beginning-of-line 2))
14037 (setq itemp (org-at-item-p))
14038 (let* ((stars
14039 (if nstars
14040 (make-string (prefix-numeric-value current-prefix-arg)
14042 (save-excursion
14043 (re-search-backward org-complex-heading-regexp nil t)
14044 (or (match-string 1) "*"))))
14045 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
14046 (rpl (concat stars add-stars " ")))
14047 (while (< (setq l (1+ l)) l2)
14048 (if itemp
14049 (and (org-at-item-p) (replace-match rpl t t))
14050 (unless (org-on-heading-p)
14051 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14052 (replace-match (concat rpl (match-string 2))))))
14053 (beginning-of-line 2)))))))
14055 (defun org-meta-return (&optional arg)
14056 "Insert a new heading or wrap a region in a table.
14057 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14058 See the individual commands for more information."
14059 (interactive "P")
14060 (cond
14061 ((run-hook-with-args-until-success 'org-metareturn-hook))
14062 ((org-at-table-p)
14063 (call-interactively 'org-table-wrap-region))
14064 (t (call-interactively 'org-insert-heading))))
14066 ;;; Menu entries
14068 ;; Define the Org-mode menus
14069 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14070 '("Tbl"
14071 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14072 ["Next Field" org-cycle (org-at-table-p)]
14073 ["Previous Field" org-shifttab (org-at-table-p)]
14074 ["Next Row" org-return (org-at-table-p)]
14075 "--"
14076 ["Blank Field" org-table-blank-field (org-at-table-p)]
14077 ["Edit Field" org-table-edit-field (org-at-table-p)]
14078 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14079 "--"
14080 ("Column"
14081 ["Move Column Left" org-metaleft (org-at-table-p)]
14082 ["Move Column Right" org-metaright (org-at-table-p)]
14083 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14084 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14085 ("Row"
14086 ["Move Row Up" org-metaup (org-at-table-p)]
14087 ["Move Row Down" org-metadown (org-at-table-p)]
14088 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14089 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14090 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14091 "--"
14092 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14093 ("Rectangle"
14094 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14095 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14096 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14097 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14098 "--"
14099 ("Calculate"
14100 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14101 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14102 ["Edit Formulas" org-edit-special (org-at-table-p)]
14103 "--"
14104 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14105 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14106 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14107 "--"
14108 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14109 "--"
14110 ["Sum Column/Rectangle" org-table-sum
14111 (or (org-at-table-p) (org-region-active-p))]
14112 ["Which Column?" org-table-current-column (org-at-table-p)])
14113 ["Debug Formulas"
14114 org-table-toggle-formula-debugger
14115 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14116 ["Show Col/Row Numbers"
14117 org-table-toggle-coordinate-overlays
14118 :style toggle
14119 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14120 "--"
14121 ["Create" org-table-create (and (not (org-at-table-p))
14122 org-enable-table-editor)]
14123 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14124 ["Import from File" org-table-import (not (org-at-table-p))]
14125 ["Export to File" org-table-export (org-at-table-p)]
14126 "--"
14127 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14129 (easy-menu-define org-org-menu org-mode-map "Org menu"
14130 '("Org"
14131 ("Show/Hide"
14132 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14133 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14134 ["Sparse Tree..." org-sparse-tree t]
14135 ["Reveal Context" org-reveal t]
14136 ["Show All" show-all t]
14137 "--"
14138 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14139 "--"
14140 ["New Heading" org-insert-heading t]
14141 ("Navigate Headings"
14142 ["Up" outline-up-heading t]
14143 ["Next" outline-next-visible-heading t]
14144 ["Previous" outline-previous-visible-heading t]
14145 ["Next Same Level" outline-forward-same-level t]
14146 ["Previous Same Level" outline-backward-same-level t]
14147 "--"
14148 ["Jump" org-goto t])
14149 ("Edit Structure"
14150 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14151 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14152 "--"
14153 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14154 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14155 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14156 "--"
14157 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14158 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14159 ["Demote Heading" org-metaright (not (org-at-table-p))]
14160 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14161 "--"
14162 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14163 "--"
14164 ["Convert to odd levels" org-convert-to-odd-levels t]
14165 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14166 ("Editing"
14167 ["Emphasis..." org-emphasize t]
14168 ["Edit Source Example" org-edit-special t]
14169 "--"
14170 ["Footnote new/jump" org-footnote-action t]
14171 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14172 ("Archive"
14173 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14174 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14175 ; :active t :keys "C-u C-c C-x C-a"]
14176 ["Sparse trees open ARCHIVE trees"
14177 (setq org-sparse-tree-open-archived-trees
14178 (not org-sparse-tree-open-archived-trees))
14179 :style toggle :selected org-sparse-tree-open-archived-trees]
14180 ["Cycling opens ARCHIVE trees"
14181 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14182 :style toggle :selected org-cycle-open-archived-trees]
14183 "--"
14184 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14185 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14186 ; ["Check and Move Children" (org-archive-subtree '(4))
14187 ; :active t :keys "C-u C-c C-x C-s"]
14189 "--"
14190 ("TODO Lists"
14191 ["TODO/DONE/-" org-todo t]
14192 ("Select keyword"
14193 ["Next keyword" org-shiftright (org-on-heading-p)]
14194 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14195 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14196 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14197 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14198 ["Show TODO Tree" org-show-todo-tree t]
14199 ["Global TODO list" org-todo-list t]
14200 "--"
14201 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14202 :selected org-enforce-todo-dependencies :style toggle :active t]
14203 "Settings for tree at point"
14204 ["Do Children sequentially" org-toggle-ordered-property :style radio
14205 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14206 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14207 ["Do Children parallel" org-toggle-ordered-property :style radio
14208 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14209 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14210 "--"
14211 ["Set Priority" org-priority t]
14212 ["Priority Up" org-shiftup t]
14213 ["Priority Down" org-shiftdown t])
14214 ("TAGS and Properties"
14215 ["Set Tags" org-set-tags-command t]
14216 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14217 "--"
14218 ["Set property" org-set-property t]
14219 ["Column view of properties" org-columns t]
14220 ["Insert Column View DBlock" org-insert-columns-dblock t])
14221 ("Dates and Scheduling"
14222 ["Timestamp" org-time-stamp t]
14223 ["Timestamp (inactive)" org-time-stamp-inactive t]
14224 ("Change Date"
14225 ["1 Day Later" org-shiftright t]
14226 ["1 Day Earlier" org-shiftleft t]
14227 ["1 ... Later" org-shiftup t]
14228 ["1 ... Earlier" org-shiftdown t])
14229 ["Compute Time Range" org-evaluate-time-range t]
14230 ["Schedule Item" org-schedule t]
14231 ["Deadline" org-deadline t]
14232 "--"
14233 ["Custom time format" org-toggle-time-stamp-overlays
14234 :style radio :selected org-display-custom-times]
14235 "--"
14236 ["Goto Calendar" org-goto-calendar t]
14237 ["Date from Calendar" org-date-from-calendar t]
14238 "--"
14239 ["Start/Restart Timer" org-timer-start t]
14240 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14241 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14242 ["Insert Timer String" org-timer t]
14243 ["Insert Timer Item" org-timer-item t])
14244 ("Logging work"
14245 ["Clock in" org-clock-in t]
14246 ["Clock out" org-clock-out t]
14247 ["Clock cancel" org-clock-cancel t]
14248 ["Goto running clock" org-clock-goto t]
14249 ["Display times" org-clock-display t]
14250 ["Create clock table" org-clock-report t]
14251 "--"
14252 ["Record DONE time"
14253 (progn (setq org-log-done (not org-log-done))
14254 (message "Switching to %s will %s record a timestamp"
14255 (car org-done-keywords)
14256 (if org-log-done "automatically" "not")))
14257 :style toggle :selected org-log-done])
14258 "--"
14259 ["Agenda Command..." org-agenda t]
14260 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14261 ("File List for Agenda")
14262 ("Special views current file"
14263 ["TODO Tree" org-show-todo-tree t]
14264 ["Check Deadlines" org-check-deadlines t]
14265 ["Timeline" org-timeline t]
14266 ["Tags Tree" org-tags-sparse-tree t])
14267 "--"
14268 ("Hyperlinks"
14269 ["Store Link (Global)" org-store-link t]
14270 ["Insert Link" org-insert-link t]
14271 ["Follow Link" org-open-at-point t]
14272 "--"
14273 ["Next link" org-next-link t]
14274 ["Previous link" org-previous-link t]
14275 "--"
14276 ["Descriptive Links"
14277 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14278 :style radio
14279 :selected (member '(org-link) buffer-invisibility-spec)]
14280 ["Literal Links"
14281 (progn
14282 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14283 :style radio
14284 :selected (not (member '(org-link) buffer-invisibility-spec))])
14285 "--"
14286 ["Export/Publish..." org-export t]
14287 ("LaTeX"
14288 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14289 :selected org-cdlatex-mode]
14290 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14291 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14292 ["Modify math symbol" org-cdlatex-math-modify
14293 (org-inside-LaTeX-fragment-p)]
14294 ["Export LaTeX fragments as images"
14295 (if (featurep 'org-exp)
14296 (setq org-export-with-LaTeX-fragments
14297 (not org-export-with-LaTeX-fragments))
14298 (require 'org-exp))
14299 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14300 org-export-with-LaTeX-fragments)])
14301 "--"
14302 ("Documentation"
14303 ["Show Version" org-version t]
14304 ["Info Documentation" org-info t])
14305 ("Customize"
14306 ["Browse Org Group" org-customize t]
14307 "--"
14308 ["Expand This Menu" org-create-customize-menu
14309 (fboundp 'customize-menu-create)])
14310 "--"
14311 ("Refresh/Reload"
14312 ["Refresh setup current buffer" org-mode-restart t]
14313 ["Reload Org (after update)" org-reload t]
14314 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14317 (defun org-info (&optional node)
14318 "Read documentation for Org-mode in the info system.
14319 With optional NODE, go directly to that node."
14320 (interactive)
14321 (info (format "(org)%s" (or node ""))))
14323 (defun org-install-agenda-files-menu ()
14324 (let ((bl (buffer-list)))
14325 (save-excursion
14326 (while bl
14327 (set-buffer (pop bl))
14328 (if (org-mode-p) (setq bl nil)))
14329 (when (org-mode-p)
14330 (easy-menu-change
14331 '("Org") "File List for Agenda"
14332 (append
14333 (list
14334 ["Edit File List" (org-edit-agenda-file-list) t]
14335 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14336 ["Remove Current File from List" org-remove-file t]
14337 ["Cycle through agenda files" org-cycle-agenda-files t]
14338 ["Occur in all agenda files" org-occur-in-agenda-files t]
14339 "--")
14340 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14342 ;;;; Documentation
14344 ;;;###autoload
14345 (defun org-require-autoloaded-modules ()
14346 (interactive)
14347 (mapc 'require
14348 '(org-agenda org-archive org-attach org-clock org-colview
14349 org-exp org-id org-export-latex org-publish
14350 org-remember org-table org-timer)))
14352 ;;;###autoload
14353 (defun org-reload (&optional uncompiled)
14354 "Reload all org lisp files.
14355 With prefix arg UNCOMPILED, load the uncompiled versions."
14356 (interactive "P")
14357 (require 'find-func)
14358 (let* ((dir (file-name-directory (find-library-name "org")))
14359 (files (directory-files dir t "\\.el\\'"))
14360 (remove-re (concat (if (featurep 'xemacs)
14361 "org-colview" "org-colview-xemacs")
14362 "\\'")))
14363 (setq files (mapcar 'file-name-sans-extension files))
14364 (setq files (mapcar
14365 (lambda (x) (if (string-match remove-re x) nil x))
14366 files))
14367 (setq files (delq nil files))
14368 (mapc
14369 (lambda (f)
14370 (if (and (not uncompiled)
14371 (file-exists-p (concat f ".elc")))
14372 (load (concat f ".elc") nil nil t)
14373 (load (concat f ".el") nil nil t)))
14374 files)))
14376 ;;;###autoload
14377 (defun org-customize ()
14378 "Call the customize function with org as argument."
14379 (interactive)
14380 (org-load-modules-maybe)
14381 (org-require-autoloaded-modules)
14382 (customize-browse 'org))
14384 (defun org-create-customize-menu ()
14385 "Create a full customization menu for Org-mode, insert it into the menu."
14386 (interactive)
14387 (org-load-modules-maybe)
14388 (org-require-autoloaded-modules)
14389 (if (fboundp 'customize-menu-create)
14390 (progn
14391 (easy-menu-change
14392 '("Org") "Customize"
14393 `(["Browse Org group" org-customize t]
14394 "--"
14395 ,(customize-menu-create 'org)
14396 ["Set" Custom-set t]
14397 ["Save" Custom-save t]
14398 ["Reset to Current" Custom-reset-current t]
14399 ["Reset to Saved" Custom-reset-saved t]
14400 ["Reset to Standard Settings" Custom-reset-standard t]))
14401 (message "\"Org\"-menu now contains full customization menu"))
14402 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14404 ;;;; Miscellaneous stuff
14406 ;;; Generally useful functions
14408 (defun org-find-text-property-in-string (prop s)
14409 "Return the first non-nil value of property PROP in string S."
14410 (or (get-text-property 0 prop s)
14411 (get-text-property (or (next-single-property-change 0 prop s) 0)
14412 prop s)))
14414 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14415 "Display the given MESSAGE as a warning."
14416 (if (fboundp 'display-warning)
14417 (display-warning 'org message
14418 (if (featurep 'xemacs)
14419 'warning
14420 :warning))
14421 (let ((buf (get-buffer-create "*Org warnings*")))
14422 (with-current-buffer buf
14423 (goto-char (point-max))
14424 (insert "Warning (Org): " message)
14425 (unless (bolp)
14426 (newline)))
14427 (display-buffer buf)
14428 (sit-for 0))))
14430 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14431 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14432 (if (and marker (marker-buffer marker)
14433 (buffer-live-p (marker-buffer marker)))
14434 (progn
14435 (switch-to-buffer (marker-buffer marker))
14436 (if (or (> marker (point-max)) (< marker (point-min)))
14437 (widen))
14438 (goto-char marker)
14439 (org-show-context 'org-goto))
14440 (if bookmark
14441 (bookmark-jump bookmark)
14442 (error "Cannot find location"))))
14444 (defun org-quote-csv-field (s)
14445 "Quote field for inclusion in CSV material."
14446 (if (string-match "[\",]" s)
14447 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14450 (defun org-plist-delete (plist property)
14451 "Delete PROPERTY from PLIST.
14452 This is in contrast to merely setting it to 0."
14453 (let (p)
14454 (while plist
14455 (if (not (eq property (car plist)))
14456 (setq p (plist-put p (car plist) (nth 1 plist))))
14457 (setq plist (cddr plist)))
14460 (defun org-force-self-insert (N)
14461 "Needed to enforce self-insert under remapping."
14462 (interactive "p")
14463 (self-insert-command N))
14465 (defun org-string-width (s)
14466 "Compute width of string, ignoring invisible characters.
14467 This ignores character with invisibility property `org-link', and also
14468 characters with property `org-cwidth', because these will become invisible
14469 upon the next fontification round."
14470 (let (b l)
14471 (when (or (eq t buffer-invisibility-spec)
14472 (assq 'org-link buffer-invisibility-spec))
14473 (while (setq b (text-property-any 0 (length s)
14474 'invisible 'org-link s))
14475 (setq s (concat (substring s 0 b)
14476 (substring s (or (next-single-property-change
14477 b 'invisible s) (length s)))))))
14478 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14479 (setq s (concat (substring s 0 b)
14480 (substring s (or (next-single-property-change
14481 b 'org-cwidth s) (length s))))))
14482 (setq l (string-width s) b -1)
14483 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14484 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14487 (defun org-get-indentation (&optional line)
14488 "Get the indentation of the current line, interpreting tabs.
14489 When LINE is given, assume it represents a line and compute its indentation."
14490 (if line
14491 (if (string-match "^ *" (org-remove-tabs line))
14492 (match-end 0))
14493 (save-excursion
14494 (beginning-of-line 1)
14495 (skip-chars-forward " \t")
14496 (current-column))))
14498 (defun org-remove-tabs (s &optional width)
14499 "Replace tabulators in S with spaces.
14500 Assumes that s is a single line, starting in column 0."
14501 (setq width (or width tab-width))
14502 (while (string-match "\t" s)
14503 (setq s (replace-match
14504 (make-string
14505 (- (* width (/ (+ (match-beginning 0) width) width))
14506 (match-beginning 0)) ?\ )
14507 t t s)))
14510 (defun org-fix-indentation (line ind)
14511 "Fix indentation in LINE.
14512 IND is a cons cell with target and minimum indentation.
14513 If the current indentation in LINE is smaller than the minimum,
14514 leave it alone. If it is larger than ind, set it to the target."
14515 (let* ((l (org-remove-tabs line))
14516 (i (org-get-indentation l))
14517 (i1 (car ind)) (i2 (cdr ind)))
14518 (if (>= i i2) (setq l (substring line i2)))
14519 (if (> i1 0)
14520 (concat (make-string i1 ?\ ) l)
14521 l)))
14523 (defun org-base-buffer (buffer)
14524 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14525 (if (not buffer)
14526 buffer
14527 (or (buffer-base-buffer buffer)
14528 buffer)))
14530 (defun org-trim (s)
14531 "Remove whitespace at beginning and end of string."
14532 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14533 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14536 (defun org-wrap (string &optional width lines)
14537 "Wrap string to either a number of lines, or a width in characters.
14538 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14539 that costs. If there is a word longer than WIDTH, the text is actually
14540 wrapped to the length of that word.
14541 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14542 many lines, whatever width that takes.
14543 The return value is a list of lines, without newlines at the end."
14544 (let* ((words (org-split-string string "[ \t\n]+"))
14545 (maxword (apply 'max (mapcar 'org-string-width words)))
14546 w ll)
14547 (cond (width
14548 (org-do-wrap words (max maxword width)))
14549 (lines
14550 (setq w maxword)
14551 (setq ll (org-do-wrap words maxword))
14552 (if (<= (length ll) lines)
14554 (setq ll words)
14555 (while (> (length ll) lines)
14556 (setq w (1+ w))
14557 (setq ll (org-do-wrap words w)))
14558 ll))
14559 (t (error "Cannot wrap this")))))
14561 (defun org-do-wrap (words width)
14562 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14563 (let (lines line)
14564 (while words
14565 (setq line (pop words))
14566 (while (and words (< (+ (length line) (length (car words))) width))
14567 (setq line (concat line " " (pop words))))
14568 (setq lines (push line lines)))
14569 (nreverse lines)))
14571 (defun org-split-string (string &optional separators)
14572 "Splits STRING into substrings at SEPARATORS.
14573 No empty strings are returned if there are matches at the beginning
14574 and end of string."
14575 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14576 (start 0)
14577 notfirst
14578 (list nil))
14579 (while (and (string-match rexp string
14580 (if (and notfirst
14581 (= start (match-beginning 0))
14582 (< start (length string)))
14583 (1+ start) start))
14584 (< (match-beginning 0) (length string)))
14585 (setq notfirst t)
14586 (or (eq (match-beginning 0) 0)
14587 (and (eq (match-beginning 0) (match-end 0))
14588 (eq (match-beginning 0) start))
14589 (setq list
14590 (cons (substring string start (match-beginning 0))
14591 list)))
14592 (setq start (match-end 0)))
14593 (or (eq start (length string))
14594 (setq list
14595 (cons (substring string start)
14596 list)))
14597 (nreverse list)))
14599 (defun org-context ()
14600 "Return a list of contexts of the current cursor position.
14601 If several contexts apply, all are returned.
14602 Each context entry is a list with a symbol naming the context, and
14603 two positions indicating start and end of the context. Possible
14604 contexts are:
14606 :headline anywhere in a headline
14607 :headline-stars on the leading stars in a headline
14608 :todo-keyword on a TODO keyword (including DONE) in a headline
14609 :tags on the TAGS in a headline
14610 :priority on the priority cookie in a headline
14611 :item on the first line of a plain list item
14612 :item-bullet on the bullet/number of a plain list item
14613 :checkbox on the checkbox in a plain list item
14614 :table in an org-mode table
14615 :table-special on a special filed in a table
14616 :table-table in a table.el table
14617 :link on a hyperlink
14618 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14619 :target on a <<target>>
14620 :radio-target on a <<<radio-target>>>
14621 :latex-fragment on a LaTeX fragment
14622 :latex-preview on a LaTeX fragment with overlayed preview image
14624 This function expects the position to be visible because it uses font-lock
14625 faces as a help to recognize the following contexts: :table-special, :link,
14626 and :keyword."
14627 (let* ((f (get-text-property (point) 'face))
14628 (faces (if (listp f) f (list f)))
14629 (p (point)) clist o)
14630 ;; First the large context
14631 (cond
14632 ((org-on-heading-p t)
14633 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14634 (when (progn
14635 (beginning-of-line 1)
14636 (looking-at org-todo-line-tags-regexp))
14637 (push (org-point-in-group p 1 :headline-stars) clist)
14638 (push (org-point-in-group p 2 :todo-keyword) clist)
14639 (push (org-point-in-group p 4 :tags) clist))
14640 (goto-char p)
14641 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14642 (if (looking-at "\\[#[A-Z0-9]\\]")
14643 (push (org-point-in-group p 0 :priority) clist)))
14645 ((org-at-item-p)
14646 (push (org-point-in-group p 2 :item-bullet) clist)
14647 (push (list :item (point-at-bol)
14648 (save-excursion (org-end-of-item) (point)))
14649 clist)
14650 (and (org-at-item-checkbox-p)
14651 (push (org-point-in-group p 0 :checkbox) clist)))
14653 ((org-at-table-p)
14654 (push (list :table (org-table-begin) (org-table-end)) clist)
14655 (if (memq 'org-formula faces)
14656 (push (list :table-special
14657 (previous-single-property-change p 'face)
14658 (next-single-property-change p 'face)) clist)))
14659 ((org-at-table-p 'any)
14660 (push (list :table-table) clist)))
14661 (goto-char p)
14663 ;; Now the small context
14664 (cond
14665 ((org-at-timestamp-p)
14666 (push (org-point-in-group p 0 :timestamp) clist))
14667 ((memq 'org-link faces)
14668 (push (list :link
14669 (previous-single-property-change p 'face)
14670 (next-single-property-change p 'face)) clist))
14671 ((memq 'org-special-keyword faces)
14672 (push (list :keyword
14673 (previous-single-property-change p 'face)
14674 (next-single-property-change p 'face)) clist))
14675 ((org-on-target-p)
14676 (push (org-point-in-group p 0 :target) clist)
14677 (goto-char (1- (match-beginning 0)))
14678 (if (looking-at org-radio-target-regexp)
14679 (push (org-point-in-group p 0 :radio-target) clist))
14680 (goto-char p))
14681 ((setq o (car (delq nil
14682 (mapcar
14683 (lambda (x)
14684 (if (memq x org-latex-fragment-image-overlays) x))
14685 (org-overlays-at (point))))))
14686 (push (list :latex-fragment
14687 (org-overlay-start o) (org-overlay-end o)) clist)
14688 (push (list :latex-preview
14689 (org-overlay-start o) (org-overlay-end o)) clist))
14690 ((org-inside-LaTeX-fragment-p)
14691 ;; FIXME: positions wrong.
14692 (push (list :latex-fragment (point) (point)) clist)))
14694 (setq clist (nreverse (delq nil clist)))
14695 clist))
14697 ;; FIXME: Compare with at-regexp-p Do we need both?
14698 (defun org-in-regexp (re &optional nlines visually)
14699 "Check if point is inside a match of regexp.
14700 Normally only the current line is checked, but you can include NLINES extra
14701 lines both before and after point into the search.
14702 If VISUALLY is set, require that the cursor is not after the match but
14703 really on, so that the block visually is on the match."
14704 (catch 'exit
14705 (let ((pos (point))
14706 (eol (point-at-eol (+ 1 (or nlines 0))))
14707 (inc (if visually 1 0)))
14708 (save-excursion
14709 (beginning-of-line (- 1 (or nlines 0)))
14710 (while (re-search-forward re eol t)
14711 (if (and (<= (match-beginning 0) pos)
14712 (>= (+ inc (match-end 0)) pos))
14713 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14715 (defun org-at-regexp-p (regexp)
14716 "Is point inside a match of REGEXP in the current line?"
14717 (catch 'exit
14718 (save-excursion
14719 (let ((pos (point)) (end (point-at-eol)))
14720 (beginning-of-line 1)
14721 (while (re-search-forward regexp end t)
14722 (if (and (<= (match-beginning 0) pos)
14723 (>= (match-end 0) pos))
14724 (throw 'exit t)))
14725 nil))))
14727 (defun org-occur-in-agenda-files (regexp &optional nlines)
14728 "Call `multi-occur' with buffers for all agenda files."
14729 (interactive "sOrg-files matching: \np")
14730 (let* ((files (org-agenda-files))
14731 (tnames (mapcar 'file-truename files))
14732 (extra org-agenda-text-search-extra-files)
14734 (when (eq (car extra) 'agenda-archives)
14735 (setq extra (cdr extra))
14736 (setq files (org-add-archive-files files)))
14737 (while (setq f (pop extra))
14738 (unless (member (file-truename f) tnames)
14739 (add-to-list 'files f 'append)
14740 (add-to-list 'tnames (file-truename f) 'append)))
14741 (multi-occur
14742 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14743 regexp)))
14745 (if (boundp 'occur-mode-find-occurrence-hook)
14746 ;; Emacs 23
14747 (add-hook 'occur-mode-find-occurrence-hook
14748 (lambda ()
14749 (when (org-mode-p)
14750 (org-reveal))))
14751 ;; Emacs 22
14752 (defadvice occur-mode-goto-occurrence
14753 (after org-occur-reveal activate)
14754 (and (org-mode-p) (org-reveal)))
14755 (defadvice occur-mode-goto-occurrence-other-window
14756 (after org-occur-reveal activate)
14757 (and (org-mode-p) (org-reveal)))
14758 (defadvice occur-mode-display-occurrence
14759 (after org-occur-reveal activate)
14760 (when (org-mode-p)
14761 (let ((pos (occur-mode-find-occurrence)))
14762 (with-current-buffer (marker-buffer pos)
14763 (save-excursion
14764 (goto-char pos)
14765 (org-reveal)))))))
14767 (defun org-uniquify (list)
14768 "Remove duplicate elements from LIST."
14769 (let (res)
14770 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14771 res))
14773 (defun org-delete-all (elts list)
14774 "Remove all elements in ELTS from LIST."
14775 (while elts
14776 (setq list (delete (pop elts) list)))
14777 list)
14779 (defun org-back-over-empty-lines ()
14780 "Move backwards over whitespace, to the beginning of the first empty line.
14781 Returns the number of empty lines passed."
14782 (let ((pos (point)))
14783 (skip-chars-backward " \t\n\r")
14784 (beginning-of-line 2)
14785 (goto-char (min (point) pos))
14786 (count-lines (point) pos)))
14788 (defun org-skip-whitespace ()
14789 (skip-chars-forward " \t\n\r"))
14791 (defun org-point-in-group (point group &optional context)
14792 "Check if POINT is in match-group GROUP.
14793 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14794 match. If the match group does ot exist or point is not inside it,
14795 return nil."
14796 (and (match-beginning group)
14797 (>= point (match-beginning group))
14798 (<= point (match-end group))
14799 (if context
14800 (list context (match-beginning group) (match-end group))
14801 t)))
14803 (defun org-switch-to-buffer-other-window (&rest args)
14804 "Switch to buffer in a second window on the current frame.
14805 In particular, do not allow pop-up frames."
14806 (let (pop-up-frames special-display-buffer-names special-display-regexps
14807 special-display-function)
14808 (apply 'switch-to-buffer-other-window args)))
14810 (defun org-combine-plists (&rest plists)
14811 "Create a single property list from all plists in PLISTS.
14812 The process starts by copying the first list, and then setting properties
14813 from the other lists. Settings in the last list are the most significant
14814 ones and overrule settings in the other lists."
14815 (let ((rtn (copy-sequence (pop plists)))
14816 p v ls)
14817 (while plists
14818 (setq ls (pop plists))
14819 (while ls
14820 (setq p (pop ls) v (pop ls))
14821 (setq rtn (plist-put rtn p v))))
14822 rtn))
14824 (defun org-move-line-down (arg)
14825 "Move the current line down. With prefix argument, move it past ARG lines."
14826 (interactive "p")
14827 (let ((col (current-column))
14828 beg end pos)
14829 (beginning-of-line 1) (setq beg (point))
14830 (beginning-of-line 2) (setq end (point))
14831 (beginning-of-line (+ 1 arg))
14832 (setq pos (move-marker (make-marker) (point)))
14833 (insert (delete-and-extract-region beg end))
14834 (goto-char pos)
14835 (org-move-to-column col)))
14837 (defun org-move-line-up (arg)
14838 "Move the current line up. With prefix argument, move it past ARG lines."
14839 (interactive "p")
14840 (let ((col (current-column))
14841 beg end pos)
14842 (beginning-of-line 1) (setq beg (point))
14843 (beginning-of-line 2) (setq end (point))
14844 (beginning-of-line (- arg))
14845 (setq pos (move-marker (make-marker) (point)))
14846 (insert (delete-and-extract-region beg end))
14847 (goto-char pos)
14848 (org-move-to-column col)))
14850 (defun org-replace-escapes (string table)
14851 "Replace %-escapes in STRING with values in TABLE.
14852 TABLE is an association list with keys like \"%a\" and string values.
14853 The sequences in STRING may contain normal field width and padding information,
14854 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14855 so values can contain further %-escapes if they are define later in TABLE."
14856 (let ((case-fold-search nil)
14857 e re rpl)
14858 (while (setq e (pop table))
14859 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14860 (while (string-match re string)
14861 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14862 (cdr e)))
14863 (setq string (replace-match rpl t t string))))
14864 string))
14867 (defun org-sublist (list start end)
14868 "Return a section of LIST, from START to END.
14869 Counting starts at 1."
14870 (let (rtn (c start))
14871 (setq list (nthcdr (1- start) list))
14872 (while (and list (<= c end))
14873 (push (pop list) rtn)
14874 (setq c (1+ c)))
14875 (nreverse rtn)))
14877 (defun org-find-base-buffer-visiting (file)
14878 "Like `find-buffer-visiting' but alway return the base buffer and
14879 not an indirect buffer."
14880 (let ((buf (find-buffer-visiting file)))
14881 (if buf
14882 (or (buffer-base-buffer buf) buf)
14883 nil)))
14885 (defun org-image-file-name-regexp (&optional extensions)
14886 "Return regexp matching the file names of images.
14887 If EXTENSIONS is given, only match these."
14888 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14889 (image-file-name-regexp)
14890 (let ((image-file-name-extensions
14891 (or extensions
14892 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14893 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14894 (concat "\\."
14895 (regexp-opt (nconc (mapcar 'upcase
14896 image-file-name-extensions)
14897 image-file-name-extensions)
14899 "\\'"))))
14901 (defun org-file-image-p (file &optional extensions)
14902 "Return non-nil if FILE is an image."
14903 (save-match-data
14904 (string-match (org-image-file-name-regexp extensions) file)))
14906 (defun org-get-cursor-date ()
14907 "Return the date at cursor in as a time.
14908 This works in the calendar and in the agenda, anywhere else it just
14909 returns the current time."
14910 (let (date day defd)
14911 (cond
14912 ((eq major-mode 'calendar-mode)
14913 (setq date (calendar-cursor-to-date)
14914 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14915 ((eq major-mode 'org-agenda-mode)
14916 (setq day (get-text-property (point) 'day))
14917 (if day
14918 (setq date (calendar-gregorian-from-absolute day)
14919 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14920 (nth 2 date))))))
14921 (or defd (current-time))))
14923 (defvar org-agenda-action-marker (make-marker)
14924 "Marker pointing to the entry for the next agenda action.")
14926 (defun org-mark-entry-for-agenda-action ()
14927 "Mark the current entry as target of an agenda action.
14928 Agenda actions are actions executed from the agenda with the key `k',
14929 which make use of the date at the cursor."
14930 (interactive)
14931 (move-marker org-agenda-action-marker
14932 (save-excursion (org-back-to-heading t) (point))
14933 (current-buffer))
14934 (message
14935 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14937 ;;; Paragraph filling stuff.
14938 ;; We want this to be just right, so use the full arsenal.
14940 (defun org-indent-line-function ()
14941 "Indent line like previous, but further if previous was headline or item."
14942 (interactive)
14943 (let* ((pos (point))
14944 (itemp (org-at-item-p))
14945 (org-drawer-regexp (or org-drawer-regexp "\000"))
14946 column bpos bcol tpos tcol bullet btype bullet-type)
14947 ;; Find the previous relevant line
14948 (beginning-of-line 1)
14949 (cond
14950 ((looking-at "#") (setq column 0))
14951 ((looking-at "\\*+ ") (setq column 0))
14952 ((and (looking-at "[ \t]*:END:")
14953 (save-excursion (re-search-backward org-drawer-regexp nil t)))
14954 (save-excursion
14955 (goto-char (1- (match-beginning 1)))
14956 (setq column (current-column))))
14958 (beginning-of-line 0)
14959 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
14960 (not (looking-at "[ \t]*:END:"))
14961 (not (looking-at org-drawer-regexp)))
14962 (beginning-of-line 0))
14963 (cond
14964 ((looking-at "\\*+[ \t]+")
14965 (if (not org-adapt-indentation)
14966 (setq column 0)
14967 (goto-char (match-end 0))
14968 (setq column (current-column))))
14969 ((looking-at org-drawer-regexp)
14970 (goto-char (1- (match-beginning 1)))
14971 (setq column (current-column)))
14972 ((looking-at "\\([ \t]*\\):END:")
14973 (goto-char (match-end 1))
14974 (setq column (current-column)))
14975 ((org-in-item-p)
14976 (org-beginning-of-item)
14977 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14978 (setq bpos (match-beginning 1) tpos (match-end 0)
14979 bcol (progn (goto-char bpos) (current-column))
14980 tcol (progn (goto-char tpos) (current-column))
14981 bullet (match-string 1)
14982 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14983 (if (> tcol (+ bcol org-description-max-indent))
14984 (setq tcol (+ bcol 5)))
14985 (if (not itemp)
14986 (setq column tcol)
14987 (goto-char pos)
14988 (beginning-of-line 1)
14989 (if (looking-at "\\S-")
14990 (progn
14991 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14992 (setq bullet (match-string 1)
14993 btype (if (string-match "[0-9]" bullet) "n" bullet))
14994 (setq column (if (equal btype bullet-type) bcol tcol)))
14995 (setq column (org-get-indentation)))))
14996 (t (setq column (org-get-indentation))))))
14997 (goto-char pos)
14998 (if (<= (current-column) (current-indentation))
14999 (org-indent-line-to column)
15000 (save-excursion (org-indent-line-to column)))
15001 (setq column (current-column))
15002 (beginning-of-line 1)
15003 (if (looking-at
15004 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15005 (replace-match (concat "\\1" (format org-property-format
15006 (match-string 2) (match-string 3)))
15007 t nil))
15008 (org-move-to-column column)))
15010 (defun org-set-autofill-regexps ()
15011 (interactive)
15012 ;; In the paragraph separator we include headlines, because filling
15013 ;; text in a line directly attached to a headline would otherwise
15014 ;; fill the headline as well.
15015 (org-set-local 'comment-start-skip "^#+[ \t]*")
15016 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15017 ;; The paragraph starter includes hand-formatted lists.
15018 (org-set-local 'paragraph-start
15019 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15020 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15021 ;; But only if the user has not turned off tables or fixed-width regions
15022 (org-set-local
15023 'auto-fill-inhibit-regexp
15024 (concat "\\*+ \\|#\\+"
15025 "\\|[ \t]*" org-keyword-time-regexp
15026 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15027 (concat
15028 "\\|[ \t]*["
15029 (if org-enable-table-editor "|" "")
15030 (if org-enable-fixed-width-editor ":" "")
15031 "]"))))
15032 ;; We use our own fill-paragraph function, to make sure that tables
15033 ;; and fixed-width regions are not wrapped. That function will pass
15034 ;; through to `fill-paragraph' when appropriate.
15035 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15036 ; Adaptive filling: To get full control, first make sure that
15037 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15038 (org-set-local 'adaptive-fill-regexp "\000")
15039 (org-set-local 'adaptive-fill-function
15040 'org-adaptive-fill-function)
15041 (org-set-local
15042 'align-mode-rules-list
15043 '((org-in-buffer-settings
15044 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15045 (modes . '(org-mode))))))
15047 (defun org-fill-paragraph (&optional justify)
15048 "Re-align a table, pass through to fill-paragraph if no table."
15049 (let ((table-p (org-at-table-p))
15050 (table.el-p (org-at-table.el-p)))
15051 (cond ((and (equal (char-after (point-at-bol)) ?*)
15052 (save-excursion (goto-char (point-at-bol))
15053 (looking-at outline-regexp)))
15054 t) ; skip headlines
15055 (table.el-p t) ; skip table.el tables
15056 (table-p (org-table-align) t) ; align org-mode tables
15057 (t nil)))) ; call paragraph-fill
15059 ;; For reference, this is the default value of adaptive-fill-regexp
15060 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15062 (defun org-adaptive-fill-function ()
15063 "Return a fill prefix for org-mode files.
15064 In particular, this makes sure hanging paragraphs for hand-formatted lists
15065 work correctly."
15066 (cond ((looking-at "#[ \t]+")
15067 (match-string 0))
15068 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15069 (save-excursion
15070 (if (> (match-end 1) (+ (match-beginning 1)
15071 org-description-max-indent))
15072 (goto-char (+ (match-beginning 1) 5))
15073 (goto-char (match-end 0)))
15074 (make-string (current-column) ?\ )))
15075 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15076 (save-excursion
15077 (goto-char (match-end 0))
15078 (make-string (current-column) ?\ )))
15079 (t nil)))
15081 ;;; Other stuff.
15083 (defun org-toggle-fixed-width-section (arg)
15084 "Toggle the fixed-width export.
15085 If there is no active region, the QUOTE keyword at the current headline is
15086 inserted or removed. When present, it causes the text between this headline
15087 and the next to be exported as fixed-width text, and unmodified.
15088 If there is an active region, this command adds or removes a colon as the
15089 first character of this line. If the first character of a line is a colon,
15090 this line is also exported in fixed-width font."
15091 (interactive "P")
15092 (let* ((cc 0)
15093 (regionp (org-region-active-p))
15094 (beg (if regionp (region-beginning) (point)))
15095 (end (if regionp (region-end)))
15096 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15097 (case-fold-search nil)
15098 (re "[ \t]*\\(:\\)")
15099 off)
15100 (if regionp
15101 (save-excursion
15102 (goto-char beg)
15103 (setq cc (current-column))
15104 (beginning-of-line 1)
15105 (setq off (looking-at re))
15106 (while (> nlines 0)
15107 (setq nlines (1- nlines))
15108 (beginning-of-line 1)
15109 (cond
15110 (arg
15111 (org-move-to-column cc t)
15112 (insert ":\n")
15113 (forward-line -1))
15114 ((and off (looking-at re))
15115 (replace-match "" t t nil 1))
15116 ((not off) (org-move-to-column cc t) (insert ":")))
15117 (forward-line 1)))
15118 (save-excursion
15119 (org-back-to-heading)
15120 (if (looking-at (concat outline-regexp
15121 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15122 (replace-match "" t t nil 1)
15123 (if (looking-at outline-regexp)
15124 (progn
15125 (goto-char (match-end 0))
15126 (insert org-quote-string " "))))))))
15128 ;;;; Functions extending outline functionality
15130 (defun org-beginning-of-line (&optional arg)
15131 "Go to the beginning of the current line. If that is invisible, continue
15132 to a visible line beginning. This makes the function of C-a more intuitive.
15133 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15134 first attempt, and only move to after the tags when the cursor is already
15135 beyond the end of the headline."
15136 (interactive "P")
15137 (let ((pos (point))
15138 (special (if (consp org-special-ctrl-a/e)
15139 (car org-special-ctrl-a/e)
15140 org-special-ctrl-a/e))
15141 refpos)
15142 (beginning-of-line 1)
15143 (if (and arg (fboundp 'move-beginning-of-line))
15144 (call-interactively 'move-beginning-of-line)
15145 (if (bobp)
15147 (backward-char 1)
15148 (if (org-invisible-p)
15149 (while (and (not (bobp)) (org-invisible-p))
15150 (backward-char 1)
15151 (beginning-of-line 1))
15152 (forward-char 1))))
15153 (when special
15154 (cond
15155 ((and (looking-at org-complex-heading-regexp)
15156 (= (char-after (match-end 1)) ?\ ))
15157 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15158 (point-at-eol)))
15159 (goto-char
15160 (if (eq special t)
15161 (cond ((> pos refpos) refpos)
15162 ((= pos (point)) refpos)
15163 (t (point)))
15164 (cond ((> pos (point)) (point))
15165 ((not (eq last-command this-command)) (point))
15166 (t refpos)))))
15167 ((org-at-item-p)
15168 (goto-char
15169 (if (eq special t)
15170 (cond ((> pos (match-end 4)) (match-end 4))
15171 ((= pos (point)) (match-end 4))
15172 (t (point)))
15173 (cond ((> pos (point)) (point))
15174 ((not (eq last-command this-command)) (point))
15175 (t (match-end 4))))))))
15176 (org-no-warnings
15177 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15179 (defun org-end-of-line (&optional arg)
15180 "Go to the end of the line.
15181 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15182 first attempt, and only move to after the tags when the cursor is already
15183 beyond the end of the headline."
15184 (interactive "P")
15185 (let ((special (if (consp org-special-ctrl-a/e)
15186 (cdr org-special-ctrl-a/e)
15187 org-special-ctrl-a/e)))
15188 (if (or (not special)
15189 (not (org-on-heading-p))
15190 arg)
15191 (call-interactively (if (fboundp 'move-end-of-line)
15192 'move-end-of-line
15193 'end-of-line))
15194 (let ((pos (point)))
15195 (beginning-of-line 1)
15196 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15197 (if (eq special t)
15198 (if (or (< pos (match-beginning 1))
15199 (= pos (match-end 0)))
15200 (goto-char (match-beginning 1))
15201 (goto-char (match-end 0)))
15202 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15203 (goto-char (match-end 0))
15204 (goto-char (match-beginning 1))))
15205 (call-interactively (if (fboundp 'move-end-of-line)
15206 'move-end-of-line
15207 'end-of-line)))))
15208 (org-no-warnings
15209 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15211 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15212 (define-key org-mode-map "\C-e" 'org-end-of-line)
15214 (defun org-kill-line (&optional arg)
15215 "Kill line, to tags or end of line."
15216 (interactive "P")
15217 (cond
15218 ((or (not org-special-ctrl-k)
15219 (bolp)
15220 (not (org-on-heading-p)))
15221 (call-interactively 'kill-line))
15222 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15223 (kill-region (point) (match-beginning 1))
15224 (org-set-tags nil t))
15225 (t (kill-region (point) (point-at-eol)))))
15227 (define-key org-mode-map "\C-k" 'org-kill-line)
15229 (defun org-yank (&optional arg)
15230 "Yank. If the kill is a subtree, treat it specially.
15231 This command will look at the current kill and check if is a single
15232 subtree, or a series of subtrees[1]. If it passes the test, and if the
15233 cursor is at the beginning of a line or after the stars of a currently
15234 empty headline, then the yank is handled specially. How exactly depends
15235 on the value of the following variables, both set by default.
15237 org-yank-folded-subtrees
15238 When set, the subtree(s) will be folded after insertion, but only
15239 if doing so would now swallow text after the yanked text.
15241 org-yank-adjusted-subtrees
15242 When set, the subtree will be promoted or demoted in order to
15243 fit into the local outline tree structure, which means that the level
15244 will be adjusted so that it becomes the smaller one of the two
15245 *visible* surrounding headings.
15247 Any prefix to this command will cause `yank' to be called directly with
15248 no special treatment. In particular, a simple `C-u' prefix will just
15249 plainly yank the text as it is.
15251 \[1] Basically, the test checks if the first non-white line is a heading
15252 and if there are no other headings with fewer stars."
15253 (interactive "P")
15254 (setq this-command 'yank)
15255 (if arg
15256 (call-interactively 'yank)
15257 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15258 (and (org-kill-is-subtree-p)
15259 (or (bolp)
15260 (and (looking-at "[ \t]*$")
15261 (string-match
15262 "\\`\\*+\\'"
15263 (buffer-substring (point-at-bol) (point)))))))
15264 swallowp)
15265 (cond
15266 ((and subtreep org-yank-folded-subtrees)
15267 (let ((beg (point))
15268 end)
15269 (if (and subtreep org-yank-adjusted-subtrees)
15270 (org-paste-subtree nil nil 'for-yank)
15271 (call-interactively 'yank))
15272 (setq end (point))
15273 (goto-char beg)
15274 (when (and (bolp) subtreep
15275 (not (setq swallowp
15276 (org-yank-folding-would-swallow-text beg end))))
15277 (or (looking-at outline-regexp)
15278 (re-search-forward (concat "^" outline-regexp) end t))
15279 (while (and (< (point) end) (looking-at outline-regexp))
15280 (hide-subtree)
15281 (org-cycle-show-empty-lines 'folded)
15282 (condition-case nil
15283 (outline-forward-same-level 1)
15284 (error (goto-char end)))))
15285 (when swallowp
15286 (message
15287 "Yanked text not folded because that would swallow text"))
15288 (goto-char end)
15289 (skip-chars-forward " \t\n\r")
15290 (beginning-of-line 1)
15291 (push-mark beg 'nomsg)))
15292 ((and subtreep org-yank-adjusted-subtrees)
15293 (let ((beg (point-at-bol)))
15294 (org-paste-subtree nil nil 'for-yank)
15295 (push-mark beg 'nomsg)))
15297 (call-interactively 'yank))))))
15299 (defun org-yank-folding-would-swallow-text (beg end)
15300 "Would hide-subtree at BEG swallow any text after END?"
15301 (let (level)
15302 (save-excursion
15303 (goto-char beg)
15304 (when (or (looking-at outline-regexp)
15305 (re-search-forward (concat "^" outline-regexp) end t))
15306 (setq level (org-outline-level)))
15307 (goto-char end)
15308 (skip-chars-forward " \t\r\n\v\f")
15309 (if (or (eobp)
15310 (and (bolp) (looking-at org-outline-regexp)
15311 (<= (org-outline-level) level)))
15312 nil ; Nothing would be swallowed
15313 t)))) ; something would swallow
15315 (define-key org-mode-map "\C-y" 'org-yank)
15317 (defun org-invisible-p ()
15318 "Check if point is at a character currently not visible."
15319 ;; Early versions of noutline don't have `outline-invisible-p'.
15320 (if (fboundp 'outline-invisible-p)
15321 (outline-invisible-p)
15322 (get-char-property (point) 'invisible)))
15324 (defun org-invisible-p2 ()
15325 "Check if point is at a character currently not visible."
15326 (save-excursion
15327 (if (and (eolp) (not (bobp))) (backward-char 1))
15328 ;; Early versions of noutline don't have `outline-invisible-p'.
15329 (if (fboundp 'outline-invisible-p)
15330 (outline-invisible-p)
15331 (get-char-property (point) 'invisible))))
15333 (defun org-back-to-heading (&optional invisible-ok)
15334 "Call `outline-back-to-heading', but provide a better error message."
15335 (condition-case nil
15336 (outline-back-to-heading invisible-ok)
15337 (error (error "Before first headline at position %d in buffer %s"
15338 (point) (current-buffer)))))
15340 (defun org-before-first-heading-p ()
15341 "Before first heading?"
15342 (save-excursion
15343 (null (re-search-backward "^\\*+ " nil t))))
15345 (defalias 'org-on-heading-p 'outline-on-heading-p)
15346 (defalias 'org-at-heading-p 'outline-on-heading-p)
15347 (defun org-at-heading-or-item-p ()
15348 (or (org-on-heading-p) (org-at-item-p)))
15350 (defun org-on-target-p ()
15351 (or (org-in-regexp org-radio-target-regexp)
15352 (org-in-regexp org-target-regexp)))
15354 (defun org-up-heading-all (arg)
15355 "Move to the heading line of which the present line is a subheading.
15356 This function considers both visible and invisible heading lines.
15357 With argument, move up ARG levels."
15358 (if (fboundp 'outline-up-heading-all)
15359 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15360 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15362 (defun org-up-heading-safe ()
15363 "Move to the heading line of which the present line is a subheading.
15364 This version will not throw an error. It will return the level of the
15365 headline found, or nil if no higher level is found."
15366 (let (start-level re)
15367 (org-back-to-heading t)
15368 (setq start-level (funcall outline-level))
15369 (if (equal start-level 1)
15371 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15372 (if (re-search-backward re nil t)
15373 (funcall outline-level)))))
15375 (defun org-first-sibling-p ()
15376 "Is this heading the first child of its parents?"
15377 (interactive)
15378 (let ((re (concat "^" outline-regexp))
15379 level l)
15380 (unless (org-at-heading-p t)
15381 (error "Not at a heading"))
15382 (setq level (funcall outline-level))
15383 (save-excursion
15384 (if (not (re-search-backward re nil t))
15386 (setq l (funcall outline-level))
15387 (< l level)))))
15389 (defun org-goto-sibling (&optional previous)
15390 "Goto the next sibling, even if it is invisible.
15391 When PREVIOUS is set, go to the previous sibling instead. Returns t
15392 when a sibling was found. When none is found, return nil and don't
15393 move point."
15394 (let ((fun (if previous 're-search-backward 're-search-forward))
15395 (pos (point))
15396 (re (concat "^" outline-regexp))
15397 level l)
15398 (when (condition-case nil (org-back-to-heading t) (error nil))
15399 (setq level (funcall outline-level))
15400 (catch 'exit
15401 (or previous (forward-char 1))
15402 (while (funcall fun re nil t)
15403 (setq l (funcall outline-level))
15404 (when (< l level) (goto-char pos) (throw 'exit nil))
15405 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15406 (goto-char pos)
15407 nil))))
15409 (defun org-show-siblings ()
15410 "Show all siblings of the current headline."
15411 (save-excursion
15412 (while (org-goto-sibling) (org-flag-heading nil)))
15413 (save-excursion
15414 (while (org-goto-sibling 'previous)
15415 (org-flag-heading nil))))
15417 (defun org-show-hidden-entry ()
15418 "Show an entry where even the heading is hidden."
15419 (save-excursion
15420 (org-show-entry)))
15422 (defun org-flag-heading (flag &optional entry)
15423 "Flag the current heading. FLAG non-nil means make invisible.
15424 When ENTRY is non-nil, show the entire entry."
15425 (save-excursion
15426 (org-back-to-heading t)
15427 ;; Check if we should show the entire entry
15428 (if entry
15429 (progn
15430 (org-show-entry)
15431 (save-excursion
15432 (and (outline-next-heading)
15433 (org-flag-heading nil))))
15434 (outline-flag-region (max (point-min) (1- (point)))
15435 (save-excursion (outline-end-of-heading) (point))
15436 flag))))
15438 (defun org-forward-same-level (arg)
15439 "Move forward to the ARG'th subheading at same level as this one.
15440 Stop at the first and last subheadings of a superior heading.
15441 This is like outline-forward-same-level, but invisible headings are ok."
15442 (interactive "p")
15443 (org-back-to-heading t)
15444 (while (> arg 0)
15445 (let ((point-to-move-to (save-excursion
15446 (org-get-next-sibling))))
15447 (if point-to-move-to
15448 (progn
15449 (goto-char point-to-move-to)
15450 (setq arg (1- arg)))
15451 (progn
15452 (setq arg 0)
15453 (error "No following same-level heading"))))))
15455 (defun org-get-next-sibling ()
15456 "Move to next heading of the same level, and return point.
15457 If there is no such heading, return nil.
15458 This is like outline-next-sibling, but invisible headings are ok."
15459 (let ((level (funcall outline-level)))
15460 (outline-next-heading)
15461 (while (and (not (eobp)) (> (funcall outline-level) level))
15462 (outline-next-heading))
15463 (if (or (eobp) (< (funcall outline-level) level))
15465 (point))))
15467 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15468 ;; This is an exact copy of the original function, but it uses
15469 ;; `org-back-to-heading', to make it work also in invisible
15470 ;; trees. And is uses an invisible-OK argument.
15471 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15472 (org-back-to-heading invisible-OK)
15473 (let ((first t)
15474 (level (funcall outline-level)))
15475 (while (and (not (eobp))
15476 (or first (> (funcall outline-level) level)))
15477 (setq first nil)
15478 (outline-next-heading))
15479 (unless to-heading
15480 (if (memq (preceding-char) '(?\n ?\^M))
15481 (progn
15482 ;; Go to end of line before heading
15483 (forward-char -1)
15484 (if (memq (preceding-char) '(?\n ?\^M))
15485 ;; leave blank line before heading
15486 (forward-char -1))))))
15487 (point))
15489 (defun org-show-subtree ()
15490 "Show everything after this heading at deeper levels."
15491 (outline-flag-region
15492 (point)
15493 (save-excursion
15494 (outline-end-of-subtree) (outline-next-heading) (point))
15495 nil))
15497 (defun org-show-entry ()
15498 "Show the body directly following this heading.
15499 Show the heading too, if it is currently invisible."
15500 (interactive)
15501 (save-excursion
15502 (condition-case nil
15503 (progn
15504 (org-back-to-heading t)
15505 (outline-flag-region
15506 (max (point-min) (1- (point)))
15507 (save-excursion
15508 (if (re-search-forward
15509 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15510 (match-beginning 1)
15511 (point-max)))
15512 nil))
15513 (error nil))))
15515 (defun org-make-options-regexp (kwds &optional extra)
15516 "Make a regular expression for keyword lines."
15517 (concat
15519 "#?[ \t]*\\+\\("
15520 (mapconcat 'regexp-quote kwds "\\|")
15521 (if extra (concat "\\|" extra))
15522 "\\):[ \t]*"
15523 "\\(.+\\)"))
15525 ;; Make isearch reveal the necessary context
15526 (defun org-isearch-end ()
15527 "Reveal context after isearch exits."
15528 (when isearch-success ; only if search was successful
15529 (if (featurep 'xemacs)
15530 ;; Under XEmacs, the hook is run in the correct place,
15531 ;; we directly show the context.
15532 (org-show-context 'isearch)
15533 ;; In Emacs the hook runs *before* restoring the overlays.
15534 ;; So we have to use a one-time post-command-hook to do this.
15535 ;; (Emacs 22 has a special variable, see function `org-mode')
15536 (unless (and (boundp 'isearch-mode-end-hook-quit)
15537 isearch-mode-end-hook-quit)
15538 ;; Only when the isearch was not quitted.
15539 (org-add-hook 'post-command-hook 'org-isearch-post-command
15540 'append 'local)))))
15542 (defun org-isearch-post-command ()
15543 "Remove self from hook, and show context."
15544 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15545 (org-show-context 'isearch))
15548 ;;;; Integration with and fixes for other packages
15550 ;;; Imenu support
15552 (defvar org-imenu-markers nil
15553 "All markers currently used by Imenu.")
15554 (make-variable-buffer-local 'org-imenu-markers)
15556 (defun org-imenu-new-marker (&optional pos)
15557 "Return a new marker for use by Imenu, and remember the marker."
15558 (let ((m (make-marker)))
15559 (move-marker m (or pos (point)))
15560 (push m org-imenu-markers)
15563 (defun org-imenu-get-tree ()
15564 "Produce the index for Imenu."
15565 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15566 (setq org-imenu-markers nil)
15567 (let* ((n org-imenu-depth)
15568 (re (concat "^" outline-regexp))
15569 (subs (make-vector (1+ n) nil))
15570 (last-level 0)
15571 m level head)
15572 (save-excursion
15573 (save-restriction
15574 (widen)
15575 (goto-char (point-max))
15576 (while (re-search-backward re nil t)
15577 (setq level (org-reduced-level (funcall outline-level)))
15578 (when (<= level n)
15579 (looking-at org-complex-heading-regexp)
15580 (setq head (org-link-display-format
15581 (org-match-string-no-properties 4))
15582 m (org-imenu-new-marker))
15583 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15584 (if (>= level last-level)
15585 (push (cons head m) (aref subs level))
15586 (push (cons head (aref subs (1+ level))) (aref subs level))
15587 (loop for i from (1+ level) to n do (aset subs i nil)))
15588 (setq last-level level)))))
15589 (aref subs 1)))
15591 (eval-after-load "imenu"
15592 '(progn
15593 (add-hook 'imenu-after-jump-hook
15594 (lambda ()
15595 (if (eq major-mode 'org-mode)
15596 (org-show-context 'org-goto))))))
15598 (defun org-link-display-format (link)
15599 "Replace a link with either the description, or the link target
15600 if no description is present"
15601 (save-match-data
15602 (if (string-match org-bracket-link-analytic-regexp link)
15603 (replace-match (or (match-string 5 link)
15604 (concat (match-string 1 link)
15605 (match-string 3 link)))
15606 nil nil link)
15607 link)))
15609 ;; Speedbar support
15611 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15612 "Overlay marking the agenda restriction line in speedbar.")
15613 (org-overlay-put org-speedbar-restriction-lock-overlay
15614 'face 'org-agenda-restriction-lock)
15615 (org-overlay-put org-speedbar-restriction-lock-overlay
15616 'help-echo "Agendas are currently limited to this item.")
15617 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15619 (defun org-speedbar-set-agenda-restriction ()
15620 "Restrict future agenda commands to the location at point in speedbar.
15621 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15622 (interactive)
15623 (require 'org-agenda)
15624 (let (p m tp np dir txt)
15625 (cond
15626 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15627 'org-imenu t))
15628 (setq m (get-text-property p 'org-imenu-marker))
15629 (save-excursion
15630 (save-restriction
15631 (set-buffer (marker-buffer m))
15632 (goto-char m)
15633 (org-agenda-set-restriction-lock 'subtree))))
15634 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15635 'speedbar-function 'speedbar-find-file))
15636 (setq tp (previous-single-property-change
15637 (1+ p) 'speedbar-function)
15638 np (next-single-property-change
15639 tp 'speedbar-function)
15640 dir (speedbar-line-directory)
15641 txt (buffer-substring-no-properties (or tp (point-min))
15642 (or np (point-max))))
15643 (save-excursion
15644 (save-restriction
15645 (set-buffer (find-file-noselect
15646 (let ((default-directory dir))
15647 (expand-file-name txt))))
15648 (unless (org-mode-p)
15649 (error "Cannot restrict to non-Org-mode file"))
15650 (org-agenda-set-restriction-lock 'file))))
15651 (t (error "Don't know how to restrict Org-mode's agenda")))
15652 (org-move-overlay org-speedbar-restriction-lock-overlay
15653 (point-at-bol) (point-at-eol))
15654 (setq current-prefix-arg nil)
15655 (org-agenda-maybe-redo)))
15657 (eval-after-load "speedbar"
15658 '(progn
15659 (speedbar-add-supported-extension ".org")
15660 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15661 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15662 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15663 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15664 (add-hook 'speedbar-visiting-tag-hook
15665 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15668 ;;; Fixes and Hacks for problems with other packages
15670 ;; Make flyspell not check words in links, to not mess up our keymap
15671 (defun org-mode-flyspell-verify ()
15672 "Don't let flyspell put overlays at active buttons."
15673 (not (get-text-property (point) 'keymap)))
15675 ;; Make `bookmark-jump' show the jump location if it was hidden.
15676 (eval-after-load "bookmark"
15677 '(if (boundp 'bookmark-after-jump-hook)
15678 ;; We can use the hook
15679 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15680 ;; Hook not available, use advice
15681 (defadvice bookmark-jump (after org-make-visible activate)
15682 "Make the position visible."
15683 (org-bookmark-jump-unhide))))
15685 ;; Make sure saveplace show the location if it was hidden
15686 (eval-after-load "saveplace"
15687 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15688 "Make the position visible."
15689 (org-bookmark-jump-unhide)))
15691 (defun org-bookmark-jump-unhide ()
15692 "Unhide the current position, to show the bookmark location."
15693 (and (org-mode-p)
15694 (or (org-invisible-p)
15695 (save-excursion (goto-char (max (point-min) (1- (point))))
15696 (org-invisible-p)))
15697 (org-show-context 'bookmark-jump)))
15699 ;; Make session.el ignore our circular variable
15700 (eval-after-load "session"
15701 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15703 ;;;; Experimental code
15705 (defun org-closed-in-range ()
15706 "Sparse tree of items closed in a certain time range.
15707 Still experimental, may disappear in the future."
15708 (interactive)
15709 ;; Get the time interval from the user.
15710 (let* ((time1 (time-to-seconds
15711 (org-read-date nil 'to-time nil "Starting date: ")))
15712 (time2 (time-to-seconds
15713 (org-read-date nil 'to-time nil "End date:")))
15714 ;; callback function
15715 (callback (lambda ()
15716 (let ((time
15717 (time-to-seconds
15718 (apply 'encode-time
15719 (org-parse-time-string
15720 (match-string 1))))))
15721 ;; check if time in interval
15722 (and (>= time time1) (<= time time2))))))
15723 ;; make tree, check each match with the callback
15724 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15727 ;;;; Finish up
15729 (provide 'org)
15731 (run-hooks 'org-load-hook)
15733 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15735 ;;; org.el ends here