Version number change to 6.03pre01.
[org-mode.git] / lisp / org.el
blob327f1fa911c0ee3f3ecf281b6f4887b7cf76a747
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 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.03pre01
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
90 ;;;; Customization variables
92 ;;; Version
94 (defconst org-version "6.03pre01"
95 "The version number of the file org.el.")
97 (defun org-version (&optional here)
98 "Show the org-mode version in the echo area.
99 With prefix arg HERE, insert it at point."
100 (interactive "P")
101 (let ((version (format "Org-mode version %s" org-version)))
102 (message version)
103 (if here
104 (insert version))))
106 ;;; Compatibility constants
108 ;;; The custom variables
110 (defgroup org nil
111 "Outline-based notes management and organizer."
112 :tag "Org"
113 :group 'outlines
114 :group 'hypermedia
115 :group 'calendar)
117 (defcustom org-load-hook nil
118 "Hook that is run after org.el has been loaded."
119 :group 'org
120 :type 'hook)
122 (defvar org-modules) ; defined below
123 (defvar org-modules-loaded nil
124 "Have the modules been loaded already?")
126 (defun org-load-modules-maybe (&optional force)
127 "Load all extensions listed in `org-default-extensions'."
128 (when (or force (not org-modules-loaded))
129 (mapc (lambda (ext)
130 (condition-case nil (require ext)
131 (error (message "Problems while trying to load feature `%s'" ext))))
132 org-modules)
133 (setq org-modules-loaded t)))
135 (defun org-set-modules (var value)
136 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
137 (set var value)
138 (when (featurep 'org)
139 (org-load-modules-maybe 'force)))
141 (when (org-bound-and-true-p org-modules)
142 (let ((a (member 'org-infojs org-modules)))
143 (and a (setcar a 'org-jsinfo))))
145 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
146 "Modules that should always be loaded together with org.el.
147 If a description starts with <C>, the file is not part of emacs
148 and loading it will require that you have downloaded and properly installed
149 the org-mode distribution.
151 You can also use this system to load external packages (i.e. neither Org
152 core modules, not modules from the CONTRIB directory). Just add symbols
153 to the end of the list. If the package is called org-xyz.e, then you need
154 to add the symbol `xyz', and the package must have a call to
156 (provide 'org-xyz)"
157 :group 'org
158 :set 'org-set-modules
159 :type
160 '(set :greedy t
161 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
162 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
163 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
164 (const :tag " info: Links to Info nodes" org-info)
165 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
166 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
167 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
168 (const :tag " mew Links to Mew folders/messages" org-mew)
169 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
170 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
171 (const :tag " vm: Links to VM folders/messages" org-vm)
172 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
173 (const :tag " mouse: Additional mouse support" org-mouse)
175 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
176 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
177 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
178 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
179 (const :tag "C eval: Include command output as text" org-eval)
180 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
181 (const :tag "C id: Global id's for identifying entries" org-id)
182 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
183 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
184 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
185 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
186 (const :tag "C registry: A registry for Org links" org-registry)
187 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
188 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
189 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
190 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
191 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
194 (defgroup org-startup nil
195 "Options concerning startup of Org-mode."
196 :tag "Org Startup"
197 :group 'org)
199 (defcustom org-startup-folded t
200 "Non-nil means, entering Org-mode will switch to OVERVIEW.
201 This can also be configured on a per-file basis by adding one of
202 the following lines anywhere in the buffer:
204 #+STARTUP: fold
205 #+STARTUP: nofold
206 #+STARTUP: content"
207 :group 'org-startup
208 :type '(choice
209 (const :tag "nofold: show all" nil)
210 (const :tag "fold: overview" t)
211 (const :tag "content: all headlines" content)))
213 (defcustom org-startup-truncated t
214 "Non-nil means, entering Org-mode will set `truncate-lines'.
215 This is useful since some lines containing links can be very long and
216 uninteresting. Also tables look terrible when wrapped."
217 :group 'org-startup
218 :type 'boolean)
220 (defcustom org-startup-align-all-tables nil
221 "Non-nil means, align all tables when visiting a file.
222 This is useful when the column width in tables is forced with <N> cookies
223 in table fields. Such tables will look correct only after the first re-align.
224 This can also be configured on a per-file basis by adding one of
225 the following lines anywhere in the buffer:
226 #+STARTUP: align
227 #+STARTUP: noalign"
228 :group 'org-startup
229 :type 'boolean)
231 (defcustom org-insert-mode-line-in-empty-file nil
232 "Non-nil means insert the first line setting Org-mode in empty files.
233 When the function `org-mode' is called interactively in an empty file, this
234 normally means that the file name does not automatically trigger Org-mode.
235 To ensure that the file will always be in Org-mode in the future, a
236 line enforcing Org-mode will be inserted into the buffer, if this option
237 has been set."
238 :group 'org-startup
239 :type 'boolean)
241 (defcustom org-replace-disputed-keys nil
242 "Non-nil means use alternative key bindings for some keys.
243 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
244 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
245 If you want to use Org-mode together with one of these other modes,
246 or more generally if you would like to move some Org-mode commands to
247 other keys, set this variable and configure the keys with the variable
248 `org-disputed-keys'.
250 This option is only relevant at load-time of Org-mode, and must be set
251 *before* org.el is loaded. Changing it requires a restart of Emacs to
252 become effective."
253 :group 'org-startup
254 :type 'boolean)
256 (if (fboundp 'defvaralias)
257 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
259 (defcustom org-disputed-keys
260 '(([(shift up)] . [(meta p)])
261 ([(shift down)] . [(meta n)])
262 ([(shift left)] . [(meta -)])
263 ([(shift right)] . [(meta +)])
264 ([(control shift right)] . [(meta shift +)])
265 ([(control shift left)] . [(meta shift -)]))
266 "Keys for which Org-mode and other modes compete.
267 This is an alist, cars are the default keys, second element specifies
268 the alternative to use when `org-replace-disputed-keys' is t.
270 Keys can be specified in any syntax supported by `define-key'.
271 The value of this option takes effect only at Org-mode's startup,
272 therefore you'll have to restart Emacs to apply it after changing."
273 :group 'org-startup
274 :type 'alist)
276 (defun org-key (key)
277 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
278 Or return the original if not disputed."
279 (if org-replace-disputed-keys
280 (let* ((nkey (key-description key))
281 (x (org-find-if (lambda (x)
282 (equal (key-description (car x)) nkey))
283 org-disputed-keys)))
284 (if x (cdr x) key))
285 key))
287 (defun org-find-if (predicate seq)
288 (catch 'exit
289 (while seq
290 (if (funcall predicate (car seq))
291 (throw 'exit (car seq))
292 (pop seq)))))
294 (defun org-defkey (keymap key def)
295 "Define a key, possibly translated, as returned by `org-key'."
296 (define-key keymap (org-key key) def))
298 (defcustom org-ellipsis nil
299 "The ellipsis to use in the Org-mode outline.
300 When nil, just use the standard three dots. When a string, use that instead,
301 When a face, use the standart 3 dots, but with the specified face.
302 The change affects only Org-mode (which will then use its own display table).
303 Changing this requires executing `M-x org-mode' in a buffer to become
304 effective."
305 :group 'org-startup
306 :type '(choice (const :tag "Default" nil)
307 (face :tag "Face" :value org-warning)
308 (string :tag "String" :value "...#")))
310 (defvar org-display-table nil
311 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
313 (defgroup org-keywords nil
314 "Keywords in Org-mode."
315 :tag "Org Keywords"
316 :group 'org)
318 (defcustom org-deadline-string "DEADLINE:"
319 "String to mark deadline entries.
320 A deadline is this string, followed by a time stamp. Should be a word,
321 terminated by a colon. You can insert a schedule keyword and
322 a timestamp with \\[org-deadline].
323 Changes become only effective after restarting Emacs."
324 :group 'org-keywords
325 :type 'string)
327 (defcustom org-scheduled-string "SCHEDULED:"
328 "String to mark scheduled TODO entries.
329 A schedule is this string, followed by a time stamp. Should be a word,
330 terminated by a colon. You can insert a schedule keyword and
331 a timestamp with \\[org-schedule].
332 Changes become only effective after restarting Emacs."
333 :group 'org-keywords
334 :type 'string)
336 (defcustom org-closed-string "CLOSED:"
337 "String used as the prefix for timestamps logging closing a TODO entry."
338 :group 'org-keywords
339 :type 'string)
341 (defcustom org-clock-string "CLOCK:"
342 "String used as prefix for timestamps clocking work hours on an item."
343 :group 'org-keywords
344 :type 'string)
346 (defcustom org-comment-string "COMMENT"
347 "Entries starting with this keyword will never be exported.
348 An entry can be toggled between COMMENT and normal with
349 \\[org-toggle-comment].
350 Changes become only effective after restarting Emacs."
351 :group 'org-keywords
352 :type 'string)
354 (defcustom org-quote-string "QUOTE"
355 "Entries starting with this keyword will be exported in fixed-width font.
356 Quoting applies only to the text in the entry following the headline, and does
357 not extend beyond the next headline, even if that is lower level.
358 An entry can be toggled between QUOTE and normal with
359 \\[org-toggle-fixed-width-section]."
360 :group 'org-keywords
361 :type 'string)
363 (defconst org-repeat-re
364 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
365 "Regular expression for specifying repeated events.
366 After a match, group 1 contains the repeat expression.")
368 (defgroup org-structure nil
369 "Options concerning the general structure of Org-mode files."
370 :tag "Org Structure"
371 :group 'org)
373 (defgroup org-reveal-location nil
374 "Options about how to make context of a location visible."
375 :tag "Org Reveal Location"
376 :group 'org-structure)
378 (defconst org-context-choice
379 '(choice
380 (const :tag "Always" t)
381 (const :tag "Never" nil)
382 (repeat :greedy t :tag "Individual contexts"
383 (cons
384 (choice :tag "Context"
385 (const agenda)
386 (const org-goto)
387 (const occur-tree)
388 (const tags-tree)
389 (const link-search)
390 (const mark-goto)
391 (const bookmark-jump)
392 (const isearch)
393 (const default))
394 (boolean))))
395 "Contexts for the reveal options.")
397 (defcustom org-show-hierarchy-above '((default . t))
398 "Non-nil means, show full hierarchy when revealing a location.
399 Org-mode often shows locations in an org-mode file which might have
400 been invisible before. When this is set, the hierarchy of headings
401 above the exposed location is shown.
402 Turning this off for example for sparse trees makes them very compact.
403 Instead of t, this can also be an alist specifying this option for different
404 contexts. Valid contexts are
405 agenda when exposing an entry from the agenda
406 org-goto when using the command `org-goto' on key C-c C-j
407 occur-tree when using the command `org-occur' on key C-c /
408 tags-tree when constructing a sparse tree based on tags matches
409 link-search when exposing search matches associated with a link
410 mark-goto when exposing the jump goal of a mark
411 bookmark-jump when exposing a bookmark location
412 isearch when exiting from an incremental search
413 default default for all contexts not set explicitly"
414 :group 'org-reveal-location
415 :type org-context-choice)
417 (defcustom org-show-following-heading '((default . nil))
418 "Non-nil means, show following heading when revealing a location.
419 Org-mode often shows locations in an org-mode file which might have
420 been invisible before. When this is set, the heading following the
421 match is shown.
422 Turning this off for example for sparse trees makes them very compact,
423 but makes it harder to edit the location of the match. In such a case,
424 use the command \\[org-reveal] to show more context.
425 Instead of t, this can also be an alist specifying this option for different
426 contexts. See `org-show-hierarchy-above' for valid contexts."
427 :group 'org-reveal-location
428 :type org-context-choice)
430 (defcustom org-show-siblings '((default . nil) (isearch t))
431 "Non-nil means, show all sibling heading when revealing a location.
432 Org-mode often shows locations in an org-mode file which might have
433 been invisible before. When this is set, the sibling of the current entry
434 heading are all made visible. If `org-show-hierarchy-above' is t,
435 the same happens on each level of the hierarchy above the current entry.
437 By default this is on for the isearch context, off for all other contexts.
438 Turning this off for example for sparse trees makes them very compact,
439 but makes it harder to edit the location of the match. In such a case,
440 use the command \\[org-reveal] to show more context.
441 Instead of t, this can also be an alist specifying this option for different
442 contexts. See `org-show-hierarchy-above' for valid contexts."
443 :group 'org-reveal-location
444 :type org-context-choice)
446 (defcustom org-show-entry-below '((default . nil))
447 "Non-nil means, show the entry below a headline when revealing a location.
448 Org-mode often shows locations in an org-mode file which might have
449 been invisible before. When this is set, the text below the headline that is
450 exposed is also shown.
452 By default this is off for all contexts.
453 Instead of t, this can also be an alist specifying this option for different
454 contexts. See `org-show-hierarchy-above' for valid contexts."
455 :group 'org-reveal-location
456 :type org-context-choice)
458 (defcustom org-indirect-buffer-display 'other-window
459 "How should indirect tree buffers be displayed?
460 This applies to indirect buffers created with the commands
461 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
462 Valid values are:
463 current-window Display in the current window
464 other-window Just display in another window.
465 dedicated-frame Create one new frame, and re-use it each time.
466 new-frame Make a new frame each time. Note that in this case
467 previously-made indirect buffers are kept, and you need to
468 kill these buffers yourself."
469 :group 'org-structure
470 :group 'org-agenda-windows
471 :type '(choice
472 (const :tag "In current window" current-window)
473 (const :tag "In current frame, other window" other-window)
474 (const :tag "Each time a new frame" new-frame)
475 (const :tag "One dedicated frame" dedicated-frame)))
477 (defgroup org-cycle nil
478 "Options concerning visibility cycling in Org-mode."
479 :tag "Org Cycle"
480 :group 'org-structure)
482 (defcustom org-drawers '("PROPERTIES" "CLOCK")
483 "Names of drawers. Drawers are not opened by cycling on the headline above.
484 Drawers only open with a TAB on the drawer line itself. A drawer looks like
485 this:
486 :DRAWERNAME:
487 .....
488 :END:
489 The drawer \"PROPERTIES\" is special for capturing properties through
490 the property API.
492 Drawers can be defined on the per-file basis with a line like:
494 #+DRAWERS: HIDDEN STATE PROPERTIES"
495 :group 'org-structure
496 :type '(repeat (string :tag "Drawer Name")))
498 (defcustom org-cycle-global-at-bob nil
499 "Cycle globally if cursor is at beginning of buffer and not at a headline.
500 This makes it possible to do global cycling without having to use S-TAB or
501 C-u TAB. For this special case to work, the first line of the buffer
502 must not be a headline - it may be empty ot some other text. When used in
503 this way, `org-cycle-hook' is disables temporarily, to make sure the
504 cursor stays at the beginning of the buffer.
505 When this option is nil, don't do anything special at the beginning
506 of the buffer."
507 :group 'org-cycle
508 :type 'boolean)
510 (defcustom org-cycle-emulate-tab t
511 "Where should `org-cycle' emulate TAB.
512 nil Never
513 white Only in completely white lines
514 whitestart Only at the beginning of lines, before the first non-white char
515 t Everywhere except in headlines
516 exc-hl-bol Everywhere except at the start of a headline
517 If TAB is used in a place where it does not emulate TAB, the current subtree
518 visibility is cycled."
519 :group 'org-cycle
520 :type '(choice (const :tag "Never" nil)
521 (const :tag "Only in completely white lines" white)
522 (const :tag "Before first char in a line" whitestart)
523 (const :tag "Everywhere except in headlines" t)
524 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
527 (defcustom org-cycle-separator-lines 2
528 "Number of empty lines needed to keep an empty line between collapsed trees.
529 If you leave an empty line between the end of a subtree and the following
530 headline, this empty line is hidden when the subtree is folded.
531 Org-mode will leave (exactly) one empty line visible if the number of
532 empty lines is equal or larger to the number given in this variable.
533 So the default 2 means, at least 2 empty lines after the end of a subtree
534 are needed to produce free space between a collapsed subtree and the
535 following headline.
537 Special case: when 0, never leave empty lines in collapsed view."
538 :group 'org-cycle
539 :type 'integer)
541 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
542 org-cycle-hide-drawers
543 org-cycle-show-empty-lines
544 org-optimize-window-after-visibility-change)
545 "Hook that is run after `org-cycle' has changed the buffer visibility.
546 The function(s) in this hook must accept a single argument which indicates
547 the new state that was set by the most recent `org-cycle' command. The
548 argument is a symbol. After a global state change, it can have the values
549 `overview', `content', or `all'. After a local state change, it can have
550 the values `folded', `children', or `subtree'."
551 :group 'org-cycle
552 :type 'hook)
554 (defgroup org-edit-structure nil
555 "Options concerning structure editing in Org-mode."
556 :tag "Org Edit Structure"
557 :group 'org-structure)
559 (defcustom org-odd-levels-only nil
560 "Non-nil means, skip even levels and only use odd levels for the outline.
561 This has the effect that two stars are being added/taken away in
562 promotion/demotion commands. It also influences how levels are
563 handled by the exporters.
564 Changing it requires restart of `font-lock-mode' to become effective
565 for fontification also in regions already fontified.
566 You may also set this on a per-file basis by adding one of the following
567 lines to the buffer:
569 #+STARTUP: odd
570 #+STARTUP: oddeven"
571 :group 'org-edit-structure
572 :group 'org-font-lock
573 :type 'boolean)
575 (defcustom org-adapt-indentation t
576 "Non-nil means, adapt indentation when promoting and demoting.
577 When this is set and the *entire* text in an entry is indented, the
578 indentation is increased by one space in a demotion command, and
579 decreased by one in a promotion command. If any line in the entry
580 body starts at column 0, indentation is not changed at all."
581 :group 'org-edit-structure
582 :type 'boolean)
584 (defcustom org-special-ctrl-a/e nil
585 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
586 When t, `C-a' will bring back the cursor to the beginning of the
587 headline text, i.e. after the stars and after a possible TODO keyword.
588 In an item, this will be the position after the bullet.
589 When the cursor is already at that position, another `C-a' will bring
590 it to the beginning of the line.
591 `C-e' will jump to the end of the headline, ignoring the presence of tags
592 in the headline. A second `C-e' will then jump to the true end of the
593 line, after any tags.
594 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
595 and only a directly following, identical keypress will bring the cursor
596 to the special positions."
597 :group 'org-edit-structure
598 :type '(choice
599 (const :tag "off" nil)
600 (const :tag "after bullet first" t)
601 (const :tag "border first" reversed)))
603 (if (fboundp 'defvaralias)
604 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
606 (defcustom org-special-ctrl-k nil
607 "Non-nil means `C-k' will behave specially in headlines.
608 When nil, `C-k' will call the default `kill-line' command.
609 When t, the following will happen while the cursor is in the headline:
611 - When the cursor is at the beginning of a headline, kill the entire
612 line and possible the folded subtree below the line.
613 - When in the middle of the headline text, kill the headline up to the tags.
614 - When after the headline text, kill the tags."
615 :group 'org-edit-structure
616 :type 'boolean)
618 (defcustom org-M-RET-may-split-line '((default . t))
619 "Non-nil means, M-RET will split the line at the cursor position.
620 When nil, it will go to the end of the line before making a
621 new line.
622 You may also set this option in a different way for different
623 contexts. Valid contexts are:
625 headline when creating a new headline
626 item when creating a new item
627 table in a table field
628 default the value to be used for all contexts not explicitly
629 customized"
630 :group 'org-structure
631 :group 'org-table
632 :type '(choice
633 (const :tag "Always" t)
634 (const :tag "Never" nil)
635 (repeat :greedy t :tag "Individual contexts"
636 (cons
637 (choice :tag "Context"
638 (const headline)
639 (const item)
640 (const table)
641 (const default))
642 (boolean)))))
645 (defcustom org-blank-before-new-entry '((heading . nil)
646 (plain-list-item . nil))
647 "Should `org-insert-heading' leave a blank line before new heading/item?
648 The value is an alist, with `heading' and `plain-list-item' as car,
649 and a boolean flag as cdr."
650 :group 'org-edit-structure
651 :type '(list
652 (cons (const heading) (boolean))
653 (cons (const plain-list-item) (boolean))))
655 (defcustom org-insert-heading-hook nil
656 "Hook being run after inserting a new heading."
657 :group 'org-edit-structure
658 :type 'hook)
660 (defcustom org-enable-fixed-width-editor t
661 "Non-nil means, lines starting with \":\" are treated as fixed-width.
662 This currently only means, they are never auto-wrapped.
663 When nil, such lines will be treated like ordinary lines.
664 See also the QUOTE keyword."
665 :group 'org-edit-structure
666 :type 'boolean)
668 (defcustom org-goto-auto-isearch t
669 "Non-nil means, typing characters in org-goto starts incremental search."
670 :group 'org-edit-structure
671 :type 'boolean)
673 (defgroup org-sparse-trees nil
674 "Options concerning sparse trees in Org-mode."
675 :tag "Org Sparse Trees"
676 :group 'org-structure)
678 (defcustom org-highlight-sparse-tree-matches t
679 "Non-nil means, highlight all matches that define a sparse tree.
680 The highlights will automatically disappear the next time the buffer is
681 changed by an edit command."
682 :group 'org-sparse-trees
683 :type 'boolean)
685 (defcustom org-remove-highlights-with-change t
686 "Non-nil means, any change to the buffer will remove temporary highlights.
687 Such highlights are created by `org-occur' and `org-clock-display'.
688 When nil, `C-c C-c needs to be used to get rid of the highlights.
689 The highlights created by `org-preview-latex-fragment' always need
690 `C-c C-c' to be removed."
691 :group 'org-sparse-trees
692 :group 'org-time
693 :type 'boolean)
696 (defcustom org-occur-hook '(org-first-headline-recenter)
697 "Hook that is run after `org-occur' has constructed a sparse tree.
698 This can be used to recenter the window to show as much of the structure
699 as possible."
700 :group 'org-sparse-trees
701 :type 'hook)
703 (defgroup org-plain-lists nil
704 "Options concerning plain lists in Org-mode."
705 :tag "Org Plain lists"
706 :group 'org-structure)
708 (defcustom org-cycle-include-plain-lists nil
709 "Non-nil means, include plain lists into visibility cycling.
710 This means that during cycling, plain list items will *temporarily* be
711 interpreted as outline headlines with a level given by 1000+i where i is the
712 indentation of the bullet. In all other operations, plain list items are
713 not seen as headlines. For example, you cannot assign a TODO keyword to
714 such an item."
715 :group 'org-plain-lists
716 :type 'boolean)
718 (defcustom org-plain-list-ordered-item-terminator t
719 "The character that makes a line with leading number an ordered list item.
720 Valid values are ?. and ?\). To get both terminators, use t. While
721 ?. may look nicer, it creates the danger that a line with leading
722 number may be incorrectly interpreted as an item. ?\) therefore is
723 the safe choice."
724 :group 'org-plain-lists
725 :type '(choice (const :tag "dot like in \"2.\"" ?.)
726 (const :tag "paren like in \"2)\"" ?\))
727 (const :tab "both" t)))
729 (defcustom org-empty-line-terminates-plain-lists nil
730 "Non-nil means, an empty line ends all plain list levels.
731 When nil, empty lines are part of the preceeding item."
732 :group 'org-plain-lists
733 :type 'boolean)
735 (defcustom org-auto-renumber-ordered-lists t
736 "Non-nil means, automatically renumber ordered plain lists.
737 Renumbering happens when the sequence have been changed with
738 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
739 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
740 :group 'org-plain-lists
741 :type 'boolean)
743 (defcustom org-provide-checkbox-statistics t
744 "Non-nil means, update checkbox statistics after insert and toggle.
745 When this is set, checkbox statistics is updated each time you either insert
746 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
747 with \\[org-ctrl-c-ctrl-c\\]."
748 :group 'org-plain-lists
749 :type 'boolean)
752 (defgroup org-imenu-and-speedbar nil
753 "Options concerning imenu and speedbar in Org-mode."
754 :tag "Org Imenu and Speedbar"
755 :group 'org-structure)
757 (defcustom org-imenu-depth 2
758 "The maximum level for Imenu access to Org-mode headlines.
759 This also applied for speedbar access."
760 :group 'org-imenu-and-speedbar
761 :type 'number)
763 (defgroup org-table nil
764 "Options concerning tables in Org-mode."
765 :tag "Org Table"
766 :group 'org)
768 (defcustom org-enable-table-editor 'optimized
769 "Non-nil means, lines starting with \"|\" are handled by the table editor.
770 When nil, such lines will be treated like ordinary lines.
772 When equal to the symbol `optimized', the table editor will be optimized to
773 do the following:
774 - Automatic overwrite mode in front of whitespace in table fields.
775 This makes the structure of the table stay in tact as long as the edited
776 field does not exceed the column width.
777 - Minimize the number of realigns. Normally, the table is aligned each time
778 TAB or RET are pressed to move to another field. With optimization this
779 happens only if changes to a field might have changed the column width.
780 Optimization requires replacing the functions `self-insert-command',
781 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
782 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
783 very good at guessing when a re-align will be necessary, but you can always
784 force one with \\[org-ctrl-c-ctrl-c].
786 If you would like to use the optimized version in Org-mode, but the
787 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
789 This variable can be used to turn on and off the table editor during a session,
790 but in order to toggle optimization, a restart is required.
792 See also the variable `org-table-auto-blank-field'."
793 :group 'org-table
794 :type '(choice
795 (const :tag "off" nil)
796 (const :tag "on" t)
797 (const :tag "on, optimized" optimized)))
799 (defcustom org-table-tab-recognizes-table.el t
800 "Non-nil means, TAB will automatically notice a table.el table.
801 When it sees such a table, it moves point into it and - if necessary -
802 calls `table-recognize-table'."
803 :group 'org-table-editing
804 :type 'boolean)
806 (defgroup org-link nil
807 "Options concerning links in Org-mode."
808 :tag "Org Link"
809 :group 'org)
811 (defvar org-link-abbrev-alist-local nil
812 "Buffer-local version of `org-link-abbrev-alist', which see.
813 The value of this is taken from the #+LINK lines.")
814 (make-variable-buffer-local 'org-link-abbrev-alist-local)
816 (defcustom org-link-abbrev-alist nil
817 "Alist of link abbreviations.
818 The car of each element is a string, to be replaced at the start of a link.
819 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
820 links in Org-mode buffers can have an optional tag after a double colon, e.g.
822 [[linkkey:tag][description]]
824 If REPLACE is a string, the tag will simply be appended to create the link.
825 If the string contains \"%s\", the tag will be inserted there.
827 REPLACE may also be a function that will be called with the tag as the
828 only argument to create the link, which should be returned as a string.
830 See the manual for examples."
831 :group 'org-link
832 :type 'alist)
834 (defcustom org-descriptive-links t
835 "Non-nil means, hide link part and only show description of bracket links.
836 Bracket links are like [[link][descritpion]]. This variable sets the initial
837 state in new org-mode buffers. The setting can then be toggled on a
838 per-buffer basis from the Org->Hyperlinks menu."
839 :group 'org-link
840 :type 'boolean)
842 (defcustom org-link-file-path-type 'adaptive
843 "How the path name in file links should be stored.
844 Valid values are:
846 relative Relative to the current directory, i.e. the directory of the file
847 into which the link is being inserted.
848 absolute Absolute path, if possible with ~ for home directory.
849 noabbrev Absolute path, no abbreviation of home directory.
850 adaptive Use relative path for files in the current directory and sub-
851 directories of it. For other files, use an absolute path."
852 :group 'org-link
853 :type '(choice
854 (const relative)
855 (const absolute)
856 (const noabbrev)
857 (const adaptive)))
859 (defcustom org-activate-links '(bracket angle plain radio tag date)
860 "Types of links that should be activated in Org-mode files.
861 This is a list of symbols, each leading to the activation of a certain link
862 type. In principle, it does not hurt to turn on most link types - there may
863 be a small gain when turning off unused link types. The types are:
865 bracket The recommended [[link][description]] or [[link]] links with hiding.
866 angular Links in angular brackes that may contain whitespace like
867 <bbdb:Carsten Dominik>.
868 plain Plain links in normal text, no whitespace, like http://google.com.
869 radio Text that is matched by a radio target, see manual for details.
870 tag Tag settings in a headline (link to tag search).
871 date Time stamps (link to calendar).
873 Changing this variable requires a restart of Emacs to become effective."
874 :group 'org-link
875 :type '(set (const :tag "Double bracket links (new style)" bracket)
876 (const :tag "Angular bracket links (old style)" angular)
877 (const :tag "Plain text links" plain)
878 (const :tag "Radio target matches" radio)
879 (const :tag "Tags" tag)
880 (const :tag "Timestamps" date)))
882 (defcustom org-make-link-description-function nil
883 "Function to use to generate link descriptions from links. If
884 nil the link location will be used. This function must take two
885 parameters; the first is the link and the second the description
886 org-insert-link has generated, and should return the description
887 to use."
888 :group 'org-link
889 :type 'function)
891 (defgroup org-link-store nil
892 "Options concerning storing links in Org-mode."
893 :tag "Org Store Link"
894 :group 'org-link)
896 (defcustom org-email-link-description-format "Email %c: %.30s"
897 "Format of the description part of a link to an email or usenet message.
898 The following %-excapes will be replaced by corresponding information:
900 %F full \"From\" field
901 %f name, taken from \"From\" field, address if no name
902 %T full \"To\" field
903 %t first name in \"To\" field, address if no name
904 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
905 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
906 %s subject
907 %m message-id.
909 You may use normal field width specification between the % and the letter.
910 This is for example useful to limit the length of the subject.
912 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
913 :group 'org-link-store
914 :type 'string)
916 (defcustom org-from-is-user-regexp
917 (let (r1 r2)
918 (when (and user-mail-address (not (string= user-mail-address "")))
919 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
920 (when (and user-full-name (not (string= user-full-name "")))
921 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
922 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
923 "Regexp mached against the \"From:\" header of an email or usenet message.
924 It should match if the message is from the user him/herself."
925 :group 'org-link-store
926 :type 'regexp)
928 (defcustom org-context-in-file-links t
929 "Non-nil means, file links from `org-store-link' contain context.
930 A search string will be added to the file name with :: as separator and
931 used to find the context when the link is activated by the command
932 `org-open-at-point'.
933 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
934 negates this setting for the duration of the command."
935 :group 'org-link-store
936 :type 'boolean)
938 (defcustom org-keep-stored-link-after-insertion nil
939 "Non-nil means, keep link in list for entire session.
941 The command `org-store-link' adds a link pointing to the current
942 location to an internal list. These links accumulate during a session.
943 The command `org-insert-link' can be used to insert links into any
944 Org-mode file (offering completion for all stored links). When this
945 option is nil, every link which has been inserted once using \\[org-insert-link]
946 will be removed from the list, to make completing the unused links
947 more efficient."
948 :group 'org-link-store
949 :type 'boolean)
951 (defgroup org-link-follow nil
952 "Options concerning following links in Org-mode."
953 :tag "Org Follow Link"
954 :group 'org-link)
956 (defcustom org-follow-link-hook nil
957 "Hook that is run after a link has been followed."
958 :group 'org-link-follow
959 :type 'hook)
961 (defcustom org-tab-follows-link nil
962 "Non-nil means, on links TAB will follow the link.
963 Needs to be set before org.el is loaded."
964 :group 'org-link-follow
965 :type 'boolean)
967 (defcustom org-return-follows-link nil
968 "Non-nil means, on links RET will follow the link.
969 Needs to be set before org.el is loaded."
970 :group 'org-link-follow
971 :type 'boolean)
973 (defcustom org-mouse-1-follows-link
974 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
975 "Non-nil means, mouse-1 on a link will follow the link.
976 A longer mouse click will still set point. Does not work on XEmacs.
977 Needs to be set before org.el is loaded."
978 :group 'org-link-follow
979 :type 'boolean)
981 (defcustom org-mark-ring-length 4
982 "Number of different positions to be recorded in the ring
983 Changing this requires a restart of Emacs to work correctly."
984 :group 'org-link-follow
985 :type 'interger)
987 (defcustom org-link-frame-setup
988 '((vm . vm-visit-folder-other-frame)
989 (gnus . gnus-other-frame)
990 (file . find-file-other-window))
991 "Setup the frame configuration for following links.
992 When following a link with Emacs, it may often be useful to display
993 this link in another window or frame. This variable can be used to
994 set this up for the different types of links.
995 For VM, use any of
996 `vm-visit-folder'
997 `vm-visit-folder-other-frame'
998 For Gnus, use any of
999 `gnus'
1000 `gnus-other-frame'
1001 For FILE, use any of
1002 `find-file'
1003 `find-file-other-window'
1004 `find-file-other-frame'
1005 For the calendar, use the variable `calendar-setup'.
1006 For BBDB, it is currently only possible to display the matches in
1007 another window."
1008 :group 'org-link-follow
1009 :type '(list
1010 (cons (const vm)
1011 (choice
1012 (const vm-visit-folder)
1013 (const vm-visit-folder-other-window)
1014 (const vm-visit-folder-other-frame)))
1015 (cons (const gnus)
1016 (choice
1017 (const gnus)
1018 (const gnus-other-frame)))
1019 (cons (const file)
1020 (choice
1021 (const find-file)
1022 (const find-file-other-window)
1023 (const find-file-other-frame)))))
1025 (defcustom org-display-internal-link-with-indirect-buffer nil
1026 "Non-nil means, use indirect buffer to display infile links.
1027 Activating internal links (from one location in a file to another location
1028 in the same file) normally just jumps to the location. When the link is
1029 activated with a C-u prefix (or with mouse-3), the link is displayed in
1030 another window. When this option is set, the other window actually displays
1031 an indirect buffer clone of the current buffer, to avoid any visibility
1032 changes to the current buffer."
1033 :group 'org-link-follow
1034 :type 'boolean)
1036 (defcustom org-open-non-existing-files nil
1037 "Non-nil means, `org-open-file' will open non-existing files.
1038 When nil, an error will be generated."
1039 :group 'org-link-follow
1040 :type 'boolean)
1042 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1043 "Function and arguments to call for following mailto links.
1044 This is a list with the first element being a lisp function, and the
1045 remaining elements being arguments to the function. In string arguments,
1046 %a will be replaced by the address, and %s will be replaced by the subject
1047 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1048 :group 'org-link-follow
1049 :type '(choice
1050 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1051 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1052 (const :tag "message-mail" (message-mail "%a" "%s"))
1053 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1055 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1056 "Non-nil means, ask for confirmation before executing shell links.
1057 Shell links can be dangerous: just think about a link
1059 [[shell:rm -rf ~/*][Google Search]]
1061 This link would show up in your Org-mode document as \"Google Search\",
1062 but really it would remove your entire home directory.
1063 Therefore we advise against setting this variable to nil.
1064 Just change it to `y-or-n-p' of you want to confirm with a
1065 single keystroke rather than having to type \"yes\"."
1066 :group 'org-link-follow
1067 :type '(choice
1068 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1069 (const :tag "with y-or-n (faster)" y-or-n-p)
1070 (const :tag "no confirmation (dangerous)" nil)))
1072 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1073 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1074 Elisp links can be dangerous: just think about a link
1076 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1078 This link would show up in your Org-mode document as \"Google Search\",
1079 but really it would remove your entire home directory.
1080 Therefore we advise against setting this variable to nil.
1081 Just change it to `y-or-n-p' of you want to confirm with a
1082 single keystroke rather than having to type \"yes\"."
1083 :group 'org-link-follow
1084 :type '(choice
1085 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1086 (const :tag "with y-or-n (faster)" y-or-n-p)
1087 (const :tag "no confirmation (dangerous)" nil)))
1089 (defconst org-file-apps-defaults-gnu
1090 '((remote . emacs)
1091 (t . mailcap))
1092 "Default file applications on a UNIX or GNU/Linux system.
1093 See `org-file-apps'.")
1095 (defconst org-file-apps-defaults-macosx
1096 '((remote . emacs)
1097 (t . "open %s")
1098 ("ps" . "gv %s")
1099 ("ps.gz" . "gv %s")
1100 ("eps" . "gv %s")
1101 ("eps.gz" . "gv %s")
1102 ("dvi" . "xdvi %s")
1103 ("fig" . "xfig %s"))
1104 "Default file applications on a MacOS X system.
1105 The system \"open\" is known as a default, but we use X11 applications
1106 for some files for which the OS does not have a good default.
1107 See `org-file-apps'.")
1109 (defconst org-file-apps-defaults-windowsnt
1110 (list
1111 '(remote . emacs)
1112 (cons t
1113 (list (if (featurep 'xemacs)
1114 'mswindows-shell-execute
1115 'w32-shell-execute)
1116 "open" 'file)))
1117 "Default file applications on a Windows NT system.
1118 The system \"open\" is used for most files.
1119 See `org-file-apps'.")
1121 (defcustom org-file-apps
1123 ("txt" . emacs)
1124 ("tex" . emacs)
1125 ("ltx" . emacs)
1126 ("org" . emacs)
1127 ("el" . emacs)
1128 ("bib" . emacs)
1130 "External applications for opening `file:path' items in a document.
1131 Org-mode uses system defaults for different file types, but
1132 you can use this variable to set the application for a given file
1133 extension. The entries in this list are cons cells where the car identifies
1134 files and the cdr the corresponding command. Possible values for the
1135 file identifier are
1136 \"ext\" A string identifying an extension
1137 `directory' Matches a directory
1138 `remote' Matches a remote file, accessible through tramp or efs.
1139 Remote files most likely should be visited through Emacs
1140 because external applications cannot handle such paths.
1141 t Default for all remaining files
1143 Possible values for the command are:
1144 `emacs' The file will be visited by the current Emacs process.
1145 `default' Use the default application for this file type.
1146 string A command to be executed by a shell; %s will be replaced
1147 by the path to the file.
1148 sexp A Lisp form which will be evaluated. The file path will
1149 be available in the Lisp variable `file'.
1150 For more examples, see the system specific constants
1151 `org-file-apps-defaults-macosx'
1152 `org-file-apps-defaults-windowsnt'
1153 `org-file-apps-defaults-gnu'."
1154 :group 'org-link-follow
1155 :type '(repeat
1156 (cons (choice :value ""
1157 (string :tag "Extension")
1158 (const :tag "Default for unrecognized files" t)
1159 (const :tag "Remote file" remote)
1160 (const :tag "Links to a directory" directory))
1161 (choice :value ""
1162 (const :tag "Visit with Emacs" emacs)
1163 (const :tag "Use system default" default)
1164 (string :tag "Command")
1165 (sexp :tag "Lisp form")))))
1167 (defgroup org-refile nil
1168 "Options concerning refiling entries in Org-mode."
1169 :tag "Org Remember"
1170 :group 'org)
1172 (defcustom org-directory "~/org"
1173 "Directory with org files.
1174 This directory will be used as default to prompt for org files.
1175 Used by the hooks for remember.el."
1176 :group 'org-refile
1177 :group 'org-remember
1178 :type 'directory)
1180 (defcustom org-default-notes-file "~/.notes"
1181 "Default target for storing notes.
1182 Used by the hooks for remember.el. This can be a string, or nil to mean
1183 the value of `remember-data-file'.
1184 You can set this on a per-template basis with the variable
1185 `org-remember-templates'."
1186 :group 'org-refile
1187 :group 'org-remember
1188 :type '(choice
1189 (const :tag "Default from remember-data-file" nil)
1190 file))
1192 (defcustom org-goto-interface 'outline
1193 "The default interface to be used for `org-goto'.
1194 Allowed vaues are:
1195 outline The interface shows an outline of the relevant file
1196 and the correct heading is found by moving through
1197 the outline or by searching with incremental search.
1198 outline-path-completion Headlines in the current buffer are offered via
1199 completion."
1200 :group 'org-refile
1201 :type '(choice
1202 (const :tag "Outline" outline)
1203 (const :tag "Outline-path-completion" outline-path-completion)))
1205 (defcustom org-reverse-note-order nil
1206 "Non-nil means, store new notes at the beginning of a file or entry.
1207 When nil, new notes will be filed to the end of a file or entry.
1208 This can also be a list with cons cells of regular expressions that
1209 are matched against file names, and values."
1210 :group 'org-remember
1211 :type '(choice
1212 (const :tag "Reverse always" t)
1213 (const :tag "Reverse never" nil)
1214 (repeat :tag "By file name regexp"
1215 (cons regexp boolean))))
1217 (defcustom org-refile-targets nil
1218 "Targets for refiling entries with \\[org-refile].
1219 This is list of cons cells. Each cell contains:
1220 - a specification of the files to be considered, either a list of files,
1221 or a symbol whose function or variable value will be used to retrieve
1222 a file name or a list of file names. Nil means, refile to a different
1223 heading in the current buffer.
1224 - A specification of how to find candidate refile targets. This may be
1225 any of
1226 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1227 This tag has to be present in all target headlines, inheritance will
1228 not be considered.
1229 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1230 todo keyword.
1231 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1232 headlines that are refiling targets.
1233 - a cons cell (:level . N). Any headline of level N is considered a target.
1234 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1235 :group 'org-remember
1236 :type '(repeat
1237 (cons
1238 (choice :value org-agenda-files
1239 (const :tag "All agenda files" org-agenda-files)
1240 (const :tag "Current buffer" nil)
1241 (function) (variable) (file))
1242 (choice :tag "Identify target headline by"
1243 (cons :tag "Specific tag" (const :tag) (string))
1244 (cons :tag "TODO keyword" (const :todo) (string))
1245 (cons :tag "Regular expression" (const :regexp) (regexp))
1246 (cons :tag "Level number" (const :level) (integer))
1247 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1249 (defcustom org-refile-use-outline-path nil
1250 "Non-nil means, provide refile targets as paths.
1251 So a level 3 headline will be available as level1/level2/level3.
1252 When the value is `file', also include the file name (without directory)
1253 into the path. When `full-file-path', include the full file path."
1254 :group 'org-remember
1255 :type '(choice
1256 (const :tag "Not" nil)
1257 (const :tag "Yes" t)
1258 (const :tag "Start with file name" file)
1259 (const :tag "Start with full file path" full-file-path)))
1261 (defgroup org-todo nil
1262 "Options concerning TODO items in Org-mode."
1263 :tag "Org TODO"
1264 :group 'org)
1266 (defgroup org-progress nil
1267 "Options concerning Progress logging in Org-mode."
1268 :tag "Org Progress"
1269 :group 'org-time)
1271 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1272 "List of TODO entry keyword sequences and their interpretation.
1273 \\<org-mode-map>This is a list of sequences.
1275 Each sequence starts with a symbol, either `sequence' or `type',
1276 indicating if the keywords should be interpreted as a sequence of
1277 action steps, or as different types of TODO items. The first
1278 keywords are states requiring action - these states will select a headline
1279 for inclusion into the global TODO list Org-mode produces. If one of
1280 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1281 signify that no further action is necessary. If \"|\" is not found,
1282 the last keyword is treated as the only DONE state of the sequence.
1284 The command \\[org-todo] cycles an entry through these states, and one
1285 additional state where no keyword is present. For details about this
1286 cycling, see the manual.
1288 TODO keywords and interpretation can also be set on a per-file basis with
1289 the special #+SEQ_TODO and #+TYP_TODO lines.
1291 Each keyword can optionally specify a character for fast state selection
1292 \(in combination with the variable `org-use-fast-todo-selection')
1293 and specifiers for state change logging, using the same syntax
1294 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1295 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1296 indicates to record a time stamp each time this state is selected.
1298 Each keyword may also specify if a timestamp or a note should be
1299 recorded when entering or leaving the state, by adding additional
1300 characters in the parenthesis after the keyword. This looks like this:
1301 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1302 record only the time of the state change. With X and Y being either
1303 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1304 Y when leaving the state if and only if the *target* state does not
1305 define X. You may omit any of the fast-selection key or X or /Y,
1306 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1308 For backward compatibility, this variable may also be just a list
1309 of keywords - in this case the interptetation (sequence or type) will be
1310 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1311 :group 'org-todo
1312 :group 'org-keywords
1313 :type '(choice
1314 (repeat :tag "Old syntax, just keywords"
1315 (string :tag "Keyword"))
1316 (repeat :tag "New syntax"
1317 (cons
1318 (choice
1319 :tag "Interpretation"
1320 (const :tag "Sequence (cycling hits every state)" sequence)
1321 (const :tag "Type (cycling directly to DONE)" type))
1322 (repeat
1323 (string :tag "Keyword"))))))
1325 (defvar org-todo-keywords-1 nil
1326 "All TODO and DONE keywords active in a buffer.")
1327 (make-variable-buffer-local 'org-todo-keywords-1)
1328 (defvar org-todo-keywords-for-agenda nil)
1329 (defvar org-done-keywords-for-agenda nil)
1330 (defvar org-agenda-contributing-files nil)
1331 (defvar org-not-done-keywords nil)
1332 (make-variable-buffer-local 'org-not-done-keywords)
1333 (defvar org-done-keywords nil)
1334 (make-variable-buffer-local 'org-done-keywords)
1335 (defvar org-todo-heads nil)
1336 (make-variable-buffer-local 'org-todo-heads)
1337 (defvar org-todo-sets nil)
1338 (make-variable-buffer-local 'org-todo-sets)
1339 (defvar org-todo-log-states nil)
1340 (make-variable-buffer-local 'org-todo-log-states)
1341 (defvar org-todo-kwd-alist nil)
1342 (make-variable-buffer-local 'org-todo-kwd-alist)
1343 (defvar org-todo-key-alist nil)
1344 (make-variable-buffer-local 'org-todo-key-alist)
1345 (defvar org-todo-key-trigger nil)
1346 (make-variable-buffer-local 'org-todo-key-trigger)
1348 (defcustom org-todo-interpretation 'sequence
1349 "Controls how TODO keywords are interpreted.
1350 This variable is in principle obsolete and is only used for
1351 backward compatibility, if the interpretation of todo keywords is
1352 not given already in `org-todo-keywords'. See that variable for
1353 more information."
1354 :group 'org-todo
1355 :group 'org-keywords
1356 :type '(choice (const sequence)
1357 (const type)))
1359 (defcustom org-use-fast-todo-selection 'prefix
1360 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1361 This variable describes if and under what circumstances the cycling
1362 mechanism for TODO keywords will be replaced by a single-key, direct
1363 selection scheme.
1365 When nil, fast selection is never used.
1367 When the symbol `prefix', it will be used when `org-todo' is called with
1368 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1369 in an agenda buffer.
1371 When t, fast selection is used by default. In this case, the prefix
1372 argument forces cycling instead.
1374 In all cases, the special interface is only used if access keys have actually
1375 been assigned by the user, i.e. if keywords in the configuration are followed
1376 by a letter in parenthesis, like TODO(t)."
1377 :group 'org-todo
1378 :type '(choice
1379 (const :tag "Never" nil)
1380 (const :tag "By default" t)
1381 (const :tag "Only with C-u C-c C-t" prefix)))
1383 (defcustom org-after-todo-state-change-hook nil
1384 "Hook which is run after the state of a TODO item was changed.
1385 The new state (a string with a TODO keyword, or nil) is available in the
1386 Lisp variable `state'."
1387 :group 'org-todo
1388 :type 'hook)
1390 (defcustom org-log-done nil
1391 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1392 When equal to the list (done), also prompt for a closing note.
1393 This can also be configured on a per-file basis by adding one of
1394 the following lines anywhere in the buffer:
1396 #+STARTUP: logdone
1397 #+STARTUP: lognotedone
1398 #+STARTUP: nologdone"
1399 :group 'org-todo
1400 :group 'org-progress
1401 :type '(choice
1402 (const :tag "No logging" nil)
1403 (const :tag "Record CLOSED timestamp" time)
1404 (const :tag "Record CLOSED timestamp with closing note." note)))
1406 ;; Normalize old uses of org-log-done.
1407 (cond
1408 ((eq org-log-done t) (setq org-log-done 'time))
1409 ((and (listp org-log-done) (memq 'done org-log-done))
1410 (setq org-log-done 'note)))
1412 (defcustom org-log-note-clock-out nil
1413 "Non-nil means, recored a note when clocking out of an item.
1414 This can also be configured on a per-file basis by adding one of
1415 the following lines anywhere in the buffer:
1417 #+STARTUP: lognoteclock-out
1418 #+STARTUP: nolognoteclock-out"
1419 :group 'org-todo
1420 :group 'org-progress
1421 :type 'boolean)
1423 (defcustom org-log-done-with-time t
1424 "Non-nil means, the CLOSED time stamp will contain date and time.
1425 When nil, only the date will be recorded."
1426 :group 'org-progress
1427 :type 'boolean)
1429 (defcustom org-log-note-headings
1430 '((done . "CLOSING NOTE %t")
1431 (state . "State %-12s %t")
1432 (note . "Note taken on %t")
1433 (clock-out . ""))
1434 "Headings for notes added to entries.
1435 The value is an alist, with the car being a symbol indicating the note
1436 context, and the cdr is the heading to be used. The heading may also be the
1437 empty string.
1438 %t in the heading will be replaced by a time stamp.
1439 %s will be replaced by the new TODO state, in double quotes.
1440 %u will be replaced by the user name.
1441 %U will be replaced by the full user name."
1442 :group 'org-todo
1443 :group 'org-progress
1444 :type '(list :greedy t
1445 (cons (const :tag "Heading when closing an item" done) string)
1446 (cons (const :tag
1447 "Heading when changing todo state (todo sequence only)"
1448 state) string)
1449 (cons (const :tag "Heading when just taking a note" note) string)
1450 (cons (const :tag "Heading when clocking out" clock-out) string)))
1452 (unless (assq 'note org-log-note-headings)
1453 (push '(note . "%t") org-log-note-headings))
1455 (defcustom org-log-states-order-reversed t
1456 "Non-nil means, the latest state change note will be directly after heading.
1457 When nil, the notes will be orderer according to time."
1458 :group 'org-todo
1459 :group 'org-progress
1460 :type 'boolean)
1462 (defcustom org-log-repeat 'time
1463 "Non-nil means, record moving through the DONE state when triggering repeat.
1464 An auto-repeating tasks is immediately switched back to TODO when marked
1465 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1466 the TODO keyword definition, or recording a closing note by setting
1467 `org-log-done', there will be no record of the task moving through DONE.
1468 This variable forces taking a note anyway. Possible values are:
1470 nil Don't force a record
1471 time Record a time stamp
1472 note Record a note
1474 This option can also be set with on a per-file-basis with
1476 #+STARTUP: logrepeat
1477 #+STARTUP: lognoterepeat
1478 #+STARTUP: nologrepeat
1480 You can have local logging settings for a subtree by setting the LOGGING
1481 property to one or more of these keywords."
1482 :group 'org-todo
1483 :group 'org-progress
1484 :type '(choice
1485 (const :tag "Don't force a record" nil)
1486 (const :tag "Force recording the DONE state" time)
1487 (const :tag "Force recording a note with the DONE state" note)))
1490 (defgroup org-priorities nil
1491 "Priorities in Org-mode."
1492 :tag "Org Priorities"
1493 :group 'org-todo)
1495 (defcustom org-highest-priority ?A
1496 "The highest priority of TODO items. A character like ?A, ?B etc.
1497 Must have a smaller ASCII number than `org-lowest-priority'."
1498 :group 'org-priorities
1499 :type 'character)
1501 (defcustom org-lowest-priority ?C
1502 "The lowest priority of TODO items. A character like ?A, ?B etc.
1503 Must have a larger ASCII number than `org-highest-priority'."
1504 :group 'org-priorities
1505 :type 'character)
1507 (defcustom org-default-priority ?B
1508 "The default priority of TODO items.
1509 This is the priority an item get if no explicit priority is given."
1510 :group 'org-priorities
1511 :type 'character)
1513 (defcustom org-priority-start-cycle-with-default t
1514 "Non-nil means, start with default priority when starting to cycle.
1515 When this is nil, the first step in the cycle will be (depending on the
1516 command used) one higher or lower that the default priority."
1517 :group 'org-priorities
1518 :type 'boolean)
1520 (defgroup org-time nil
1521 "Options concerning time stamps and deadlines in Org-mode."
1522 :tag "Org Time"
1523 :group 'org)
1525 (defcustom org-insert-labeled-timestamps-at-point nil
1526 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1527 When nil, these labeled time stamps are forces into the second line of an
1528 entry, just after the headline. When scheduling from the global TODO list,
1529 the time stamp will always be forced into the second line."
1530 :group 'org-time
1531 :type 'boolean)
1533 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1534 "Formats for `format-time-string' which are used for time stamps.
1535 It is not recommended to change this constant.")
1537 (defcustom org-time-stamp-rounding-minutes '(0 5)
1538 "Number of minutes to round time stamps to.
1539 These are two values, the first applies when first creating a time stamp.
1540 The second applies when changing it with the commands `S-up' and `S-down'.
1541 When changing the time stamp, this means that it will change in steps
1542 of N minutes, as given by the second value.
1544 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1545 numbers should be factors of 60, so for example 5, 10, 15.
1547 When this is larger than 1, you can still force an exact time-stamp by using
1548 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1549 and by using a prefix arg to `S-up/down' to specify the exact number
1550 of minutes to shift."
1551 :group 'org-time
1552 :get '(lambda (var) ; Make sure all entries have 5 elements
1553 (if (integerp (default-value var))
1554 (list (default-value var) 5)
1555 (default-value var)))
1556 :type '(list
1557 (integer :tag "when inserting times")
1558 (integer :tag "when modifying times")))
1560 ;; Normalize old customizations of this variable.
1561 (when (integerp org-time-stamp-rounding-minutes)
1562 (setq org-time-stamp-rounding-minutes
1563 (list org-time-stamp-rounding-minutes
1564 org-time-stamp-rounding-minutes)))
1566 (defcustom org-display-custom-times nil
1567 "Non-nil means, overlay custom formats over all time stamps.
1568 The formats are defined through the variable `org-time-stamp-custom-formats'.
1569 To turn this on on a per-file basis, insert anywhere in the file:
1570 #+STARTUP: customtime"
1571 :group 'org-time
1572 :set 'set-default
1573 :type 'sexp)
1574 (make-variable-buffer-local 'org-display-custom-times)
1576 (defcustom org-time-stamp-custom-formats
1577 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1578 "Custom formats for time stamps. See `format-time-string' for the syntax.
1579 These are overlayed over the default ISO format if the variable
1580 `org-display-custom-times' is set. Time like %H:%M should be at the
1581 end of the second format."
1582 :group 'org-time
1583 :type 'sexp)
1585 (defun org-time-stamp-format (&optional long inactive)
1586 "Get the right format for a time string."
1587 (let ((f (if long (cdr org-time-stamp-formats)
1588 (car org-time-stamp-formats))))
1589 (if inactive
1590 (concat "[" (substring f 1 -1) "]")
1591 f)))
1593 (defcustom org-deadline-warning-days 14
1594 "No. of days before expiration during which a deadline becomes active.
1595 This variable governs the display in sparse trees and in the agenda.
1596 When 0 or negative, it means use this number (the absolute value of it)
1597 even if a deadline has a different individual lead time specified."
1598 :group 'org-time
1599 :group 'org-agenda-daily/weekly
1600 :type 'number)
1602 (defcustom org-read-date-prefer-future t
1603 "Non-nil means, assume future for incomplete date input from user.
1604 This affects the following situations:
1605 1. The user gives a day, but no month.
1606 For example, if today is the 15th, and you enter \"3\", Org-mode will
1607 read this as the third of *next* month. However, if you enter \"17\",
1608 it will be considered as *this* month.
1609 2. The user gives a month but not a year.
1610 For example, if it is april and you enter \"feb 2\", this will be read
1611 as feb 2, *next* year. \"May 5\", however, will be this year.
1613 Currently this does not work for ISO week specifications.
1615 When this option is nil, the current month and year will always be used
1616 as defaults."
1617 :group 'org-time
1618 :type 'boolean)
1620 (defcustom org-read-date-display-live t
1621 "Non-nil means, display current interpretation of date prompt live.
1622 This display will be in an overlay, in the minibuffer."
1623 :group 'org-time
1624 :type 'boolean)
1626 (defcustom org-read-date-popup-calendar t
1627 "Non-nil means, pop up a calendar when prompting for a date.
1628 In the calendar, the date can be selected with mouse-1. However, the
1629 minibuffer will also be active, and you can simply enter the date as well.
1630 When nil, only the minibuffer will be available."
1631 :group 'org-time
1632 :type 'boolean)
1633 (if (fboundp 'defvaralias)
1634 (defvaralias 'org-popup-calendar-for-date-prompt
1635 'org-read-date-popup-calendar))
1637 (defcustom org-extend-today-until 0
1638 "The hour when your day really ends.
1639 This has influence for the following applications:
1640 - When switching the agenda to \"today\". It it is still earlier than
1641 the time given here, the day recognized as TODAY is actually yesterday.
1642 - When a date is read from the user and it is still before the time given
1643 here, the current date and time will be assumed to be yesterday, 23:59.
1645 FIXME:
1646 IMPORTANT: This is still a very experimental feature, it may disappear
1647 again or it may be extended to mean more things."
1648 :group 'org-time
1649 :type 'number)
1651 (defcustom org-edit-timestamp-down-means-later nil
1652 "Non-nil means, S-down will increase the time in a time stamp.
1653 When nil, S-up will increase."
1654 :group 'org-time
1655 :type 'boolean)
1657 (defcustom org-calendar-follow-timestamp-change t
1658 "Non-nil means, make the calendar window follow timestamp changes.
1659 When a timestamp is modified and the calendar window is visible, it will be
1660 moved to the new date."
1661 :group 'org-time
1662 :type 'boolean)
1664 (defgroup org-tags nil
1665 "Options concerning tags in Org-mode."
1666 :tag "Org Tags"
1667 :group 'org)
1669 (defcustom org-tag-alist nil
1670 "List of tags allowed in Org-mode files.
1671 When this list is nil, Org-mode will base TAG input on what is already in the
1672 buffer.
1673 The value of this variable is an alist, the car of each entry must be a
1674 keyword as a string, the cdr may be a character that is used to select
1675 that tag through the fast-tag-selection interface.
1676 See the manual for details."
1677 :group 'org-tags
1678 :type '(repeat
1679 (choice
1680 (cons (string :tag "Tag name")
1681 (character :tag "Access char"))
1682 (const :tag "Start radio group" (:startgroup))
1683 (const :tag "End radio group" (:endgroup)))))
1685 (defcustom org-use-fast-tag-selection 'auto
1686 "Non-nil means, use fast tag selection scheme.
1687 This is a special interface to select and deselect tags with single keys.
1688 When nil, fast selection is never used.
1689 When the symbol `auto', fast selection is used if and only if selection
1690 characters for tags have been configured, either through the variable
1691 `org-tag-alist' or through a #+TAGS line in the buffer.
1692 When t, fast selection is always used and selection keys are assigned
1693 automatically if necessary."
1694 :group 'org-tags
1695 :type '(choice
1696 (const :tag "Always" t)
1697 (const :tag "Never" nil)
1698 (const :tag "When selection characters are configured" 'auto)))
1700 (defcustom org-fast-tag-selection-single-key nil
1701 "Non-nil means, fast tag selection exits after first change.
1702 When nil, you have to press RET to exit it.
1703 During fast tag selection, you can toggle this flag with `C-c'.
1704 This variable can also have the value `expert'. In this case, the window
1705 displaying the tags menu is not even shown, until you press C-c again."
1706 :group 'org-tags
1707 :type '(choice
1708 (const :tag "No" nil)
1709 (const :tag "Yes" t)
1710 (const :tag "Expert" expert)))
1712 (defvar org-fast-tag-selection-include-todo nil
1713 "Non-nil means, fast tags selection interface will also offer TODO states.
1714 This is an undocumented feature, you should not rely on it.")
1716 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1717 "The column to which tags should be indented in a headline.
1718 If this number is positive, it specifies the column. If it is negative,
1719 it means that the tags should be flushright to that column. For example,
1720 -80 works well for a normal 80 character screen."
1721 :group 'org-tags
1722 :type 'integer)
1724 (defcustom org-auto-align-tags t
1725 "Non-nil means, realign tags after pro/demotion of TODO state change.
1726 These operations change the length of a headline and therefore shift
1727 the tags around. With this options turned on, after each such operation
1728 the tags are again aligned to `org-tags-column'."
1729 :group 'org-tags
1730 :type 'boolean)
1732 (defcustom org-use-tag-inheritance t
1733 "Non-nil means, tags in levels apply also for sublevels.
1734 When nil, only the tags directly given in a specific line apply there.
1735 If you turn off this option, you very likely want to turn on the
1736 companion option `org-tags-match-list-sublevels'.
1738 This may also be a list of tags that should be inherited, or a regexp that
1739 matches tags that should be inherited."
1740 :group 'org-tags
1741 :type '(choice
1742 (const :tag "Not" nil)
1743 (const :tag "Always" t)
1744 (repeat :tag "Specific tags" (string :tag "Tag"))
1745 (regexp :tag "Tags matched by regexp")))
1747 (defun org-tag-inherit-p (tag)
1748 "Check if TAG is one that should be inherited."
1749 (cond
1750 ((eq org-use-tag-inheritance t) t)
1751 ((not org-use-tag-inheritance) nil)
1752 ((stringp org-use-tag-inheritance)
1753 (string-match org-use-tag-inheritance tag))
1754 ((listp org-use-tag-inheritance)
1755 (member tag org-use-tag-inheritance))
1756 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1758 (defcustom org-tags-match-list-sublevels nil
1759 "Non-nil means list also sublevels of headlines matching tag search.
1760 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1761 the sublevels of a headline matching a tag search often also match
1762 the same search. Listing all of them can create very long lists.
1763 Setting this variable to nil causes subtrees of a match to be skipped.
1764 This option is off by default, because inheritance in on. If you turn
1765 inheritance off, you very likely want to turn this option on.
1767 As a special case, if the tag search is restricted to TODO items, the
1768 value of this variable is ignored and sublevels are always checked, to
1769 make sure all corresponding TODO items find their way into the list."
1770 :group 'org-tags
1771 :type 'boolean)
1773 (defvar org-tags-history nil
1774 "History of minibuffer reads for tags.")
1775 (defvar org-last-tags-completion-table nil
1776 "The last used completion table for tags.")
1777 (defvar org-after-tags-change-hook nil
1778 "Hook that is run after the tags in a line have changed.")
1780 (defgroup org-properties nil
1781 "Options concerning properties in Org-mode."
1782 :tag "Org Properties"
1783 :group 'org)
1785 (defcustom org-property-format "%-10s %s"
1786 "How property key/value pairs should be formatted by `indent-line'.
1787 When `indent-line' hits a property definition, it will format the line
1788 according to this format, mainly to make sure that the values are
1789 lined-up with respect to each other."
1790 :group 'org-properties
1791 :type 'string)
1793 (defcustom org-use-property-inheritance nil
1794 "Non-nil means, properties apply also for sublevels.
1796 This setting is chiefly used during property searches. Turning it on can
1797 cause significant overhead when doing a search, which is why it is not
1798 on by default.
1800 When nil, only the properties directly given in the current entry count.
1801 When t, every property is inherited. The value may also be a list of
1802 properties that should have inheritance, or a regular expression matching
1803 properties that should be inherited.
1805 However, note that some special properties use inheritance under special
1806 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1807 and the properties ending in \"_ALL\" when they are used as descriptor
1808 for valid values of a property.
1810 Note for programmers:
1811 When querying an entry with `org-entry-get', you can control if inheritance
1812 should be used. By default, `org-entry-get' looks only at the local
1813 properties. You can request inheritance by setting the inherit argument
1814 to t (to force inheritance) or to `selective' (to respect the setting
1815 in this variable)."
1816 :group 'org-properties
1817 :type '(choice
1818 (const :tag "Not" nil)
1819 (const :tag "Always" t)
1820 (repeat :tag "Specific properties" (string :tag "Property"))
1821 (regexp :tag "Properties matched by regexp")))
1823 (defun org-property-inherit-p (property)
1824 "Check if PROPERTY is one that should be inherited."
1825 (cond
1826 ((eq org-use-property-inheritance t) t)
1827 ((not org-use-property-inheritance) nil)
1828 ((stringp org-use-property-inheritance)
1829 (string-match org-use-property-inheritance property))
1830 ((listp org-use-property-inheritance)
1831 (member property org-use-property-inheritance))
1832 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1834 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1835 "The default column format, if no other format has been defined.
1836 This variable can be set on the per-file basis by inserting a line
1838 #+COLUMNS: %25ITEM ....."
1839 :group 'org-properties
1840 :type 'string)
1842 (defcustom org-effort-property "Effort"
1843 "The property that is being used to keep track of effort estimates.
1844 Effort estimates given in this property need to have the format H:MM."
1845 :group 'org-properties
1846 :group 'org-progress
1847 :type '(string :tag "Property"))
1849 (defconst org-global-properties-fixed
1850 '(("VISIBILITY_ALL" . "folded children content all"))
1851 "List of property/value pairs that can be inherited by any entry.
1852 These are fixed values, for the preset properties.")
1855 (defcustom org-global-properties nil
1856 "List of property/value pairs that can be inherited by any entry.
1857 You can set buffer-local values for this by adding lines like
1859 #+PROPERTY: NAME VALUE"
1860 :group 'org-properties
1861 :type '(repeat
1862 (cons (string :tag "Property")
1863 (string :tag "Value"))))
1865 (defvar org-local-properties nil
1866 "List of property/value pairs that can be inherited by any entry.
1867 Valid for the current buffer.
1868 This variable is populated from #+PROPERTY lines.")
1870 (defgroup org-agenda nil
1871 "Options concerning agenda views in Org-mode."
1872 :tag "Org Agenda"
1873 :group 'org)
1875 (defvar org-category nil
1876 "Variable used by org files to set a category for agenda display.
1877 Such files should use a file variable to set it, for example
1879 # -*- mode: org; org-category: \"ELisp\"
1881 or contain a special line
1883 #+CATEGORY: ELisp
1885 If the file does not specify a category, then file's base name
1886 is used instead.")
1887 (make-variable-buffer-local 'org-category)
1889 (defcustom org-agenda-files nil
1890 "The files to be used for agenda display.
1891 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1892 \\[org-remove-file]. You can also use customize to edit the list.
1894 If an entry is a directory, all files in that directory that are matched by
1895 `org-agenda-file-regexp' will be part of the file list.
1897 If the value of the variable is not a list but a single file name, then
1898 the list of agenda files is actually stored and maintained in that file, one
1899 agenda file per line."
1900 :group 'org-agenda
1901 :type '(choice
1902 (repeat :tag "List of files and directories" file)
1903 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1905 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1906 "Regular expression to match files for `org-agenda-files'.
1907 If any element in the list in that variable contains a directory instead
1908 of a normal file, all files in that directory that are matched by this
1909 regular expression will be included."
1910 :group 'org-agenda
1911 :type 'regexp)
1913 (defcustom org-agenda-text-search-extra-files nil
1914 "List of extra files to be searched by text search commands.
1915 These files will be search in addition to the agenda files by the
1916 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1917 Note that these files will only be searched for text search commands,
1918 not for the other agenda views like todo lists, tag searches or the weekly
1919 agenda. This variable is intended to list notes and possibly archive files
1920 that should also be searched by these two commands.
1921 In fact, if the first element in the list is the symbol `agenda-archives',
1922 than all archive files of all agenda files will be added to the search
1923 scope."
1924 :group 'org-agenda
1925 :type '(set :greedy t
1926 (const :tag "Agenda Archives" agenda-archives)
1927 (repeat :inline t (file))))
1929 (if (fboundp 'defvaralias)
1930 (defvaralias 'org-agenda-multi-occur-extra-files
1931 'org-agenda-text-search-extra-files))
1933 (defcustom org-agenda-skip-unavailable-files nil
1934 "t means to just skip non-reachable files in `org-agenda-files'.
1935 Nil means to remove them, after a query, from the list."
1936 :group 'org-agenda
1937 :type 'boolean)
1939 (defcustom org-calendar-to-agenda-key [?c]
1940 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1941 The command `org-calendar-goto-agenda' will be bound to this key. The
1942 default is the character `c' because then `c' can be used to switch back and
1943 forth between agenda and calendar."
1944 :group 'org-agenda
1945 :type 'sexp)
1947 (eval-after-load "calendar"
1948 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1949 'org-calendar-goto-agenda))
1951 (defgroup org-latex nil
1952 "Options for embedding LaTeX code into Org-mode."
1953 :tag "Org LaTeX"
1954 :group 'org)
1956 (defcustom org-format-latex-options
1957 '(:foreground default :background default :scale 1.0
1958 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1959 :matchers ("begin" "$" "$$" "\\(" "\\["))
1960 "Options for creating images from LaTeX fragments.
1961 This is a property list with the following properties:
1962 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1963 `default' means use the forground of the default face.
1964 :background the background color, or \"Transparent\".
1965 `default' means use the background of the default face.
1966 :scale a scaling factor for the size of the images
1967 :html-foreground, :html-background, :html-scale
1968 The same numbers for HTML export.
1969 :matchers a list indicating which matchers should be used to
1970 find LaTeX fragments. Valid members of this list are:
1971 \"begin\" find environments
1972 \"$\" find math expressions surrounded by $...$
1973 \"$$\" find math expressions surrounded by $$....$$
1974 \"\\(\" find math expressions surrounded by \\(...\\)
1975 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1976 :group 'org-latex
1977 :type 'plist)
1979 (defcustom org-format-latex-header "\\documentclass{article}
1980 \\usepackage{fullpage} % do not remove
1981 \\usepackage{amssymb}
1982 \\usepackage[usenames]{color}
1983 \\usepackage{amsmath}
1984 \\usepackage{latexsym}
1985 \\usepackage[mathscr]{eucal}
1986 \\pagestyle{empty} % do not remove"
1987 "The document header used for processing LaTeX fragments."
1988 :group 'org-latex
1989 :type 'string)
1992 (defgroup org-font-lock nil
1993 "Font-lock settings for highlighting in Org-mode."
1994 :tag "Org Font Lock"
1995 :group 'org)
1997 (defcustom org-level-color-stars-only nil
1998 "Non-nil means fontify only the stars in each headline.
1999 When nil, the entire headline is fontified.
2000 Changing it requires restart of `font-lock-mode' to become effective
2001 also in regions already fontified."
2002 :group 'org-font-lock
2003 :type 'boolean)
2005 (defcustom org-hide-leading-stars nil
2006 "Non-nil means, hide the first N-1 stars in a headline.
2007 This works by using the face `org-hide' for these stars. This
2008 face is white for a light background, and black for a dark
2009 background. You may have to customize the face `org-hide' to
2010 make this work.
2011 Changing it requires restart of `font-lock-mode' to become effective
2012 also in regions already fontified.
2013 You may also set this on a per-file basis by adding one of the following
2014 lines to the buffer:
2016 #+STARTUP: hidestars
2017 #+STARTUP: showstars"
2018 :group 'org-font-lock
2019 :type 'boolean)
2021 (defcustom org-fontify-done-headline nil
2022 "Non-nil means, change the face of a headline if it is marked DONE.
2023 Normally, only the TODO/DONE keyword indicates the state of a headline.
2024 When this is non-nil, the headline after the keyword is set to the
2025 `org-headline-done' as an additional indication."
2026 :group 'org-font-lock
2027 :type 'boolean)
2029 (defcustom org-fontify-emphasized-text t
2030 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2031 Changing this variable requires a restart of Emacs to take effect."
2032 :group 'org-font-lock
2033 :type 'boolean)
2035 (defcustom org-highlight-latex-fragments-and-specials nil
2036 "Non-nil means, fontify what is treated specially by the exporters."
2037 :group 'org-font-lock
2038 :type 'boolean)
2040 (defcustom org-hide-emphasis-markers nil
2041 "Non-nil mean font-lock should hide the emphasis marker characters."
2042 :group 'org-font-lock
2043 :type 'boolean)
2045 (defvar org-emph-re nil
2046 "Regular expression for matching emphasis.")
2047 (defvar org-verbatim-re nil
2048 "Regular expression for matching verbatim text.")
2049 (defvar org-emphasis-regexp-components) ; defined just below
2050 (defvar org-emphasis-alist) ; defined just below
2051 (defun org-set-emph-re (var val)
2052 "Set variable and compute the emphasis regular expression."
2053 (set var val)
2054 (when (and (boundp 'org-emphasis-alist)
2055 (boundp 'org-emphasis-regexp-components)
2056 org-emphasis-alist org-emphasis-regexp-components)
2057 (let* ((e org-emphasis-regexp-components)
2058 (pre (car e))
2059 (post (nth 1 e))
2060 (border (nth 2 e))
2061 (body (nth 3 e))
2062 (nl (nth 4 e))
2063 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2064 (body1 (concat body "*?"))
2065 (markers (mapconcat 'car org-emphasis-alist ""))
2066 (vmarkers (mapconcat
2067 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2068 org-emphasis-alist "")))
2069 ;; make sure special characters appear at the right position in the class
2070 (if (string-match "\\^" markers)
2071 (setq markers (concat (replace-match "" t t markers) "^")))
2072 (if (string-match "-" markers)
2073 (setq markers (concat (replace-match "" t t markers) "-")))
2074 (if (string-match "\\^" vmarkers)
2075 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2076 (if (string-match "-" vmarkers)
2077 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2078 (if (> nl 0)
2079 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2080 (int-to-string nl) "\\}")))
2081 ;; Make the regexp
2082 (setq org-emph-re
2083 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2084 "\\("
2085 "\\([" markers "]\\)"
2086 "\\("
2087 "[^" border "]\\|"
2088 "[^" border (if (and nil stacked) markers) "]"
2089 body1
2090 "[^" border (if (and nil stacked) markers) "]"
2091 "\\)"
2092 "\\3\\)"
2093 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2094 (setq org-verbatim-re
2095 (concat "\\([" pre "]\\|^\\)"
2096 "\\("
2097 "\\([" vmarkers "]\\)"
2098 "\\("
2099 "[^" border "]\\|"
2100 "[^" border "]"
2101 body1
2102 "[^" border "]"
2103 "\\)"
2104 "\\3\\)"
2105 "\\([" post "]\\|$\\)")))))
2107 (defcustom org-emphasis-regexp-components
2108 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2109 "Components used to build the regular expression for emphasis.
2110 This is a list with 6 entries. Terminology: In an emphasis string
2111 like \" *strong word* \", we call the initial space PREMATCH, the final
2112 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2113 and \"trong wor\" is the body. The different components in this variable
2114 specify what is allowed/forbidden in each part:
2116 pre Chars allowed as prematch. Beginning of line will be allowed too.
2117 post Chars allowed as postmatch. End of line will be allowed too.
2118 border The chars *forbidden* as border characters.
2119 body-regexp A regexp like \".\" to match a body character. Don't use
2120 non-shy groups here, and don't allow newline here.
2121 newline The maximum number of newlines allowed in an emphasis exp.
2123 Use customize to modify this, or restart Emacs after changing it."
2124 :group 'org-font-lock
2125 :set 'org-set-emph-re
2126 :type '(list
2127 (sexp :tag "Allowed chars in pre ")
2128 (sexp :tag "Allowed chars in post ")
2129 (sexp :tag "Forbidden chars in border ")
2130 (sexp :tag "Regexp for body ")
2131 (integer :tag "number of newlines allowed")
2132 (option (boolean :tag "Stacking (DISABLED) "))))
2134 (defcustom org-emphasis-alist
2135 `(("*" bold "<b>" "</b>")
2136 ("/" italic "<i>" "</i>")
2137 ("_" underline "<u>" "</u>")
2138 ("=" org-code "<code>" "</code>" verbatim)
2139 ("~" org-verbatim "" "" verbatim)
2140 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2141 "<del>" "</del>")
2143 "Special syntax for emphasized text.
2144 Text starting and ending with a special character will be emphasized, for
2145 example *bold*, _underlined_ and /italic/. This variable sets the marker
2146 characters, the face to be used by font-lock for highlighting in Org-mode
2147 Emacs buffers, and the HTML tags to be used for this.
2148 Use customize to modify this, or restart Emacs after changing it."
2149 :group 'org-font-lock
2150 :set 'org-set-emph-re
2151 :type '(repeat
2152 (list
2153 (string :tag "Marker character")
2154 (choice
2155 (face :tag "Font-lock-face")
2156 (plist :tag "Face property list"))
2157 (string :tag "HTML start tag")
2158 (string :tag "HTML end tag")
2159 (option (const verbatim)))))
2161 ;;; Miscellaneous options
2163 (defgroup org-completion nil
2164 "Completion in Org-mode."
2165 :tag "Org Completion"
2166 :group 'org)
2168 (defcustom org-completion-fallback-command 'hippie-expand
2169 "The expansion command called by \\[org-complete] in normal context.
2170 Normal means, no org-mode-specific context."
2171 :group 'org-completion
2172 :type 'function)
2174 ;;; Functions and variables from ther packages
2175 ;; Declared here to avoid compiler warnings
2177 ;; XEmacs only
2178 (defvar outline-mode-menu-heading)
2179 (defvar outline-mode-menu-show)
2180 (defvar outline-mode-menu-hide)
2181 (defvar zmacs-regions) ; XEmacs regions
2183 ;; Emacs only
2184 (defvar mark-active)
2186 ;; Various packages
2187 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2188 (declare-function calendar-forward-day "cal-move" (arg))
2189 (declare-function calendar-goto-date "cal-move" (date))
2190 (declare-function calendar-goto-today "cal-move" ())
2191 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2192 (defvar calc-embedded-close-formula)
2193 (defvar calc-embedded-open-formula)
2194 (declare-function cdlatex-tab "ext:cdlatex" ())
2195 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2196 (defvar font-lock-unfontify-region-function)
2197 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2198 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2199 (defvar iswitchb-temp-buflist)
2200 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2201 (declare-function org-agenda-skip "org-agenda" ())
2202 (declare-function org-format-agenda-item "org-agenda"
2203 (extra txt &optional category tags dotime noprefix remove-re))
2204 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2205 (declare-function org-agenda-change-all-lines "org-agenda"
2206 (newhead hdmarker &optional fixface))
2207 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2208 (declare-function org-agenda-maybe-redo "org-agenda" ())
2209 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2210 (beg end))
2211 (declare-function parse-time-string "parse-time" (string))
2212 (declare-function remember "remember" (&optional initial))
2213 (declare-function remember-buffer-desc "remember" ())
2214 (declare-function remember-finalize "remember" ())
2215 (defvar remember-save-after-remembering)
2216 (defvar remember-data-file)
2217 (defvar remember-register)
2218 (defvar remember-buffer)
2219 (defvar remember-handler-functions)
2220 (defvar remember-annotation-functions)
2221 (defvar texmathp-why)
2222 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2223 (declare-function table--at-cell-p "table" (position &optional object at-column))
2225 (defvar w3m-current-url)
2226 (defvar w3m-current-title)
2228 (defvar org-latex-regexps)
2230 ;;; Autoload and prepare some org modules
2232 ;; Some table stuff that needs to be defined here, because it is used
2233 ;; by the functions setting up org-mode or checking for table context.
2235 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2236 "Detects an org-type or table-type table.")
2237 (defconst org-table-line-regexp "^[ \t]*|"
2238 "Detects an org-type table line.")
2239 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2240 "Detects an org-type table line.")
2241 (defconst org-table-hline-regexp "^[ \t]*|-"
2242 "Detects an org-type table hline.")
2243 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2244 "Detects a table-type table hline.")
2245 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2246 "Searching from within a table (any type) this finds the first line
2247 outside the table.")
2249 ;; Autoload the functions in org-table.el that are needed by functions here.
2251 (eval-and-compile
2252 (org-autoload "org-table"
2253 '(org-table-align org-table-begin org-table-blank-field
2254 org-table-convert org-table-convert-region org-table-copy-down
2255 org-table-copy-region org-table-create
2256 org-table-create-or-convert-from-region
2257 org-table-create-with-table.el org-table-current-dline
2258 org-table-cut-region org-table-delete-column org-table-edit-field
2259 org-table-edit-formulas org-table-end org-table-eval-formula
2260 org-table-export org-table-field-info
2261 org-table-get-stored-formulas org-table-goto-column
2262 org-table-hline-and-move org-table-import org-table-insert-column
2263 org-table-insert-hline org-table-insert-row org-table-iterate
2264 org-table-justify-field-maybe org-table-kill-row
2265 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2266 org-table-move-column org-table-move-column-left
2267 org-table-move-column-right org-table-move-row
2268 org-table-move-row-down org-table-move-row-up
2269 org-table-next-field org-table-next-row org-table-paste-rectangle
2270 org-table-previous-field org-table-recalculate
2271 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2272 org-table-toggle-coordinate-overlays
2273 org-table-toggle-formula-debugger org-table-wrap-region
2274 orgtbl-mode turn-on-orgtbl)))
2276 (defun org-at-table-p (&optional table-type)
2277 "Return t if the cursor is inside an org-type table.
2278 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2279 (if org-enable-table-editor
2280 (save-excursion
2281 (beginning-of-line 1)
2282 (looking-at (if table-type org-table-any-line-regexp
2283 org-table-line-regexp)))
2284 nil))
2285 (defsubst org-table-p () (org-at-table-p))
2287 (defun org-at-table.el-p ()
2288 "Return t if and only if we are at a table.el table."
2289 (and (org-at-table-p 'any)
2290 (save-excursion
2291 (goto-char (org-table-begin 'any))
2292 (looking-at org-table1-hline-regexp))))
2293 (defun org-table-recognize-table.el ()
2294 "If there is a table.el table nearby, recognize it and move into it."
2295 (if org-table-tab-recognizes-table.el
2296 (if (org-at-table.el-p)
2297 (progn
2298 (beginning-of-line 1)
2299 (if (looking-at org-table-dataline-regexp)
2301 (if (looking-at org-table1-hline-regexp)
2302 (progn
2303 (beginning-of-line 2)
2304 (if (looking-at org-table-any-border-regexp)
2305 (beginning-of-line -1)))))
2306 (if (re-search-forward "|" (org-table-end t) t)
2307 (progn
2308 (require 'table)
2309 (if (table--at-cell-p (point))
2311 (message "recognizing table.el table...")
2312 (table-recognize-table)
2313 (message "recognizing table.el table...done")))
2314 (error "This should not happen..."))
2316 nil)
2317 nil))
2319 (defun org-at-table-hline-p ()
2320 "Return t if the cursor is inside a hline in a table."
2321 (if org-enable-table-editor
2322 (save-excursion
2323 (beginning-of-line 1)
2324 (looking-at org-table-hline-regexp))
2325 nil))
2327 (defvar org-table-clean-did-remove-column nil)
2329 (defun org-table-map-tables (function)
2330 "Apply FUNCTION to the start of all tables in the buffer."
2331 (save-excursion
2332 (save-restriction
2333 (widen)
2334 (goto-char (point-min))
2335 (while (re-search-forward org-table-any-line-regexp nil t)
2336 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2337 (beginning-of-line 1)
2338 (if (looking-at org-table-line-regexp)
2339 (save-excursion (funcall function)))
2340 (re-search-forward org-table-any-border-regexp nil 1))))
2341 (message "Mapping tables: done"))
2343 ;; Declare and autoload functions from org-exp.el
2345 (declare-function org-default-export-plist "org-exp")
2346 (declare-function org-infile-export-plist "org-exp")
2347 (declare-function org-get-current-options "org-exp")
2348 (eval-and-compile
2349 (org-autoload "org-exp"
2350 '(org-export org-export-as-ascii org-export-visible
2351 org-insert-export-options-template org-export-as-html-and-open
2352 org-export-as-html-batch org-export-as-html-to-buffer
2353 org-replace-region-by-html org-export-region-as-html
2354 org-export-as-html org-export-icalendar-this-file
2355 org-export-icalendar-all-agenda-files
2356 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2358 ;; Declare and autoload functions from org-exp.el
2360 (eval-and-compile
2361 (org-autoload "org-exp"
2362 '(org-agenda org-agenda-list org-search-view
2363 org-todo-list org-tags-view org-agenda-list-stuck-projects
2364 org-diary org-agenda-to-appt)))
2366 ;; Autoload org-remember
2368 (eval-and-compile
2369 (org-autoload "org-remember"
2370 '(org-remember-insinuate org-remember-annotation
2371 org-remember-apply-template org-remember org-remember-handler)))
2373 ;; Autoload org-clock.el
2376 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2377 (beg end))
2378 (defvar org-clock-marker (make-marker)
2379 "Marker recording the last clock-in.")
2381 (eval-and-compile
2382 (org-autoload
2383 "org-clock"
2384 '(org-clock-in org-clock-out org-clock-cancel
2385 org-clock-goto org-clock-sum org-clock-display
2386 org-remove-clock-overlays org-clock-report
2387 org-clocktable-shift org-dblock-write:clocktable
2388 org-get-clocktable)))
2390 (defun org-clock-update-time-maybe ()
2391 "If this is a CLOCK line, update it and return t.
2392 Otherwise, return nil."
2393 (interactive)
2394 (save-excursion
2395 (beginning-of-line 1)
2396 (skip-chars-forward " \t")
2397 (when (looking-at org-clock-string)
2398 (let ((re (concat "[ \t]*" org-clock-string
2399 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2400 "\\([ \t]*=>.*\\)?"))
2401 ts te h m s)
2402 (if (not (looking-at re))
2404 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2405 (end-of-line 1)
2406 (setq ts (match-string 1)
2407 te (match-string 2))
2408 (setq s (- (time-to-seconds
2409 (apply 'encode-time (org-parse-time-string te)))
2410 (time-to-seconds
2411 (apply 'encode-time (org-parse-time-string ts))))
2412 h (floor (/ s 3600))
2413 s (- s (* 3600 h))
2414 m (floor (/ s 60))
2415 s (- s (* 60 s)))
2416 (insert " => " (format "%2d:%02d" h m))
2417 t)))))
2419 (defun org-check-running-clock ()
2420 "Check if the current buffer contains the running clock.
2421 If yes, offer to stop it and to save the buffer with the changes."
2422 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2423 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2424 (buffer-name))))
2425 (org-clock-out)
2426 (when (y-or-n-p "Save changed buffer?")
2427 (save-buffer))))
2429 (defun org-clocktable-try-shift (dir n)
2430 "Check if this line starts a clock table, if yes, shift the time block."
2431 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2432 (org-clocktable-shift dir n)))
2434 ;; Autoload archiving code
2435 ;; The stuff that is needed for cycling and tags has to be defined here.
2437 (defgroup org-archive nil
2438 "Options concerning archiving in Org-mode."
2439 :tag "Org Archive"
2440 :group 'org-structure)
2442 (defcustom org-archive-location "%s_archive::"
2443 "The location where subtrees should be archived.
2445 Otherwise, the value of this variable is a string, consisting of two
2446 parts, separated by a double-colon.
2448 The first part is a file name - when omitted, archiving happens in the same
2449 file. %s will be replaced by the current file name (without directory part).
2450 Archiving to a different file is useful to keep archived entries from
2451 contributing to the Org-mode Agenda.
2453 The part after the double colon is a headline. The archived entries will be
2454 filed under that headline. When omitted, the subtrees are simply filed away
2455 at the end of the file, as top-level entries.
2457 Here are a few examples:
2458 \"%s_archive::\"
2459 If the current file is Projects.org, archive in file
2460 Projects.org_archive, as top-level trees. This is the default.
2462 \"::* Archived Tasks\"
2463 Archive in the current file, under the top-level headline
2464 \"* Archived Tasks\".
2466 \"~/org/archive.org::\"
2467 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2469 \"basement::** Finished Tasks\"
2470 Archive in file ./basement (relative path), as level 3 trees
2471 below the level 2 heading \"** Finished Tasks\".
2473 You may set this option on a per-file basis by adding to the buffer a
2474 line like
2476 #+ARCHIVE: basement::** Finished Tasks
2478 You may also define it locally for a subtree by setting an ARCHIVE property
2479 in the entry. If such a property is found in an entry, or anywhere up
2480 the hierarchy, it will be used."
2481 :group 'org-archive
2482 :type 'string)
2484 (defcustom org-archive-tag "ARCHIVE"
2485 "The tag that marks a subtree as archived.
2486 An archived subtree does not open during visibility cycling, and does
2487 not contribute to the agenda listings.
2488 After changing this, font-lock must be restarted in the relevant buffers to
2489 get the proper fontification."
2490 :group 'org-archive
2491 :group 'org-keywords
2492 :type 'string)
2494 (defcustom org-agenda-skip-archived-trees t
2495 "Non-nil means, the agenda will skip any items located in archived trees.
2496 An archived tree is a tree marked with the tag ARCHIVE."
2497 :group 'org-archive
2498 :group 'org-agenda-skip
2499 :type 'boolean)
2501 (defcustom org-cycle-open-archived-trees nil
2502 "Non-nil means, `org-cycle' will open archived trees.
2503 An archived tree is a tree marked with the tag ARCHIVE.
2504 When nil, archived trees will stay folded. You can still open them with
2505 normal outline commands like `show-all', but not with the cycling commands."
2506 :group 'org-archive
2507 :group 'org-cycle
2508 :type 'boolean)
2510 (defcustom org-sparse-tree-open-archived-trees nil
2511 "Non-nil means sparse tree construction shows matches in archived trees.
2512 When nil, matches in these trees are highlighted, but the trees are kept in
2513 collapsed state."
2514 :group 'org-archive
2515 :group 'org-sparse-trees
2516 :type 'boolean)
2518 (defun org-cycle-hide-archived-subtrees (state)
2519 "Re-hide all archived subtrees after a visibility state change."
2520 (when (and (not org-cycle-open-archived-trees)
2521 (not (memq state '(overview folded))))
2522 (save-excursion
2523 (let* ((globalp (memq state '(contents all)))
2524 (beg (if globalp (point-min) (point)))
2525 (end (if globalp (point-max) (org-end-of-subtree t))))
2526 (org-hide-archived-subtrees beg end)
2527 (goto-char beg)
2528 (if (looking-at (concat ".*:" org-archive-tag ":"))
2529 (message "%s" (substitute-command-keys
2530 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2532 (defun org-force-cycle-archived ()
2533 "Cycle subtree even if it is archived."
2534 (interactive)
2535 (setq this-command 'org-cycle)
2536 (let ((org-cycle-open-archived-trees t))
2537 (call-interactively 'org-cycle)))
2539 (defun org-hide-archived-subtrees (beg end)
2540 "Re-hide all archived subtrees after a visibility state change."
2541 (save-excursion
2542 (let* ((re (concat ":" org-archive-tag ":")))
2543 (goto-char beg)
2544 (while (re-search-forward re end t)
2545 (and (org-on-heading-p) (hide-subtree))
2546 (org-end-of-subtree t)))))
2548 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2550 (eval-and-compile
2551 (org-autoload "org-archive"
2552 '(org-add-archive-files org-archive-subtree
2553 org-archive-to-archive-sibling org-toggle-archive-tag)))
2555 ;; Autoload Column View Code
2557 (declare-function org-columns-number-to-string "org-colview")
2558 (declare-function org-columns-get-format-and-top-level "org-colview")
2559 (declare-function org-columns-compute "org-colview")
2561 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2562 '(org-columns-number-to-string org-columns-get-format-and-top-level
2563 org-columns-compute org-agenda-columns org-columns-remove-overlays
2564 org-columns org-insert-columns-dblock))
2566 ;;; Variables for pre-computed regular expressions, all buffer local
2568 (defvar org-drawer-regexp nil
2569 "Matches first line of a hidden block.")
2570 (make-variable-buffer-local 'org-drawer-regexp)
2571 (defvar org-todo-regexp nil
2572 "Matches any of the TODO state keywords.")
2573 (make-variable-buffer-local 'org-todo-regexp)
2574 (defvar org-not-done-regexp nil
2575 "Matches any of the TODO state keywords except the last one.")
2576 (make-variable-buffer-local 'org-not-done-regexp)
2577 (defvar org-todo-line-regexp nil
2578 "Matches a headline and puts TODO state into group 2 if present.")
2579 (make-variable-buffer-local 'org-todo-line-regexp)
2580 (defvar org-complex-heading-regexp nil
2581 "Matches a headline and puts everything into groups:
2582 group 1: the stars
2583 group 2: The todo keyword, maybe
2584 group 3: Priority cookie
2585 group 4: True headline
2586 group 5: Tags")
2587 (make-variable-buffer-local 'org-complex-heading-regexp)
2588 (defvar org-todo-line-tags-regexp nil
2589 "Matches a headline and puts TODO state into group 2 if present.
2590 Also put tags into group 4 if tags are present.")
2591 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2592 (defvar org-nl-done-regexp nil
2593 "Matches newline followed by a headline with the DONE keyword.")
2594 (make-variable-buffer-local 'org-nl-done-regexp)
2595 (defvar org-looking-at-done-regexp nil
2596 "Matches the DONE keyword a point.")
2597 (make-variable-buffer-local 'org-looking-at-done-regexp)
2598 (defvar org-ds-keyword-length 12
2599 "Maximum length of the Deadline and SCHEDULED keywords.")
2600 (make-variable-buffer-local 'org-ds-keyword-length)
2601 (defvar org-deadline-regexp nil
2602 "Matches the DEADLINE keyword.")
2603 (make-variable-buffer-local 'org-deadline-regexp)
2604 (defvar org-deadline-time-regexp nil
2605 "Matches the DEADLINE keyword together with a time stamp.")
2606 (make-variable-buffer-local 'org-deadline-time-regexp)
2607 (defvar org-deadline-line-regexp nil
2608 "Matches the DEADLINE keyword and the rest of the line.")
2609 (make-variable-buffer-local 'org-deadline-line-regexp)
2610 (defvar org-scheduled-regexp nil
2611 "Matches the SCHEDULED keyword.")
2612 (make-variable-buffer-local 'org-scheduled-regexp)
2613 (defvar org-scheduled-time-regexp nil
2614 "Matches the SCHEDULED keyword together with a time stamp.")
2615 (make-variable-buffer-local 'org-scheduled-time-regexp)
2616 (defvar org-closed-time-regexp nil
2617 "Matches the CLOSED keyword together with a time stamp.")
2618 (make-variable-buffer-local 'org-closed-time-regexp)
2620 (defvar org-keyword-time-regexp nil
2621 "Matches any of the 4 keywords, together with the time stamp.")
2622 (make-variable-buffer-local 'org-keyword-time-regexp)
2623 (defvar org-keyword-time-not-clock-regexp nil
2624 "Matches any of the 3 keywords, together with the time stamp.")
2625 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2626 (defvar org-maybe-keyword-time-regexp nil
2627 "Matches a timestamp, possibly preceeded by a keyword.")
2628 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2629 (defvar org-planning-or-clock-line-re nil
2630 "Matches a line with planning or clock info.")
2631 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2633 (defconst org-plain-time-of-day-regexp
2634 (concat
2635 "\\(\\<[012]?[0-9]"
2636 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2637 "\\(--?"
2638 "\\(\\<[012]?[0-9]"
2639 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2640 "\\)?")
2641 "Regular expression to match a plain time or time range.
2642 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2643 groups carry important information:
2644 0 the full match
2645 1 the first time, range or not
2646 8 the second time, if it is a range.")
2648 (defconst org-plain-time-extension-regexp
2649 (concat
2650 "\\(\\<[012]?[0-9]"
2651 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2652 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2653 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2654 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2655 groups carry important information:
2656 0 the full match
2657 7 hours of duration
2658 9 minutes of duration")
2660 (defconst org-stamp-time-of-day-regexp
2661 (concat
2662 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2663 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2664 "\\(--?"
2665 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2666 "Regular expression to match a timestamp time or time range.
2667 After a match, the following groups carry important information:
2668 0 the full match
2669 1 date plus weekday, for backreferencing to make sure both times on same day
2670 2 the first time, range or not
2671 4 the second time, if it is a range.")
2673 (defconst org-startup-options
2674 '(("fold" org-startup-folded t)
2675 ("overview" org-startup-folded t)
2676 ("nofold" org-startup-folded nil)
2677 ("showall" org-startup-folded nil)
2678 ("content" org-startup-folded content)
2679 ("hidestars" org-hide-leading-stars t)
2680 ("showstars" org-hide-leading-stars nil)
2681 ("odd" org-odd-levels-only t)
2682 ("oddeven" org-odd-levels-only nil)
2683 ("align" org-startup-align-all-tables t)
2684 ("noalign" org-startup-align-all-tables nil)
2685 ("customtime" org-display-custom-times t)
2686 ("logdone" org-log-done time)
2687 ("lognotedone" org-log-done note)
2688 ("nologdone" org-log-done nil)
2689 ("lognoteclock-out" org-log-note-clock-out t)
2690 ("nolognoteclock-out" org-log-note-clock-out nil)
2691 ("logrepeat" org-log-repeat state)
2692 ("lognoterepeat" org-log-repeat note)
2693 ("nologrepeat" org-log-repeat nil)
2694 ("constcgs" constants-unit-system cgs)
2695 ("constSI" constants-unit-system SI))
2696 "Variable associated with STARTUP options for org-mode.
2697 Each element is a list of three items: The startup options as written
2698 in the #+STARTUP line, the corresponding variable, and the value to
2699 set this variable to if the option is found. An optional forth element PUSH
2700 means to push this value onto the list in the variable.")
2702 (defun org-set-regexps-and-options ()
2703 "Precompute regular expressions for current buffer."
2704 (when (org-mode-p)
2705 (org-set-local 'org-todo-kwd-alist nil)
2706 (org-set-local 'org-todo-key-alist nil)
2707 (org-set-local 'org-todo-key-trigger nil)
2708 (org-set-local 'org-todo-keywords-1 nil)
2709 (org-set-local 'org-done-keywords nil)
2710 (org-set-local 'org-todo-heads nil)
2711 (org-set-local 'org-todo-sets nil)
2712 (org-set-local 'org-todo-log-states nil)
2713 (let ((re (org-make-options-regexp
2714 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2715 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2716 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2717 (splitre "[ \t]+")
2718 kwds kws0 kwsa key log value cat arch tags const links hw dws
2719 tail sep kws1 prio props drawers
2720 ext-setup-or-nil setup-contents (start 0))
2721 (save-excursion
2722 (save-restriction
2723 (widen)
2724 (goto-char (point-min))
2725 (while (or (and ext-setup-or-nil
2726 (string-match re ext-setup-or-nil start)
2727 (setq start (match-end 0)))
2728 (and (setq ext-setup-or-nil nil start 0)
2729 (re-search-forward re nil t)))
2730 (setq key (upcase (match-string 1 ext-setup-or-nil))
2731 value (org-match-string-no-properties 2 ext-setup-or-nil))
2732 (cond
2733 ((equal key "CATEGORY")
2734 (if (string-match "[ \t]+$" value)
2735 (setq value (replace-match "" t t value)))
2736 (setq cat value))
2737 ((member key '("SEQ_TODO" "TODO"))
2738 (push (cons 'sequence (org-split-string value splitre)) kwds))
2739 ((equal key "TYP_TODO")
2740 (push (cons 'type (org-split-string value splitre)) kwds))
2741 ((equal key "TAGS")
2742 (setq tags (append tags (org-split-string value splitre))))
2743 ((equal key "COLUMNS")
2744 (org-set-local 'org-columns-default-format value))
2745 ((equal key "LINK")
2746 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2747 (push (cons (match-string 1 value)
2748 (org-trim (match-string 2 value)))
2749 links)))
2750 ((equal key "PRIORITIES")
2751 (setq prio (org-split-string value " +")))
2752 ((equal key "PROPERTY")
2753 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2754 (push (cons (match-string 1 value) (match-string 2 value))
2755 props)))
2756 ((equal key "DRAWERS")
2757 (setq drawers (org-split-string value splitre)))
2758 ((equal key "CONSTANTS")
2759 (setq const (append const (org-split-string value splitre))))
2760 ((equal key "STARTUP")
2761 (let ((opts (org-split-string value splitre))
2762 l var val)
2763 (while (setq l (pop opts))
2764 (when (setq l (assoc l org-startup-options))
2765 (setq var (nth 1 l) val (nth 2 l))
2766 (if (not (nth 3 l))
2767 (set (make-local-variable var) val)
2768 (if (not (listp (symbol-value var)))
2769 (set (make-local-variable var) nil))
2770 (set (make-local-variable var) (symbol-value var))
2771 (add-to-list var val))))))
2772 ((equal key "ARCHIVE")
2773 (string-match " *$" value)
2774 (setq arch (replace-match "" t t value))
2775 (remove-text-properties 0 (length arch)
2776 '(face t fontified t) arch))
2777 ((equal key "SETUPFILE")
2778 (setq setup-contents (org-file-contents
2779 (expand-file-name
2780 (org-remove-double-quotes value))
2781 'noerror))
2782 (if (not ext-setup-or-nil)
2783 (setq ext-setup-or-nil setup-contents start 0)
2784 (setq ext-setup-or-nil
2785 (concat (substring ext-setup-or-nil 0 start)
2786 "\n" setup-contents "\n"
2787 (substring ext-setup-or-nil start)))))
2788 ))))
2789 (when cat
2790 (org-set-local 'org-category (intern cat))
2791 (push (cons "CATEGORY" cat) props))
2792 (when prio
2793 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2794 (setq prio (mapcar 'string-to-char prio))
2795 (org-set-local 'org-highest-priority (nth 0 prio))
2796 (org-set-local 'org-lowest-priority (nth 1 prio))
2797 (org-set-local 'org-default-priority (nth 2 prio)))
2798 (and props (org-set-local 'org-local-properties (nreverse props)))
2799 (and drawers (org-set-local 'org-drawers drawers))
2800 (and arch (org-set-local 'org-archive-location arch))
2801 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2802 ;; Process the TODO keywords
2803 (unless kwds
2804 ;; Use the global values as if they had been given locally.
2805 (setq kwds (default-value 'org-todo-keywords))
2806 (if (stringp (car kwds))
2807 (setq kwds (list (cons org-todo-interpretation
2808 (default-value 'org-todo-keywords)))))
2809 (setq kwds (reverse kwds)))
2810 (setq kwds (nreverse kwds))
2811 (let (inter kws kw)
2812 (while (setq kws (pop kwds))
2813 (setq inter (pop kws) sep (member "|" kws)
2814 kws0 (delete "|" (copy-sequence kws))
2815 kwsa nil
2816 kws1 (mapcar
2817 (lambda (x)
2818 ;; 1 2
2819 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2820 (progn
2821 (setq kw (match-string 1 x)
2822 key (and (match-end 2) (match-string 2 x))
2823 log (org-extract-log-state-settings x))
2824 (push (cons kw (and key (string-to-char key))) kwsa)
2825 (and log (push log org-todo-log-states))
2827 (error "Invalid TODO keyword %s" x)))
2828 kws0)
2829 kwsa (if kwsa (append '((:startgroup))
2830 (nreverse kwsa)
2831 '((:endgroup))))
2832 hw (car kws1)
2833 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2834 tail (list inter hw (car dws) (org-last dws)))
2835 (add-to-list 'org-todo-heads hw 'append)
2836 (push kws1 org-todo-sets)
2837 (setq org-done-keywords (append org-done-keywords dws nil))
2838 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2839 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2840 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2841 (setq org-todo-sets (nreverse org-todo-sets)
2842 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2843 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2844 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2845 ;; Process the constants
2846 (when const
2847 (let (e cst)
2848 (while (setq e (pop const))
2849 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2850 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2851 (setq org-table-formula-constants-local cst)))
2853 ;; Process the tags.
2854 (when tags
2855 (let (e tgs)
2856 (while (setq e (pop tags))
2857 (cond
2858 ((equal e "{") (push '(:startgroup) tgs))
2859 ((equal e "}") (push '(:endgroup) tgs))
2860 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2861 (push (cons (match-string 1 e)
2862 (string-to-char (match-string 2 e)))
2863 tgs))
2864 (t (push (list e) tgs))))
2865 (org-set-local 'org-tag-alist nil)
2866 (while (setq e (pop tgs))
2867 (or (and (stringp (car e))
2868 (assoc (car e) org-tag-alist))
2869 (push e org-tag-alist))))))
2871 ;; Compute the regular expressions and other local variables
2872 (if (not org-done-keywords)
2873 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2874 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2875 (length org-scheduled-string)
2876 (length org-clock-string)
2877 (length org-closed-string)))
2878 org-drawer-regexp
2879 (concat "^[ \t]*:\\("
2880 (mapconcat 'regexp-quote org-drawers "\\|")
2881 "\\):[ \t]*$")
2882 org-not-done-keywords
2883 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2884 org-todo-regexp
2885 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2886 "\\|") "\\)\\>")
2887 org-not-done-regexp
2888 (concat "\\<\\("
2889 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2890 "\\)\\>")
2891 org-todo-line-regexp
2892 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2893 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2894 "\\)\\>\\)?[ \t]*\\(.*\\)")
2895 org-complex-heading-regexp
2896 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2897 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2898 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2899 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2900 org-nl-done-regexp
2901 (concat "\n\\*+[ \t]+"
2902 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2903 "\\)" "\\>")
2904 org-todo-line-tags-regexp
2905 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2906 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2907 (org-re
2908 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2909 org-looking-at-done-regexp
2910 (concat "^" "\\(?:"
2911 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2912 "\\>")
2913 org-deadline-regexp (concat "\\<" org-deadline-string)
2914 org-deadline-time-regexp
2915 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2916 org-deadline-line-regexp
2917 (concat "\\<\\(" org-deadline-string "\\).*")
2918 org-scheduled-regexp
2919 (concat "\\<" org-scheduled-string)
2920 org-scheduled-time-regexp
2921 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2922 org-closed-time-regexp
2923 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2924 org-keyword-time-regexp
2925 (concat "\\<\\(" org-scheduled-string
2926 "\\|" org-deadline-string
2927 "\\|" org-closed-string
2928 "\\|" org-clock-string "\\)"
2929 " *[[<]\\([^]>]+\\)[]>]")
2930 org-keyword-time-not-clock-regexp
2931 (concat "\\<\\(" org-scheduled-string
2932 "\\|" org-deadline-string
2933 "\\|" org-closed-string
2934 "\\)"
2935 " *[[<]\\([^]>]+\\)[]>]")
2936 org-maybe-keyword-time-regexp
2937 (concat "\\(\\<\\(" org-scheduled-string
2938 "\\|" org-deadline-string
2939 "\\|" org-closed-string
2940 "\\|" org-clock-string "\\)\\)?"
2941 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2942 org-planning-or-clock-line-re
2943 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2944 "\\|" org-deadline-string
2945 "\\|" org-closed-string "\\|" org-clock-string
2946 "\\)\\>\\)")
2948 (org-compute-latex-and-specials-regexp)
2949 (org-set-font-lock-defaults)))
2951 (defun org-file-contents (file &optional noerror)
2952 "Return the contents of FILE, as a string."
2953 (if (or (not file)
2954 (not (file-readable-p file)))
2955 (if noerror
2956 (progn
2957 (message "Cannot read file %s" file)
2958 (ding) (sit-for 2)
2960 (error "Cannot read file %s" file))
2961 (with-temp-buffer
2962 (insert-file-contents file)
2963 (buffer-string))))
2965 (defun org-extract-log-state-settings (x)
2966 "Extract the log state setting from a TODO keyword string.
2967 This will extract info from a string like \"WAIT(w@/!)\"."
2968 (let (kw key log1 log2)
2969 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2970 (setq kw (match-string 1 x)
2971 key (and (match-end 2) (match-string 2 x))
2972 log1 (and (match-end 3) (match-string 3 x))
2973 log2 (and (match-end 4) (match-string 4 x)))
2974 (and (or log1 log2)
2975 (list kw
2976 (and log1 (if (equal log1 "!") 'time 'note))
2977 (and log2 (if (equal log2 "!") 'time 'note)))))))
2979 (defun org-remove-keyword-keys (list)
2980 "Remove a pair of parenthesis at the end of each string in LIST."
2981 (mapcar (lambda (x)
2982 (if (string-match "(.*)$" x)
2983 (substring x 0 (match-beginning 0))
2985 list))
2987 ;; FIXME: this could be done much better, using second characters etc.
2988 (defun org-assign-fast-keys (alist)
2989 "Assign fast keys to a keyword-key alist.
2990 Respect keys that are already there."
2991 (let (new e k c c1 c2 (char ?a))
2992 (while (setq e (pop alist))
2993 (cond
2994 ((equal e '(:startgroup)) (push e new))
2995 ((equal e '(:endgroup)) (push e new))
2997 (setq k (car e) c2 nil)
2998 (if (cdr e)
2999 (setq c (cdr e))
3000 ;; automatically assign a character.
3001 (setq c1 (string-to-char
3002 (downcase (substring
3003 k (if (= (string-to-char k) ?@) 1 0)))))
3004 (if (or (rassoc c1 new) (rassoc c1 alist))
3005 (while (or (rassoc char new) (rassoc char alist))
3006 (setq char (1+ char)))
3007 (setq c2 c1))
3008 (setq c (or c2 char)))
3009 (push (cons k c) new))))
3010 (nreverse new)))
3012 ;;; Some variables used in various places
3014 (defvar org-window-configuration nil
3015 "Used in various places to store a window configuration.")
3016 (defvar org-finish-function nil
3017 "Function to be called when `C-c C-c' is used.
3018 This is for getting out of special buffers like remember.")
3021 ;; FIXME: Occasionally check by commenting these, to make sure
3022 ;; no other functions uses these, forgetting to let-bind them.
3023 (defvar entry)
3024 (defvar state)
3025 (defvar last-state)
3026 (defvar date)
3027 (defvar description)
3029 ;; Defined somewhere in this file, but used before definition.
3030 (defvar org-html-entities)
3031 (defvar org-struct-menu)
3032 (defvar org-org-menu)
3033 (defvar org-tbl-menu)
3034 (defvar org-agenda-keymap)
3036 ;;;; Define the Org-mode
3038 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3039 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
3042 ;; We use a before-change function to check if a table might need
3043 ;; an update.
3044 (defvar org-table-may-need-update t
3045 "Indicates that a table might need an update.
3046 This variable is set by `org-before-change-function'.
3047 `org-table-align' sets it back to nil.")
3048 (defun org-before-change-function (beg end)
3049 "Every change indicates that a table might need an update."
3050 (setq org-table-may-need-update t))
3051 (defvar org-mode-map)
3052 (defvar org-mode-hook nil)
3053 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3054 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3055 (defvar org-table-buffer-is-an nil)
3056 (defconst org-outline-regexp "\\*+ ")
3058 ;;;###autoload
3059 (define-derived-mode org-mode outline-mode "Org"
3060 "Outline-based notes management and organizer, alias
3061 \"Carsten's outline-mode for keeping track of everything.\"
3063 Org-mode develops organizational tasks around a NOTES file which
3064 contains information about projects as plain text. Org-mode is
3065 implemented on top of outline-mode, which is ideal to keep the content
3066 of large files well structured. It supports ToDo items, deadlines and
3067 time stamps, which magically appear in the diary listing of the Emacs
3068 calendar. Tables are easily created with a built-in table editor.
3069 Plain text URL-like links connect to websites, emails (VM), Usenet
3070 messages (Gnus), BBDB entries, and any files related to the project.
3071 For printing and sharing of notes, an Org-mode file (or a part of it)
3072 can be exported as a structured ASCII or HTML file.
3074 The following commands are available:
3076 \\{org-mode-map}"
3078 ;; Get rid of Outline menus, they are not needed
3079 ;; Need to do this here because define-derived-mode sets up
3080 ;; the keymap so late. Still, it is a waste to call this each time
3081 ;; we switch another buffer into org-mode.
3082 (if (featurep 'xemacs)
3083 (when (boundp 'outline-mode-menu-heading)
3084 ;; Assume this is Greg's port, it used easymenu
3085 (easy-menu-remove outline-mode-menu-heading)
3086 (easy-menu-remove outline-mode-menu-show)
3087 (easy-menu-remove outline-mode-menu-hide))
3088 (define-key org-mode-map [menu-bar headings] 'undefined)
3089 (define-key org-mode-map [menu-bar hide] 'undefined)
3090 (define-key org-mode-map [menu-bar show] 'undefined))
3092 (org-load-modules-maybe)
3093 (easy-menu-add org-org-menu)
3094 (easy-menu-add org-tbl-menu)
3095 (org-install-agenda-files-menu)
3096 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3097 (org-add-to-invisibility-spec '(org-cwidth))
3098 (when (featurep 'xemacs)
3099 (org-set-local 'line-move-ignore-invisible t))
3100 (org-set-local 'outline-regexp org-outline-regexp)
3101 (org-set-local 'outline-level 'org-outline-level)
3102 (when (and org-ellipsis
3103 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3104 (fboundp 'make-glyph-code))
3105 (unless org-display-table
3106 (setq org-display-table (make-display-table)))
3107 (set-display-table-slot
3108 org-display-table 4
3109 (vconcat (mapcar
3110 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3111 org-ellipsis)))
3112 (if (stringp org-ellipsis) org-ellipsis "..."))))
3113 (setq buffer-display-table org-display-table))
3114 (org-set-regexps-and-options)
3115 ;; Calc embedded
3116 (org-set-local 'calc-embedded-open-mode "# ")
3117 (modify-syntax-entry ?# "<")
3118 (modify-syntax-entry ?@ "w")
3119 (if org-startup-truncated (setq truncate-lines t))
3120 (org-set-local 'font-lock-unfontify-region-function
3121 'org-unfontify-region)
3122 ;; Activate before-change-function
3123 (org-set-local 'org-table-may-need-update t)
3124 (org-add-hook 'before-change-functions 'org-before-change-function nil
3125 'local)
3126 ;; Check for running clock before killing a buffer
3127 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3128 ;; Paragraphs and auto-filling
3129 (org-set-autofill-regexps)
3130 (setq indent-line-function 'org-indent-line-function)
3131 (org-update-radio-target-regexp)
3133 ;; Comment characters
3134 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3135 (org-set-local 'comment-padding " ")
3137 ;; Align options lines
3138 (org-set-local
3139 'align-mode-rules-list
3140 '((org-in-buffer-settings
3141 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3142 (modes . '(org-mode)))))
3144 ;; Imenu
3145 (org-set-local 'imenu-create-index-function
3146 'org-imenu-get-tree)
3148 ;; Make isearch reveal context
3149 (if (or (featurep 'xemacs)
3150 (not (boundp 'outline-isearch-open-invisible-function)))
3151 ;; Emacs 21 and XEmacs make use of the hook
3152 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3153 ;; Emacs 22 deals with this through a special variable
3154 (org-set-local 'outline-isearch-open-invisible-function
3155 (lambda (&rest ignore) (org-show-context 'isearch))))
3157 ;; If empty file that did not turn on org-mode automatically, make it to.
3158 (if (and org-insert-mode-line-in-empty-file
3159 (interactive-p)
3160 (= (point-min) (point-max)))
3161 (insert "# -*- mode: org -*-\n\n"))
3163 (unless org-inhibit-startup
3164 (when org-startup-align-all-tables
3165 (let ((bmp (buffer-modified-p)))
3166 (org-table-map-tables 'org-table-align)
3167 (set-buffer-modified-p bmp)))
3168 (org-set-startup-visibility)))
3170 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3172 (defun org-current-time ()
3173 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3174 (if (> (car org-time-stamp-rounding-minutes) 1)
3175 (let ((r (car org-time-stamp-rounding-minutes))
3176 (time (decode-time)))
3177 (apply 'encode-time
3178 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3179 (nthcdr 2 time))))
3180 (current-time)))
3182 ;;;; Font-Lock stuff, including the activators
3184 (defvar org-mouse-map (make-sparse-keymap))
3185 (org-defkey org-mouse-map
3186 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3187 (org-defkey org-mouse-map
3188 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3189 (when org-mouse-1-follows-link
3190 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3191 (when org-tab-follows-link
3192 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3193 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3194 (when org-return-follows-link
3195 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3196 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3198 (require 'font-lock)
3200 (defconst org-non-link-chars "]\t\n\r<>")
3201 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3202 "shell" "elisp"))
3203 (defvar org-link-types-re nil
3204 "Matches a link that has a url-like prefix like \"http:\"")
3205 (defvar org-link-re-with-space nil
3206 "Matches a link with spaces, optional angular brackets around it.")
3207 (defvar org-link-re-with-space2 nil
3208 "Matches a link with spaces, optional angular brackets around it.")
3209 (defvar org-angle-link-re nil
3210 "Matches link with angular brackets, spaces are allowed.")
3211 (defvar org-plain-link-re nil
3212 "Matches plain link, without spaces.")
3213 (defvar org-bracket-link-regexp nil
3214 "Matches a link in double brackets.")
3215 (defvar org-bracket-link-analytic-regexp nil
3216 "Regular expression used to analyze links.
3217 Here is what the match groups contain after a match:
3218 1: http:
3219 2: http
3220 3: path
3221 4: [desc]
3222 5: desc")
3223 (defvar org-any-link-re nil
3224 "Regular expression matching any link.")
3226 (defun org-make-link-regexps ()
3227 "Update the link regular expressions.
3228 This should be called after the variable `org-link-types' has changed."
3229 (setq org-link-types-re
3230 (concat
3231 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3232 org-link-re-with-space
3233 (concat
3234 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3235 "\\([^" org-non-link-chars " ]"
3236 "[^" org-non-link-chars "]*"
3237 "[^" org-non-link-chars " ]\\)>?")
3238 org-link-re-with-space2
3239 (concat
3240 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3241 "\\([^" org-non-link-chars " ]"
3242 "[^]\t\n\r]*"
3243 "[^" org-non-link-chars " ]\\)>?")
3244 org-angle-link-re
3245 (concat
3246 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3247 "\\([^" org-non-link-chars " ]"
3248 "[^" org-non-link-chars "]*"
3249 "\\)>")
3250 org-plain-link-re
3251 (concat
3252 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3253 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3254 org-bracket-link-regexp
3255 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3256 org-bracket-link-analytic-regexp
3257 (concat
3258 "\\[\\["
3259 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3260 "\\([^]]+\\)"
3261 "\\]"
3262 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3263 "\\]")
3264 org-any-link-re
3265 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3266 org-angle-link-re "\\)\\|\\("
3267 org-plain-link-re "\\)")))
3269 (org-make-link-regexps)
3271 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3272 "Regular expression for fast time stamp matching.")
3273 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3274 "Regular expression for fast time stamp matching.")
3275 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3276 "Regular expression matching time strings for analysis.
3277 This one does not require the space after the date, so it can be used
3278 on a string that terminates immediately after the date.")
3279 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3280 "Regular expression matching time strings for analysis.")
3281 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3282 "Regular expression matching time stamps, with groups.")
3283 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3284 "Regular expression matching time stamps (also [..]), with groups.")
3285 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3286 "Regular expression matching a time stamp range.")
3287 (defconst org-tr-regexp-both
3288 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3289 "Regular expression matching a time stamp range.")
3290 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3291 org-ts-regexp "\\)?")
3292 "Regular expression matching a time stamp or time stamp range.")
3293 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3294 org-ts-regexp-both "\\)?")
3295 "Regular expression matching a time stamp or time stamp range.
3296 The time stamps may be either active or inactive.")
3298 (defvar org-emph-face nil)
3300 (defun org-do-emphasis-faces (limit)
3301 "Run through the buffer and add overlays to links."
3302 (let (rtn)
3303 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3304 (if (not (= (char-after (match-beginning 3))
3305 (char-after (match-beginning 4))))
3306 (progn
3307 (setq rtn t)
3308 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3309 'face
3310 (nth 1 (assoc (match-string 3)
3311 org-emphasis-alist)))
3312 (add-text-properties (match-beginning 2) (match-end 2)
3313 '(font-lock-multiline t))
3314 (when org-hide-emphasis-markers
3315 (add-text-properties (match-end 4) (match-beginning 5)
3316 '(invisible org-link))
3317 (add-text-properties (match-beginning 3) (match-end 3)
3318 '(invisible org-link)))))
3319 (backward-char 1))
3320 rtn))
3322 (defun org-emphasize (&optional char)
3323 "Insert or change an emphasis, i.e. a font like bold or italic.
3324 If there is an active region, change that region to a new emphasis.
3325 If there is no region, just insert the marker characters and position
3326 the cursor between them.
3327 CHAR should be either the marker character, or the first character of the
3328 HTML tag associated with that emphasis. If CHAR is a space, the means
3329 to remove the emphasis of the selected region.
3330 If char is not given (for example in an interactive call) it
3331 will be prompted for."
3332 (interactive)
3333 (let ((eal org-emphasis-alist) e det
3334 (erc org-emphasis-regexp-components)
3335 (prompt "")
3336 (string "") beg end move tag c s)
3337 (if (org-region-active-p)
3338 (setq beg (region-beginning) end (region-end)
3339 string (buffer-substring beg end))
3340 (setq move t))
3342 (while (setq e (pop eal))
3343 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3344 c (aref tag 0))
3345 (push (cons c (string-to-char (car e))) det)
3346 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3347 (substring tag 1)))))
3348 (unless char
3349 (message "%s" (concat "Emphasis marker or tag:" prompt))
3350 (setq char (read-char-exclusive)))
3351 (setq char (or (cdr (assoc char det)) char))
3352 (if (equal char ?\ )
3353 (setq s "" move nil)
3354 (unless (assoc (char-to-string char) org-emphasis-alist)
3355 (error "No such emphasis marker: \"%c\"" char))
3356 (setq s (char-to-string char)))
3357 (while (and (> (length string) 1)
3358 (equal (substring string 0 1) (substring string -1))
3359 (assoc (substring string 0 1) org-emphasis-alist))
3360 (setq string (substring string 1 -1)))
3361 (setq string (concat s string s))
3362 (if beg (delete-region beg end))
3363 (unless (or (bolp)
3364 (string-match (concat "[" (nth 0 erc) "\n]")
3365 (char-to-string (char-before (point)))))
3366 (insert " "))
3367 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3368 (char-to-string (char-after (point))))
3369 (insert " ") (backward-char 1))
3370 (insert string)
3371 (and move (backward-char 1))))
3373 (defconst org-nonsticky-props
3374 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3377 (defun org-activate-plain-links (limit)
3378 "Run through the buffer and add overlays to links."
3379 (catch 'exit
3380 (let (f)
3381 (while (re-search-forward org-plain-link-re limit t)
3382 (setq f (get-text-property (match-beginning 0) 'face))
3383 (if (or (eq f 'org-tag)
3384 (and (listp f) (memq 'org-tag f)))
3386 (add-text-properties (match-beginning 0) (match-end 0)
3387 (list 'mouse-face 'highlight
3388 'rear-nonsticky org-nonsticky-props
3389 'keymap org-mouse-map
3391 (throw 'exit t))))))
3393 (defun org-activate-code (limit)
3394 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3395 (unless (get-text-property (match-beginning 1) 'face)
3396 (remove-text-properties (match-beginning 0) (match-end 0)
3397 '(display t invisible t intangible t))
3398 t)))
3400 (defun org-activate-angle-links (limit)
3401 "Run through the buffer and add overlays to links."
3402 (if (re-search-forward org-angle-link-re limit t)
3403 (progn
3404 (add-text-properties (match-beginning 0) (match-end 0)
3405 (list 'mouse-face 'highlight
3406 'rear-nonsticky org-nonsticky-props
3407 'keymap org-mouse-map
3409 t)))
3411 (defun org-activate-bracket-links (limit)
3412 "Run through the buffer and add overlays to bracketed links."
3413 (if (re-search-forward org-bracket-link-regexp limit t)
3414 (let* ((help (concat "LINK: "
3415 (org-match-string-no-properties 1)))
3416 ;; FIXME: above we should remove the escapes.
3417 ;; but that requires another match, protecting match data,
3418 ;; a lot of overhead for font-lock.
3419 (ip (org-maybe-intangible
3420 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3421 'keymap org-mouse-map 'mouse-face 'highlight
3422 'font-lock-multiline t 'help-echo help)))
3423 (vp (list 'rear-nonsticky org-nonsticky-props
3424 'keymap org-mouse-map 'mouse-face 'highlight
3425 ' font-lock-multiline t 'help-echo help)))
3426 ;; We need to remove the invisible property here. Table narrowing
3427 ;; may have made some of this invisible.
3428 (remove-text-properties (match-beginning 0) (match-end 0)
3429 '(invisible nil))
3430 (if (match-end 3)
3431 (progn
3432 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3433 (add-text-properties (match-beginning 3) (match-end 3) vp)
3434 (add-text-properties (match-end 3) (match-end 0) ip))
3435 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3436 (add-text-properties (match-beginning 1) (match-end 1) vp)
3437 (add-text-properties (match-end 1) (match-end 0) ip))
3438 t)))
3440 (defun org-activate-dates (limit)
3441 "Run through the buffer and add overlays to dates."
3442 (if (re-search-forward org-tsr-regexp-both limit t)
3443 (progn
3444 (add-text-properties (match-beginning 0) (match-end 0)
3445 (list 'mouse-face 'highlight
3446 'rear-nonsticky org-nonsticky-props
3447 'keymap org-mouse-map))
3448 (when org-display-custom-times
3449 (if (match-end 3)
3450 (org-display-custom-time (match-beginning 3) (match-end 3)))
3451 (org-display-custom-time (match-beginning 1) (match-end 1)))
3452 t)))
3454 (defvar org-target-link-regexp nil
3455 "Regular expression matching radio targets in plain text.")
3456 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3457 "Regular expression matching a link target.")
3458 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3459 "Regular expression matching a radio target.")
3460 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3461 "Regular expression matching any target.")
3463 (defun org-activate-target-links (limit)
3464 "Run through the buffer and add overlays to target matches."
3465 (when org-target-link-regexp
3466 (let ((case-fold-search t))
3467 (if (re-search-forward org-target-link-regexp limit t)
3468 (progn
3469 (add-text-properties (match-beginning 0) (match-end 0)
3470 (list 'mouse-face 'highlight
3471 'rear-nonsticky org-nonsticky-props
3472 'keymap org-mouse-map
3473 'help-echo "Radio target link"
3474 'org-linked-text t))
3475 t)))))
3477 (defun org-update-radio-target-regexp ()
3478 "Find all radio targets in this file and update the regular expression."
3479 (interactive)
3480 (when (memq 'radio org-activate-links)
3481 (setq org-target-link-regexp
3482 (org-make-target-link-regexp (org-all-targets 'radio)))
3483 (org-restart-font-lock)))
3485 (defun org-hide-wide-columns (limit)
3486 (let (s e)
3487 (setq s (text-property-any (point) (or limit (point-max))
3488 'org-cwidth t))
3489 (when s
3490 (setq e (next-single-property-change s 'org-cwidth))
3491 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3492 (goto-char e)
3493 t)))
3495 (defvar org-latex-and-specials-regexp nil
3496 "Regular expression for highlighting export special stuff.")
3497 (defvar org-match-substring-regexp)
3498 (defvar org-match-substring-with-braces-regexp)
3499 (defvar org-export-html-special-string-regexps)
3501 (defun org-compute-latex-and-specials-regexp ()
3502 "Compute regular expression for stuff treated specially by exporters."
3503 (if (not org-highlight-latex-fragments-and-specials)
3504 (org-set-local 'org-latex-and-specials-regexp nil)
3505 (require 'org-exp)
3506 (let*
3507 ((matchers (plist-get org-format-latex-options :matchers))
3508 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3509 org-latex-regexps)))
3510 (options (org-combine-plists (org-default-export-plist)
3511 (org-infile-export-plist)))
3512 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3513 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3514 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3515 (org-export-html-expand (plist-get options :expand-quoted-html))
3516 (org-export-with-special-strings (plist-get options :special-strings))
3517 (re-sub
3518 (cond
3519 ((equal org-export-with-sub-superscripts '{})
3520 (list org-match-substring-with-braces-regexp))
3521 (org-export-with-sub-superscripts
3522 (list org-match-substring-regexp))
3523 (t nil)))
3524 (re-latex
3525 (if org-export-with-LaTeX-fragments
3526 (mapcar (lambda (x) (nth 1 x)) latexs)))
3527 (re-macros
3528 (if org-export-with-TeX-macros
3529 (list (concat "\\\\"
3530 (regexp-opt
3531 (append (mapcar 'car org-html-entities)
3532 (if (boundp 'org-latex-entities)
3533 org-latex-entities nil))
3534 'words))) ; FIXME
3536 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3537 (re-special (if org-export-with-special-strings
3538 (mapcar (lambda (x) (car x))
3539 org-export-html-special-string-regexps)))
3540 (re-rest
3541 (delq nil
3542 (list
3543 (if org-export-html-expand "@<[^>\n]+>")
3544 ))))
3545 (org-set-local
3546 'org-latex-and-specials-regexp
3547 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3548 re-rest) "\\|")))))
3550 (defun org-do-latex-and-special-faces (limit)
3551 "Run through the buffer and add overlays to links."
3552 (when org-latex-and-specials-regexp
3553 (let (rtn d)
3554 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3555 limit t))
3556 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3557 'face))
3558 '(org-code org-verbatim underline)))
3559 (progn
3560 (setq rtn t
3561 d (cond ((member (char-after (1+ (match-beginning 0)))
3562 '(?_ ?^)) 1)
3563 (t 0)))
3564 (font-lock-prepend-text-property
3565 (+ d (match-beginning 0)) (match-end 0)
3566 'face 'org-latex-and-export-specials)
3567 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3568 '(font-lock-multiline t)))))
3569 rtn)))
3571 (defun org-restart-font-lock ()
3572 "Restart font-lock-mode, to force refontification."
3573 (when (and (boundp 'font-lock-mode) font-lock-mode)
3574 (font-lock-mode -1)
3575 (font-lock-mode 1)))
3577 (defun org-all-targets (&optional radio)
3578 "Return a list of all targets in this file.
3579 With optional argument RADIO, only find radio targets."
3580 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3581 rtn)
3582 (save-excursion
3583 (goto-char (point-min))
3584 (while (re-search-forward re nil t)
3585 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3586 rtn)))
3588 (defun org-make-target-link-regexp (targets)
3589 "Make regular expression matching all strings in TARGETS.
3590 The regular expression finds the targets also if there is a line break
3591 between words."
3592 (and targets
3593 (concat
3594 "\\<\\("
3595 (mapconcat
3596 (lambda (x)
3597 (while (string-match " +" x)
3598 (setq x (replace-match "\\s-+" t t x)))
3600 targets
3601 "\\|")
3602 "\\)\\>")))
3604 (defun org-activate-tags (limit)
3605 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3606 (progn
3607 (add-text-properties (match-beginning 1) (match-end 1)
3608 (list 'mouse-face 'highlight
3609 'rear-nonsticky org-nonsticky-props
3610 'keymap org-mouse-map))
3611 t)))
3613 (defun org-outline-level ()
3614 (save-excursion
3615 (looking-at outline-regexp)
3616 (if (match-beginning 1)
3617 (+ (org-get-string-indentation (match-string 1)) 1000)
3618 (1- (- (match-end 0) (match-beginning 0))))))
3620 (defvar org-font-lock-keywords nil)
3622 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3623 "Regular expression matching a property line.")
3625 (defvar org-font-lock-hook nil
3626 "Functions to be called for special font loch stuff.")
3628 (defun org-font-lock-hook (limit)
3629 (run-hook-with-args 'org-font-lock-hook limit))
3631 (defun org-set-font-lock-defaults ()
3632 (let* ((em org-fontify-emphasized-text)
3633 (lk org-activate-links)
3634 (org-font-lock-extra-keywords
3635 (list
3636 ;; Call the hook
3637 '(org-font-lock-hook)
3638 ;; Headlines
3639 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3640 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3641 ;; Table lines
3642 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3643 (1 'org-table t))
3644 ;; Table internals
3645 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3646 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3647 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3648 ;; Drawers
3649 (list org-drawer-regexp '(0 'org-special-keyword t))
3650 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3651 ;; Properties
3652 (list org-property-re
3653 '(1 'org-special-keyword t)
3654 '(3 'org-property-value t))
3655 (if org-format-transports-properties-p
3656 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3657 ;; Links
3658 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3659 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3660 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3661 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3662 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3663 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3664 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3665 '(org-hide-wide-columns (0 nil append))
3666 ;; TODO lines
3667 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3668 '(1 (org-get-todo-face 1) t))
3669 ;; DONE
3670 (if org-fontify-done-headline
3671 (list (concat "^[*]+ +\\<\\("
3672 (mapconcat 'regexp-quote org-done-keywords "\\|")
3673 "\\)\\(.*\\)")
3674 '(2 'org-headline-done t))
3675 nil)
3676 ;; Priorities
3677 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3678 ;; Special keywords
3679 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3680 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3681 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3682 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3683 ;; Emphasis
3684 (if em
3685 (if (featurep 'xemacs)
3686 '(org-do-emphasis-faces (0 nil append))
3687 '(org-do-emphasis-faces)))
3688 ;; Checkboxes
3689 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3690 2 'bold prepend)
3691 (if org-provide-checkbox-statistics
3692 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3693 (0 (org-get-checkbox-statistics-face) t)))
3694 ;; Description list items
3695 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*?\\) ::"
3696 2 'bold prepend)
3697 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3698 '(1 'org-archived prepend))
3699 ;; Specials
3700 '(org-do-latex-and-special-faces)
3701 ;; Code
3702 '(org-activate-code (1 'org-code t))
3703 ;; COMMENT
3704 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3705 "\\|" org-quote-string "\\)\\>")
3706 '(1 'org-special-keyword t))
3707 '("^#.*" (0 'font-lock-comment-face t))
3709 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3710 ;; Now set the full font-lock-keywords
3711 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3712 (org-set-local 'font-lock-defaults
3713 '(org-font-lock-keywords t nil nil backward-paragraph))
3714 (kill-local-variable 'font-lock-keywords) nil))
3716 (defvar org-m nil)
3717 (defvar org-l nil)
3718 (defvar org-f nil)
3719 (defun org-get-level-face (n)
3720 "Get the right face for match N in font-lock matching of healdines."
3721 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3722 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3723 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3724 (cond
3725 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3726 ((eq n 2) org-f)
3727 (t (if org-level-color-stars-only nil org-f))))
3729 (defun org-get-todo-face (kwd)
3730 "Get the right face for a TODO keyword KWD.
3731 If KWD is a number, get the corresponding match group."
3732 (if (numberp kwd) (setq kwd (match-string kwd)))
3733 (or (cdr (assoc kwd org-todo-keyword-faces))
3734 (and (member kwd org-done-keywords) 'org-done)
3735 'org-todo))
3737 (defun org-unfontify-region (beg end &optional maybe_loudly)
3738 "Remove fontification and activation overlays from links."
3739 (font-lock-default-unfontify-region beg end)
3740 (let* ((buffer-undo-list t)
3741 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3742 (inhibit-modification-hooks t)
3743 deactivate-mark buffer-file-name buffer-file-truename)
3744 (remove-text-properties beg end
3745 '(mouse-face t keymap t org-linked-text t
3746 invisible t intangible t))))
3748 ;;;; Visibility cycling, including org-goto and indirect buffer
3750 ;;; Cycling
3752 (defvar org-cycle-global-status nil)
3753 (make-variable-buffer-local 'org-cycle-global-status)
3754 (defvar org-cycle-subtree-status nil)
3755 (make-variable-buffer-local 'org-cycle-subtree-status)
3757 ;;;###autoload
3758 (defun org-cycle (&optional arg)
3759 "Visibility cycling for Org-mode.
3761 - When this function is called with a prefix argument, rotate the entire
3762 buffer through 3 states (global cycling)
3763 1. OVERVIEW: Show only top-level headlines.
3764 2. CONTENTS: Show all headlines of all levels, but no body text.
3765 3. SHOW ALL: Show everything.
3766 When called with two C-c C-u prefixes, switch to the startup visibility,
3767 determined by the variable `org-startup-folded', and by any VISIBILITY
3768 properties in the buffer.
3770 - When point is at the beginning of a headline, rotate the subtree started
3771 by this line through 3 different states (local cycling)
3772 1. FOLDED: Only the main headline is shown.
3773 2. CHILDREN: The main headline and the direct children are shown.
3774 From this state, you can move to one of the children
3775 and zoom in further.
3776 3. SUBTREE: Show the entire subtree, including body text.
3778 - When there is a numeric prefix, go up to a heading with level ARG, do
3779 a `show-subtree' and return to the previous cursor position. If ARG
3780 is negative, go up that many levels.
3782 - When point is not at the beginning of a headline, execute the global
3783 binding for TAB, which is re-indenting the line. See the option
3784 `org-cycle-emulate-tab' for details.
3786 - Special case: if point is at the beginning of the buffer and there is
3787 no headline in line 1, this function will act as if called with prefix arg.
3788 But only if also the variable `org-cycle-global-at-bob' is t."
3789 (interactive "P")
3790 (org-load-modules-maybe)
3791 (let* ((outline-regexp
3792 (if (and (org-mode-p) org-cycle-include-plain-lists)
3793 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3794 outline-regexp))
3795 (bob-special (and org-cycle-global-at-bob (bobp)
3796 (not (looking-at outline-regexp))))
3797 (org-cycle-hook
3798 (if bob-special
3799 (delq 'org-optimize-window-after-visibility-change
3800 (copy-sequence org-cycle-hook))
3801 org-cycle-hook))
3802 (pos (point)))
3804 (if (or bob-special (equal arg '(4)))
3805 ;; special case: use global cycling
3806 (setq arg t))
3808 (cond
3810 ((equal arg '(16))
3811 (org-set-startup-visibility)
3812 (message "Startup visibility, plus VISIBILITY properties."))
3814 ((org-at-table-p 'any)
3815 ;; Enter the table or move to the next field in the table
3816 (or (org-table-recognize-table.el)
3817 (progn
3818 (if arg (org-table-edit-field t)
3819 (org-table-justify-field-maybe)
3820 (call-interactively 'org-table-next-field)))))
3822 ((eq arg t) ;; Global cycling
3824 (cond
3825 ((and (eq last-command this-command)
3826 (eq org-cycle-global-status 'overview))
3827 ;; We just created the overview - now do table of contents
3828 ;; This can be slow in very large buffers, so indicate action
3829 (message "CONTENTS...")
3830 (org-content)
3831 (message "CONTENTS...done")
3832 (setq org-cycle-global-status 'contents)
3833 (run-hook-with-args 'org-cycle-hook 'contents))
3835 ((and (eq last-command this-command)
3836 (eq org-cycle-global-status 'contents))
3837 ;; We just showed the table of contents - now show everything
3838 (show-all)
3839 (message "SHOW ALL")
3840 (setq org-cycle-global-status 'all)
3841 (run-hook-with-args 'org-cycle-hook 'all))
3844 ;; Default action: go to overview
3845 (org-overview)
3846 (message "OVERVIEW")
3847 (setq org-cycle-global-status 'overview)
3848 (run-hook-with-args 'org-cycle-hook 'overview))))
3850 ((and org-drawers org-drawer-regexp
3851 (save-excursion
3852 (beginning-of-line 1)
3853 (looking-at org-drawer-regexp)))
3854 ;; Toggle block visibility
3855 (org-flag-drawer
3856 (not (get-char-property (match-end 0) 'invisible))))
3858 ((integerp arg)
3859 ;; Show-subtree, ARG levels up from here.
3860 (save-excursion
3861 (org-back-to-heading)
3862 (outline-up-heading (if (< arg 0) (- arg)
3863 (- (funcall outline-level) arg)))
3864 (org-show-subtree)))
3866 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3867 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3868 ;; At a heading: rotate between three different views
3869 (org-back-to-heading)
3870 (let ((goal-column 0) eoh eol eos)
3871 ;; First, some boundaries
3872 (save-excursion
3873 (org-back-to-heading)
3874 (save-excursion
3875 (beginning-of-line 2)
3876 (while (and (not (eobp)) ;; this is like `next-line'
3877 (get-char-property (1- (point)) 'invisible))
3878 (beginning-of-line 2)) (setq eol (point)))
3879 (outline-end-of-heading) (setq eoh (point))
3880 (org-end-of-subtree t)
3881 (unless (eobp)
3882 (skip-chars-forward " \t\n")
3883 (beginning-of-line 1) ; in case this is an item
3885 (setq eos (1- (point))))
3886 ;; Find out what to do next and set `this-command'
3887 (cond
3888 ((= eos eoh)
3889 ;; Nothing is hidden behind this heading
3890 (message "EMPTY ENTRY")
3891 (setq org-cycle-subtree-status nil)
3892 (save-excursion
3893 (goto-char eos)
3894 (outline-next-heading)
3895 (if (org-invisible-p) (org-flag-heading nil))))
3896 ((or (>= eol eos)
3897 (not (string-match "\\S-" (buffer-substring eol eos))))
3898 ;; Entire subtree is hidden in one line: open it
3899 (org-show-entry)
3900 (show-children)
3901 (message "CHILDREN")
3902 (save-excursion
3903 (goto-char eos)
3904 (outline-next-heading)
3905 (if (org-invisible-p) (org-flag-heading nil)))
3906 (setq org-cycle-subtree-status 'children)
3907 (run-hook-with-args 'org-cycle-hook 'children))
3908 ((and (eq last-command this-command)
3909 (eq org-cycle-subtree-status 'children))
3910 ;; We just showed the children, now show everything.
3911 (org-show-subtree)
3912 (message "SUBTREE")
3913 (setq org-cycle-subtree-status 'subtree)
3914 (run-hook-with-args 'org-cycle-hook 'subtree))
3916 ;; Default action: hide the subtree.
3917 (hide-subtree)
3918 (message "FOLDED")
3919 (setq org-cycle-subtree-status 'folded)
3920 (run-hook-with-args 'org-cycle-hook 'folded)))))
3922 ;; TAB emulation
3923 (buffer-read-only (org-back-to-heading))
3925 ((org-try-cdlatex-tab))
3927 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3928 (or (not (bolp))
3929 (not (looking-at outline-regexp))))
3930 (call-interactively (global-key-binding "\t")))
3932 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3933 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3934 (or (and (eq org-cycle-emulate-tab 'white)
3935 (= (match-end 0) (point-at-eol)))
3936 (and (eq org-cycle-emulate-tab 'whitestart)
3937 (>= (match-end 0) pos))))
3939 (eq org-cycle-emulate-tab t))
3940 (call-interactively (global-key-binding "\t")))
3942 (t (save-excursion
3943 (org-back-to-heading)
3944 (org-cycle))))))
3946 ;;;###autoload
3947 (defun org-global-cycle (&optional arg)
3948 "Cycle the global visibility. For details see `org-cycle'.
3949 With C-u prefix arg, switch to startup visibility.
3950 With a numeric prefix, show all headlines up to that level."
3951 (interactive "P")
3952 (let ((org-cycle-include-plain-lists
3953 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3954 (cond
3955 ((integerp arg)
3956 (show-all)
3957 (hide-sublevels arg)
3958 (setq org-cycle-global-status 'contents))
3959 ((equal arg '(4))
3960 (org-set-startup-visibility)
3961 (message "Startup visibility, plus VISIBILITY properties."))
3963 (org-cycle '(4))))))
3965 (defun org-set-startup-visibility ()
3966 "Set the visibility required by startup options and properties."
3967 (cond
3968 ((eq org-startup-folded t)
3969 (org-cycle '(4)))
3970 ((eq org-startup-folded 'content)
3971 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3972 (org-cycle '(4)) (org-cycle '(4)))))
3973 (org-set-visibility-according-to-property 'no-cleanup)
3974 (org-cycle-hide-archived-subtrees 'all)
3975 (org-cycle-hide-drawers 'all)
3976 (org-cycle-show-empty-lines 'all))
3978 (defun org-set-visibility-according-to-property (&optional no-cleanup)
3979 "Switch subtree visibilities according to :VISIBILITY: property."
3980 (interactive)
3981 (let (state)
3982 (save-excursion
3983 (goto-char (point-min))
3984 (while (re-search-forward
3985 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
3986 nil t)
3987 (setq state (match-string 1))
3988 (save-excursion
3989 (org-back-to-heading t)
3990 (hide-subtree)
3991 (org-reveal)
3992 (cond
3993 ((equal state '("fold" "folded"))
3994 (hide-subtree))
3995 ((equal state "children")
3996 (org-show-hidden-entry)
3997 (show-children))
3998 ((equal state "content")
3999 (save-excursion
4000 (save-restriction
4001 (org-narrow-to-subtree)
4002 (org-content))))
4003 ((member state '("all" "showall"))
4004 (show-subtree)))))
4005 (unless no-cleanup
4006 (org-cycle-hide-archived-subtrees 'all)
4007 (org-cycle-hide-drawers 'all)
4008 (org-cycle-show-empty-lines 'all)))))
4010 (defun org-overview ()
4011 "Switch to overview mode, shoing only top-level headlines.
4012 Really, this shows all headlines with level equal or greater than the level
4013 of the first headline in the buffer. This is important, because if the
4014 first headline is not level one, then (hide-sublevels 1) gives confusing
4015 results."
4016 (interactive)
4017 (let ((level (save-excursion
4018 (goto-char (point-min))
4019 (if (re-search-forward (concat "^" outline-regexp) nil t)
4020 (progn
4021 (goto-char (match-beginning 0))
4022 (funcall outline-level))))))
4023 (and level (hide-sublevels level))))
4025 (defun org-content (&optional arg)
4026 "Show all headlines in the buffer, like a table of contents.
4027 With numerical argument N, show content up to level N."
4028 (interactive "P")
4029 (save-excursion
4030 ;; Visit all headings and show their offspring
4031 (and (integerp arg) (org-overview))
4032 (goto-char (point-max))
4033 (catch 'exit
4034 (while (and (progn (condition-case nil
4035 (outline-previous-visible-heading 1)
4036 (error (goto-char (point-min))))
4038 (looking-at outline-regexp))
4039 (if (integerp arg)
4040 (show-children (1- arg))
4041 (show-branches))
4042 (if (bobp) (throw 'exit nil))))))
4045 (defun org-optimize-window-after-visibility-change (state)
4046 "Adjust the window after a change in outline visibility.
4047 This function is the default value of the hook `org-cycle-hook'."
4048 (when (get-buffer-window (current-buffer))
4049 (cond
4050 ; ((eq state 'overview) (org-first-headline-recenter 1))
4051 ; ((eq state 'overview) (org-beginning-of-line))
4052 ((eq state 'content) nil)
4053 ((eq state 'all) nil)
4054 ((eq state 'folded) nil)
4055 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4056 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4058 (defun org-compact-display-after-subtree-move ()
4059 (let (beg end)
4060 (save-excursion
4061 (if (org-up-heading-safe)
4062 (progn
4063 (hide-subtree)
4064 (show-entry)
4065 (show-children)
4066 (org-cycle-show-empty-lines 'children)
4067 (org-cycle-hide-drawers 'children))
4068 (org-overview)))))
4070 (defun org-cycle-show-empty-lines (state)
4071 "Show empty lines above all visible headlines.
4072 The region to be covered depends on STATE when called through
4073 `org-cycle-hook'. Lisp program can use t for STATE to get the
4074 entire buffer covered. Note that an empty line is only shown if there
4075 are at least `org-cycle-separator-lines' empty lines before the headeline."
4076 (when (> org-cycle-separator-lines 0)
4077 (save-excursion
4078 (let* ((n org-cycle-separator-lines)
4079 (re (cond
4080 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4081 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4082 (t (let ((ns (number-to-string (- n 2))))
4083 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4084 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4085 beg end)
4086 (cond
4087 ((memq state '(overview contents t))
4088 (setq beg (point-min) end (point-max)))
4089 ((memq state '(children folded))
4090 (setq beg (point) end (progn (org-end-of-subtree t t)
4091 (beginning-of-line 2)
4092 (point)))))
4093 (when beg
4094 (goto-char beg)
4095 (while (re-search-forward re end t)
4096 (if (not (get-char-property (match-end 1) 'invisible))
4097 (outline-flag-region
4098 (match-beginning 1) (match-end 1) nil)))))))
4099 ;; Never hide empty lines at the end of the file.
4100 (save-excursion
4101 (goto-char (point-max))
4102 (outline-previous-heading)
4103 (outline-end-of-heading)
4104 (if (and (looking-at "[ \t\n]+")
4105 (= (match-end 0) (point-max)))
4106 (outline-flag-region (point) (match-end 0) nil))))
4108 (defun org-cycle-hide-drawers (state)
4109 "Re-hide all drawers after a visibility state change."
4110 (when (and (org-mode-p)
4111 (not (memq state '(overview folded))))
4112 (save-excursion
4113 (let* ((globalp (memq state '(contents all)))
4114 (beg (if globalp (point-min) (point)))
4115 (end (if globalp (point-max) (org-end-of-subtree t))))
4116 (goto-char beg)
4117 (while (re-search-forward org-drawer-regexp end t)
4118 (org-flag-drawer t))))))
4120 (defun org-flag-drawer (flag)
4121 (save-excursion
4122 (beginning-of-line 1)
4123 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4124 (let ((b (match-end 0))
4125 (outline-regexp org-outline-regexp))
4126 (if (re-search-forward
4127 "^[ \t]*:END:"
4128 (save-excursion (outline-next-heading) (point)) t)
4129 (outline-flag-region b (point-at-eol) flag)
4130 (error ":END: line missing"))))))
4132 (defun org-subtree-end-visible-p ()
4133 "Is the end of the current subtree visible?"
4134 (pos-visible-in-window-p
4135 (save-excursion (org-end-of-subtree t) (point))))
4137 (defun org-first-headline-recenter (&optional N)
4138 "Move cursor to the first headline and recenter the headline.
4139 Optional argument N means, put the headline into the Nth line of the window."
4140 (goto-char (point-min))
4141 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4142 (beginning-of-line)
4143 (recenter (prefix-numeric-value N))))
4145 ;;; Org-goto
4147 (defvar org-goto-window-configuration nil)
4148 (defvar org-goto-marker nil)
4149 (defvar org-goto-map
4150 (let ((map (make-sparse-keymap)))
4151 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4152 (while (setq cmd (pop cmds))
4153 (substitute-key-definition cmd cmd map global-map)))
4154 (suppress-keymap map)
4155 (org-defkey map "\C-m" 'org-goto-ret)
4156 (org-defkey map [(return)] 'org-goto-ret)
4157 (org-defkey map [(left)] 'org-goto-left)
4158 (org-defkey map [(right)] 'org-goto-right)
4159 (org-defkey map [(control ?g)] 'org-goto-quit)
4160 (org-defkey map "\C-i" 'org-cycle)
4161 (org-defkey map [(tab)] 'org-cycle)
4162 (org-defkey map [(down)] 'outline-next-visible-heading)
4163 (org-defkey map [(up)] 'outline-previous-visible-heading)
4164 (if org-goto-auto-isearch
4165 (if (fboundp 'define-key-after)
4166 (define-key-after map [t] 'org-goto-local-auto-isearch)
4167 nil)
4168 (org-defkey map "q" 'org-goto-quit)
4169 (org-defkey map "n" 'outline-next-visible-heading)
4170 (org-defkey map "p" 'outline-previous-visible-heading)
4171 (org-defkey map "f" 'outline-forward-same-level)
4172 (org-defkey map "b" 'outline-backward-same-level)
4173 (org-defkey map "u" 'outline-up-heading))
4174 (org-defkey map "/" 'org-occur)
4175 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4176 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4177 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4178 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4179 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4180 map))
4182 (defconst org-goto-help
4183 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4184 RET=jump to location [Q]uit and return to previous location
4185 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4187 (defvar org-goto-start-pos) ; dynamically scoped parameter
4189 (defun org-goto (&optional alternative-interface)
4190 "Look up a different location in the current file, keeping current visibility.
4192 When you want look-up or go to a different location in a document, the
4193 fastest way is often to fold the entire buffer and then dive into the tree.
4194 This method has the disadvantage, that the previous location will be folded,
4195 which may not be what you want.
4197 This command works around this by showing a copy of the current buffer
4198 in an indirect buffer, in overview mode. You can dive into the tree in
4199 that copy, use org-occur and incremental search to find a location.
4200 When pressing RET or `Q', the command returns to the original buffer in
4201 which the visibility is still unchanged. After RET is will also jump to
4202 the location selected in the indirect buffer and expose the
4203 the headline hierarchy above."
4204 (interactive "P")
4205 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4206 (org-refile-use-outline-path t)
4207 (interface
4208 (if (not alternative-interface)
4209 org-goto-interface
4210 (if (eq org-goto-interface 'outline)
4211 'outline-path-completion
4212 'outline)))
4213 (org-goto-start-pos (point))
4214 (selected-point
4215 (if (eq interface 'outline)
4216 (car (org-get-location (current-buffer) org-goto-help))
4217 (nth 3 (org-refile-get-location "Goto: ")))))
4218 (if selected-point
4219 (progn
4220 (org-mark-ring-push org-goto-start-pos)
4221 (goto-char selected-point)
4222 (if (or (org-invisible-p) (org-invisible-p2))
4223 (org-show-context 'org-goto)))
4224 (message "Quit"))))
4226 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4227 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4228 (defvar org-goto-local-auto-isearch-map) ; defined below
4230 (defun org-get-location (buf help)
4231 "Let the user select a location in the Org-mode buffer BUF.
4232 This function uses a recursive edit. It returns the selected position
4233 or nil."
4234 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4235 (isearch-hide-immediately nil)
4236 (isearch-search-fun-function
4237 (lambda () 'org-goto-local-search-forward-headings))
4238 (org-goto-selected-point org-goto-exit-command))
4239 (save-excursion
4240 (save-window-excursion
4241 (delete-other-windows)
4242 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4243 (switch-to-buffer
4244 (condition-case nil
4245 (make-indirect-buffer (current-buffer) "*org-goto*")
4246 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4247 (with-output-to-temp-buffer "*Help*"
4248 (princ help))
4249 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4250 (setq buffer-read-only nil)
4251 (let ((org-startup-truncated t)
4252 (org-startup-folded nil)
4253 (org-startup-align-all-tables nil))
4254 (org-mode)
4255 (org-overview))
4256 (setq buffer-read-only t)
4257 (if (and (boundp 'org-goto-start-pos)
4258 (integer-or-marker-p org-goto-start-pos))
4259 (let ((org-show-hierarchy-above t)
4260 (org-show-siblings t)
4261 (org-show-following-heading t))
4262 (goto-char org-goto-start-pos)
4263 (and (org-invisible-p) (org-show-context)))
4264 (goto-char (point-min)))
4265 (org-beginning-of-line)
4266 (message "Select location and press RET")
4267 (use-local-map org-goto-map)
4268 (recursive-edit)
4270 (kill-buffer "*org-goto*")
4271 (cons org-goto-selected-point org-goto-exit-command)))
4273 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4274 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4275 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4276 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4278 (defun org-goto-local-search-forward-headings (string bound noerror)
4279 "Search and make sure that anu matches are in headlines."
4280 (catch 'return
4281 (while (search-forward string bound noerror)
4282 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4283 (and (member :headline context)
4284 (not (member :tags context))))
4285 (throw 'return (point))))))
4287 (defun org-goto-local-auto-isearch ()
4288 "Start isearch."
4289 (interactive)
4290 (goto-char (point-min))
4291 (let ((keys (this-command-keys)))
4292 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4293 (isearch-mode t)
4294 (isearch-process-search-char (string-to-char keys)))))
4296 (defun org-goto-ret (&optional arg)
4297 "Finish `org-goto' by going to the new location."
4298 (interactive "P")
4299 (setq org-goto-selected-point (point)
4300 org-goto-exit-command 'return)
4301 (throw 'exit nil))
4303 (defun org-goto-left ()
4304 "Finish `org-goto' by going to the new location."
4305 (interactive)
4306 (if (org-on-heading-p)
4307 (progn
4308 (beginning-of-line 1)
4309 (setq org-goto-selected-point (point)
4310 org-goto-exit-command 'left)
4311 (throw 'exit nil))
4312 (error "Not on a heading")))
4314 (defun org-goto-right ()
4315 "Finish `org-goto' by going to the new location."
4316 (interactive)
4317 (if (org-on-heading-p)
4318 (progn
4319 (setq org-goto-selected-point (point)
4320 org-goto-exit-command 'right)
4321 (throw 'exit nil))
4322 (error "Not on a heading")))
4324 (defun org-goto-quit ()
4325 "Finish `org-goto' without cursor motion."
4326 (interactive)
4327 (setq org-goto-selected-point nil)
4328 (setq org-goto-exit-command 'quit)
4329 (throw 'exit nil))
4331 ;;; Indirect buffer display of subtrees
4333 (defvar org-indirect-dedicated-frame nil
4334 "This is the frame being used for indirect tree display.")
4335 (defvar org-last-indirect-buffer nil)
4337 (defun org-tree-to-indirect-buffer (&optional arg)
4338 "Create indirect buffer and narrow it to current subtree.
4339 With numerical prefix ARG, go up to this level and then take that tree.
4340 If ARG is negative, go up that many levels.
4341 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4342 indirect buffer previously made with this command, to avoid proliferation of
4343 indirect buffers. However, when you call the command with a `C-u' prefix, or
4344 when `org-indirect-buffer-display' is `new-frame', the last buffer
4345 is kept so that you can work with several indirect buffers at the same time.
4346 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4347 requests that a new frame be made for the new buffer, so that the dedicated
4348 frame is not changed."
4349 (interactive "P")
4350 (let ((cbuf (current-buffer))
4351 (cwin (selected-window))
4352 (pos (point))
4353 beg end level heading ibuf)
4354 (save-excursion
4355 (org-back-to-heading t)
4356 (when (numberp arg)
4357 (setq level (org-outline-level))
4358 (if (< arg 0) (setq arg (+ level arg)))
4359 (while (> (setq level (org-outline-level)) arg)
4360 (outline-up-heading 1 t)))
4361 (setq beg (point)
4362 heading (org-get-heading))
4363 (org-end-of-subtree t) (setq end (point)))
4364 (if (and (buffer-live-p org-last-indirect-buffer)
4365 (not (eq org-indirect-buffer-display 'new-frame))
4366 (not arg))
4367 (kill-buffer org-last-indirect-buffer))
4368 (setq ibuf (org-get-indirect-buffer cbuf)
4369 org-last-indirect-buffer ibuf)
4370 (cond
4371 ((or (eq org-indirect-buffer-display 'new-frame)
4372 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4373 (select-frame (make-frame))
4374 (delete-other-windows)
4375 (switch-to-buffer ibuf)
4376 (org-set-frame-title heading))
4377 ((eq org-indirect-buffer-display 'dedicated-frame)
4378 (raise-frame
4379 (select-frame (or (and org-indirect-dedicated-frame
4380 (frame-live-p org-indirect-dedicated-frame)
4381 org-indirect-dedicated-frame)
4382 (setq org-indirect-dedicated-frame (make-frame)))))
4383 (delete-other-windows)
4384 (switch-to-buffer ibuf)
4385 (org-set-frame-title (concat "Indirect: " heading)))
4386 ((eq org-indirect-buffer-display 'current-window)
4387 (switch-to-buffer ibuf))
4388 ((eq org-indirect-buffer-display 'other-window)
4389 (pop-to-buffer ibuf))
4390 (t (error "Invalid value.")))
4391 (if (featurep 'xemacs)
4392 (save-excursion (org-mode) (turn-on-font-lock)))
4393 (narrow-to-region beg end)
4394 (show-all)
4395 (goto-char pos)
4396 (and (window-live-p cwin) (select-window cwin))))
4398 (defun org-get-indirect-buffer (&optional buffer)
4399 (setq buffer (or buffer (current-buffer)))
4400 (let ((n 1) (base (buffer-name buffer)) bname)
4401 (while (buffer-live-p
4402 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4403 (setq n (1+ n)))
4404 (condition-case nil
4405 (make-indirect-buffer buffer bname 'clone)
4406 (error (make-indirect-buffer buffer bname)))))
4408 (defun org-set-frame-title (title)
4409 "Set the title of the current frame to the string TITLE."
4410 ;; FIXME: how to name a single frame in XEmacs???
4411 (unless (featurep 'xemacs)
4412 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4414 ;;;; Structure editing
4416 ;;; Inserting headlines
4418 (defun org-insert-heading (&optional force-heading)
4419 "Insert a new heading or item with same depth at point.
4420 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4421 If point is at the beginning of a headline, insert a sibling before the
4422 current headline. If point is not at the beginning, do not split the line,
4423 but create the new hedline after the current line."
4424 (interactive "P")
4425 (if (= (buffer-size) 0)
4426 (insert "\n* ")
4427 (when (or force-heading (not (org-insert-item)))
4428 (let* ((head (save-excursion
4429 (condition-case nil
4430 (progn
4431 (org-back-to-heading)
4432 (match-string 0))
4433 (error "*"))))
4434 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4435 pos)
4436 (cond
4437 ((and (org-on-heading-p) (bolp)
4438 (or (bobp)
4439 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4440 ;; insert before the current line
4441 (open-line (if blank 2 1)))
4442 ((and (bolp)
4443 (or (bobp)
4444 (save-excursion
4445 (backward-char 1) (not (org-invisible-p)))))
4446 ;; insert right here
4447 nil)
4449 ;; in the middle of the line
4450 (org-show-entry)
4451 (let ((split
4452 (org-get-alist-option org-M-RET-may-split-line 'headline))
4453 tags pos)
4454 (if (org-on-heading-p)
4455 (progn
4456 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4457 (setq tags (and (match-end 2) (match-string 2)))
4458 (and (match-end 1)
4459 (delete-region (match-beginning 1) (match-end 1)))
4460 (setq pos (point-at-bol))
4461 (or split (end-of-line 1))
4462 (delete-horizontal-space)
4463 (newline (if blank 2 1))
4464 (when tags
4465 (save-excursion
4466 (goto-char pos)
4467 (end-of-line 1)
4468 (insert " " tags)
4469 (org-set-tags nil 'align))))
4470 (or split (end-of-line 1))
4471 (newline (if blank 2 1))))))
4472 (insert head) (just-one-space)
4473 (setq pos (point))
4474 (end-of-line 1)
4475 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4476 (run-hooks 'org-insert-heading-hook)))))
4478 (defun org-get-heading (&optional no-tags)
4479 "Return the heading of the current entry, without the stars."
4480 (save-excursion
4481 (org-back-to-heading t)
4482 (if (looking-at
4483 (if no-tags
4484 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4485 "\\*+[ \t]+\\([^\r\n]*\\)"))
4486 (match-string 1) "")))
4488 (defun org-insert-heading-after-current ()
4489 "Insert a new heading with same level as current, after current subtree."
4490 (interactive)
4491 (org-back-to-heading)
4492 (org-insert-heading)
4493 (org-move-subtree-down)
4494 (end-of-line 1))
4496 (defun org-insert-todo-heading (arg)
4497 "Insert a new heading with the same level and TODO state as current heading.
4498 If the heading has no TODO state, or if the state is DONE, use the first
4499 state (TODO by default). Also with prefix arg, force first state."
4500 (interactive "P")
4501 (when (not (org-insert-item 'checkbox))
4502 (org-insert-heading)
4503 (save-excursion
4504 (org-back-to-heading)
4505 (outline-previous-heading)
4506 (looking-at org-todo-line-regexp))
4507 (if (or arg
4508 (not (match-beginning 2))
4509 (member (match-string 2) org-done-keywords))
4510 (insert (car org-todo-keywords-1) " ")
4511 (insert (match-string 2) " "))))
4513 (defun org-insert-subheading (arg)
4514 "Insert a new subheading and demote it.
4515 Works for outline headings and for plain lists alike."
4516 (interactive "P")
4517 (org-insert-heading arg)
4518 (cond
4519 ((org-on-heading-p) (org-do-demote))
4520 ((org-at-item-p) (org-indent-item 1))))
4522 (defun org-insert-todo-subheading (arg)
4523 "Insert a new subheading with TODO keyword or checkbox and demote it.
4524 Works for outline headings and for plain lists alike."
4525 (interactive "P")
4526 (org-insert-todo-heading arg)
4527 (cond
4528 ((org-on-heading-p) (org-do-demote))
4529 ((org-at-item-p) (org-indent-item 1))))
4531 ;;; Promotion and Demotion
4533 (defun org-promote-subtree ()
4534 "Promote the entire subtree.
4535 See also `org-promote'."
4536 (interactive)
4537 (save-excursion
4538 (org-map-tree 'org-promote))
4539 (org-fix-position-after-promote))
4541 (defun org-demote-subtree ()
4542 "Demote the entire subtree. See `org-demote'.
4543 See also `org-promote'."
4544 (interactive)
4545 (save-excursion
4546 (org-map-tree 'org-demote))
4547 (org-fix-position-after-promote))
4550 (defun org-do-promote ()
4551 "Promote the current heading higher up the tree.
4552 If the region is active in `transient-mark-mode', promote all headings
4553 in the region."
4554 (interactive)
4555 (save-excursion
4556 (if (org-region-active-p)
4557 (org-map-region 'org-promote (region-beginning) (region-end))
4558 (org-promote)))
4559 (org-fix-position-after-promote))
4561 (defun org-do-demote ()
4562 "Demote the current heading lower down the tree.
4563 If the region is active in `transient-mark-mode', demote all headings
4564 in the region."
4565 (interactive)
4566 (save-excursion
4567 (if (org-region-active-p)
4568 (org-map-region 'org-demote (region-beginning) (region-end))
4569 (org-demote)))
4570 (org-fix-position-after-promote))
4572 (defun org-fix-position-after-promote ()
4573 "Make sure that after pro/demotion cursor position is right."
4574 (let ((pos (point)))
4575 (when (save-excursion
4576 (beginning-of-line 1)
4577 (looking-at org-todo-line-regexp)
4578 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4579 (cond ((eobp) (insert " "))
4580 ((eolp) (insert " "))
4581 ((equal (char-after) ?\ ) (forward-char 1))))))
4583 (defun org-reduced-level (l)
4584 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4586 (defun org-get-valid-level (level &optional change)
4587 "Rectify a level change under the influence of `org-odd-levels-only'
4588 LEVEL is a current level, CHANGE is by how much the level should be
4589 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4590 even level numbers will become the next higher odd number."
4591 (if org-odd-levels-only
4592 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4593 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4594 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4595 (max 1 (+ level change))))
4597 (if (boundp 'define-obsolete-function-alias)
4598 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4599 (define-obsolete-function-alias 'org-get-legal-level
4600 'org-get-valid-level)
4601 (define-obsolete-function-alias 'org-get-legal-level
4602 'org-get-valid-level "23.1")))
4604 (defun org-promote ()
4605 "Promote the current heading higher up the tree.
4606 If the region is active in `transient-mark-mode', promote all headings
4607 in the region."
4608 (org-back-to-heading t)
4609 (let* ((level (save-match-data (funcall outline-level)))
4610 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4611 (diff (abs (- level (length up-head) -1))))
4612 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4613 (replace-match up-head nil t)
4614 ;; Fixup tag positioning
4615 (and org-auto-align-tags (org-set-tags nil t))
4616 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4618 (defun org-demote ()
4619 "Demote the current heading lower down the tree.
4620 If the region is active in `transient-mark-mode', demote all headings
4621 in the region."
4622 (org-back-to-heading t)
4623 (let* ((level (save-match-data (funcall outline-level)))
4624 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4625 (diff (abs (- level (length down-head) -1))))
4626 (replace-match down-head nil t)
4627 ;; Fixup tag positioning
4628 (and org-auto-align-tags (org-set-tags nil t))
4629 (if org-adapt-indentation (org-fixup-indentation diff))))
4631 (defun org-map-tree (fun)
4632 "Call FUN for every heading underneath the current one."
4633 (org-back-to-heading)
4634 (let ((level (funcall outline-level)))
4635 (save-excursion
4636 (funcall fun)
4637 (while (and (progn
4638 (outline-next-heading)
4639 (> (funcall outline-level) level))
4640 (not (eobp)))
4641 (funcall fun)))))
4643 (defun org-map-region (fun beg end)
4644 "Call FUN for every heading between BEG and END."
4645 (let ((org-ignore-region t))
4646 (save-excursion
4647 (setq end (copy-marker end))
4648 (goto-char beg)
4649 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4650 (< (point) end))
4651 (funcall fun))
4652 (while (and (progn
4653 (outline-next-heading)
4654 (< (point) end))
4655 (not (eobp)))
4656 (funcall fun)))))
4658 (defun org-fixup-indentation (diff)
4659 "Change the indentation in the current entry by DIFF
4660 However, if any line in the current entry has no indentation, or if it
4661 would end up with no indentation after the change, nothing at all is done."
4662 (save-excursion
4663 (let ((end (save-excursion (outline-next-heading)
4664 (point-marker)))
4665 (prohibit (if (> diff 0)
4666 "^\\S-"
4667 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4668 col)
4669 (unless (save-excursion (end-of-line 1)
4670 (re-search-forward prohibit end t))
4671 (while (and (< (point) end)
4672 (re-search-forward "^[ \t]+" end t))
4673 (goto-char (match-end 0))
4674 (setq col (current-column))
4675 (if (< diff 0) (replace-match ""))
4676 (indent-to (+ diff col))))
4677 (move-marker end nil))))
4679 (defun org-convert-to-odd-levels ()
4680 "Convert an org-mode file with all levels allowed to one with odd levels.
4681 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4682 level 5 etc."
4683 (interactive)
4684 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4685 (let ((org-odd-levels-only nil) n)
4686 (save-excursion
4687 (goto-char (point-min))
4688 (while (re-search-forward "^\\*\\*+ " nil t)
4689 (setq n (- (length (match-string 0)) 2))
4690 (while (>= (setq n (1- n)) 0)
4691 (org-demote))
4692 (end-of-line 1))))))
4695 (defun org-convert-to-oddeven-levels ()
4696 "Convert an org-mode file with only odd levels to one with odd and even levels.
4697 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4698 section with an even level, conversion would destroy the structure of the file. An error
4699 is signaled in this case."
4700 (interactive)
4701 (goto-char (point-min))
4702 ;; First check if there are no even levels
4703 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4704 (org-show-context t)
4705 (error "Not all levels are odd in this file. Conversion not possible."))
4706 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4707 (let ((org-odd-levels-only nil) n)
4708 (save-excursion
4709 (goto-char (point-min))
4710 (while (re-search-forward "^\\*\\*+ " nil t)
4711 (setq n (/ (1- (length (match-string 0))) 2))
4712 (while (>= (setq n (1- n)) 0)
4713 (org-promote))
4714 (end-of-line 1))))))
4716 (defun org-tr-level (n)
4717 "Make N odd if required."
4718 (if org-odd-levels-only (1+ (/ n 2)) n))
4720 ;;; Vertical tree motion, cutting and pasting of subtrees
4722 (defun org-move-subtree-up (&optional arg)
4723 "Move the current subtree up past ARG headlines of the same level."
4724 (interactive "p")
4725 (org-move-subtree-down (- (prefix-numeric-value arg))))
4727 (defun org-move-subtree-down (&optional arg)
4728 "Move the current subtree down past ARG headlines of the same level."
4729 (interactive "p")
4730 (setq arg (prefix-numeric-value arg))
4731 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4732 'outline-get-last-sibling))
4733 (ins-point (make-marker))
4734 (cnt (abs arg))
4735 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4736 ;; Select the tree
4737 (org-back-to-heading)
4738 (setq beg0 (point))
4739 (save-excursion
4740 (setq ne-beg (org-back-over-empty-lines))
4741 (setq beg (point)))
4742 (save-match-data
4743 (save-excursion (outline-end-of-heading)
4744 (setq folded (org-invisible-p)))
4745 (outline-end-of-subtree))
4746 (outline-next-heading)
4747 (setq ne-end (org-back-over-empty-lines))
4748 (setq end (point))
4749 (goto-char beg0)
4750 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4751 ;; include less whitespace
4752 (save-excursion
4753 (goto-char beg)
4754 (forward-line (- ne-beg ne-end))
4755 (setq beg (point))))
4756 ;; Find insertion point, with error handling
4757 (while (> cnt 0)
4758 (or (and (funcall movfunc) (looking-at outline-regexp))
4759 (progn (goto-char beg0)
4760 (error "Cannot move past superior level or buffer limit")))
4761 (setq cnt (1- cnt)))
4762 (if (> arg 0)
4763 ;; Moving forward - still need to move over subtree
4764 (progn (org-end-of-subtree t t)
4765 (save-excursion
4766 (org-back-over-empty-lines)
4767 (or (bolp) (newline)))))
4768 (setq ne-ins (org-back-over-empty-lines))
4769 (move-marker ins-point (point))
4770 (setq txt (buffer-substring beg end))
4771 (org-save-markers-in-region beg end)
4772 (delete-region beg end)
4773 (outline-flag-region (1- beg) beg nil)
4774 (outline-flag-region (1- (point)) (point) nil)
4775 (let ((bbb (point)))
4776 (insert-before-markers txt)
4777 (org-reinstall-markers-in-region bbb)
4778 (move-marker ins-point bbb))
4779 (or (bolp) (insert "\n"))
4780 (setq ins-end (point))
4781 (goto-char ins-point)
4782 (org-skip-whitespace)
4783 (when (and (< arg 0)
4784 (org-first-sibling-p)
4785 (> ne-ins ne-beg))
4786 ;; Move whitespace back to beginning
4787 (save-excursion
4788 (goto-char ins-end)
4789 (let ((kill-whole-line t))
4790 (kill-line (- ne-ins ne-beg)) (point)))
4791 (insert (make-string (- ne-ins ne-beg) ?\n)))
4792 (move-marker ins-point nil)
4793 (org-compact-display-after-subtree-move)
4794 (unless folded
4795 (org-show-entry)
4796 (show-children)
4797 (org-cycle-hide-drawers 'children))))
4799 (defvar org-subtree-clip ""
4800 "Clipboard for cut and paste of subtrees.
4801 This is actually only a copy of the kill, because we use the normal kill
4802 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4804 (defvar org-subtree-clip-folded nil
4805 "Was the last copied subtree folded?
4806 This is used to fold the tree back after pasting.")
4808 (defun org-cut-subtree (&optional n)
4809 "Cut the current subtree into the clipboard.
4810 With prefix arg N, cut this many sequential subtrees.
4811 This is a short-hand for marking the subtree and then cutting it."
4812 (interactive "p")
4813 (org-copy-subtree n 'cut))
4815 (defun org-copy-subtree (&optional n cut force-store-markers)
4816 "Cut the current subtree into the clipboard.
4817 With prefix arg N, cut this many sequential subtrees.
4818 This is a short-hand for marking the subtree and then copying it.
4819 If CUT is non-nil, actually cut the subtree.
4820 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4821 of some markers in the region, even if CUT is non-nil. This is
4822 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4823 (interactive "p")
4824 (let (beg end folded (beg0 (point)))
4825 (if (interactive-p)
4826 (org-back-to-heading nil) ; take what looks like a subtree
4827 (org-back-to-heading t)) ; take what is really there
4828 (org-back-over-empty-lines)
4829 (setq beg (point))
4830 (skip-chars-forward " \t\r\n")
4831 (save-match-data
4832 (save-excursion (outline-end-of-heading)
4833 (setq folded (org-invisible-p)))
4834 (condition-case nil
4835 (outline-forward-same-level (1- n))
4836 (error nil))
4837 (org-end-of-subtree t t))
4838 (org-back-over-empty-lines)
4839 (setq end (point))
4840 (goto-char beg0)
4841 (when (> end beg)
4842 (setq org-subtree-clip-folded folded)
4843 (when (or cut force-store-markers)
4844 (org-save-markers-in-region beg end))
4845 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4846 (setq org-subtree-clip (current-kill 0))
4847 (message "%s: Subtree(s) with %d characters"
4848 (if cut "Cut" "Copied")
4849 (length org-subtree-clip)))))
4851 (defun org-paste-subtree (&optional level tree)
4852 "Paste the clipboard as a subtree, with modification of headline level.
4853 The entire subtree is promoted or demoted in order to match a new headline
4854 level. By default, the new level is derived from the visible headings
4855 before and after the insertion point, and taken to be the inferior headline
4856 level of the two. So if the previous visible heading is level 3 and the
4857 next is level 4 (or vice versa), level 4 will be used for insertion.
4858 This makes sure that the subtree remains an independent subtree and does
4859 not swallow low level entries.
4861 You can also force a different level, either by using a numeric prefix
4862 argument, or by inserting the heading marker by hand. For example, if the
4863 cursor is after \"*****\", then the tree will be shifted to level 5.
4865 If you want to insert the tree as is, just use \\[yank].
4867 If optional TREE is given, use this text instead of the kill ring."
4868 (interactive "P")
4869 (unless (org-kill-is-subtree-p tree)
4870 (error "%s"
4871 (substitute-command-keys
4872 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4873 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4874 (^re (concat "^\\(" outline-regexp "\\)"))
4875 (re (concat "\\(" outline-regexp "\\)"))
4876 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4878 (old-level (if (string-match ^re txt)
4879 (- (match-end 0) (match-beginning 0) 1)
4880 -1))
4881 (force-level (cond (level (prefix-numeric-value level))
4882 ((string-match
4883 ^re_ (buffer-substring (point-at-bol) (point)))
4884 (- (match-end 1) (match-beginning 1)))
4885 (t nil)))
4886 (previous-level (save-excursion
4887 (condition-case nil
4888 (progn
4889 (outline-previous-visible-heading 1)
4890 (if (looking-at re)
4891 (- (match-end 0) (match-beginning 0) 1)
4893 (error 1))))
4894 (next-level (save-excursion
4895 (condition-case nil
4896 (progn
4897 (or (looking-at outline-regexp)
4898 (outline-next-visible-heading 1))
4899 (if (looking-at re)
4900 (- (match-end 0) (match-beginning 0) 1)
4902 (error 1))))
4903 (new-level (or force-level (max previous-level next-level)))
4904 (shift (if (or (= old-level -1)
4905 (= new-level -1)
4906 (= old-level new-level))
4908 (- new-level old-level)))
4909 (delta (if (> shift 0) -1 1))
4910 (func (if (> shift 0) 'org-demote 'org-promote))
4911 (org-odd-levels-only nil)
4912 beg end)
4913 ;; Remove the forced level indicator
4914 (if force-level
4915 (delete-region (point-at-bol) (point)))
4916 ;; Paste
4917 (beginning-of-line 1)
4918 (org-back-over-empty-lines)
4919 (setq beg (point))
4920 (insert-before-markers txt)
4921 (unless (string-match "\n\\'" txt) (insert "\n"))
4922 (org-reinstall-markers-in-region beg)
4923 (setq end (point))
4924 (goto-char beg)
4925 (skip-chars-forward " \t\n\r")
4926 (setq beg (point))
4927 ;; Shift if necessary
4928 (unless (= shift 0)
4929 (save-restriction
4930 (narrow-to-region beg end)
4931 (while (not (= shift 0))
4932 (org-map-region func (point-min) (point-max))
4933 (setq shift (+ delta shift)))
4934 (goto-char (point-min))))
4935 (when (interactive-p)
4936 (message "Clipboard pasted as level %d subtree" new-level))
4937 (if (and kill-ring
4938 (eq org-subtree-clip (current-kill 0))
4939 org-subtree-clip-folded)
4940 ;; The tree was folded before it was killed/copied
4941 (hide-subtree))))
4943 (defun org-kill-is-subtree-p (&optional txt)
4944 "Check if the current kill is an outline subtree, or a set of trees.
4945 Returns nil if kill does not start with a headline, or if the first
4946 headline level is not the largest headline level in the tree.
4947 So this will actually accept several entries of equal levels as well,
4948 which is OK for `org-paste-subtree'.
4949 If optional TXT is given, check this string instead of the current kill."
4950 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4951 (start-level (and kill
4952 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4953 org-outline-regexp "\\)")
4954 kill)
4955 (- (match-end 2) (match-beginning 2) 1)))
4956 (re (concat "^" org-outline-regexp))
4957 (start (1+ (match-beginning 2))))
4958 (if (not start-level)
4959 (progn
4960 nil) ;; does not even start with a heading
4961 (catch 'exit
4962 (while (setq start (string-match re kill (1+ start)))
4963 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4964 (throw 'exit nil)))
4965 t))))
4967 (defvar org-markers-to-move nil
4968 "Markers that should be moved with a cut-and-paste operation.
4969 Those markers are stored together with their positions relative to
4970 the start of the region.")
4972 (defun org-save-markers-in-region (beg end)
4973 "Check markers in region.
4974 If these markers are between BEG and END, record their position relative
4975 to BEG, so that after moving the block of text, we can put the markers back
4976 into place.
4977 This function gets called just before an entry or tree gets cut from the
4978 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4979 called immediately, to move the markers with the entries."
4980 (setq org-markers-to-move nil)
4981 (when (featurep 'org-clock)
4982 (org-clock-save-markers-for-cut-and-paste beg end))
4983 (when (featurep 'org-agenda)
4984 (org-agenda-save-markers-for-cut-and-paste beg end)))
4986 (defun org-check-and-save-marker (marker beg end)
4987 "Check if MARKER is between BEG and END.
4988 If yes, remember the marker and the distance to BEG."
4989 (when (and (marker-buffer marker)
4990 (equal (marker-buffer marker) (current-buffer)))
4991 (if (and (>= marker beg) (< marker end))
4992 (push (cons marker (- marker beg)) org-markers-to-move))))
4994 (defun org-reinstall-markers-in-region (beg)
4995 "Move all remembered markers to their position relative to BEG."
4996 (mapc (lambda (x)
4997 (move-marker (car x) (+ beg (cdr x))))
4998 org-markers-to-move)
4999 (setq org-markers-to-move nil))
5001 (defun org-narrow-to-subtree ()
5002 "Narrow buffer to the current subtree."
5003 (interactive)
5004 (save-excursion
5005 (save-match-data
5006 (narrow-to-region
5007 (progn (org-back-to-heading) (point))
5008 (progn (org-end-of-subtree t t) (point))))))
5011 ;;; Outline Sorting
5013 (defun org-sort (with-case)
5014 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5015 Optional argument WITH-CASE means sort case-sensitively."
5016 (interactive "P")
5017 (if (org-at-table-p)
5018 (org-call-with-arg 'org-table-sort-lines with-case)
5019 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5021 (defun org-sort-remove-invisible (s)
5022 (remove-text-properties 0 (length s) org-rm-props s)
5023 (while (string-match org-bracket-link-regexp s)
5024 (setq s (replace-match (if (match-end 2)
5025 (match-string 3 s)
5026 (match-string 1 s)) t t s)))
5029 (defvar org-priority-regexp) ; defined later in the file
5031 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5032 "Sort entries on a certain level of an outline tree.
5033 If there is an active region, the entries in the region are sorted.
5034 Else, if the cursor is before the first entry, sort the top-level items.
5035 Else, the children of the entry at point are sorted.
5037 Sorting can be alphabetically, numerically, and by date/time as given by
5038 the first time stamp in the entry. The command prompts for the sorting
5039 type unless it has been given to the function through the SORTING-TYPE
5040 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5041 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5042 called with point at the beginning of the record. It must return either
5043 a string or a number that should serve as the sorting key for that record.
5045 Comparing entries ignores case by default. However, with an optional argument
5046 WITH-CASE, the sorting considers case as well."
5047 (interactive "P")
5048 (let ((case-func (if with-case 'identity 'downcase))
5049 start beg end stars re re2
5050 txt what tmp plain-list-p)
5051 ;; Find beginning and end of region to sort
5052 (cond
5053 ((org-region-active-p)
5054 ;; we will sort the region
5055 (setq end (region-end)
5056 what "region")
5057 (goto-char (region-beginning))
5058 (if (not (org-on-heading-p)) (outline-next-heading))
5059 (setq start (point)))
5060 ((org-at-item-p)
5061 ;; we will sort this plain list
5062 (org-beginning-of-item-list) (setq start (point))
5063 (org-end-of-item-list) (setq end (point))
5064 (goto-char start)
5065 (setq plain-list-p t
5066 what "plain list"))
5067 ((or (org-on-heading-p)
5068 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5069 ;; we will sort the children of the current headline
5070 (org-back-to-heading)
5071 (setq start (point)
5072 end (progn (org-end-of-subtree t t)
5073 (org-back-over-empty-lines)
5074 (point))
5075 what "children")
5076 (goto-char start)
5077 (show-subtree)
5078 (outline-next-heading))
5080 ;; we will sort the top-level entries in this file
5081 (goto-char (point-min))
5082 (or (org-on-heading-p) (outline-next-heading))
5083 (setq start (point) end (point-max) what "top-level")
5084 (goto-char start)
5085 (show-all)))
5087 (setq beg (point))
5088 (if (>= beg end) (error "Nothing to sort"))
5090 (unless plain-list-p
5091 (looking-at "\\(\\*+\\)")
5092 (setq stars (match-string 1)
5093 re (concat "^" (regexp-quote stars) " +")
5094 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5095 txt (buffer-substring beg end))
5096 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5097 (if (and (not (equal stars "*")) (string-match re2 txt))
5098 (error "Region to sort contains a level above the first entry")))
5100 (unless sorting-type
5101 (message
5102 (if plain-list-p
5103 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5104 "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:")
5105 what)
5106 (setq sorting-type (read-char-exclusive))
5108 (and (= (downcase sorting-type) ?f)
5109 (setq getkey-func
5110 (completing-read "Sort using function: "
5111 obarray 'fboundp t nil nil))
5112 (setq getkey-func (intern getkey-func)))
5114 (and (= (downcase sorting-type) ?r)
5115 (setq property
5116 (completing-read "Property: "
5117 (mapcar 'list (org-buffer-property-keys t))
5118 nil t))))
5120 (message "Sorting entries...")
5122 (save-restriction
5123 (narrow-to-region start end)
5125 (let ((dcst (downcase sorting-type))
5126 (now (current-time)))
5127 (sort-subr
5128 (/= dcst sorting-type)
5129 ;; This function moves to the beginning character of the "record" to
5130 ;; be sorted.
5131 (if plain-list-p
5132 (lambda nil
5133 (if (org-at-item-p) t (goto-char (point-max))))
5134 (lambda nil
5135 (if (re-search-forward re nil t)
5136 (goto-char (match-beginning 0))
5137 (goto-char (point-max)))))
5138 ;; This function moves to the last character of the "record" being
5139 ;; sorted.
5140 (if plain-list-p
5141 'org-end-of-item
5142 (lambda nil
5143 (save-match-data
5144 (condition-case nil
5145 (outline-forward-same-level 1)
5146 (error
5147 (goto-char (point-max)))))))
5149 ;; This function returns the value that gets sorted against.
5150 (if plain-list-p
5151 (lambda nil
5152 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5153 (cond
5154 ((= dcst ?n)
5155 (string-to-number (buffer-substring (match-end 0)
5156 (point-at-eol))))
5157 ((= dcst ?a)
5158 (buffer-substring (match-end 0) (point-at-eol)))
5159 ((= dcst ?t)
5160 (if (re-search-forward org-ts-regexp
5161 (point-at-eol) t)
5162 (org-time-string-to-time (match-string 0))
5163 now))
5164 ((= dcst ?f)
5165 (if getkey-func
5166 (progn
5167 (setq tmp (funcall getkey-func))
5168 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5169 tmp)
5170 (error "Invalid key function `%s'" getkey-func)))
5171 (t (error "Invalid sorting type `%c'" sorting-type)))))
5172 (lambda nil
5173 (cond
5174 ((= dcst ?n)
5175 (if (looking-at outline-regexp)
5176 (string-to-number (buffer-substring (match-end 0)
5177 (point-at-eol)))
5178 nil))
5179 ((= dcst ?a)
5180 (funcall case-func (buffer-substring (point-at-bol)
5181 (point-at-eol))))
5182 ((= dcst ?t)
5183 (if (re-search-forward org-ts-regexp
5184 (save-excursion
5185 (forward-line 2)
5186 (point)) t)
5187 (org-time-string-to-time (match-string 0))
5188 now))
5189 ((= dcst ?p)
5190 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5191 (string-to-char (match-string 2))
5192 org-default-priority))
5193 ((= dcst ?r)
5194 (or (org-entry-get nil property) ""))
5195 ((= dcst ?o)
5196 (if (looking-at org-complex-heading-regexp)
5197 (- 9999 (length (member (match-string 2)
5198 org-todo-keywords-1)))))
5199 ((= dcst ?f)
5200 (if getkey-func
5201 (progn
5202 (setq tmp (funcall getkey-func))
5203 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5204 tmp)
5205 (error "Invalid key function `%s'" getkey-func)))
5206 (t (error "Invalid sorting type `%c'" sorting-type)))))
5208 (cond
5209 ((= dcst ?a) 'string<)
5210 ((= dcst ?t) 'time-less-p)
5211 (t nil)))))
5212 (message "Sorting entries...done")))
5214 (defun org-do-sort (table what &optional with-case sorting-type)
5215 "Sort TABLE of WHAT according to SORTING-TYPE.
5216 The user will be prompted for the SORTING-TYPE if the call to this
5217 function does not specify it. WHAT is only for the prompt, to indicate
5218 what is being sorted. The sorting key will be extracted from
5219 the car of the elements of the table.
5220 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5221 (unless sorting-type
5222 (message
5223 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5224 what)
5225 (setq sorting-type (read-char-exclusive)))
5226 (let ((dcst (downcase sorting-type))
5227 extractfun comparefun)
5228 ;; Define the appropriate functions
5229 (cond
5230 ((= dcst ?n)
5231 (setq extractfun 'string-to-number
5232 comparefun (if (= dcst sorting-type) '< '>)))
5233 ((= dcst ?a)
5234 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5235 (lambda(x) (downcase (org-sort-remove-invisible x))))
5236 comparefun (if (= dcst sorting-type)
5237 'string<
5238 (lambda (a b) (and (not (string< a b))
5239 (not (string= a b)))))))
5240 ((= dcst ?t)
5241 (setq extractfun
5242 (lambda (x)
5243 (if (string-match org-ts-regexp x)
5244 (time-to-seconds
5245 (org-time-string-to-time (match-string 0 x)))
5247 comparefun (if (= dcst sorting-type) '< '>)))
5248 (t (error "Invalid sorting type `%c'" sorting-type)))
5250 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5251 table)
5252 (lambda (a b) (funcall comparefun (car a) (car b))))))
5254 ;;;; Plain list items, including checkboxes
5256 ;;; Plain list items
5258 (defun org-at-item-p ()
5259 "Is point in a line starting a hand-formatted item?"
5260 (let ((llt org-plain-list-ordered-item-terminator))
5261 (save-excursion
5262 (goto-char (point-at-bol))
5263 (looking-at
5264 (cond
5265 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5266 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5267 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5268 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5270 (defun org-in-item-p ()
5271 "It the cursor inside a plain list item.
5272 Does not have to be the first line."
5273 (save-excursion
5274 (condition-case nil
5275 (progn
5276 (org-beginning-of-item)
5277 (org-at-item-p)
5279 (error nil))))
5281 (defun org-insert-item (&optional checkbox)
5282 "Insert a new item at the current level.
5283 Return t when things worked, nil when we are not in an item."
5284 (when (save-excursion
5285 (condition-case nil
5286 (progn
5287 (org-beginning-of-item)
5288 (org-at-item-p)
5289 (if (org-invisible-p) (error "Invisible item"))
5291 (error nil)))
5292 (let* ((bul (match-string 0))
5293 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5294 (match-end 0)))
5295 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5296 pos)
5297 (cond
5298 ((and (org-at-item-p) (<= (point) eow))
5299 ;; before the bullet
5300 (beginning-of-line 1)
5301 (open-line (if blank 2 1)))
5302 ((<= (point) eow)
5303 (beginning-of-line 1))
5305 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5306 (end-of-line 1)
5307 (delete-horizontal-space))
5308 (newline (if blank 2 1))))
5309 (insert bul (if checkbox "[ ]" ""))
5310 (just-one-space)
5311 (setq pos (point))
5312 (end-of-line 1)
5313 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5314 (org-maybe-renumber-ordered-list)
5315 (and checkbox (org-update-checkbox-count-maybe))
5318 ;;; Checkboxes
5320 (defun org-at-item-checkbox-p ()
5321 "Is point at a line starting a plain-list item with a checklet?"
5322 (and (org-at-item-p)
5323 (save-excursion
5324 (goto-char (match-end 0))
5325 (skip-chars-forward " \t")
5326 (looking-at "\\[[- X]\\]"))))
5328 (defun org-toggle-checkbox (&optional arg)
5329 "Toggle the checkbox in the current line."
5330 (interactive "P")
5331 (catch 'exit
5332 (let (beg end status (firstnew 'unknown))
5333 (cond
5334 ((org-region-active-p)
5335 (setq beg (region-beginning) end (region-end)))
5336 ((org-on-heading-p)
5337 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5338 ((org-at-item-checkbox-p)
5339 (let ((pos (point)))
5340 (replace-match
5341 (cond (arg "[-]")
5342 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5343 (t "[ ]"))
5344 t t)
5345 (goto-char pos))
5346 (throw 'exit t))
5347 (t (error "Not at a checkbox or heading, and no active region")))
5348 (save-excursion
5349 (goto-char beg)
5350 (while (< (point) end)
5351 (when (org-at-item-checkbox-p)
5352 (setq status (equal (match-string 0) "[X]"))
5353 (when (eq firstnew 'unknown)
5354 (setq firstnew (not status)))
5355 (replace-match
5356 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5357 (beginning-of-line 2)))))
5358 (org-update-checkbox-count-maybe))
5360 (defun org-update-checkbox-count-maybe ()
5361 "Update checkbox statistics unless turned off by user."
5362 (when org-provide-checkbox-statistics
5363 (org-update-checkbox-count)))
5365 (defun org-update-checkbox-count (&optional all)
5366 "Update the checkbox statistics in the current section.
5367 This will find all statistic cookies like [57%] and [6/12] and update them
5368 with the current numbers. With optional prefix argument ALL, do this for
5369 the whole buffer."
5370 (interactive "P")
5371 (save-excursion
5372 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5373 (beg (condition-case nil
5374 (progn (outline-back-to-heading) (point))
5375 (error (point-min))))
5376 (end (move-marker (make-marker)
5377 (progn (outline-next-heading) (point))))
5378 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5379 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5380 (re-find (concat re "\\|" re-box))
5381 beg-cookie end-cookie is-percent c-on c-off lim
5382 eline curr-ind next-ind continue-from startsearch
5383 (cstat 0)
5385 (when all
5386 (goto-char (point-min))
5387 (outline-next-heading)
5388 (setq beg (point) end (point-max)))
5389 (goto-char end)
5390 ;; find each statistic cookie
5391 (while (re-search-backward re-find beg t)
5392 (setq beg-cookie (match-beginning 1)
5393 end-cookie (match-end 1)
5394 cstat (+ cstat (if end-cookie 1 0))
5395 startsearch (point-at-eol)
5396 continue-from (point-at-bol)
5397 is-percent (match-beginning 2)
5398 lim (cond
5399 ((org-on-heading-p) (outline-next-heading) (point))
5400 ((org-at-item-p) (org-end-of-item) (point))
5401 (t nil))
5402 c-on 0
5403 c-off 0)
5404 (when lim
5405 ;; find first checkbox for this cookie and gather
5406 ;; statistics from all that are at this indentation level
5407 (goto-char startsearch)
5408 (if (re-search-forward re-box lim t)
5409 (progn
5410 (org-beginning-of-item)
5411 (setq curr-ind (org-get-indentation))
5412 (setq next-ind curr-ind)
5413 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5414 (save-excursion (end-of-line) (setq eline (point)))
5415 (if (re-search-forward re-box eline t)
5416 (if (member (match-string 2) '("[ ]" "[-]"))
5417 (setq c-off (1+ c-off))
5418 (setq c-on (1+ c-on))
5421 (org-end-of-item)
5422 (setq next-ind (org-get-indentation))
5424 (goto-char continue-from)
5425 ;; update cookie
5426 (when end-cookie
5427 (delete-region beg-cookie end-cookie)
5428 (goto-char beg-cookie)
5429 (insert
5430 (if is-percent
5431 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5432 (format "[%d/%d]" c-on (+ c-on c-off)))))
5433 ;; update items checkbox if it has one
5434 (when (org-at-item-p)
5435 (org-beginning-of-item)
5436 (when (and (> (+ c-on c-off) 0)
5437 (re-search-forward re-box (point-at-eol) t))
5438 (setq beg-cookie (match-beginning 2)
5439 end-cookie (match-end 2))
5440 (delete-region beg-cookie end-cookie)
5441 (goto-char beg-cookie)
5442 (cond ((= c-off 0) (insert "[X]"))
5443 ((= c-on 0) (insert "[ ]"))
5444 (t (insert "[-]")))
5446 (goto-char continue-from))
5447 (when (interactive-p)
5448 (message "Checkbox satistics updated %s (%d places)"
5449 (if all "in entire file" "in current outline entry") cstat)))))
5451 (defun org-get-checkbox-statistics-face ()
5452 "Select the face for checkbox statistics.
5453 The face will be `org-done' when all relevant boxes are checked. Otherwise
5454 it will be `org-todo'."
5455 (if (match-end 1)
5456 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5457 (if (and (> (match-end 2) (match-beginning 2))
5458 (equal (match-string 2) (match-string 3)))
5459 'org-done
5460 'org-todo)))
5462 (defun org-get-indentation (&optional line)
5463 "Get the indentation of the current line, interpreting tabs.
5464 When LINE is given, assume it represents a line and compute its indentation."
5465 (if line
5466 (if (string-match "^ *" (org-remove-tabs line))
5467 (match-end 0))
5468 (save-excursion
5469 (beginning-of-line 1)
5470 (skip-chars-forward " \t")
5471 (current-column))))
5473 (defun org-remove-tabs (s &optional width)
5474 "Replace tabulators in S with spaces.
5475 Assumes that s is a single line, starting in column 0."
5476 (setq width (or width tab-width))
5477 (while (string-match "\t" s)
5478 (setq s (replace-match
5479 (make-string
5480 (- (* width (/ (+ (match-beginning 0) width) width))
5481 (match-beginning 0)) ?\ )
5482 t t s)))
5485 (defun org-fix-indentation (line ind)
5486 "Fix indentation in LINE.
5487 IND is a cons cell with target and minimum indentation.
5488 If the current indenation in LINE is smaller than the minimum,
5489 leave it alone. If it is larger than ind, set it to the target."
5490 (let* ((l (org-remove-tabs line))
5491 (i (org-get-indentation l))
5492 (i1 (car ind)) (i2 (cdr ind)))
5493 (if (>= i i2) (setq l (substring line i2)))
5494 (if (> i1 0)
5495 (concat (make-string i1 ?\ ) l)
5496 l)))
5498 (defun org-beginning-of-item ()
5499 "Go to the beginning of the current hand-formatted item.
5500 If the cursor is not in an item, throw an error."
5501 (interactive)
5502 (let ((pos (point))
5503 (limit (save-excursion
5504 (condition-case nil
5505 (progn
5506 (org-back-to-heading)
5507 (beginning-of-line 2) (point))
5508 (error (point-min)))))
5509 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5510 ind ind1)
5511 (if (org-at-item-p)
5512 (beginning-of-line 1)
5513 (beginning-of-line 1)
5514 (skip-chars-forward " \t")
5515 (setq ind (current-column))
5516 (if (catch 'exit
5517 (while t
5518 (beginning-of-line 0)
5519 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5521 (if (looking-at "[ \t]*$")
5522 (setq ind1 ind-empty)
5523 (skip-chars-forward " \t")
5524 (setq ind1 (current-column)))
5525 (if (< ind1 ind)
5526 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5528 (goto-char pos)
5529 (error "Not in an item")))))
5531 (defun org-end-of-item ()
5532 "Go to the end of the current hand-formatted item.
5533 If the cursor is not in an item, throw an error."
5534 (interactive)
5535 (let* ((pos (point))
5536 ind1
5537 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5538 (limit (save-excursion (outline-next-heading) (point)))
5539 (ind (save-excursion
5540 (org-beginning-of-item)
5541 (skip-chars-forward " \t")
5542 (current-column)))
5543 (end (catch 'exit
5544 (while t
5545 (beginning-of-line 2)
5546 (if (eobp) (throw 'exit (point)))
5547 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5548 (if (looking-at "[ \t]*$")
5549 (setq ind1 ind-empty)
5550 (skip-chars-forward " \t")
5551 (setq ind1 (current-column)))
5552 (if (<= ind1 ind)
5553 (throw 'exit (point-at-bol)))))))
5554 (if end
5555 (goto-char end)
5556 (goto-char pos)
5557 (error "Not in an item"))))
5559 (defun org-next-item ()
5560 "Move to the beginning of the next item in the current plain list.
5561 Error if not at a plain list, or if this is the last item in the list."
5562 (interactive)
5563 (let (ind ind1 (pos (point)))
5564 (org-beginning-of-item)
5565 (setq ind (org-get-indentation))
5566 (org-end-of-item)
5567 (setq ind1 (org-get-indentation))
5568 (unless (and (org-at-item-p) (= ind ind1))
5569 (goto-char pos)
5570 (error "On last item"))))
5572 (defun org-previous-item ()
5573 "Move to the beginning of the previous item in the current plain list.
5574 Error if not at a plain list, or if this is the first item in the list."
5575 (interactive)
5576 (let (beg ind ind1 (pos (point)))
5577 (org-beginning-of-item)
5578 (setq beg (point))
5579 (setq ind (org-get-indentation))
5580 (goto-char beg)
5581 (catch 'exit
5582 (while t
5583 (beginning-of-line 0)
5584 (if (looking-at "[ \t]*$")
5586 (if (<= (setq ind1 (org-get-indentation)) ind)
5587 (throw 'exit t)))))
5588 (condition-case nil
5589 (if (or (not (org-at-item-p))
5590 (< ind1 (1- ind)))
5591 (error "")
5592 (org-beginning-of-item))
5593 (error (goto-char pos)
5594 (error "On first item")))))
5596 (defun org-first-list-item-p ()
5597 "Is this heading the item in a plain list?"
5598 (unless (org-at-item-p)
5599 (error "Not at a plain list item"))
5600 (org-beginning-of-item)
5601 (= (point) (save-excursion (org-beginning-of-item-list))))
5603 (defun org-move-item-down ()
5604 "Move the plain list item at point down, i.e. swap with following item.
5605 Subitems (items with larger indentation) are considered part of the item,
5606 so this really moves item trees."
5607 (interactive)
5608 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5609 (org-beginning-of-item)
5610 (setq beg0 (point))
5611 (save-excursion
5612 (setq ne-beg (org-back-over-empty-lines))
5613 (setq beg (point)))
5614 (goto-char beg0)
5615 (setq ind (org-get-indentation))
5616 (org-end-of-item)
5617 (setq end0 (point))
5618 (setq ind1 (org-get-indentation))
5619 (setq ne-end (org-back-over-empty-lines))
5620 (setq end (point))
5621 (goto-char beg0)
5622 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5623 ;; include less whitespace
5624 (save-excursion
5625 (goto-char beg)
5626 (forward-line (- ne-beg ne-end))
5627 (setq beg (point))))
5628 (goto-char end0)
5629 (if (and (org-at-item-p) (= ind ind1))
5630 (progn
5631 (org-end-of-item)
5632 (org-back-over-empty-lines)
5633 (setq txt (buffer-substring beg end))
5634 (save-excursion
5635 (delete-region beg end))
5636 (setq pos (point))
5637 (insert txt)
5638 (goto-char pos) (org-skip-whitespace)
5639 (org-maybe-renumber-ordered-list))
5640 (goto-char pos)
5641 (error "Cannot move this item further down"))))
5643 (defun org-move-item-up (arg)
5644 "Move the plain list item at point up, i.e. swap with previous item.
5645 Subitems (items with larger indentation) are considered part of the item,
5646 so this really moves item trees."
5647 (interactive "p")
5648 (let (beg beg0 end ind ind1 (pos (point)) txt
5649 ne-beg ne-ins ins-end)
5650 (org-beginning-of-item)
5651 (setq beg0 (point))
5652 (setq ind (org-get-indentation))
5653 (save-excursion
5654 (setq ne-beg (org-back-over-empty-lines))
5655 (setq beg (point)))
5656 (goto-char beg0)
5657 (org-end-of-item)
5658 (setq end (point))
5659 (goto-char beg0)
5660 (catch 'exit
5661 (while t
5662 (beginning-of-line 0)
5663 (if (looking-at "[ \t]*$")
5664 (if org-empty-line-terminates-plain-lists
5665 (progn
5666 (goto-char pos)
5667 (error "Cannot move this item further up"))
5668 nil)
5669 (if (<= (setq ind1 (org-get-indentation)) ind)
5670 (throw 'exit t)))))
5671 (condition-case nil
5672 (org-beginning-of-item)
5673 (error (goto-char beg)
5674 (error "Cannot move this item further up")))
5675 (setq ind1 (org-get-indentation))
5676 (if (and (org-at-item-p) (= ind ind1))
5677 (progn
5678 (setq ne-ins (org-back-over-empty-lines))
5679 (setq txt (buffer-substring beg end))
5680 (save-excursion
5681 (delete-region beg end))
5682 (setq pos (point))
5683 (insert txt)
5684 (setq ins-end (point))
5685 (goto-char pos) (org-skip-whitespace)
5687 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5688 ;; Move whitespace back to beginning
5689 (save-excursion
5690 (goto-char ins-end)
5691 (let ((kill-whole-line t))
5692 (kill-line (- ne-ins ne-beg)) (point)))
5693 (insert (make-string (- ne-ins ne-beg) ?\n)))
5695 (org-maybe-renumber-ordered-list))
5696 (goto-char pos)
5697 (error "Cannot move this item further up"))))
5699 (defun org-maybe-renumber-ordered-list ()
5700 "Renumber the ordered list at point if setup allows it.
5701 This tests the user option `org-auto-renumber-ordered-lists' before
5702 doing the renumbering."
5703 (interactive)
5704 (when (and org-auto-renumber-ordered-lists
5705 (org-at-item-p))
5706 (if (match-beginning 3)
5707 (org-renumber-ordered-list 1)
5708 (org-fix-bullet-type))))
5710 (defun org-maybe-renumber-ordered-list-safe ()
5711 (condition-case nil
5712 (save-excursion
5713 (org-maybe-renumber-ordered-list))
5714 (error nil)))
5716 (defun org-cycle-list-bullet (&optional which)
5717 "Cycle through the different itemize/enumerate bullets.
5718 This cycle the entire list level through the sequence:
5720 `-' -> `+' -> `*' -> `1.' -> `1)'
5722 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5723 0 meand `-', 1 means `+' etc."
5724 (interactive "P")
5725 (org-preserve-lc
5726 (org-beginning-of-item-list)
5727 (org-at-item-p)
5728 (beginning-of-line 1)
5729 (let ((current (match-string 0))
5730 (prevp (eq which 'previous))
5731 new)
5732 (setq new (cond
5733 ((and (numberp which)
5734 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5735 ((string-match "-" current) (if prevp "1)" "+"))
5736 ((string-match "\\+" current)
5737 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5738 ((string-match "\\*" current) (if prevp "+" "1."))
5739 ((string-match "\\." current) (if prevp "*" "1)"))
5740 ((string-match ")" current) (if prevp "1." "-"))
5741 (t (error "This should not happen"))))
5742 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5743 (org-fix-bullet-type)
5744 (org-maybe-renumber-ordered-list))))
5746 (defun org-get-string-indentation (s)
5747 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5748 (let ((n -1) (i 0) (w tab-width) c)
5749 (catch 'exit
5750 (while (< (setq n (1+ n)) (length s))
5751 (setq c (aref s n))
5752 (cond ((= c ?\ ) (setq i (1+ i)))
5753 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5754 (t (throw 'exit t)))))
5757 (defun org-renumber-ordered-list (arg)
5758 "Renumber an ordered plain list.
5759 Cursor needs to be in the first line of an item, the line that starts
5760 with something like \"1.\" or \"2)\"."
5761 (interactive "p")
5762 (unless (and (org-at-item-p)
5763 (match-beginning 3))
5764 (error "This is not an ordered list"))
5765 (let ((line (org-current-line))
5766 (col (current-column))
5767 (ind (org-get-string-indentation
5768 (buffer-substring (point-at-bol) (match-beginning 3))))
5769 ;; (term (substring (match-string 3) -1))
5770 ind1 (n (1- arg))
5771 fmt)
5772 ;; find where this list begins
5773 (org-beginning-of-item-list)
5774 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5775 (setq fmt (concat "%d" (match-string 1)))
5776 (beginning-of-line 0)
5777 ;; walk forward and replace these numbers
5778 (catch 'exit
5779 (while t
5780 (catch 'next
5781 (beginning-of-line 2)
5782 (if (eobp) (throw 'exit nil))
5783 (if (looking-at "[ \t]*$") (throw 'next nil))
5784 (skip-chars-forward " \t") (setq ind1 (current-column))
5785 (if (> ind1 ind) (throw 'next t))
5786 (if (< ind1 ind) (throw 'exit t))
5787 (if (not (org-at-item-p)) (throw 'exit nil))
5788 (delete-region (match-beginning 2) (match-end 2))
5789 (goto-char (match-beginning 2))
5790 (insert (format fmt (setq n (1+ n)))))))
5791 (goto-line line)
5792 (org-move-to-column col)))
5794 (defun org-fix-bullet-type ()
5795 "Make sure all items in this list have the same bullet as the firsst item."
5796 (interactive)
5797 (unless (org-at-item-p) (error "This is not a list"))
5798 (let ((line (org-current-line))
5799 (col (current-column))
5800 (ind (current-indentation))
5801 ind1 bullet)
5802 ;; find where this list begins
5803 (org-beginning-of-item-list)
5804 (beginning-of-line 1)
5805 ;; find out what the bullet type is
5806 (looking-at "[ \t]*\\(\\S-+\\)")
5807 (setq bullet (match-string 1))
5808 ;; walk forward and replace these numbers
5809 (beginning-of-line 0)
5810 (catch 'exit
5811 (while t
5812 (catch 'next
5813 (beginning-of-line 2)
5814 (if (eobp) (throw 'exit nil))
5815 (if (looking-at "[ \t]*$") (throw 'next nil))
5816 (skip-chars-forward " \t") (setq ind1 (current-column))
5817 (if (> ind1 ind) (throw 'next t))
5818 (if (< ind1 ind) (throw 'exit t))
5819 (if (not (org-at-item-p)) (throw 'exit nil))
5820 (skip-chars-forward " \t")
5821 (looking-at "\\S-+")
5822 (replace-match bullet))))
5823 (goto-line line)
5824 (org-move-to-column col)
5825 (if (string-match "[0-9]" bullet)
5826 (org-renumber-ordered-list 1))))
5828 (defun org-beginning-of-item-list ()
5829 "Go to the beginning of the current item list.
5830 I.e. to the first item in this list."
5831 (interactive)
5832 (org-beginning-of-item)
5833 (let ((pos (point-at-bol))
5834 (ind (org-get-indentation))
5835 ind1)
5836 ;; find where this list begins
5837 (catch 'exit
5838 (while t
5839 (catch 'next
5840 (beginning-of-line 0)
5841 (if (looking-at "[ \t]*$")
5842 (throw (if (bobp) 'exit 'next) t))
5843 (skip-chars-forward " \t") (setq ind1 (current-column))
5844 (if (or (< ind1 ind)
5845 (and (= ind1 ind)
5846 (not (org-at-item-p)))
5847 (bobp))
5848 (throw 'exit t)
5849 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5850 (goto-char pos)))
5853 (defun org-end-of-item-list ()
5854 "Go to the end of the current item list.
5855 I.e. to the text after the last item."
5856 (interactive)
5857 (org-beginning-of-item)
5858 (let ((pos (point-at-bol))
5859 (ind (org-get-indentation))
5860 ind1)
5861 ;; find where this list begins
5862 (catch 'exit
5863 (while t
5864 (catch 'next
5865 (beginning-of-line 2)
5866 (if (looking-at "[ \t]*$")
5867 (throw (if (eobp) 'exit 'next) t))
5868 (skip-chars-forward " \t") (setq ind1 (current-column))
5869 (if (or (< ind1 ind)
5870 (and (= ind1 ind)
5871 (not (org-at-item-p)))
5872 (eobp))
5873 (progn
5874 (setq pos (point-at-bol))
5875 (throw 'exit t))))))
5876 (goto-char pos)))
5879 (defvar org-last-indent-begin-marker (make-marker))
5880 (defvar org-last-indent-end-marker (make-marker))
5882 (defun org-outdent-item (arg)
5883 "Outdent a local list item."
5884 (interactive "p")
5885 (org-indent-item (- arg)))
5887 (defun org-indent-item (arg)
5888 "Indent a local list item."
5889 (interactive "p")
5890 (unless (org-at-item-p)
5891 (error "Not on an item"))
5892 (save-excursion
5893 (let (beg end ind ind1 tmp delta ind-down ind-up)
5894 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5895 (setq beg org-last-indent-begin-marker
5896 end org-last-indent-end-marker)
5897 (org-beginning-of-item)
5898 (setq beg (move-marker org-last-indent-begin-marker (point)))
5899 (org-end-of-item)
5900 (setq end (move-marker org-last-indent-end-marker (point))))
5901 (goto-char beg)
5902 (setq tmp (org-item-indent-positions)
5903 ind (car tmp)
5904 ind-down (nth 2 tmp)
5905 ind-up (nth 1 tmp)
5906 delta (if (> arg 0)
5907 (if ind-down (- ind-down ind) 2)
5908 (if ind-up (- ind-up ind) -2)))
5909 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5910 (while (< (point) end)
5911 (beginning-of-line 1)
5912 (skip-chars-forward " \t") (setq ind1 (current-column))
5913 (delete-region (point-at-bol) (point))
5914 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5915 (beginning-of-line 2))))
5916 (org-fix-bullet-type)
5917 (org-maybe-renumber-ordered-list-safe)
5918 (save-excursion
5919 (beginning-of-line 0)
5920 (condition-case nil (org-beginning-of-item) (error nil))
5921 (org-maybe-renumber-ordered-list-safe)))
5923 (defun org-item-indent-positions ()
5924 "Return indentation for plain list items.
5925 This returns a list with three values: The current indentation, the
5926 parent indentation and the indentation a child should habe.
5927 Assumes cursor in item line."
5928 (let* ((bolpos (point-at-bol))
5929 (ind (org-get-indentation))
5930 ind-down ind-up pos)
5931 (save-excursion
5932 (org-beginning-of-item-list)
5933 (skip-chars-backward "\n\r \t")
5934 (when (org-in-item-p)
5935 (org-beginning-of-item)
5936 (setq ind-up (org-get-indentation))))
5937 (setq pos (point))
5938 (save-excursion
5939 (cond
5940 ((and (condition-case nil (progn (org-previous-item) t)
5941 (error nil))
5942 (or (forward-char 1) t)
5943 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5944 (setq ind-down (org-get-indentation)))
5945 ((and (goto-char pos)
5946 (org-at-item-p))
5947 (goto-char (match-end 0))
5948 (skip-chars-forward " \t")
5949 (setq ind-down (current-column)))))
5950 (list ind ind-up ind-down)))
5952 ;;; The orgstruct minor mode
5954 ;; Define a minor mode which can be used in other modes in order to
5955 ;; integrate the org-mode structure editing commands.
5957 ;; This is really a hack, because the org-mode structure commands use
5958 ;; keys which normally belong to the major mode. Here is how it
5959 ;; works: The minor mode defines all the keys necessary to operate the
5960 ;; structure commands, but wraps the commands into a function which
5961 ;; tests if the cursor is currently at a headline or a plain list
5962 ;; item. If that is the case, the structure command is used,
5963 ;; temporarily setting many Org-mode variables like regular
5964 ;; expressions for filling etc. However, when any of those keys is
5965 ;; used at a different location, function uses `key-binding' to look
5966 ;; up if the key has an associated command in another currently active
5967 ;; keymap (minor modes, major mode, global), and executes that
5968 ;; command. There might be problems if any of the keys is otherwise
5969 ;; used as a prefix key.
5971 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5972 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5973 ;; addresses this by checking explicitly for both bindings.
5975 (defvar orgstruct-mode-map (make-sparse-keymap)
5976 "Keymap for the minor `orgstruct-mode'.")
5978 (defvar org-local-vars nil
5979 "List of local variables, for use by `orgstruct-mode'")
5981 ;;;###autoload
5982 (define-minor-mode orgstruct-mode
5983 "Toggle the minor more `orgstruct-mode'.
5984 This mode is for using Org-mode structure commands in other modes.
5985 The following key behave as if Org-mode was active, if the cursor
5986 is on a headline, or on a plain list item (both in the definition
5987 of Org-mode).
5989 M-up Move entry/item up
5990 M-down Move entry/item down
5991 M-left Promote
5992 M-right Demote
5993 M-S-up Move entry/item up
5994 M-S-down Move entry/item down
5995 M-S-left Promote subtree
5996 M-S-right Demote subtree
5997 M-q Fill paragraph and items like in Org-mode
5998 C-c ^ Sort entries
5999 C-c - Cycle list bullet
6000 TAB Cycle item visibility
6001 M-RET Insert new heading/item
6002 S-M-RET Insert new TODO heading / Chekbox item
6003 C-c C-c Set tags / toggle checkbox"
6004 nil " OrgStruct" nil
6005 (org-load-modules-maybe)
6006 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6008 ;;;###autoload
6009 (defun turn-on-orgstruct ()
6010 "Unconditionally turn on `orgstruct-mode'."
6011 (orgstruct-mode 1))
6013 ;;;###autoload
6014 (defun turn-on-orgstruct++ ()
6015 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6016 In addition to setting orgstruct-mode, this also exports all indentation and
6017 autofilling variables from org-mode into the buffer. Note that turning
6018 off orgstruct-mode will *not* remove these additional settings."
6019 (orgstruct-mode 1)
6020 (let (var val)
6021 (mapc
6022 (lambda (x)
6023 (when (string-match
6024 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6025 (symbol-name (car x)))
6026 (setq var (car x) val (nth 1 x))
6027 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6028 org-local-vars)))
6030 (defun orgstruct-error ()
6031 "Error when there is no default binding for a structure key."
6032 (interactive)
6033 (error "This key has no function outside structure elements"))
6035 (defun orgstruct-setup ()
6036 "Setup orgstruct keymaps."
6037 (let ((nfunc 0)
6038 (bindings
6039 (list
6040 '([(meta up)] org-metaup)
6041 '([(meta down)] org-metadown)
6042 '([(meta left)] org-metaleft)
6043 '([(meta right)] org-metaright)
6044 '([(meta shift up)] org-shiftmetaup)
6045 '([(meta shift down)] org-shiftmetadown)
6046 '([(meta shift left)] org-shiftmetaleft)
6047 '([(meta shift right)] org-shiftmetaright)
6048 '([(shift up)] org-shiftup)
6049 '([(shift down)] org-shiftdown)
6050 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6051 '("\M-q" fill-paragraph)
6052 '("\C-c^" org-sort)
6053 '("\C-c-" org-cycle-list-bullet)))
6054 elt key fun cmd)
6055 (while (setq elt (pop bindings))
6056 (setq nfunc (1+ nfunc))
6057 (setq key (org-key (car elt))
6058 fun (nth 1 elt)
6059 cmd (orgstruct-make-binding fun nfunc key))
6060 (org-defkey orgstruct-mode-map key cmd))
6062 ;; Special treatment needed for TAB and RET
6063 (org-defkey orgstruct-mode-map [(tab)]
6064 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6065 (org-defkey orgstruct-mode-map "\C-i"
6066 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6068 (org-defkey orgstruct-mode-map "\M-\C-m"
6069 (orgstruct-make-binding 'org-insert-heading 105
6070 "\M-\C-m" [(meta return)]))
6071 (org-defkey orgstruct-mode-map [(meta return)]
6072 (orgstruct-make-binding 'org-insert-heading 106
6073 [(meta return)] "\M-\C-m"))
6075 (org-defkey orgstruct-mode-map [(shift meta return)]
6076 (orgstruct-make-binding 'org-insert-todo-heading 107
6077 [(meta return)] "\M-\C-m"))
6079 (unless org-local-vars
6080 (setq org-local-vars (org-get-local-variables)))
6084 (defun orgstruct-make-binding (fun n &rest keys)
6085 "Create a function for binding in the structure minor mode.
6086 FUN is the command to call inside a table. N is used to create a unique
6087 command name. KEYS are keys that should be checked in for a command
6088 to execute outside of tables."
6089 (eval
6090 (list 'defun
6091 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6092 '(arg)
6093 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6094 "Outside of structure, run the binding of `"
6095 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6096 "'.")
6097 '(interactive "p")
6098 (list 'if
6099 '(org-context-p 'headline 'item)
6100 (list 'org-run-like-in-org-mode (list 'quote fun))
6101 (list 'let '(orgstruct-mode)
6102 (list 'call-interactively
6103 (append '(or)
6104 (mapcar (lambda (k)
6105 (list 'key-binding k))
6106 keys)
6107 '('orgstruct-error))))))))
6109 (defun org-context-p (&rest contexts)
6110 "Check if local context is and of CONTEXTS.
6111 Possible values in the list of contexts are `table', `headline', and `item'."
6112 (let ((pos (point)))
6113 (goto-char (point-at-bol))
6114 (prog1 (or (and (memq 'table contexts)
6115 (looking-at "[ \t]*|"))
6116 (and (memq 'headline contexts)
6117 (looking-at "\\*+"))
6118 (and (memq 'item contexts)
6119 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6120 (goto-char pos))))
6122 (defun org-get-local-variables ()
6123 "Return a list of all local variables in an org-mode buffer."
6124 (let (varlist)
6125 (with-current-buffer (get-buffer-create "*Org tmp*")
6126 (erase-buffer)
6127 (org-mode)
6128 (setq varlist (buffer-local-variables)))
6129 (kill-buffer "*Org tmp*")
6130 (delq nil
6131 (mapcar
6132 (lambda (x)
6133 (setq x
6134 (if (symbolp x)
6135 (list x)
6136 (list (car x) (list 'quote (cdr x)))))
6137 (if (string-match
6138 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6139 (symbol-name (car x)))
6140 x nil))
6141 varlist))))
6143 ;;;###autoload
6144 (defun org-run-like-in-org-mode (cmd)
6145 (org-load-modules-maybe)
6146 (unless org-local-vars
6147 (setq org-local-vars (org-get-local-variables)))
6148 (eval (list 'let org-local-vars
6149 (list 'call-interactively (list 'quote cmd)))))
6151 ;;;; Archiving
6153 (defun org-get-category (&optional pos)
6154 "Get the category applying to position POS."
6155 (get-text-property (or pos (point)) 'org-category))
6157 (defun org-refresh-category-properties ()
6158 "Refresh category text properties in the buffer."
6159 (let ((def-cat (cond
6160 ((null org-category)
6161 (if buffer-file-name
6162 (file-name-sans-extension
6163 (file-name-nondirectory buffer-file-name))
6164 "???"))
6165 ((symbolp org-category) (symbol-name org-category))
6166 (t org-category)))
6167 beg end cat pos optionp)
6168 (org-unmodified
6169 (save-excursion
6170 (save-restriction
6171 (widen)
6172 (goto-char (point-min))
6173 (put-text-property (point) (point-max) 'org-category def-cat)
6174 (while (re-search-forward
6175 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6176 (setq pos (match-end 0)
6177 optionp (equal (char-after (match-beginning 0)) ?#)
6178 cat (org-trim (match-string 2)))
6179 (if optionp
6180 (setq beg (point-at-bol) end (point-max))
6181 (org-back-to-heading t)
6182 (setq beg (point) end (org-end-of-subtree t t)))
6183 (put-text-property beg end 'org-category cat)
6184 (goto-char pos)))))))
6187 ;;;; Link Stuff
6189 ;;; Link abbreviations
6191 (defun org-link-expand-abbrev (link)
6192 "Apply replacements as defined in `org-link-abbrev-alist."
6193 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6194 (let* ((key (match-string 1 link))
6195 (as (or (assoc key org-link-abbrev-alist-local)
6196 (assoc key org-link-abbrev-alist)))
6197 (tag (and (match-end 2) (match-string 3 link)))
6198 rpl)
6199 (if (not as)
6200 link
6201 (setq rpl (cdr as))
6202 (cond
6203 ((symbolp rpl) (funcall rpl tag))
6204 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6205 (t (concat rpl tag)))))
6206 link))
6208 ;;; Storing and inserting links
6210 (defvar org-insert-link-history nil
6211 "Minibuffer history for links inserted with `org-insert-link'.")
6213 (defvar org-stored-links nil
6214 "Contains the links stored with `org-store-link'.")
6216 (defvar org-store-link-plist nil
6217 "Plist with info about the most recently link created with `org-store-link'.")
6219 (defvar org-link-protocols nil
6220 "Link protocols added to Org-mode using `org-add-link-type'.")
6222 (defvar org-store-link-functions nil
6223 "List of functions that are called to create and store a link.
6224 Each function will be called in turn until one returns a non-nil
6225 value. Each function should check if it is responsible for creating
6226 this link (for example by looking at the major mode).
6227 If not, it must exit and return nil.
6228 If yes, it should return a non-nil value after a calling
6229 `org-store-link-props' with a list of properties and values.
6230 Special properties are:
6232 :type The link prefix. like \"http\". This must be given.
6233 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6234 This is obligatory as well.
6235 :description Optional default description for the second pair
6236 of brackets in an Org-mode link. The user can still change
6237 this when inserting this link into an Org-mode buffer.
6239 In addition to these, any additional properties can be specified
6240 and then used in remember templates.")
6242 (defun org-add-link-type (type &optional follow export)
6243 "Add TYPE to the list of `org-link-types'.
6244 Re-compute all regular expressions depending on `org-link-types'
6246 FOLLOW and EXPORT are two functions.
6248 FOLLOW should take the link path as the single argument and do whatever
6249 is necessary to follow the link, for example find a file or display
6250 a mail message.
6252 EXPORT should format the link path for export to one of the export formats.
6253 It should be a function accepting three arguments:
6255 path the path of the link, the text after the prefix (like \"http:\")
6256 desc the description of the link, if any, nil if there was no descripton
6257 format the export format, a symbol like `html' or `latex'.
6259 The function may use the FORMAT information to return different values
6260 depending on the format. The return value will be put literally into
6261 the exported file.
6262 Org-mode has a built-in default for exporting links. If you are happy with
6263 this default, there is no need to define an export function for the link
6264 type. For a simple example of an export function, see `org-bbdb.el'."
6265 (add-to-list 'org-link-types type t)
6266 (org-make-link-regexps)
6267 (if (assoc type org-link-protocols)
6268 (setcdr (assoc type org-link-protocols) (list follow export))
6269 (push (list type follow export) org-link-protocols)))
6272 ;;;###autoload
6273 (defun org-store-link (arg)
6274 "\\<org-mode-map>Store an org-link to the current location.
6275 This link is added to `org-stored-links' and can later be inserted
6276 into an org-buffer with \\[org-insert-link].
6278 For some link types, a prefix arg is interpreted:
6279 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6280 For file links, arg negates `org-context-in-file-links'."
6281 (interactive "P")
6282 (org-load-modules-maybe)
6283 (setq org-store-link-plist nil) ; reset
6284 (let (link cpltxt desc description search txt)
6285 (cond
6287 ((run-hook-with-args-until-success 'org-store-link-functions)
6288 (setq link (plist-get org-store-link-plist :link)
6289 desc (or (plist-get org-store-link-plist :description) link)))
6291 ((eq major-mode 'calendar-mode)
6292 (let ((cd (calendar-cursor-to-date)))
6293 (setq link
6294 (format-time-string
6295 (car org-time-stamp-formats)
6296 (apply 'encode-time
6297 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6298 nil nil nil))))
6299 (org-store-link-props :type "calendar" :date cd)))
6301 ((eq major-mode 'w3-mode)
6302 (setq cpltxt (url-view-url t)
6303 link (org-make-link cpltxt))
6304 (org-store-link-props :type "w3" :url (url-view-url t)))
6306 ((eq major-mode 'w3m-mode)
6307 (setq cpltxt (or w3m-current-title w3m-current-url)
6308 link (org-make-link w3m-current-url))
6309 (org-store-link-props :type "w3m" :url (url-view-url t)))
6311 ((setq search (run-hook-with-args-until-success
6312 'org-create-file-search-functions))
6313 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6314 "::" search))
6315 (setq cpltxt (or description link)))
6317 ((eq major-mode 'image-mode)
6318 (setq cpltxt (concat "file:"
6319 (abbreviate-file-name buffer-file-name))
6320 link (org-make-link cpltxt))
6321 (org-store-link-props :type "image" :file buffer-file-name))
6323 ((eq major-mode 'dired-mode)
6324 ;; link to the file in the current line
6325 (setq cpltxt (concat "file:"
6326 (abbreviate-file-name
6327 (expand-file-name
6328 (dired-get-filename nil t))))
6329 link (org-make-link cpltxt)))
6331 ((and buffer-file-name (org-mode-p))
6332 ;; Just link to current headline
6333 (setq cpltxt (concat "file:"
6334 (abbreviate-file-name buffer-file-name)))
6335 ;; Add a context search string
6336 (when (org-xor org-context-in-file-links arg)
6337 ;; Check if we are on a target
6338 (if (org-in-regexp "<<\\(.*?\\)>>")
6339 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6340 (setq txt (cond
6341 ((org-on-heading-p) nil)
6342 ((org-region-active-p)
6343 (buffer-substring (region-beginning) (region-end)))
6344 (t nil)))
6345 (when (or (null txt) (string-match "\\S-" txt))
6346 (setq cpltxt
6347 (concat cpltxt "::"
6348 (condition-case nil
6349 (org-make-org-heading-search-string txt)
6350 (error "")))
6351 desc "NONE"))))
6352 (if (string-match "::\\'" cpltxt)
6353 (setq cpltxt (substring cpltxt 0 -2)))
6354 (setq link (org-make-link cpltxt)))
6356 ((buffer-file-name (buffer-base-buffer))
6357 ;; Just link to this file here.
6358 (setq cpltxt (concat "file:"
6359 (abbreviate-file-name
6360 (buffer-file-name (buffer-base-buffer)))))
6361 ;; Add a context string
6362 (when (org-xor org-context-in-file-links arg)
6363 (setq txt (if (org-region-active-p)
6364 (buffer-substring (region-beginning) (region-end))
6365 (buffer-substring (point-at-bol) (point-at-eol))))
6366 ;; Only use search option if there is some text.
6367 (when (string-match "\\S-" txt)
6368 (setq cpltxt
6369 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6370 desc "NONE")))
6371 (setq link (org-make-link cpltxt)))
6373 ((interactive-p)
6374 (error "Cannot link to a buffer which is not visiting a file"))
6376 (t (setq link nil)))
6378 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6379 (setq link (or link cpltxt)
6380 desc (or desc cpltxt))
6381 (if (equal desc "NONE") (setq desc nil))
6383 (if (and (interactive-p) link)
6384 (progn
6385 (setq org-stored-links
6386 (cons (list link desc) org-stored-links))
6387 (message "Stored: %s" (or desc link)))
6388 (and link (org-make-link-string link desc)))))
6390 (defun org-store-link-props (&rest plist)
6391 "Store link properties, extract names and addresses."
6392 (let (x adr)
6393 (when (setq x (plist-get plist :from))
6394 (setq adr (mail-extract-address-components x))
6395 (plist-put plist :fromname (car adr))
6396 (plist-put plist :fromaddress (nth 1 adr)))
6397 (when (setq x (plist-get plist :to))
6398 (setq adr (mail-extract-address-components x))
6399 (plist-put plist :toname (car adr))
6400 (plist-put plist :toaddress (nth 1 adr))))
6401 (let ((from (plist-get plist :from))
6402 (to (plist-get plist :to)))
6403 (when (and from to org-from-is-user-regexp)
6404 (plist-put plist :fromto
6405 (if (string-match org-from-is-user-regexp from)
6406 (concat "to %t")
6407 (concat "from %f")))))
6408 (setq org-store-link-plist plist))
6410 (defun org-add-link-props (&rest plist)
6411 "Add these properties to the link property list."
6412 (let (key value)
6413 (while plist
6414 (setq key (pop plist) value (pop plist))
6415 (setq org-store-link-plist
6416 (plist-put org-store-link-plist key value)))))
6418 (defun org-email-link-description (&optional fmt)
6419 "Return the description part of an email link.
6420 This takes information from `org-store-link-plist' and formats it
6421 according to FMT (default from `org-email-link-description-format')."
6422 (setq fmt (or fmt org-email-link-description-format))
6423 (let* ((p org-store-link-plist)
6424 (to (plist-get p :toaddress))
6425 (from (plist-get p :fromaddress))
6426 (table
6427 (list
6428 (cons "%c" (plist-get p :fromto))
6429 (cons "%F" (plist-get p :from))
6430 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6431 (cons "%T" (plist-get p :to))
6432 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6433 (cons "%s" (plist-get p :subject))
6434 (cons "%m" (plist-get p :message-id)))))
6435 (when (string-match "%c" fmt)
6436 ;; Check if the user wrote this message
6437 (if (and org-from-is-user-regexp from to
6438 (save-match-data (string-match org-from-is-user-regexp from)))
6439 (setq fmt (replace-match "to %t" t t fmt))
6440 (setq fmt (replace-match "from %f" t t fmt))))
6441 (org-replace-escapes fmt table)))
6443 (defun org-make-org-heading-search-string (&optional string heading)
6444 "Make search string for STRING or current headline."
6445 (interactive)
6446 (let ((s (or string (org-get-heading))))
6447 (unless (and string (not heading))
6448 ;; We are using a headline, clean up garbage in there.
6449 (if (string-match org-todo-regexp s)
6450 (setq s (replace-match "" t t s)))
6451 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6452 (setq s (replace-match "" t t s)))
6453 (setq s (org-trim s))
6454 (if (string-match (concat "^\\(" org-quote-string "\\|"
6455 org-comment-string "\\)") s)
6456 (setq s (replace-match "" t t s)))
6457 (while (string-match org-ts-regexp s)
6458 (setq s (replace-match "" t t s))))
6459 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6460 (setq s (replace-match " " t t s)))
6461 (or string (setq s (concat "*" s))) ; Add * for headlines
6462 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6464 (defun org-make-link (&rest strings)
6465 "Concatenate STRINGS."
6466 (apply 'concat strings))
6468 (defun org-make-link-string (link &optional description)
6469 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6470 (unless (string-match "\\S-" link)
6471 (error "Empty link"))
6472 (when (stringp description)
6473 ;; Remove brackets from the description, they are fatal.
6474 (while (string-match "\\[" description)
6475 (setq description (replace-match "{" t t description)))
6476 (while (string-match "\\]" description)
6477 (setq description (replace-match "}" t t description))))
6478 (when (equal (org-link-escape link) description)
6479 ;; No description needed, it is identical
6480 (setq description nil))
6481 (when (and (not description)
6482 (not (equal link (org-link-escape link))))
6483 (setq description link))
6484 (concat "[[" (org-link-escape link) "]"
6485 (if description (concat "[" description "]") "")
6486 "]"))
6488 (defconst org-link-escape-chars
6489 '((?\ . "%20")
6490 (?\[ . "%5B")
6491 (?\] . "%5D")
6492 (?\340 . "%E0") ; `a
6493 (?\342 . "%E2") ; ^a
6494 (?\347 . "%E7") ; ,c
6495 (?\350 . "%E8") ; `e
6496 (?\351 . "%E9") ; 'e
6497 (?\352 . "%EA") ; ^e
6498 (?\356 . "%EE") ; ^i
6499 (?\364 . "%F4") ; ^o
6500 (?\371 . "%F9") ; `u
6501 (?\373 . "%FB") ; ^u
6502 (?\; . "%3B")
6503 (?? . "%3F")
6504 (?= . "%3D")
6505 (?+ . "%2B")
6507 "Association list of escapes for some characters problematic in links.
6508 This is the list that is used for internal purposes.")
6510 (defconst org-link-escape-chars-browser
6511 '((?\ . "%20")) ; 32 for the SPC char
6512 "Association list of escapes for some characters problematic in links.
6513 This is the list that is used before handing over to the browser.")
6515 (defun org-link-escape (text &optional table)
6516 "Escape charaters in TEXT that are problematic for links."
6517 (setq table (or table org-link-escape-chars))
6518 (when text
6519 (let ((re (mapconcat (lambda (x) (regexp-quote
6520 (char-to-string (car x))))
6521 table "\\|")))
6522 (while (string-match re text)
6523 (setq text
6524 (replace-match
6525 (cdr (assoc (string-to-char (match-string 0 text))
6526 table))
6527 t t text)))
6528 text)))
6530 (defun org-link-unescape (text &optional table)
6531 "Reverse the action of `org-link-escape'."
6532 (setq table (or table org-link-escape-chars))
6533 (when text
6534 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6535 table "\\|")))
6536 (while (string-match re text)
6537 (setq text
6538 (replace-match
6539 (char-to-string (car (rassoc (match-string 0 text) table)))
6540 t t text)))
6541 text)))
6543 (defun org-xor (a b)
6544 "Exclusive or."
6545 (if a (not b) b))
6547 (defun org-get-header (header)
6548 "Find a header field in the current buffer."
6549 (save-excursion
6550 (goto-char (point-min))
6551 (let ((case-fold-search t) s)
6552 (cond
6553 ((eq header 'from)
6554 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6555 (setq s (match-string 1)))
6556 (while (string-match "\"" s)
6557 (setq s (replace-match "" t t s)))
6558 (if (string-match "[<(].*" s)
6559 (setq s (replace-match "" t t s))))
6560 ((eq header 'message-id)
6561 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6562 (setq s (match-string 1))))
6563 ((eq header 'subject)
6564 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6565 (setq s (match-string 1)))))
6566 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6567 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6568 s)))
6571 (defun org-fixup-message-id-for-http (s)
6572 "Replace special characters in a message id, so it can be used in an http query."
6573 (while (string-match "<" s)
6574 (setq s (replace-match "%3C" t t s)))
6575 (while (string-match ">" s)
6576 (setq s (replace-match "%3E" t t s)))
6577 (while (string-match "@" s)
6578 (setq s (replace-match "%40" t t s)))
6581 ;;;###autoload
6582 (defun org-insert-link-global ()
6583 "Insert a link like Org-mode does.
6584 This command can be called in any mode to insert a link in Org-mode syntax."
6585 (interactive)
6586 (org-load-modules-maybe)
6587 (org-run-like-in-org-mode 'org-insert-link))
6589 (defun org-insert-link (&optional complete-file link-location)
6590 "Insert a link. At the prompt, enter the link.
6592 Completion can be used to select a link previously stored with
6593 `org-store-link'. When the empty string is entered (i.e. if you just
6594 press RET at the prompt), the link defaults to the most recently
6595 stored link. As SPC triggers completion in the minibuffer, you need to
6596 use M-SPC or C-q SPC to force the insertion of a space character.
6598 You will also be prompted for a description, and if one is given, it will
6599 be displayed in the buffer instead of the link.
6601 If there is already a link at point, this command will allow you to edit link
6602 and description parts.
6604 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6605 be selected using completion. The path to the file will be relative to the
6606 current directory if the file is in the current directory or a subdirectory.
6607 Otherwise, the link will be the absolute path as completed in the minibuffer
6608 \(i.e. normally ~/path/to/file).
6610 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6611 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6612 of `org-keep-stored-link-after-insertion'.
6614 If `org-make-link-description-function' is non-nil, this function will be
6615 called with the link target, and the result will be the default
6616 link description.
6618 If the LINK-LOCATION parameter is non-nil, this value will be
6619 used as the link location instead of reading one interactively."
6620 (interactive "P")
6621 (let* ((wcf (current-window-configuration))
6622 (region (if (org-region-active-p)
6623 (buffer-substring (region-beginning) (region-end))))
6624 (remove (and region (list (region-beginning) (region-end))))
6625 (desc region)
6626 tmphist ; byte-compile incorrectly complains about this
6627 (link link-location)
6628 entry file)
6629 (cond
6630 (link-location) ; specified by arg, just use it.
6631 ((org-in-regexp org-bracket-link-regexp 1)
6632 ;; We do have a link at point, and we are going to edit it.
6633 (setq remove (list (match-beginning 0) (match-end 0)))
6634 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6635 (setq link (read-string "Link: "
6636 (org-link-unescape
6637 (org-match-string-no-properties 1)))))
6638 ((or (org-in-regexp org-angle-link-re)
6639 (org-in-regexp org-plain-link-re))
6640 ;; Convert to bracket link
6641 (setq remove (list (match-beginning 0) (match-end 0))
6642 link (read-string "Link: "
6643 (org-remove-angle-brackets (match-string 0)))))
6644 ((equal complete-file '(4))
6645 ;; Completing read for file names.
6646 (setq file (read-file-name "File: "))
6647 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6648 (pwd1 (file-name-as-directory (abbreviate-file-name
6649 (expand-file-name ".")))))
6650 (cond
6651 ((equal complete-file '(16))
6652 (setq link (org-make-link
6653 "file:"
6654 (abbreviate-file-name (expand-file-name file)))))
6655 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6656 (setq link (org-make-link "file:" (match-string 1 file))))
6657 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6658 (expand-file-name file))
6659 (setq link (org-make-link
6660 "file:" (match-string 1 (expand-file-name file)))))
6661 (t (setq link (org-make-link "file:" file))))))
6663 ;; Read link, with completion for stored links.
6664 (with-output-to-temp-buffer "*Org Links*"
6665 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6666 (when org-stored-links
6667 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6668 (princ (mapconcat
6669 (lambda (x)
6670 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6671 (reverse org-stored-links) "\n"))))
6672 (let ((cw (selected-window)))
6673 (select-window (get-buffer-window "*Org Links*"))
6674 (shrink-window-if-larger-than-buffer)
6675 (setq truncate-lines t)
6676 (select-window cw))
6677 ;; Fake a link history, containing the stored links.
6678 (setq tmphist (append (mapcar 'car org-stored-links)
6679 org-insert-link-history))
6680 (unwind-protect
6681 (setq link (org-completing-read
6682 "Link: "
6683 (append
6684 (mapcar (lambda (x) (list (concat (car x) ":")))
6685 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6686 (mapcar (lambda (x) (list (concat x ":")))
6687 org-link-types))
6688 nil nil nil
6689 'tmphist
6690 (or (car (car org-stored-links)))))
6691 (set-window-configuration wcf)
6692 (kill-buffer "*Org Links*"))
6693 (setq entry (assoc link org-stored-links))
6694 (or entry (push link org-insert-link-history))
6695 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6696 (not org-keep-stored-link-after-insertion))
6697 (setq org-stored-links (delq (assoc link org-stored-links)
6698 org-stored-links)))
6699 (setq desc (or desc (nth 1 entry)))))
6701 (if (string-match org-plain-link-re link)
6702 ;; URL-like link, normalize the use of angular brackets.
6703 (setq link (org-make-link (org-remove-angle-brackets link))))
6705 ;; Check if we are linking to the current file with a search option
6706 ;; If yes, simplify the link by using only the search option.
6707 (when (and buffer-file-name
6708 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6709 (let* ((path (match-string 1 link))
6710 (case-fold-search nil)
6711 (search (match-string 2 link)))
6712 (save-match-data
6713 (if (equal (file-truename buffer-file-name) (file-truename path))
6714 ;; We are linking to this same file, with a search option
6715 (setq link search)))))
6717 ;; Check if we can/should use a relative path. If yes, simplify the link
6718 (when (string-match "\\<file:\\(.*\\)" link)
6719 (let* ((path (match-string 1 link))
6720 (origpath path)
6721 (case-fold-search nil))
6722 (cond
6723 ((eq org-link-file-path-type 'absolute)
6724 (setq path (abbreviate-file-name (expand-file-name path))))
6725 ((eq org-link-file-path-type 'noabbrev)
6726 (setq path (expand-file-name path)))
6727 ((eq org-link-file-path-type 'relative)
6728 (setq path (file-relative-name path)))
6730 (save-match-data
6731 (if (string-match (concat "^" (regexp-quote
6732 (file-name-as-directory
6733 (expand-file-name "."))))
6734 (expand-file-name path))
6735 ;; We are linking a file with relative path name.
6736 (setq path (substring (expand-file-name path)
6737 (match-end 0)))))))
6738 (setq link (concat "file:" path))
6739 (if (equal desc origpath)
6740 (setq desc path))))
6742 (if org-make-link-description-function
6743 (setq desc (funcall org-make-link-description-function link desc)))
6745 (setq desc (read-string "Description: " desc))
6746 (unless (string-match "\\S-" desc) (setq desc nil))
6747 (if remove (apply 'delete-region remove))
6748 (insert (org-make-link-string link desc))))
6750 (defun org-completing-read (&rest args)
6751 (let ((minibuffer-local-completion-map
6752 (copy-keymap minibuffer-local-completion-map)))
6753 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6754 (apply 'completing-read args)))
6756 ;;; Opening/following a link
6758 (defvar org-link-search-failed nil)
6760 (defun org-next-link ()
6761 "Move forward to the next link.
6762 If the link is in hidden text, expose it."
6763 (interactive)
6764 (when (and org-link-search-failed (eq this-command last-command))
6765 (goto-char (point-min))
6766 (message "Link search wrapped back to beginning of buffer"))
6767 (setq org-link-search-failed nil)
6768 (let* ((pos (point))
6769 (ct (org-context))
6770 (a (assoc :link ct)))
6771 (if a (goto-char (nth 2 a)))
6772 (if (re-search-forward org-any-link-re nil t)
6773 (progn
6774 (goto-char (match-beginning 0))
6775 (if (org-invisible-p) (org-show-context)))
6776 (goto-char pos)
6777 (setq org-link-search-failed t)
6778 (error "No further link found"))))
6780 (defun org-previous-link ()
6781 "Move backward to the previous link.
6782 If the link is in hidden text, expose it."
6783 (interactive)
6784 (when (and org-link-search-failed (eq this-command last-command))
6785 (goto-char (point-max))
6786 (message "Link search wrapped back to end of buffer"))
6787 (setq org-link-search-failed nil)
6788 (let* ((pos (point))
6789 (ct (org-context))
6790 (a (assoc :link ct)))
6791 (if a (goto-char (nth 1 a)))
6792 (if (re-search-backward org-any-link-re nil t)
6793 (progn
6794 (goto-char (match-beginning 0))
6795 (if (org-invisible-p) (org-show-context)))
6796 (goto-char pos)
6797 (setq org-link-search-failed t)
6798 (error "No further link found"))))
6800 (defun org-find-file-at-mouse (ev)
6801 "Open file link or URL at mouse."
6802 (interactive "e")
6803 (mouse-set-point ev)
6804 (org-open-at-point 'in-emacs))
6806 (defun org-open-at-mouse (ev)
6807 "Open file link or URL at mouse."
6808 (interactive "e")
6809 (mouse-set-point ev)
6810 (org-open-at-point))
6812 (defvar org-window-config-before-follow-link nil
6813 "The window configuration before following a link.
6814 This is saved in case the need arises to restore it.")
6816 (defvar org-open-link-marker (make-marker)
6817 "Marker pointing to the location where `org-open-at-point; was called.")
6819 ;;;###autoload
6820 (defun org-open-at-point-global ()
6821 "Follow a link like Org-mode does.
6822 This command can be called in any mode to follow a link that has
6823 Org-mode syntax."
6824 (interactive)
6825 (org-run-like-in-org-mode 'org-open-at-point))
6827 ;;;###autoload
6828 (defun org-open-link-from-string (s &optional arg)
6829 "Open a link in the string S, as if it was in Org-mode."
6830 (interactive "sLink: \nP")
6831 (with-temp-buffer
6832 (let ((org-inhibit-startup t))
6833 (org-mode)
6834 (insert s)
6835 (goto-char (point-min))
6836 (org-open-at-point arg))))
6838 (defun org-open-at-point (&optional in-emacs)
6839 "Open link at or after point.
6840 If there is no link at point, this function will search forward up to
6841 the end of the current subtree.
6842 Normally, files will be opened by an appropriate application. If the
6843 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6844 (interactive "P")
6845 (org-load-modules-maybe)
6846 (move-marker org-open-link-marker (point))
6847 (setq org-window-config-before-follow-link (current-window-configuration))
6848 (org-remove-occur-highlights nil nil t)
6849 (if (org-at-timestamp-p t)
6850 (org-follow-timestamp-link)
6851 (let (type path link line search (pos (point)))
6852 (catch 'match
6853 (save-excursion
6854 (skip-chars-forward "^]\n\r")
6855 (when (org-in-regexp org-bracket-link-regexp)
6856 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6857 (while (string-match " *\n *" link)
6858 (setq link (replace-match " " t t link)))
6859 (setq link (org-link-expand-abbrev link))
6860 (if (string-match org-link-re-with-space2 link)
6861 (setq type (match-string 1 link) path (match-string 2 link))
6862 (setq type "thisfile" path link))
6863 (throw 'match t)))
6865 (when (get-text-property (point) 'org-linked-text)
6866 (setq type "thisfile"
6867 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6868 (1+ (point)) (point))
6869 path (buffer-substring
6870 (previous-single-property-change pos 'org-linked-text)
6871 (next-single-property-change pos 'org-linked-text)))
6872 (throw 'match t))
6874 (save-excursion
6875 (when (or (org-in-regexp org-angle-link-re)
6876 (org-in-regexp org-plain-link-re))
6877 (setq type (match-string 1) path (match-string 2))
6878 (throw 'match t)))
6879 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6880 (setq type "tree-match"
6881 path (match-string 1))
6882 (throw 'match t))
6883 (save-excursion
6884 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6885 (setq type "tags"
6886 path (match-string 1))
6887 (while (string-match ":" path)
6888 (setq path (replace-match "+" t t path)))
6889 (throw 'match t))))
6890 (unless path
6891 (error "No link found"))
6892 ;; Remove any trailing spaces in path
6893 (if (string-match " +\\'" path)
6894 (setq path (replace-match "" t t path)))
6896 (cond
6898 ((assoc type org-link-protocols)
6899 (funcall (nth 1 (assoc type org-link-protocols)) path))
6901 ((equal type "mailto")
6902 (let ((cmd (car org-link-mailto-program))
6903 (args (cdr org-link-mailto-program)) args1
6904 (address path) (subject "") a)
6905 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6906 (setq address (match-string 1 path)
6907 subject (org-link-escape (match-string 2 path))))
6908 (while args
6909 (cond
6910 ((not (stringp (car args))) (push (pop args) args1))
6911 (t (setq a (pop args))
6912 (if (string-match "%a" a)
6913 (setq a (replace-match address t t a)))
6914 (if (string-match "%s" a)
6915 (setq a (replace-match subject t t a)))
6916 (push a args1))))
6917 (apply cmd (nreverse args1))))
6919 ((member type '("http" "https" "ftp" "news"))
6920 (browse-url (concat type ":" (org-link-escape
6921 path org-link-escape-chars-browser))))
6923 ((member type '("message"))
6924 (browse-url (concat type ":" path)))
6926 ((string= type "tags")
6927 (org-tags-view in-emacs path))
6928 ((string= type "thisfile")
6929 (if in-emacs
6930 (switch-to-buffer-other-window
6931 (org-get-buffer-for-internal-link (current-buffer)))
6932 (org-mark-ring-push))
6933 (let ((cmd `(org-link-search
6934 ,path
6935 ,(cond ((equal in-emacs '(4)) 'occur)
6936 ((equal in-emacs '(16)) 'org-occur)
6937 (t nil))
6938 ,pos)))
6939 (condition-case nil (eval cmd)
6940 (error (progn (widen) (eval cmd))))))
6942 ((string= type "tree-match")
6943 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6945 ((string= type "file")
6946 (if (string-match "::\\([0-9]+\\)\\'" path)
6947 (setq line (string-to-number (match-string 1 path))
6948 path (substring path 0 (match-beginning 0)))
6949 (if (string-match "::\\(.+\\)\\'" path)
6950 (setq search (match-string 1 path)
6951 path (substring path 0 (match-beginning 0)))))
6952 (if (string-match "[*?{]" (file-name-nondirectory path))
6953 (dired path)
6954 (org-open-file path in-emacs line search)))
6956 ((string= type "news")
6957 (require 'org-gnus)
6958 (org-gnus-follow-link path))
6960 ((string= type "shell")
6961 (let ((cmd path))
6962 (if (or (not org-confirm-shell-link-function)
6963 (funcall org-confirm-shell-link-function
6964 (format "Execute \"%s\" in shell? "
6965 (org-add-props cmd nil
6966 'face 'org-warning))))
6967 (progn
6968 (message "Executing %s" cmd)
6969 (shell-command cmd))
6970 (error "Abort"))))
6972 ((string= type "elisp")
6973 (let ((cmd path))
6974 (if (or (not org-confirm-elisp-link-function)
6975 (funcall org-confirm-elisp-link-function
6976 (format "Execute \"%s\" as elisp? "
6977 (org-add-props cmd nil
6978 'face 'org-warning))))
6979 (message "%s => %s" cmd (eval (read cmd)))
6980 (error "Abort"))))
6983 (browse-url-at-point)))))
6984 (move-marker org-open-link-marker nil)
6985 (run-hook-with-args 'org-follow-link-hook))
6987 ;;;; Time estimates
6989 (defun org-get-effort (&optional pom)
6990 "Get the effort estimate for the current entry."
6991 (org-entry-get pom org-effort-property))
6993 ;;; File search
6995 (defvar org-create-file-search-functions nil
6996 "List of functions to construct the right search string for a file link.
6997 These functions are called in turn with point at the location to
6998 which the link should point.
7000 A function in the hook should first test if it would like to
7001 handle this file type, for example by checking the major-mode or
7002 the file extension. If it decides not to handle this file, it
7003 should just return nil to give other functions a chance. If it
7004 does handle the file, it must return the search string to be used
7005 when following the link. The search string will be part of the
7006 file link, given after a double colon, and `org-open-at-point'
7007 will automatically search for it. If special measures must be
7008 taken to make the search successful, another function should be
7009 added to the companion hook `org-execute-file-search-functions',
7010 which see.
7012 A function in this hook may also use `setq' to set the variable
7013 `description' to provide a suggestion for the descriptive text to
7014 be used for this link when it gets inserted into an Org-mode
7015 buffer with \\[org-insert-link].")
7017 (defvar org-execute-file-search-functions nil
7018 "List of functions to execute a file search triggered by a link.
7020 Functions added to this hook must accept a single argument, the
7021 search string that was part of the file link, the part after the
7022 double colon. The function must first check if it would like to
7023 handle this search, for example by checking the major-mode or the
7024 file extension. If it decides not to handle this search, it
7025 should just return nil to give other functions a chance. If it
7026 does handle the search, it must return a non-nil value to keep
7027 other functions from trying.
7029 Each function can access the current prefix argument through the
7030 variable `current-prefix-argument'. Note that a single prefix is
7031 used to force opening a link in Emacs, so it may be good to only
7032 use a numeric or double prefix to guide the search function.
7034 In case this is needed, a function in this hook can also restore
7035 the window configuration before `org-open-at-point' was called using:
7037 (set-window-configuration org-window-config-before-follow-link)")
7039 (defun org-link-search (s &optional type avoid-pos)
7040 "Search for a link search option.
7041 If S is surrounded by forward slashes, it is interpreted as a
7042 regular expression. In org-mode files, this will create an `org-occur'
7043 sparse tree. In ordinary files, `occur' will be used to list matches.
7044 If the current buffer is in `dired-mode', grep will be used to search
7045 in all files. If AVOID-POS is given, ignore matches near that position."
7046 (let ((case-fold-search t)
7047 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7048 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7049 (append '(("") (" ") ("\t") ("\n"))
7050 org-emphasis-alist)
7051 "\\|") "\\)"))
7052 (pos (point))
7053 (pre nil) (post nil)
7054 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7055 (cond
7056 ;; First check if there are any special
7057 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7058 ;; Now try the builtin stuff
7059 ((save-excursion
7060 (goto-char (point-min))
7061 (and
7062 (re-search-forward
7063 (concat "<<" (regexp-quote s0) ">>") nil t)
7064 (setq type 'dedicated
7065 pos (match-beginning 0))))
7066 ;; There is an exact target for this
7067 (goto-char pos))
7068 ((string-match "^/\\(.*\\)/$" s)
7069 ;; A regular expression
7070 (cond
7071 ((org-mode-p)
7072 (org-occur (match-string 1 s)))
7073 ;;((eq major-mode 'dired-mode)
7074 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7075 (t (org-do-occur (match-string 1 s)))))
7077 ;; A normal search strings
7078 (when (equal (string-to-char s) ?*)
7079 ;; Anchor on headlines, post may include tags.
7080 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7081 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7082 s (substring s 1)))
7083 (remove-text-properties
7084 0 (length s)
7085 '(face nil mouse-face nil keymap nil fontified nil) s)
7086 ;; Make a series of regular expressions to find a match
7087 (setq words (org-split-string s "[ \n\r\t]+")
7089 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7090 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7091 "\\)" markers)
7092 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7093 re2a (concat "[ \t\r\n]" re2a_)
7094 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7095 re4 (concat "[^a-zA-Z_]" re4_)
7097 re1 (concat pre re2 post)
7098 re3 (concat pre (if pre re4_ re4) post)
7099 re5 (concat pre ".*" re4)
7100 re2 (concat pre re2)
7101 re2a (concat pre (if pre re2a_ re2a))
7102 re4 (concat pre (if pre re4_ re4))
7103 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7104 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7105 re5 "\\)"
7107 (cond
7108 ((eq type 'org-occur) (org-occur reall))
7109 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7110 (t (goto-char (point-min))
7111 (setq type 'fuzzy)
7112 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7113 (org-search-not-self 1 re1 nil t)
7114 (org-search-not-self 1 re2 nil t)
7115 (org-search-not-self 1 re2a nil t)
7116 (org-search-not-self 1 re3 nil t)
7117 (org-search-not-self 1 re4 nil t)
7118 (org-search-not-self 1 re5 nil t)
7120 (goto-char (match-beginning 1))
7121 (goto-char pos)
7122 (error "No match")))))
7124 ;; Normal string-search
7125 (goto-char (point-min))
7126 (if (search-forward s nil t)
7127 (goto-char (match-beginning 0))
7128 (error "No match"))))
7129 (and (org-mode-p) (org-show-context 'link-search))
7130 type))
7132 (defun org-search-not-self (group &rest args)
7133 "Execute `re-search-forward', but only accept matches that do not
7134 enclose the position of `org-open-link-marker'."
7135 (let ((m org-open-link-marker))
7136 (catch 'exit
7137 (while (apply 're-search-forward args)
7138 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7139 (goto-char (match-end group))
7140 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7141 (> (match-beginning 0) (marker-position m))
7142 (< (match-end 0) (marker-position m)))
7143 (save-match-data
7144 (or (not (org-in-regexp
7145 org-bracket-link-analytic-regexp 1))
7146 (not (match-end 4)) ; no description
7147 (and (<= (match-beginning 4) (point))
7148 (>= (match-end 4) (point))))))
7149 (throw 'exit (point))))))))
7151 (defun org-get-buffer-for-internal-link (buffer)
7152 "Return a buffer to be used for displaying the link target of internal links."
7153 (cond
7154 ((not org-display-internal-link-with-indirect-buffer)
7155 buffer)
7156 ((string-match "(Clone)$" (buffer-name buffer))
7157 (message "Buffer is already a clone, not making another one")
7158 ;; we also do not modify visibility in this case
7159 buffer)
7160 (t ; make a new indirect buffer for displaying the link
7161 (let* ((bn (buffer-name buffer))
7162 (ibn (concat bn "(Clone)"))
7163 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7164 (with-current-buffer ib (org-overview))
7165 ib))))
7167 (defun org-do-occur (regexp &optional cleanup)
7168 "Call the Emacs command `occur'.
7169 If CLEANUP is non-nil, remove the printout of the regular expression
7170 in the *Occur* buffer. This is useful if the regex is long and not useful
7171 to read."
7172 (occur regexp)
7173 (when cleanup
7174 (let ((cwin (selected-window)) win beg end)
7175 (when (setq win (get-buffer-window "*Occur*"))
7176 (select-window win))
7177 (goto-char (point-min))
7178 (when (re-search-forward "match[a-z]+" nil t)
7179 (setq beg (match-end 0))
7180 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7181 (setq end (1- (match-beginning 0)))))
7182 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7183 (goto-char (point-min))
7184 (select-window cwin))))
7186 ;;; The mark ring for links jumps
7188 (defvar org-mark-ring nil
7189 "Mark ring for positions before jumps in Org-mode.")
7190 (defvar org-mark-ring-last-goto nil
7191 "Last position in the mark ring used to go back.")
7192 ;; Fill and close the ring
7193 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7194 (loop for i from 1 to org-mark-ring-length do
7195 (push (make-marker) org-mark-ring))
7196 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7197 org-mark-ring)
7199 (defun org-mark-ring-push (&optional pos buffer)
7200 "Put the current position or POS into the mark ring and rotate it."
7201 (interactive)
7202 (setq pos (or pos (point)))
7203 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7204 (move-marker (car org-mark-ring)
7205 (or pos (point))
7206 (or buffer (current-buffer)))
7207 (message "%s"
7208 (substitute-command-keys
7209 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7211 (defun org-mark-ring-goto (&optional n)
7212 "Jump to the previous position in the mark ring.
7213 With prefix arg N, jump back that many stored positions. When
7214 called several times in succession, walk through the entire ring.
7215 Org-mode commands jumping to a different position in the current file,
7216 or to another Org-mode file, automatically push the old position
7217 onto the ring."
7218 (interactive "p")
7219 (let (p m)
7220 (if (eq last-command this-command)
7221 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7222 (setq p org-mark-ring))
7223 (setq org-mark-ring-last-goto p)
7224 (setq m (car p))
7225 (switch-to-buffer (marker-buffer m))
7226 (goto-char m)
7227 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7229 (defun org-remove-angle-brackets (s)
7230 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7231 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7233 (defun org-add-angle-brackets (s)
7234 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7235 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7237 (defun org-remove-double-quotes (s)
7238 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7239 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7242 ;;; Following specific links
7244 (defun org-follow-timestamp-link ()
7245 (cond
7246 ((org-at-date-range-p t)
7247 (let ((org-agenda-start-on-weekday)
7248 (t1 (match-string 1))
7249 (t2 (match-string 2)))
7250 (setq t1 (time-to-days (org-time-string-to-time t1))
7251 t2 (time-to-days (org-time-string-to-time t2)))
7252 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7253 ((org-at-timestamp-p t)
7254 (org-agenda-list nil (time-to-days (org-time-string-to-time
7255 (substring (match-string 1) 0 10)))
7257 (t (error "This should not happen"))))
7260 ;;; Following file links
7261 (defvar org-wait nil)
7262 (defun org-open-file (path &optional in-emacs line search)
7263 "Open the file at PATH.
7264 First, this expands any special file name abbreviations. Then the
7265 configuration variable `org-file-apps' is checked if it contains an
7266 entry for this file type, and if yes, the corresponding command is launched.
7267 If no application is found, Emacs simply visits the file.
7268 With optional argument IN-EMACS, Emacs will visit the file.
7269 Optional LINE specifies a line to go to, optional SEARCH a string to
7270 search for. If LINE or SEARCH is given, the file will always be
7271 opened in Emacs.
7272 If the file does not exist, an error is thrown."
7273 (setq in-emacs (or in-emacs line search))
7274 (let* ((file (if (equal path "")
7275 buffer-file-name
7276 (substitute-in-file-name (expand-file-name path))))
7277 (apps (append org-file-apps (org-default-apps)))
7278 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7279 (dirp (if remp nil (file-directory-p file)))
7280 (dfile (downcase file))
7281 (old-buffer (current-buffer))
7282 (old-pos (point))
7283 (old-mode major-mode)
7284 ext cmd)
7285 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7286 (setq ext (match-string 1 dfile))
7287 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7288 (setq ext (match-string 1 dfile))))
7289 (if in-emacs
7290 (setq cmd 'emacs)
7291 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7292 (and dirp (cdr (assoc 'directory apps)))
7293 (cdr (assoc ext apps))
7294 (cdr (assoc t apps)))))
7295 (when (eq cmd 'mailcap)
7296 (require 'mailcap)
7297 (mailcap-parse-mailcaps)
7298 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7299 (command (mailcap-mime-info mime-type)))
7300 (if (stringp command)
7301 (setq cmd command)
7302 (setq cmd 'emacs))))
7303 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7304 (not (file-exists-p file))
7305 (not org-open-non-existing-files))
7306 (error "No such file: %s" file))
7307 (cond
7308 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7309 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7310 (while (string-match "['\"]%s['\"]" cmd)
7311 (setq cmd (replace-match "%s" t t cmd)))
7312 (while (string-match "%s" cmd)
7313 (setq cmd (replace-match
7314 (save-match-data (shell-quote-argument file))
7315 t t cmd)))
7316 (save-window-excursion
7317 (start-process-shell-command cmd nil cmd)
7318 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7320 ((or (stringp cmd)
7321 (eq cmd 'emacs))
7322 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7323 (widen)
7324 (if line (goto-line line)
7325 (if search (org-link-search search))))
7326 ((consp cmd)
7327 (eval cmd))
7328 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7329 (and (org-mode-p) (eq old-mode 'org-mode)
7330 (or (not (equal old-buffer (current-buffer)))
7331 (not (equal old-pos (point))))
7332 (org-mark-ring-push old-pos old-buffer))))
7334 (defun org-default-apps ()
7335 "Return the default applications for this operating system."
7336 (cond
7337 ((eq system-type 'darwin)
7338 org-file-apps-defaults-macosx)
7339 ((eq system-type 'windows-nt)
7340 org-file-apps-defaults-windowsnt)
7341 (t org-file-apps-defaults-gnu)))
7343 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7344 (defun org-file-remote-p (file)
7345 "Test whether FILE specifies a location on a remote system.
7346 Return non-nil if the location is indeed remote.
7348 For example, the filename \"/user@host:/foo\" specifies a location
7349 on the system \"/user@host:\"."
7350 (cond ((fboundp 'file-remote-p)
7351 (file-remote-p file))
7352 ((fboundp 'tramp-handle-file-remote-p)
7353 (tramp-handle-file-remote-p file))
7354 ((and (boundp 'ange-ftp-name-format)
7355 (string-match (car ange-ftp-name-format) file))
7357 (t nil)))
7360 ;;;; Refiling
7362 (defun org-get-org-file ()
7363 "Read a filename, with default directory `org-directory'."
7364 (let ((default (or org-default-notes-file remember-data-file)))
7365 (read-file-name (format "File name [%s]: " default)
7366 (file-name-as-directory org-directory)
7367 default)))
7369 (defun org-notes-order-reversed-p ()
7370 "Check if the current file should receive notes in reversed order."
7371 (cond
7372 ((not org-reverse-note-order) nil)
7373 ((eq t org-reverse-note-order) t)
7374 ((not (listp org-reverse-note-order)) nil)
7375 (t (catch 'exit
7376 (let ((all org-reverse-note-order)
7377 entry)
7378 (while (setq entry (pop all))
7379 (if (string-match (car entry) buffer-file-name)
7380 (throw 'exit (cdr entry))))
7381 nil)))))
7383 (defvar org-refile-target-table nil
7384 "The list of refile targets, created by `org-refile'.")
7386 (defvar org-agenda-new-buffers nil
7387 "Buffers created to visit agenda files.")
7389 (defun org-get-refile-targets (&optional default-buffer)
7390 "Produce a table with refile targets."
7391 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7392 targets txt re files f desc descre)
7393 (with-current-buffer (or default-buffer (current-buffer))
7394 (while (setq entry (pop entries))
7395 (setq files (car entry) desc (cdr entry))
7396 (cond
7397 ((null files) (setq files (list (current-buffer))))
7398 ((eq files 'org-agenda-files)
7399 (setq files (org-agenda-files 'unrestricted)))
7400 ((and (symbolp files) (fboundp files))
7401 (setq files (funcall files)))
7402 ((and (symbolp files) (boundp files))
7403 (setq files (symbol-value files))))
7404 (if (stringp files) (setq files (list files)))
7405 (cond
7406 ((eq (car desc) :tag)
7407 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7408 ((eq (car desc) :todo)
7409 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7410 ((eq (car desc) :regexp)
7411 (setq descre (cdr desc)))
7412 ((eq (car desc) :level)
7413 (setq descre (concat "^\\*\\{" (number-to-string
7414 (if org-odd-levels-only
7415 (1- (* 2 (cdr desc)))
7416 (cdr desc)))
7417 "\\}[ \t]")))
7418 ((eq (car desc) :maxlevel)
7419 (setq descre (concat "^\\*\\{1," (number-to-string
7420 (if org-odd-levels-only
7421 (1- (* 2 (cdr desc)))
7422 (cdr desc)))
7423 "\\}[ \t]")))
7424 (t (error "Bad refiling target description %s" desc)))
7425 (while (setq f (pop files))
7426 (save-excursion
7427 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7428 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7429 (save-excursion
7430 (save-restriction
7431 (widen)
7432 (goto-char (point-min))
7433 (while (re-search-forward descre nil t)
7434 (goto-char (point-at-bol))
7435 (when (looking-at org-complex-heading-regexp)
7436 (setq txt (match-string 4)
7437 re (concat "^" (regexp-quote
7438 (buffer-substring (match-beginning 1)
7439 (match-end 4)))))
7440 (if (match-end 5) (setq re (concat re "[ \t]+"
7441 (regexp-quote
7442 (match-string 5)))))
7443 (setq re (concat re "[ \t]*$"))
7444 (when org-refile-use-outline-path
7445 (setq txt (mapconcat 'identity
7446 (append
7447 (if (eq org-refile-use-outline-path 'file)
7448 (list (file-name-nondirectory
7449 (buffer-file-name (buffer-base-buffer))))
7450 (if (eq org-refile-use-outline-path 'full-file-path)
7451 (list (buffer-file-name (buffer-base-buffer)))))
7452 (org-get-outline-path)
7453 (list txt))
7454 "/")))
7455 (push (list txt f re (point)) targets))
7456 (goto-char (point-at-eol))))))))
7457 (nreverse targets))))
7459 (defun org-get-outline-path ()
7460 "Return the outline path to the current entry, as a list."
7461 (let (rtn)
7462 (save-excursion
7463 (while (org-up-heading-safe)
7464 (when (looking-at org-complex-heading-regexp)
7465 (push (org-match-string-no-properties 4) rtn)))
7466 rtn)))
7468 (defvar org-refile-history nil
7469 "History for refiling operations.")
7471 (defun org-refile (&optional goto default-buffer)
7472 "Move the entry at point to another heading.
7473 The list of target headings is compiled using the information in
7474 `org-refile-targets', which see. This list is created before each use
7475 and will therefore always be up-to-date.
7477 At the target location, the entry is filed as a subitem of the target heading.
7478 Depending on `org-reverse-note-order', the new subitem will either be the
7479 first of the last subitem.
7481 With prefix arg GOTO, the command will only visit the target location,
7482 not actually move anything.
7483 With a double prefix `C-c C-c', go to the location where the last refiling
7484 operation has put the subtree."
7485 (interactive "P")
7486 (let* ((cbuf (current-buffer))
7487 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7488 pos it nbuf file re level reversed)
7489 (if (equal goto '(16))
7490 (org-refile-goto-last-stored)
7491 (when (setq it (org-refile-get-location
7492 (if goto "Goto: " "Refile to: ") default-buffer))
7493 (setq file (nth 1 it)
7494 re (nth 2 it)
7495 pos (nth 3 it))
7496 (setq nbuf (or (find-buffer-visiting file)
7497 (find-file-noselect file)))
7498 (if goto
7499 (progn
7500 (switch-to-buffer nbuf)
7501 (goto-char pos)
7502 (org-show-context 'org-goto))
7503 (org-copy-subtree 1 nil t)
7504 (save-excursion
7505 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7506 (find-file-noselect file))))
7507 (setq reversed (org-notes-order-reversed-p))
7508 (save-excursion
7509 (save-restriction
7510 (widen)
7511 (goto-char pos)
7512 (looking-at outline-regexp)
7513 (setq level (org-get-valid-level (funcall outline-level) 1))
7514 (goto-char
7515 (if reversed
7516 (outline-next-heading)
7517 (or (save-excursion (outline-get-next-sibling))
7518 (org-end-of-subtree t t)
7519 (point-max))))
7520 (bookmark-set "org-refile-last-stored")
7521 (org-paste-subtree level))))
7522 (org-cut-subtree)
7523 (setq org-markers-to-move nil)
7524 (message "Entry refiled to \"%s\"" (car it)))))))
7526 (defun org-refile-goto-last-stored ()
7527 "Go to the location where the last refile was stored."
7528 (interactive)
7529 (bookmark-jump "org-refile-last-stored")
7530 (message "This is the location of the last refile"))
7532 (defun org-refile-get-location (&optional prompt default-buffer)
7533 "Prompt the user for a refile location, using PROMPT."
7534 (let ((org-refile-targets org-refile-targets)
7535 (org-refile-use-outline-path org-refile-use-outline-path))
7536 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7537 (unless org-refile-target-table
7538 (error "No refile targets"))
7539 (let* ((cbuf (current-buffer))
7540 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7541 (fname (and filename (file-truename filename)))
7542 (tbl (mapcar
7543 (lambda (x)
7544 (if (not (equal fname (file-truename (nth 1 x))))
7545 (cons (concat (car x) " (" (file-name-nondirectory
7546 (nth 1 x)) ")")
7547 (cdr x))
7549 org-refile-target-table))
7550 (completion-ignore-case t))
7551 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7552 tbl)))
7554 ;;;; Dynamic blocks
7556 (defun org-find-dblock (name)
7557 "Find the first dynamic block with name NAME in the buffer.
7558 If not found, stay at current position and return nil."
7559 (let (pos)
7560 (save-excursion
7561 (goto-char (point-min))
7562 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7563 nil t)
7564 (match-beginning 0))))
7565 (if pos (goto-char pos))
7566 pos))
7568 (defconst org-dblock-start-re
7569 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7570 "Matches the startline of a dynamic block, with parameters.")
7572 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7573 "Matches the end of a dyhamic block.")
7575 (defun org-create-dblock (plist)
7576 "Create a dynamic block section, with parameters taken from PLIST.
7577 PLIST must containe a :name entry which is used as name of the block."
7578 (unless (bolp) (newline))
7579 (let ((name (plist-get plist :name)))
7580 (insert "#+BEGIN: " name)
7581 (while plist
7582 (if (eq (car plist) :name)
7583 (setq plist (cddr plist))
7584 (insert " " (prin1-to-string (pop plist)))))
7585 (insert "\n\n#+END:\n")
7586 (beginning-of-line -2)))
7588 (defun org-prepare-dblock ()
7589 "Prepare dynamic block for refresh.
7590 This empties the block, puts the cursor at the insert position and returns
7591 the property list including an extra property :name with the block name."
7592 (unless (looking-at org-dblock-start-re)
7593 (error "Not at a dynamic block"))
7594 (let* ((begdel (1+ (match-end 0)))
7595 (name (org-no-properties (match-string 1)))
7596 (params (append (list :name name)
7597 (read (concat "(" (match-string 3) ")")))))
7598 (unless (re-search-forward org-dblock-end-re nil t)
7599 (error "Dynamic block not terminated"))
7600 (setq params
7601 (append params
7602 (list :content (buffer-substring
7603 begdel (match-beginning 0)))))
7604 (delete-region begdel (match-beginning 0))
7605 (goto-char begdel)
7606 (open-line 1)
7607 params))
7609 (defun org-map-dblocks (&optional command)
7610 "Apply COMMAND to all dynamic blocks in the current buffer.
7611 If COMMAND is not given, use `org-update-dblock'."
7612 (let ((cmd (or command 'org-update-dblock))
7613 pos)
7614 (save-excursion
7615 (goto-char (point-min))
7616 (while (re-search-forward org-dblock-start-re nil t)
7617 (goto-char (setq pos (match-beginning 0)))
7618 (condition-case nil
7619 (funcall cmd)
7620 (error (message "Error during update of dynamic block")))
7621 (goto-char pos)
7622 (unless (re-search-forward org-dblock-end-re nil t)
7623 (error "Dynamic block not terminated"))))))
7625 (defun org-dblock-update (&optional arg)
7626 "User command for updating dynamic blocks.
7627 Update the dynamic block at point. With prefix ARG, update all dynamic
7628 blocks in the buffer."
7629 (interactive "P")
7630 (if arg
7631 (org-update-all-dblocks)
7632 (or (looking-at org-dblock-start-re)
7633 (org-beginning-of-dblock))
7634 (org-update-dblock)))
7636 (defun org-update-dblock ()
7637 "Update the dynamic block at point
7638 This means to empty the block, parse for parameters and then call
7639 the correct writing function."
7640 (save-window-excursion
7641 (let* ((pos (point))
7642 (line (org-current-line))
7643 (params (org-prepare-dblock))
7644 (name (plist-get params :name))
7645 (cmd (intern (concat "org-dblock-write:" name))))
7646 (message "Updating dynamic block `%s' at line %d..." name line)
7647 (funcall cmd params)
7648 (message "Updating dynamic block `%s' at line %d...done" name line)
7649 (goto-char pos))))
7651 (defun org-beginning-of-dblock ()
7652 "Find the beginning of the dynamic block at point.
7653 Error if there is no scuh block at point."
7654 (let ((pos (point))
7655 beg)
7656 (end-of-line 1)
7657 (if (and (re-search-backward org-dblock-start-re nil t)
7658 (setq beg (match-beginning 0))
7659 (re-search-forward org-dblock-end-re nil t)
7660 (> (match-end 0) pos))
7661 (goto-char beg)
7662 (goto-char pos)
7663 (error "Not in a dynamic block"))))
7665 (defun org-update-all-dblocks ()
7666 "Update all dynamic blocks in the buffer.
7667 This function can be used in a hook."
7668 (when (org-mode-p)
7669 (org-map-dblocks 'org-update-dblock)))
7672 ;;;; Completion
7674 (defconst org-additional-option-like-keywords
7675 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7676 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7677 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7679 (defcustom org-structure-template-alist
7681 ("s" "#+begin_src ?\n\n#+end_src")
7682 ("e" "#+begin_example\n?\n#+end_example")
7683 ("q" "#+begin_quote\n?\n#+end_quote")
7684 ("v" "#+begin_verse\n?\n#+end_verse")
7685 ("l" "#+begin_latex\n?\n#+end_latex")
7686 ("L" "#+latex: ")
7687 ("h" "#+begin_html\n?\n#+end_html")
7688 ("H" "#+html: ")
7689 ("a" "#+begin_ascii\n?\n#+end_ascii")
7690 ("A" "#+ascii: ")
7691 ("i" "#+include: %file ?")
7693 "Structure completion elements.
7694 This is a list of abbreviation keys and values. The value gets inserted
7695 it you type @samp{.} followed by the key and then the completion key,
7696 usually `M-TAB'. %file will be replaced by a file name after prompting
7697 for the file uning completion.
7698 This is an experimental feature, it is undecided if it is going to stay in."
7699 :group 'org-completion
7700 :type '(repeat
7701 (string :tag "Key") (string :tag "Template")))
7703 (defun org-complete-expand-structure-template (start cell)
7704 "Expand a structure template."
7705 (let ((rpl (nth 1 cell)))
7706 (delete-region start (point))
7707 (when (string-match "\\`#\\+" rpl)
7708 (cond
7709 ((bolp))
7710 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7711 (delete-region (point-at-bol) (point)))
7712 (t (newline))))
7713 (setq start (point))
7714 (if (string-match "%file" rpl)
7715 (setq rpl (replace-match
7716 (concat
7717 "\""
7718 (save-match-data
7719 (abbreviate-file-name (read-file-name "Include file: ")))
7720 "\"")
7721 t t rpl)))
7722 (insert rpl)
7723 (if (re-search-backward "\\?" start t) (delete-char 1))))
7726 (defun org-complete (&optional arg)
7727 "Perform completion on word at point.
7728 At the beginning of a headline, this completes TODO keywords as given in
7729 `org-todo-keywords'.
7730 If the current word is preceded by a backslash, completes the TeX symbols
7731 that are supported for HTML support.
7732 If the current word is preceded by \"#+\", completes special words for
7733 setting file options.
7734 In the line after \"#+STARTUP:, complete valid keywords.\"
7735 At all other locations, this simply calls the value of
7736 `org-completion-fallback-command'."
7737 (interactive "P")
7738 (org-without-partial-completion
7739 (catch 'exit
7740 (let* ((a nil)
7741 (end (point))
7742 (beg1 (save-excursion
7743 (skip-chars-backward (org-re "[:alnum:]_@"))
7744 (point)))
7745 (beg (save-excursion
7746 (skip-chars-backward "a-zA-Z0-9_:$")
7747 (point)))
7748 (confirm (lambda (x) (stringp (car x))))
7749 (searchhead (equal (char-before beg) ?*))
7750 (struct
7751 (when (and (equal (char-before beg1) ?.)
7752 (setq a (assoc (buffer-substring beg1 (point))
7753 org-structure-template-alist)))
7754 (org-complete-expand-structure-template (1- beg1) a)
7755 (throw 'exit t)))
7756 (tag (and (equal (char-before beg1) ?:)
7757 (equal (char-after (point-at-bol)) ?*)))
7758 (prop (and (equal (char-before beg1) ?:)
7759 (not (equal (char-after (point-at-bol)) ?*))))
7760 (texp (equal (char-before beg) ?\\))
7761 (link (equal (char-before beg) ?\[))
7762 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7763 beg)
7764 "#+"))
7765 (startup (string-match "^#\\+STARTUP:.*"
7766 (buffer-substring (point-at-bol) (point))))
7767 (completion-ignore-case opt)
7768 (type nil)
7769 (tbl nil)
7770 (table (cond
7771 (opt
7772 (setq type :opt)
7773 (require 'org-exp)
7774 (append
7775 (mapcar
7776 (lambda (x)
7777 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7778 (cons (match-string 2 x) (match-string 1 x)))
7779 (org-split-string (org-get-current-options) "\n"))
7780 (mapcar 'list org-additional-option-like-keywords)))
7781 (startup
7782 (setq type :startup)
7783 org-startup-options)
7784 (link (append org-link-abbrev-alist-local
7785 org-link-abbrev-alist))
7786 (texp
7787 (setq type :tex)
7788 org-html-entities)
7789 ((string-match "\\`\\*+[ \t]+\\'"
7790 (buffer-substring (point-at-bol) beg))
7791 (setq type :todo)
7792 (mapcar 'list org-todo-keywords-1))
7793 (searchhead
7794 (setq type :searchhead)
7795 (save-excursion
7796 (goto-char (point-min))
7797 (while (re-search-forward org-todo-line-regexp nil t)
7798 (push (list
7799 (org-make-org-heading-search-string
7800 (match-string 3) t))
7801 tbl)))
7802 tbl)
7803 (tag (setq type :tag beg beg1)
7804 (or org-tag-alist (org-get-buffer-tags)))
7805 (prop (setq type :prop beg beg1)
7806 (mapcar 'list (org-buffer-property-keys nil t t)))
7807 (t (progn
7808 (call-interactively org-completion-fallback-command)
7809 (throw 'exit nil)))))
7810 (pattern (buffer-substring-no-properties beg end))
7811 (completion (try-completion pattern table confirm)))
7812 (cond ((eq completion t)
7813 (if (not (assoc (upcase pattern) table))
7814 (message "Already complete")
7815 (if (and (equal type :opt)
7816 (not (member (car (assoc (upcase pattern) table))
7817 org-additional-option-like-keywords)))
7818 (insert (substring (cdr (assoc (upcase pattern) table))
7819 (length pattern)))
7820 (if (memq type '(:tag :prop)) (insert ":")))))
7821 ((null completion)
7822 (message "Can't find completion for \"%s\"" pattern)
7823 (ding))
7824 ((not (string= pattern completion))
7825 (delete-region beg end)
7826 (if (string-match " +$" completion)
7827 (setq completion (replace-match "" t t completion)))
7828 (insert completion)
7829 (if (get-buffer-window "*Completions*")
7830 (delete-window (get-buffer-window "*Completions*")))
7831 (if (assoc completion table)
7832 (if (eq type :todo) (insert " ")
7833 (if (memq type '(:tag :prop)) (insert ":"))))
7834 (if (and (equal type :opt) (assoc completion table))
7835 (message "%s" (substitute-command-keys
7836 "Press \\[org-complete] again to insert example settings"))))
7838 (message "Making completion list...")
7839 (let ((list (sort (all-completions pattern table confirm)
7840 'string<)))
7841 (with-output-to-temp-buffer "*Completions*"
7842 (condition-case nil
7843 ;; Protection needed for XEmacs and emacs 21
7844 (display-completion-list list pattern)
7845 (error (display-completion-list list)))))
7846 (message "Making completion list...%s" "done")))))))
7848 ;;;; TODO, DEADLINE, Comments
7850 (defun org-toggle-comment ()
7851 "Change the COMMENT state of an entry."
7852 (interactive)
7853 (save-excursion
7854 (org-back-to-heading)
7855 (let (case-fold-search)
7856 (if (looking-at (concat outline-regexp
7857 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7858 (replace-match "" t t nil 1)
7859 (if (looking-at outline-regexp)
7860 (progn
7861 (goto-char (match-end 0))
7862 (insert org-comment-string " ")))))))
7864 (defvar org-last-todo-state-is-todo nil
7865 "This is non-nil when the last TODO state change led to a TODO state.
7866 If the last change removed the TODO tag or switched to DONE, then
7867 this is nil.")
7869 (defvar org-setting-tags nil) ; dynamically skiped
7871 (defun org-parse-local-options (string var)
7872 "Parse STRING for startup setting relevant for variable VAR."
7873 (let ((rtn (symbol-value var))
7874 e opts)
7875 (save-match-data
7876 (if (or (not string) (not (string-match "\\S-" string)))
7878 (setq opts (delq nil (mapcar (lambda (x)
7879 (setq e (assoc x org-startup-options))
7880 (if (eq (nth 1 e) var) e nil))
7881 (org-split-string string "[ \t]+"))))
7882 (if (not opts)
7884 (setq rtn nil)
7885 (while (setq e (pop opts))
7886 (if (not (nth 3 e))
7887 (setq rtn (nth 2 e))
7888 (if (not (listp rtn)) (setq rtn nil))
7889 (push (nth 2 e) rtn)))
7890 rtn)))))
7892 (defvar org-blocker-hook nil
7893 "Hook for functions that are allowed to block a state change.
7895 Each function gets as its single argument a property list, see
7896 `org-trigger-hook' for more information about this list.
7898 If any of the functions in this hook returns nil, the state change
7899 is blocked.")
7901 (defvar org-trigger-hook nil
7902 "Hook for functions that are triggered by a state change.
7904 Each function gets as its single argument a property list with at least
7905 the following elements:
7907 (:type type-of-change :position pos-at-entry-start
7908 :from old-state :to new-state)
7910 Depending on the type, more properties may be present.
7912 This mechanism is currently implemented for:
7914 TODO state changes
7915 ------------------
7916 :type todo-state-change
7917 :from previous state (keyword as a string), or nil
7918 :to new state (keyword as a string), or nil")
7921 (defun org-todo (&optional arg)
7922 "Change the TODO state of an item.
7923 The state of an item is given by a keyword at the start of the heading,
7924 like
7925 *** TODO Write paper
7926 *** DONE Call mom
7928 The different keywords are specified in the variable `org-todo-keywords'.
7929 By default the available states are \"TODO\" and \"DONE\".
7930 So for this example: when the item starts with TODO, it is changed to DONE.
7931 When it starts with DONE, the DONE is removed. And when neither TODO nor
7932 DONE are present, add TODO at the beginning of the heading.
7934 With C-u prefix arg, use completion to determine the new state.
7935 With numeric prefix arg, switch to that state.
7937 For calling through lisp, arg is also interpreted in the following way:
7938 'none -> empty state
7939 \"\"(empty string) -> switch to empty state
7940 'done -> switch to DONE
7941 'nextset -> switch to the next set of keywords
7942 'previousset -> switch to the previous set of keywords
7943 \"WAITING\" -> switch to the specified keyword, but only if it
7944 really is a member of `org-todo-keywords'."
7945 (interactive "P")
7946 (save-excursion
7947 (catch 'exit
7948 (org-back-to-heading)
7949 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7950 (or (looking-at (concat " +" org-todo-regexp " *"))
7951 (looking-at " *"))
7952 (let* ((match-data (match-data))
7953 (startpos (point-at-bol))
7954 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7955 (org-log-done org-log-done)
7956 (org-log-repeat org-log-repeat)
7957 (org-todo-log-states org-todo-log-states)
7958 (this (match-string 1))
7959 (hl-pos (match-beginning 0))
7960 (head (org-get-todo-sequence-head this))
7961 (ass (assoc head org-todo-kwd-alist))
7962 (interpret (nth 1 ass))
7963 (done-word (nth 3 ass))
7964 (final-done-word (nth 4 ass))
7965 (last-state (or this ""))
7966 (completion-ignore-case t)
7967 (member (member this org-todo-keywords-1))
7968 (tail (cdr member))
7969 (state (cond
7970 ((and org-todo-key-trigger
7971 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7972 (and (not arg) org-use-fast-todo-selection
7973 (not (eq org-use-fast-todo-selection 'prefix)))))
7974 ;; Use fast selection
7975 (org-fast-todo-selection))
7976 ((and (equal arg '(4))
7977 (or (not org-use-fast-todo-selection)
7978 (not org-todo-key-trigger)))
7979 ;; Read a state with completion
7980 (completing-read "State: " (mapcar (lambda(x) (list x))
7981 org-todo-keywords-1)
7982 nil t))
7983 ((eq arg 'right)
7984 (if this
7985 (if tail (car tail) nil)
7986 (car org-todo-keywords-1)))
7987 ((eq arg 'left)
7988 (if (equal member org-todo-keywords-1)
7990 (if this
7991 (nth (- (length org-todo-keywords-1) (length tail) 2)
7992 org-todo-keywords-1)
7993 (org-last org-todo-keywords-1))))
7994 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7995 (setq arg nil))) ; hack to fall back to cycling
7996 (arg
7997 ;; user or caller requests a specific state
7998 (cond
7999 ((equal arg "") nil)
8000 ((eq arg 'none) nil)
8001 ((eq arg 'done) (or done-word (car org-done-keywords)))
8002 ((eq arg 'nextset)
8003 (or (car (cdr (member head org-todo-heads)))
8004 (car org-todo-heads)))
8005 ((eq arg 'previousset)
8006 (let ((org-todo-heads (reverse org-todo-heads)))
8007 (or (car (cdr (member head org-todo-heads)))
8008 (car org-todo-heads))))
8009 ((car (member arg org-todo-keywords-1)))
8010 ((nth (1- (prefix-numeric-value arg))
8011 org-todo-keywords-1))))
8012 ((null member) (or head (car org-todo-keywords-1)))
8013 ((equal this final-done-word) nil) ;; -> make empty
8014 ((null tail) nil) ;; -> first entry
8015 ((eq interpret 'sequence)
8016 (car tail))
8017 ((memq interpret '(type priority))
8018 (if (eq this-command last-command)
8019 (car tail)
8020 (if (> (length tail) 0)
8021 (or done-word (car org-done-keywords))
8022 nil)))
8023 (t nil)))
8024 (next (if state (concat " " state " ") " "))
8025 (change-plist (list :type 'todo-state-change :from this :to state
8026 :position startpos))
8027 dolog now-done-p)
8028 (when org-blocker-hook
8029 (unless (save-excursion
8030 (save-match-data
8031 (run-hook-with-args-until-failure
8032 'org-blocker-hook change-plist)))
8033 (if (interactive-p)
8034 (error "TODO state change from %s to %s blocked" this state)
8035 ;; fail silently
8036 (message "TODO state change from %s to %s blocked" this state)
8037 (throw 'exit nil))))
8038 (store-match-data match-data)
8039 (replace-match next t t)
8040 (unless (pos-visible-in-window-p hl-pos)
8041 (message "TODO state changed to %s" (org-trim next)))
8042 (unless head
8043 (setq head (org-get-todo-sequence-head state)
8044 ass (assoc head org-todo-kwd-alist)
8045 interpret (nth 1 ass)
8046 done-word (nth 3 ass)
8047 final-done-word (nth 4 ass)))
8048 (when (memq arg '(nextset previousset))
8049 (message "Keyword-Set %d/%d: %s"
8050 (- (length org-todo-sets) -1
8051 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8052 (length org-todo-sets)
8053 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8054 (setq org-last-todo-state-is-todo
8055 (not (member state org-done-keywords)))
8056 (setq now-done-p (and (member state org-done-keywords)
8057 (not (member this org-done-keywords))))
8058 (and logging (org-local-logging logging))
8059 (when (and (or org-todo-log-states org-log-done)
8060 (not (memq arg '(nextset previousset))))
8061 ;; we need to look at recording a time and note
8062 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8063 (nth 2 (assoc this org-todo-log-states))))
8064 (when (and state
8065 (member state org-not-done-keywords)
8066 (not (member this org-not-done-keywords)))
8067 ;; This is now a todo state and was not one before
8068 ;; If there was a CLOSED time stamp, get rid of it.
8069 (org-add-planning-info nil nil 'closed))
8070 (when (and now-done-p org-log-done)
8071 ;; It is now done, and it was not done before
8072 (org-add-planning-info 'closed (org-current-time))
8073 (if (and (not dolog) (eq 'note org-log-done))
8074 (org-add-log-setup 'done state 'findpos 'note)))
8075 (when (and state dolog)
8076 ;; This is a non-nil state, and we need to log it
8077 (org-add-log-setup 'state state 'findpos dolog)))
8078 ;; Fixup tag positioning
8079 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8080 (run-hooks 'org-after-todo-state-change-hook)
8081 (if (and arg (not (member state org-done-keywords)))
8082 (setq head (org-get-todo-sequence-head state)))
8083 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8084 ;; Do we need to trigger a repeat?
8085 (when now-done-p (org-auto-repeat-maybe state))
8086 ;; Fixup cursor location if close to the keyword
8087 (if (and (outline-on-heading-p)
8088 (not (bolp))
8089 (save-excursion (beginning-of-line 1)
8090 (looking-at org-todo-line-regexp))
8091 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8092 (progn
8093 (goto-char (or (match-end 2) (match-end 1)))
8094 (just-one-space)))
8095 (when org-trigger-hook
8096 (save-excursion
8097 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8099 (defun org-local-logging (value)
8100 "Get logging settings from a property VALUE."
8101 (let* (words w a)
8102 ;; directly set the variables, they are already local.
8103 (setq org-log-done nil
8104 org-log-repeat nil
8105 org-todo-log-states nil)
8106 (setq words (org-split-string value))
8107 (while (setq w (pop words))
8108 (cond
8109 ((setq a (assoc w org-startup-options))
8110 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8111 (set (nth 1 a) (nth 2 a))))
8112 ((setq a (org-extract-log-state-settings w))
8113 (and (member (car a) org-todo-keywords-1)
8114 (push a org-todo-log-states)))))))
8116 (defun org-get-todo-sequence-head (kwd)
8117 "Return the head of the TODO sequence to which KWD belongs.
8118 If KWD is not set, check if there is a text property remembering the
8119 right sequence."
8120 (let (p)
8121 (cond
8122 ((not kwd)
8123 (or (get-text-property (point-at-bol) 'org-todo-head)
8124 (progn
8125 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8126 nil (point-at-eol)))
8127 (get-text-property p 'org-todo-head))))
8128 ((not (member kwd org-todo-keywords-1))
8129 (car org-todo-keywords-1))
8130 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8132 (defun org-fast-todo-selection ()
8133 "Fast TODO keyword selection with single keys.
8134 Returns the new TODO keyword, or nil if no state change should occur."
8135 (let* ((fulltable org-todo-key-alist)
8136 (done-keywords org-done-keywords) ;; needed for the faces.
8137 (maxlen (apply 'max (mapcar
8138 (lambda (x)
8139 (if (stringp (car x)) (string-width (car x)) 0))
8140 fulltable)))
8141 (expert nil)
8142 (fwidth (+ maxlen 3 1 3))
8143 (ncol (/ (- (window-width) 4) fwidth))
8144 tg cnt e c tbl
8145 groups ingroup)
8146 (save-window-excursion
8147 (if expert
8148 (set-buffer (get-buffer-create " *Org todo*"))
8149 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8150 (erase-buffer)
8151 (org-set-local 'org-done-keywords done-keywords)
8152 (setq tbl fulltable cnt 0)
8153 (while (setq e (pop tbl))
8154 (cond
8155 ((equal e '(:startgroup))
8156 (push '() groups) (setq ingroup t)
8157 (when (not (= cnt 0))
8158 (setq cnt 0)
8159 (insert "\n"))
8160 (insert "{ "))
8161 ((equal e '(:endgroup))
8162 (setq ingroup nil cnt 0)
8163 (insert "}\n"))
8165 (setq tg (car e) c (cdr e))
8166 (if ingroup (push tg (car groups)))
8167 (setq tg (org-add-props tg nil 'face
8168 (org-get-todo-face tg)))
8169 (if (and (= cnt 0) (not ingroup)) (insert " "))
8170 (insert "[" c "] " tg (make-string
8171 (- fwidth 4 (length tg)) ?\ ))
8172 (when (= (setq cnt (1+ cnt)) ncol)
8173 (insert "\n")
8174 (if ingroup (insert " "))
8175 (setq cnt 0)))))
8176 (insert "\n")
8177 (goto-char (point-min))
8178 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8179 (fit-window-to-buffer))
8180 (message "[a-z..]:Set [SPC]:clear")
8181 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8182 (cond
8183 ((or (= c ?\C-g)
8184 (and (= c ?q) (not (rassoc c fulltable))))
8185 (setq quit-flag t))
8186 ((= c ?\ ) nil)
8187 ((setq e (rassoc c fulltable) tg (car e))
8189 (t (setq quit-flag t))))))
8191 (defun org-entry-is-todo-p ()
8192 (member (org-get-todo-state) org-not-done-keywords))
8194 (defun org-entry-is-done-p ()
8195 (member (org-get-todo-state) org-done-keywords))
8197 (defun org-get-todo-state ()
8198 (save-excursion
8199 (org-back-to-heading t)
8200 (and (looking-at org-todo-line-regexp)
8201 (match-end 2)
8202 (match-string 2))))
8204 (defun org-at-date-range-p (&optional inactive-ok)
8205 "Is the cursor inside a date range?"
8206 (interactive)
8207 (save-excursion
8208 (catch 'exit
8209 (let ((pos (point)))
8210 (skip-chars-backward "^[<\r\n")
8211 (skip-chars-backward "<[")
8212 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8213 (>= (match-end 0) pos)
8214 (throw 'exit t))
8215 (skip-chars-backward "^<[\r\n")
8216 (skip-chars-backward "<[")
8217 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8218 (>= (match-end 0) pos)
8219 (throw 'exit t)))
8220 nil)))
8222 (defun org-get-repeat ()
8223 "Check if tere is a deadline/schedule with repeater in this entry."
8224 (save-match-data
8225 (save-excursion
8226 (org-back-to-heading t)
8227 (if (re-search-forward
8228 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8229 (match-string 1)))))
8231 (defvar org-last-changed-timestamp)
8232 (defvar org-log-post-message)
8233 (defvar org-log-note-purpose)
8234 (defvar org-log-note-how)
8235 (defun org-auto-repeat-maybe (done-word)
8236 "Check if the current headline contains a repeated deadline/schedule.
8237 If yes, set TODO state back to what it was and change the base date
8238 of repeating deadline/scheduled time stamps to new date.
8239 This function is run automatically after each state change to a DONE state."
8240 ;; last-state is dynamically scoped into this function
8241 (let* ((repeat (org-get-repeat))
8242 (aa (assoc last-state org-todo-kwd-alist))
8243 (interpret (nth 1 aa))
8244 (head (nth 2 aa))
8245 (whata '(("d" . day) ("m" . month) ("y" . year)))
8246 (msg "Entry repeats: ")
8247 (org-log-done nil)
8248 (org-todo-log-states nil)
8249 (nshiftmax 10) (nshift 0)
8250 re type n what ts mb0 time)
8251 (when repeat
8252 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8253 (org-todo (if (eq interpret 'type) last-state head))
8254 (when org-log-repeat
8255 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8256 (memq 'org-add-log-note post-command-hook))
8257 ;; OK, we are already setup for some record
8258 (if (eq org-log-repeat 'note)
8259 ;; make sure we take a note, not only a time stamp
8260 (setq org-log-note-how 'note))
8261 ;; Set up for taking a record
8262 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8263 'findpos org-log-repeat)))
8264 (org-back-to-heading t)
8265 (org-add-planning-info nil nil 'closed)
8266 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8267 org-deadline-time-regexp "\\)\\|\\("
8268 org-ts-regexp "\\)"))
8269 (while (re-search-forward
8270 re (save-excursion (outline-next-heading) (point)) t)
8271 (setq type (if (match-end 1) org-scheduled-string
8272 (if (match-end 3) org-deadline-string "Plain:"))
8273 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8274 mb0 (match-beginning 0))
8275 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8276 (setq n (string-to-number (match-string 2 ts))
8277 what (match-string 3 ts))
8278 (if (equal what "w") (setq n (* n 7) what "d"))
8279 ;; Preparation, see if we need to modify the start date for the change
8280 (when (match-end 1)
8281 (setq time (save-match-data (org-time-string-to-time ts)))
8282 (cond
8283 ((equal (match-string 1 ts) ".")
8284 ;; Shift starting date to today
8285 (org-timestamp-change
8286 (- (time-to-days (current-time)) (time-to-days time))
8287 'day))
8288 ((equal (match-string 1 ts) "+")
8289 (while (or (= nshift 0)
8290 (<= (time-to-days time) (time-to-days (current-time))))
8291 (when (= (incf nshift) nshiftmax)
8292 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8293 (error "Abort")))
8294 (org-timestamp-change n (cdr (assoc what whata)))
8295 (org-at-timestamp-p t)
8296 (setq ts (match-string 1))
8297 (setq time (save-match-data (org-time-string-to-time ts))))
8298 (org-timestamp-change (- n) (cdr (assoc what whata)))
8299 ;; rematch, so that we have everything in place for the real shift
8300 (org-at-timestamp-p t)
8301 (setq ts (match-string 1))
8302 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8303 (org-timestamp-change n (cdr (assoc what whata)))
8304 (setq msg (concat msg type org-last-changed-timestamp " "))))
8305 (setq org-log-post-message msg)
8306 (message "%s" msg))))
8308 (defun org-show-todo-tree (arg)
8309 "Make a compact tree which shows all headlines marked with TODO.
8310 The tree will show the lines where the regexp matches, and all higher
8311 headlines above the match.
8312 With a \\[universal-argument] prefix, also show the DONE entries.
8313 With a numeric prefix N, construct a sparse tree for the Nth element
8314 of `org-todo-keywords-1'."
8315 (interactive "P")
8316 (let ((case-fold-search nil)
8317 (kwd-re
8318 (cond ((null arg) org-not-done-regexp)
8319 ((equal arg '(4))
8320 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8321 (mapcar 'list org-todo-keywords-1))))
8322 (concat "\\("
8323 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8324 "\\)\\>")))
8325 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8326 (regexp-quote (nth (1- (prefix-numeric-value arg))
8327 org-todo-keywords-1)))
8328 (t (error "Invalid prefix argument: %s" arg)))))
8329 (message "%d TODO entries found"
8330 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8332 (defun org-deadline (&optional remove)
8333 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8334 With argument REMOVE, remove any deadline from the item."
8335 (interactive "P")
8336 (if remove
8337 (progn
8338 (org-remove-timestamp-with-keyword org-deadline-string)
8339 (message "Item no longer has a deadline."))
8340 (org-add-planning-info 'deadline nil 'closed)))
8342 (defun org-schedule (&optional remove)
8343 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8344 With argument REMOVE, remove any scheduling date from the item."
8345 (interactive "P")
8346 (if remove
8347 (progn
8348 (org-remove-timestamp-with-keyword org-scheduled-string)
8349 (message "Item is no longer scheduled."))
8350 (org-add-planning-info 'scheduled nil 'closed)))
8352 (defun org-remove-timestamp-with-keyword (keyword)
8353 "Remove all time stamps with KEYWORD in the current entry."
8354 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8355 beg)
8356 (save-excursion
8357 (org-back-to-heading t)
8358 (setq beg (point))
8359 (org-end-of-subtree t t)
8360 (while (re-search-backward re beg t)
8361 (replace-match "")
8362 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8363 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8365 (defun org-add-planning-info (what &optional time &rest remove)
8366 "Insert new timestamp with keyword in the line directly after the headline.
8367 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8368 If non is given, the user is prompted for a date.
8369 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8370 be removed."
8371 (interactive)
8372 (let (org-time-was-given org-end-time-was-given ts
8373 end default-time default-input)
8375 (when (and (not time) (memq what '(scheduled deadline)))
8376 ;; Try to get a default date/time from existing timestamp
8377 (save-excursion
8378 (org-back-to-heading t)
8379 (setq end (save-excursion (outline-next-heading) (point)))
8380 (when (re-search-forward (if (eq what 'scheduled)
8381 org-scheduled-time-regexp
8382 org-deadline-time-regexp)
8383 end t)
8384 (setq ts (match-string 1)
8385 default-time
8386 (apply 'encode-time (org-parse-time-string ts))
8387 default-input (and ts (org-get-compact-tod ts))))))
8388 (when what
8389 ;; If necessary, get the time from the user
8390 (setq time (or time (org-read-date nil 'to-time nil nil
8391 default-time default-input))))
8393 (when (and org-insert-labeled-timestamps-at-point
8394 (member what '(scheduled deadline)))
8395 (insert
8396 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8397 (org-insert-time-stamp time org-time-was-given
8398 nil nil nil (list org-end-time-was-given))
8399 (setq what nil))
8400 (save-excursion
8401 (save-restriction
8402 (let (col list elt ts buffer-invisibility-spec)
8403 (org-back-to-heading t)
8404 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8405 (goto-char (match-end 1))
8406 (setq col (current-column))
8407 (goto-char (match-end 0))
8408 (if (eobp) (insert "\n") (forward-char 1))
8409 (if (and (not (looking-at outline-regexp))
8410 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8411 "[^\r\n]*"))
8412 (not (equal (match-string 1) org-clock-string)))
8413 (narrow-to-region (match-beginning 0) (match-end 0))
8414 (insert-before-markers "\n")
8415 (backward-char 1)
8416 (narrow-to-region (point) (point))
8417 (org-indent-to-column col))
8418 ;; Check if we have to remove something.
8419 (setq list (cons what remove))
8420 (while list
8421 (setq elt (pop list))
8422 (goto-char (point-min))
8423 (when (or (and (eq elt 'scheduled)
8424 (re-search-forward org-scheduled-time-regexp nil t))
8425 (and (eq elt 'deadline)
8426 (re-search-forward org-deadline-time-regexp nil t))
8427 (and (eq elt 'closed)
8428 (re-search-forward org-closed-time-regexp nil t)))
8429 (replace-match "")
8430 (if (looking-at "--+<[^>]+>") (replace-match ""))
8431 (if (looking-at " +") (replace-match ""))))
8432 (goto-char (point-max))
8433 (when what
8434 (insert
8435 (if (not (equal (char-before) ?\ )) " " "")
8436 (cond ((eq what 'scheduled) org-scheduled-string)
8437 ((eq what 'deadline) org-deadline-string)
8438 ((eq what 'closed) org-closed-string))
8439 " ")
8440 (setq ts (org-insert-time-stamp
8441 time
8442 (or org-time-was-given
8443 (and (eq what 'closed) org-log-done-with-time))
8444 (eq what 'closed)
8445 nil nil (list org-end-time-was-given)))
8446 (end-of-line 1))
8447 (goto-char (point-min))
8448 (widen)
8449 (if (and (looking-at "[ \t]+\n")
8450 (equal (char-before) ?\n))
8451 (delete-region (1- (point)) (point-at-eol)))
8452 ts)))))
8454 (defvar org-log-note-marker (make-marker))
8455 (defvar org-log-note-purpose nil)
8456 (defvar org-log-note-state nil)
8457 (defvar org-log-note-how nil)
8458 (defvar org-log-note-window-configuration nil)
8459 (defvar org-log-note-return-to (make-marker))
8460 (defvar org-log-post-message nil
8461 "Message to be displayed after a log note has been stored.
8462 The auto-repeater uses this.")
8464 (defun org-add-note ()
8465 "Add a note to the current entry.
8466 This is done in the same way as adding a state change note."
8467 (interactive)
8468 (org-add-log-setup 'note nil t nil))
8470 (defun org-add-log-setup (&optional purpose state findpos how)
8471 "Set up the post command hook to take a note.
8472 If this is about to TODO state change, the new state is expected in STATE.
8473 When FINDPOS is non-nil, find the correct position for the note in
8474 the current entry. If not, assume that it can be inserted at point."
8475 (save-excursion
8476 (when findpos
8477 (org-back-to-heading t)
8478 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8479 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8480 "[^\r\n]*\\)?"))
8481 (goto-char (match-end 0))
8482 (unless org-log-states-order-reversed
8483 (and (= (char-after) ?\n) (forward-char 1))
8484 (org-skip-over-state-notes)
8485 (skip-chars-backward " \t\n\r")))
8486 (move-marker org-log-note-marker (point))
8487 (setq org-log-note-purpose purpose
8488 org-log-note-state state
8489 org-log-note-how how)
8490 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8492 (defun org-skip-over-state-notes ()
8493 "Skip past the list of State notes in an entry."
8494 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8495 (while (looking-at "[ \t]*- State")
8496 (condition-case nil
8497 (org-next-item)
8498 (error (org-end-of-item)))))
8500 (defun org-add-log-note (&optional purpose)
8501 "Pop up a window for taking a note, and add this note later at point."
8502 (remove-hook 'post-command-hook 'org-add-log-note)
8503 (setq org-log-note-window-configuration (current-window-configuration))
8504 (delete-other-windows)
8505 (move-marker org-log-note-return-to (point))
8506 (switch-to-buffer (marker-buffer org-log-note-marker))
8507 (goto-char org-log-note-marker)
8508 (org-switch-to-buffer-other-window "*Org Note*")
8509 (erase-buffer)
8510 (if (memq org-log-note-how '(time state))
8511 (org-store-log-note)
8512 (let ((org-inhibit-startup t)) (org-mode))
8513 (insert (format "# Insert note for %s.
8514 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8515 (cond
8516 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8517 ((eq org-log-note-purpose 'done) "closed todo item")
8518 ((eq org-log-note-purpose 'state)
8519 (format "state change to \"%s\"" org-log-note-state))
8520 ((eq org-log-note-purpose 'note)
8521 "this entry")
8522 (t (error "This should not happen")))))
8523 (org-set-local 'org-finish-function 'org-store-log-note)))
8525 (defvar org-note-abort nil) ; dynamically scoped
8526 (defun org-store-log-note ()
8527 "Finish taking a log note, and insert it to where it belongs."
8528 (let ((txt (buffer-string))
8529 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8530 lines ind)
8531 (kill-buffer (current-buffer))
8532 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8533 (setq txt (replace-match "" t t txt)))
8534 (if (string-match "\\s-+\\'" txt)
8535 (setq txt (replace-match "" t t txt)))
8536 (setq lines (org-split-string txt "\n"))
8537 (when (and note (string-match "\\S-" note))
8538 (setq note
8539 (org-replace-escapes
8540 note
8541 (list (cons "%u" (user-login-name))
8542 (cons "%U" user-full-name)
8543 (cons "%t" (format-time-string
8544 (org-time-stamp-format 'long 'inactive)
8545 (current-time)))
8546 (cons "%s" (if org-log-note-state
8547 (concat "\"" org-log-note-state "\"")
8548 "")))))
8549 (if lines (setq note (concat note " \\\\")))
8550 (push note lines))
8551 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8552 (when lines
8553 (save-excursion
8554 (set-buffer (marker-buffer org-log-note-marker))
8555 (save-excursion
8556 (goto-char org-log-note-marker)
8557 (move-marker org-log-note-marker nil)
8558 (end-of-line 1)
8559 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8560 (indent-relative nil)
8561 (insert "- " (pop lines))
8562 (org-indent-line-function)
8563 (beginning-of-line 1)
8564 (looking-at "[ \t]*")
8565 (setq ind (concat (match-string 0) " "))
8566 (end-of-line 1)
8567 (while lines (insert "\n" ind (pop lines)))))))
8568 (set-window-configuration org-log-note-window-configuration)
8569 (with-current-buffer (marker-buffer org-log-note-return-to)
8570 (goto-char org-log-note-return-to))
8571 (move-marker org-log-note-return-to nil)
8572 (and org-log-post-message (message "%s" org-log-post-message)))
8574 (defun org-sparse-tree (&optional arg)
8575 "Create a sparse tree, prompt for the details.
8576 This command can create sparse trees. You first need to select the type
8577 of match used to create the tree:
8579 t Show entries with a specific TODO keyword.
8580 T Show entries selected by a tags match.
8581 p Enter a property name and its value (both with completion on existing
8582 names/values) and show entries with that property.
8583 r Show entries matching a regular expression
8584 d Show deadlines due within `org-deadline-warning-days'."
8585 (interactive "P")
8586 (let (ans kwd value)
8587 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8588 (setq ans (read-char-exclusive))
8589 (cond
8590 ((equal ans ?d)
8591 (call-interactively 'org-check-deadlines))
8592 ((equal ans ?b)
8593 (call-interactively 'org-check-before-date))
8594 ((equal ans ?t)
8595 (org-show-todo-tree '(4)))
8596 ((equal ans ?T)
8597 (call-interactively 'org-tags-sparse-tree))
8598 ((member ans '(?p ?P))
8599 (setq kwd (completing-read "Property: "
8600 (mapcar 'list (org-buffer-property-keys))))
8601 (setq value (completing-read "Value: "
8602 (mapcar 'list (org-property-values kwd))))
8603 (unless (string-match "\\`{.*}\\'" value)
8604 (setq value (concat "\"" value "\"")))
8605 (org-tags-sparse-tree arg (concat kwd "=" value)))
8606 ((member ans '(?r ?R ?/))
8607 (call-interactively 'org-occur))
8608 (t (error "No such sparse tree command \"%c\"" ans)))))
8610 (defvar org-occur-highlights nil
8611 "List of overlays used for occur matches.")
8612 (make-variable-buffer-local 'org-occur-highlights)
8613 (defvar org-occur-parameters nil
8614 "Parameters of the active org-occur calls.
8615 This is a list, each call to org-occur pushes as cons cell,
8616 containing the regular expression and the callback, onto the list.
8617 The list can contain several entries if `org-occur' has been called
8618 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8619 will only contain one set of parameters. When the highlights are
8620 removed (for example with `C-c C-c', or with the next edit (depending
8621 on `org-remove-highlights-with-change'), this variable is emptied
8622 as well.")
8623 (make-variable-buffer-local 'org-occur-parameters)
8625 (defun org-occur (regexp &optional keep-previous callback)
8626 "Make a compact tree which shows all matches of REGEXP.
8627 The tree will show the lines where the regexp matches, and all higher
8628 headlines above the match. It will also show the heading after the match,
8629 to make sure editing the matching entry is easy.
8630 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8631 call to `org-occur' will be kept, to allow stacking of calls to this
8632 command.
8633 If CALLBACK is non-nil, it is a function which is called to confirm
8634 that the match should indeed be shown."
8635 (interactive "sRegexp: \nP")
8636 (unless keep-previous
8637 (org-remove-occur-highlights nil nil t))
8638 (push (cons regexp callback) org-occur-parameters)
8639 (let ((cnt 0))
8640 (save-excursion
8641 (goto-char (point-min))
8642 (if (or (not keep-previous) ; do not want to keep
8643 (not org-occur-highlights)) ; no previous matches
8644 ;; hide everything
8645 (org-overview))
8646 (while (re-search-forward regexp nil t)
8647 (when (or (not callback)
8648 (save-match-data (funcall callback)))
8649 (setq cnt (1+ cnt))
8650 (when org-highlight-sparse-tree-matches
8651 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8652 (org-show-context 'occur-tree))))
8653 (when org-remove-highlights-with-change
8654 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8655 nil 'local))
8656 (unless org-sparse-tree-open-archived-trees
8657 (org-hide-archived-subtrees (point-min) (point-max)))
8658 (run-hooks 'org-occur-hook)
8659 (if (interactive-p)
8660 (message "%d match(es) for regexp %s" cnt regexp))
8661 cnt))
8663 (defun org-show-context (&optional key)
8664 "Make sure point and context and visible.
8665 How much context is shown depends upon the variables
8666 `org-show-hierarchy-above', `org-show-following-heading'. and
8667 `org-show-siblings'."
8668 (let ((heading-p (org-on-heading-p t))
8669 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8670 (following-p (org-get-alist-option org-show-following-heading key))
8671 (entry-p (org-get-alist-option org-show-entry-below key))
8672 (siblings-p (org-get-alist-option org-show-siblings key)))
8673 (catch 'exit
8674 ;; Show heading or entry text
8675 (if (and heading-p (not entry-p))
8676 (org-flag-heading nil) ; only show the heading
8677 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8678 (org-show-hidden-entry))) ; show entire entry
8679 (when following-p
8680 ;; Show next sibling, or heading below text
8681 (save-excursion
8682 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8683 (org-flag-heading nil))))
8684 (when siblings-p (org-show-siblings))
8685 (when hierarchy-p
8686 ;; show all higher headings, possibly with siblings
8687 (save-excursion
8688 (while (and (condition-case nil
8689 (progn (org-up-heading-all 1) t)
8690 (error nil))
8691 (not (bobp)))
8692 (org-flag-heading nil)
8693 (when siblings-p (org-show-siblings))))))))
8695 (defun org-reveal (&optional siblings)
8696 "Show current entry, hierarchy above it, and the following headline.
8697 This can be used to show a consistent set of context around locations
8698 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8699 not t for the search context.
8701 With optional argument SIBLINGS, on each level of the hierarchy all
8702 siblings are shown. This repairs the tree structure to what it would
8703 look like when opened with hierarchical calls to `org-cycle'."
8704 (interactive "P")
8705 (let ((org-show-hierarchy-above t)
8706 (org-show-following-heading t)
8707 (org-show-siblings (if siblings t org-show-siblings)))
8708 (org-show-context nil)))
8710 (defun org-highlight-new-match (beg end)
8711 "Highlight from BEG to END and mark the highlight is an occur headline."
8712 (let ((ov (org-make-overlay beg end)))
8713 (org-overlay-put ov 'face 'secondary-selection)
8714 (push ov org-occur-highlights)))
8716 (defun org-remove-occur-highlights (&optional beg end noremove)
8717 "Remove the occur highlights from the buffer.
8718 BEG and END are ignored. If NOREMOVE is nil, remove this function
8719 from the `before-change-functions' in the current buffer."
8720 (interactive)
8721 (unless org-inhibit-highlight-removal
8722 (mapc 'org-delete-overlay org-occur-highlights)
8723 (setq org-occur-highlights nil)
8724 (setq org-occur-parameters nil)
8725 (unless noremove
8726 (remove-hook 'before-change-functions
8727 'org-remove-occur-highlights 'local))))
8729 ;;;; Priorities
8731 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8732 "Regular expression matching the priority indicator.")
8734 (defvar org-remove-priority-next-time nil)
8736 (defun org-priority-up ()
8737 "Increase the priority of the current item."
8738 (interactive)
8739 (org-priority 'up))
8741 (defun org-priority-down ()
8742 "Decrease the priority of the current item."
8743 (interactive)
8744 (org-priority 'down))
8746 (defun org-priority (&optional action)
8747 "Change the priority of an item by ARG.
8748 ACTION can be `set', `up', `down', or a character."
8749 (interactive)
8750 (setq action (or action 'set))
8751 (let (current new news have remove)
8752 (save-excursion
8753 (org-back-to-heading)
8754 (if (looking-at org-priority-regexp)
8755 (setq current (string-to-char (match-string 2))
8756 have t)
8757 (setq current org-default-priority))
8758 (cond
8759 ((or (eq action 'set)
8760 (if (featurep 'xemacs) (characterp action) (integerp action)))
8761 (if (not (eq action 'set))
8762 (setq new action)
8763 (message "Priority %c-%c, SPC to remove: "
8764 org-highest-priority org-lowest-priority)
8765 (setq new (read-char-exclusive)))
8766 (if (and (= (upcase org-highest-priority) org-highest-priority)
8767 (= (upcase org-lowest-priority) org-lowest-priority))
8768 (setq new (upcase new)))
8769 (cond ((equal new ?\ ) (setq remove t))
8770 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8771 (error "Priority must be between `%c' and `%c'"
8772 org-highest-priority org-lowest-priority))))
8773 ((eq action 'up)
8774 (if (and (not have) (eq last-command this-command))
8775 (setq new org-lowest-priority)
8776 (setq new (if (and org-priority-start-cycle-with-default (not have))
8777 org-default-priority (1- current)))))
8778 ((eq action 'down)
8779 (if (and (not have) (eq last-command this-command))
8780 (setq new org-highest-priority)
8781 (setq new (if (and org-priority-start-cycle-with-default (not have))
8782 org-default-priority (1+ current)))))
8783 (t (error "Invalid action")))
8784 (if (or (< (upcase new) org-highest-priority)
8785 (> (upcase new) org-lowest-priority))
8786 (setq remove t))
8787 (setq news (format "%c" new))
8788 (if have
8789 (if remove
8790 (replace-match "" t t nil 1)
8791 (replace-match news t t nil 2))
8792 (if remove
8793 (error "No priority cookie found in line")
8794 (looking-at org-todo-line-regexp)
8795 (if (match-end 2)
8796 (progn
8797 (goto-char (match-end 2))
8798 (insert " [#" news "]"))
8799 (goto-char (match-beginning 3))
8800 (insert "[#" news "] ")))))
8801 (org-preserve-lc (org-set-tags nil 'align))
8802 (if remove
8803 (message "Priority removed")
8804 (message "Priority of current item set to %s" news))))
8807 (defun org-get-priority (s)
8808 "Find priority cookie and return priority."
8809 (save-match-data
8810 (if (not (string-match org-priority-regexp s))
8811 (* 1000 (- org-lowest-priority org-default-priority))
8812 (* 1000 (- org-lowest-priority
8813 (string-to-char (match-string 2 s)))))))
8815 ;;;; Tags
8817 (defun org-scan-tags (action matcher &optional todo-only)
8818 "Scan headline tags with inheritance and produce output ACTION.
8819 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8820 evaluated, testing if a given set of tags qualifies a headline for
8821 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8822 are included in the output."
8823 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8824 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8825 (org-re
8826 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8827 (props (list 'face nil
8828 'done-face 'org-done
8829 'undone-face nil
8830 'mouse-face 'highlight
8831 'org-not-done-regexp org-not-done-regexp
8832 'org-todo-regexp org-todo-regexp
8833 'keymap org-agenda-keymap
8834 'help-echo
8835 (format "mouse-2 or RET jump to org file %s"
8836 (abbreviate-file-name
8837 (or (buffer-file-name (buffer-base-buffer))
8838 (buffer-name (buffer-base-buffer)))))))
8839 (case-fold-search nil)
8840 lspos
8841 tags tags-list tags-alist (llast 0) rtn level category i txt
8842 todo marker entry priority)
8843 (save-excursion
8844 (goto-char (point-min))
8845 (when (eq action 'sparse-tree)
8846 (org-overview)
8847 (org-remove-occur-highlights))
8848 (while (re-search-forward re nil t)
8849 (catch :skip
8850 (setq todo (if (match-end 1) (match-string 2))
8851 tags (if (match-end 4) (match-string 4)))
8852 (goto-char (setq lspos (1+ (match-beginning 0))))
8853 (setq level (org-reduced-level (funcall outline-level))
8854 category (org-get-category))
8855 (setq i llast llast level)
8856 ;; remove tag lists from same and sublevels
8857 (while (>= i level)
8858 (when (setq entry (assoc i tags-alist))
8859 (setq tags-alist (delete entry tags-alist)))
8860 (setq i (1- i)))
8861 ;; add the next tags
8862 (when tags
8863 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8864 tags-alist
8865 (cons (cons level tags) tags-alist)))
8866 ;; compile tags for current headline
8867 (setq tags-list
8868 (if org-use-tag-inheritance
8869 (apply 'append (mapcar 'cdr tags-alist))
8870 tags))
8871 (when (and tags org-use-tag-inheritance
8872 (not (eq t org-use-tag-inheritance)))
8873 ;; selective inheritance, remove uninherited ones
8874 (setcdr (car tags-alist)
8875 (org-remove-uniherited-tags (cdar tags-alist))))
8876 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8877 (eval matcher)
8878 (or (not org-agenda-skip-archived-trees)
8879 (not (member org-archive-tag tags-list))))
8880 (and (eq action 'agenda) (org-agenda-skip))
8881 ;; list this headline
8883 (if (eq action 'sparse-tree)
8884 (progn
8885 (and org-highlight-sparse-tree-matches
8886 (org-get-heading) (match-end 0)
8887 (org-highlight-new-match
8888 (match-beginning 0) (match-beginning 1)))
8889 (org-show-context 'tags-tree))
8890 (setq txt (org-format-agenda-item
8892 (concat
8893 (if org-tags-match-list-sublevels
8894 (make-string (1- level) ?.) "")
8895 (org-get-heading))
8896 category tags-list)
8897 priority (org-get-priority txt))
8898 (goto-char lspos)
8899 (setq marker (org-agenda-new-marker))
8900 (org-add-props txt props
8901 'org-marker marker 'org-hd-marker marker 'org-category category
8902 'priority priority 'type "tagsmatch")
8903 (push txt rtn))
8904 ;; if we are to skip sublevels, jump to end of subtree
8905 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8906 (when (and (eq action 'sparse-tree)
8907 (not org-sparse-tree-open-archived-trees))
8908 (org-hide-archived-subtrees (point-min) (point-max)))
8909 (nreverse rtn)))
8911 (defun org-remove-uniherited-tags (tags)
8912 "Remove all tags that are not inherited from the list TAGS."
8913 (cond
8914 ((eq org-use-tag-inheritance t) tags)
8915 ((not org-use-tag-inheritance) nil)
8916 ((stringp org-use-tag-inheritance)
8917 (delq nil (mapcar
8918 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8919 tags)))
8920 ((listp org-use-tag-inheritance)
8921 (org-delete-all org-use-tag-inheritance tags))))
8923 (defvar todo-only) ;; dynamically scoped
8925 (defun org-tags-sparse-tree (&optional todo-only match)
8926 "Create a sparse tree according to tags string MATCH.
8927 MATCH can contain positive and negative selection of tags, like
8928 \"+WORK+URGENT-WITHBOSS\".
8929 If optional argument TODO_ONLY is non-nil, only select lines that are
8930 also TODO lines."
8931 (interactive "P")
8932 (org-prepare-agenda-buffers (list (current-buffer)))
8933 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8935 (defvar org-cached-props nil)
8936 (defun org-cached-entry-get (pom property)
8937 (if (or (eq t org-use-property-inheritance)
8938 (and (stringp org-use-property-inheritance)
8939 (string-match org-use-property-inheritance property))
8940 (and (listp org-use-property-inheritance)
8941 (member property org-use-property-inheritance)))
8942 ;; Caching is not possible, check it directly
8943 (org-entry-get pom property 'inherit)
8944 ;; Get all properties, so that we can do complicated checks easily
8945 (cdr (assoc property (or org-cached-props
8946 (setq org-cached-props
8947 (org-entry-properties pom)))))))
8949 (defun org-global-tags-completion-table (&optional files)
8950 "Return the list of all tags in all agenda buffer/files."
8951 (save-excursion
8952 (org-uniquify
8953 (delq nil
8954 (apply 'append
8955 (mapcar
8956 (lambda (file)
8957 (set-buffer (find-file-noselect file))
8958 (append (org-get-buffer-tags)
8959 (mapcar (lambda (x) (if (stringp (car-safe x))
8960 (list (car-safe x)) nil))
8961 org-tag-alist)))
8962 (if (and files (car files))
8963 files
8964 (org-agenda-files))))))))
8966 (defun org-make-tags-matcher (match)
8967 "Create the TAGS//TODO matcher form for the selection string MATCH."
8968 ;; todo-only is scoped dynamically into this function, and the function
8969 ;; may change it it the matcher asksk for it.
8970 (unless match
8971 ;; Get a new match request, with completion
8972 (let ((org-last-tags-completion-table
8973 (org-global-tags-completion-table)))
8974 (setq match (completing-read
8975 "Match: " 'org-tags-completion-function nil nil nil
8976 'org-tags-history))))
8978 ;; Parse the string and create a lisp form
8979 (let ((match0 match)
8980 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8981 minus tag mm
8982 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8983 orterms term orlist re-p str-p level-p level-op
8984 prop-p pn pv po cat-p gv)
8985 (if (string-match "/+" match)
8986 ;; match contains also a todo-matching request
8987 (progn
8988 (setq tagsmatch (substring match 0 (match-beginning 0))
8989 todomatch (substring match (match-end 0)))
8990 (if (string-match "^!" todomatch)
8991 (setq todo-only t todomatch (substring todomatch 1)))
8992 (if (string-match "^\\s-*$" todomatch)
8993 (setq todomatch nil)))
8994 ;; only matching tags
8995 (setq tagsmatch match todomatch nil))
8997 ;; Make the tags matcher
8998 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8999 (setq tagsmatcher t)
9000 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9001 (while (setq term (pop orterms))
9002 (while (and (equal (substring term -1) "\\") orterms)
9003 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9004 (while (string-match re term)
9005 (setq minus (and (match-end 1)
9006 (equal (match-string 1 term) "-"))
9007 tag (match-string 2 term)
9008 re-p (equal (string-to-char tag) ?{)
9009 level-p (match-end 4)
9010 prop-p (match-end 5)
9011 mm (cond
9012 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9013 (level-p
9014 (setq level-op (org-op-to-function (match-string 3 term)))
9015 `(,level-op level ,(string-to-number
9016 (match-string 4 term))))
9017 (prop-p
9018 (setq pn (match-string 5 term)
9019 po (match-string 6 term)
9020 pv (match-string 7 term)
9021 cat-p (equal pn "CATEGORY")
9022 re-p (equal (string-to-char pv) ?{)
9023 str-p (equal (string-to-char pv) ?\")
9024 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9025 (setq po (org-op-to-function po str-p))
9026 (if (equal pn "CATEGORY")
9027 (setq gv '(get-text-property (point) 'org-category))
9028 (setq gv `(org-cached-entry-get nil ,pn)))
9029 (if re-p
9030 (if (eq po 'org<>)
9031 `(not (string-match ,pv (or ,gv "")))
9032 `(string-match ,pv (or ,gv "")))
9033 (if str-p
9034 `(,po (or ,gv "") ,pv)
9035 `(,po (string-to-number (or ,gv ""))
9036 ,(string-to-number pv) ))))
9037 (t `(member ,(downcase tag) tags-list)))
9038 mm (if minus (list 'not mm) mm)
9039 term (substring term (match-end 0)))
9040 (push mm tagsmatcher))
9041 (push (if (> (length tagsmatcher) 1)
9042 (cons 'and tagsmatcher)
9043 (car tagsmatcher))
9044 orlist)
9045 (setq tagsmatcher nil))
9046 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9047 (setq tagsmatcher
9048 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9049 ;; Make the todo matcher
9050 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9051 (setq todomatcher t)
9052 (setq orterms (org-split-string todomatch "|") orlist nil)
9053 (while (setq term (pop orterms))
9054 (while (string-match re term)
9055 (setq minus (and (match-end 1)
9056 (equal (match-string 1 term) "-"))
9057 kwd (match-string 2 term)
9058 re-p (equal (string-to-char kwd) ?{)
9059 term (substring term (match-end 0))
9060 mm (if re-p
9061 `(string-match ,(substring kwd 1 -1) todo)
9062 (list 'equal 'todo kwd))
9063 mm (if minus (list 'not mm) mm))
9064 (push mm todomatcher))
9065 (push (if (> (length todomatcher) 1)
9066 (cons 'and todomatcher)
9067 (car todomatcher))
9068 orlist)
9069 (setq todomatcher nil))
9070 (setq todomatcher (if (> (length orlist) 1)
9071 (cons 'or orlist) (car orlist))))
9073 ;; Return the string and lisp forms of the matcher
9074 (setq matcher (if todomatcher
9075 (list 'and tagsmatcher todomatcher)
9076 tagsmatcher))
9077 (cons match0 matcher)))
9079 (defun org-op-to-function (op &optional stringp)
9080 (setq op
9081 (cond
9082 ((equal op "<" ) '(< string< ))
9083 ((equal op ">" ) '(> org-string> ))
9084 ((member op '("<=" "=<")) '(<= org-string<= ))
9085 ((member op '(">=" "=>")) '(>= org-string>= ))
9086 ((member op '("=" "==")) '(= string= ))
9087 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9088 (nth (if stringp 1 0) op))
9090 (defun org<> (a b) (not (= a b)))
9091 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9092 (defun org-string>= (a b) (not (string< a b)))
9093 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9094 (defun org-string<> (a b) (not (string= a b)))
9096 (defun org-match-any-p (re list)
9097 "Does re match any element of list?"
9098 (setq list (mapcar (lambda (x) (string-match re x)) list))
9099 (delq nil list))
9101 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9102 (defvar org-tags-overlay (org-make-overlay 1 1))
9103 (org-detach-overlay org-tags-overlay)
9105 (defun org-get-tags-at (&optional pos)
9106 "Get a list of all headline tags applicable at POS.
9107 POS defaults to point. If tags are inherited, the list contains
9108 the targets in the same sequence as the headlines appear, i.e.
9109 sthe tags of the current headline come last."
9110 (interactive)
9111 (let (tags ltags lastpos parent)
9112 (save-excursion
9113 (save-restriction
9114 (widen)
9115 (goto-char (or pos (point)))
9116 (save-match-data
9117 (condition-case nil
9118 (progn
9119 (org-back-to-heading t)
9120 (while (not (equal lastpos (point)))
9121 (setq lastpos (point))
9122 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9123 (setq ltags (org-split-string
9124 (org-match-string-no-properties 1) ":"))
9125 (setq tags (append (org-remove-uniherited-tags ltags)
9126 tags)))
9127 (or org-use-tag-inheritance (error ""))
9128 (org-up-heading-all 1)
9129 (setq parent t)))
9130 (error nil))))
9131 tags)))
9133 (defun org-toggle-tag (tag &optional onoff)
9134 "Toggle the tag TAG for the current line.
9135 If ONOFF is `on' or `off', don't toggle but set to this state."
9136 (unless (org-on-heading-p t) (error "Not on headling"))
9137 (let (res current)
9138 (save-excursion
9139 (beginning-of-line)
9140 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9141 (point-at-eol) t)
9142 (progn
9143 (setq current (match-string 1))
9144 (replace-match ""))
9145 (setq current ""))
9146 (setq current (nreverse (org-split-string current ":")))
9147 (cond
9148 ((eq onoff 'on)
9149 (setq res t)
9150 (or (member tag current) (push tag current)))
9151 ((eq onoff 'off)
9152 (or (not (member tag current)) (setq current (delete tag current))))
9153 (t (if (member tag current)
9154 (setq current (delete tag current))
9155 (setq res t)
9156 (push tag current))))
9157 (end-of-line 1)
9158 (if current
9159 (progn
9160 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9161 (org-set-tags nil t))
9162 (delete-horizontal-space))
9163 (run-hooks 'org-after-tags-change-hook))
9164 res))
9166 (defun org-align-tags-here (to-col)
9167 ;; Assumes that this is a headline
9168 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9169 (beginning-of-line 1)
9170 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9171 (< pos (match-beginning 2)))
9172 (progn
9173 (setq tags-l (- (match-end 2) (match-beginning 2)))
9174 (goto-char (match-beginning 1))
9175 (insert " ")
9176 (delete-region (point) (1+ (match-beginning 2)))
9177 (setq ncol (max (1+ (current-column))
9178 (1+ col)
9179 (if (> to-col 0)
9180 to-col
9181 (- (abs to-col) tags-l))))
9182 (setq p (point))
9183 (insert (make-string (- ncol (current-column)) ?\ ))
9184 (setq ncol (current-column))
9185 (tabify p (point-at-eol))
9186 (org-move-to-column (min ncol col) t))
9187 (goto-char pos))))
9189 (defun org-set-tags (&optional arg just-align)
9190 "Set the tags for the current headline.
9191 With prefix ARG, realign all tags in headings in the current buffer."
9192 (interactive "P")
9193 (let* ((re (concat "^" outline-regexp))
9194 (current (org-get-tags-string))
9195 (col (current-column))
9196 (org-setting-tags t)
9197 table current-tags inherited-tags ; computed below when needed
9198 tags p0 c0 c1 rpl)
9199 (if arg
9200 (save-excursion
9201 (goto-char (point-min))
9202 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9203 (while (re-search-forward re nil t)
9204 (org-set-tags nil t)
9205 (end-of-line 1)))
9206 (message "All tags realigned to column %d" org-tags-column))
9207 (if just-align
9208 (setq tags current)
9209 ;; Get a new set of tags from the user
9210 (save-excursion
9211 (setq table (or org-tag-alist (org-get-buffer-tags))
9212 org-last-tags-completion-table table
9213 current-tags (org-split-string current ":")
9214 inherited-tags (nreverse
9215 (nthcdr (length current-tags)
9216 (nreverse (org-get-tags-at))))
9217 tags
9218 (if (or (eq t org-use-fast-tag-selection)
9219 (and org-use-fast-tag-selection
9220 (delq nil (mapcar 'cdr table))))
9221 (org-fast-tag-selection
9222 current-tags inherited-tags table
9223 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9224 (let ((org-add-colon-after-tag-completion t))
9225 (org-trim
9226 (org-without-partial-completion
9227 (completing-read "Tags: " 'org-tags-completion-function
9228 nil nil current 'org-tags-history)))))))
9229 (while (string-match "[-+&]+" tags)
9230 ;; No boolean logic, just a list
9231 (setq tags (replace-match ":" t t tags))))
9233 (if (string-match "\\`[\t ]*\\'" tags)
9234 (setq tags "")
9235 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9236 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9238 ;; Insert new tags at the correct column
9239 (beginning-of-line 1)
9240 (cond
9241 ((and (equal current "") (equal tags "")))
9242 ((re-search-forward
9243 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9244 (point-at-eol) t)
9245 (if (equal tags "")
9246 (setq rpl "")
9247 (goto-char (match-beginning 0))
9248 (setq c0 (current-column) p0 (point)
9249 c1 (max (1+ c0) (if (> org-tags-column 0)
9250 org-tags-column
9251 (- (- org-tags-column) (length tags))))
9252 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9253 (replace-match rpl t t)
9254 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9255 tags)
9256 (t (error "Tags alignment failed")))
9257 (org-move-to-column col)
9258 (unless just-align
9259 (run-hooks 'org-after-tags-change-hook)))))
9261 (defun org-change-tag-in-region (beg end tag off)
9262 "Add or remove TAG for each entry in the region.
9263 This works in the agenda, and also in an org-mode buffer."
9264 (interactive
9265 (list (region-beginning) (region-end)
9266 (let ((org-last-tags-completion-table
9267 (if (org-mode-p)
9268 (org-get-buffer-tags)
9269 (org-global-tags-completion-table))))
9270 (completing-read
9271 "Tag: " 'org-tags-completion-function nil nil nil
9272 'org-tags-history))
9273 (progn
9274 (message "[s]et or [r]emove? ")
9275 (equal (read-char-exclusive) ?r))))
9276 (if (fboundp 'deactivate-mark) (deactivate-mark))
9277 (let ((agendap (equal major-mode 'org-agenda-mode))
9278 l1 l2 m buf pos newhead (cnt 0))
9279 (goto-char end)
9280 (setq l2 (1- (org-current-line)))
9281 (goto-char beg)
9282 (setq l1 (org-current-line))
9283 (loop for l from l1 to l2 do
9284 (goto-line l)
9285 (setq m (get-text-property (point) 'org-hd-marker))
9286 (when (or (and (org-mode-p) (org-on-heading-p))
9287 (and agendap m))
9288 (setq buf (if agendap (marker-buffer m) (current-buffer))
9289 pos (if agendap m (point)))
9290 (with-current-buffer buf
9291 (save-excursion
9292 (save-restriction
9293 (goto-char pos)
9294 (setq cnt (1+ cnt))
9295 (org-toggle-tag tag (if off 'off 'on))
9296 (setq newhead (org-get-heading)))))
9297 (and agendap (org-agenda-change-all-lines newhead m))))
9298 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9300 (defun org-tags-completion-function (string predicate &optional flag)
9301 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9302 (confirm (lambda (x) (stringp (car x)))))
9303 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9304 (setq s1 (match-string 1 string)
9305 s2 (match-string 2 string))
9306 (setq s1 "" s2 string))
9307 (cond
9308 ((eq flag nil)
9309 ;; try completion
9310 (setq rtn (try-completion s2 ctable confirm))
9311 (if (stringp rtn)
9312 (setq rtn
9313 (concat s1 s2 (substring rtn (length s2))
9314 (if (and org-add-colon-after-tag-completion
9315 (assoc rtn ctable))
9316 ":" ""))))
9317 rtn)
9318 ((eq flag t)
9319 ;; all-completions
9320 (all-completions s2 ctable confirm)
9322 ((eq flag 'lambda)
9323 ;; exact match?
9324 (assoc s2 ctable)))
9327 (defun org-fast-tag-insert (kwd tags face &optional end)
9328 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9329 (insert (format "%-12s" (concat kwd ":"))
9330 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9331 (or end "")))
9333 (defun org-fast-tag-show-exit (flag)
9334 (save-excursion
9335 (goto-line 3)
9336 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9337 (replace-match ""))
9338 (when flag
9339 (end-of-line 1)
9340 (org-move-to-column (- (window-width) 19) t)
9341 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9343 (defun org-set-current-tags-overlay (current prefix)
9344 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9345 (if (featurep 'xemacs)
9346 (org-overlay-display org-tags-overlay (concat prefix s)
9347 'secondary-selection)
9348 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9349 (org-overlay-display org-tags-overlay (concat prefix s)))))
9351 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9352 "Fast tag selection with single keys.
9353 CURRENT is the current list of tags in the headline, INHERITED is the
9354 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9355 possibly with grouping information. TODO-TABLE is a similar table with
9356 TODO keywords, should these have keys assigned to them.
9357 If the keys are nil, a-z are automatically assigned.
9358 Returns the new tags string, or nil to not change the current settings."
9359 (let* ((fulltable (append table todo-table))
9360 (maxlen (apply 'max (mapcar
9361 (lambda (x)
9362 (if (stringp (car x)) (string-width (car x)) 0))
9363 fulltable)))
9364 (buf (current-buffer))
9365 (expert (eq org-fast-tag-selection-single-key 'expert))
9366 (buffer-tags nil)
9367 (fwidth (+ maxlen 3 1 3))
9368 (ncol (/ (- (window-width) 4) fwidth))
9369 (i-face 'org-done)
9370 (c-face 'org-todo)
9371 tg cnt e c char c1 c2 ntable tbl rtn
9372 ov-start ov-end ov-prefix
9373 (exit-after-next org-fast-tag-selection-single-key)
9374 (done-keywords org-done-keywords)
9375 groups ingroup)
9376 (save-excursion
9377 (beginning-of-line 1)
9378 (if (looking-at
9379 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9380 (setq ov-start (match-beginning 1)
9381 ov-end (match-end 1)
9382 ov-prefix "")
9383 (setq ov-start (1- (point-at-eol))
9384 ov-end (1+ ov-start))
9385 (skip-chars-forward "^\n\r")
9386 (setq ov-prefix
9387 (concat
9388 (buffer-substring (1- (point)) (point))
9389 (if (> (current-column) org-tags-column)
9391 (make-string (- org-tags-column (current-column)) ?\ ))))))
9392 (org-move-overlay org-tags-overlay ov-start ov-end)
9393 (save-window-excursion
9394 (if expert
9395 (set-buffer (get-buffer-create " *Org tags*"))
9396 (delete-other-windows)
9397 (split-window-vertically)
9398 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9399 (erase-buffer)
9400 (org-set-local 'org-done-keywords done-keywords)
9401 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9402 (org-fast-tag-insert "Current" current c-face "\n\n")
9403 (org-fast-tag-show-exit exit-after-next)
9404 (org-set-current-tags-overlay current ov-prefix)
9405 (setq tbl fulltable char ?a cnt 0)
9406 (while (setq e (pop tbl))
9407 (cond
9408 ((equal e '(:startgroup))
9409 (push '() groups) (setq ingroup t)
9410 (when (not (= cnt 0))
9411 (setq cnt 0)
9412 (insert "\n"))
9413 (insert "{ "))
9414 ((equal e '(:endgroup))
9415 (setq ingroup nil cnt 0)
9416 (insert "}\n"))
9418 (setq tg (car e) c2 nil)
9419 (if (cdr e)
9420 (setq c (cdr e))
9421 ;; automatically assign a character.
9422 (setq c1 (string-to-char
9423 (downcase (substring
9424 tg (if (= (string-to-char tg) ?@) 1 0)))))
9425 (if (or (rassoc c1 ntable) (rassoc c1 table))
9426 (while (or (rassoc char ntable) (rassoc char table))
9427 (setq char (1+ char)))
9428 (setq c2 c1))
9429 (setq c (or c2 char)))
9430 (if ingroup (push tg (car groups)))
9431 (setq tg (org-add-props tg nil 'face
9432 (cond
9433 ((not (assoc tg table))
9434 (org-get-todo-face tg))
9435 ((member tg current) c-face)
9436 ((member tg inherited) i-face)
9437 (t nil))))
9438 (if (and (= cnt 0) (not ingroup)) (insert " "))
9439 (insert "[" c "] " tg (make-string
9440 (- fwidth 4 (length tg)) ?\ ))
9441 (push (cons tg c) ntable)
9442 (when (= (setq cnt (1+ cnt)) ncol)
9443 (insert "\n")
9444 (if ingroup (insert " "))
9445 (setq cnt 0)))))
9446 (setq ntable (nreverse ntable))
9447 (insert "\n")
9448 (goto-char (point-min))
9449 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9450 (fit-window-to-buffer))
9451 (setq rtn
9452 (catch 'exit
9453 (while t
9454 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9455 (if groups " [!] no groups" " [!]groups")
9456 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9457 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9458 (cond
9459 ((= c ?\r) (throw 'exit t))
9460 ((= c ?!)
9461 (setq groups (not groups))
9462 (goto-char (point-min))
9463 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9464 ((= c ?\C-c)
9465 (if (not expert)
9466 (org-fast-tag-show-exit
9467 (setq exit-after-next (not exit-after-next)))
9468 (setq expert nil)
9469 (delete-other-windows)
9470 (split-window-vertically)
9471 (org-switch-to-buffer-other-window " *Org tags*")
9472 (and (fboundp 'fit-window-to-buffer)
9473 (fit-window-to-buffer))))
9474 ((or (= c ?\C-g)
9475 (and (= c ?q) (not (rassoc c ntable))))
9476 (org-detach-overlay org-tags-overlay)
9477 (setq quit-flag t))
9478 ((= c ?\ )
9479 (setq current nil)
9480 (if exit-after-next (setq exit-after-next 'now)))
9481 ((= c ?\t)
9482 (condition-case nil
9483 (setq tg (completing-read
9484 "Tag: "
9485 (or buffer-tags
9486 (with-current-buffer buf
9487 (org-get-buffer-tags)))))
9488 (quit (setq tg "")))
9489 (when (string-match "\\S-" tg)
9490 (add-to-list 'buffer-tags (list tg))
9491 (if (member tg current)
9492 (setq current (delete tg current))
9493 (push tg current)))
9494 (if exit-after-next (setq exit-after-next 'now)))
9495 ((setq e (rassoc c todo-table) tg (car e))
9496 (with-current-buffer buf
9497 (save-excursion (org-todo tg)))
9498 (if exit-after-next (setq exit-after-next 'now)))
9499 ((setq e (rassoc c ntable) tg (car e))
9500 (if (member tg current)
9501 (setq current (delete tg current))
9502 (loop for g in groups do
9503 (if (member tg g)
9504 (mapc (lambda (x)
9505 (setq current (delete x current)))
9506 g)))
9507 (push tg current))
9508 (if exit-after-next (setq exit-after-next 'now))))
9510 ;; Create a sorted list
9511 (setq current
9512 (sort current
9513 (lambda (a b)
9514 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9515 (if (eq exit-after-next 'now) (throw 'exit t))
9516 (goto-char (point-min))
9517 (beginning-of-line 2)
9518 (delete-region (point) (point-at-eol))
9519 (org-fast-tag-insert "Current" current c-face)
9520 (org-set-current-tags-overlay current ov-prefix)
9521 (while (re-search-forward
9522 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9523 (setq tg (match-string 1))
9524 (add-text-properties
9525 (match-beginning 1) (match-end 1)
9526 (list 'face
9527 (cond
9528 ((member tg current) c-face)
9529 ((member tg inherited) i-face)
9530 (t (get-text-property (match-beginning 1) 'face))))))
9531 (goto-char (point-min)))))
9532 (org-detach-overlay org-tags-overlay)
9533 (if rtn
9534 (mapconcat 'identity current ":")
9535 nil))))
9537 (defun org-get-tags-string ()
9538 "Get the TAGS string in the current headline."
9539 (unless (org-on-heading-p t)
9540 (error "Not on a heading"))
9541 (save-excursion
9542 (beginning-of-line 1)
9543 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9544 (org-match-string-no-properties 1)
9545 "")))
9547 (defun org-get-tags ()
9548 "Get the list of tags specified in the current headline."
9549 (org-split-string (org-get-tags-string) ":"))
9551 (defun org-get-buffer-tags ()
9552 "Get a table of all tags used in the buffer, for completion."
9553 (let (tags)
9554 (save-excursion
9555 (goto-char (point-min))
9556 (while (re-search-forward
9557 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9558 (when (equal (char-after (point-at-bol 0)) ?*)
9559 (mapc (lambda (x) (add-to-list 'tags x))
9560 (org-split-string (org-match-string-no-properties 1) ":")))))
9561 (mapcar 'list tags)))
9564 ;;;; Properties
9566 ;;; Setting and retrieving properties
9568 (defconst org-special-properties
9569 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9570 "TIMESTAMP" "TIMESTAMP_IA")
9571 "The special properties valid in Org-mode.
9573 These are properties that are not defined in the property drawer,
9574 but in some other way.")
9576 (defconst org-default-properties
9577 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9578 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY")
9579 "Some properties that are used by Org-mode for various purposes.
9580 Being in this list makes sure that they are offered for completion.")
9582 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9583 "Regular expression matching the first line of a property drawer.")
9585 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9586 "Regular expression matching the first line of a property drawer.")
9588 (defun org-property-action ()
9589 "Do an action on properties."
9590 (interactive)
9591 (let (c)
9592 (org-at-property-p)
9593 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9594 (setq c (read-char-exclusive))
9595 (cond
9596 ((equal c ?s)
9597 (call-interactively 'org-set-property))
9598 ((equal c ?d)
9599 (call-interactively 'org-delete-property))
9600 ((equal c ?D)
9601 (call-interactively 'org-delete-property-globally))
9602 ((equal c ?c)
9603 (call-interactively 'org-compute-property-at-point))
9604 (t (error "No such property action %c" c)))))
9606 (defun org-at-property-p ()
9607 "Is the cursor in a property line?"
9608 ;; FIXME: Does not check if we are actually in the drawer.
9609 ;; FIXME: also returns true on any drawers.....
9610 ;; This is used by C-c C-c for property action.
9611 (save-excursion
9612 (beginning-of-line 1)
9613 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9615 (defun org-get-property-block (&optional beg end force)
9616 "Return the (beg . end) range of the body of the property drawer.
9617 BEG and END can be beginning and end of subtree, if not given
9618 they will be found.
9619 If the drawer does not exist and FORCE is non-nil, create the drawer."
9620 (catch 'exit
9621 (save-excursion
9622 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9623 (end (or end (progn (outline-next-heading) (point)))))
9624 (goto-char beg)
9625 (if (re-search-forward org-property-start-re end t)
9626 (setq beg (1+ (match-end 0)))
9627 (if force
9628 (save-excursion
9629 (org-insert-property-drawer)
9630 (setq end (progn (outline-next-heading) (point))))
9631 (throw 'exit nil))
9632 (goto-char beg)
9633 (if (re-search-forward org-property-start-re end t)
9634 (setq beg (1+ (match-end 0)))))
9635 (if (re-search-forward org-property-end-re end t)
9636 (setq end (match-beginning 0))
9637 (or force (throw 'exit nil))
9638 (goto-char beg)
9639 (setq end beg)
9640 (org-indent-line-function)
9641 (insert ":END:\n"))
9642 (cons beg end)))))
9644 (defun org-entry-properties (&optional pom which)
9645 "Get all properties of the entry at point-or-marker POM.
9646 This includes the TODO keyword, the tags, time strings for deadline,
9647 scheduled, and clocking, and any additional properties defined in the
9648 entry. The return value is an alist, keys may occur multiple times
9649 if the property key was used several times.
9650 POM may also be nil, in which case the current entry is used.
9651 If WHICH is nil or `all', get all properties. If WHICH is
9652 `special' or `standard', only get that subclass."
9653 (setq which (or which 'all))
9654 (org-with-point-at pom
9655 (let ((clockstr (substring org-clock-string 0 -1))
9656 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9657 beg end range props sum-props key value string clocksum)
9658 (save-excursion
9659 (when (condition-case nil (org-back-to-heading t) (error nil))
9660 (setq beg (point))
9661 (setq sum-props (get-text-property (point) 'org-summaries))
9662 (setq clocksum (get-text-property (point) :org-clock-minutes))
9663 (outline-next-heading)
9664 (setq end (point))
9665 (when (memq which '(all special))
9666 ;; Get the special properties, like TODO and tags
9667 (goto-char beg)
9668 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9669 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9670 (when (looking-at org-priority-regexp)
9671 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9672 (when (and (setq value (org-get-tags-string))
9673 (string-match "\\S-" value))
9674 (push (cons "TAGS" value) props))
9675 (when (setq value (org-get-tags-at))
9676 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9677 props))
9678 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9679 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9680 string (if (equal key clockstr)
9681 (org-no-properties
9682 (org-trim
9683 (buffer-substring
9684 (match-beginning 3) (goto-char (point-at-eol)))))
9685 (substring (org-match-string-no-properties 3) 1 -1)))
9686 (unless key
9687 (if (= (char-after (match-beginning 3)) ?\[)
9688 (setq key "TIMESTAMP_IA")
9689 (setq key "TIMESTAMP")))
9690 (when (or (equal key clockstr) (not (assoc key props)))
9691 (push (cons key string) props)))
9695 (when (memq which '(all standard))
9696 ;; Get the standard properties, like :PORP: ...
9697 (setq range (org-get-property-block beg end))
9698 (when range
9699 (goto-char (car range))
9700 (while (re-search-forward
9701 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9702 (cdr range) t)
9703 (setq key (org-match-string-no-properties 1)
9704 value (org-trim (or (org-match-string-no-properties 2) "")))
9705 (unless (member key excluded)
9706 (push (cons key (or value "")) props)))))
9707 (if clocksum
9708 (push (cons "CLOCKSUM"
9709 (org-columns-number-to-string (/ (float clocksum) 60.)
9710 'add_times))
9711 props))
9712 (append sum-props (nreverse props)))))))
9714 (defun org-entry-get (pom property &optional inherit)
9715 "Get value of PROPERTY for entry at point-or-marker POM.
9716 If INHERIT is non-nil and the entry does not have the property,
9717 then also check higher levels of the hierarchy.
9718 If INHERIT is the symbol `selective', use inheritance only if the setting
9719 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9720 If the property is present but empty, the return value is the empty string.
9721 If the property is not present at all, nil is returned."
9722 (org-with-point-at pom
9723 (if (and inherit (if (eq inherit 'selective)
9724 (org-property-inherit-p property)
9726 (org-entry-get-with-inheritance property)
9727 (if (member property org-special-properties)
9728 ;; We need a special property. Use brute force, get all properties.
9729 (cdr (assoc property (org-entry-properties nil 'special)))
9730 (let ((range (org-get-property-block)))
9731 (if (and range
9732 (goto-char (car range))
9733 (re-search-forward
9734 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9735 (cdr range) t))
9736 ;; Found the property, return it.
9737 (if (match-end 1)
9738 (org-match-string-no-properties 1)
9739 "")))))))
9741 (defun org-property-or-variable-value (var &optional inherit)
9742 "Check if there is a property fixing the value of VAR.
9743 If yes, return this value. If not, return the current value of the variable."
9744 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9745 (if (and prop (stringp prop) (string-match "\\S-" prop))
9746 (read prop)
9747 (symbol-value var))))
9749 (defun org-entry-delete (pom property)
9750 "Delete the property PROPERTY from entry at point-or-marker POM."
9751 (org-with-point-at pom
9752 (if (member property org-special-properties)
9753 nil ; cannot delete these properties.
9754 (let ((range (org-get-property-block)))
9755 (if (and range
9756 (goto-char (car range))
9757 (re-search-forward
9758 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9759 (cdr range) t))
9760 (progn
9761 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9763 nil)))))
9765 ;; Multi-values properties are properties that contain multiple values
9766 ;; These values are assumed to be single words, separated by whitespace.
9767 (defun org-entry-add-to-multivalued-property (pom property value)
9768 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9769 (let* ((old (org-entry-get pom property))
9770 (values (and old (org-split-string old "[ \t]"))))
9771 (unless (member value values)
9772 (setq values (cons value values))
9773 (org-entry-put pom property
9774 (mapconcat 'identity values " ")))))
9776 (defun org-entry-remove-from-multivalued-property (pom property value)
9777 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9778 (let* ((old (org-entry-get pom property))
9779 (values (and old (org-split-string old "[ \t]"))))
9780 (when (member value values)
9781 (setq values (delete value values))
9782 (org-entry-put pom property
9783 (mapconcat 'identity values " ")))))
9785 (defun org-entry-member-in-multivalued-property (pom property value)
9786 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9787 (let* ((old (org-entry-get pom property))
9788 (values (and old (org-split-string old "[ \t]"))))
9789 (member value values)))
9791 (defvar org-entry-property-inherited-from (make-marker))
9793 (defun org-entry-get-with-inheritance (property)
9794 "Get entry property, and search higher levels if not present."
9795 (let (tmp)
9796 (save-excursion
9797 (save-restriction
9798 (widen)
9799 (catch 'ex
9800 (while t
9801 (when (setq tmp (org-entry-get nil property))
9802 (org-back-to-heading t)
9803 (move-marker org-entry-property-inherited-from (point))
9804 (throw 'ex tmp))
9805 (or (org-up-heading-safe) (throw 'ex nil)))))
9806 (or tmp
9807 (cdr (assoc property org-local-properties))
9808 (cdr (assoc property org-global-properties))
9809 (cdr (assoc property org-global-properties-fixed))))))
9811 (defun org-entry-put (pom property value)
9812 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9813 (org-with-point-at pom
9814 (org-back-to-heading t)
9815 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9816 range)
9817 (cond
9818 ((equal property "TODO")
9819 (when (and (stringp value) (string-match "\\S-" value)
9820 (not (member value org-todo-keywords-1)))
9821 (error "\"%s\" is not a valid TODO state" value))
9822 (if (or (not value)
9823 (not (string-match "\\S-" value)))
9824 (setq value 'none))
9825 (org-todo value)
9826 (org-set-tags nil 'align))
9827 ((equal property "PRIORITY")
9828 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9829 (string-to-char value) ?\ ))
9830 (org-set-tags nil 'align))
9831 ((equal property "SCHEDULED")
9832 (if (re-search-forward org-scheduled-time-regexp end t)
9833 (cond
9834 ((eq value 'earlier) (org-timestamp-change -1 'day))
9835 ((eq value 'later) (org-timestamp-change 1 'day))
9836 (t (call-interactively 'org-schedule)))
9837 (call-interactively 'org-schedule)))
9838 ((equal property "DEADLINE")
9839 (if (re-search-forward org-deadline-time-regexp end t)
9840 (cond
9841 ((eq value 'earlier) (org-timestamp-change -1 'day))
9842 ((eq value 'later) (org-timestamp-change 1 'day))
9843 (t (call-interactively 'org-deadline)))
9844 (call-interactively 'org-deadline)))
9845 ((member property org-special-properties)
9846 (error "The %s property can not yet be set with `org-entry-put'"
9847 property))
9848 (t ; a non-special property
9849 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9850 (setq range (org-get-property-block beg end 'force))
9851 (goto-char (car range))
9852 (if (re-search-forward
9853 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9854 (progn
9855 (delete-region (match-beginning 1) (match-end 1))
9856 (goto-char (match-beginning 1)))
9857 (goto-char (cdr range))
9858 (insert "\n")
9859 (backward-char 1)
9860 (org-indent-line-function)
9861 (insert ":" property ":"))
9862 (and value (insert " " value))
9863 (org-indent-line-function)))))))
9865 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9866 "Get all property keys in the current buffer.
9867 With INCLUDE-SPECIALS, also list the special properties that relect things
9868 like tags and TODO state.
9869 With INCLUDE-DEFAULTS, also include properties that has special meaning
9870 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9871 With INCLUDE-COLUMNS, also include property names given in COLUMN
9872 formats in the current buffer."
9873 (let (rtn range cfmt cols s p)
9874 (save-excursion
9875 (save-restriction
9876 (widen)
9877 (goto-char (point-min))
9878 (while (re-search-forward org-property-start-re nil t)
9879 (setq range (org-get-property-block))
9880 (goto-char (car range))
9881 (while (re-search-forward
9882 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9883 (cdr range) t)
9884 (add-to-list 'rtn (org-match-string-no-properties 1)))
9885 (outline-next-heading))))
9887 (when include-specials
9888 (setq rtn (append org-special-properties rtn)))
9890 (when include-defaults
9891 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9893 (when include-columns
9894 (save-excursion
9895 (save-restriction
9896 (widen)
9897 (goto-char (point-min))
9898 (while (re-search-forward
9899 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9900 nil t)
9901 (setq cfmt (match-string 2) s 0)
9902 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9903 cfmt s)
9904 (setq s (match-end 0)
9905 p (match-string 1 cfmt))
9906 (unless (or (equal p "ITEM")
9907 (member p org-special-properties))
9908 (add-to-list 'rtn (match-string 1 cfmt))))))))
9910 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9912 (defun org-property-values (key)
9913 "Return a list of all values of property KEY."
9914 (save-excursion
9915 (save-restriction
9916 (widen)
9917 (goto-char (point-min))
9918 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9919 values)
9920 (while (re-search-forward re nil t)
9921 (add-to-list 'values (org-trim (match-string 1))))
9922 (delete "" values)))))
9924 (defun org-insert-property-drawer ()
9925 "Insert a property drawer into the current entry."
9926 (interactive)
9927 (org-back-to-heading t)
9928 (looking-at outline-regexp)
9929 (let ((indent (- (match-end 0)(match-beginning 0)))
9930 (beg (point))
9931 (re (concat "^[ \t]*" org-keyword-time-regexp))
9932 end hiddenp)
9933 (outline-next-heading)
9934 (setq end (point))
9935 (goto-char beg)
9936 (while (re-search-forward re end t))
9937 (setq hiddenp (org-invisible-p))
9938 (end-of-line 1)
9939 (and (equal (char-after) ?\n) (forward-char 1))
9940 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9941 (beginning-of-line 2))
9942 (org-skip-over-state-notes)
9943 (skip-chars-backward " \t\n\r")
9944 (if (eq (char-before) ?*) (forward-char 1))
9945 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9946 (beginning-of-line 0)
9947 (org-indent-to-column indent)
9948 (beginning-of-line 2)
9949 (org-indent-to-column indent)
9950 (beginning-of-line 0)
9951 (if hiddenp
9952 (save-excursion
9953 (org-back-to-heading t)
9954 (hide-entry))
9955 (org-flag-drawer t))))
9957 (defun org-set-property (property value)
9958 "In the current entry, set PROPERTY to VALUE.
9959 When called interactively, this will prompt for a property name, offering
9960 completion on existing and default properties. And then it will prompt
9961 for a value, offering competion either on allowed values (via an inherited
9962 xxx_ALL property) or on existing values in other instances of this property
9963 in the current file."
9964 (interactive
9965 (let* ((completion-ignore-case t)
9966 (keys (org-buffer-property-keys nil t t))
9967 (prop0 (completing-read "Property: " (mapcar 'list keys)))
9968 (prop (if (member prop0 keys)
9969 prop0
9970 (or (cdr (assoc (downcase prop0)
9971 (mapcar (lambda (x) (cons (downcase x) x))
9972 keys)))
9973 prop0)))
9974 (cur (org-entry-get nil prop))
9975 (allowed (org-property-get-allowed-values nil prop 'table))
9976 (existing (mapcar 'list (org-property-values prop)))
9977 (val (if allowed
9978 (org-completing-read "Value: " allowed nil 'req-match)
9979 (org-completing-read
9980 (concat "Value" (if (and cur (string-match "\\S-" cur))
9981 (concat "[" cur "]") "")
9982 ": ")
9983 existing nil nil "" nil cur))))
9984 (list prop (if (equal val "") cur val))))
9985 (unless (equal (org-entry-get nil property) value)
9986 (org-entry-put nil property value)))
9988 (defun org-delete-property (property)
9989 "In the current entry, delete PROPERTY."
9990 (interactive
9991 (let* ((completion-ignore-case t)
9992 (prop (completing-read
9993 "Property: " (org-entry-properties nil 'standard))))
9994 (list prop)))
9995 (message "Property %s %s" property
9996 (if (org-entry-delete nil property)
9997 "deleted"
9998 "was not present in the entry")))
10000 (defun org-delete-property-globally (property)
10001 "Remove PROPERTY globally, from all entries."
10002 (interactive
10003 (let* ((completion-ignore-case t)
10004 (prop (completing-read
10005 "Globally remove property: "
10006 (mapcar 'list (org-buffer-property-keys)))))
10007 (list prop)))
10008 (save-excursion
10009 (save-restriction
10010 (widen)
10011 (goto-char (point-min))
10012 (let ((cnt 0))
10013 (while (re-search-forward
10014 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10015 nil t)
10016 (setq cnt (1+ cnt))
10017 (replace-match ""))
10018 (message "Property \"%s\" removed from %d entries" property cnt)))))
10020 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10022 (defun org-compute-property-at-point ()
10023 "Compute the property at point.
10024 This looks for an enclosing column format, extracts the operator and
10025 then applies it to the proerty in the column format's scope."
10026 (interactive)
10027 (unless (org-at-property-p)
10028 (error "Not at a property"))
10029 (let ((prop (org-match-string-no-properties 2)))
10030 (org-columns-get-format-and-top-level)
10031 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10032 (error "No operator defined for property %s" prop))
10033 (org-columns-compute prop)))
10035 (defun org-property-get-allowed-values (pom property &optional table)
10036 "Get allowed values for the property PROPERTY.
10037 When TABLE is non-nil, return an alist that can directly be used for
10038 completion."
10039 (let (vals)
10040 (cond
10041 ((equal property "TODO")
10042 (setq vals (org-with-point-at pom
10043 (append org-todo-keywords-1 '("")))))
10044 ((equal property "PRIORITY")
10045 (let ((n org-lowest-priority))
10046 (while (>= n org-highest-priority)
10047 (push (char-to-string n) vals)
10048 (setq n (1- n)))))
10049 ((member property org-special-properties))
10051 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10053 (when (and vals (string-match "\\S-" vals))
10054 (setq vals (car (read-from-string (concat "(" vals ")"))))
10055 (setq vals (mapcar (lambda (x)
10056 (cond ((stringp x) x)
10057 ((numberp x) (number-to-string x))
10058 ((symbolp x) (symbol-name x))
10059 (t "???")))
10060 vals)))))
10061 (if table (mapcar 'list vals) vals)))
10063 (defun org-property-previous-allowed-value (&optional previous)
10064 "Switch to the next allowed value for this property."
10065 (interactive)
10066 (org-property-next-allowed-value t))
10068 (defun org-property-next-allowed-value (&optional previous)
10069 "Switch to the next allowed value for this property."
10070 (interactive)
10071 (unless (org-at-property-p)
10072 (error "Not at a property"))
10073 (let* ((key (match-string 2))
10074 (value (match-string 3))
10075 (allowed (or (org-property-get-allowed-values (point) key)
10076 (and (member value '("[ ]" "[-]" "[X]"))
10077 '("[ ]" "[X]"))))
10078 nval)
10079 (unless allowed
10080 (error "Allowed values for this property have not been defined"))
10081 (if previous (setq allowed (reverse allowed)))
10082 (if (member value allowed)
10083 (setq nval (car (cdr (member value allowed)))))
10084 (setq nval (or nval (car allowed)))
10085 (if (equal nval value)
10086 (error "Only one allowed value for this property"))
10087 (org-at-property-p)
10088 (replace-match (concat " :" key ": " nval) t t)
10089 (org-indent-line-function)
10090 (beginning-of-line 1)
10091 (skip-chars-forward " \t")))
10093 (defun org-find-entry-with-id (ident)
10094 "Locate the entry that contains the ID property with exact value IDENT.
10095 IDENT can be a string, a symbol or a number, this function will search for
10096 the string representation of it.
10097 Return the position where this entry starts, or nil if there is no such entry."
10098 (let ((id (cond
10099 ((stringp ident) ident)
10100 ((symbol-name ident) (symbol-name ident))
10101 ((numberp ident) (number-to-string ident))
10102 (t (error "IDENT %s must be a string, symbol or number" ident))))
10103 (case-fold-search nil))
10104 (save-excursion
10105 (save-restriction
10106 (widen)
10107 (goto-char (point-min))
10108 (when (re-search-forward
10109 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10110 nil t)
10111 (org-back-to-heading)
10112 (point))))))
10114 ;;;; Timestamps
10116 (defvar org-last-changed-timestamp nil)
10117 (defvar org-time-was-given) ; dynamically scoped parameter
10118 (defvar org-end-time-was-given) ; dynamically scoped parameter
10119 (defvar org-ts-what) ; dynamically scoped parameter
10121 (defun org-time-stamp (arg)
10122 "Prompt for a date/time and insert a time stamp.
10123 If the user specifies a time like HH:MM, or if this command is called
10124 with a prefix argument, the time stamp will contain date and time.
10125 Otherwise, only the date will be included. All parts of a date not
10126 specified by the user will be filled in from the current date/time.
10127 So if you press just return without typing anything, the time stamp
10128 will represent the current date/time. If there is already a timestamp
10129 at the cursor, it will be modified."
10130 (interactive "P")
10131 (let* ((ts nil)
10132 (default-time
10133 ;; Default time is either today, or, when entering a range,
10134 ;; the range start.
10135 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10136 (save-excursion
10137 (re-search-backward
10138 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10139 (- (point) 20) t)))
10140 (apply 'encode-time (org-parse-time-string (match-string 1)))
10141 (current-time)))
10142 (default-input (and ts (org-get-compact-tod ts)))
10143 org-time-was-given org-end-time-was-given time)
10144 (cond
10145 ((and (org-at-timestamp-p)
10146 (eq last-command 'org-time-stamp)
10147 (eq this-command 'org-time-stamp))
10148 (insert "--")
10149 (setq time (let ((this-command this-command))
10150 (org-read-date arg 'totime nil nil default-time default-input)))
10151 (org-insert-time-stamp time (or org-time-was-given arg)))
10152 ((org-at-timestamp-p)
10153 (setq time (let ((this-command this-command))
10154 (org-read-date arg 'totime nil nil default-time default-input)))
10155 (when (org-at-timestamp-p) ; just to get the match data
10156 (replace-match "")
10157 (setq org-last-changed-timestamp
10158 (org-insert-time-stamp
10159 time (or org-time-was-given arg)
10160 nil nil nil (list org-end-time-was-given))))
10161 (message "Timestamp updated"))
10163 (setq time (let ((this-command this-command))
10164 (org-read-date arg 'totime nil nil default-time default-input)))
10165 (org-insert-time-stamp time (or org-time-was-given arg)
10166 nil nil nil (list org-end-time-was-given))))))
10168 ;; FIXME: can we use this for something else, like computing time differences?
10169 (defun org-get-compact-tod (s)
10170 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10171 (let* ((t1 (match-string 1 s))
10172 (h1 (string-to-number (match-string 2 s)))
10173 (m1 (string-to-number (match-string 3 s)))
10174 (t2 (and (match-end 4) (match-string 5 s)))
10175 (h2 (and t2 (string-to-number (match-string 6 s))))
10176 (m2 (and t2 (string-to-number (match-string 7 s))))
10177 dh dm)
10178 (if (not t2)
10180 (setq dh (- h2 h1) dm (- m2 m1))
10181 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10182 (concat t1 "+" (number-to-string dh)
10183 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10185 (defun org-time-stamp-inactive (&optional arg)
10186 "Insert an inactive time stamp.
10187 An inactive time stamp is enclosed in square brackets instead of angle
10188 brackets. It is inactive in the sense that it does not trigger agenda entries,
10189 does not link to the calendar and cannot be changed with the S-cursor keys.
10190 So these are more for recording a certain time/date."
10191 (interactive "P")
10192 (let (org-time-was-given org-end-time-was-given time)
10193 (setq time (org-read-date arg 'totime))
10194 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10195 nil nil (list org-end-time-was-given))))
10197 (defvar org-date-ovl (org-make-overlay 1 1))
10198 (org-overlay-put org-date-ovl 'face 'org-warning)
10199 (org-detach-overlay org-date-ovl)
10201 (defvar org-ans1) ; dynamically scoped parameter
10202 (defvar org-ans2) ; dynamically scoped parameter
10204 (defvar org-plain-time-of-day-regexp) ; defined below
10206 (defvar org-read-date-overlay nil)
10207 (defvar org-dcst nil) ; dynamically scoped
10209 (defun org-read-date (&optional with-time to-time from-string prompt
10210 default-time default-input)
10211 "Read a date, possibly a time, and make things smooth for the user.
10212 The prompt will suggest to enter an ISO date, but you can also enter anything
10213 which will at least partially be understood by `parse-time-string'.
10214 Unrecognized parts of the date will default to the current day, month, year,
10215 hour and minute. If this command is called to replace a timestamp at point,
10216 of to enter the second timestamp of a range, the default time is taken from the
10217 existing stamp. For example,
10218 3-2-5 --> 2003-02-05
10219 feb 15 --> currentyear-02-15
10220 sep 12 9 --> 2009-09-12
10221 12:45 --> today 12:45
10222 22 sept 0:34 --> currentyear-09-22 0:34
10223 12 --> currentyear-currentmonth-12
10224 Fri --> nearest Friday (today or later)
10225 etc.
10227 Furthermore you can specify a relative date by giving, as the *first* thing
10228 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10229 change in days weeks, months, years.
10230 With a single plus or minus, the date is relative to today. With a double
10231 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10232 +4d --> four days from today
10233 +4 --> same as above
10234 +2w --> two weeks from today
10235 ++5 --> five days from default date
10237 The function understands only English month and weekday abbreviations,
10238 but this can be configured with the variables `parse-time-months' and
10239 `parse-time-weekdays'.
10241 While prompting, a calendar is popped up - you can also select the
10242 date with the mouse (button 1). The calendar shows a period of three
10243 months. To scroll it to other months, use the keys `>' and `<'.
10244 If you don't like the calendar, turn it off with
10245 \(setq org-read-date-popup-calendar nil)
10247 With optional argument TO-TIME, the date will immediately be converted
10248 to an internal time.
10249 With an optional argument WITH-TIME, the prompt will suggest to also
10250 insert a time. Note that when WITH-TIME is not set, you can still
10251 enter a time, and this function will inform the calling routine about
10252 this change. The calling routine may then choose to change the format
10253 used to insert the time stamp into the buffer to include the time.
10254 With optional argument FROM-STRING, read from this string instead from
10255 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10256 the time/date that is used for everything that is not specified by the
10257 user."
10258 (require 'parse-time)
10259 (let* ((org-time-stamp-rounding-minutes
10260 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10261 (org-dcst org-display-custom-times)
10262 (ct (org-current-time))
10263 (def (or default-time ct))
10264 (defdecode (decode-time def))
10265 (dummy (progn
10266 (when (< (nth 2 defdecode) org-extend-today-until)
10267 (setcar (nthcdr 2 defdecode) -1)
10268 (setcar (nthcdr 1 defdecode) 59)
10269 (setq def (apply 'encode-time defdecode)
10270 defdecode (decode-time def)))))
10271 (calendar-move-hook nil)
10272 (calendar-view-diary-initially-flag nil)
10273 (view-diary-entries-initially nil)
10274 (calendar-view-holidays-initially-flag nil)
10275 (view-calendar-holidays-initially nil)
10276 (timestr (format-time-string
10277 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10278 (prompt (concat (if prompt (concat prompt " ") "")
10279 (format "Date+time [%s]: " timestr)))
10280 ans (org-ans0 "") org-ans1 org-ans2 final)
10282 (cond
10283 (from-string (setq ans from-string))
10284 (org-read-date-popup-calendar
10285 (save-excursion
10286 (save-window-excursion
10287 (calendar)
10288 (calendar-forward-day (- (time-to-days def)
10289 (calendar-absolute-from-gregorian
10290 (calendar-current-date))))
10291 (org-eval-in-calendar nil t)
10292 (let* ((old-map (current-local-map))
10293 (map (copy-keymap calendar-mode-map))
10294 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10295 (org-defkey map (kbd "RET") 'org-calendar-select)
10296 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10297 'org-calendar-select-mouse)
10298 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10299 'org-calendar-select-mouse)
10300 (org-defkey minibuffer-local-map [(meta shift left)]
10301 (lambda () (interactive)
10302 (org-eval-in-calendar '(calendar-backward-month 1))))
10303 (org-defkey minibuffer-local-map [(meta shift right)]
10304 (lambda () (interactive)
10305 (org-eval-in-calendar '(calendar-forward-month 1))))
10306 (org-defkey minibuffer-local-map [(meta shift up)]
10307 (lambda () (interactive)
10308 (org-eval-in-calendar '(calendar-backward-year 1))))
10309 (org-defkey minibuffer-local-map [(meta shift down)]
10310 (lambda () (interactive)
10311 (org-eval-in-calendar '(calendar-forward-year 1))))
10312 (org-defkey minibuffer-local-map [(shift up)]
10313 (lambda () (interactive)
10314 (org-eval-in-calendar '(calendar-backward-week 1))))
10315 (org-defkey minibuffer-local-map [(shift down)]
10316 (lambda () (interactive)
10317 (org-eval-in-calendar '(calendar-forward-week 1))))
10318 (org-defkey minibuffer-local-map [(shift left)]
10319 (lambda () (interactive)
10320 (org-eval-in-calendar '(calendar-backward-day 1))))
10321 (org-defkey minibuffer-local-map [(shift right)]
10322 (lambda () (interactive)
10323 (org-eval-in-calendar '(calendar-forward-day 1))))
10324 (org-defkey minibuffer-local-map ">"
10325 (lambda () (interactive)
10326 (org-eval-in-calendar '(scroll-calendar-left 1))))
10327 (org-defkey minibuffer-local-map "<"
10328 (lambda () (interactive)
10329 (org-eval-in-calendar '(scroll-calendar-right 1))))
10330 (unwind-protect
10331 (progn
10332 (use-local-map map)
10333 (add-hook 'post-command-hook 'org-read-date-display)
10334 (setq org-ans0 (read-string prompt default-input nil nil))
10335 ;; org-ans0: from prompt
10336 ;; org-ans1: from mouse click
10337 ;; org-ans2: from calendar motion
10338 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10339 (remove-hook 'post-command-hook 'org-read-date-display)
10340 (use-local-map old-map)
10341 (when org-read-date-overlay
10342 (org-delete-overlay org-read-date-overlay)
10343 (setq org-read-date-overlay nil)))))))
10345 (t ; Naked prompt only
10346 (unwind-protect
10347 (setq ans (read-string prompt default-input nil timestr))
10348 (when org-read-date-overlay
10349 (org-delete-overlay org-read-date-overlay)
10350 (setq org-read-date-overlay nil)))))
10352 (setq final (org-read-date-analyze ans def defdecode))
10354 (if to-time
10355 (apply 'encode-time final)
10356 (if (and (boundp 'org-time-was-given) org-time-was-given)
10357 (format "%04d-%02d-%02d %02d:%02d"
10358 (nth 5 final) (nth 4 final) (nth 3 final)
10359 (nth 2 final) (nth 1 final))
10360 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10361 (defvar def)
10362 (defvar defdecode)
10363 (defvar with-time)
10364 (defun org-read-date-display ()
10365 "Display the currrent date prompt interpretation in the minibuffer."
10366 (when org-read-date-display-live
10367 (when org-read-date-overlay
10368 (org-delete-overlay org-read-date-overlay))
10369 (let ((p (point)))
10370 (end-of-line 1)
10371 (while (not (equal (buffer-substring
10372 (max (point-min) (- (point) 4)) (point))
10373 " "))
10374 (insert " "))
10375 (goto-char p))
10376 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10377 " " (or org-ans1 org-ans2)))
10378 (org-end-time-was-given nil)
10379 (f (org-read-date-analyze ans def defdecode))
10380 (fmts (if org-dcst
10381 org-time-stamp-custom-formats
10382 org-time-stamp-formats))
10383 (fmt (if (or with-time
10384 (and (boundp 'org-time-was-given) org-time-was-given))
10385 (cdr fmts)
10386 (car fmts)))
10387 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10388 (when (and org-end-time-was-given
10389 (string-match org-plain-time-of-day-regexp txt))
10390 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10391 org-end-time-was-given
10392 (substring txt (match-end 0)))))
10393 (setq org-read-date-overlay
10394 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10395 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10397 (defun org-read-date-analyze (ans def defdecode)
10398 "Analyze the combined answer of the date prompt."
10399 ;; FIXME: cleanup and comment
10400 (let (delta deltan deltaw deltadef year month day
10401 hour minute second wday pm h2 m2 tl wday1
10402 iso-year iso-weekday iso-week iso-year iso-date)
10404 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10405 (setq ans "+0"))
10407 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10408 (setq ans (replace-match "" t t ans)
10409 deltan (car delta)
10410 deltaw (nth 1 delta)
10411 deltadef (nth 2 delta)))
10413 ;; Check if there is an iso week date in there
10414 ;; If yes, sore the info and ostpone interpreting it until the rest
10415 ;; of the parsing is done
10416 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10417 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10418 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10419 iso-week (string-to-number (match-string 2 ans)))
10420 (setq ans (replace-match "" t t ans)))
10422 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10423 (when (string-match
10424 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10425 (setq year (if (match-end 2)
10426 (string-to-number (match-string 2 ans))
10427 (string-to-number (format-time-string "%Y")))
10428 month (string-to-number (match-string 3 ans))
10429 day (string-to-number (match-string 4 ans)))
10430 (if (< year 100) (setq year (+ 2000 year)))
10431 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10432 t nil ans)))
10433 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10434 ;; If there is a time with am/pm, and *no* time without it, we convert
10435 ;; so that matching will be successful.
10436 (loop for i from 1 to 2 do ; twice, for end time as well
10437 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10438 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10439 (setq hour (string-to-number (match-string 1 ans))
10440 minute (if (match-end 3)
10441 (string-to-number (match-string 3 ans))
10443 pm (equal ?p
10444 (string-to-char (downcase (match-string 4 ans)))))
10445 (if (and (= hour 12) (not pm))
10446 (setq hour 0)
10447 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10448 (setq ans (replace-match (format "%02d:%02d" hour minute)
10449 t t ans))))
10451 ;; Check if a time range is given as a duration
10452 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10453 (setq hour (string-to-number (match-string 1 ans))
10454 h2 (+ hour (string-to-number (match-string 3 ans)))
10455 minute (string-to-number (match-string 2 ans))
10456 m2 (+ minute (if (match-end 5) (string-to-number
10457 (match-string 5 ans))0)))
10458 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10459 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10460 t t ans)))
10462 ;; Check if there is a time range
10463 (when (boundp 'org-end-time-was-given)
10464 (setq org-time-was-given nil)
10465 (when (and (string-match org-plain-time-of-day-regexp ans)
10466 (match-end 8))
10467 (setq org-end-time-was-given (match-string 8 ans))
10468 (setq ans (concat (substring ans 0 (match-beginning 7))
10469 (substring ans (match-end 7))))))
10471 (setq tl (parse-time-string ans)
10472 day (or (nth 3 tl) (nth 3 defdecode))
10473 month (or (nth 4 tl)
10474 (if (and org-read-date-prefer-future
10475 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10476 (1+ (nth 4 defdecode))
10477 (nth 4 defdecode)))
10478 year (or (nth 5 tl)
10479 (if (and org-read-date-prefer-future
10480 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10481 (1+ (nth 5 defdecode))
10482 (nth 5 defdecode)))
10483 hour (or (nth 2 tl) (nth 2 defdecode))
10484 minute (or (nth 1 tl) (nth 1 defdecode))
10485 second (or (nth 0 tl) 0)
10486 wday (nth 6 tl))
10488 ;; Special date definitions below
10489 (cond
10490 (iso-week
10491 ;; There was an iso week
10492 (setq year (or iso-year year)
10493 day (or iso-weekday wday 1)
10494 wday nil ; to make sure that the trigger below does not match
10495 iso-date (calendar-gregorian-from-absolute
10496 (calendar-absolute-from-iso
10497 (list iso-week day year))))
10498 ; FIXME: Should we also push ISO weeks into the future?
10499 ; (when (and org-read-date-prefer-future
10500 ; (not iso-year)
10501 ; (< (calendar-absolute-from-gregorian iso-date)
10502 ; (time-to-days (current-time))))
10503 ; (setq year (1+ year)
10504 ; iso-date (calendar-gregorian-from-absolute
10505 ; (calendar-absolute-from-iso
10506 ; (list iso-week day year)))))
10507 (setq month (car iso-date)
10508 year (nth 2 iso-date)
10509 day (nth 1 iso-date)))
10510 (deltan
10511 (unless deltadef
10512 (let ((now (decode-time (current-time))))
10513 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10514 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10515 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10516 ((equal deltaw "m") (setq month (+ month deltan)))
10517 ((equal deltaw "y") (setq year (+ year deltan)))))
10518 ((and wday (not (nth 3 tl)))
10519 ;; Weekday was given, but no day, so pick that day in the week
10520 ;; on or after the derived date.
10521 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10522 (unless (equal wday wday1)
10523 (setq day (+ day (% (- wday wday1 -7) 7))))))
10524 (if (and (boundp 'org-time-was-given)
10525 (nth 2 tl))
10526 (setq org-time-was-given t))
10527 (if (< year 100) (setq year (+ 2000 year)))
10528 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10529 (list second minute hour day month year)))
10531 (defvar parse-time-weekdays)
10533 (defun org-read-date-get-relative (s today default)
10534 "Check string S for special relative date string.
10535 TODAY and DEFAULT are internal times, for today and for a default.
10536 Return shift list (N what def-flag)
10537 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10538 N is the number of WHATs to shift.
10539 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10540 the DEFAULT date rather than TODAY."
10541 (when (and
10542 (string-match
10543 (concat
10544 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10545 "\\([0-9]+\\)?"
10546 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10547 "\\([ \t]\\|$\\)") s)
10548 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10549 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10550 (string-to-char (substring (match-string 1 s) -1))
10551 ?+))
10552 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10553 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10554 (what (if (match-end 3) (match-string 3 s) "d"))
10555 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10556 (date (if rel default today))
10557 (wday (nth 6 (decode-time date)))
10558 delta)
10559 (if wday1
10560 (progn
10561 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10562 (if (= dir ?-) (setq delta (- delta 7)))
10563 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10564 (list delta "d" rel))
10565 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10567 (defun org-eval-in-calendar (form &optional keepdate)
10568 "Eval FORM in the calendar window and return to current window.
10569 Also, store the cursor date in variable org-ans2."
10570 (let ((sw (selected-window)))
10571 (select-window (get-buffer-window "*Calendar*"))
10572 (eval form)
10573 (when (and (not keepdate) (calendar-cursor-to-date))
10574 (let* ((date (calendar-cursor-to-date))
10575 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10576 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10577 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10578 (select-window sw)))
10580 ; ;; Update the prompt to show new default date
10581 ; (save-excursion
10582 ; (goto-char (point-min))
10583 ; (when (and org-ans2
10584 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10585 ; (get-text-property (match-end 0) 'field))
10586 ; (let ((inhibit-read-only t))
10587 ; (replace-match (concat "[" org-ans2 "]") t t)
10588 ; (add-text-properties (point-min) (1+ (match-end 0))
10589 ; (text-properties-at (1+ (point-min)))))))))
10591 (defun org-calendar-select ()
10592 "Return to `org-read-date' with the date currently selected.
10593 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10594 (interactive)
10595 (when (calendar-cursor-to-date)
10596 (let* ((date (calendar-cursor-to-date))
10597 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10598 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10599 (if (active-minibuffer-window) (exit-minibuffer))))
10601 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10602 "Insert a date stamp for the date given by the internal TIME.
10603 WITH-HM means, use the stamp format that includes the time of the day.
10604 INACTIVE means use square brackets instead of angular ones, so that the
10605 stamp will not contribute to the agenda.
10606 PRE and POST are optional strings to be inserted before and after the
10607 stamp.
10608 The command returns the inserted time stamp."
10609 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10610 stamp)
10611 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10612 (insert-before-markers (or pre ""))
10613 (insert-before-markers (setq stamp (format-time-string fmt time)))
10614 (when (listp extra)
10615 (setq extra (car extra))
10616 (if (and (stringp extra)
10617 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10618 (setq extra (format "-%02d:%02d"
10619 (string-to-number (match-string 1 extra))
10620 (string-to-number (match-string 2 extra))))
10621 (setq extra nil)))
10622 (when extra
10623 (backward-char 1)
10624 (insert-before-markers extra)
10625 (forward-char 1))
10626 (insert-before-markers (or post ""))
10627 stamp))
10629 (defun org-toggle-time-stamp-overlays ()
10630 "Toggle the use of custom time stamp formats."
10631 (interactive)
10632 (setq org-display-custom-times (not org-display-custom-times))
10633 (unless org-display-custom-times
10634 (let ((p (point-min)) (bmp (buffer-modified-p)))
10635 (while (setq p (next-single-property-change p 'display))
10636 (if (and (get-text-property p 'display)
10637 (eq (get-text-property p 'face) 'org-date))
10638 (remove-text-properties
10639 p (setq p (next-single-property-change p 'display))
10640 '(display t))))
10641 (set-buffer-modified-p bmp)))
10642 (if (featurep 'xemacs)
10643 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10644 (org-restart-font-lock)
10645 (setq org-table-may-need-update t)
10646 (if org-display-custom-times
10647 (message "Time stamps are overlayed with custom format")
10648 (message "Time stamp overlays removed")))
10650 (defun org-display-custom-time (beg end)
10651 "Overlay modified time stamp format over timestamp between BEG and END."
10652 (let* ((ts (buffer-substring beg end))
10653 t1 w1 with-hm tf time str w2 (off 0))
10654 (save-match-data
10655 (setq t1 (org-parse-time-string ts t))
10656 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10657 (setq off (- (match-end 0) (match-beginning 0)))))
10658 (setq end (- end off))
10659 (setq w1 (- end beg)
10660 with-hm (and (nth 1 t1) (nth 2 t1))
10661 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10662 time (org-fix-decoded-time t1)
10663 str (org-add-props
10664 (format-time-string
10665 (substring tf 1 -1) (apply 'encode-time time))
10666 nil 'mouse-face 'highlight)
10667 w2 (length str))
10668 (if (not (= w2 w1))
10669 (add-text-properties (1+ beg) (+ 2 beg)
10670 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10671 (if (featurep 'xemacs)
10672 (progn
10673 (put-text-property beg end 'invisible t)
10674 (put-text-property beg end 'end-glyph (make-glyph str)))
10675 (put-text-property beg end 'display str))))
10677 (defun org-translate-time (string)
10678 "Translate all timestamps in STRING to custom format.
10679 But do this only if the variable `org-display-custom-times' is set."
10680 (when org-display-custom-times
10681 (save-match-data
10682 (let* ((start 0)
10683 (re org-ts-regexp-both)
10684 t1 with-hm inactive tf time str beg end)
10685 (while (setq start (string-match re string start))
10686 (setq beg (match-beginning 0)
10687 end (match-end 0)
10688 t1 (save-match-data
10689 (org-parse-time-string (substring string beg end) t))
10690 with-hm (and (nth 1 t1) (nth 2 t1))
10691 inactive (equal (substring string beg (1+ beg)) "[")
10692 tf (funcall (if with-hm 'cdr 'car)
10693 org-time-stamp-custom-formats)
10694 time (org-fix-decoded-time t1)
10695 str (format-time-string
10696 (concat
10697 (if inactive "[" "<") (substring tf 1 -1)
10698 (if inactive "]" ">"))
10699 (apply 'encode-time time))
10700 string (replace-match str t t string)
10701 start (+ start (length str)))))))
10702 string)
10704 (defun org-fix-decoded-time (time)
10705 "Set 0 instead of nil for the first 6 elements of time.
10706 Don't touch the rest."
10707 (let ((n 0))
10708 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10710 (defun org-days-to-time (timestamp-string)
10711 "Difference between TIMESTAMP-STRING and now in days."
10712 (- (time-to-days (org-time-string-to-time timestamp-string))
10713 (time-to-days (current-time))))
10715 (defun org-deadline-close (timestamp-string &optional ndays)
10716 "Is the time in TIMESTAMP-STRING close to the current date?"
10717 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10718 (and (< (org-days-to-time timestamp-string) ndays)
10719 (not (org-entry-is-done-p))))
10721 (defun org-get-wdays (ts)
10722 "Get the deadline lead time appropriate for timestring TS."
10723 (cond
10724 ((<= org-deadline-warning-days 0)
10725 ;; 0 or negative, enforce this value no matter what
10726 (- org-deadline-warning-days))
10727 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10728 ;; lead time is specified.
10729 (floor (* (string-to-number (match-string 1 ts))
10730 (cdr (assoc (match-string 2 ts)
10731 '(("d" . 1) ("w" . 7)
10732 ("m" . 30.4) ("y" . 365.25)))))))
10733 ;; go for the default.
10734 (t org-deadline-warning-days)))
10736 (defun org-calendar-select-mouse (ev)
10737 "Return to `org-read-date' with the date currently selected.
10738 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10739 (interactive "e")
10740 (mouse-set-point ev)
10741 (when (calendar-cursor-to-date)
10742 (let* ((date (calendar-cursor-to-date))
10743 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10744 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10745 (if (active-minibuffer-window) (exit-minibuffer))))
10747 (defun org-check-deadlines (ndays)
10748 "Check if there are any deadlines due or past due.
10749 A deadline is considered due if it happens within `org-deadline-warning-days'
10750 days from today's date. If the deadline appears in an entry marked DONE,
10751 it is not shown. The prefix arg NDAYS can be used to test that many
10752 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10753 (interactive "P")
10754 (let* ((org-warn-days
10755 (cond
10756 ((equal ndays '(4)) 100000)
10757 (ndays (prefix-numeric-value ndays))
10758 (t (abs org-deadline-warning-days))))
10759 (case-fold-search nil)
10760 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10761 (callback
10762 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10764 (message "%d deadlines past-due or due within %d days"
10765 (org-occur regexp nil callback)
10766 org-warn-days)))
10768 (defun org-check-before-date (date)
10769 "Check if there are deadlines or scheduled entries before DATE."
10770 (interactive (list (org-read-date)))
10771 (let ((case-fold-search nil)
10772 (regexp (concat "\\<\\(" org-deadline-string
10773 "\\|" org-scheduled-string
10774 "\\) *<\\([^>]+\\)>"))
10775 (callback
10776 (lambda () (time-less-p
10777 (org-time-string-to-time (match-string 2))
10778 (org-time-string-to-time date)))))
10779 (message "%d entries before %s"
10780 (org-occur regexp nil callback) date)))
10782 (defun org-evaluate-time-range (&optional to-buffer)
10783 "Evaluate a time range by computing the difference between start and end.
10784 Normally the result is just printed in the echo area, but with prefix arg
10785 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10786 If the time range is actually in a table, the result is inserted into the
10787 next column.
10788 For time difference computation, a year is assumed to be exactly 365
10789 days in order to avoid rounding problems."
10790 (interactive "P")
10792 (org-clock-update-time-maybe)
10793 (save-excursion
10794 (unless (org-at-date-range-p t)
10795 (goto-char (point-at-bol))
10796 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10797 (if (not (org-at-date-range-p t))
10798 (error "Not at a time-stamp range, and none found in current line")))
10799 (let* ((ts1 (match-string 1))
10800 (ts2 (match-string 2))
10801 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10802 (match-end (match-end 0))
10803 (time1 (org-time-string-to-time ts1))
10804 (time2 (org-time-string-to-time ts2))
10805 (t1 (time-to-seconds time1))
10806 (t2 (time-to-seconds time2))
10807 (diff (abs (- t2 t1)))
10808 (negative (< (- t2 t1) 0))
10809 ;; (ys (floor (* 365 24 60 60)))
10810 (ds (* 24 60 60))
10811 (hs (* 60 60))
10812 (fy "%dy %dd %02d:%02d")
10813 (fy1 "%dy %dd")
10814 (fd "%dd %02d:%02d")
10815 (fd1 "%dd")
10816 (fh "%02d:%02d")
10817 y d h m align)
10818 (if havetime
10819 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10821 d (floor (/ diff ds)) diff (mod diff ds)
10822 h (floor (/ diff hs)) diff (mod diff hs)
10823 m (floor (/ diff 60)))
10824 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10826 d (floor (+ (/ diff ds) 0.5))
10827 h 0 m 0))
10828 (if (not to-buffer)
10829 (message "%s" (org-make-tdiff-string y d h m))
10830 (if (org-at-table-p)
10831 (progn
10832 (goto-char match-end)
10833 (setq align t)
10834 (and (looking-at " *|") (goto-char (match-end 0))))
10835 (goto-char match-end))
10836 (if (looking-at
10837 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10838 (replace-match ""))
10839 (if negative (insert " -"))
10840 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10841 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10842 (insert " " (format fh h m))))
10843 (if align (org-table-align))
10844 (message "Time difference inserted")))))
10846 (defun org-make-tdiff-string (y d h m)
10847 (let ((fmt "")
10848 (l nil))
10849 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10850 l (push y l)))
10851 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10852 l (push d l)))
10853 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10854 l (push h l)))
10855 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10856 l (push m l)))
10857 (apply 'format fmt (nreverse l))))
10859 (defun org-time-string-to-time (s)
10860 (apply 'encode-time (org-parse-time-string s)))
10862 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10863 "Convert a time stamp to an absolute day number.
10864 If there is a specifyer for a cyclic time stamp, get the closest date to
10865 DAYNR.
10866 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10867 (cond
10868 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10869 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10870 daynr
10871 (+ daynr 1000)))
10872 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10873 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10874 (time-to-days (current-time))) (match-string 0 s)
10875 prefer show-all))
10876 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10878 (defun org-days-to-iso-week (days)
10879 "Return the iso week number."
10880 (require 'cal-iso)
10881 (car (calendar-iso-from-absolute days)))
10883 (defun org-small-year-to-year (year)
10884 "Convert 2-digit years into 4-digit years.
10885 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10886 The year 2000 cannot be abbreviated. Any year lager than 99
10887 is retrned unchanged."
10888 (if (< year 38)
10889 (setq year (+ 2000 year))
10890 (if (< year 100)
10891 (setq year (+ 1900 year))))
10892 year)
10894 (defun org-time-from-absolute (d)
10895 "Return the time corresponding to date D.
10896 D may be an absolute day number, or a calendar-type list (month day year)."
10897 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10898 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10900 (defun org-calendar-holiday ()
10901 "List of holidays, for Diary display in Org-mode."
10902 (require 'holidays)
10903 (let ((hl (funcall
10904 (if (fboundp 'calendar-check-holidays)
10905 'calendar-check-holidays 'check-calendar-holidays) date)))
10906 (if hl (mapconcat 'identity hl "; "))))
10908 (defun org-diary-sexp-entry (sexp entry date)
10909 "Process a SEXP diary ENTRY for DATE."
10910 (require 'diary-lib)
10911 (let ((result (if calendar-debug-sexp
10912 (let ((stack-trace-on-error t))
10913 (eval (car (read-from-string sexp))))
10914 (condition-case nil
10915 (eval (car (read-from-string sexp)))
10916 (error
10917 (beep)
10918 (message "Bad sexp at line %d in %s: %s"
10919 (org-current-line)
10920 (buffer-file-name) sexp)
10921 (sleep-for 2))))))
10922 (cond ((stringp result) result)
10923 ((and (consp result)
10924 (stringp (cdr result))) (cdr result))
10925 (result entry)
10926 (t nil))))
10928 (defun org-diary-to-ical-string (frombuf)
10929 "Get iCalendar entries from diary entries in buffer FROMBUF.
10930 This uses the icalendar.el library."
10931 (let* ((tmpdir (if (featurep 'xemacs)
10932 (temp-directory)
10933 temporary-file-directory))
10934 (tmpfile (make-temp-name
10935 (expand-file-name "orgics" tmpdir)))
10936 buf rtn b e)
10937 (save-excursion
10938 (set-buffer frombuf)
10939 (icalendar-export-region (point-min) (point-max) tmpfile)
10940 (setq buf (find-buffer-visiting tmpfile))
10941 (set-buffer buf)
10942 (goto-char (point-min))
10943 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10944 (setq b (match-beginning 0)))
10945 (goto-char (point-max))
10946 (if (re-search-backward "^END:VEVENT" nil t)
10947 (setq e (match-end 0)))
10948 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10949 (kill-buffer buf)
10950 (kill-buffer frombuf)
10951 (delete-file tmpfile)
10952 rtn))
10954 (defun org-closest-date (start current change prefer show-all)
10955 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10956 When PREFER is `past' return a date that is either CURRENT or past.
10957 When PREFER is `future', return a date that is either CURRENT or future.
10958 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10959 ;; Make the proper lists from the dates
10960 (catch 'exit
10961 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10962 dn dw sday cday n1 n2
10963 d m y y1 y2 date1 date2 nmonths nm ny m2)
10965 (setq start (org-date-to-gregorian start)
10966 current (org-date-to-gregorian
10967 (if show-all
10968 current
10969 (time-to-days (current-time))))
10970 sday (calendar-absolute-from-gregorian start)
10971 cday (calendar-absolute-from-gregorian current))
10973 (if (<= cday sday) (throw 'exit sday))
10975 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10976 (setq dn (string-to-number (match-string 1 change))
10977 dw (cdr (assoc (match-string 2 change) a1)))
10978 (error "Invalid change specifyer: %s" change))
10979 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10980 (cond
10981 ((eq dw 'day)
10982 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10983 n2 (+ n1 dn)))
10984 ((eq dw 'year)
10985 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10986 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10987 (setq date1 (list m d y1)
10988 n1 (calendar-absolute-from-gregorian date1)
10989 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10990 n2 (calendar-absolute-from-gregorian date2)))
10991 ((eq dw 'month)
10992 ;; approx number of month between the tow dates
10993 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10994 ;; How often does dn fit in there?
10995 (setq d (nth 1 start) m (car start) y (nth 2 start)
10996 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10997 m (+ m nm)
10998 ny (floor (/ m 12))
10999 y (+ y ny)
11000 m (- m (* ny 12)))
11001 (while (> m 12) (setq m (- m 12) y (1+ y)))
11002 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11003 (setq m2 (+ m dn) y2 y)
11004 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11005 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11006 (while (< n2 cday)
11007 (setq n1 n2 m m2 y y2)
11008 (setq m2 (+ m dn) y2 y)
11009 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11010 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11012 (if show-all
11013 (cond
11014 ((eq prefer 'past) n1)
11015 ((eq prefer 'future) (if (= cday n1) n1 n2))
11016 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11017 (cond
11018 ((eq prefer 'past) n1)
11019 ((eq prefer 'future) (if (= cday n1) n1 n2))
11020 (t (if (= cday n1) n1 n2)))))))
11022 (defun org-date-to-gregorian (date)
11023 "Turn any specification of DATE into a gregorian date for the calendar."
11024 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11025 ((and (listp date) (= (length date) 3)) date)
11026 ((stringp date)
11027 (setq date (org-parse-time-string date))
11028 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11029 ((listp date)
11030 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11032 (defun org-parse-time-string (s &optional nodefault)
11033 "Parse the standard Org-mode time string.
11034 This should be a lot faster than the normal `parse-time-string'.
11035 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11036 hour and minute fields will be nil if not given."
11037 (if (string-match org-ts-regexp0 s)
11038 (list 0
11039 (if (or (match-beginning 8) (not nodefault))
11040 (string-to-number (or (match-string 8 s) "0")))
11041 (if (or (match-beginning 7) (not nodefault))
11042 (string-to-number (or (match-string 7 s) "0")))
11043 (string-to-number (match-string 4 s))
11044 (string-to-number (match-string 3 s))
11045 (string-to-number (match-string 2 s))
11046 nil nil nil)
11047 (make-list 9 0)))
11049 (defun org-timestamp-up (&optional arg)
11050 "Increase the date item at the cursor by one.
11051 If the cursor is on the year, change the year. If it is on the month or
11052 the day, change that.
11053 With prefix ARG, change by that many units."
11054 (interactive "p")
11055 (org-timestamp-change (prefix-numeric-value arg)))
11057 (defun org-timestamp-down (&optional arg)
11058 "Decrease the date item at the cursor by one.
11059 If the cursor is on the year, change the year. If it is on the month or
11060 the day, change that.
11061 With prefix ARG, change by that many units."
11062 (interactive "p")
11063 (org-timestamp-change (- (prefix-numeric-value arg))))
11065 (defun org-timestamp-up-day (&optional arg)
11066 "Increase the date in the time stamp by one day.
11067 With prefix ARG, change that many days."
11068 (interactive "p")
11069 (if (and (not (org-at-timestamp-p t))
11070 (org-on-heading-p))
11071 (org-todo 'up)
11072 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11074 (defun org-timestamp-down-day (&optional arg)
11075 "Decrease the date in the time stamp by one day.
11076 With prefix ARG, change that many days."
11077 (interactive "p")
11078 (if (and (not (org-at-timestamp-p t))
11079 (org-on-heading-p))
11080 (org-todo 'down)
11081 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11083 (defun org-at-timestamp-p (&optional inactive-ok)
11084 "Determine if the cursor is in or at a timestamp."
11085 (interactive)
11086 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11087 (pos (point))
11088 (ans (or (looking-at tsr)
11089 (save-excursion
11090 (skip-chars-backward "^[<\n\r\t")
11091 (if (> (point) (point-min)) (backward-char 1))
11092 (and (looking-at tsr)
11093 (> (- (match-end 0) pos) -1))))))
11094 (and ans
11095 (boundp 'org-ts-what)
11096 (setq org-ts-what
11097 (cond
11098 ((= pos (match-beginning 0)) 'bracket)
11099 ((= pos (1- (match-end 0))) 'bracket)
11100 ((org-pos-in-match-range pos 2) 'year)
11101 ((org-pos-in-match-range pos 3) 'month)
11102 ((org-pos-in-match-range pos 7) 'hour)
11103 ((org-pos-in-match-range pos 8) 'minute)
11104 ((or (org-pos-in-match-range pos 4)
11105 (org-pos-in-match-range pos 5)) 'day)
11106 ((and (> pos (or (match-end 8) (match-end 5)))
11107 (< pos (match-end 0)))
11108 (- pos (or (match-end 8) (match-end 5))))
11109 (t 'day))))
11110 ans))
11112 (defun org-toggle-timestamp-type ()
11113 "Toggle the type (<active> or [inactive]) of a time stamp."
11114 (interactive)
11115 (when (org-at-timestamp-p t)
11116 (save-excursion
11117 (goto-char (match-beginning 0))
11118 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11119 (goto-char (1- (match-end 0)))
11120 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11121 (message "Timestamp is now %sactive"
11122 (if (equal (char-before) ?>) "in" ""))))
11124 (defun org-timestamp-change (n &optional what)
11125 "Change the date in the time stamp at point.
11126 The date will be changed by N times WHAT. WHAT can be `day', `month',
11127 `year', `minute', `second'. If WHAT is not given, the cursor position
11128 in the timestamp determines what will be changed."
11129 (let ((pos (point))
11130 with-hm inactive
11131 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11132 org-ts-what
11133 extra rem
11134 ts time time0)
11135 (if (not (org-at-timestamp-p t))
11136 (error "Not at a timestamp"))
11137 (if (and (not what) (eq org-ts-what 'bracket))
11138 (org-toggle-timestamp-type)
11139 (if (and (not what) (not (eq org-ts-what 'day))
11140 org-display-custom-times
11141 (get-text-property (point) 'display)
11142 (not (get-text-property (1- (point)) 'display)))
11143 (setq org-ts-what 'day))
11144 (setq org-ts-what (or what org-ts-what)
11145 inactive (= (char-after (match-beginning 0)) ?\[)
11146 ts (match-string 0))
11147 (replace-match "")
11148 (if (string-match
11149 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11151 (setq extra (match-string 1 ts)))
11152 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11153 (setq with-hm t))
11154 (setq time0 (org-parse-time-string ts))
11155 (when (and (eq org-ts-what 'minute)
11156 (eq current-prefix-arg nil))
11157 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11158 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11159 (setcar (cdr time0) (+ (nth 1 time0)
11160 (if (> n 0) (- rem) (- dm rem))))))
11161 (setq time
11162 (encode-time (or (car time0) 0)
11163 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11164 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11165 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11166 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11167 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11168 (nthcdr 6 time0)))
11169 (when (integerp org-ts-what)
11170 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11171 (if (eq what 'calendar)
11172 (let ((cal-date (org-get-date-from-calendar)))
11173 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11174 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11175 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11176 (setcar time0 (or (car time0) 0))
11177 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11178 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11179 (setq time (apply 'encode-time time0))))
11180 (setq org-last-changed-timestamp
11181 (org-insert-time-stamp time with-hm inactive nil nil extra))
11182 (org-clock-update-time-maybe)
11183 (goto-char pos)
11184 ;; Try to recenter the calendar window, if any
11185 (if (and org-calendar-follow-timestamp-change
11186 (get-buffer-window "*Calendar*" t)
11187 (memq org-ts-what '(day month year)))
11188 (org-recenter-calendar (time-to-days time))))))
11190 (defun org-modify-ts-extra (s pos n dm)
11191 "Change the different parts of the lead-time and repeat fields in timestamp."
11192 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11193 ng h m new rem)
11194 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11195 (cond
11196 ((or (org-pos-in-match-range pos 2)
11197 (org-pos-in-match-range pos 3))
11198 (setq m (string-to-number (match-string 3 s))
11199 h (string-to-number (match-string 2 s)))
11200 (if (org-pos-in-match-range pos 2)
11201 (setq h (+ h n))
11202 (setq n (* dm (org-no-warnings (signum n))))
11203 (when (not (= 0 (setq rem (% m dm))))
11204 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11205 (setq m (+ m n)))
11206 (if (< m 0) (setq m (+ m 60) h (1- h)))
11207 (if (> m 59) (setq m (- m 60) h (1+ h)))
11208 (setq h (min 24 (max 0 h)))
11209 (setq ng 1 new (format "-%02d:%02d" h m)))
11210 ((org-pos-in-match-range pos 6)
11211 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11212 ((org-pos-in-match-range pos 5)
11213 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11215 ((org-pos-in-match-range pos 9)
11216 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11217 ((org-pos-in-match-range pos 8)
11218 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11220 (when ng
11221 (setq s (concat
11222 (substring s 0 (match-beginning ng))
11224 (substring s (match-end ng))))))
11227 (defun org-recenter-calendar (date)
11228 "If the calendar is visible, recenter it to DATE."
11229 (let* ((win (selected-window))
11230 (cwin (get-buffer-window "*Calendar*" t))
11231 (calendar-move-hook nil))
11232 (when cwin
11233 (select-window cwin)
11234 (calendar-goto-date (if (listp date) date
11235 (calendar-gregorian-from-absolute date)))
11236 (select-window win))))
11238 (defun org-goto-calendar (&optional arg)
11239 "Go to the Emacs calendar at the current date.
11240 If there is a time stamp in the current line, go to that date.
11241 A prefix ARG can be used to force the current date."
11242 (interactive "P")
11243 (let ((tsr org-ts-regexp) diff
11244 (calendar-move-hook nil)
11245 (calendar-view-holidays-initially-flag nil)
11246 (view-calendar-holidays-initially nil)
11247 (calendar-view-diary-initially-flag nil)
11248 (view-diary-entries-initially nil))
11249 (if (or (org-at-timestamp-p)
11250 (save-excursion
11251 (beginning-of-line 1)
11252 (looking-at (concat ".*" tsr))))
11253 (let ((d1 (time-to-days (current-time)))
11254 (d2 (time-to-days
11255 (org-time-string-to-time (match-string 1)))))
11256 (setq diff (- d2 d1))))
11257 (calendar)
11258 (calendar-goto-today)
11259 (if (and diff (not arg)) (calendar-forward-day diff))))
11261 (defun org-get-date-from-calendar ()
11262 "Return a list (month day year) of date at point in calendar."
11263 (with-current-buffer "*Calendar*"
11264 (save-match-data
11265 (calendar-cursor-to-date))))
11267 (defun org-date-from-calendar ()
11268 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11269 If there is already a time stamp at the cursor position, update it."
11270 (interactive)
11271 (if (org-at-timestamp-p t)
11272 (org-timestamp-change 0 'calendar)
11273 (let ((cal-date (org-get-date-from-calendar)))
11274 (org-insert-time-stamp
11275 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11277 (defun org-minutes-to-hh:mm-string (m)
11278 "Compute H:MM from a number of minutes."
11279 (let ((h (/ m 60)))
11280 (setq m (- m (* 60 h)))
11281 (format "%d:%02d" h m)))
11283 (defun org-hh:mm-string-to-minutes (s)
11284 "Convert a string H:MM to a number of minutes."
11285 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11286 (+ (* (string-to-number (match-string 1 s)) 60)
11287 (string-to-number (match-string 2 s)))
11290 ;;;; Agenda files
11292 ;;;###autoload
11293 (defun org-iswitchb (&optional arg)
11294 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11295 With a prefix argument, restrict available to files.
11296 With two prefix arguments, restrict available buffers to agenda files.
11298 Due to some yet unresolved reason, global function
11299 `iswitchb-mode' needs to be active for this function to work."
11300 (interactive "P")
11301 (require 'iswitchb)
11302 (let ((enabled iswitchb-mode) blist)
11303 (or enabled (iswitchb-mode 1))
11304 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11305 ((equal arg '(16)) (org-buffer-list 'agenda))
11306 (t (org-buffer-list))))
11307 (unwind-protect
11308 (let ((iswitchb-make-buflist-hook
11309 (lambda ()
11310 (setq iswitchb-temp-buflist
11311 (mapcar 'buffer-name blist)))))
11312 (switch-to-buffer
11313 (iswitchb-read-buffer
11314 "Switch-to: " nil t))
11315 (or enabled (iswitchb-mode -1))))))
11317 (defun org-buffer-list (&optional predicate tmp)
11318 "Return a list of Org buffers.
11319 PREDICATE can be either 'export, 'files or 'agenda.
11321 'export restrict the list to Export buffers.
11322 'files restrict the list to buffers visiting Org files.
11323 'agenda restrict the list to buffers visiting agenda files.
11325 If TMP is non-nil, don't include temporary buffers."
11326 (let (filter blist)
11327 (setq filter
11328 (cond ((eq predicate 'files) "\.org$")
11329 ((eq predicate 'export) "\*Org .*Export")
11330 (t "\*Org \\|\.org$")))
11331 (setq blist
11332 (mapcar
11333 (lambda(b)
11334 (let ((bname (buffer-name b))
11335 (bfile (buffer-file-name b)))
11336 (if (and (string-match filter bname)
11337 (if (eq predicate 'agenda)
11338 (member bfile
11339 (mapcar (lambda(f) (file-truename f))
11340 org-agenda-files)) t)
11341 (if tmp (not (string-match "tmp" bname)) t)) b)))
11342 (buffer-list)))
11343 (delete nil blist)))
11345 (defun org-agenda-files (&optional unrestricted ext)
11346 "Get the list of agenda files.
11347 Optional UNRESTRICTED means return the full list even if a restriction
11348 is currently in place.
11349 When EXT is non-nil, try to add all files that are created by adding EXT
11350 to the file nemes. Basically, this is a way to add the archive files
11351 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11352 a string, \"_archive\" will be used."
11353 (let ((files
11354 (cond
11355 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11356 ((stringp org-agenda-files) (org-read-agenda-file-list))
11357 ((listp org-agenda-files) org-agenda-files)
11358 (t (error "Invalid value of `org-agenda-files'")))))
11359 (setq files (apply 'append
11360 (mapcar (lambda (f)
11361 (if (file-directory-p f)
11362 (directory-files
11363 f t org-agenda-file-regexp)
11364 (list f)))
11365 files)))
11366 (when org-agenda-skip-unavailable-files
11367 (setq files (delq nil
11368 (mapcar (function
11369 (lambda (file)
11370 (and (file-readable-p file) file)))
11371 files))))
11372 (when ext
11373 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11374 ext "_archive"))
11375 (setq files (apply 'append
11376 (mapcar
11377 (lambda (f)
11378 (if (file-exists-p (concat f ext))
11379 (list f (concat f ext))
11380 (list f)))
11381 files))))
11382 files))
11384 (defun org-edit-agenda-file-list ()
11385 "Edit the list of agenda files.
11386 Depending on setup, this either uses customize to edit the variable
11387 `org-agenda-files', or it visits the file that is holding the list. In the
11388 latter case, the buffer is set up in a way that saving it automatically kills
11389 the buffer and restores the previous window configuration."
11390 (interactive)
11391 (if (stringp org-agenda-files)
11392 (let ((cw (current-window-configuration)))
11393 (find-file org-agenda-files)
11394 (org-set-local 'org-window-configuration cw)
11395 (org-add-hook 'after-save-hook
11396 (lambda ()
11397 (set-window-configuration
11398 (prog1 org-window-configuration
11399 (kill-buffer (current-buffer))))
11400 (org-install-agenda-files-menu)
11401 (message "New agenda file list installed"))
11402 nil 'local)
11403 (message "%s" (substitute-command-keys
11404 "Edit list and finish with \\[save-buffer]")))
11405 (customize-variable 'org-agenda-files)))
11407 (defun org-store-new-agenda-file-list (list)
11408 "Set new value for the agenda file list and save it correcly."
11409 (if (stringp org-agenda-files)
11410 (let ((f org-agenda-files) b)
11411 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11412 (with-temp-file f
11413 (insert (mapconcat 'identity list "\n") "\n")))
11414 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11415 (setq org-agenda-files list)
11416 (customize-save-variable 'org-agenda-files org-agenda-files))))
11418 (defun org-read-agenda-file-list ()
11419 "Read the list of agenda files from a file."
11420 (when (file-directory-p org-agenda-files)
11421 (error "`org-agenda-files' cannot be a single directory"))
11422 (when (stringp org-agenda-files)
11423 (with-temp-buffer
11424 (insert-file-contents org-agenda-files)
11425 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11428 ;;;###autoload
11429 (defun org-cycle-agenda-files ()
11430 "Cycle through the files in `org-agenda-files'.
11431 If the current buffer visits an agenda file, find the next one in the list.
11432 If the current buffer does not, find the first agenda file."
11433 (interactive)
11434 (let* ((fs (org-agenda-files t))
11435 (files (append fs (list (car fs))))
11436 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11437 file)
11438 (unless files (error "No agenda files"))
11439 (catch 'exit
11440 (while (setq file (pop files))
11441 (if (equal (file-truename file) tcf)
11442 (when (car files)
11443 (find-file (car files))
11444 (throw 'exit t))))
11445 (find-file (car fs)))
11446 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11448 (defun org-agenda-file-to-front (&optional to-end)
11449 "Move/add the current file to the top of the agenda file list.
11450 If the file is not present in the list, it is added to the front. If it is
11451 present, it is moved there. With optional argument TO-END, add/move to the
11452 end of the list."
11453 (interactive "P")
11454 (let ((org-agenda-skip-unavailable-files nil)
11455 (file-alist (mapcar (lambda (x)
11456 (cons (file-truename x) x))
11457 (org-agenda-files t)))
11458 (ctf (file-truename buffer-file-name))
11459 x had)
11460 (setq x (assoc ctf file-alist) had x)
11462 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11463 (if to-end
11464 (setq file-alist (append (delq x file-alist) (list x)))
11465 (setq file-alist (cons x (delq x file-alist))))
11466 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11467 (org-install-agenda-files-menu)
11468 (message "File %s to %s of agenda file list"
11469 (if had "moved" "added") (if to-end "end" "front"))))
11471 (defun org-remove-file (&optional file)
11472 "Remove current file from the list of files in variable `org-agenda-files'.
11473 These are the files which are being checked for agenda entries.
11474 Optional argument FILE means, use this file instead of the current."
11475 (interactive)
11476 (let* ((org-agenda-skip-unavailable-files nil)
11477 (file (or file buffer-file-name))
11478 (true-file (file-truename file))
11479 (afile (abbreviate-file-name file))
11480 (files (delq nil (mapcar
11481 (lambda (x)
11482 (if (equal true-file
11483 (file-truename x))
11484 nil x))
11485 (org-agenda-files t)))))
11486 (if (not (= (length files) (length (org-agenda-files t))))
11487 (progn
11488 (org-store-new-agenda-file-list files)
11489 (org-install-agenda-files-menu)
11490 (message "Removed file: %s" afile))
11491 (message "File was not in list: %s (not removed)" afile))))
11493 (defun org-file-menu-entry (file)
11494 (vector file (list 'find-file file) t))
11496 (defun org-check-agenda-file (file)
11497 "Make sure FILE exists. If not, ask user what to do."
11498 (when (not (file-exists-p file))
11499 (message "non-existent file %s. [R]emove from list or [A]bort?"
11500 (abbreviate-file-name file))
11501 (let ((r (downcase (read-char-exclusive))))
11502 (cond
11503 ((equal r ?r)
11504 (org-remove-file file)
11505 (throw 'nextfile t))
11506 (t (error "Abort"))))))
11508 (defun org-get-agenda-file-buffer (file)
11509 "Get a buffer visiting FILE. If the buffer needs to be created, add
11510 it to the list of buffers which might be released later."
11511 (let ((buf (org-find-base-buffer-visiting file)))
11512 (if buf
11513 buf ; just return it
11514 ;; Make a new buffer and remember it
11515 (setq buf (find-file-noselect file))
11516 (if buf (push buf org-agenda-new-buffers))
11517 buf)))
11519 (defun org-release-buffers (blist)
11520 "Release all buffers in list, asking the user for confirmation when needed.
11521 When a buffer is unmodified, it is just killed. When modified, it is saved
11522 \(if the user agrees) and then killed."
11523 (let (buf file)
11524 (while (setq buf (pop blist))
11525 (setq file (buffer-file-name buf))
11526 (when (and (buffer-modified-p buf)
11527 file
11528 (y-or-n-p (format "Save file %s? " file)))
11529 (with-current-buffer buf (save-buffer)))
11530 (kill-buffer buf))))
11532 (defun org-prepare-agenda-buffers (files)
11533 "Create buffers for all agenda files, protect archived trees and comments."
11534 (interactive)
11535 (let ((pa '(:org-archived t))
11536 (pc '(:org-comment t))
11537 (pall '(:org-archived t :org-comment t))
11538 (inhibit-read-only t)
11539 (rea (concat ":" org-archive-tag ":"))
11540 bmp file re)
11541 (save-excursion
11542 (save-restriction
11543 (while (setq file (pop files))
11544 (if (bufferp file)
11545 (set-buffer file)
11546 (org-check-agenda-file file)
11547 (set-buffer (org-get-agenda-file-buffer file)))
11548 (widen)
11549 (setq bmp (buffer-modified-p))
11550 (org-refresh-category-properties)
11551 (setq org-todo-keywords-for-agenda
11552 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11553 (setq org-done-keywords-for-agenda
11554 (append org-done-keywords-for-agenda org-done-keywords))
11555 (save-excursion
11556 (remove-text-properties (point-min) (point-max) pall)
11557 (when org-agenda-skip-archived-trees
11558 (goto-char (point-min))
11559 (while (re-search-forward rea nil t)
11560 (if (org-on-heading-p t)
11561 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11562 (goto-char (point-min))
11563 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11564 (while (re-search-forward re nil t)
11565 (add-text-properties
11566 (match-beginning 0) (org-end-of-subtree t) pc)))
11567 (set-buffer-modified-p bmp))))))
11569 ;;;; Embedded LaTeX
11571 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11572 "Keymap for the minor `org-cdlatex-mode'.")
11574 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11575 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11576 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11577 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11578 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11580 (defvar org-cdlatex-texmathp-advice-is-done nil
11581 "Flag remembering if we have applied the advice to texmathp already.")
11583 (define-minor-mode org-cdlatex-mode
11584 "Toggle the minor `org-cdlatex-mode'.
11585 This mode supports entering LaTeX environment and math in LaTeX fragments
11586 in Org-mode.
11587 \\{org-cdlatex-mode-map}"
11588 nil " OCDL" nil
11589 (when org-cdlatex-mode (require 'cdlatex))
11590 (unless org-cdlatex-texmathp-advice-is-done
11591 (setq org-cdlatex-texmathp-advice-is-done t)
11592 (defadvice texmathp (around org-math-always-on activate)
11593 "Always return t in org-mode buffers.
11594 This is because we want to insert math symbols without dollars even outside
11595 the LaTeX math segments. If Orgmode thinks that point is actually inside
11596 en embedded LaTeX fragement, let texmathp do its job.
11597 \\[org-cdlatex-mode-map]"
11598 (interactive)
11599 (let (p)
11600 (cond
11601 ((not (org-mode-p)) ad-do-it)
11602 ((eq this-command 'cdlatex-math-symbol)
11603 (setq ad-return-value t
11604 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11606 (let ((p (org-inside-LaTeX-fragment-p)))
11607 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11608 (setq ad-return-value t
11609 texmathp-why '("Org-mode embedded math" . 0))
11610 (if p ad-do-it)))))))))
11612 (defun turn-on-org-cdlatex ()
11613 "Unconditionally turn on `org-cdlatex-mode'."
11614 (org-cdlatex-mode 1))
11616 (defun org-inside-LaTeX-fragment-p ()
11617 "Test if point is inside a LaTeX fragment.
11618 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11619 sequence appearing also before point.
11620 Even though the matchers for math are configurable, this function assumes
11621 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11622 delimiters are skipped when they have been removed by customization.
11623 The return value is nil, or a cons cell with the delimiter and
11624 and the position of this delimiter.
11626 This function does a reasonably good job, but can locally be fooled by
11627 for example currency specifications. For example it will assume being in
11628 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11629 fragments that are properly closed, but during editing, we have to live
11630 with the uncertainty caused by missing closing delimiters. This function
11631 looks only before point, not after."
11632 (catch 'exit
11633 (let ((pos (point))
11634 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11635 (lim (progn
11636 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11637 (point)))
11638 dd-on str (start 0) m re)
11639 (goto-char pos)
11640 (when dodollar
11641 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11642 re (nth 1 (assoc "$" org-latex-regexps)))
11643 (while (string-match re str start)
11644 (cond
11645 ((= (match-end 0) (length str))
11646 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11647 ((= (match-end 0) (- (length str) 5))
11648 (throw 'exit nil))
11649 (t (setq start (match-end 0))))))
11650 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11651 (goto-char pos)
11652 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11653 (and (match-beginning 2) (throw 'exit nil))
11654 ;; count $$
11655 (while (re-search-backward "\\$\\$" lim t)
11656 (setq dd-on (not dd-on)))
11657 (goto-char pos)
11658 (if dd-on (cons "$$" m))))))
11661 (defun org-try-cdlatex-tab ()
11662 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11663 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11664 - inside a LaTeX fragment, or
11665 - after the first word in a line, where an abbreviation expansion could
11666 insert a LaTeX environment."
11667 (when org-cdlatex-mode
11668 (cond
11669 ((save-excursion
11670 (skip-chars-backward "a-zA-Z0-9*")
11671 (skip-chars-backward " \t")
11672 (bolp))
11673 (cdlatex-tab) t)
11674 ((org-inside-LaTeX-fragment-p)
11675 (cdlatex-tab) t)
11676 (t nil))))
11678 (defun org-cdlatex-underscore-caret (&optional arg)
11679 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11680 Revert to the normal definition outside of these fragments."
11681 (interactive "P")
11682 (if (org-inside-LaTeX-fragment-p)
11683 (call-interactively 'cdlatex-sub-superscript)
11684 (let (org-cdlatex-mode)
11685 (call-interactively (key-binding (vector last-input-event))))))
11687 (defun org-cdlatex-math-modify (&optional arg)
11688 "Execute `cdlatex-math-modify' in LaTeX fragments.
11689 Revert to the normal definition outside of these fragments."
11690 (interactive "P")
11691 (if (org-inside-LaTeX-fragment-p)
11692 (call-interactively 'cdlatex-math-modify)
11693 (let (org-cdlatex-mode)
11694 (call-interactively (key-binding (vector last-input-event))))))
11696 (defvar org-latex-fragment-image-overlays nil
11697 "List of overlays carrying the images of latex fragments.")
11698 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11700 (defun org-remove-latex-fragment-image-overlays ()
11701 "Remove all overlays with LaTeX fragment images in current buffer."
11702 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11703 (setq org-latex-fragment-image-overlays nil))
11705 (defun org-preview-latex-fragment (&optional subtree)
11706 "Preview the LaTeX fragment at point, or all locally or globally.
11707 If the cursor is in a LaTeX fragment, create the image and overlay
11708 it over the source code. If there is no fragment at point, display
11709 all fragments in the current text, from one headline to the next. With
11710 prefix SUBTREE, display all fragments in the current subtree. With a
11711 double prefix `C-u C-u', or when the cursor is before the first headline,
11712 display all fragments in the buffer.
11713 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11714 (interactive "P")
11715 (org-remove-latex-fragment-image-overlays)
11716 (save-excursion
11717 (save-restriction
11718 (let (beg end at msg)
11719 (cond
11720 ((or (equal subtree '(16))
11721 (not (save-excursion
11722 (re-search-backward (concat "^" outline-regexp) nil t))))
11723 (setq beg (point-min) end (point-max)
11724 msg "Creating images for buffer...%s"))
11725 ((equal subtree '(4))
11726 (org-back-to-heading)
11727 (setq beg (point) end (org-end-of-subtree t)
11728 msg "Creating images for subtree...%s"))
11730 (if (setq at (org-inside-LaTeX-fragment-p))
11731 (goto-char (max (point-min) (- (cdr at) 2)))
11732 (org-back-to-heading))
11733 (setq beg (point) end (progn (outline-next-heading) (point))
11734 msg (if at "Creating image...%s"
11735 "Creating images for entry...%s"))))
11736 (message msg "")
11737 (narrow-to-region beg end)
11738 (goto-char beg)
11739 (org-format-latex
11740 (concat "ltxpng/" (file-name-sans-extension
11741 (file-name-nondirectory
11742 buffer-file-name)))
11743 default-directory 'overlays msg at 'forbuffer)
11744 (message msg "done. Use `C-c C-c' to remove images.")))))
11746 (defvar org-latex-regexps
11747 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11748 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11749 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11750 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11751 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11752 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11753 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11754 "Regular expressions for matching embedded LaTeX.")
11756 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11757 "Replace LaTeX fragments with links to an image, and produce images."
11758 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11759 (let* ((prefixnodir (file-name-nondirectory prefix))
11760 (absprefix (expand-file-name prefix dir))
11761 (todir (file-name-directory absprefix))
11762 (opt org-format-latex-options)
11763 (matchers (plist-get opt :matchers))
11764 (re-list org-latex-regexps)
11765 (cnt 0) txt link beg end re e checkdir
11766 m n block linkfile movefile ov)
11767 ;; Check if there are old images files with this prefix, and remove them
11768 (when (file-directory-p todir)
11769 (mapc 'delete-file
11770 (directory-files
11771 todir 'full
11772 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11773 ;; Check the different regular expressions
11774 (while (setq e (pop re-list))
11775 (setq m (car e) re (nth 1 e) n (nth 2 e)
11776 block (if (nth 3 e) "\n\n" ""))
11777 (when (member m matchers)
11778 (goto-char (point-min))
11779 (while (re-search-forward re nil t)
11780 (when (or (not at) (equal (cdr at) (match-beginning n)))
11781 (setq txt (match-string n)
11782 beg (match-beginning n) end (match-end n)
11783 cnt (1+ cnt)
11784 linkfile (format "%s_%04d.png" prefix cnt)
11785 movefile (format "%s_%04d.png" absprefix cnt)
11786 link (concat block "[[file:" linkfile "]]" block))
11787 (if msg (message msg cnt))
11788 (goto-char beg)
11789 (unless checkdir ; make sure the directory exists
11790 (setq checkdir t)
11791 (or (file-directory-p todir) (make-directory todir)))
11792 (org-create-formula-image
11793 txt movefile opt forbuffer)
11794 (if overlays
11795 (progn
11796 (setq ov (org-make-overlay beg end))
11797 (if (featurep 'xemacs)
11798 (progn
11799 (org-overlay-put ov 'invisible t)
11800 (org-overlay-put
11801 ov 'end-glyph
11802 (make-glyph (vector 'png :file movefile))))
11803 (org-overlay-put
11804 ov 'display
11805 (list 'image :type 'png :file movefile :ascent 'center)))
11806 (push ov org-latex-fragment-image-overlays)
11807 (goto-char end))
11808 (delete-region beg end)
11809 (insert link))))))))
11811 ;; This function borrows from Ganesh Swami's latex2png.el
11812 (defun org-create-formula-image (string tofile options buffer)
11813 (let* ((tmpdir (if (featurep 'xemacs)
11814 (temp-directory)
11815 temporary-file-directory))
11816 (texfilebase (make-temp-name
11817 (expand-file-name "orgtex" tmpdir)))
11818 (texfile (concat texfilebase ".tex"))
11819 (dvifile (concat texfilebase ".dvi"))
11820 (pngfile (concat texfilebase ".png"))
11821 (fnh (if (featurep 'xemacs)
11822 (font-height (get-face-font 'default))
11823 (face-attribute 'default :height nil)))
11824 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11825 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11826 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11827 "Black"))
11828 (bg (or (plist-get options (if buffer :background :html-background))
11829 "Transparent")))
11830 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11831 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11832 (with-temp-file texfile
11833 (insert org-format-latex-header
11834 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11835 (let ((dir default-directory))
11836 (condition-case nil
11837 (progn
11838 (cd tmpdir)
11839 (call-process "latex" nil nil nil texfile))
11840 (error nil))
11841 (cd dir))
11842 (if (not (file-exists-p dvifile))
11843 (progn (message "Failed to create dvi file from %s" texfile) nil)
11844 (call-process "dvipng" nil nil nil
11845 "-E" "-fg" fg "-bg" bg
11846 "-D" dpi
11847 ;;"-x" scale "-y" scale
11848 "-T" "tight"
11849 "-o" pngfile
11850 dvifile)
11851 (if (not (file-exists-p pngfile))
11852 (progn (message "Failed to create png file from %s" texfile) nil)
11853 ;; Use the requested file name and clean up
11854 (copy-file pngfile tofile 'replace)
11855 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11856 (delete-file (concat texfilebase e)))
11857 pngfile))))
11859 (defun org-dvipng-color (attr)
11860 "Return an rgb color specification for dvipng."
11861 (apply 'format "rgb %s %s %s"
11862 (mapcar 'org-normalize-color
11863 (color-values (face-attribute 'default attr nil)))))
11865 (defun org-normalize-color (value)
11866 "Return string to be used as color value for an RGB component."
11867 (format "%g" (/ value 65535.0)))
11870 ;;;; Key bindings
11872 ;; Make `C-c C-x' a prefix key
11873 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11875 ;; TAB key with modifiers
11876 (org-defkey org-mode-map "\C-i" 'org-cycle)
11877 (org-defkey org-mode-map [(tab)] 'org-cycle)
11878 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11879 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11880 (org-defkey org-mode-map "\M-\t" 'org-complete)
11881 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11882 ;; The following line is necessary under Suse GNU/Linux
11883 (unless (featurep 'xemacs)
11884 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11885 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11886 (define-key org-mode-map [backtab] 'org-shifttab)
11888 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11889 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11890 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11892 ;; Cursor keys with modifiers
11893 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11894 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11895 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11896 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11898 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11899 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11900 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11901 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11903 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11904 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11905 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11906 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11908 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11909 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11911 ;;; Extra keys for tty access.
11912 ;; We only set them when really needed because otherwise the
11913 ;; menus don't show the simple keys
11915 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11916 (not window-system))
11917 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11918 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11919 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11920 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11921 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11922 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11923 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11924 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11925 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11926 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11927 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11928 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11929 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11930 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11931 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11932 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11933 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11934 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11935 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11936 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11937 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11938 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11940 ;; All the other keys
11942 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11943 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11944 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11945 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11946 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11947 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11948 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11949 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11950 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11951 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11952 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11953 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11954 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11955 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11956 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11957 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11958 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11959 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11960 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11961 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11962 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11963 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11964 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11965 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11966 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11967 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11968 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11969 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11970 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11971 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11972 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11973 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11974 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11975 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11976 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11977 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11978 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11979 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11980 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11981 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11982 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11983 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11984 (org-defkey org-mode-map "\C-c^" 'org-sort)
11985 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11986 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11987 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11988 (org-defkey org-mode-map "\C-m" 'org-return)
11989 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11990 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11991 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11992 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11993 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11994 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11995 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11996 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11997 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11998 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11999 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12000 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12001 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12002 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12003 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12004 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12006 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12007 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12008 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12009 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12011 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12012 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12013 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12014 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12015 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12016 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12017 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12018 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12019 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12020 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12021 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12022 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12024 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12026 (when (featurep 'xemacs)
12027 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12029 (defvar org-table-auto-blank-field) ; defined in org-table.el
12030 (defun org-self-insert-command (N)
12031 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12032 If the cursor is in a table looking at whitespace, the whitespace is
12033 overwritten, and the table is not marked as requiring realignment."
12034 (interactive "p")
12035 (if (and (org-table-p)
12036 (progn
12037 ;; check if we blank the field, and if that triggers align
12038 (and (featurep 'org-table) org-table-auto-blank-field
12039 (member last-command
12040 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12041 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12042 ;; got extra space, this field does not determine column width
12043 (let (org-table-may-need-update) (org-table-blank-field))
12044 ;; no extra space, this field may determine column width
12045 (org-table-blank-field)))
12047 (eq N 1)
12048 (looking-at "[^|\n]* |"))
12049 (let (org-table-may-need-update)
12050 (goto-char (1- (match-end 0)))
12051 (delete-backward-char 1)
12052 (goto-char (match-beginning 0))
12053 (self-insert-command N))
12054 (setq org-table-may-need-update t)
12055 (self-insert-command N)
12056 (org-fix-tags-on-the-fly)))
12058 (defun org-fix-tags-on-the-fly ()
12059 (when (and (equal (char-after (point-at-bol)) ?*)
12060 (org-on-heading-p))
12061 (org-align-tags-here org-tags-column)))
12063 (defun org-delete-backward-char (N)
12064 "Like `delete-backward-char', insert whitespace at field end in tables.
12065 When deleting backwards, in tables this function will insert whitespace in
12066 front of the next \"|\" separator, to keep the table aligned. The table will
12067 still be marked for re-alignment if the field did fill the entire column,
12068 because, in this case the deletion might narrow the column."
12069 (interactive "p")
12070 (if (and (org-table-p)
12071 (eq N 1)
12072 (string-match "|" (buffer-substring (point-at-bol) (point)))
12073 (looking-at ".*?|"))
12074 (let ((pos (point))
12075 (noalign (looking-at "[^|\n\r]* |"))
12076 (c org-table-may-need-update))
12077 (backward-delete-char N)
12078 (skip-chars-forward "^|")
12079 (insert " ")
12080 (goto-char (1- pos))
12081 ;; noalign: if there were two spaces at the end, this field
12082 ;; does not determine the width of the column.
12083 (if noalign (setq org-table-may-need-update c)))
12084 (backward-delete-char N)
12085 (org-fix-tags-on-the-fly)))
12087 (defun org-delete-char (N)
12088 "Like `delete-char', but insert whitespace at field end in tables.
12089 When deleting characters, in tables this function will insert whitespace in
12090 front of the next \"|\" separator, to keep the table aligned. The table will
12091 still be marked for re-alignment if the field did fill the entire column,
12092 because, in this case the deletion might narrow the column."
12093 (interactive "p")
12094 (if (and (org-table-p)
12095 (not (bolp))
12096 (not (= (char-after) ?|))
12097 (eq N 1))
12098 (if (looking-at ".*?|")
12099 (let ((pos (point))
12100 (noalign (looking-at "[^|\n\r]* |"))
12101 (c org-table-may-need-update))
12102 (replace-match (concat
12103 (substring (match-string 0) 1 -1)
12104 " |"))
12105 (goto-char pos)
12106 ;; noalign: if there were two spaces at the end, this field
12107 ;; does not determine the width of the column.
12108 (if noalign (setq org-table-may-need-update c)))
12109 (delete-char N))
12110 (delete-char N)
12111 (org-fix-tags-on-the-fly)))
12113 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12114 (put 'org-self-insert-command 'delete-selection t)
12115 (put 'orgtbl-self-insert-command 'delete-selection t)
12116 (put 'org-delete-char 'delete-selection 'supersede)
12117 (put 'org-delete-backward-char 'delete-selection 'supersede)
12119 ;; Make `flyspell-mode' delay after some commands
12120 (put 'org-self-insert-command 'flyspell-delayed t)
12121 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12122 (put 'org-delete-char 'flyspell-delayed t)
12123 (put 'org-delete-backward-char 'flyspell-delayed t)
12125 ;; Make pabbrev-mode expand after org-mode commands
12126 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12127 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12129 ;; How to do this: Measure non-white length of current string
12130 ;; If equal to column width, we should realign.
12132 (defun org-remap (map &rest commands)
12133 "In MAP, remap the functions given in COMMANDS.
12134 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12135 (let (new old)
12136 (while commands
12137 (setq old (pop commands) new (pop commands))
12138 (if (fboundp 'command-remapping)
12139 (org-defkey map (vector 'remap old) new)
12140 (substitute-key-definition old new map global-map)))))
12142 (when (eq org-enable-table-editor 'optimized)
12143 ;; If the user wants maximum table support, we need to hijack
12144 ;; some standard editing functions
12145 (org-remap org-mode-map
12146 'self-insert-command 'org-self-insert-command
12147 'delete-char 'org-delete-char
12148 'delete-backward-char 'org-delete-backward-char)
12149 (org-defkey org-mode-map "|" 'org-force-self-insert))
12151 (defun org-shiftcursor-error ()
12152 "Throw an error because Shift-Cursor command was applied in wrong context."
12153 (error "This command is active in special context like tables, headlines or timestamps"))
12155 (defun org-shifttab (&optional arg)
12156 "Global visibility cycling or move to previous table field.
12157 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12158 on context.
12159 See the individual commands for more information."
12160 (interactive "P")
12161 (cond
12162 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12163 ((integerp arg)
12164 (message "Content view to level: " arg)
12165 (org-content (prefix-numeric-value arg))
12166 (setq org-cycle-global-status 'overview))
12167 (t (call-interactively 'org-global-cycle))))
12169 (defun org-shiftmetaleft ()
12170 "Promote subtree or delete table column.
12171 Calls `org-promote-subtree', `org-outdent-item',
12172 or `org-table-delete-column', depending on context.
12173 See the individual commands for more information."
12174 (interactive)
12175 (cond
12176 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12177 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12178 ((org-at-item-p) (call-interactively 'org-outdent-item))
12179 (t (org-shiftcursor-error))))
12181 (defun org-shiftmetaright ()
12182 "Demote subtree or insert table column.
12183 Calls `org-demote-subtree', `org-indent-item',
12184 or `org-table-insert-column', depending on context.
12185 See the individual commands for more information."
12186 (interactive)
12187 (cond
12188 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12189 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12190 ((org-at-item-p) (call-interactively 'org-indent-item))
12191 (t (org-shiftcursor-error))))
12193 (defun org-shiftmetaup (&optional arg)
12194 "Move subtree up or kill table row.
12195 Calls `org-move-subtree-up' or `org-table-kill-row' or
12196 `org-move-item-up' depending on context. See the individual commands
12197 for more information."
12198 (interactive "P")
12199 (cond
12200 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12201 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12202 ((org-at-item-p) (call-interactively 'org-move-item-up))
12203 (t (org-shiftcursor-error))))
12204 (defun org-shiftmetadown (&optional arg)
12205 "Move subtree down or insert table row.
12206 Calls `org-move-subtree-down' or `org-table-insert-row' or
12207 `org-move-item-down', depending on context. See the individual
12208 commands for more information."
12209 (interactive "P")
12210 (cond
12211 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12212 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12213 ((org-at-item-p) (call-interactively 'org-move-item-down))
12214 (t (org-shiftcursor-error))))
12216 (defun org-metaleft (&optional arg)
12217 "Promote heading or move table column to left.
12218 Calls `org-do-promote' or `org-table-move-column', depending on context.
12219 With no specific context, calls the Emacs default `backward-word'.
12220 See the individual commands for more information."
12221 (interactive "P")
12222 (cond
12223 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12224 ((or (org-on-heading-p) (org-region-active-p))
12225 (call-interactively 'org-do-promote))
12226 ((org-at-item-p) (call-interactively 'org-outdent-item))
12227 (t (call-interactively 'backward-word))))
12229 (defun org-metaright (&optional arg)
12230 "Demote subtree or move table column to right.
12231 Calls `org-do-demote' or `org-table-move-column', depending on context.
12232 With no specific context, calls the Emacs default `forward-word'.
12233 See the individual commands for more information."
12234 (interactive "P")
12235 (cond
12236 ((org-at-table-p) (call-interactively 'org-table-move-column))
12237 ((or (org-on-heading-p) (org-region-active-p))
12238 (call-interactively 'org-do-demote))
12239 ((org-at-item-p) (call-interactively 'org-indent-item))
12240 (t (call-interactively 'forward-word))))
12242 (defun org-metaup (&optional arg)
12243 "Move subtree up or move table row up.
12244 Calls `org-move-subtree-up' or `org-table-move-row' or
12245 `org-move-item-up', depending on context. See the individual commands
12246 for more information."
12247 (interactive "P")
12248 (cond
12249 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12250 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12251 ((org-at-item-p) (call-interactively 'org-move-item-up))
12252 (t (transpose-lines 1) (beginning-of-line -1))))
12254 (defun org-metadown (&optional arg)
12255 "Move subtree down or move table row down.
12256 Calls `org-move-subtree-down' or `org-table-move-row' or
12257 `org-move-item-down', depending on context. See the individual
12258 commands for more information."
12259 (interactive "P")
12260 (cond
12261 ((org-at-table-p) (call-interactively 'org-table-move-row))
12262 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12263 ((org-at-item-p) (call-interactively 'org-move-item-down))
12264 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12266 (defun org-shiftup (&optional arg)
12267 "Increase item in timestamp or increase priority of current headline.
12268 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12269 depending on context. See the individual commands for more information."
12270 (interactive "P")
12271 (cond
12272 ((org-at-timestamp-p t)
12273 (call-interactively (if org-edit-timestamp-down-means-later
12274 'org-timestamp-down 'org-timestamp-up)))
12275 ((org-on-heading-p) (call-interactively 'org-priority-up))
12276 ((org-at-item-p) (call-interactively 'org-previous-item))
12277 ((org-clocktable-try-shift 'up arg))
12278 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12280 (defun org-shiftdown (&optional arg)
12281 "Decrease item in timestamp or decrease priority of current headline.
12282 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12283 depending on context. See the individual commands for more information."
12284 (interactive "P")
12285 (cond
12286 ((org-at-timestamp-p t)
12287 (call-interactively (if org-edit-timestamp-down-means-later
12288 'org-timestamp-up 'org-timestamp-down)))
12289 ((org-on-heading-p) (call-interactively 'org-priority-down))
12290 ((org-clocktable-try-shift 'down arg))
12291 (t (call-interactively 'org-next-item))))
12293 (defun org-shiftright (&optional arg)
12294 "Next TODO keyword or timestamp one day later, depending on context."
12295 (interactive "P")
12296 (cond
12297 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12298 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12299 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12300 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12301 ((org-clocktable-try-shift 'right arg))
12302 (t (org-shiftcursor-error))))
12304 (defun org-shiftleft (&optional arg)
12305 "Previous TODO keyword or timestamp one day earlier, depending on context."
12306 (interactive "P")
12307 (cond
12308 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12309 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12310 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12311 ((org-at-property-p)
12312 (call-interactively 'org-property-previous-allowed-value))
12313 ((org-clocktable-try-shift 'left arg))
12314 (t (org-shiftcursor-error))))
12316 (defun org-shiftcontrolright ()
12317 "Switch to next TODO set."
12318 (interactive)
12319 (cond
12320 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12321 (t (org-shiftcursor-error))))
12323 (defun org-shiftcontrolleft ()
12324 "Switch to previous TODO set."
12325 (interactive)
12326 (cond
12327 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12328 (t (org-shiftcursor-error))))
12330 (defun org-ctrl-c-ret ()
12331 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12332 (interactive)
12333 (cond
12334 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12335 (t (call-interactively 'org-insert-heading))))
12337 (defun org-copy-special ()
12338 "Copy region in table or copy current subtree.
12339 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12340 See the individual commands for more information."
12341 (interactive)
12342 (call-interactively
12343 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12345 (defun org-cut-special ()
12346 "Cut region in table or cut current subtree.
12347 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12348 See the individual commands for more information."
12349 (interactive)
12350 (call-interactively
12351 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12353 (defun org-paste-special (arg)
12354 "Paste rectangular region into table, or past subtree relative to level.
12355 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12356 See the individual commands for more information."
12357 (interactive "P")
12358 (if (org-at-table-p)
12359 (org-table-paste-rectangle)
12360 (org-paste-subtree arg)))
12362 (defun org-ctrl-c-ctrl-c (&optional arg)
12363 "Set tags in headline, or update according to changed information at point.
12365 This command does many different things, depending on context:
12367 - If the cursor is in a headline, prompt for tags and insert them
12368 into the current line, aligned to `org-tags-column'. When called
12369 with prefix arg, realign all tags in the current buffer.
12371 - If the cursor is in one of the special #+KEYWORD lines, this
12372 triggers scanning the buffer for these lines and updating the
12373 information.
12375 - If the cursor is inside a table, realign the table. This command
12376 works even if the automatic table editor has been turned off.
12378 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12379 the entire table.
12381 - If the cursor is a the beginning of a dynamic block, update it.
12383 - If the cursor is inside a table created by the table.el package,
12384 activate that table.
12386 - If the current buffer is a remember buffer, close note and file it.
12387 with a prefix argument, file it without further interaction to the default
12388 location.
12390 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12391 links in this buffer.
12393 - If the cursor is on a numbered item in a plain list, renumber the
12394 ordered list.
12396 - If the cursor is on a checkbox, toggle it."
12397 (interactive "P")
12398 (let ((org-enable-table-editor t))
12399 (cond
12400 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12401 org-occur-highlights
12402 org-latex-fragment-image-overlays)
12403 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12404 (org-remove-occur-highlights)
12405 (org-remove-latex-fragment-image-overlays)
12406 (message "Temporary highlights/overlays removed from current buffer"))
12407 ((and (local-variable-p 'org-finish-function (current-buffer))
12408 (fboundp org-finish-function))
12409 (funcall org-finish-function))
12410 ((org-at-property-p)
12411 (call-interactively 'org-property-action))
12412 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12413 ((org-on-heading-p) (call-interactively 'org-set-tags))
12414 ((org-at-table.el-p)
12415 (require 'table)
12416 (beginning-of-line 1)
12417 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12418 (call-interactively 'table-recognize-table))
12419 ((org-at-table-p)
12420 (org-table-maybe-eval-formula)
12421 (if arg
12422 (call-interactively 'org-table-recalculate)
12423 (org-table-maybe-recalculate-line))
12424 (call-interactively 'org-table-align))
12425 ((org-at-item-checkbox-p)
12426 (call-interactively 'org-toggle-checkbox))
12427 ((org-at-item-p)
12428 (call-interactively 'org-maybe-renumber-ordered-list))
12429 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12430 ;; Dynamic block
12431 (beginning-of-line 1)
12432 (org-update-dblock))
12433 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12434 (cond
12435 ((equal (match-string 1) "TBLFM")
12436 ;; Recalculate the table before this line
12437 (save-excursion
12438 (beginning-of-line 1)
12439 (skip-chars-backward " \r\n\t")
12440 (if (org-at-table-p)
12441 (org-call-with-arg 'org-table-recalculate t))))
12443 (org-set-regexps-and-options)
12444 (org-restart-font-lock)
12445 (message "Local setup has been refreshed"))))
12446 (t (error "C-c C-c can do nothing useful at this location.")))))
12448 (defun org-mode-restart ()
12449 "Restart Org-mode, to scan again for special lines.
12450 Also updates the keyword regular expressions."
12451 (interactive)
12452 (org-mode)
12453 (message "Org-mode restarted"))
12455 (defun org-kill-note-or-show-branches ()
12456 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12457 (interactive)
12458 (if (not org-finish-function)
12459 (call-interactively 'show-branches)
12460 (let ((org-note-abort t))
12461 (funcall org-finish-function))))
12463 (defun org-return (&optional indent)
12464 "Goto next table row or insert a newline.
12465 Calls `org-table-next-row' or `newline', depending on context.
12466 See the individual commands for more information."
12467 (interactive)
12468 (cond
12469 ((bobp) (if indent (newline-and-indent) (newline)))
12470 ((and (org-at-heading-p)
12471 (looking-at
12472 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12473 (org-show-entry)
12474 (end-of-line 1)
12475 (newline))
12476 ((org-at-table-p)
12477 (org-table-justify-field-maybe)
12478 (call-interactively 'org-table-next-row))
12479 (t (if indent (newline-and-indent) (newline)))))
12481 (defun org-return-indent ()
12482 "Goto next table row or insert a newline and indent.
12483 Calls `org-table-next-row' or `newline-and-indent', depending on
12484 context. See the individual commands for more information."
12485 (interactive)
12486 (org-return t))
12488 (defun org-ctrl-c-star ()
12489 "Compute table, or change heading status of lines.
12490 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12491 depending on context. This will also turn a plain list item or a normal
12492 line into a subheading."
12493 (interactive)
12494 (cond
12495 ((org-at-table-p)
12496 (call-interactively 'org-table-recalculate))
12497 ((org-region-active-p)
12498 ;; Convert all lines in region to list items
12499 (call-interactively 'org-toggle-region-headings))
12500 ((org-on-heading-p)
12501 (org-toggle-region-headings (point-at-bol)
12502 (min (1+ (point-at-eol)) (point-max))))
12503 ((org-at-item-p)
12504 ;; Convert to heading
12505 (let ((level (save-match-data
12506 (save-excursion
12507 (condition-case nil
12508 (progn
12509 (org-back-to-heading t)
12510 (funcall outline-level))
12511 (error 0))))))
12512 (replace-match
12513 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12514 (t (org-toggle-region-headings (point-at-bol)
12515 (min (1+ (point-at-eol)) (point-max))))))
12517 (defun org-ctrl-c-minus ()
12518 "Insert separator line in table or modify bullet status of line.
12519 Also turns a plain line or a region of lines into list items.
12520 Calls `org-table-insert-hline', `org-toggle-region-items', or
12521 `org-cycle-list-bullet', depending on context."
12522 (interactive)
12523 (cond
12524 ((org-at-table-p)
12525 (call-interactively 'org-table-insert-hline))
12526 ((org-on-heading-p)
12527 ;; Convert to item
12528 (save-excursion
12529 (beginning-of-line 1)
12530 (if (looking-at "\\*+ ")
12531 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12532 ((org-region-active-p)
12533 ;; Convert all lines in region to list items
12534 (call-interactively 'org-toggle-region-items))
12535 ((org-in-item-p)
12536 (call-interactively 'org-cycle-list-bullet))
12537 (t (org-toggle-region-items (point-at-bol)
12538 (min (1+ (point-at-eol)) (point-max))))))
12540 (defun org-toggle-region-items (beg end)
12541 "Convert all lines in region to list items.
12542 If the first line is already an item, convert all list items in the region
12543 to normal lines."
12544 (interactive "r")
12545 (let (l2 l)
12546 (save-excursion
12547 (goto-char end)
12548 (setq l2 (org-current-line))
12549 (goto-char beg)
12550 (beginning-of-line 1)
12551 (setq l (1- (org-current-line)))
12552 (if (org-at-item-p)
12553 ;; We already have items, de-itemize
12554 (while (< (setq l (1+ l)) l2)
12555 (when (org-at-item-p)
12556 (goto-char (match-beginning 2))
12557 (delete-region (match-beginning 2) (match-end 2))
12558 (and (looking-at "[ \t]+") (replace-match "")))
12559 (beginning-of-line 2))
12560 (while (< (setq l (1+ l)) l2)
12561 (unless (org-at-item-p)
12562 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12563 (replace-match "\\1- \\2")))
12564 (beginning-of-line 2))))))
12566 (defun org-toggle-region-headings (beg end)
12567 "Convert all lines in region to list items.
12568 If the first line is already an item, convert all list items in the region
12569 to normal lines."
12570 (interactive "r")
12571 (let (l2 l)
12572 (save-excursion
12573 (goto-char end)
12574 (setq l2 (org-current-line))
12575 (goto-char beg)
12576 (beginning-of-line 1)
12577 (setq l (1- (org-current-line)))
12578 (if (org-on-heading-p)
12579 ;; We already have headlines, de-star them
12580 (while (< (setq l (1+ l)) l2)
12581 (when (org-on-heading-p t)
12582 (and (looking-at outline-regexp) (replace-match "")))
12583 (beginning-of-line 2))
12584 (let* ((stars (save-excursion
12585 (re-search-backward org-complex-heading-regexp nil t)
12586 (or (match-string 1) "*")))
12587 (add-stars (if org-odd-levels-only "**" "*"))
12588 (rpl (concat stars add-stars " \\2")))
12589 (while (< (setq l (1+ l)) l2)
12590 (unless (org-on-heading-p)
12591 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12592 (replace-match rpl)))
12593 (beginning-of-line 2)))))))
12595 (defun org-meta-return (&optional arg)
12596 "Insert a new heading or wrap a region in a table.
12597 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12598 See the individual commands for more information."
12599 (interactive "P")
12600 (cond
12601 ((org-at-table-p)
12602 (call-interactively 'org-table-wrap-region))
12603 (t (call-interactively 'org-insert-heading))))
12605 ;;; Menu entries
12607 ;; Define the Org-mode menus
12608 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12609 '("Tbl"
12610 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12611 ["Next Field" org-cycle (org-at-table-p)]
12612 ["Previous Field" org-shifttab (org-at-table-p)]
12613 ["Next Row" org-return (org-at-table-p)]
12614 "--"
12615 ["Blank Field" org-table-blank-field (org-at-table-p)]
12616 ["Edit Field" org-table-edit-field (org-at-table-p)]
12617 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12618 "--"
12619 ("Column"
12620 ["Move Column Left" org-metaleft (org-at-table-p)]
12621 ["Move Column Right" org-metaright (org-at-table-p)]
12622 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12623 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12624 ("Row"
12625 ["Move Row Up" org-metaup (org-at-table-p)]
12626 ["Move Row Down" org-metadown (org-at-table-p)]
12627 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12628 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12629 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12630 "--"
12631 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12632 ("Rectangle"
12633 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12634 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12635 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12636 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12637 "--"
12638 ("Calculate"
12639 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12640 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12641 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12642 "--"
12643 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12644 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12645 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12646 "--"
12647 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12648 "--"
12649 ["Sum Column/Rectangle" org-table-sum
12650 (or (org-at-table-p) (org-region-active-p))]
12651 ["Which Column?" org-table-current-column (org-at-table-p)])
12652 ["Debug Formulas"
12653 org-table-toggle-formula-debugger
12654 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12655 ["Show Col/Row Numbers"
12656 org-table-toggle-coordinate-overlays
12657 :style toggle
12658 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12659 "--"
12660 ["Create" org-table-create (and (not (org-at-table-p))
12661 org-enable-table-editor)]
12662 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12663 ["Import from File" org-table-import (not (org-at-table-p))]
12664 ["Export to File" org-table-export (org-at-table-p)]
12665 "--"
12666 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12668 (easy-menu-define org-org-menu org-mode-map "Org menu"
12669 '("Org"
12670 ("Show/Hide"
12671 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12672 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12673 ["Sparse Tree..." org-sparse-tree t]
12674 ["Reveal Context" org-reveal t]
12675 ["Show All" show-all t]
12676 "--"
12677 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12678 "--"
12679 ["New Heading" org-insert-heading t]
12680 ("Navigate Headings"
12681 ["Up" outline-up-heading t]
12682 ["Next" outline-next-visible-heading t]
12683 ["Previous" outline-previous-visible-heading t]
12684 ["Next Same Level" outline-forward-same-level t]
12685 ["Previous Same Level" outline-backward-same-level t]
12686 "--"
12687 ["Jump" org-goto t])
12688 ("Edit Structure"
12689 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12690 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12691 "--"
12692 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12693 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12694 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12695 "--"
12696 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12697 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12698 ["Demote Heading" org-metaright (not (org-at-table-p))]
12699 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12700 "--"
12701 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12702 "--"
12703 ["Convert to odd levels" org-convert-to-odd-levels t]
12704 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12705 ("Editing"
12706 ["Emphasis..." org-emphasize t])
12707 ("Archive"
12708 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12709 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12710 ; :active t :keys "C-u C-c C-x C-a"]
12711 ["Sparse trees open ARCHIVE trees"
12712 (setq org-sparse-tree-open-archived-trees
12713 (not org-sparse-tree-open-archived-trees))
12714 :style toggle :selected org-sparse-tree-open-archived-trees]
12715 ["Cycling opens ARCHIVE trees"
12716 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12717 :style toggle :selected org-cycle-open-archived-trees]
12718 ["Agenda includes ARCHIVE trees"
12719 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12720 :style toggle :selected (not org-agenda-skip-archived-trees)]
12721 "--"
12722 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12723 ; ["Check and Move Children" (org-archive-subtree '(4))
12724 ; :active t :keys "C-u C-c C-x C-s"]
12726 "--"
12727 ("TODO Lists"
12728 ["TODO/DONE/-" org-todo t]
12729 ("Select keyword"
12730 ["Next keyword" org-shiftright (org-on-heading-p)]
12731 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12732 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12733 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12734 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12735 ["Show TODO Tree" org-show-todo-tree t]
12736 ["Global TODO list" org-todo-list t]
12737 "--"
12738 ["Set Priority" org-priority t]
12739 ["Priority Up" org-shiftup t]
12740 ["Priority Down" org-shiftdown t])
12741 ("TAGS and Properties"
12742 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12743 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12744 "--"
12745 ["Set property" 'org-set-property t]
12746 ["Column view of properties" org-columns t]
12747 ["Insert Column View DBlock" org-insert-columns-dblock t])
12748 ("Dates and Scheduling"
12749 ["Timestamp" org-time-stamp t]
12750 ["Timestamp (inactive)" org-time-stamp-inactive t]
12751 ("Change Date"
12752 ["1 Day Later" org-shiftright t]
12753 ["1 Day Earlier" org-shiftleft t]
12754 ["1 ... Later" org-shiftup t]
12755 ["1 ... Earlier" org-shiftdown t])
12756 ["Compute Time Range" org-evaluate-time-range t]
12757 ["Schedule Item" org-schedule t]
12758 ["Deadline" org-deadline t]
12759 "--"
12760 ["Custom time format" org-toggle-time-stamp-overlays
12761 :style radio :selected org-display-custom-times]
12762 "--"
12763 ["Goto Calendar" org-goto-calendar t]
12764 ["Date from Calendar" org-date-from-calendar t])
12765 ("Logging work"
12766 ["Clock in" org-clock-in t]
12767 ["Clock out" org-clock-out t]
12768 ["Clock cancel" org-clock-cancel t]
12769 ["Goto running clock" org-clock-goto t]
12770 ["Display times" org-clock-display t]
12771 ["Create clock table" org-clock-report t]
12772 "--"
12773 ["Record DONE time"
12774 (progn (setq org-log-done (not org-log-done))
12775 (message "Switching to %s will %s record a timestamp"
12776 (car org-done-keywords)
12777 (if org-log-done "automatically" "not")))
12778 :style toggle :selected org-log-done])
12779 "--"
12780 ["Agenda Command..." org-agenda t]
12781 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12782 ("File List for Agenda")
12783 ("Special views current file"
12784 ["TODO Tree" org-show-todo-tree t]
12785 ["Check Deadlines" org-check-deadlines t]
12786 ["Timeline" org-timeline t]
12787 ["Tags Tree" org-tags-sparse-tree t])
12788 "--"
12789 ("Hyperlinks"
12790 ["Store Link (Global)" org-store-link t]
12791 ["Insert Link" org-insert-link t]
12792 ["Follow Link" org-open-at-point t]
12793 "--"
12794 ["Next link" org-next-link t]
12795 ["Previous link" org-previous-link t]
12796 "--"
12797 ["Descriptive Links"
12798 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12799 :style radio
12800 :selected (member '(org-link) buffer-invisibility-spec)]
12801 ["Literal Links"
12802 (progn
12803 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12804 :style radio
12805 :selected (not (member '(org-link) buffer-invisibility-spec))])
12806 "--"
12807 ["Export/Publish..." org-export t]
12808 ("LaTeX"
12809 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12810 :selected org-cdlatex-mode]
12811 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12812 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12813 ["Modify math symbol" org-cdlatex-math-modify
12814 (org-inside-LaTeX-fragment-p)]
12815 ["Export LaTeX fragments as images"
12816 (if (featurep 'org-exp)
12817 (setq org-export-with-LaTeX-fragments
12818 (not org-export-with-LaTeX-fragments))
12819 (require 'org-exp))
12820 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12821 org-export-with-LaTeX-fragments)])
12822 "--"
12823 ("Documentation"
12824 ["Show Version" org-version t]
12825 ["Info Documentation" org-info t])
12826 ("Customize"
12827 ["Browse Org Group" org-customize t]
12828 "--"
12829 ["Expand This Menu" org-create-customize-menu
12830 (fboundp 'customize-menu-create)])
12831 "--"
12832 ["Refresh setup" org-mode-restart t]
12835 (defun org-info (&optional node)
12836 "Read documentation for Org-mode in the info system.
12837 With optional NODE, go directly to that node."
12838 (interactive)
12839 (info (format "(org)%s" (or node ""))))
12841 (defun org-install-agenda-files-menu ()
12842 (let ((bl (buffer-list)))
12843 (save-excursion
12844 (while bl
12845 (set-buffer (pop bl))
12846 (if (org-mode-p) (setq bl nil)))
12847 (when (org-mode-p)
12848 (easy-menu-change
12849 '("Org") "File List for Agenda"
12850 (append
12851 (list
12852 ["Edit File List" (org-edit-agenda-file-list) t]
12853 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12854 ["Remove Current File from List" org-remove-file t]
12855 ["Cycle through agenda files" org-cycle-agenda-files t]
12856 ["Occur in all agenda files" org-occur-in-agenda-files t]
12857 "--")
12858 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12860 ;;;; Documentation
12862 (defun org-require-autoloaded-modules ()
12863 (interactive)
12864 (mapc 'require
12865 '(org-agenda org-archive org-clock org-colview
12866 org-exp org-export-latex org-publish
12867 org-remember org-table)))
12869 (defun org-customize ()
12870 "Call the customize function with org as argument."
12871 (interactive)
12872 (org-load-modules-maybe)
12873 (org-require-autoloaded-modules)
12874 (customize-browse 'org))
12876 (defun org-create-customize-menu ()
12877 "Create a full customization menu for Org-mode, insert it into the menu."
12878 (interactive)
12879 (org-load-modules-maybe)
12880 (org-require-autoloaded-modules)
12881 (if (fboundp 'customize-menu-create)
12882 (progn
12883 (easy-menu-change
12884 '("Org") "Customize"
12885 `(["Browse Org group" org-customize t]
12886 "--"
12887 ,(customize-menu-create 'org)
12888 ["Set" Custom-set t]
12889 ["Save" Custom-save t]
12890 ["Reset to Current" Custom-reset-current t]
12891 ["Reset to Saved" Custom-reset-saved t]
12892 ["Reset to Standard Settings" Custom-reset-standard t]))
12893 (message "\"Org\"-menu now contains full customization menu"))
12894 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12896 ;;;; Miscellaneous stuff
12898 ;;; Generally useful functions
12900 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12901 "Display the given MESSAGE as a warning."
12902 (if (fboundp 'display-warning)
12903 (display-warning 'org message
12904 (if (featurep 'xemacs)
12905 'warning
12906 :warning))
12907 (let ((buf (get-buffer-create "*Org warnings*")))
12908 (with-current-buffer buf
12909 (goto-char (point-max))
12910 (insert "Warning (Org): " message)
12911 (unless (bolp)
12912 (newline)))
12913 (display-buffer buf)
12914 (sit-for 0))))
12916 (defun org-plist-delete (plist property)
12917 "Delete PROPERTY from PLIST.
12918 This is in contrast to merely setting it to 0."
12919 (let (p)
12920 (while plist
12921 (if (not (eq property (car plist)))
12922 (setq p (plist-put p (car plist) (nth 1 plist))))
12923 (setq plist (cddr plist)))
12926 (defun org-force-self-insert (N)
12927 "Needed to enforce self-insert under remapping."
12928 (interactive "p")
12929 (self-insert-command N))
12931 (defun org-string-width (s)
12932 "Compute width of string, ignoring invisible characters.
12933 This ignores character with invisibility property `org-link', and also
12934 characters with property `org-cwidth', because these will become invisible
12935 upon the next fontification round."
12936 (let (b l)
12937 (when (or (eq t buffer-invisibility-spec)
12938 (assq 'org-link buffer-invisibility-spec))
12939 (while (setq b (text-property-any 0 (length s)
12940 'invisible 'org-link s))
12941 (setq s (concat (substring s 0 b)
12942 (substring s (or (next-single-property-change
12943 b 'invisible s) (length s)))))))
12944 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12945 (setq s (concat (substring s 0 b)
12946 (substring s (or (next-single-property-change
12947 b 'org-cwidth s) (length s))))))
12948 (setq l (string-width s) b -1)
12949 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12950 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12953 (defun org-base-buffer (buffer)
12954 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12955 (if (not buffer)
12956 buffer
12957 (or (buffer-base-buffer buffer)
12958 buffer)))
12960 (defun org-trim (s)
12961 "Remove whitespace at beginning and end of string."
12962 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12963 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12966 (defun org-wrap (string &optional width lines)
12967 "Wrap string to either a number of lines, or a width in characters.
12968 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12969 that costs. If there is a word longer than WIDTH, the text is actually
12970 wrapped to the length of that word.
12971 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12972 many lines, whatever width that takes.
12973 The return value is a list of lines, without newlines at the end."
12974 (let* ((words (org-split-string string "[ \t\n]+"))
12975 (maxword (apply 'max (mapcar 'org-string-width words)))
12976 w ll)
12977 (cond (width
12978 (org-do-wrap words (max maxword width)))
12979 (lines
12980 (setq w maxword)
12981 (setq ll (org-do-wrap words maxword))
12982 (if (<= (length ll) lines)
12984 (setq ll words)
12985 (while (> (length ll) lines)
12986 (setq w (1+ w))
12987 (setq ll (org-do-wrap words w)))
12988 ll))
12989 (t (error "Cannot wrap this")))))
12991 (defun org-do-wrap (words width)
12992 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12993 (let (lines line)
12994 (while words
12995 (setq line (pop words))
12996 (while (and words (< (+ (length line) (length (car words))) width))
12997 (setq line (concat line " " (pop words))))
12998 (setq lines (push line lines)))
12999 (nreverse lines)))
13001 (defun org-split-string (string &optional separators)
13002 "Splits STRING into substrings at SEPARATORS.
13003 No empty strings are returned if there are matches at the beginning
13004 and end of string."
13005 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13006 (start 0)
13007 notfirst
13008 (list nil))
13009 (while (and (string-match rexp string
13010 (if (and notfirst
13011 (= start (match-beginning 0))
13012 (< start (length string)))
13013 (1+ start) start))
13014 (< (match-beginning 0) (length string)))
13015 (setq notfirst t)
13016 (or (eq (match-beginning 0) 0)
13017 (and (eq (match-beginning 0) (match-end 0))
13018 (eq (match-beginning 0) start))
13019 (setq list
13020 (cons (substring string start (match-beginning 0))
13021 list)))
13022 (setq start (match-end 0)))
13023 (or (eq start (length string))
13024 (setq list
13025 (cons (substring string start)
13026 list)))
13027 (nreverse list)))
13029 (defun org-context ()
13030 "Return a list of contexts of the current cursor position.
13031 If several contexts apply, all are returned.
13032 Each context entry is a list with a symbol naming the context, and
13033 two positions indicating start and end of the context. Possible
13034 contexts are:
13036 :headline anywhere in a headline
13037 :headline-stars on the leading stars in a headline
13038 :todo-keyword on a TODO keyword (including DONE) in a headline
13039 :tags on the TAGS in a headline
13040 :priority on the priority cookie in a headline
13041 :item on the first line of a plain list item
13042 :item-bullet on the bullet/number of a plain list item
13043 :checkbox on the checkbox in a plain list item
13044 :table in an org-mode table
13045 :table-special on a special filed in a table
13046 :table-table in a table.el table
13047 :link on a hyperlink
13048 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13049 :target on a <<target>>
13050 :radio-target on a <<<radio-target>>>
13051 :latex-fragment on a LaTeX fragment
13052 :latex-preview on a LaTeX fragment with overlayed preview image
13054 This function expects the position to be visible because it uses font-lock
13055 faces as a help to recognize the following contexts: :table-special, :link,
13056 and :keyword."
13057 (let* ((f (get-text-property (point) 'face))
13058 (faces (if (listp f) f (list f)))
13059 (p (point)) clist o)
13060 ;; First the large context
13061 (cond
13062 ((org-on-heading-p t)
13063 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13064 (when (progn
13065 (beginning-of-line 1)
13066 (looking-at org-todo-line-tags-regexp))
13067 (push (org-point-in-group p 1 :headline-stars) clist)
13068 (push (org-point-in-group p 2 :todo-keyword) clist)
13069 (push (org-point-in-group p 4 :tags) clist))
13070 (goto-char p)
13071 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13072 (if (looking-at "\\[#[A-Z0-9]\\]")
13073 (push (org-point-in-group p 0 :priority) clist)))
13075 ((org-at-item-p)
13076 (push (org-point-in-group p 2 :item-bullet) clist)
13077 (push (list :item (point-at-bol)
13078 (save-excursion (org-end-of-item) (point)))
13079 clist)
13080 (and (org-at-item-checkbox-p)
13081 (push (org-point-in-group p 0 :checkbox) clist)))
13083 ((org-at-table-p)
13084 (push (list :table (org-table-begin) (org-table-end)) clist)
13085 (if (memq 'org-formula faces)
13086 (push (list :table-special
13087 (previous-single-property-change p 'face)
13088 (next-single-property-change p 'face)) clist)))
13089 ((org-at-table-p 'any)
13090 (push (list :table-table) clist)))
13091 (goto-char p)
13093 ;; Now the small context
13094 (cond
13095 ((org-at-timestamp-p)
13096 (push (org-point-in-group p 0 :timestamp) clist))
13097 ((memq 'org-link faces)
13098 (push (list :link
13099 (previous-single-property-change p 'face)
13100 (next-single-property-change p 'face)) clist))
13101 ((memq 'org-special-keyword faces)
13102 (push (list :keyword
13103 (previous-single-property-change p 'face)
13104 (next-single-property-change p 'face)) clist))
13105 ((org-on-target-p)
13106 (push (org-point-in-group p 0 :target) clist)
13107 (goto-char (1- (match-beginning 0)))
13108 (if (looking-at org-radio-target-regexp)
13109 (push (org-point-in-group p 0 :radio-target) clist))
13110 (goto-char p))
13111 ((setq o (car (delq nil
13112 (mapcar
13113 (lambda (x)
13114 (if (memq x org-latex-fragment-image-overlays) x))
13115 (org-overlays-at (point))))))
13116 (push (list :latex-fragment
13117 (org-overlay-start o) (org-overlay-end o)) clist)
13118 (push (list :latex-preview
13119 (org-overlay-start o) (org-overlay-end o)) clist))
13120 ((org-inside-LaTeX-fragment-p)
13121 ;; FIXME: positions wrong.
13122 (push (list :latex-fragment (point) (point)) clist)))
13124 (setq clist (nreverse (delq nil clist)))
13125 clist))
13127 ;; FIXME: Compare with at-regexp-p Do we need both?
13128 (defun org-in-regexp (re &optional nlines visually)
13129 "Check if point is inside a match of regexp.
13130 Normally only the current line is checked, but you can include NLINES extra
13131 lines both before and after point into the search.
13132 If VISUALLY is set, require that the cursor is not after the match but
13133 really on, so that the block visually is on the match."
13134 (catch 'exit
13135 (let ((pos (point))
13136 (eol (point-at-eol (+ 1 (or nlines 0))))
13137 (inc (if visually 1 0)))
13138 (save-excursion
13139 (beginning-of-line (- 1 (or nlines 0)))
13140 (while (re-search-forward re eol t)
13141 (if (and (<= (match-beginning 0) pos)
13142 (>= (+ inc (match-end 0)) pos))
13143 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13145 (defun org-at-regexp-p (regexp)
13146 "Is point inside a match of REGEXP in the current line?"
13147 (catch 'exit
13148 (save-excursion
13149 (let ((pos (point)) (end (point-at-eol)))
13150 (beginning-of-line 1)
13151 (while (re-search-forward regexp end t)
13152 (if (and (<= (match-beginning 0) pos)
13153 (>= (match-end 0) pos))
13154 (throw 'exit t)))
13155 nil))))
13157 (defun org-occur-in-agenda-files (regexp &optional nlines)
13158 "Call `multi-occur' with buffers for all agenda files."
13159 (interactive "sOrg-files matching: \np")
13160 (let* ((files (org-agenda-files))
13161 (tnames (mapcar 'file-truename files))
13162 (extra org-agenda-text-search-extra-files)
13164 (when (eq (car extra) 'agenda-archives)
13165 (setq extra (cdr extra))
13166 (setq files (org-add-archive-files files)))
13167 (while (setq f (pop extra))
13168 (unless (member (file-truename f) tnames)
13169 (add-to-list 'files f 'append)
13170 (add-to-list 'tnames (file-truename f) 'append)))
13171 (multi-occur
13172 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13173 regexp)))
13175 (if (boundp 'occur-mode-find-occurrence-hook)
13176 ;; Emacs 23
13177 (add-hook 'occur-mode-find-occurrence-hook
13178 (lambda ()
13179 (when (org-mode-p)
13180 (org-reveal))))
13181 ;; Emacs 22
13182 (defadvice occur-mode-goto-occurrence
13183 (after org-occur-reveal activate)
13184 (and (org-mode-p) (org-reveal)))
13185 (defadvice occur-mode-goto-occurrence-other-window
13186 (after org-occur-reveal activate)
13187 (and (org-mode-p) (org-reveal)))
13188 (defadvice occur-mode-display-occurrence
13189 (after org-occur-reveal activate)
13190 (when (org-mode-p)
13191 (let ((pos (occur-mode-find-occurrence)))
13192 (with-current-buffer (marker-buffer pos)
13193 (save-excursion
13194 (goto-char pos)
13195 (org-reveal)))))))
13197 (defun org-uniquify (list)
13198 "Remove duplicate elements from LIST."
13199 (let (res)
13200 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13201 res))
13203 (defun org-delete-all (elts list)
13204 "Remove all elements in ELTS from LIST."
13205 (while elts
13206 (setq list (delete (pop elts) list)))
13207 list)
13209 (defun org-back-over-empty-lines ()
13210 "Move backwards over witespace, to the beginning of the first empty line.
13211 Returns the number of empty lines passed."
13212 (let ((pos (point)))
13213 (skip-chars-backward " \t\n\r")
13214 (beginning-of-line 2)
13215 (goto-char (min (point) pos))
13216 (count-lines (point) pos)))
13218 (defun org-skip-whitespace ()
13219 (skip-chars-forward " \t\n\r"))
13221 (defun org-point-in-group (point group &optional context)
13222 "Check if POINT is in match-group GROUP.
13223 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13224 match. If the match group does ot exist or point is not inside it,
13225 return nil."
13226 (and (match-beginning group)
13227 (>= point (match-beginning group))
13228 (<= point (match-end group))
13229 (if context
13230 (list context (match-beginning group) (match-end group))
13231 t)))
13233 (defun org-switch-to-buffer-other-window (&rest args)
13234 "Switch to buffer in a second window on the current frame.
13235 In particular, do not allow pop-up frames."
13236 (let (pop-up-frames special-display-buffer-names special-display-regexps
13237 special-display-function)
13238 (apply 'switch-to-buffer-other-window args)))
13240 (defun org-combine-plists (&rest plists)
13241 "Create a single property list from all plists in PLISTS.
13242 The process starts by copying the first list, and then setting properties
13243 from the other lists. Settings in the last list are the most significant
13244 ones and overrule settings in the other lists."
13245 (let ((rtn (copy-sequence (pop plists)))
13246 p v ls)
13247 (while plists
13248 (setq ls (pop plists))
13249 (while ls
13250 (setq p (pop ls) v (pop ls))
13251 (setq rtn (plist-put rtn p v))))
13252 rtn))
13254 (defun org-move-line-down (arg)
13255 "Move the current line down. With prefix argument, move it past ARG lines."
13256 (interactive "p")
13257 (let ((col (current-column))
13258 beg end pos)
13259 (beginning-of-line 1) (setq beg (point))
13260 (beginning-of-line 2) (setq end (point))
13261 (beginning-of-line (+ 1 arg))
13262 (setq pos (move-marker (make-marker) (point)))
13263 (insert (delete-and-extract-region beg end))
13264 (goto-char pos)
13265 (org-move-to-column col)))
13267 (defun org-move-line-up (arg)
13268 "Move the current line up. With prefix argument, move it past ARG lines."
13269 (interactive "p")
13270 (let ((col (current-column))
13271 beg end pos)
13272 (beginning-of-line 1) (setq beg (point))
13273 (beginning-of-line 2) (setq end (point))
13274 (beginning-of-line (- arg))
13275 (setq pos (move-marker (make-marker) (point)))
13276 (insert (delete-and-extract-region beg end))
13277 (goto-char pos)
13278 (org-move-to-column col)))
13280 (defun org-replace-escapes (string table)
13281 "Replace %-escapes in STRING with values in TABLE.
13282 TABLE is an association list with keys like \"%a\" and string values.
13283 The sequences in STRING may contain normal field width and padding information,
13284 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13285 so values can contain further %-escapes if they are define later in TABLE."
13286 (let ((case-fold-search nil)
13287 e re rpl)
13288 (while (setq e (pop table))
13289 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13290 (while (string-match re string)
13291 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13292 (cdr e)))
13293 (setq string (replace-match rpl t t string))))
13294 string))
13297 (defun org-sublist (list start end)
13298 "Return a section of LIST, from START to END.
13299 Counting starts at 1."
13300 (let (rtn (c start))
13301 (setq list (nthcdr (1- start) list))
13302 (while (and list (<= c end))
13303 (push (pop list) rtn)
13304 (setq c (1+ c)))
13305 (nreverse rtn)))
13307 (defun org-find-base-buffer-visiting (file)
13308 "Like `find-buffer-visiting' but alway return the base buffer and
13309 not an indirect buffer."
13310 (let ((buf (find-buffer-visiting file)))
13311 (if buf
13312 (or (buffer-base-buffer buf) buf)
13313 nil)))
13315 (defun org-image-file-name-regexp ()
13316 "Return regexp matching the file names of images."
13317 (if (fboundp 'image-file-name-regexp)
13318 (image-file-name-regexp)
13319 (let ((image-file-name-extensions
13320 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13321 "xbm" "xpm" "pbm" "pgm" "ppm")))
13322 (concat "\\."
13323 (regexp-opt (nconc (mapcar 'upcase
13324 image-file-name-extensions)
13325 image-file-name-extensions)
13327 "\\'"))))
13329 (defun org-file-image-p (file)
13330 "Return non-nil if FILE is an image."
13331 (save-match-data
13332 (string-match (org-image-file-name-regexp) file)))
13334 ;;; Paragraph filling stuff.
13335 ;; We want this to be just right, so use the full arsenal.
13337 (defun org-indent-line-function ()
13338 "Indent line like previous, but further if previous was headline or item."
13339 (interactive)
13340 (let* ((pos (point))
13341 (itemp (org-at-item-p))
13342 column bpos bcol tpos tcol bullet btype bullet-type)
13343 ;; Find the previous relevant line
13344 (beginning-of-line 1)
13345 (cond
13346 ((looking-at "#") (setq column 0))
13347 ((looking-at "\\*+ ") (setq column 0))
13349 (beginning-of-line 0)
13350 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13351 (beginning-of-line 0))
13352 (cond
13353 ((looking-at "\\*+[ \t]+")
13354 (goto-char (match-end 0))
13355 (setq column (current-column)))
13356 ((org-in-item-p)
13357 (org-beginning-of-item)
13358 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13359 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13360 (setq bpos (match-beginning 1) tpos (match-end 0)
13361 bcol (progn (goto-char bpos) (current-column))
13362 tcol (progn (goto-char tpos) (current-column))
13363 bullet (match-string 1)
13364 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13365 (if (not itemp)
13366 (setq column tcol)
13367 (goto-char pos)
13368 (beginning-of-line 1)
13369 (if (looking-at "\\S-")
13370 (progn
13371 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13372 (setq bullet (match-string 1)
13373 btype (if (string-match "[0-9]" bullet) "n" bullet))
13374 (setq column (if (equal btype bullet-type) bcol tcol)))
13375 (setq column (org-get-indentation)))))
13376 (t (setq column (org-get-indentation))))))
13377 (goto-char pos)
13378 (if (<= (current-column) (current-indentation))
13379 (org-indent-line-to column)
13380 (save-excursion (org-indent-line-to column)))
13381 (setq column (current-column))
13382 (beginning-of-line 1)
13383 (if (looking-at
13384 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13385 (replace-match (concat "\\1" (format org-property-format
13386 (match-string 2) (match-string 3)))
13387 t nil))
13388 (org-move-to-column column)))
13390 (defun org-set-autofill-regexps ()
13391 (interactive)
13392 ;; In the paragraph separator we include headlines, because filling
13393 ;; text in a line directly attached to a headline would otherwise
13394 ;; fill the headline as well.
13395 (org-set-local 'comment-start-skip "^#+[ \t]*")
13396 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13397 ;; The paragraph starter includes hand-formatted lists.
13398 (org-set-local 'paragraph-start
13399 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13400 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13401 ;; But only if the user has not turned off tables or fixed-width regions
13402 (org-set-local
13403 'auto-fill-inhibit-regexp
13404 (concat "\\*+ \\|#\\+"
13405 "\\|[ \t]*" org-keyword-time-regexp
13406 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13407 (concat
13408 "\\|[ \t]*["
13409 (if org-enable-table-editor "|" "")
13410 (if org-enable-fixed-width-editor ":" "")
13411 "]"))))
13412 ;; We use our own fill-paragraph function, to make sure that tables
13413 ;; and fixed-width regions are not wrapped. That function will pass
13414 ;; through to `fill-paragraph' when appropriate.
13415 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13416 ; Adaptive filling: To get full control, first make sure that
13417 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13418 (org-set-local 'adaptive-fill-regexp "\000")
13419 (org-set-local 'adaptive-fill-function
13420 'org-adaptive-fill-function)
13421 (org-set-local
13422 'align-mode-rules-list
13423 '((org-in-buffer-settings
13424 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13425 (modes . '(org-mode))))))
13427 (defun org-fill-paragraph (&optional justify)
13428 "Re-align a table, pass through to fill-paragraph if no table."
13429 (let ((table-p (org-at-table-p))
13430 (table.el-p (org-at-table.el-p)))
13431 (cond ((and (equal (char-after (point-at-bol)) ?*)
13432 (save-excursion (goto-char (point-at-bol))
13433 (looking-at outline-regexp)))
13434 t) ; skip headlines
13435 (table.el-p t) ; skip table.el tables
13436 (table-p (org-table-align) t) ; align org-mode tables
13437 (t nil)))) ; call paragraph-fill
13439 ;; For reference, this is the default value of adaptive-fill-regexp
13440 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13442 (defun org-adaptive-fill-function ()
13443 "Return a fill prefix for org-mode files.
13444 In particular, this makes sure hanging paragraphs for hand-formatted lists
13445 work correctly."
13446 (cond ((looking-at "#[ \t]+")
13447 (match-string 0))
13448 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13449 (save-excursion
13450 (goto-char (match-end 0))
13451 (make-string (current-column) ?\ )))
13452 (t nil)))
13454 ;;; Other stuff.
13456 (defun org-toggle-fixed-width-section (arg)
13457 "Toggle the fixed-width export.
13458 If there is no active region, the QUOTE keyword at the current headline is
13459 inserted or removed. When present, it causes the text between this headline
13460 and the next to be exported as fixed-width text, and unmodified.
13461 If there is an active region, this command adds or removes a colon as the
13462 first character of this line. If the first character of a line is a colon,
13463 this line is also exported in fixed-width font."
13464 (interactive "P")
13465 (let* ((cc 0)
13466 (regionp (org-region-active-p))
13467 (beg (if regionp (region-beginning) (point)))
13468 (end (if regionp (region-end)))
13469 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13470 (case-fold-search nil)
13471 (re "[ \t]*\\(:\\)")
13472 off)
13473 (if regionp
13474 (save-excursion
13475 (goto-char beg)
13476 (setq cc (current-column))
13477 (beginning-of-line 1)
13478 (setq off (looking-at re))
13479 (while (> nlines 0)
13480 (setq nlines (1- nlines))
13481 (beginning-of-line 1)
13482 (cond
13483 (arg
13484 (org-move-to-column cc t)
13485 (insert ":\n")
13486 (forward-line -1))
13487 ((and off (looking-at re))
13488 (replace-match "" t t nil 1))
13489 ((not off) (org-move-to-column cc t) (insert ":")))
13490 (forward-line 1)))
13491 (save-excursion
13492 (org-back-to-heading)
13493 (if (looking-at (concat outline-regexp
13494 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13495 (replace-match "" t t nil 1)
13496 (if (looking-at outline-regexp)
13497 (progn
13498 (goto-char (match-end 0))
13499 (insert org-quote-string " "))))))))
13501 ;;;; Functions extending outline functionality
13503 (defun org-beginning-of-line (&optional arg)
13504 "Go to the beginning of the current line. If that is invisible, continue
13505 to a visible line beginning. This makes the function of C-a more intuitive.
13506 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13507 first attempt, and only move to after the tags when the cursor is already
13508 beyond the end of the headline."
13509 (interactive "P")
13510 (let ((pos (point)))
13511 (beginning-of-line 1)
13512 (if (bobp)
13514 (backward-char 1)
13515 (if (org-invisible-p)
13516 (while (and (not (bobp)) (org-invisible-p))
13517 (backward-char 1)
13518 (beginning-of-line 1))
13519 (forward-char 1)))
13520 (when org-special-ctrl-a/e
13521 (cond
13522 ((and (looking-at org-todo-line-regexp)
13523 (= (char-after (match-end 1)) ?\ ))
13524 (goto-char
13525 (if (eq org-special-ctrl-a/e t)
13526 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13527 ((= pos (point)) (match-beginning 3))
13528 (t (point)))
13529 (cond ((> pos (point)) (point))
13530 ((not (eq last-command this-command)) (point))
13531 (t (match-beginning 3))))))
13532 ((org-at-item-p)
13533 (goto-char
13534 (if (eq org-special-ctrl-a/e t)
13535 (cond ((> pos (match-end 4)) (match-end 4))
13536 ((= pos (point)) (match-end 4))
13537 (t (point)))
13538 (cond ((> pos (point)) (point))
13539 ((not (eq last-command this-command)) (point))
13540 (t (match-end 4))))))))))
13542 (defun org-end-of-line (&optional arg)
13543 "Go to the end of the line.
13544 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13545 first attempt, and only move to after the tags when the cursor is already
13546 beyond the end of the headline."
13547 (interactive "P")
13548 (if (or (not org-special-ctrl-a/e)
13549 (not (org-on-heading-p)))
13550 (end-of-line arg)
13551 (let ((pos (point)))
13552 (beginning-of-line 1)
13553 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13554 (if (eq org-special-ctrl-a/e t)
13555 (if (or (< pos (match-beginning 1))
13556 (= pos (match-end 0)))
13557 (goto-char (match-beginning 1))
13558 (goto-char (match-end 0)))
13559 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13560 (goto-char (match-end 0))
13561 (goto-char (match-beginning 1))))
13562 (end-of-line arg)))))
13564 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13565 (define-key org-mode-map "\C-e" 'org-end-of-line)
13567 (defun org-kill-line (&optional arg)
13568 "Kill line, to tags or end of line."
13569 (interactive "P")
13570 (cond
13571 ((or (not org-special-ctrl-k)
13572 (bolp)
13573 (not (org-on-heading-p)))
13574 (call-interactively 'kill-line))
13575 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13576 (kill-region (point) (match-beginning 1))
13577 (org-set-tags nil t))
13578 (t (kill-region (point) (point-at-eol)))))
13580 (define-key org-mode-map "\C-k" 'org-kill-line)
13582 (defun org-invisible-p ()
13583 "Check if point is at a character currently not visible."
13584 ;; Early versions of noutline don't have `outline-invisible-p'.
13585 (if (fboundp 'outline-invisible-p)
13586 (outline-invisible-p)
13587 (get-char-property (point) 'invisible)))
13589 (defun org-invisible-p2 ()
13590 "Check if point is at a character currently not visible."
13591 (save-excursion
13592 (if (and (eolp) (not (bobp))) (backward-char 1))
13593 ;; Early versions of noutline don't have `outline-invisible-p'.
13594 (if (fboundp 'outline-invisible-p)
13595 (outline-invisible-p)
13596 (get-char-property (point) 'invisible))))
13598 (defalias 'org-back-to-heading 'outline-back-to-heading)
13599 (defalias 'org-on-heading-p 'outline-on-heading-p)
13600 (defalias 'org-at-heading-p 'outline-on-heading-p)
13601 (defun org-at-heading-or-item-p ()
13602 (or (org-on-heading-p) (org-at-item-p)))
13604 (defun org-on-target-p ()
13605 (or (org-in-regexp org-radio-target-regexp)
13606 (org-in-regexp org-target-regexp)))
13608 (defun org-up-heading-all (arg)
13609 "Move to the heading line of which the present line is a subheading.
13610 This function considers both visible and invisible heading lines.
13611 With argument, move up ARG levels."
13612 (if (fboundp 'outline-up-heading-all)
13613 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13614 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13616 (defun org-up-heading-safe ()
13617 "Move to the heading line of which the present line is a subheading.
13618 This version will not throw an error. It will return the level of the
13619 headline found, or nil if no higher level is found."
13620 (let ((pos (point)) start-level level
13621 (re (concat "^" outline-regexp)))
13622 (catch 'exit
13623 (outline-back-to-heading t)
13624 (setq start-level (funcall outline-level))
13625 (if (equal start-level 1) (throw 'exit nil))
13626 (while (re-search-backward re nil t)
13627 (setq level (funcall outline-level))
13628 (if (< level start-level) (throw 'exit level)))
13629 nil)))
13631 (defun org-first-sibling-p ()
13632 "Is this heading the first child of its parents?"
13633 (interactive)
13634 (let ((re (concat "^" outline-regexp))
13635 level l)
13636 (unless (org-at-heading-p t)
13637 (error "Not at a heading"))
13638 (setq level (funcall outline-level))
13639 (save-excursion
13640 (if (not (re-search-backward re nil t))
13642 (setq l (funcall outline-level))
13643 (< l level)))))
13645 (defun org-goto-sibling (&optional previous)
13646 "Goto the next sibling, even if it is invisible.
13647 When PREVIOUS is set, go to the previous sibling instead. Returns t
13648 when a sibling was found. When none is found, return nil and don't
13649 move point."
13650 (let ((fun (if previous 're-search-backward 're-search-forward))
13651 (pos (point))
13652 (re (concat "^" outline-regexp))
13653 level l)
13654 (when (condition-case nil (org-back-to-heading t) (error nil))
13655 (setq level (funcall outline-level))
13656 (catch 'exit
13657 (or previous (forward-char 1))
13658 (while (funcall fun re nil t)
13659 (setq l (funcall outline-level))
13660 (when (< l level) (goto-char pos) (throw 'exit nil))
13661 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13662 (goto-char pos)
13663 nil))))
13665 (defun org-show-siblings ()
13666 "Show all siblings of the current headline."
13667 (save-excursion
13668 (while (org-goto-sibling) (org-flag-heading nil)))
13669 (save-excursion
13670 (while (org-goto-sibling 'previous)
13671 (org-flag-heading nil))))
13673 (defun org-show-hidden-entry ()
13674 "Show an entry where even the heading is hidden."
13675 (save-excursion
13676 (org-show-entry)))
13678 (defun org-flag-heading (flag &optional entry)
13679 "Flag the current heading. FLAG non-nil means make invisible.
13680 When ENTRY is non-nil, show the entire entry."
13681 (save-excursion
13682 (org-back-to-heading t)
13683 ;; Check if we should show the entire entry
13684 (if entry
13685 (progn
13686 (org-show-entry)
13687 (save-excursion
13688 (and (outline-next-heading)
13689 (org-flag-heading nil))))
13690 (outline-flag-region (max (point-min) (1- (point)))
13691 (save-excursion (outline-end-of-heading) (point))
13692 flag))))
13694 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13695 ;; This is an exact copy of the original function, but it uses
13696 ;; `org-back-to-heading', to make it work also in invisible
13697 ;; trees. And is uses an invisible-OK argument.
13698 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13699 (org-back-to-heading invisible-OK)
13700 (let ((first t)
13701 (level (funcall outline-level)))
13702 (while (and (not (eobp))
13703 (or first (> (funcall outline-level) level)))
13704 (setq first nil)
13705 (outline-next-heading))
13706 (unless to-heading
13707 (if (memq (preceding-char) '(?\n ?\^M))
13708 (progn
13709 ;; Go to end of line before heading
13710 (forward-char -1)
13711 (if (memq (preceding-char) '(?\n ?\^M))
13712 ;; leave blank line before heading
13713 (forward-char -1))))))
13714 (point))
13716 (defun org-show-subtree ()
13717 "Show everything after this heading at deeper levels."
13718 (outline-flag-region
13719 (point)
13720 (save-excursion
13721 (outline-end-of-subtree) (outline-next-heading) (point))
13722 nil))
13724 (defun org-show-entry ()
13725 "Show the body directly following this heading.
13726 Show the heading too, if it is currently invisible."
13727 (interactive)
13728 (save-excursion
13729 (condition-case nil
13730 (progn
13731 (org-back-to-heading t)
13732 (outline-flag-region
13733 (max (point-min) (1- (point)))
13734 (save-excursion
13735 (re-search-forward
13736 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13737 (or (match-beginning 1) (point-max)))
13738 nil))
13739 (error nil))))
13741 (defun org-make-options-regexp (kwds)
13742 "Make a regular expression for keyword lines."
13743 (concat
13745 "#?[ \t]*\\+\\("
13746 (mapconcat 'regexp-quote kwds "\\|")
13747 "\\):[ \t]*"
13748 "\\(.+\\)"))
13750 ;; Make isearch reveal the necessary context
13751 (defun org-isearch-end ()
13752 "Reveal context after isearch exits."
13753 (when isearch-success ; only if search was successful
13754 (if (featurep 'xemacs)
13755 ;; Under XEmacs, the hook is run in the correct place,
13756 ;; we directly show the context.
13757 (org-show-context 'isearch)
13758 ;; In Emacs the hook runs *before* restoring the overlays.
13759 ;; So we have to use a one-time post-command-hook to do this.
13760 ;; (Emacs 22 has a special variable, see function `org-mode')
13761 (unless (and (boundp 'isearch-mode-end-hook-quit)
13762 isearch-mode-end-hook-quit)
13763 ;; Only when the isearch was not quitted.
13764 (org-add-hook 'post-command-hook 'org-isearch-post-command
13765 'append 'local)))))
13767 (defun org-isearch-post-command ()
13768 "Remove self from hook, and show context."
13769 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13770 (org-show-context 'isearch))
13773 ;;;; Integration with and fixes for other packages
13775 ;;; Imenu support
13777 (defvar org-imenu-markers nil
13778 "All markers currently used by Imenu.")
13779 (make-variable-buffer-local 'org-imenu-markers)
13781 (defun org-imenu-new-marker (&optional pos)
13782 "Return a new marker for use by Imenu, and remember the marker."
13783 (let ((m (make-marker)))
13784 (move-marker m (or pos (point)))
13785 (push m org-imenu-markers)
13788 (defun org-imenu-get-tree ()
13789 "Produce the index for Imenu."
13790 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13791 (setq org-imenu-markers nil)
13792 (let* ((n org-imenu-depth)
13793 (re (concat "^" outline-regexp))
13794 (subs (make-vector (1+ n) nil))
13795 (last-level 0)
13796 m tree level head)
13797 (save-excursion
13798 (save-restriction
13799 (widen)
13800 (goto-char (point-max))
13801 (while (re-search-backward re nil t)
13802 (setq level (org-reduced-level (funcall outline-level)))
13803 (when (<= level n)
13804 (looking-at org-complex-heading-regexp)
13805 (setq head (org-match-string-no-properties 4)
13806 m (org-imenu-new-marker))
13807 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13808 (if (>= level last-level)
13809 (push (cons head m) (aref subs level))
13810 (push (cons head (aref subs (1+ level))) (aref subs level))
13811 (loop for i from (1+ level) to n do (aset subs i nil)))
13812 (setq last-level level)))))
13813 (aref subs 1)))
13815 (eval-after-load "imenu"
13816 '(progn
13817 (add-hook 'imenu-after-jump-hook
13818 (lambda () (org-show-context 'org-goto)))))
13820 ;; Speedbar support
13822 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13823 "Overlay marking the agenda restriction line in speedbar.")
13824 (org-overlay-put org-speedbar-restriction-lock-overlay
13825 'face 'org-agenda-restriction-lock)
13826 (org-overlay-put org-speedbar-restriction-lock-overlay
13827 'help-echo "Agendas are currently limited to this item.")
13828 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13830 (defun org-speedbar-set-agenda-restriction ()
13831 "Restrict future agenda commands to the location at point in speedbar.
13832 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13833 (interactive)
13834 (require 'org-agenda)
13835 (let (p m tp np dir txt w)
13836 (cond
13837 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13838 'org-imenu t))
13839 (setq m (get-text-property p 'org-imenu-marker))
13840 (save-excursion
13841 (save-restriction
13842 (set-buffer (marker-buffer m))
13843 (goto-char m)
13844 (org-agenda-set-restriction-lock 'subtree))))
13845 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13846 'speedbar-function 'speedbar-find-file))
13847 (setq tp (previous-single-property-change
13848 (1+ p) 'speedbar-function)
13849 np (next-single-property-change
13850 tp 'speedbar-function)
13851 dir (speedbar-line-directory)
13852 txt (buffer-substring-no-properties (or tp (point-min))
13853 (or np (point-max))))
13854 (save-excursion
13855 (save-restriction
13856 (set-buffer (find-file-noselect
13857 (let ((default-directory dir))
13858 (expand-file-name txt))))
13859 (unless (org-mode-p)
13860 (error "Cannot restrict to non-Org-mode file"))
13861 (org-agenda-set-restriction-lock 'file))))
13862 (t (error "Don't know how to restrict Org-mode's agenda")))
13863 (org-move-overlay org-speedbar-restriction-lock-overlay
13864 (point-at-bol) (point-at-eol))
13865 (setq current-prefix-arg nil)
13866 (org-agenda-maybe-redo)))
13868 (eval-after-load "speedbar"
13869 '(progn
13870 (speedbar-add-supported-extension ".org")
13871 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13872 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13873 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13874 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13875 (add-hook 'speedbar-visiting-tag-hook
13876 (lambda () (org-show-context 'org-goto)))))
13879 ;;; Fixes and Hacks for problems with other packages
13881 ;; Make flyspell not check words in links, to not mess up our keymap
13882 (defun org-mode-flyspell-verify ()
13883 "Don't let flyspell put overlays at active buttons."
13884 (not (get-text-property (point) 'keymap)))
13886 ;; Make `bookmark-jump' show the jump location if it was hidden.
13887 (eval-after-load "bookmark"
13888 '(if (boundp 'bookmark-after-jump-hook)
13889 ;; We can use the hook
13890 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13891 ;; Hook not available, use advice
13892 (defadvice bookmark-jump (after org-make-visible activate)
13893 "Make the position visible."
13894 (org-bookmark-jump-unhide))))
13896 (defun org-bookmark-jump-unhide ()
13897 "Unhide the current position, to show the bookmark location."
13898 (and (org-mode-p)
13899 (or (org-invisible-p)
13900 (save-excursion (goto-char (max (point-min) (1- (point))))
13901 (org-invisible-p)))
13902 (org-show-context 'bookmark-jump)))
13904 ;; Make session.el ignore our circular variable
13905 (eval-after-load "session"
13906 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13908 ;;;; Experimental code
13910 (defun org-closed-in-range ()
13911 "Sparse tree of items closed in a certain time range.
13912 Still experimental, may disappear in the future."
13913 (interactive)
13914 ;; Get the time interval from the user.
13915 (let* ((time1 (time-to-seconds
13916 (org-read-date nil 'to-time nil "Starting date: ")))
13917 (time2 (time-to-seconds
13918 (org-read-date nil 'to-time nil "End date:")))
13919 ;; callback function
13920 (callback (lambda ()
13921 (let ((time
13922 (time-to-seconds
13923 (apply 'encode-time
13924 (org-parse-time-string
13925 (match-string 1))))))
13926 ;; check if time in interval
13927 (and (>= time time1) (<= time time2))))))
13928 ;; make tree, check each match with the callback
13929 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13932 ;;;; Finish up
13934 (provide 'org)
13936 (run-hooks 'org-load-hook)
13938 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13940 ;;; org.el ends here