Allow properties to influence startup visibilities.
[org-mode/org-tableheadings.git] / lisp / org.el
blob4ad737d32ee04285efc3e0b3f12a0b9c5ef29d53
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.02b
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.02b"
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 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
142 "Modules that should always be loaded together with org.el.
143 If a description starts with <C>, the file is not part of emacs
144 and loading it will require that you have downloaded and properly installed
145 the org-mode distribution.
147 You can also use this system to load external packages (i.e. neither Org
148 core modules, not modules from the CONTRIB directory). Just add symbols
149 to the end of the list. If the package is called org-xyz.e, then you need
150 to add the symbol `xyz', and the package must have a call to
152 (provide 'org-xyz)"
153 :group 'org
154 :set 'org-set-modules
155 :type
156 '(set :greedy t
157 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
158 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
159 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
160 (const :tag " info: Links to Info nodes" org-info)
161 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
162 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
163 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
164 (const :tag " mew Links to Mew folders/messages" org-mew)
165 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
166 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
167 (const :tag " vm: Links to VM folders/messages" org-vm)
168 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
169 (const :tag " mouse: Additional mouse support" org-mouse)
171 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
172 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
173 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
174 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
175 (const :tag "C eval: Include command output as text" org-eval)
176 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
177 (const :tag "C id: Global id's for identifying entries" org-id)
178 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
179 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
180 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
181 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
182 (const :tag "C registry: A registry for Org links" org-registry)
183 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
184 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
185 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
186 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
187 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
190 (defgroup org-startup nil
191 "Options concerning startup of Org-mode."
192 :tag "Org Startup"
193 :group 'org)
195 (defcustom org-startup-folded t
196 "Non-nil means, entering Org-mode will switch to OVERVIEW.
197 This can also be configured on a per-file basis by adding one of
198 the following lines anywhere in the buffer:
200 #+STARTUP: fold
201 #+STARTUP: nofold
202 #+STARTUP: content"
203 :group 'org-startup
204 :type '(choice
205 (const :tag "nofold: show all" nil)
206 (const :tag "fold: overview" t)
207 (const :tag "content: all headlines" content)))
209 (defcustom org-startup-truncated t
210 "Non-nil means, entering Org-mode will set `truncate-lines'.
211 This is useful since some lines containing links can be very long and
212 uninteresting. Also tables look terrible when wrapped."
213 :group 'org-startup
214 :type 'boolean)
216 (defcustom org-startup-align-all-tables nil
217 "Non-nil means, align all tables when visiting a file.
218 This is useful when the column width in tables is forced with <N> cookies
219 in table fields. Such tables will look correct only after the first re-align.
220 This can also be configured on a per-file basis by adding one of
221 the following lines anywhere in the buffer:
222 #+STARTUP: align
223 #+STARTUP: noalign"
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-insert-mode-line-in-empty-file nil
228 "Non-nil means insert the first line setting Org-mode in empty files.
229 When the function `org-mode' is called interactively in an empty file, this
230 normally means that the file name does not automatically trigger Org-mode.
231 To ensure that the file will always be in Org-mode in the future, a
232 line enforcing Org-mode will be inserted into the buffer, if this option
233 has been set."
234 :group 'org-startup
235 :type 'boolean)
237 (defcustom org-replace-disputed-keys nil
238 "Non-nil means use alternative key bindings for some keys.
239 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
240 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
241 If you want to use Org-mode together with one of these other modes,
242 or more generally if you would like to move some Org-mode commands to
243 other keys, set this variable and configure the keys with the variable
244 `org-disputed-keys'.
246 This option is only relevant at load-time of Org-mode, and must be set
247 *before* org.el is loaded. Changing it requires a restart of Emacs to
248 become effective."
249 :group 'org-startup
250 :type 'boolean)
252 (if (fboundp 'defvaralias)
253 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
255 (defcustom org-disputed-keys
256 '(([(shift up)] . [(meta p)])
257 ([(shift down)] . [(meta n)])
258 ([(shift left)] . [(meta -)])
259 ([(shift right)] . [(meta +)])
260 ([(control shift right)] . [(meta shift +)])
261 ([(control shift left)] . [(meta shift -)]))
262 "Keys for which Org-mode and other modes compete.
263 This is an alist, cars are the default keys, second element specifies
264 the alternative to use when `org-replace-disputed-keys' is t.
266 Keys can be specified in any syntax supported by `define-key'.
267 The value of this option takes effect only at Org-mode's startup,
268 therefore you'll have to restart Emacs to apply it after changing."
269 :group 'org-startup
270 :type 'alist)
272 (defun org-key (key)
273 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
274 Or return the original if not disputed."
275 (if org-replace-disputed-keys
276 (let* ((nkey (key-description key))
277 (x (org-find-if (lambda (x)
278 (equal (key-description (car x)) nkey))
279 org-disputed-keys)))
280 (if x (cdr x) key))
281 key))
283 (defun org-find-if (predicate seq)
284 (catch 'exit
285 (while seq
286 (if (funcall predicate (car seq))
287 (throw 'exit (car seq))
288 (pop seq)))))
290 (defun org-defkey (keymap key def)
291 "Define a key, possibly translated, as returned by `org-key'."
292 (define-key keymap (org-key key) def))
294 (defcustom org-ellipsis nil
295 "The ellipsis to use in the Org-mode outline.
296 When nil, just use the standard three dots. When a string, use that instead,
297 When a face, use the standart 3 dots, but with the specified face.
298 The change affects only Org-mode (which will then use its own display table).
299 Changing this requires executing `M-x org-mode' in a buffer to become
300 effective."
301 :group 'org-startup
302 :type '(choice (const :tag "Default" nil)
303 (face :tag "Face" :value org-warning)
304 (string :tag "String" :value "...#")))
306 (defvar org-display-table nil
307 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
309 (defgroup org-keywords nil
310 "Keywords in Org-mode."
311 :tag "Org Keywords"
312 :group 'org)
314 (defcustom org-deadline-string "DEADLINE:"
315 "String to mark deadline entries.
316 A deadline is this string, followed by a time stamp. Should be a word,
317 terminated by a colon. You can insert a schedule keyword and
318 a timestamp with \\[org-deadline].
319 Changes become only effective after restarting Emacs."
320 :group 'org-keywords
321 :type 'string)
323 (defcustom org-scheduled-string "SCHEDULED:"
324 "String to mark scheduled TODO entries.
325 A schedule is this string, followed by a time stamp. Should be a word,
326 terminated by a colon. You can insert a schedule keyword and
327 a timestamp with \\[org-schedule].
328 Changes become only effective after restarting Emacs."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-closed-string "CLOSED:"
333 "String used as the prefix for timestamps logging closing a TODO entry."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-clock-string "CLOCK:"
338 "String used as prefix for timestamps clocking work hours on an item."
339 :group 'org-keywords
340 :type 'string)
342 (defcustom org-comment-string "COMMENT"
343 "Entries starting with this keyword will never be exported.
344 An entry can be toggled between COMMENT and normal with
345 \\[org-toggle-comment].
346 Changes become only effective after restarting Emacs."
347 :group 'org-keywords
348 :type 'string)
350 (defcustom org-quote-string "QUOTE"
351 "Entries starting with this keyword will be exported in fixed-width font.
352 Quoting applies only to the text in the entry following the headline, and does
353 not extend beyond the next headline, even if that is lower level.
354 An entry can be toggled between QUOTE and normal with
355 \\[org-toggle-fixed-width-section]."
356 :group 'org-keywords
357 :type 'string)
359 (defconst org-repeat-re
360 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
361 "Regular expression for specifying repeated events.
362 After a match, group 1 contains the repeat expression.")
364 (defgroup org-structure nil
365 "Options concerning the general structure of Org-mode files."
366 :tag "Org Structure"
367 :group 'org)
369 (defgroup org-reveal-location nil
370 "Options about how to make context of a location visible."
371 :tag "Org Reveal Location"
372 :group 'org-structure)
374 (defconst org-context-choice
375 '(choice
376 (const :tag "Always" t)
377 (const :tag "Never" nil)
378 (repeat :greedy t :tag "Individual contexts"
379 (cons
380 (choice :tag "Context"
381 (const agenda)
382 (const org-goto)
383 (const occur-tree)
384 (const tags-tree)
385 (const link-search)
386 (const mark-goto)
387 (const bookmark-jump)
388 (const isearch)
389 (const default))
390 (boolean))))
391 "Contexts for the reveal options.")
393 (defcustom org-show-hierarchy-above '((default . t))
394 "Non-nil means, show full hierarchy when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the hierarchy of headings
397 above the exposed location is shown.
398 Turning this off for example for sparse trees makes them very compact.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. Valid contexts are
401 agenda when exposing an entry from the agenda
402 org-goto when using the command `org-goto' on key C-c C-j
403 occur-tree when using the command `org-occur' on key C-c /
404 tags-tree when constructing a sparse tree based on tags matches
405 link-search when exposing search matches associated with a link
406 mark-goto when exposing the jump goal of a mark
407 bookmark-jump when exposing a bookmark location
408 isearch when exiting from an incremental search
409 default default for all contexts not set explicitly"
410 :group 'org-reveal-location
411 :type org-context-choice)
413 (defcustom org-show-following-heading '((default . nil))
414 "Non-nil means, show following heading when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the heading following the
417 match is shown.
418 Turning this off for example for sparse trees makes them very compact,
419 but makes it harder to edit the location of the match. In such a case,
420 use the command \\[org-reveal] to show more context.
421 Instead of t, this can also be an alist specifying this option for different
422 contexts. See `org-show-hierarchy-above' for valid contexts."
423 :group 'org-reveal-location
424 :type org-context-choice)
426 (defcustom org-show-siblings '((default . nil) (isearch t))
427 "Non-nil means, show all sibling heading when revealing a location.
428 Org-mode often shows locations in an org-mode file which might have
429 been invisible before. When this is set, the sibling of the current entry
430 heading are all made visible. If `org-show-hierarchy-above' is t,
431 the same happens on each level of the hierarchy above the current entry.
433 By default this is on for the isearch context, off for all other contexts.
434 Turning this off for example for sparse trees makes them very compact,
435 but makes it harder to edit the location of the match. In such a case,
436 use the command \\[org-reveal] to show more context.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type org-context-choice)
442 (defcustom org-show-entry-below '((default . nil))
443 "Non-nil means, show the entry below a headline when revealing a location.
444 Org-mode often shows locations in an org-mode file which might have
445 been invisible before. When this is set, the text below the headline that is
446 exposed is also shown.
448 By default this is off for all contexts.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. See `org-show-hierarchy-above' for valid contexts."
451 :group 'org-reveal-location
452 :type org-context-choice)
454 (defcustom org-indirect-buffer-display 'other-window
455 "How should indirect tree buffers be displayed?
456 This applies to indirect buffers created with the commands
457 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
458 Valid values are:
459 current-window Display in the current window
460 other-window Just display in another window.
461 dedicated-frame Create one new frame, and re-use it each time.
462 new-frame Make a new frame each time. Note that in this case
463 previously-made indirect buffers are kept, and you need to
464 kill these buffers yourself."
465 :group 'org-structure
466 :group 'org-agenda-windows
467 :type '(choice
468 (const :tag "In current window" current-window)
469 (const :tag "In current frame, other window" other-window)
470 (const :tag "Each time a new frame" new-frame)
471 (const :tag "One dedicated frame" dedicated-frame)))
473 (defgroup org-cycle nil
474 "Options concerning visibility cycling in Org-mode."
475 :tag "Org Cycle"
476 :group 'org-structure)
478 (defcustom org-drawers '("PROPERTIES" "CLOCK")
479 "Names of drawers. Drawers are not opened by cycling on the headline above.
480 Drawers only open with a TAB on the drawer line itself. A drawer looks like
481 this:
482 :DRAWERNAME:
483 .....
484 :END:
485 The drawer \"PROPERTIES\" is special for capturing properties through
486 the property API.
488 Drawers can be defined on the per-file basis with a line like:
490 #+DRAWERS: HIDDEN STATE PROPERTIES"
491 :group 'org-structure
492 :type '(repeat (string :tag "Drawer Name")))
494 (defcustom org-cycle-global-at-bob nil
495 "Cycle globally if cursor is at beginning of buffer and not at a headline.
496 This makes it possible to do global cycling without having to use S-TAB or
497 C-u TAB. For this special case to work, the first line of the buffer
498 must not be a headline - it may be empty ot some other text. When used in
499 this way, `org-cycle-hook' is disables temporarily, to make sure the
500 cursor stays at the beginning of the buffer.
501 When this option is nil, don't do anything special at the beginning
502 of the buffer."
503 :group 'org-cycle
504 :type 'boolean)
506 (defcustom org-cycle-emulate-tab t
507 "Where should `org-cycle' emulate TAB.
508 nil Never
509 white Only in completely white lines
510 whitestart Only at the beginning of lines, before the first non-white char
511 t Everywhere except in headlines
512 exc-hl-bol Everywhere except at the start of a headline
513 If TAB is used in a place where it does not emulate TAB, the current subtree
514 visibility is cycled."
515 :group 'org-cycle
516 :type '(choice (const :tag "Never" nil)
517 (const :tag "Only in completely white lines" white)
518 (const :tag "Before first char in a line" whitestart)
519 (const :tag "Everywhere except in headlines" t)
520 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
523 (defcustom org-cycle-separator-lines 2
524 "Number of empty lines needed to keep an empty line between collapsed trees.
525 If you leave an empty line between the end of a subtree and the following
526 headline, this empty line is hidden when the subtree is folded.
527 Org-mode will leave (exactly) one empty line visible if the number of
528 empty lines is equal or larger to the number given in this variable.
529 So the default 2 means, at least 2 empty lines after the end of a subtree
530 are needed to produce free space between a collapsed subtree and the
531 following headline.
533 Special case: when 0, never leave empty lines in collapsed view."
534 :group 'org-cycle
535 :type 'integer)
537 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
538 org-cycle-hide-drawers
539 org-cycle-show-empty-lines
540 org-optimize-window-after-visibility-change)
541 "Hook that is run after `org-cycle' has changed the buffer visibility.
542 The function(s) in this hook must accept a single argument which indicates
543 the new state that was set by the most recent `org-cycle' command. The
544 argument is a symbol. After a global state change, it can have the values
545 `overview', `content', or `all'. After a local state change, it can have
546 the values `folded', `children', or `subtree'."
547 :group 'org-cycle
548 :type 'hook)
550 (defgroup org-edit-structure nil
551 "Options concerning structure editing in Org-mode."
552 :tag "Org Edit Structure"
553 :group 'org-structure)
555 (defcustom org-odd-levels-only nil
556 "Non-nil means, skip even levels and only use odd levels for the outline.
557 This has the effect that two stars are being added/taken away in
558 promotion/demotion commands. It also influences how levels are
559 handled by the exporters.
560 Changing it requires restart of `font-lock-mode' to become effective
561 for fontification also in regions already fontified.
562 You may also set this on a per-file basis by adding one of the following
563 lines to the buffer:
565 #+STARTUP: odd
566 #+STARTUP: oddeven"
567 :group 'org-edit-structure
568 :group 'org-font-lock
569 :type 'boolean)
571 (defcustom org-adapt-indentation t
572 "Non-nil means, adapt indentation when promoting and demoting.
573 When this is set and the *entire* text in an entry is indented, the
574 indentation is increased by one space in a demotion command, and
575 decreased by one in a promotion command. If any line in the entry
576 body starts at column 0, indentation is not changed at all."
577 :group 'org-edit-structure
578 :type 'boolean)
580 (defcustom org-special-ctrl-a/e nil
581 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
582 When t, `C-a' will bring back the cursor to the beginning of the
583 headline text, i.e. after the stars and after a possible TODO keyword.
584 In an item, this will be the position after the bullet.
585 When the cursor is already at that position, another `C-a' will bring
586 it to the beginning of the line.
587 `C-e' will jump to the end of the headline, ignoring the presence of tags
588 in the headline. A second `C-e' will then jump to the true end of the
589 line, after any tags.
590 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
591 and only a directly following, identical keypress will bring the cursor
592 to the special positions."
593 :group 'org-edit-structure
594 :type '(choice
595 (const :tag "off" nil)
596 (const :tag "after bullet first" t)
597 (const :tag "border first" reversed)))
599 (if (fboundp 'defvaralias)
600 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
602 (defcustom org-special-ctrl-k nil
603 "Non-nil means `C-k' will behave specially in headlines.
604 When nil, `C-k' will call the default `kill-line' command.
605 When t, the following will happen while the cursor is in the headline:
607 - When the cursor is at the beginning of a headline, kill the entire
608 line and possible the folded subtree below the line.
609 - When in the middle of the headline text, kill the headline up to the tags.
610 - When after the headline text, kill the tags."
611 :group 'org-edit-structure
612 :type 'boolean)
614 (defcustom org-M-RET-may-split-line '((default . t))
615 "Non-nil means, M-RET will split the line at the cursor position.
616 When nil, it will go to the end of the line before making a
617 new line.
618 You may also set this option in a different way for different
619 contexts. Valid contexts are:
621 headline when creating a new headline
622 item when creating a new item
623 table in a table field
624 default the value to be used for all contexts not explicitly
625 customized"
626 :group 'org-structure
627 :group 'org-table
628 :type '(choice
629 (const :tag "Always" t)
630 (const :tag "Never" nil)
631 (repeat :greedy t :tag "Individual contexts"
632 (cons
633 (choice :tag "Context"
634 (const headline)
635 (const item)
636 (const table)
637 (const default))
638 (boolean)))))
641 (defcustom org-blank-before-new-entry '((heading . nil)
642 (plain-list-item . nil))
643 "Should `org-insert-heading' leave a blank line before new heading/item?
644 The value is an alist, with `heading' and `plain-list-item' as car,
645 and a boolean flag as cdr."
646 :group 'org-edit-structure
647 :type '(list
648 (cons (const heading) (boolean))
649 (cons (const plain-list-item) (boolean))))
651 (defcustom org-insert-heading-hook nil
652 "Hook being run after inserting a new heading."
653 :group 'org-edit-structure
654 :type 'hook)
656 (defcustom org-enable-fixed-width-editor t
657 "Non-nil means, lines starting with \":\" are treated as fixed-width.
658 This currently only means, they are never auto-wrapped.
659 When nil, such lines will be treated like ordinary lines.
660 See also the QUOTE keyword."
661 :group 'org-edit-structure
662 :type 'boolean)
664 (defcustom org-goto-auto-isearch t
665 "Non-nil means, typing characters in org-goto starts incremental search."
666 :group 'org-edit-structure
667 :type 'boolean)
669 (defgroup org-sparse-trees nil
670 "Options concerning sparse trees in Org-mode."
671 :tag "Org Sparse Trees"
672 :group 'org-structure)
674 (defcustom org-highlight-sparse-tree-matches t
675 "Non-nil means, highlight all matches that define a sparse tree.
676 The highlights will automatically disappear the next time the buffer is
677 changed by an edit command."
678 :group 'org-sparse-trees
679 :type 'boolean)
681 (defcustom org-remove-highlights-with-change t
682 "Non-nil means, any change to the buffer will remove temporary highlights.
683 Such highlights are created by `org-occur' and `org-clock-display'.
684 When nil, `C-c C-c needs to be used to get rid of the highlights.
685 The highlights created by `org-preview-latex-fragment' always need
686 `C-c C-c' to be removed."
687 :group 'org-sparse-trees
688 :group 'org-time
689 :type 'boolean)
692 (defcustom org-occur-hook '(org-first-headline-recenter)
693 "Hook that is run after `org-occur' has constructed a sparse tree.
694 This can be used to recenter the window to show as much of the structure
695 as possible."
696 :group 'org-sparse-trees
697 :type 'hook)
699 (defgroup org-plain-lists nil
700 "Options concerning plain lists in Org-mode."
701 :tag "Org Plain lists"
702 :group 'org-structure)
704 (defcustom org-cycle-include-plain-lists nil
705 "Non-nil means, include plain lists into visibility cycling.
706 This means that during cycling, plain list items will *temporarily* be
707 interpreted as outline headlines with a level given by 1000+i where i is the
708 indentation of the bullet. In all other operations, plain list items are
709 not seen as headlines. For example, you cannot assign a TODO keyword to
710 such an item."
711 :group 'org-plain-lists
712 :type 'boolean)
714 (defcustom org-plain-list-ordered-item-terminator t
715 "The character that makes a line with leading number an ordered list item.
716 Valid values are ?. and ?\). To get both terminators, use t. While
717 ?. may look nicer, it creates the danger that a line with leading
718 number may be incorrectly interpreted as an item. ?\) therefore is
719 the safe choice."
720 :group 'org-plain-lists
721 :type '(choice (const :tag "dot like in \"2.\"" ?.)
722 (const :tag "paren like in \"2)\"" ?\))
723 (const :tab "both" t)))
725 (defcustom org-empty-line-terminates-plain-lists nil
726 "Non-nil means, an empty line ends all plain list levels.
727 When nil, empty lines are part of the preceeding item."
728 :group 'org-plain-lists
729 :type 'boolean)
731 (defcustom org-auto-renumber-ordered-lists t
732 "Non-nil means, automatically renumber ordered plain lists.
733 Renumbering happens when the sequence have been changed with
734 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
735 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
736 :group 'org-plain-lists
737 :type 'boolean)
739 (defcustom org-provide-checkbox-statistics t
740 "Non-nil means, update checkbox statistics after insert and toggle.
741 When this is set, checkbox statistics is updated each time you either insert
742 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
743 with \\[org-ctrl-c-ctrl-c\\]."
744 :group 'org-plain-lists
745 :type 'boolean)
748 (defgroup org-imenu-and-speedbar nil
749 "Options concerning imenu and speedbar in Org-mode."
750 :tag "Org Imenu and Speedbar"
751 :group 'org-structure)
753 (defcustom org-imenu-depth 2
754 "The maximum level for Imenu access to Org-mode headlines.
755 This also applied for speedbar access."
756 :group 'org-imenu-and-speedbar
757 :type 'number)
759 (defgroup org-table nil
760 "Options concerning tables in Org-mode."
761 :tag "Org Table"
762 :group 'org)
764 (defcustom org-enable-table-editor 'optimized
765 "Non-nil means, lines starting with \"|\" are handled by the table editor.
766 When nil, such lines will be treated like ordinary lines.
768 When equal to the symbol `optimized', the table editor will be optimized to
769 do the following:
770 - Automatic overwrite mode in front of whitespace in table fields.
771 This makes the structure of the table stay in tact as long as the edited
772 field does not exceed the column width.
773 - Minimize the number of realigns. Normally, the table is aligned each time
774 TAB or RET are pressed to move to another field. With optimization this
775 happens only if changes to a field might have changed the column width.
776 Optimization requires replacing the functions `self-insert-command',
777 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
778 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
779 very good at guessing when a re-align will be necessary, but you can always
780 force one with \\[org-ctrl-c-ctrl-c].
782 If you would like to use the optimized version in Org-mode, but the
783 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
785 This variable can be used to turn on and off the table editor during a session,
786 but in order to toggle optimization, a restart is required.
788 See also the variable `org-table-auto-blank-field'."
789 :group 'org-table
790 :type '(choice
791 (const :tag "off" nil)
792 (const :tag "on" t)
793 (const :tag "on, optimized" optimized)))
795 (defcustom org-table-tab-recognizes-table.el t
796 "Non-nil means, TAB will automatically notice a table.el table.
797 When it sees such a table, it moves point into it and - if necessary -
798 calls `table-recognize-table'."
799 :group 'org-table-editing
800 :type 'boolean)
802 (defgroup org-link nil
803 "Options concerning links in Org-mode."
804 :tag "Org Link"
805 :group 'org)
807 (defvar org-link-abbrev-alist-local nil
808 "Buffer-local version of `org-link-abbrev-alist', which see.
809 The value of this is taken from the #+LINK lines.")
810 (make-variable-buffer-local 'org-link-abbrev-alist-local)
812 (defcustom org-link-abbrev-alist nil
813 "Alist of link abbreviations.
814 The car of each element is a string, to be replaced at the start of a link.
815 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
816 links in Org-mode buffers can have an optional tag after a double colon, e.g.
818 [[linkkey:tag][description]]
820 If REPLACE is a string, the tag will simply be appended to create the link.
821 If the string contains \"%s\", the tag will be inserted there.
823 REPLACE may also be a function that will be called with the tag as the
824 only argument to create the link, which should be returned as a string.
826 See the manual for examples."
827 :group 'org-link
828 :type 'alist)
830 (defcustom org-descriptive-links t
831 "Non-nil means, hide link part and only show description of bracket links.
832 Bracket links are like [[link][descritpion]]. This variable sets the initial
833 state in new org-mode buffers. The setting can then be toggled on a
834 per-buffer basis from the Org->Hyperlinks menu."
835 :group 'org-link
836 :type 'boolean)
838 (defcustom org-link-file-path-type 'adaptive
839 "How the path name in file links should be stored.
840 Valid values are:
842 relative Relative to the current directory, i.e. the directory of the file
843 into which the link is being inserted.
844 absolute Absolute path, if possible with ~ for home directory.
845 noabbrev Absolute path, no abbreviation of home directory.
846 adaptive Use relative path for files in the current directory and sub-
847 directories of it. For other files, use an absolute path."
848 :group 'org-link
849 :type '(choice
850 (const relative)
851 (const absolute)
852 (const noabbrev)
853 (const adaptive)))
855 (defcustom org-activate-links '(bracket angle plain radio tag date)
856 "Types of links that should be activated in Org-mode files.
857 This is a list of symbols, each leading to the activation of a certain link
858 type. In principle, it does not hurt to turn on most link types - there may
859 be a small gain when turning off unused link types. The types are:
861 bracket The recommended [[link][description]] or [[link]] links with hiding.
862 angular Links in angular brackes that may contain whitespace like
863 <bbdb:Carsten Dominik>.
864 plain Plain links in normal text, no whitespace, like http://google.com.
865 radio Text that is matched by a radio target, see manual for details.
866 tag Tag settings in a headline (link to tag search).
867 date Time stamps (link to calendar).
869 Changing this variable requires a restart of Emacs to become effective."
870 :group 'org-link
871 :type '(set (const :tag "Double bracket links (new style)" bracket)
872 (const :tag "Angular bracket links (old style)" angular)
873 (const :tag "Plain text links" plain)
874 (const :tag "Radio target matches" radio)
875 (const :tag "Tags" tag)
876 (const :tag "Timestamps" date)))
878 (defcustom org-make-link-description-function nil
879 "Function to use to generate link descriptions from links. If
880 nil the link location will be used. This function must take two
881 parameters; the first is the link and the second the description
882 org-insert-link has generated, and should return the description
883 to use."
884 :group 'org-link
885 :type 'function)
887 (defgroup org-link-store nil
888 "Options concerning storing links in Org-mode."
889 :tag "Org Store Link"
890 :group 'org-link)
892 (defcustom org-email-link-description-format "Email %c: %.30s"
893 "Format of the description part of a link to an email or usenet message.
894 The following %-excapes will be replaced by corresponding information:
896 %F full \"From\" field
897 %f name, taken from \"From\" field, address if no name
898 %T full \"To\" field
899 %t first name in \"To\" field, address if no name
900 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
901 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
902 %s subject
903 %m message-id.
905 You may use normal field width specification between the % and the letter.
906 This is for example useful to limit the length of the subject.
908 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
909 :group 'org-link-store
910 :type 'string)
912 (defcustom org-from-is-user-regexp
913 (let (r1 r2)
914 (when (and user-mail-address (not (string= user-mail-address "")))
915 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
916 (when (and user-full-name (not (string= user-full-name "")))
917 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
918 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
919 "Regexp mached against the \"From:\" header of an email or usenet message.
920 It should match if the message is from the user him/herself."
921 :group 'org-link-store
922 :type 'regexp)
924 (defcustom org-context-in-file-links t
925 "Non-nil means, file links from `org-store-link' contain context.
926 A search string will be added to the file name with :: as separator and
927 used to find the context when the link is activated by the command
928 `org-open-at-point'.
929 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
930 negates this setting for the duration of the command."
931 :group 'org-link-store
932 :type 'boolean)
934 (defcustom org-keep-stored-link-after-insertion nil
935 "Non-nil means, keep link in list for entire session.
937 The command `org-store-link' adds a link pointing to the current
938 location to an internal list. These links accumulate during a session.
939 The command `org-insert-link' can be used to insert links into any
940 Org-mode file (offering completion for all stored links). When this
941 option is nil, every link which has been inserted once using \\[org-insert-link]
942 will be removed from the list, to make completing the unused links
943 more efficient."
944 :group 'org-link-store
945 :type 'boolean)
947 (defgroup org-link-follow nil
948 "Options concerning following links in Org-mode."
949 :tag "Org Follow Link"
950 :group 'org-link)
952 (defcustom org-follow-link-hook nil
953 "Hook that is run after a link has been followed."
954 :group 'org-link-follow
955 :type 'hook)
957 (defcustom org-tab-follows-link nil
958 "Non-nil means, on links TAB will follow the link.
959 Needs to be set before org.el is loaded."
960 :group 'org-link-follow
961 :type 'boolean)
963 (defcustom org-return-follows-link nil
964 "Non-nil means, on links RET will follow the link.
965 Needs to be set before org.el is loaded."
966 :group 'org-link-follow
967 :type 'boolean)
969 (defcustom org-mouse-1-follows-link
970 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
971 "Non-nil means, mouse-1 on a link will follow the link.
972 A longer mouse click will still set point. Does not work on XEmacs.
973 Needs to be set before org.el is loaded."
974 :group 'org-link-follow
975 :type 'boolean)
977 (defcustom org-mark-ring-length 4
978 "Number of different positions to be recorded in the ring
979 Changing this requires a restart of Emacs to work correctly."
980 :group 'org-link-follow
981 :type 'interger)
983 (defcustom org-link-frame-setup
984 '((vm . vm-visit-folder-other-frame)
985 (gnus . gnus-other-frame)
986 (file . find-file-other-window))
987 "Setup the frame configuration for following links.
988 When following a link with Emacs, it may often be useful to display
989 this link in another window or frame. This variable can be used to
990 set this up for the different types of links.
991 For VM, use any of
992 `vm-visit-folder'
993 `vm-visit-folder-other-frame'
994 For Gnus, use any of
995 `gnus'
996 `gnus-other-frame'
997 For FILE, use any of
998 `find-file'
999 `find-file-other-window'
1000 `find-file-other-frame'
1001 For the calendar, use the variable `calendar-setup'.
1002 For BBDB, it is currently only possible to display the matches in
1003 another window."
1004 :group 'org-link-follow
1005 :type '(list
1006 (cons (const vm)
1007 (choice
1008 (const vm-visit-folder)
1009 (const vm-visit-folder-other-window)
1010 (const vm-visit-folder-other-frame)))
1011 (cons (const gnus)
1012 (choice
1013 (const gnus)
1014 (const gnus-other-frame)))
1015 (cons (const file)
1016 (choice
1017 (const find-file)
1018 (const find-file-other-window)
1019 (const find-file-other-frame)))))
1021 (defcustom org-display-internal-link-with-indirect-buffer nil
1022 "Non-nil means, use indirect buffer to display infile links.
1023 Activating internal links (from one location in a file to another location
1024 in the same file) normally just jumps to the location. When the link is
1025 activated with a C-u prefix (or with mouse-3), the link is displayed in
1026 another window. When this option is set, the other window actually displays
1027 an indirect buffer clone of the current buffer, to avoid any visibility
1028 changes to the current buffer."
1029 :group 'org-link-follow
1030 :type 'boolean)
1032 (defcustom org-open-non-existing-files nil
1033 "Non-nil means, `org-open-file' will open non-existing files.
1034 When nil, an error will be generated."
1035 :group 'org-link-follow
1036 :type 'boolean)
1038 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1039 "Function and arguments to call for following mailto links.
1040 This is a list with the first element being a lisp function, and the
1041 remaining elements being arguments to the function. In string arguments,
1042 %a will be replaced by the address, and %s will be replaced by the subject
1043 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1044 :group 'org-link-follow
1045 :type '(choice
1046 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1047 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1048 (const :tag "message-mail" (message-mail "%a" "%s"))
1049 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1051 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1052 "Non-nil means, ask for confirmation before executing shell links.
1053 Shell links can be dangerous: just think about a link
1055 [[shell:rm -rf ~/*][Google Search]]
1057 This link would show up in your Org-mode document as \"Google Search\",
1058 but really it would remove your entire home directory.
1059 Therefore we advise against setting this variable to nil.
1060 Just change it to `y-or-n-p' of you want to confirm with a
1061 single keystroke rather than having to type \"yes\"."
1062 :group 'org-link-follow
1063 :type '(choice
1064 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1065 (const :tag "with y-or-n (faster)" y-or-n-p)
1066 (const :tag "no confirmation (dangerous)" nil)))
1068 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1069 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1070 Elisp links can be dangerous: just think about a link
1072 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1074 This link would show up in your Org-mode document as \"Google Search\",
1075 but really it would remove your entire home directory.
1076 Therefore we advise against setting this variable to nil.
1077 Just change it to `y-or-n-p' of you want to confirm with a
1078 single keystroke rather than having to type \"yes\"."
1079 :group 'org-link-follow
1080 :type '(choice
1081 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1082 (const :tag "with y-or-n (faster)" y-or-n-p)
1083 (const :tag "no confirmation (dangerous)" nil)))
1085 (defconst org-file-apps-defaults-gnu
1086 '((remote . emacs)
1087 (t . mailcap))
1088 "Default file applications on a UNIX or GNU/Linux system.
1089 See `org-file-apps'.")
1091 (defconst org-file-apps-defaults-macosx
1092 '((remote . emacs)
1093 (t . "open %s")
1094 ("ps" . "gv %s")
1095 ("ps.gz" . "gv %s")
1096 ("eps" . "gv %s")
1097 ("eps.gz" . "gv %s")
1098 ("dvi" . "xdvi %s")
1099 ("fig" . "xfig %s"))
1100 "Default file applications on a MacOS X system.
1101 The system \"open\" is known as a default, but we use X11 applications
1102 for some files for which the OS does not have a good default.
1103 See `org-file-apps'.")
1105 (defconst org-file-apps-defaults-windowsnt
1106 (list
1107 '(remote . emacs)
1108 (cons t
1109 (list (if (featurep 'xemacs)
1110 'mswindows-shell-execute
1111 'w32-shell-execute)
1112 "open" 'file)))
1113 "Default file applications on a Windows NT system.
1114 The system \"open\" is used for most files.
1115 See `org-file-apps'.")
1117 (defcustom org-file-apps
1119 ("txt" . emacs)
1120 ("tex" . emacs)
1121 ("ltx" . emacs)
1122 ("org" . emacs)
1123 ("el" . emacs)
1124 ("bib" . emacs)
1126 "External applications for opening `file:path' items in a document.
1127 Org-mode uses system defaults for different file types, but
1128 you can use this variable to set the application for a given file
1129 extension. The entries in this list are cons cells where the car identifies
1130 files and the cdr the corresponding command. Possible values for the
1131 file identifier are
1132 \"ext\" A string identifying an extension
1133 `directory' Matches a directory
1134 `remote' Matches a remote file, accessible through tramp or efs.
1135 Remote files most likely should be visited through Emacs
1136 because external applications cannot handle such paths.
1137 t Default for all remaining files
1139 Possible values for the command are:
1140 `emacs' The file will be visited by the current Emacs process.
1141 `default' Use the default application for this file type.
1142 string A command to be executed by a shell; %s will be replaced
1143 by the path to the file.
1144 sexp A Lisp form which will be evaluated. The file path will
1145 be available in the Lisp variable `file'.
1146 For more examples, see the system specific constants
1147 `org-file-apps-defaults-macosx'
1148 `org-file-apps-defaults-windowsnt'
1149 `org-file-apps-defaults-gnu'."
1150 :group 'org-link-follow
1151 :type '(repeat
1152 (cons (choice :value ""
1153 (string :tag "Extension")
1154 (const :tag "Default for unrecognized files" t)
1155 (const :tag "Remote file" remote)
1156 (const :tag "Links to a directory" directory))
1157 (choice :value ""
1158 (const :tag "Visit with Emacs" emacs)
1159 (const :tag "Use system default" default)
1160 (string :tag "Command")
1161 (sexp :tag "Lisp form")))))
1163 (defgroup org-refile nil
1164 "Options concerning refiling entries in Org-mode."
1165 :tag "Org Remember"
1166 :group 'org)
1168 (defcustom org-directory "~/org"
1169 "Directory with org files.
1170 This directory will be used as default to prompt for org files.
1171 Used by the hooks for remember.el."
1172 :group 'org-refile
1173 :group 'org-remember
1174 :type 'directory)
1176 (defcustom org-default-notes-file "~/.notes"
1177 "Default target for storing notes.
1178 Used by the hooks for remember.el. This can be a string, or nil to mean
1179 the value of `remember-data-file'.
1180 You can set this on a per-template basis with the variable
1181 `org-remember-templates'."
1182 :group 'org-refile
1183 :group 'org-remember
1184 :type '(choice
1185 (const :tag "Default from remember-data-file" nil)
1186 file))
1188 (defcustom org-goto-interface 'outline
1189 "The default interface to be used for `org-goto'.
1190 Allowed vaues are:
1191 outline The interface shows an outline of the relevant file
1192 and the correct heading is found by moving through
1193 the outline or by searching with incremental search.
1194 outline-path-completion Headlines in the current buffer are offered via
1195 completion."
1196 :group 'org-refile
1197 :type '(choice
1198 (const :tag "Outline" outline)
1199 (const :tag "Outline-path-completion" outline-path-completion)))
1201 (defcustom org-reverse-note-order nil
1202 "Non-nil means, store new notes at the beginning of a file or entry.
1203 When nil, new notes will be filed to the end of a file or entry.
1204 This can also be a list with cons cells of regular expressions that
1205 are matched against file names, and values."
1206 :group 'org-remember
1207 :type '(choice
1208 (const :tag "Reverse always" t)
1209 (const :tag "Reverse never" nil)
1210 (repeat :tag "By file name regexp"
1211 (cons regexp boolean))))
1213 (defcustom org-refile-targets nil
1214 "Targets for refiling entries with \\[org-refile].
1215 This is list of cons cells. Each cell contains:
1216 - a specification of the files to be considered, either a list of files,
1217 or a symbol whose function or variable value will be used to retrieve
1218 a file name or a list of file names. Nil means, refile to a different
1219 heading in the current buffer.
1220 - A specification of how to find candidate refile targets. This may be
1221 any of
1222 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1223 This tag has to be present in all target headlines, inheritance will
1224 not be considered.
1225 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1226 todo keyword.
1227 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1228 headlines that are refiling targets.
1229 - a cons cell (:level . N). Any headline of level N is considered a target.
1230 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1231 :group 'org-remember
1232 :type '(repeat
1233 (cons
1234 (choice :value org-agenda-files
1235 (const :tag "All agenda files" org-agenda-files)
1236 (const :tag "Current buffer" nil)
1237 (function) (variable) (file))
1238 (choice :tag "Identify target headline by"
1239 (cons :tag "Specific tag" (const :tag) (string))
1240 (cons :tag "TODO keyword" (const :todo) (string))
1241 (cons :tag "Regular expression" (const :regexp) (regexp))
1242 (cons :tag "Level number" (const :level) (integer))
1243 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1245 (defcustom org-refile-use-outline-path nil
1246 "Non-nil means, provide refile targets as paths.
1247 So a level 3 headline will be available as level1/level2/level3.
1248 When the value is `file', also include the file name (without directory)
1249 into the path. When `full-file-path', include the full file path."
1250 :group 'org-remember
1251 :type '(choice
1252 (const :tag "Not" nil)
1253 (const :tag "Yes" t)
1254 (const :tag "Start with file name" file)
1255 (const :tag "Start with full file path" full-file-path)))
1257 (defgroup org-todo nil
1258 "Options concerning TODO items in Org-mode."
1259 :tag "Org TODO"
1260 :group 'org)
1262 (defgroup org-progress nil
1263 "Options concerning Progress logging in Org-mode."
1264 :tag "Org Progress"
1265 :group 'org-time)
1267 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1268 "List of TODO entry keyword sequences and their interpretation.
1269 \\<org-mode-map>This is a list of sequences.
1271 Each sequence starts with a symbol, either `sequence' or `type',
1272 indicating if the keywords should be interpreted as a sequence of
1273 action steps, or as different types of TODO items. The first
1274 keywords are states requiring action - these states will select a headline
1275 for inclusion into the global TODO list Org-mode produces. If one of
1276 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1277 signify that no further action is necessary. If \"|\" is not found,
1278 the last keyword is treated as the only DONE state of the sequence.
1280 The command \\[org-todo] cycles an entry through these states, and one
1281 additional state where no keyword is present. For details about this
1282 cycling, see the manual.
1284 TODO keywords and interpretation can also be set on a per-file basis with
1285 the special #+SEQ_TODO and #+TYP_TODO lines.
1287 Each keyword can optionally specify a character for fast state selection
1288 \(in combination with the variable `org-use-fast-todo-selection')
1289 and specifiers for state change logging, using the same syntax
1290 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1291 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1292 indicates to record a time stamp each time this state is selected.
1294 Each keyword may also specify if a timestamp or a note should be
1295 recorded when entering or leaving the state, by adding additional
1296 characters in the parenthesis after the keyword. This looks like this:
1297 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1298 record only the time of the state change. With X and Y being either
1299 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1300 Y when leaving the state if and only if the *target* state does not
1301 define X. You may omit any of the fast-selection key or X or /Y,
1302 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1304 For backward compatibility, this variable may also be just a list
1305 of keywords - in this case the interptetation (sequence or type) will be
1306 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1307 :group 'org-todo
1308 :group 'org-keywords
1309 :type '(choice
1310 (repeat :tag "Old syntax, just keywords"
1311 (string :tag "Keyword"))
1312 (repeat :tag "New syntax"
1313 (cons
1314 (choice
1315 :tag "Interpretation"
1316 (const :tag "Sequence (cycling hits every state)" sequence)
1317 (const :tag "Type (cycling directly to DONE)" type))
1318 (repeat
1319 (string :tag "Keyword"))))))
1321 (defvar org-todo-keywords-1 nil
1322 "All TODO and DONE keywords active in a buffer.")
1323 (make-variable-buffer-local 'org-todo-keywords-1)
1324 (defvar org-todo-keywords-for-agenda nil)
1325 (defvar org-done-keywords-for-agenda nil)
1326 (defvar org-agenda-contributing-files nil)
1327 (defvar org-not-done-keywords nil)
1328 (make-variable-buffer-local 'org-not-done-keywords)
1329 (defvar org-done-keywords nil)
1330 (make-variable-buffer-local 'org-done-keywords)
1331 (defvar org-todo-heads nil)
1332 (make-variable-buffer-local 'org-todo-heads)
1333 (defvar org-todo-sets nil)
1334 (make-variable-buffer-local 'org-todo-sets)
1335 (defvar org-todo-log-states nil)
1336 (make-variable-buffer-local 'org-todo-log-states)
1337 (defvar org-todo-kwd-alist nil)
1338 (make-variable-buffer-local 'org-todo-kwd-alist)
1339 (defvar org-todo-key-alist nil)
1340 (make-variable-buffer-local 'org-todo-key-alist)
1341 (defvar org-todo-key-trigger nil)
1342 (make-variable-buffer-local 'org-todo-key-trigger)
1344 (defcustom org-todo-interpretation 'sequence
1345 "Controls how TODO keywords are interpreted.
1346 This variable is in principle obsolete and is only used for
1347 backward compatibility, if the interpretation of todo keywords is
1348 not given already in `org-todo-keywords'. See that variable for
1349 more information."
1350 :group 'org-todo
1351 :group 'org-keywords
1352 :type '(choice (const sequence)
1353 (const type)))
1355 (defcustom org-use-fast-todo-selection 'prefix
1356 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1357 This variable describes if and under what circumstances the cycling
1358 mechanism for TODO keywords will be replaced by a single-key, direct
1359 selection scheme.
1361 When nil, fast selection is never used.
1363 When the symbol `prefix', it will be used when `org-todo' is called with
1364 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1365 in an agenda buffer.
1367 When t, fast selection is used by default. In this case, the prefix
1368 argument forces cycling instead.
1370 In all cases, the special interface is only used if access keys have actually
1371 been assigned by the user, i.e. if keywords in the configuration are followed
1372 by a letter in parenthesis, like TODO(t)."
1373 :group 'org-todo
1374 :type '(choice
1375 (const :tag "Never" nil)
1376 (const :tag "By default" t)
1377 (const :tag "Only with C-u C-c C-t" prefix)))
1379 (defcustom org-after-todo-state-change-hook nil
1380 "Hook which is run after the state of a TODO item was changed.
1381 The new state (a string with a TODO keyword, or nil) is available in the
1382 Lisp variable `state'."
1383 :group 'org-todo
1384 :type 'hook)
1386 (defcustom org-log-done nil
1387 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1388 When equal to the list (done), also prompt for a closing note.
1389 This can also be configured on a per-file basis by adding one of
1390 the following lines anywhere in the buffer:
1392 #+STARTUP: logdone
1393 #+STARTUP: lognotedone
1394 #+STARTUP: nologdone"
1395 :group 'org-todo
1396 :group 'org-progress
1397 :type '(choice
1398 (const :tag "No logging" nil)
1399 (const :tag "Record CLOSED timestamp" time)
1400 (const :tag "Record CLOSED timestamp with closing note." note)))
1402 ;; Normalize old uses of org-log-done.
1403 (cond
1404 ((eq org-log-done t) (setq org-log-done 'time))
1405 ((and (listp org-log-done) (memq 'done org-log-done))
1406 (setq org-log-done 'note)))
1408 (defcustom org-log-note-clock-out nil
1409 "Non-nil means, recored a note when clocking out of an item.
1410 This can also be configured on a per-file basis by adding one of
1411 the following lines anywhere in the buffer:
1413 #+STARTUP: lognoteclock-out
1414 #+STARTUP: nolognoteclock-out"
1415 :group 'org-todo
1416 :group 'org-progress
1417 :type 'boolean)
1419 (defcustom org-log-done-with-time t
1420 "Non-nil means, the CLOSED time stamp will contain date and time.
1421 When nil, only the date will be recorded."
1422 :group 'org-progress
1423 :type 'boolean)
1425 (defcustom org-log-note-headings
1426 '((done . "CLOSING NOTE %t")
1427 (state . "State %-12s %t")
1428 (note . "Note taken on %t")
1429 (clock-out . ""))
1430 "Headings for notes added to entries.
1431 The value is an alist, with the car being a symbol indicating the note
1432 context, and the cdr is the heading to be used. The heading may also be the
1433 empty string.
1434 %t in the heading will be replaced by a time stamp.
1435 %s will be replaced by the new TODO state, in double quotes.
1436 %u will be replaced by the user name.
1437 %U will be replaced by the full user name."
1438 :group 'org-todo
1439 :group 'org-progress
1440 :type '(list :greedy t
1441 (cons (const :tag "Heading when closing an item" done) string)
1442 (cons (const :tag
1443 "Heading when changing todo state (todo sequence only)"
1444 state) string)
1445 (cons (const :tag "Heading when just taking a note" note) string)
1446 (cons (const :tag "Heading when clocking out" clock-out) string)))
1448 (unless (assq 'note org-log-note-headings)
1449 (push '(note . "%t") org-log-note-headings))
1451 (defcustom org-log-states-order-reversed t
1452 "Non-nil means, the latest state change note will be directly after heading.
1453 When nil, the notes will be orderer according to time."
1454 :group 'org-todo
1455 :group 'org-progress
1456 :type 'boolean)
1458 (defcustom org-log-repeat 'time
1459 "Non-nil means, record moving through the DONE state when triggering repeat.
1460 An auto-repeating tasks is immediately switched back to TODO when marked
1461 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1462 the TODO keyword definition, or recording a closing note by setting
1463 `org-log-done', there will be no record of the task moving through DONE.
1464 This variable forces taking a note anyway. Possible values are:
1466 nil Don't force a record
1467 time Record a time stamp
1468 note Record a note
1470 This option can also be set with on a per-file-basis with
1472 #+STARTUP: logrepeat
1473 #+STARTUP: lognoterepeat
1474 #+STARTUP: nologrepeat
1476 You can have local logging settings for a subtree by setting the LOGGING
1477 property to one or more of these keywords."
1478 :group 'org-todo
1479 :group 'org-progress
1480 :type '(choice
1481 (const :tag "Don't force a record" nil)
1482 (const :tag "Force recording the DONE state" time)
1483 (const :tag "Force recording a note with the DONE state" note)))
1486 (defgroup org-priorities nil
1487 "Priorities in Org-mode."
1488 :tag "Org Priorities"
1489 :group 'org-todo)
1491 (defcustom org-highest-priority ?A
1492 "The highest priority of TODO items. A character like ?A, ?B etc.
1493 Must have a smaller ASCII number than `org-lowest-priority'."
1494 :group 'org-priorities
1495 :type 'character)
1497 (defcustom org-lowest-priority ?C
1498 "The lowest priority of TODO items. A character like ?A, ?B etc.
1499 Must have a larger ASCII number than `org-highest-priority'."
1500 :group 'org-priorities
1501 :type 'character)
1503 (defcustom org-default-priority ?B
1504 "The default priority of TODO items.
1505 This is the priority an item get if no explicit priority is given."
1506 :group 'org-priorities
1507 :type 'character)
1509 (defcustom org-priority-start-cycle-with-default t
1510 "Non-nil means, start with default priority when starting to cycle.
1511 When this is nil, the first step in the cycle will be (depending on the
1512 command used) one higher or lower that the default priority."
1513 :group 'org-priorities
1514 :type 'boolean)
1516 (defgroup org-time nil
1517 "Options concerning time stamps and deadlines in Org-mode."
1518 :tag "Org Time"
1519 :group 'org)
1521 (defcustom org-insert-labeled-timestamps-at-point nil
1522 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1523 When nil, these labeled time stamps are forces into the second line of an
1524 entry, just after the headline. When scheduling from the global TODO list,
1525 the time stamp will always be forced into the second line."
1526 :group 'org-time
1527 :type 'boolean)
1529 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1530 "Formats for `format-time-string' which are used for time stamps.
1531 It is not recommended to change this constant.")
1533 (defcustom org-time-stamp-rounding-minutes '(0 5)
1534 "Number of minutes to round time stamps to.
1535 These are two values, the first applies when first creating a time stamp.
1536 The second applies when changing it with the commands `S-up' and `S-down'.
1537 When changing the time stamp, this means that it will change in steps
1538 of N minutes, as given by the second value.
1540 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1541 numbers should be factors of 60, so for example 5, 10, 15.
1543 When this is larger than 1, you can still force an exact time-stamp by using
1544 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1545 and by using a prefix arg to `S-up/down' to specify the exact number
1546 of minutes to shift."
1547 :group 'org-time
1548 :get '(lambda (var) ; Make sure all entries have 5 elements
1549 (if (integerp (default-value var))
1550 (list (default-value var) 5)
1551 (default-value var)))
1552 :type '(list
1553 (integer :tag "when inserting times")
1554 (integer :tag "when modifying times")))
1556 ;; Normalize old customizations of this variable.
1557 (when (integerp org-time-stamp-rounding-minutes)
1558 (setq org-time-stamp-rounding-minutes
1559 (list org-time-stamp-rounding-minutes
1560 org-time-stamp-rounding-minutes)))
1562 (defcustom org-display-custom-times nil
1563 "Non-nil means, overlay custom formats over all time stamps.
1564 The formats are defined through the variable `org-time-stamp-custom-formats'.
1565 To turn this on on a per-file basis, insert anywhere in the file:
1566 #+STARTUP: customtime"
1567 :group 'org-time
1568 :set 'set-default
1569 :type 'sexp)
1570 (make-variable-buffer-local 'org-display-custom-times)
1572 (defcustom org-time-stamp-custom-formats
1573 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1574 "Custom formats for time stamps. See `format-time-string' for the syntax.
1575 These are overlayed over the default ISO format if the variable
1576 `org-display-custom-times' is set. Time like %H:%M should be at the
1577 end of the second format."
1578 :group 'org-time
1579 :type 'sexp)
1581 (defun org-time-stamp-format (&optional long inactive)
1582 "Get the right format for a time string."
1583 (let ((f (if long (cdr org-time-stamp-formats)
1584 (car org-time-stamp-formats))))
1585 (if inactive
1586 (concat "[" (substring f 1 -1) "]")
1587 f)))
1589 (defcustom org-deadline-warning-days 14
1590 "No. of days before expiration during which a deadline becomes active.
1591 This variable governs the display in sparse trees and in the agenda.
1592 When 0 or negative, it means use this number (the absolute value of it)
1593 even if a deadline has a different individual lead time specified."
1594 :group 'org-time
1595 :group 'org-agenda-daily/weekly
1596 :type 'number)
1598 (defcustom org-read-date-prefer-future t
1599 "Non-nil means, assume future for incomplete date input from user.
1600 This affects the following situations:
1601 1. The user gives a day, but no month.
1602 For example, if today is the 15th, and you enter \"3\", Org-mode will
1603 read this as the third of *next* month. However, if you enter \"17\",
1604 it will be considered as *this* month.
1605 2. The user gives a month but not a year.
1606 For example, if it is april and you enter \"feb 2\", this will be read
1607 as feb 2, *next* year. \"May 5\", however, will be this year.
1609 Currently this does not work for ISO week specifications.
1611 When this option is nil, the current month and year will always be used
1612 as defaults."
1613 :group 'org-time
1614 :type 'boolean)
1616 (defcustom org-read-date-display-live t
1617 "Non-nil means, display current interpretation of date prompt live.
1618 This display will be in an overlay, in the minibuffer."
1619 :group 'org-time
1620 :type 'boolean)
1622 (defcustom org-read-date-popup-calendar t
1623 "Non-nil means, pop up a calendar when prompting for a date.
1624 In the calendar, the date can be selected with mouse-1. However, the
1625 minibuffer will also be active, and you can simply enter the date as well.
1626 When nil, only the minibuffer will be available."
1627 :group 'org-time
1628 :type 'boolean)
1629 (if (fboundp 'defvaralias)
1630 (defvaralias 'org-popup-calendar-for-date-prompt
1631 'org-read-date-popup-calendar))
1633 (defcustom org-extend-today-until 0
1634 "The hour when your day really ends.
1635 This has influence for the following applications:
1636 - When switching the agenda to \"today\". It it is still earlier than
1637 the time given here, the day recognized as TODAY is actually yesterday.
1638 - When a date is read from the user and it is still before the time given
1639 here, the current date and time will be assumed to be yesterday, 23:59.
1641 FIXME:
1642 IMPORTANT: This is still a very experimental feature, it may disappear
1643 again or it may be extended to mean more things."
1644 :group 'org-time
1645 :type 'number)
1647 (defcustom org-edit-timestamp-down-means-later nil
1648 "Non-nil means, S-down will increase the time in a time stamp.
1649 When nil, S-up will increase."
1650 :group 'org-time
1651 :type 'boolean)
1653 (defcustom org-calendar-follow-timestamp-change t
1654 "Non-nil means, make the calendar window follow timestamp changes.
1655 When a timestamp is modified and the calendar window is visible, it will be
1656 moved to the new date."
1657 :group 'org-time
1658 :type 'boolean)
1660 (defgroup org-tags nil
1661 "Options concerning tags in Org-mode."
1662 :tag "Org Tags"
1663 :group 'org)
1665 (defcustom org-tag-alist nil
1666 "List of tags allowed in Org-mode files.
1667 When this list is nil, Org-mode will base TAG input on what is already in the
1668 buffer.
1669 The value of this variable is an alist, the car of each entry must be a
1670 keyword as a string, the cdr may be a character that is used to select
1671 that tag through the fast-tag-selection interface.
1672 See the manual for details."
1673 :group 'org-tags
1674 :type '(repeat
1675 (choice
1676 (cons (string :tag "Tag name")
1677 (character :tag "Access char"))
1678 (const :tag "Start radio group" (:startgroup))
1679 (const :tag "End radio group" (:endgroup)))))
1681 (defcustom org-use-fast-tag-selection 'auto
1682 "Non-nil means, use fast tag selection scheme.
1683 This is a special interface to select and deselect tags with single keys.
1684 When nil, fast selection is never used.
1685 When the symbol `auto', fast selection is used if and only if selection
1686 characters for tags have been configured, either through the variable
1687 `org-tag-alist' or through a #+TAGS line in the buffer.
1688 When t, fast selection is always used and selection keys are assigned
1689 automatically if necessary."
1690 :group 'org-tags
1691 :type '(choice
1692 (const :tag "Always" t)
1693 (const :tag "Never" nil)
1694 (const :tag "When selection characters are configured" 'auto)))
1696 (defcustom org-fast-tag-selection-single-key nil
1697 "Non-nil means, fast tag selection exits after first change.
1698 When nil, you have to press RET to exit it.
1699 During fast tag selection, you can toggle this flag with `C-c'.
1700 This variable can also have the value `expert'. In this case, the window
1701 displaying the tags menu is not even shown, until you press C-c again."
1702 :group 'org-tags
1703 :type '(choice
1704 (const :tag "No" nil)
1705 (const :tag "Yes" t)
1706 (const :tag "Expert" expert)))
1708 (defvar org-fast-tag-selection-include-todo nil
1709 "Non-nil means, fast tags selection interface will also offer TODO states.
1710 This is an undocumented feature, you should not rely on it.")
1712 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1713 "The column to which tags should be indented in a headline.
1714 If this number is positive, it specifies the column. If it is negative,
1715 it means that the tags should be flushright to that column. For example,
1716 -80 works well for a normal 80 character screen."
1717 :group 'org-tags
1718 :type 'integer)
1720 (defcustom org-auto-align-tags t
1721 "Non-nil means, realign tags after pro/demotion of TODO state change.
1722 These operations change the length of a headline and therefore shift
1723 the tags around. With this options turned on, after each such operation
1724 the tags are again aligned to `org-tags-column'."
1725 :group 'org-tags
1726 :type 'boolean)
1728 (defcustom org-use-tag-inheritance t
1729 "Non-nil means, tags in levels apply also for sublevels.
1730 When nil, only the tags directly given in a specific line apply there.
1731 If you turn off this option, you very likely want to turn on the
1732 companion option `org-tags-match-list-sublevels'.
1734 This may also be a list of tags that should be inherited, or a regexp that
1735 matches tags that should be inherited."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Not" nil)
1739 (const :tag "Always" t)
1740 (repeat :tag "Specific tags" (string :tag "Tag"))
1741 (regexp :tag "Tags matched by regexp")))
1743 (defun org-tag-inherit-p (tag)
1744 "Check if TAG is one that should be inherited."
1745 (cond
1746 ((eq org-use-tag-inheritance t) t)
1747 ((not org-use-tag-inheritance) nil)
1748 ((stringp org-use-tag-inheritance)
1749 (string-match org-use-tag-inheritance tag))
1750 ((listp org-use-tag-inheritance)
1751 (member tag org-use-tag-inheritance))
1752 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1754 (defcustom org-tags-match-list-sublevels nil
1755 "Non-nil means list also sublevels of headlines matching tag search.
1756 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1757 the sublevels of a headline matching a tag search often also match
1758 the same search. Listing all of them can create very long lists.
1759 Setting this variable to nil causes subtrees of a match to be skipped.
1760 This option is off by default, because inheritance in on. If you turn
1761 inheritance off, you very likely want to turn this option on.
1763 As a special case, if the tag search is restricted to TODO items, the
1764 value of this variable is ignored and sublevels are always checked, to
1765 make sure all corresponding TODO items find their way into the list."
1766 :group 'org-tags
1767 :type 'boolean)
1769 (defvar org-tags-history nil
1770 "History of minibuffer reads for tags.")
1771 (defvar org-last-tags-completion-table nil
1772 "The last used completion table for tags.")
1773 (defvar org-after-tags-change-hook nil
1774 "Hook that is run after the tags in a line have changed.")
1776 (defgroup org-properties nil
1777 "Options concerning properties in Org-mode."
1778 :tag "Org Properties"
1779 :group 'org)
1781 (defcustom org-property-format "%-10s %s"
1782 "How property key/value pairs should be formatted by `indent-line'.
1783 When `indent-line' hits a property definition, it will format the line
1784 according to this format, mainly to make sure that the values are
1785 lined-up with respect to each other."
1786 :group 'org-properties
1787 :type 'string)
1789 (defcustom org-use-property-inheritance nil
1790 "Non-nil means, properties apply also for sublevels.
1792 This setting is chiefly used during property searches. Turning it on can
1793 cause significant overhead when doing a search, which is why it is not
1794 on by default.
1796 When nil, only the properties directly given in the current entry count.
1797 When t, every property is inherited. The value may also be a list of
1798 properties that should have inheritance, or a regular expression matching
1799 properties that should be inherited.
1801 However, note that some special properties use inheritance under special
1802 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1803 and the properties ending in \"_ALL\" when they are used as descriptor
1804 for valid values of a property.
1806 Note for programmers:
1807 When querying an entry with `org-entry-get', you can control if inheritance
1808 should be used. By default, `org-entry-get' looks only at the local
1809 properties. You can request inheritance by setting the inherit argument
1810 to t (to force inheritance) or to `selective' (to respect the setting
1811 in this variable)."
1812 :group 'org-properties
1813 :type '(choice
1814 (const :tag "Not" nil)
1815 (const :tag "Always" t)
1816 (repeat :tag "Specific properties" (string :tag "Property"))
1817 (regexp :tag "Properties matched by regexp")))
1819 (defun org-property-inherit-p (property)
1820 "Check if PROPERTY is one that should be inherited."
1821 (cond
1822 ((eq org-use-property-inheritance t) t)
1823 ((not org-use-property-inheritance) nil)
1824 ((stringp org-use-property-inheritance)
1825 (string-match org-use-property-inheritance property))
1826 ((listp org-use-property-inheritance)
1827 (member property org-use-property-inheritance))
1828 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1830 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1831 "The default column format, if no other format has been defined.
1832 This variable can be set on the per-file basis by inserting a line
1834 #+COLUMNS: %25ITEM ....."
1835 :group 'org-properties
1836 :type 'string)
1838 (defcustom org-effort-property "Effort"
1839 "The property that is being used to keep track of effort estimates.
1840 Effort estimates given in this property need to have the format H:MM."
1841 :group 'org-properties
1842 :group 'org-progress
1843 :type '(string :tag "Property"))
1845 (defconst org-global-properties-fixed
1846 '(("VISIBILITY_ALL" . "folded children content all"))
1847 "List of property/value pairs that can be inherited by any entry.
1848 These are fixed values, for the preset properties.")
1851 (defcustom org-global-properties nil
1852 "List of property/value pairs that can be inherited by any entry.
1853 You can set buffer-local values for this by adding lines like
1855 #+PROPERTY: NAME VALUE"
1856 :group 'org-properties
1857 :type '(repeat
1858 (cons (string :tag "Property")
1859 (string :tag "Value"))))
1861 (defvar org-local-properties nil
1862 "List of property/value pairs that can be inherited by any entry.
1863 Valid for the current buffer.
1864 This variable is populated from #+PROPERTY lines.")
1866 (defgroup org-agenda nil
1867 "Options concerning agenda views in Org-mode."
1868 :tag "Org Agenda"
1869 :group 'org)
1871 (defvar org-category nil
1872 "Variable used by org files to set a category for agenda display.
1873 Such files should use a file variable to set it, for example
1875 # -*- mode: org; org-category: \"ELisp\"
1877 or contain a special line
1879 #+CATEGORY: ELisp
1881 If the file does not specify a category, then file's base name
1882 is used instead.")
1883 (make-variable-buffer-local 'org-category)
1885 (defcustom org-agenda-files nil
1886 "The files to be used for agenda display.
1887 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1888 \\[org-remove-file]. You can also use customize to edit the list.
1890 If an entry is a directory, all files in that directory that are matched by
1891 `org-agenda-file-regexp' will be part of the file list.
1893 If the value of the variable is not a list but a single file name, then
1894 the list of agenda files is actually stored and maintained in that file, one
1895 agenda file per line."
1896 :group 'org-agenda
1897 :type '(choice
1898 (repeat :tag "List of files and directories" file)
1899 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1901 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1902 "Regular expression to match files for `org-agenda-files'.
1903 If any element in the list in that variable contains a directory instead
1904 of a normal file, all files in that directory that are matched by this
1905 regular expression will be included."
1906 :group 'org-agenda
1907 :type 'regexp)
1909 (defcustom org-agenda-text-search-extra-files nil
1910 "List of extra files to be searched by text search commands.
1911 These files will be search in addition to the agenda files by the
1912 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1913 Note that these files will only be searched for text search commands,
1914 not for the other agenda views like todo lists, tag searches or the weekly
1915 agenda. This variable is intended to list notes and possibly archive files
1916 that should also be searched by these two commands.
1917 In fact, if the first element in the list is the symbol `agenda-archives',
1918 than all archive files of all agenda files will be added to the search
1919 scope."
1920 :group 'org-agenda
1921 :type '(set :greedy t
1922 (const :tag "Agenda Archives" agenda-archives)
1923 (repeat :inline t (file))))
1925 (if (fboundp 'defvaralias)
1926 (defvaralias 'org-agenda-multi-occur-extra-files
1927 'org-agenda-text-search-extra-files))
1929 (defcustom org-agenda-skip-unavailable-files nil
1930 "t means to just skip non-reachable files in `org-agenda-files'.
1931 Nil means to remove them, after a query, from the list."
1932 :group 'org-agenda
1933 :type 'boolean)
1935 (defcustom org-calendar-to-agenda-key [?c]
1936 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1937 The command `org-calendar-goto-agenda' will be bound to this key. The
1938 default is the character `c' because then `c' can be used to switch back and
1939 forth between agenda and calendar."
1940 :group 'org-agenda
1941 :type 'sexp)
1943 (eval-after-load "calendar"
1944 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1945 'org-calendar-goto-agenda))
1947 (defgroup org-latex nil
1948 "Options for embedding LaTeX code into Org-mode."
1949 :tag "Org LaTeX"
1950 :group 'org)
1952 (defcustom org-format-latex-options
1953 '(:foreground default :background default :scale 1.0
1954 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1955 :matchers ("begin" "$" "$$" "\\(" "\\["))
1956 "Options for creating images from LaTeX fragments.
1957 This is a property list with the following properties:
1958 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1959 `default' means use the forground of the default face.
1960 :background the background color, or \"Transparent\".
1961 `default' means use the background of the default face.
1962 :scale a scaling factor for the size of the images
1963 :html-foreground, :html-background, :html-scale
1964 The same numbers for HTML export.
1965 :matchers a list indicating which matchers should be used to
1966 find LaTeX fragments. Valid members of this list are:
1967 \"begin\" find environments
1968 \"$\" find math expressions surrounded by $...$
1969 \"$$\" find math expressions surrounded by $$....$$
1970 \"\\(\" find math expressions surrounded by \\(...\\)
1971 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1972 :group 'org-latex
1973 :type 'plist)
1975 (defcustom org-format-latex-header "\\documentclass{article}
1976 \\usepackage{fullpage} % do not remove
1977 \\usepackage{amssymb}
1978 \\usepackage[usenames]{color}
1979 \\usepackage{amsmath}
1980 \\usepackage{latexsym}
1981 \\usepackage[mathscr]{eucal}
1982 \\pagestyle{empty} % do not remove"
1983 "The document header used for processing LaTeX fragments."
1984 :group 'org-latex
1985 :type 'string)
1988 (defgroup org-font-lock nil
1989 "Font-lock settings for highlighting in Org-mode."
1990 :tag "Org Font Lock"
1991 :group 'org)
1993 (defcustom org-level-color-stars-only nil
1994 "Non-nil means fontify only the stars in each headline.
1995 When nil, the entire headline is fontified.
1996 Changing it requires restart of `font-lock-mode' to become effective
1997 also in regions already fontified."
1998 :group 'org-font-lock
1999 :type 'boolean)
2001 (defcustom org-hide-leading-stars nil
2002 "Non-nil means, hide the first N-1 stars in a headline.
2003 This works by using the face `org-hide' for these stars. This
2004 face is white for a light background, and black for a dark
2005 background. You may have to customize the face `org-hide' to
2006 make this work.
2007 Changing it requires restart of `font-lock-mode' to become effective
2008 also in regions already fontified.
2009 You may also set this on a per-file basis by adding one of the following
2010 lines to the buffer:
2012 #+STARTUP: hidestars
2013 #+STARTUP: showstars"
2014 :group 'org-font-lock
2015 :type 'boolean)
2017 (defcustom org-fontify-done-headline nil
2018 "Non-nil means, change the face of a headline if it is marked DONE.
2019 Normally, only the TODO/DONE keyword indicates the state of a headline.
2020 When this is non-nil, the headline after the keyword is set to the
2021 `org-headline-done' as an additional indication."
2022 :group 'org-font-lock
2023 :type 'boolean)
2025 (defcustom org-fontify-emphasized-text t
2026 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2027 Changing this variable requires a restart of Emacs to take effect."
2028 :group 'org-font-lock
2029 :type 'boolean)
2031 (defcustom org-highlight-latex-fragments-and-specials nil
2032 "Non-nil means, fontify what is treated specially by the exporters."
2033 :group 'org-font-lock
2034 :type 'boolean)
2036 (defcustom org-hide-emphasis-markers nil
2037 "Non-nil mean font-lock should hide the emphasis marker characters."
2038 :group 'org-font-lock
2039 :type 'boolean)
2041 (defvar org-emph-re nil
2042 "Regular expression for matching emphasis.")
2043 (defvar org-verbatim-re nil
2044 "Regular expression for matching verbatim text.")
2045 (defvar org-emphasis-regexp-components) ; defined just below
2046 (defvar org-emphasis-alist) ; defined just below
2047 (defun org-set-emph-re (var val)
2048 "Set variable and compute the emphasis regular expression."
2049 (set var val)
2050 (when (and (boundp 'org-emphasis-alist)
2051 (boundp 'org-emphasis-regexp-components)
2052 org-emphasis-alist org-emphasis-regexp-components)
2053 (let* ((e org-emphasis-regexp-components)
2054 (pre (car e))
2055 (post (nth 1 e))
2056 (border (nth 2 e))
2057 (body (nth 3 e))
2058 (nl (nth 4 e))
2059 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2060 (body1 (concat body "*?"))
2061 (markers (mapconcat 'car org-emphasis-alist ""))
2062 (vmarkers (mapconcat
2063 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2064 org-emphasis-alist "")))
2065 ;; make sure special characters appear at the right position in the class
2066 (if (string-match "\\^" markers)
2067 (setq markers (concat (replace-match "" t t markers) "^")))
2068 (if (string-match "-" markers)
2069 (setq markers (concat (replace-match "" t t markers) "-")))
2070 (if (string-match "\\^" vmarkers)
2071 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2072 (if (string-match "-" vmarkers)
2073 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2074 (if (> nl 0)
2075 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2076 (int-to-string nl) "\\}")))
2077 ;; Make the regexp
2078 (setq org-emph-re
2079 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2080 "\\("
2081 "\\([" markers "]\\)"
2082 "\\("
2083 "[^" border "]\\|"
2084 "[^" border (if (and nil stacked) markers) "]"
2085 body1
2086 "[^" border (if (and nil stacked) markers) "]"
2087 "\\)"
2088 "\\3\\)"
2089 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2090 (setq org-verbatim-re
2091 (concat "\\([" pre "]\\|^\\)"
2092 "\\("
2093 "\\([" vmarkers "]\\)"
2094 "\\("
2095 "[^" border "]\\|"
2096 "[^" border "]"
2097 body1
2098 "[^" border "]"
2099 "\\)"
2100 "\\3\\)"
2101 "\\([" post "]\\|$\\)")))))
2103 (defcustom org-emphasis-regexp-components
2104 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2105 "Components used to build the regular expression for emphasis.
2106 This is a list with 6 entries. Terminology: In an emphasis string
2107 like \" *strong word* \", we call the initial space PREMATCH, the final
2108 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2109 and \"trong wor\" is the body. The different components in this variable
2110 specify what is allowed/forbidden in each part:
2112 pre Chars allowed as prematch. Beginning of line will be allowed too.
2113 post Chars allowed as postmatch. End of line will be allowed too.
2114 border The chars *forbidden* as border characters.
2115 body-regexp A regexp like \".\" to match a body character. Don't use
2116 non-shy groups here, and don't allow newline here.
2117 newline The maximum number of newlines allowed in an emphasis exp.
2119 Use customize to modify this, or restart Emacs after changing it."
2120 :group 'org-font-lock
2121 :set 'org-set-emph-re
2122 :type '(list
2123 (sexp :tag "Allowed chars in pre ")
2124 (sexp :tag "Allowed chars in post ")
2125 (sexp :tag "Forbidden chars in border ")
2126 (sexp :tag "Regexp for body ")
2127 (integer :tag "number of newlines allowed")
2128 (option (boolean :tag "Stacking (DISABLED) "))))
2130 (defcustom org-emphasis-alist
2131 `(("*" bold "<b>" "</b>")
2132 ("/" italic "<i>" "</i>")
2133 ("_" underline "<u>" "</u>")
2134 ("=" org-code "<code>" "</code>" verbatim)
2135 ("~" org-verbatim "" "" verbatim)
2136 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2137 "<del>" "</del>")
2139 "Special syntax for emphasized text.
2140 Text starting and ending with a special character will be emphasized, for
2141 example *bold*, _underlined_ and /italic/. This variable sets the marker
2142 characters, the face to be used by font-lock for highlighting in Org-mode
2143 Emacs buffers, and the HTML tags to be used for this.
2144 Use customize to modify this, or restart Emacs after changing it."
2145 :group 'org-font-lock
2146 :set 'org-set-emph-re
2147 :type '(repeat
2148 (list
2149 (string :tag "Marker character")
2150 (choice
2151 (face :tag "Font-lock-face")
2152 (plist :tag "Face property list"))
2153 (string :tag "HTML start tag")
2154 (string :tag "HTML end tag")
2155 (option (const verbatim)))))
2157 ;;; Miscellaneous options
2159 (defgroup org-completion nil
2160 "Completion in Org-mode."
2161 :tag "Org Completion"
2162 :group 'org)
2164 (defcustom org-completion-fallback-command 'hippie-expand
2165 "The expansion command called by \\[org-complete] in normal context.
2166 Normal means, no org-mode-specific context."
2167 :group 'org-completion
2168 :type 'function)
2170 ;;; Functions and variables from ther packages
2171 ;; Declared here to avoid compiler warnings
2173 ;; XEmacs only
2174 (defvar outline-mode-menu-heading)
2175 (defvar outline-mode-menu-show)
2176 (defvar outline-mode-menu-hide)
2177 (defvar zmacs-regions) ; XEmacs regions
2179 ;; Emacs only
2180 (defvar mark-active)
2182 ;; Various packages
2183 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2184 (declare-function calendar-forward-day "cal-move" (arg))
2185 (declare-function calendar-goto-date "cal-move" (date))
2186 (declare-function calendar-goto-today "cal-move" ())
2187 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2188 (defvar calc-embedded-close-formula)
2189 (defvar calc-embedded-open-formula)
2190 (declare-function cdlatex-tab "ext:cdlatex" ())
2191 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2192 (defvar font-lock-unfontify-region-function)
2193 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2194 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2195 (defvar iswitchb-temp-buflist)
2196 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2197 (declare-function org-agenda-skip "org-agenda" ())
2198 (declare-function org-format-agenda-item "org-agenda"
2199 (extra txt &optional category tags dotime noprefix remove-re))
2200 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2201 (declare-function org-agenda-change-all-lines "org-agenda"
2202 (newhead hdmarker &optional fixface))
2203 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2204 (declare-function org-agenda-maybe-redo "org-agenda" ())
2205 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2206 (beg end))
2207 (declare-function parse-time-string "parse-time" (string))
2208 (declare-function remember "remember" (&optional initial))
2209 (declare-function remember-buffer-desc "remember" ())
2210 (declare-function remember-finalize "remember" ())
2211 (defvar remember-save-after-remembering)
2212 (defvar remember-data-file)
2213 (defvar remember-register)
2214 (defvar remember-buffer)
2215 (defvar remember-handler-functions)
2216 (defvar remember-annotation-functions)
2217 (defvar texmathp-why)
2218 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2219 (declare-function table--at-cell-p "table" (position &optional object at-column))
2221 (defvar w3m-current-url)
2222 (defvar w3m-current-title)
2224 (defvar org-latex-regexps)
2226 ;;; Autoload and prepare some org modules
2228 ;; Some table stuff that needs to be defined here, because it is used
2229 ;; by the functions setting up org-mode or checking for table context.
2231 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2232 "Detects an org-type or table-type table.")
2233 (defconst org-table-line-regexp "^[ \t]*|"
2234 "Detects an org-type table line.")
2235 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2236 "Detects an org-type table line.")
2237 (defconst org-table-hline-regexp "^[ \t]*|-"
2238 "Detects an org-type table hline.")
2239 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2240 "Detects a table-type table hline.")
2241 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2242 "Searching from within a table (any type) this finds the first line
2243 outside the table.")
2245 ;; Autoload the functions in org-table.el that are needed by functions here.
2247 (eval-and-compile
2248 (org-autoload "org-table"
2249 '(org-table-align org-table-begin org-table-blank-field
2250 org-table-convert org-table-convert-region org-table-copy-down
2251 org-table-copy-region org-table-create
2252 org-table-create-or-convert-from-region
2253 org-table-create-with-table.el org-table-current-dline
2254 org-table-cut-region org-table-delete-column org-table-edit-field
2255 org-table-edit-formulas org-table-end org-table-eval-formula
2256 org-table-export org-table-field-info
2257 org-table-get-stored-formulas org-table-goto-column
2258 org-table-hline-and-move org-table-import org-table-insert-column
2259 org-table-insert-hline org-table-insert-row org-table-iterate
2260 org-table-justify-field-maybe org-table-kill-row
2261 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2262 org-table-move-column org-table-move-column-left
2263 org-table-move-column-right org-table-move-row
2264 org-table-move-row-down org-table-move-row-up
2265 org-table-next-field org-table-next-row org-table-paste-rectangle
2266 org-table-previous-field org-table-recalculate
2267 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2268 org-table-toggle-coordinate-overlays
2269 org-table-toggle-formula-debugger org-table-wrap-region
2270 orgtbl-mode turn-on-orgtbl)))
2272 (defun org-at-table-p (&optional table-type)
2273 "Return t if the cursor is inside an org-type table.
2274 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2275 (if org-enable-table-editor
2276 (save-excursion
2277 (beginning-of-line 1)
2278 (looking-at (if table-type org-table-any-line-regexp
2279 org-table-line-regexp)))
2280 nil))
2281 (defsubst org-table-p () (org-at-table-p))
2283 (defun org-at-table.el-p ()
2284 "Return t if and only if we are at a table.el table."
2285 (and (org-at-table-p 'any)
2286 (save-excursion
2287 (goto-char (org-table-begin 'any))
2288 (looking-at org-table1-hline-regexp))))
2289 (defun org-table-recognize-table.el ()
2290 "If there is a table.el table nearby, recognize it and move into it."
2291 (if org-table-tab-recognizes-table.el
2292 (if (org-at-table.el-p)
2293 (progn
2294 (beginning-of-line 1)
2295 (if (looking-at org-table-dataline-regexp)
2297 (if (looking-at org-table1-hline-regexp)
2298 (progn
2299 (beginning-of-line 2)
2300 (if (looking-at org-table-any-border-regexp)
2301 (beginning-of-line -1)))))
2302 (if (re-search-forward "|" (org-table-end t) t)
2303 (progn
2304 (require 'table)
2305 (if (table--at-cell-p (point))
2307 (message "recognizing table.el table...")
2308 (table-recognize-table)
2309 (message "recognizing table.el table...done")))
2310 (error "This should not happen..."))
2312 nil)
2313 nil))
2315 (defun org-at-table-hline-p ()
2316 "Return t if the cursor is inside a hline in a table."
2317 (if org-enable-table-editor
2318 (save-excursion
2319 (beginning-of-line 1)
2320 (looking-at org-table-hline-regexp))
2321 nil))
2323 (defvar org-table-clean-did-remove-column nil)
2325 (defun org-table-map-tables (function)
2326 "Apply FUNCTION to the start of all tables in the buffer."
2327 (save-excursion
2328 (save-restriction
2329 (widen)
2330 (goto-char (point-min))
2331 (while (re-search-forward org-table-any-line-regexp nil t)
2332 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2333 (beginning-of-line 1)
2334 (if (looking-at org-table-line-regexp)
2335 (save-excursion (funcall function)))
2336 (re-search-forward org-table-any-border-regexp nil 1))))
2337 (message "Mapping tables: done"))
2339 ;; Declare and autoload functions from org-exp.el
2341 (declare-function org-default-export-plist "org-exp")
2342 (declare-function org-infile-export-plist "org-exp")
2343 (declare-function org-get-current-options "org-exp")
2344 (eval-and-compile
2345 (org-autoload "org-exp"
2346 '(org-export org-export-as-ascii org-export-visible
2347 org-insert-export-options-template org-export-as-html-and-open
2348 org-export-as-html-batch org-export-as-html-to-buffer
2349 org-replace-region-by-html org-export-region-as-html
2350 org-export-as-html org-export-icalendar-this-file
2351 org-export-icalendar-all-agenda-files
2352 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2354 ;; Declare and autoload functions from org-exp.el
2356 (eval-and-compile
2357 (org-autoload "org-exp"
2358 '(org-agenda org-agenda-list org-search-view
2359 org-todo-list org-tags-view org-agenda-list-stuck-projects
2360 org-diary org-agenda-to-appt)))
2362 ;; Autoload org-remember
2364 (eval-and-compile
2365 (org-autoload "org-remember"
2366 '(org-remember-insinuate org-remember-annotation
2367 org-remember-apply-template org-remember org-remember-handler)))
2369 ;; Autoload org-clock.el
2372 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2373 (beg end))
2374 (defvar org-clock-marker (make-marker)
2375 "Marker recording the last clock-in.")
2377 (eval-and-compile
2378 (org-autoload
2379 "org-clock"
2380 '(org-clock-in org-clock-out org-clock-cancel
2381 org-clock-goto org-clock-sum org-clock-display
2382 org-remove-clock-overlays org-clock-report
2383 org-clocktable-shift org-dblock-write:clocktable
2384 org-get-clocktable)))
2386 (defun org-clock-update-time-maybe ()
2387 "If this is a CLOCK line, update it and return t.
2388 Otherwise, return nil."
2389 (interactive)
2390 (save-excursion
2391 (beginning-of-line 1)
2392 (skip-chars-forward " \t")
2393 (when (looking-at org-clock-string)
2394 (let ((re (concat "[ \t]*" org-clock-string
2395 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2396 "\\([ \t]*=>.*\\)?"))
2397 ts te h m s)
2398 (if (not (looking-at re))
2400 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2401 (end-of-line 1)
2402 (setq ts (match-string 1)
2403 te (match-string 2))
2404 (setq s (- (time-to-seconds
2405 (apply 'encode-time (org-parse-time-string te)))
2406 (time-to-seconds
2407 (apply 'encode-time (org-parse-time-string ts))))
2408 h (floor (/ s 3600))
2409 s (- s (* 3600 h))
2410 m (floor (/ s 60))
2411 s (- s (* 60 s)))
2412 (insert " => " (format "%2d:%02d" h m))
2413 t)))))
2415 (defun org-check-running-clock ()
2416 "Check if the current buffer contains the running clock.
2417 If yes, offer to stop it and to save the buffer with the changes."
2418 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2419 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2420 (buffer-name))))
2421 (org-clock-out)
2422 (when (y-or-n-p "Save changed buffer?")
2423 (save-buffer))))
2425 (defun org-clocktable-try-shift (dir n)
2426 "Check if this line starts a clock table, if yes, shift the time block."
2427 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2428 (org-clocktable-shift dir n)))
2430 ;; Autoload archiving code
2431 ;; The stuff that is needed for cycling and tags has to be defined here.
2433 (defgroup org-archive nil
2434 "Options concerning archiving in Org-mode."
2435 :tag "Org Archive"
2436 :group 'org-structure)
2438 (defcustom org-archive-location "%s_archive::"
2439 "The location where subtrees should be archived.
2441 Otherwise, the value of this variable is a string, consisting of two
2442 parts, separated by a double-colon.
2444 The first part is a file name - when omitted, archiving happens in the same
2445 file. %s will be replaced by the current file name (without directory part).
2446 Archiving to a different file is useful to keep archived entries from
2447 contributing to the Org-mode Agenda.
2449 The part after the double colon is a headline. The archived entries will be
2450 filed under that headline. When omitted, the subtrees are simply filed away
2451 at the end of the file, as top-level entries.
2453 Here are a few examples:
2454 \"%s_archive::\"
2455 If the current file is Projects.org, archive in file
2456 Projects.org_archive, as top-level trees. This is the default.
2458 \"::* Archived Tasks\"
2459 Archive in the current file, under the top-level headline
2460 \"* Archived Tasks\".
2462 \"~/org/archive.org::\"
2463 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2465 \"basement::** Finished Tasks\"
2466 Archive in file ./basement (relative path), as level 3 trees
2467 below the level 2 heading \"** Finished Tasks\".
2469 You may set this option on a per-file basis by adding to the buffer a
2470 line like
2472 #+ARCHIVE: basement::** Finished Tasks
2474 You may also define it locally for a subtree by setting an ARCHIVE property
2475 in the entry. If such a property is found in an entry, or anywhere up
2476 the hierarchy, it will be used."
2477 :group 'org-archive
2478 :type 'string)
2480 (defcustom org-archive-tag "ARCHIVE"
2481 "The tag that marks a subtree as archived.
2482 An archived subtree does not open during visibility cycling, and does
2483 not contribute to the agenda listings.
2484 After changing this, font-lock must be restarted in the relevant buffers to
2485 get the proper fontification."
2486 :group 'org-archive
2487 :group 'org-keywords
2488 :type 'string)
2490 (defcustom org-agenda-skip-archived-trees t
2491 "Non-nil means, the agenda will skip any items located in archived trees.
2492 An archived tree is a tree marked with the tag ARCHIVE."
2493 :group 'org-archive
2494 :group 'org-agenda-skip
2495 :type 'boolean)
2497 (defcustom org-cycle-open-archived-trees nil
2498 "Non-nil means, `org-cycle' will open archived trees.
2499 An archived tree is a tree marked with the tag ARCHIVE.
2500 When nil, archived trees will stay folded. You can still open them with
2501 normal outline commands like `show-all', but not with the cycling commands."
2502 :group 'org-archive
2503 :group 'org-cycle
2504 :type 'boolean)
2506 (defcustom org-sparse-tree-open-archived-trees nil
2507 "Non-nil means sparse tree construction shows matches in archived trees.
2508 When nil, matches in these trees are highlighted, but the trees are kept in
2509 collapsed state."
2510 :group 'org-archive
2511 :group 'org-sparse-trees
2512 :type 'boolean)
2514 (defun org-cycle-hide-archived-subtrees (state)
2515 "Re-hide all archived subtrees after a visibility state change."
2516 (when (and (not org-cycle-open-archived-trees)
2517 (not (memq state '(overview folded))))
2518 (save-excursion
2519 (let* ((globalp (memq state '(contents all)))
2520 (beg (if globalp (point-min) (point)))
2521 (end (if globalp (point-max) (org-end-of-subtree t))))
2522 (org-hide-archived-subtrees beg end)
2523 (goto-char beg)
2524 (if (looking-at (concat ".*:" org-archive-tag ":"))
2525 (message "%s" (substitute-command-keys
2526 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2528 (defun org-force-cycle-archived ()
2529 "Cycle subtree even if it is archived."
2530 (interactive)
2531 (setq this-command 'org-cycle)
2532 (let ((org-cycle-open-archived-trees t))
2533 (call-interactively 'org-cycle)))
2535 (defun org-hide-archived-subtrees (beg end)
2536 "Re-hide all archived subtrees after a visibility state change."
2537 (save-excursion
2538 (let* ((re (concat ":" org-archive-tag ":")))
2539 (goto-char beg)
2540 (while (re-search-forward re end t)
2541 (and (org-on-heading-p) (hide-subtree))
2542 (org-end-of-subtree t)))))
2544 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2546 (eval-and-compile
2547 (org-autoload "org-archive"
2548 '(org-add-archive-files org-archive-subtree
2549 org-archive-to-archive-sibling org-toggle-archive-tag)))
2551 ;; Autoload Column View Code
2553 (declare-function org-columns-number-to-string "org-colview")
2554 (declare-function org-columns-get-format-and-top-level "org-colview")
2555 (declare-function org-columns-compute "org-colview")
2557 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2558 '(org-columns-number-to-string org-columns-get-format-and-top-level
2559 org-columns-compute org-agenda-columns org-columns-remove-overlays
2560 org-columns org-insert-columns-dblock))
2562 ;;; Variables for pre-computed regular expressions, all buffer local
2564 (defvar org-drawer-regexp nil
2565 "Matches first line of a hidden block.")
2566 (make-variable-buffer-local 'org-drawer-regexp)
2567 (defvar org-todo-regexp nil
2568 "Matches any of the TODO state keywords.")
2569 (make-variable-buffer-local 'org-todo-regexp)
2570 (defvar org-not-done-regexp nil
2571 "Matches any of the TODO state keywords except the last one.")
2572 (make-variable-buffer-local 'org-not-done-regexp)
2573 (defvar org-todo-line-regexp nil
2574 "Matches a headline and puts TODO state into group 2 if present.")
2575 (make-variable-buffer-local 'org-todo-line-regexp)
2576 (defvar org-complex-heading-regexp nil
2577 "Matches a headline and puts everything into groups:
2578 group 1: the stars
2579 group 2: The todo keyword, maybe
2580 group 3: Priority cookie
2581 group 4: True headline
2582 group 5: Tags")
2583 (make-variable-buffer-local 'org-complex-heading-regexp)
2584 (defvar org-todo-line-tags-regexp nil
2585 "Matches a headline and puts TODO state into group 2 if present.
2586 Also put tags into group 4 if tags are present.")
2587 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2588 (defvar org-nl-done-regexp nil
2589 "Matches newline followed by a headline with the DONE keyword.")
2590 (make-variable-buffer-local 'org-nl-done-regexp)
2591 (defvar org-looking-at-done-regexp nil
2592 "Matches the DONE keyword a point.")
2593 (make-variable-buffer-local 'org-looking-at-done-regexp)
2594 (defvar org-ds-keyword-length 12
2595 "Maximum length of the Deadline and SCHEDULED keywords.")
2596 (make-variable-buffer-local 'org-ds-keyword-length)
2597 (defvar org-deadline-regexp nil
2598 "Matches the DEADLINE keyword.")
2599 (make-variable-buffer-local 'org-deadline-regexp)
2600 (defvar org-deadline-time-regexp nil
2601 "Matches the DEADLINE keyword together with a time stamp.")
2602 (make-variable-buffer-local 'org-deadline-time-regexp)
2603 (defvar org-deadline-line-regexp nil
2604 "Matches the DEADLINE keyword and the rest of the line.")
2605 (make-variable-buffer-local 'org-deadline-line-regexp)
2606 (defvar org-scheduled-regexp nil
2607 "Matches the SCHEDULED keyword.")
2608 (make-variable-buffer-local 'org-scheduled-regexp)
2609 (defvar org-scheduled-time-regexp nil
2610 "Matches the SCHEDULED keyword together with a time stamp.")
2611 (make-variable-buffer-local 'org-scheduled-time-regexp)
2612 (defvar org-closed-time-regexp nil
2613 "Matches the CLOSED keyword together with a time stamp.")
2614 (make-variable-buffer-local 'org-closed-time-regexp)
2616 (defvar org-keyword-time-regexp nil
2617 "Matches any of the 4 keywords, together with the time stamp.")
2618 (make-variable-buffer-local 'org-keyword-time-regexp)
2619 (defvar org-keyword-time-not-clock-regexp nil
2620 "Matches any of the 3 keywords, together with the time stamp.")
2621 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2622 (defvar org-maybe-keyword-time-regexp nil
2623 "Matches a timestamp, possibly preceeded by a keyword.")
2624 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2625 (defvar org-planning-or-clock-line-re nil
2626 "Matches a line with planning or clock info.")
2627 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2629 (defconst org-plain-time-of-day-regexp
2630 (concat
2631 "\\(\\<[012]?[0-9]"
2632 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2633 "\\(--?"
2634 "\\(\\<[012]?[0-9]"
2635 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2636 "\\)?")
2637 "Regular expression to match a plain time or time range.
2638 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2639 groups carry important information:
2640 0 the full match
2641 1 the first time, range or not
2642 8 the second time, if it is a range.")
2644 (defconst org-plain-time-extension-regexp
2645 (concat
2646 "\\(\\<[012]?[0-9]"
2647 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2648 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2649 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2650 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2651 groups carry important information:
2652 0 the full match
2653 7 hours of duration
2654 9 minutes of duration")
2656 (defconst org-stamp-time-of-day-regexp
2657 (concat
2658 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2659 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2660 "\\(--?"
2661 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2662 "Regular expression to match a timestamp time or time range.
2663 After a match, the following groups carry important information:
2664 0 the full match
2665 1 date plus weekday, for backreferencing to make sure both times on same day
2666 2 the first time, range or not
2667 4 the second time, if it is a range.")
2669 (defconst org-startup-options
2670 '(("fold" org-startup-folded t)
2671 ("overview" org-startup-folded t)
2672 ("nofold" org-startup-folded nil)
2673 ("showall" org-startup-folded nil)
2674 ("content" org-startup-folded content)
2675 ("hidestars" org-hide-leading-stars t)
2676 ("showstars" org-hide-leading-stars nil)
2677 ("odd" org-odd-levels-only t)
2678 ("oddeven" org-odd-levels-only nil)
2679 ("align" org-startup-align-all-tables t)
2680 ("noalign" org-startup-align-all-tables nil)
2681 ("customtime" org-display-custom-times t)
2682 ("logdone" org-log-done time)
2683 ("lognotedone" org-log-done note)
2684 ("nologdone" org-log-done nil)
2685 ("lognoteclock-out" org-log-note-clock-out t)
2686 ("nolognoteclock-out" org-log-note-clock-out nil)
2687 ("logrepeat" org-log-repeat state)
2688 ("lognoterepeat" org-log-repeat note)
2689 ("nologrepeat" org-log-repeat nil)
2690 ("constcgs" constants-unit-system cgs)
2691 ("constSI" constants-unit-system SI))
2692 "Variable associated with STARTUP options for org-mode.
2693 Each element is a list of three items: The startup options as written
2694 in the #+STARTUP line, the corresponding variable, and the value to
2695 set this variable to if the option is found. An optional forth element PUSH
2696 means to push this value onto the list in the variable.")
2698 (defun org-set-regexps-and-options ()
2699 "Precompute regular expressions for current buffer."
2700 (when (org-mode-p)
2701 (org-set-local 'org-todo-kwd-alist nil)
2702 (org-set-local 'org-todo-key-alist nil)
2703 (org-set-local 'org-todo-key-trigger nil)
2704 (org-set-local 'org-todo-keywords-1 nil)
2705 (org-set-local 'org-done-keywords nil)
2706 (org-set-local 'org-todo-heads nil)
2707 (org-set-local 'org-todo-sets nil)
2708 (org-set-local 'org-todo-log-states nil)
2709 (let ((re (org-make-options-regexp
2710 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2711 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2712 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2713 (splitre "[ \t]+")
2714 kwds kws0 kwsa key log value cat arch tags const links hw dws
2715 tail sep kws1 prio props drawers
2716 ext-setup-or-nil setup-contents (start 0))
2717 (save-excursion
2718 (save-restriction
2719 (widen)
2720 (goto-char (point-min))
2721 (while (or (and ext-setup-or-nil
2722 (string-match re ext-setup-or-nil start)
2723 (setq start (match-end 0)))
2724 (and (setq ext-setup-or-nil nil start 0)
2725 (re-search-forward re nil t)))
2726 (setq key (upcase (match-string 1 ext-setup-or-nil))
2727 value (org-match-string-no-properties 2 ext-setup-or-nil))
2728 (cond
2729 ((equal key "CATEGORY")
2730 (if (string-match "[ \t]+$" value)
2731 (setq value (replace-match "" t t value)))
2732 (setq cat value))
2733 ((member key '("SEQ_TODO" "TODO"))
2734 (push (cons 'sequence (org-split-string value splitre)) kwds))
2735 ((equal key "TYP_TODO")
2736 (push (cons 'type (org-split-string value splitre)) kwds))
2737 ((equal key "TAGS")
2738 (setq tags (append tags (org-split-string value splitre))))
2739 ((equal key "COLUMNS")
2740 (org-set-local 'org-columns-default-format value))
2741 ((equal key "LINK")
2742 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2743 (push (cons (match-string 1 value)
2744 (org-trim (match-string 2 value)))
2745 links)))
2746 ((equal key "PRIORITIES")
2747 (setq prio (org-split-string value " +")))
2748 ((equal key "PROPERTY")
2749 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2750 (push (cons (match-string 1 value) (match-string 2 value))
2751 props)))
2752 ((equal key "DRAWERS")
2753 (setq drawers (org-split-string value splitre)))
2754 ((equal key "CONSTANTS")
2755 (setq const (append const (org-split-string value splitre))))
2756 ((equal key "STARTUP")
2757 (let ((opts (org-split-string value splitre))
2758 l var val)
2759 (while (setq l (pop opts))
2760 (when (setq l (assoc l org-startup-options))
2761 (setq var (nth 1 l) val (nth 2 l))
2762 (if (not (nth 3 l))
2763 (set (make-local-variable var) val)
2764 (if (not (listp (symbol-value var)))
2765 (set (make-local-variable var) nil))
2766 (set (make-local-variable var) (symbol-value var))
2767 (add-to-list var val))))))
2768 ((equal key "ARCHIVE")
2769 (string-match " *$" value)
2770 (setq arch (replace-match "" t t value))
2771 (remove-text-properties 0 (length arch)
2772 '(face t fontified t) arch))
2773 ((equal key "SETUPFILE")
2774 (setq setup-contents (org-file-contents
2775 (expand-file-name
2776 (org-remove-double-quotes value))
2777 'noerror))
2778 (if (not ext-setup-or-nil)
2779 (setq ext-setup-or-nil setup-contents start 0)
2780 (setq ext-setup-or-nil
2781 (concat (substring ext-setup-or-nil 0 start)
2782 "\n" setup-contents "\n"
2783 (substring ext-setup-or-nil start)))))
2784 ))))
2785 (when cat
2786 (org-set-local 'org-category (intern cat))
2787 (push (cons "CATEGORY" cat) props))
2788 (when prio
2789 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2790 (setq prio (mapcar 'string-to-char prio))
2791 (org-set-local 'org-highest-priority (nth 0 prio))
2792 (org-set-local 'org-lowest-priority (nth 1 prio))
2793 (org-set-local 'org-default-priority (nth 2 prio)))
2794 (and props (org-set-local 'org-local-properties (nreverse props)))
2795 (and drawers (org-set-local 'org-drawers drawers))
2796 (and arch (org-set-local 'org-archive-location arch))
2797 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2798 ;; Process the TODO keywords
2799 (unless kwds
2800 ;; Use the global values as if they had been given locally.
2801 (setq kwds (default-value 'org-todo-keywords))
2802 (if (stringp (car kwds))
2803 (setq kwds (list (cons org-todo-interpretation
2804 (default-value 'org-todo-keywords)))))
2805 (setq kwds (reverse kwds)))
2806 (setq kwds (nreverse kwds))
2807 (let (inter kws kw)
2808 (while (setq kws (pop kwds))
2809 (setq inter (pop kws) sep (member "|" kws)
2810 kws0 (delete "|" (copy-sequence kws))
2811 kwsa nil
2812 kws1 (mapcar
2813 (lambda (x)
2814 ;; 1 2
2815 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2816 (progn
2817 (setq kw (match-string 1 x)
2818 key (and (match-end 2) (match-string 2 x))
2819 log (org-extract-log-state-settings x))
2820 (push (cons kw (and key (string-to-char key))) kwsa)
2821 (and log (push log org-todo-log-states))
2823 (error "Invalid TODO keyword %s" x)))
2824 kws0)
2825 kwsa (if kwsa (append '((:startgroup))
2826 (nreverse kwsa)
2827 '((:endgroup))))
2828 hw (car kws1)
2829 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2830 tail (list inter hw (car dws) (org-last dws)))
2831 (add-to-list 'org-todo-heads hw 'append)
2832 (push kws1 org-todo-sets)
2833 (setq org-done-keywords (append org-done-keywords dws nil))
2834 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2835 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2836 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2837 (setq org-todo-sets (nreverse org-todo-sets)
2838 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2839 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2840 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2841 ;; Process the constants
2842 (when const
2843 (let (e cst)
2844 (while (setq e (pop const))
2845 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2846 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2847 (setq org-table-formula-constants-local cst)))
2849 ;; Process the tags.
2850 (when tags
2851 (let (e tgs)
2852 (while (setq e (pop tags))
2853 (cond
2854 ((equal e "{") (push '(:startgroup) tgs))
2855 ((equal e "}") (push '(:endgroup) tgs))
2856 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2857 (push (cons (match-string 1 e)
2858 (string-to-char (match-string 2 e)))
2859 tgs))
2860 (t (push (list e) tgs))))
2861 (org-set-local 'org-tag-alist nil)
2862 (while (setq e (pop tgs))
2863 (or (and (stringp (car e))
2864 (assoc (car e) org-tag-alist))
2865 (push e org-tag-alist))))))
2867 ;; Compute the regular expressions and other local variables
2868 (if (not org-done-keywords)
2869 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2870 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2871 (length org-scheduled-string)
2872 (length org-clock-string)
2873 (length org-closed-string)))
2874 org-drawer-regexp
2875 (concat "^[ \t]*:\\("
2876 (mapconcat 'regexp-quote org-drawers "\\|")
2877 "\\):[ \t]*$")
2878 org-not-done-keywords
2879 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2880 org-todo-regexp
2881 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2882 "\\|") "\\)\\>")
2883 org-not-done-regexp
2884 (concat "\\<\\("
2885 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2886 "\\)\\>")
2887 org-todo-line-regexp
2888 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2889 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2890 "\\)\\>\\)?[ \t]*\\(.*\\)")
2891 org-complex-heading-regexp
2892 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2893 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2894 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2895 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2896 org-nl-done-regexp
2897 (concat "\n\\*+[ \t]+"
2898 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2899 "\\)" "\\>")
2900 org-todo-line-tags-regexp
2901 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2902 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2903 (org-re
2904 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2905 org-looking-at-done-regexp
2906 (concat "^" "\\(?:"
2907 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2908 "\\>")
2909 org-deadline-regexp (concat "\\<" org-deadline-string)
2910 org-deadline-time-regexp
2911 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2912 org-deadline-line-regexp
2913 (concat "\\<\\(" org-deadline-string "\\).*")
2914 org-scheduled-regexp
2915 (concat "\\<" org-scheduled-string)
2916 org-scheduled-time-regexp
2917 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2918 org-closed-time-regexp
2919 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2920 org-keyword-time-regexp
2921 (concat "\\<\\(" org-scheduled-string
2922 "\\|" org-deadline-string
2923 "\\|" org-closed-string
2924 "\\|" org-clock-string "\\)"
2925 " *[[<]\\([^]>]+\\)[]>]")
2926 org-keyword-time-not-clock-regexp
2927 (concat "\\<\\(" org-scheduled-string
2928 "\\|" org-deadline-string
2929 "\\|" org-closed-string
2930 "\\)"
2931 " *[[<]\\([^]>]+\\)[]>]")
2932 org-maybe-keyword-time-regexp
2933 (concat "\\(\\<\\(" org-scheduled-string
2934 "\\|" org-deadline-string
2935 "\\|" org-closed-string
2936 "\\|" org-clock-string "\\)\\)?"
2937 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2938 org-planning-or-clock-line-re
2939 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2940 "\\|" org-deadline-string
2941 "\\|" org-closed-string "\\|" org-clock-string
2942 "\\)\\>\\)")
2944 (org-compute-latex-and-specials-regexp)
2945 (org-set-font-lock-defaults)))
2947 (defun org-file-contents (file &optional noerror)
2948 "Return the contents of FILE, as a string."
2949 (if (or (not file)
2950 (not (file-readable-p file)))
2951 (if noerror
2952 (progn
2953 (message "Cannot read file %s" file)
2954 (ding) (sit-for 2)
2956 (error "Cannot read file %s" file))
2957 (with-temp-buffer
2958 (insert-file-contents file)
2959 (buffer-string))))
2961 (defun org-extract-log-state-settings (x)
2962 "Extract the log state setting from a TODO keyword string.
2963 This will extract info from a string like \"WAIT(w@/!)\"."
2964 (let (kw key log1 log2)
2965 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2966 (setq kw (match-string 1 x)
2967 key (and (match-end 2) (match-string 2 x))
2968 log1 (and (match-end 3) (match-string 3 x))
2969 log2 (and (match-end 4) (match-string 4 x)))
2970 (and (or log1 log2)
2971 (list kw
2972 (and log1 (if (equal log1 "!") 'time 'note))
2973 (and log2 (if (equal log2 "!") 'time 'note)))))))
2975 (defun org-remove-keyword-keys (list)
2976 "Remove a pair of parenthesis at the end of each string in LIST."
2977 (mapcar (lambda (x)
2978 (if (string-match "(.*)$" x)
2979 (substring x 0 (match-beginning 0))
2981 list))
2983 ;; FIXME: this could be done much better, using second characters etc.
2984 (defun org-assign-fast-keys (alist)
2985 "Assign fast keys to a keyword-key alist.
2986 Respect keys that are already there."
2987 (let (new e k c c1 c2 (char ?a))
2988 (while (setq e (pop alist))
2989 (cond
2990 ((equal e '(:startgroup)) (push e new))
2991 ((equal e '(:endgroup)) (push e new))
2993 (setq k (car e) c2 nil)
2994 (if (cdr e)
2995 (setq c (cdr e))
2996 ;; automatically assign a character.
2997 (setq c1 (string-to-char
2998 (downcase (substring
2999 k (if (= (string-to-char k) ?@) 1 0)))))
3000 (if (or (rassoc c1 new) (rassoc c1 alist))
3001 (while (or (rassoc char new) (rassoc char alist))
3002 (setq char (1+ char)))
3003 (setq c2 c1))
3004 (setq c (or c2 char)))
3005 (push (cons k c) new))))
3006 (nreverse new)))
3008 ;;; Some variables used in various places
3010 (defvar org-window-configuration nil
3011 "Used in various places to store a window configuration.")
3012 (defvar org-finish-function nil
3013 "Function to be called when `C-c C-c' is used.
3014 This is for getting out of special buffers like remember.")
3017 ;; FIXME: Occasionally check by commenting these, to make sure
3018 ;; no other functions uses these, forgetting to let-bind them.
3019 (defvar entry)
3020 (defvar state)
3021 (defvar last-state)
3022 (defvar date)
3023 (defvar description)
3025 ;; Defined somewhere in this file, but used before definition.
3026 (defvar org-html-entities)
3027 (defvar org-struct-menu)
3028 (defvar org-org-menu)
3029 (defvar org-tbl-menu)
3030 (defvar org-agenda-keymap)
3032 ;;;; Define the Org-mode
3034 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3035 (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."))
3038 ;; We use a before-change function to check if a table might need
3039 ;; an update.
3040 (defvar org-table-may-need-update t
3041 "Indicates that a table might need an update.
3042 This variable is set by `org-before-change-function'.
3043 `org-table-align' sets it back to nil.")
3044 (defun org-before-change-function (beg end)
3045 "Every change indicates that a table might need an update."
3046 (setq org-table-may-need-update t))
3047 (defvar org-mode-map)
3048 (defvar org-mode-hook nil)
3049 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3050 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3051 (defvar org-table-buffer-is-an nil)
3052 (defconst org-outline-regexp "\\*+ ")
3054 ;;;###autoload
3055 (define-derived-mode org-mode outline-mode "Org"
3056 "Outline-based notes management and organizer, alias
3057 \"Carsten's outline-mode for keeping track of everything.\"
3059 Org-mode develops organizational tasks around a NOTES file which
3060 contains information about projects as plain text. Org-mode is
3061 implemented on top of outline-mode, which is ideal to keep the content
3062 of large files well structured. It supports ToDo items, deadlines and
3063 time stamps, which magically appear in the diary listing of the Emacs
3064 calendar. Tables are easily created with a built-in table editor.
3065 Plain text URL-like links connect to websites, emails (VM), Usenet
3066 messages (Gnus), BBDB entries, and any files related to the project.
3067 For printing and sharing of notes, an Org-mode file (or a part of it)
3068 can be exported as a structured ASCII or HTML file.
3070 The following commands are available:
3072 \\{org-mode-map}"
3074 ;; Get rid of Outline menus, they are not needed
3075 ;; Need to do this here because define-derived-mode sets up
3076 ;; the keymap so late. Still, it is a waste to call this each time
3077 ;; we switch another buffer into org-mode.
3078 (if (featurep 'xemacs)
3079 (when (boundp 'outline-mode-menu-heading)
3080 ;; Assume this is Greg's port, it used easymenu
3081 (easy-menu-remove outline-mode-menu-heading)
3082 (easy-menu-remove outline-mode-menu-show)
3083 (easy-menu-remove outline-mode-menu-hide))
3084 (define-key org-mode-map [menu-bar headings] 'undefined)
3085 (define-key org-mode-map [menu-bar hide] 'undefined)
3086 (define-key org-mode-map [menu-bar show] 'undefined))
3088 (org-load-modules-maybe)
3089 (easy-menu-add org-org-menu)
3090 (easy-menu-add org-tbl-menu)
3091 (org-install-agenda-files-menu)
3092 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3093 (org-add-to-invisibility-spec '(org-cwidth))
3094 (when (featurep 'xemacs)
3095 (org-set-local 'line-move-ignore-invisible t))
3096 (org-set-local 'outline-regexp org-outline-regexp)
3097 (org-set-local 'outline-level 'org-outline-level)
3098 (when (and org-ellipsis
3099 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3100 (fboundp 'make-glyph-code))
3101 (unless org-display-table
3102 (setq org-display-table (make-display-table)))
3103 (set-display-table-slot
3104 org-display-table 4
3105 (vconcat (mapcar
3106 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3107 org-ellipsis)))
3108 (if (stringp org-ellipsis) org-ellipsis "..."))))
3109 (setq buffer-display-table org-display-table))
3110 (org-set-regexps-and-options)
3111 ;; Calc embedded
3112 (org-set-local 'calc-embedded-open-mode "# ")
3113 (modify-syntax-entry ?# "<")
3114 (modify-syntax-entry ?@ "w")
3115 (if org-startup-truncated (setq truncate-lines t))
3116 (org-set-local 'font-lock-unfontify-region-function
3117 'org-unfontify-region)
3118 ;; Activate before-change-function
3119 (org-set-local 'org-table-may-need-update t)
3120 (org-add-hook 'before-change-functions 'org-before-change-function nil
3121 'local)
3122 ;; Check for running clock before killing a buffer
3123 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3124 ;; Paragraphs and auto-filling
3125 (org-set-autofill-regexps)
3126 (setq indent-line-function 'org-indent-line-function)
3127 (org-update-radio-target-regexp)
3129 ;; Comment characters
3130 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3131 (org-set-local 'comment-padding " ")
3133 ;; Align options lines
3134 (org-set-local
3135 'align-mode-rules-list
3136 '((org-in-buffer-settings
3137 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3138 (modes . '(org-mode)))))
3140 ;; Imenu
3141 (org-set-local 'imenu-create-index-function
3142 'org-imenu-get-tree)
3144 ;; Make isearch reveal context
3145 (if (or (featurep 'xemacs)
3146 (not (boundp 'outline-isearch-open-invisible-function)))
3147 ;; Emacs 21 and XEmacs make use of the hook
3148 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3149 ;; Emacs 22 deals with this through a special variable
3150 (org-set-local 'outline-isearch-open-invisible-function
3151 (lambda (&rest ignore) (org-show-context 'isearch))))
3153 ;; If empty file that did not turn on org-mode automatically, make it to.
3154 (if (and org-insert-mode-line-in-empty-file
3155 (interactive-p)
3156 (= (point-min) (point-max)))
3157 (insert "# -*- mode: org -*-\n\n"))
3159 (unless org-inhibit-startup
3160 (when org-startup-align-all-tables
3161 (let ((bmp (buffer-modified-p)))
3162 (org-table-map-tables 'org-table-align)
3163 (set-buffer-modified-p bmp)))
3164 (org-set-startup-visibility)))
3166 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3168 (defun org-current-time ()
3169 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3170 (if (> (car org-time-stamp-rounding-minutes) 1)
3171 (let ((r (car org-time-stamp-rounding-minutes))
3172 (time (decode-time)))
3173 (apply 'encode-time
3174 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3175 (nthcdr 2 time))))
3176 (current-time)))
3178 ;;;; Font-Lock stuff, including the activators
3180 (defvar org-mouse-map (make-sparse-keymap))
3181 (org-defkey org-mouse-map
3182 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3183 (org-defkey org-mouse-map
3184 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3185 (when org-mouse-1-follows-link
3186 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3187 (when org-tab-follows-link
3188 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3189 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3190 (when org-return-follows-link
3191 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3192 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3194 (require 'font-lock)
3196 (defconst org-non-link-chars "]\t\n\r<>")
3197 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3198 "shell" "elisp"))
3199 (defvar org-link-types-re nil
3200 "Matches a link that has a url-like prefix like \"http:\"")
3201 (defvar org-link-re-with-space nil
3202 "Matches a link with spaces, optional angular brackets around it.")
3203 (defvar org-link-re-with-space2 nil
3204 "Matches a link with spaces, optional angular brackets around it.")
3205 (defvar org-angle-link-re nil
3206 "Matches link with angular brackets, spaces are allowed.")
3207 (defvar org-plain-link-re nil
3208 "Matches plain link, without spaces.")
3209 (defvar org-bracket-link-regexp nil
3210 "Matches a link in double brackets.")
3211 (defvar org-bracket-link-analytic-regexp nil
3212 "Regular expression used to analyze links.
3213 Here is what the match groups contain after a match:
3214 1: http:
3215 2: http
3216 3: path
3217 4: [desc]
3218 5: desc")
3219 (defvar org-any-link-re nil
3220 "Regular expression matching any link.")
3222 (defun org-make-link-regexps ()
3223 "Update the link regular expressions.
3224 This should be called after the variable `org-link-types' has changed."
3225 (setq org-link-types-re
3226 (concat
3227 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3228 org-link-re-with-space
3229 (concat
3230 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3231 "\\([^" org-non-link-chars " ]"
3232 "[^" org-non-link-chars "]*"
3233 "[^" org-non-link-chars " ]\\)>?")
3234 org-link-re-with-space2
3235 (concat
3236 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3237 "\\([^" org-non-link-chars " ]"
3238 "[^]\t\n\r]*"
3239 "[^" org-non-link-chars " ]\\)>?")
3240 org-angle-link-re
3241 (concat
3242 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3243 "\\([^" org-non-link-chars " ]"
3244 "[^" org-non-link-chars "]*"
3245 "\\)>")
3246 org-plain-link-re
3247 (concat
3248 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3249 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3250 org-bracket-link-regexp
3251 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3252 org-bracket-link-analytic-regexp
3253 (concat
3254 "\\[\\["
3255 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3256 "\\([^]]+\\)"
3257 "\\]"
3258 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3259 "\\]")
3260 org-any-link-re
3261 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3262 org-angle-link-re "\\)\\|\\("
3263 org-plain-link-re "\\)")))
3265 (org-make-link-regexps)
3267 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3268 "Regular expression for fast time stamp matching.")
3269 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3270 "Regular expression for fast time stamp matching.")
3271 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3272 "Regular expression matching time strings for analysis.
3273 This one does not require the space after the date, so it can be used
3274 on a string that terminates immediately after the date.")
3275 (defconst org-ts-regexp1 "\\(\\([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 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3278 "Regular expression matching time stamps, with groups.")
3279 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3280 "Regular expression matching time stamps (also [..]), with groups.")
3281 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3282 "Regular expression matching a time stamp range.")
3283 (defconst org-tr-regexp-both
3284 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3285 "Regular expression matching a time stamp range.")
3286 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3287 org-ts-regexp "\\)?")
3288 "Regular expression matching a time stamp or time stamp range.")
3289 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3290 org-ts-regexp-both "\\)?")
3291 "Regular expression matching a time stamp or time stamp range.
3292 The time stamps may be either active or inactive.")
3294 (defvar org-emph-face nil)
3296 (defun org-do-emphasis-faces (limit)
3297 "Run through the buffer and add overlays to links."
3298 (let (rtn)
3299 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3300 (if (not (= (char-after (match-beginning 3))
3301 (char-after (match-beginning 4))))
3302 (progn
3303 (setq rtn t)
3304 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3305 'face
3306 (nth 1 (assoc (match-string 3)
3307 org-emphasis-alist)))
3308 (add-text-properties (match-beginning 2) (match-end 2)
3309 '(font-lock-multiline t))
3310 (when org-hide-emphasis-markers
3311 (add-text-properties (match-end 4) (match-beginning 5)
3312 '(invisible org-link))
3313 (add-text-properties (match-beginning 3) (match-end 3)
3314 '(invisible org-link)))))
3315 (backward-char 1))
3316 rtn))
3318 (defun org-emphasize (&optional char)
3319 "Insert or change an emphasis, i.e. a font like bold or italic.
3320 If there is an active region, change that region to a new emphasis.
3321 If there is no region, just insert the marker characters and position
3322 the cursor between them.
3323 CHAR should be either the marker character, or the first character of the
3324 HTML tag associated with that emphasis. If CHAR is a space, the means
3325 to remove the emphasis of the selected region.
3326 If char is not given (for example in an interactive call) it
3327 will be prompted for."
3328 (interactive)
3329 (let ((eal org-emphasis-alist) e det
3330 (erc org-emphasis-regexp-components)
3331 (prompt "")
3332 (string "") beg end move tag c s)
3333 (if (org-region-active-p)
3334 (setq beg (region-beginning) end (region-end)
3335 string (buffer-substring beg end))
3336 (setq move t))
3338 (while (setq e (pop eal))
3339 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3340 c (aref tag 0))
3341 (push (cons c (string-to-char (car e))) det)
3342 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3343 (substring tag 1)))))
3344 (unless char
3345 (message "%s" (concat "Emphasis marker or tag:" prompt))
3346 (setq char (read-char-exclusive)))
3347 (setq char (or (cdr (assoc char det)) char))
3348 (if (equal char ?\ )
3349 (setq s "" move nil)
3350 (unless (assoc (char-to-string char) org-emphasis-alist)
3351 (error "No such emphasis marker: \"%c\"" char))
3352 (setq s (char-to-string char)))
3353 (while (and (> (length string) 1)
3354 (equal (substring string 0 1) (substring string -1))
3355 (assoc (substring string 0 1) org-emphasis-alist))
3356 (setq string (substring string 1 -1)))
3357 (setq string (concat s string s))
3358 (if beg (delete-region beg end))
3359 (unless (or (bolp)
3360 (string-match (concat "[" (nth 0 erc) "\n]")
3361 (char-to-string (char-before (point)))))
3362 (insert " "))
3363 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3364 (char-to-string (char-after (point))))
3365 (insert " ") (backward-char 1))
3366 (insert string)
3367 (and move (backward-char 1))))
3369 (defconst org-nonsticky-props
3370 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3373 (defun org-activate-plain-links (limit)
3374 "Run through the buffer and add overlays to links."
3375 (catch 'exit
3376 (let (f)
3377 (while (re-search-forward org-plain-link-re limit t)
3378 (setq f (get-text-property (match-beginning 0) 'face))
3379 (if (or (eq f 'org-tag)
3380 (and (listp f) (memq 'org-tag f)))
3382 (add-text-properties (match-beginning 0) (match-end 0)
3383 (list 'mouse-face 'highlight
3384 'rear-nonsticky org-nonsticky-props
3385 'keymap org-mouse-map
3387 (throw 'exit t))))))
3389 (defun org-activate-code (limit)
3390 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3391 (unless (get-text-property (match-beginning 1) 'face)
3392 (remove-text-properties (match-beginning 0) (match-end 0)
3393 '(display t invisible t intangible t))
3394 t)))
3396 (defun org-activate-angle-links (limit)
3397 "Run through the buffer and add overlays to links."
3398 (if (re-search-forward org-angle-link-re limit t)
3399 (progn
3400 (add-text-properties (match-beginning 0) (match-end 0)
3401 (list 'mouse-face 'highlight
3402 'rear-nonsticky org-nonsticky-props
3403 'keymap org-mouse-map
3405 t)))
3407 (defun org-activate-bracket-links (limit)
3408 "Run through the buffer and add overlays to bracketed links."
3409 (if (re-search-forward org-bracket-link-regexp limit t)
3410 (let* ((help (concat "LINK: "
3411 (org-match-string-no-properties 1)))
3412 ;; FIXME: above we should remove the escapes.
3413 ;; but that requires another match, protecting match data,
3414 ;; a lot of overhead for font-lock.
3415 (ip (org-maybe-intangible
3416 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3417 'keymap org-mouse-map 'mouse-face 'highlight
3418 'font-lock-multiline t 'help-echo help)))
3419 (vp (list 'rear-nonsticky org-nonsticky-props
3420 'keymap org-mouse-map 'mouse-face 'highlight
3421 ' font-lock-multiline t 'help-echo help)))
3422 ;; We need to remove the invisible property here. Table narrowing
3423 ;; may have made some of this invisible.
3424 (remove-text-properties (match-beginning 0) (match-end 0)
3425 '(invisible nil))
3426 (if (match-end 3)
3427 (progn
3428 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3429 (add-text-properties (match-beginning 3) (match-end 3) vp)
3430 (add-text-properties (match-end 3) (match-end 0) ip))
3431 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3432 (add-text-properties (match-beginning 1) (match-end 1) vp)
3433 (add-text-properties (match-end 1) (match-end 0) ip))
3434 t)))
3436 (defun org-activate-dates (limit)
3437 "Run through the buffer and add overlays to dates."
3438 (if (re-search-forward org-tsr-regexp-both limit t)
3439 (progn
3440 (add-text-properties (match-beginning 0) (match-end 0)
3441 (list 'mouse-face 'highlight
3442 'rear-nonsticky org-nonsticky-props
3443 'keymap org-mouse-map))
3444 (when org-display-custom-times
3445 (if (match-end 3)
3446 (org-display-custom-time (match-beginning 3) (match-end 3)))
3447 (org-display-custom-time (match-beginning 1) (match-end 1)))
3448 t)))
3450 (defvar org-target-link-regexp nil
3451 "Regular expression matching radio targets in plain text.")
3452 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3453 "Regular expression matching a link target.")
3454 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3455 "Regular expression matching a radio target.")
3456 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3457 "Regular expression matching any target.")
3459 (defun org-activate-target-links (limit)
3460 "Run through the buffer and add overlays to target matches."
3461 (when org-target-link-regexp
3462 (let ((case-fold-search t))
3463 (if (re-search-forward org-target-link-regexp limit t)
3464 (progn
3465 (add-text-properties (match-beginning 0) (match-end 0)
3466 (list 'mouse-face 'highlight
3467 'rear-nonsticky org-nonsticky-props
3468 'keymap org-mouse-map
3469 'help-echo "Radio target link"
3470 'org-linked-text t))
3471 t)))))
3473 (defun org-update-radio-target-regexp ()
3474 "Find all radio targets in this file and update the regular expression."
3475 (interactive)
3476 (when (memq 'radio org-activate-links)
3477 (setq org-target-link-regexp
3478 (org-make-target-link-regexp (org-all-targets 'radio)))
3479 (org-restart-font-lock)))
3481 (defun org-hide-wide-columns (limit)
3482 (let (s e)
3483 (setq s (text-property-any (point) (or limit (point-max))
3484 'org-cwidth t))
3485 (when s
3486 (setq e (next-single-property-change s 'org-cwidth))
3487 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3488 (goto-char e)
3489 t)))
3491 (defvar org-latex-and-specials-regexp nil
3492 "Regular expression for highlighting export special stuff.")
3493 (defvar org-match-substring-regexp)
3494 (defvar org-match-substring-with-braces-regexp)
3495 (defvar org-export-html-special-string-regexps)
3497 (defun org-compute-latex-and-specials-regexp ()
3498 "Compute regular expression for stuff treated specially by exporters."
3499 (if (not org-highlight-latex-fragments-and-specials)
3500 (org-set-local 'org-latex-and-specials-regexp nil)
3501 (require 'org-exp)
3502 (let*
3503 ((matchers (plist-get org-format-latex-options :matchers))
3504 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3505 org-latex-regexps)))
3506 (options (org-combine-plists (org-default-export-plist)
3507 (org-infile-export-plist)))
3508 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3509 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3510 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3511 (org-export-html-expand (plist-get options :expand-quoted-html))
3512 (org-export-with-special-strings (plist-get options :special-strings))
3513 (re-sub
3514 (cond
3515 ((equal org-export-with-sub-superscripts '{})
3516 (list org-match-substring-with-braces-regexp))
3517 (org-export-with-sub-superscripts
3518 (list org-match-substring-regexp))
3519 (t nil)))
3520 (re-latex
3521 (if org-export-with-LaTeX-fragments
3522 (mapcar (lambda (x) (nth 1 x)) latexs)))
3523 (re-macros
3524 (if org-export-with-TeX-macros
3525 (list (concat "\\\\"
3526 (regexp-opt
3527 (append (mapcar 'car org-html-entities)
3528 (if (boundp 'org-latex-entities)
3529 org-latex-entities nil))
3530 'words))) ; FIXME
3532 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3533 (re-special (if org-export-with-special-strings
3534 (mapcar (lambda (x) (car x))
3535 org-export-html-special-string-regexps)))
3536 (re-rest
3537 (delq nil
3538 (list
3539 (if org-export-html-expand "@<[^>\n]+>")
3540 ))))
3541 (org-set-local
3542 'org-latex-and-specials-regexp
3543 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3544 re-rest) "\\|")))))
3546 (defun org-do-latex-and-special-faces (limit)
3547 "Run through the buffer and add overlays to links."
3548 (when org-latex-and-specials-regexp
3549 (let (rtn d)
3550 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3551 limit t))
3552 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3553 'face))
3554 '(org-code org-verbatim underline)))
3555 (progn
3556 (setq rtn t
3557 d (cond ((member (char-after (1+ (match-beginning 0)))
3558 '(?_ ?^)) 1)
3559 (t 0)))
3560 (font-lock-prepend-text-property
3561 (+ d (match-beginning 0)) (match-end 0)
3562 'face 'org-latex-and-export-specials)
3563 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3564 '(font-lock-multiline t)))))
3565 rtn)))
3567 (defun org-restart-font-lock ()
3568 "Restart font-lock-mode, to force refontification."
3569 (when (and (boundp 'font-lock-mode) font-lock-mode)
3570 (font-lock-mode -1)
3571 (font-lock-mode 1)))
3573 (defun org-all-targets (&optional radio)
3574 "Return a list of all targets in this file.
3575 With optional argument RADIO, only find radio targets."
3576 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3577 rtn)
3578 (save-excursion
3579 (goto-char (point-min))
3580 (while (re-search-forward re nil t)
3581 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3582 rtn)))
3584 (defun org-make-target-link-regexp (targets)
3585 "Make regular expression matching all strings in TARGETS.
3586 The regular expression finds the targets also if there is a line break
3587 between words."
3588 (and targets
3589 (concat
3590 "\\<\\("
3591 (mapconcat
3592 (lambda (x)
3593 (while (string-match " +" x)
3594 (setq x (replace-match "\\s-+" t t x)))
3596 targets
3597 "\\|")
3598 "\\)\\>")))
3600 (defun org-activate-tags (limit)
3601 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3602 (progn
3603 (add-text-properties (match-beginning 1) (match-end 1)
3604 (list 'mouse-face 'highlight
3605 'rear-nonsticky org-nonsticky-props
3606 'keymap org-mouse-map))
3607 t)))
3609 (defun org-outline-level ()
3610 (save-excursion
3611 (looking-at outline-regexp)
3612 (if (match-beginning 1)
3613 (+ (org-get-string-indentation (match-string 1)) 1000)
3614 (1- (- (match-end 0) (match-beginning 0))))))
3616 (defvar org-font-lock-keywords nil)
3618 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3619 "Regular expression matching a property line.")
3621 (defvar org-font-lock-hook nil
3622 "Functions to be called for special font loch stuff.")
3624 (defun org-font-lock-hook (limit)
3625 (run-hook-with-args 'org-font-lock-hook limit))
3627 (defun org-set-font-lock-defaults ()
3628 (let* ((em org-fontify-emphasized-text)
3629 (lk org-activate-links)
3630 (org-font-lock-extra-keywords
3631 (list
3632 ;; Call the hook
3633 '(org-font-lock-hook)
3634 ;; Headlines
3635 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3636 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3637 ;; Table lines
3638 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3639 (1 'org-table t))
3640 ;; Table internals
3641 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3642 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3643 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3644 ;; Drawers
3645 (list org-drawer-regexp '(0 'org-special-keyword t))
3646 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3647 ;; Properties
3648 (list org-property-re
3649 '(1 'org-special-keyword t)
3650 '(3 'org-property-value t))
3651 (if org-format-transports-properties-p
3652 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3653 ;; Links
3654 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3655 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3656 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3657 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3658 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3659 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3660 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3661 '(org-hide-wide-columns (0 nil append))
3662 ;; TODO lines
3663 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3664 '(1 (org-get-todo-face 1) t))
3665 ;; DONE
3666 (if org-fontify-done-headline
3667 (list (concat "^[*]+ +\\<\\("
3668 (mapconcat 'regexp-quote org-done-keywords "\\|")
3669 "\\)\\(.*\\)")
3670 '(2 'org-headline-done t))
3671 nil)
3672 ;; Priorities
3673 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3674 ;; Special keywords
3675 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3676 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3677 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3678 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3679 ;; Emphasis
3680 (if em
3681 (if (featurep 'xemacs)
3682 '(org-do-emphasis-faces (0 nil append))
3683 '(org-do-emphasis-faces)))
3684 ;; Checkboxes
3685 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3686 2 'bold prepend)
3687 (if org-provide-checkbox-statistics
3688 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3689 (0 (org-get-checkbox-statistics-face) t)))
3690 ;; Description list items
3691 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*?\\) ::"
3692 2 'bold prepend)
3693 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3694 '(1 'org-archived prepend))
3695 ;; Specials
3696 '(org-do-latex-and-special-faces)
3697 ;; Code
3698 '(org-activate-code (1 'org-code t))
3699 ;; COMMENT
3700 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3701 "\\|" org-quote-string "\\)\\>")
3702 '(1 'org-special-keyword t))
3703 '("^#.*" (0 'font-lock-comment-face t))
3705 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3706 ;; Now set the full font-lock-keywords
3707 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3708 (org-set-local 'font-lock-defaults
3709 '(org-font-lock-keywords t nil nil backward-paragraph))
3710 (kill-local-variable 'font-lock-keywords) nil))
3712 (defvar org-m nil)
3713 (defvar org-l nil)
3714 (defvar org-f nil)
3715 (defun org-get-level-face (n)
3716 "Get the right face for match N in font-lock matching of healdines."
3717 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3718 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3719 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3720 (cond
3721 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3722 ((eq n 2) org-f)
3723 (t (if org-level-color-stars-only nil org-f))))
3725 (defun org-get-todo-face (kwd)
3726 "Get the right face for a TODO keyword KWD.
3727 If KWD is a number, get the corresponding match group."
3728 (if (numberp kwd) (setq kwd (match-string kwd)))
3729 (or (cdr (assoc kwd org-todo-keyword-faces))
3730 (and (member kwd org-done-keywords) 'org-done)
3731 'org-todo))
3733 (defun org-unfontify-region (beg end &optional maybe_loudly)
3734 "Remove fontification and activation overlays from links."
3735 (font-lock-default-unfontify-region beg end)
3736 (let* ((buffer-undo-list t)
3737 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3738 (inhibit-modification-hooks t)
3739 deactivate-mark buffer-file-name buffer-file-truename)
3740 (remove-text-properties beg end
3741 '(mouse-face t keymap t org-linked-text t
3742 invisible t intangible t))))
3744 ;;;; Visibility cycling, including org-goto and indirect buffer
3746 ;;; Cycling
3748 (defvar org-cycle-global-status nil)
3749 (make-variable-buffer-local 'org-cycle-global-status)
3750 (defvar org-cycle-subtree-status nil)
3751 (make-variable-buffer-local 'org-cycle-subtree-status)
3753 ;;;###autoload
3754 (defun org-cycle (&optional arg)
3755 "Visibility cycling for Org-mode.
3757 - When this function is called with a prefix argument, rotate the entire
3758 buffer through 3 states (global cycling)
3759 1. OVERVIEW: Show only top-level headlines.
3760 2. CONTENTS: Show all headlines of all levels, but no body text.
3761 3. SHOW ALL: Show everything.
3762 When called with two C-c C-u prefixes, switch to the startup visibility,
3763 determined by the variable `org-startup-folded', and by any VISIBILITY
3764 properties in the buffer.
3766 - When point is at the beginning of a headline, rotate the subtree started
3767 by this line through 3 different states (local cycling)
3768 1. FOLDED: Only the main headline is shown.
3769 2. CHILDREN: The main headline and the direct children are shown.
3770 From this state, you can move to one of the children
3771 and zoom in further.
3772 3. SUBTREE: Show the entire subtree, including body text.
3774 - When there is a numeric prefix, go up to a heading with level ARG, do
3775 a `show-subtree' and return to the previous cursor position. If ARG
3776 is negative, go up that many levels.
3778 - When point is not at the beginning of a headline, execute the global
3779 binding for TAB, which is re-indenting the line. See the option
3780 `org-cycle-emulate-tab' for details.
3782 - Special case: if point is at the beginning of the buffer and there is
3783 no headline in line 1, this function will act as if called with prefix arg.
3784 But only if also the variable `org-cycle-global-at-bob' is t."
3785 (interactive "P")
3786 (org-load-modules-maybe)
3787 (let* ((outline-regexp
3788 (if (and (org-mode-p) org-cycle-include-plain-lists)
3789 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3790 outline-regexp))
3791 (bob-special (and org-cycle-global-at-bob (bobp)
3792 (not (looking-at outline-regexp))))
3793 (org-cycle-hook
3794 (if bob-special
3795 (delq 'org-optimize-window-after-visibility-change
3796 (copy-sequence org-cycle-hook))
3797 org-cycle-hook))
3798 (pos (point)))
3800 (if (or bob-special (equal arg '(4)))
3801 ;; special case: use global cycling
3802 (setq arg t))
3804 (cond
3806 ((equal arg '(16))
3807 (org-set-startup-visibility)
3808 (message "Startup visibility, plus VISIBILITY properties."))
3810 ((org-at-table-p 'any)
3811 ;; Enter the table or move to the next field in the table
3812 (or (org-table-recognize-table.el)
3813 (progn
3814 (if arg (org-table-edit-field t)
3815 (org-table-justify-field-maybe)
3816 (call-interactively 'org-table-next-field)))))
3818 ((eq arg t) ;; Global cycling
3820 (cond
3821 ((and (eq last-command this-command)
3822 (eq org-cycle-global-status 'overview))
3823 ;; We just created the overview - now do table of contents
3824 ;; This can be slow in very large buffers, so indicate action
3825 (message "CONTENTS...")
3826 (org-content)
3827 (message "CONTENTS...done")
3828 (setq org-cycle-global-status 'contents)
3829 (run-hook-with-args 'org-cycle-hook 'contents))
3831 ((and (eq last-command this-command)
3832 (eq org-cycle-global-status 'contents))
3833 ;; We just showed the table of contents - now show everything
3834 (show-all)
3835 (message "SHOW ALL")
3836 (setq org-cycle-global-status 'all)
3837 (run-hook-with-args 'org-cycle-hook 'all))
3840 ;; Default action: go to overview
3841 (org-overview)
3842 (message "OVERVIEW")
3843 (setq org-cycle-global-status 'overview)
3844 (run-hook-with-args 'org-cycle-hook 'overview))))
3846 ((and org-drawers org-drawer-regexp
3847 (save-excursion
3848 (beginning-of-line 1)
3849 (looking-at org-drawer-regexp)))
3850 ;; Toggle block visibility
3851 (org-flag-drawer
3852 (not (get-char-property (match-end 0) 'invisible))))
3854 ((integerp arg)
3855 ;; Show-subtree, ARG levels up from here.
3856 (save-excursion
3857 (org-back-to-heading)
3858 (outline-up-heading (if (< arg 0) (- arg)
3859 (- (funcall outline-level) arg)))
3860 (org-show-subtree)))
3862 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3863 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3864 ;; At a heading: rotate between three different views
3865 (org-back-to-heading)
3866 (let ((goal-column 0) eoh eol eos)
3867 ;; First, some boundaries
3868 (save-excursion
3869 (org-back-to-heading)
3870 (save-excursion
3871 (beginning-of-line 2)
3872 (while (and (not (eobp)) ;; this is like `next-line'
3873 (get-char-property (1- (point)) 'invisible))
3874 (beginning-of-line 2)) (setq eol (point)))
3875 (outline-end-of-heading) (setq eoh (point))
3876 (org-end-of-subtree t)
3877 (unless (eobp)
3878 (skip-chars-forward " \t\n")
3879 (beginning-of-line 1) ; in case this is an item
3881 (setq eos (1- (point))))
3882 ;; Find out what to do next and set `this-command'
3883 (cond
3884 ((= eos eoh)
3885 ;; Nothing is hidden behind this heading
3886 (message "EMPTY ENTRY")
3887 (setq org-cycle-subtree-status nil)
3888 (save-excursion
3889 (goto-char eos)
3890 (outline-next-heading)
3891 (if (org-invisible-p) (org-flag-heading nil))))
3892 ((or (>= eol eos)
3893 (not (string-match "\\S-" (buffer-substring eol eos))))
3894 ;; Entire subtree is hidden in one line: open it
3895 (org-show-entry)
3896 (show-children)
3897 (message "CHILDREN")
3898 (save-excursion
3899 (goto-char eos)
3900 (outline-next-heading)
3901 (if (org-invisible-p) (org-flag-heading nil)))
3902 (setq org-cycle-subtree-status 'children)
3903 (run-hook-with-args 'org-cycle-hook 'children))
3904 ((and (eq last-command this-command)
3905 (eq org-cycle-subtree-status 'children))
3906 ;; We just showed the children, now show everything.
3907 (org-show-subtree)
3908 (message "SUBTREE")
3909 (setq org-cycle-subtree-status 'subtree)
3910 (run-hook-with-args 'org-cycle-hook 'subtree))
3912 ;; Default action: hide the subtree.
3913 (hide-subtree)
3914 (message "FOLDED")
3915 (setq org-cycle-subtree-status 'folded)
3916 (run-hook-with-args 'org-cycle-hook 'folded)))))
3918 ;; TAB emulation
3919 (buffer-read-only (org-back-to-heading))
3921 ((org-try-cdlatex-tab))
3923 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3924 (or (not (bolp))
3925 (not (looking-at outline-regexp))))
3926 (call-interactively (global-key-binding "\t")))
3928 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3929 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3930 (or (and (eq org-cycle-emulate-tab 'white)
3931 (= (match-end 0) (point-at-eol)))
3932 (and (eq org-cycle-emulate-tab 'whitestart)
3933 (>= (match-end 0) pos))))
3935 (eq org-cycle-emulate-tab t))
3936 (call-interactively (global-key-binding "\t")))
3938 (t (save-excursion
3939 (org-back-to-heading)
3940 (org-cycle))))))
3942 ;;;###autoload
3943 (defun org-global-cycle (&optional arg)
3944 "Cycle the global visibility. For details see `org-cycle'.
3945 With C-u prefix arg, switch to startup visibility.
3946 With a numeric prefix, show all headlines up to that level."
3947 (interactive "P")
3948 (let ((org-cycle-include-plain-lists
3949 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3950 (cond
3951 ((integerp arg)
3952 (show-all)
3953 (hide-sublevels arg)
3954 (setq org-cycle-global-status 'contents))
3955 ((equal arg '(4))
3956 (org-set-startup-visibility)
3957 (message "Startup visibility, plus VISIBILITY properties."))
3959 (org-cycle '(4))))))
3961 (defun org-set-startup-visibility ()
3962 "Set the visibility required by startup options and properties."
3963 (cond
3964 ((eq org-startup-folded t)
3965 (org-cycle '(4)))
3966 ((eq org-startup-folded 'content)
3967 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3968 (org-cycle '(4)) (org-cycle '(4)))))
3969 (org-set-visibility-according-to-property 'no-cleanup)
3970 (org-cycle-hide-archived-subtrees 'all)
3971 (org-cycle-hide-drawers 'all)
3972 (org-cycle-show-empty-lines 'all))
3974 (defun org-set-visibility-according-to-property (&optional no-cleanup)
3975 "Switch subtree visibilities according to :VISIBILITY: property."
3976 (interactive)
3977 (let (state)
3978 (save-excursion
3979 (goto-char (point-min))
3980 (while (re-search-forward
3981 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
3982 nil t)
3983 (setq state (match-string 1))
3984 (save-excursion
3985 (org-back-to-heading t)
3986 (hide-subtree)
3987 (org-reveal)
3988 (cond
3989 ((equal state '("fold" "folded"))
3990 (hide-subtree))
3991 ((equal state "children")
3992 (org-show-hidden-entry)
3993 (show-children))
3994 ((equal state "content")
3995 (save-excursion
3996 (save-restriction
3997 (org-narrow-to-subtree)
3998 (org-content))))
3999 ((member state '("all" "showall"))
4000 (show-subtree)))))
4001 (unless no-cleanup
4002 (org-cycle-hide-archived-subtrees 'all)
4003 (org-cycle-hide-drawers 'all)
4004 (org-cycle-show-empty-lines 'all)))))
4006 (defun org-overview ()
4007 "Switch to overview mode, shoing only top-level headlines.
4008 Really, this shows all headlines with level equal or greater than the level
4009 of the first headline in the buffer. This is important, because if the
4010 first headline is not level one, then (hide-sublevels 1) gives confusing
4011 results."
4012 (interactive)
4013 (let ((level (save-excursion
4014 (goto-char (point-min))
4015 (if (re-search-forward (concat "^" outline-regexp) nil t)
4016 (progn
4017 (goto-char (match-beginning 0))
4018 (funcall outline-level))))))
4019 (and level (hide-sublevels level))))
4021 (defun org-content (&optional arg)
4022 "Show all headlines in the buffer, like a table of contents.
4023 With numerical argument N, show content up to level N."
4024 (interactive "P")
4025 (save-excursion
4026 ;; Visit all headings and show their offspring
4027 (and (integerp arg) (org-overview))
4028 (goto-char (point-max))
4029 (catch 'exit
4030 (while (and (progn (condition-case nil
4031 (outline-previous-visible-heading 1)
4032 (error (goto-char (point-min))))
4034 (looking-at outline-regexp))
4035 (if (integerp arg)
4036 (show-children (1- arg))
4037 (show-branches))
4038 (if (bobp) (throw 'exit nil))))))
4041 (defun org-optimize-window-after-visibility-change (state)
4042 "Adjust the window after a change in outline visibility.
4043 This function is the default value of the hook `org-cycle-hook'."
4044 (when (get-buffer-window (current-buffer))
4045 (cond
4046 ; ((eq state 'overview) (org-first-headline-recenter 1))
4047 ; ((eq state 'overview) (org-beginning-of-line))
4048 ((eq state 'content) nil)
4049 ((eq state 'all) nil)
4050 ((eq state 'folded) nil)
4051 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4052 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4054 (defun org-compact-display-after-subtree-move ()
4055 (let (beg end)
4056 (save-excursion
4057 (if (org-up-heading-safe)
4058 (progn
4059 (hide-subtree)
4060 (show-entry)
4061 (show-children)
4062 (org-cycle-show-empty-lines 'children)
4063 (org-cycle-hide-drawers 'children))
4064 (org-overview)))))
4066 (defun org-cycle-show-empty-lines (state)
4067 "Show empty lines above all visible headlines.
4068 The region to be covered depends on STATE when called through
4069 `org-cycle-hook'. Lisp program can use t for STATE to get the
4070 entire buffer covered. Note that an empty line is only shown if there
4071 are at least `org-cycle-separator-lines' empty lines before the headeline."
4072 (when (> org-cycle-separator-lines 0)
4073 (save-excursion
4074 (let* ((n org-cycle-separator-lines)
4075 (re (cond
4076 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4077 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4078 (t (let ((ns (number-to-string (- n 2))))
4079 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4080 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4081 beg end)
4082 (cond
4083 ((memq state '(overview contents t))
4084 (setq beg (point-min) end (point-max)))
4085 ((memq state '(children folded))
4086 (setq beg (point) end (progn (org-end-of-subtree t t)
4087 (beginning-of-line 2)
4088 (point)))))
4089 (when beg
4090 (goto-char beg)
4091 (while (re-search-forward re end t)
4092 (if (not (get-char-property (match-end 1) 'invisible))
4093 (outline-flag-region
4094 (match-beginning 1) (match-end 1) nil)))))))
4095 ;; Never hide empty lines at the end of the file.
4096 (save-excursion
4097 (goto-char (point-max))
4098 (outline-previous-heading)
4099 (outline-end-of-heading)
4100 (if (and (looking-at "[ \t\n]+")
4101 (= (match-end 0) (point-max)))
4102 (outline-flag-region (point) (match-end 0) nil))))
4104 (defun org-cycle-hide-drawers (state)
4105 "Re-hide all drawers after a visibility state change."
4106 (when (and (org-mode-p)
4107 (not (memq state '(overview folded))))
4108 (save-excursion
4109 (let* ((globalp (memq state '(contents all)))
4110 (beg (if globalp (point-min) (point)))
4111 (end (if globalp (point-max) (org-end-of-subtree t))))
4112 (goto-char beg)
4113 (while (re-search-forward org-drawer-regexp end t)
4114 (org-flag-drawer t))))))
4116 (defun org-flag-drawer (flag)
4117 (save-excursion
4118 (beginning-of-line 1)
4119 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4120 (let ((b (match-end 0))
4121 (outline-regexp org-outline-regexp))
4122 (if (re-search-forward
4123 "^[ \t]*:END:"
4124 (save-excursion (outline-next-heading) (point)) t)
4125 (outline-flag-region b (point-at-eol) flag)
4126 (error ":END: line missing"))))))
4128 (defun org-subtree-end-visible-p ()
4129 "Is the end of the current subtree visible?"
4130 (pos-visible-in-window-p
4131 (save-excursion (org-end-of-subtree t) (point))))
4133 (defun org-first-headline-recenter (&optional N)
4134 "Move cursor to the first headline and recenter the headline.
4135 Optional argument N means, put the headline into the Nth line of the window."
4136 (goto-char (point-min))
4137 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4138 (beginning-of-line)
4139 (recenter (prefix-numeric-value N))))
4141 ;;; Org-goto
4143 (defvar org-goto-window-configuration nil)
4144 (defvar org-goto-marker nil)
4145 (defvar org-goto-map
4146 (let ((map (make-sparse-keymap)))
4147 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4148 (while (setq cmd (pop cmds))
4149 (substitute-key-definition cmd cmd map global-map)))
4150 (suppress-keymap map)
4151 (org-defkey map "\C-m" 'org-goto-ret)
4152 (org-defkey map [(return)] 'org-goto-ret)
4153 (org-defkey map [(left)] 'org-goto-left)
4154 (org-defkey map [(right)] 'org-goto-right)
4155 (org-defkey map [(control ?g)] 'org-goto-quit)
4156 (org-defkey map "\C-i" 'org-cycle)
4157 (org-defkey map [(tab)] 'org-cycle)
4158 (org-defkey map [(down)] 'outline-next-visible-heading)
4159 (org-defkey map [(up)] 'outline-previous-visible-heading)
4160 (if org-goto-auto-isearch
4161 (if (fboundp 'define-key-after)
4162 (define-key-after map [t] 'org-goto-local-auto-isearch)
4163 nil)
4164 (org-defkey map "q" 'org-goto-quit)
4165 (org-defkey map "n" 'outline-next-visible-heading)
4166 (org-defkey map "p" 'outline-previous-visible-heading)
4167 (org-defkey map "f" 'outline-forward-same-level)
4168 (org-defkey map "b" 'outline-backward-same-level)
4169 (org-defkey map "u" 'outline-up-heading))
4170 (org-defkey map "/" 'org-occur)
4171 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4172 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4173 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4174 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4175 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4176 map))
4178 (defconst org-goto-help
4179 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4180 RET=jump to location [Q]uit and return to previous location
4181 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4183 (defvar org-goto-start-pos) ; dynamically scoped parameter
4185 (defun org-goto (&optional alternative-interface)
4186 "Look up a different location in the current file, keeping current visibility.
4188 When you want look-up or go to a different location in a document, the
4189 fastest way is often to fold the entire buffer and then dive into the tree.
4190 This method has the disadvantage, that the previous location will be folded,
4191 which may not be what you want.
4193 This command works around this by showing a copy of the current buffer
4194 in an indirect buffer, in overview mode. You can dive into the tree in
4195 that copy, use org-occur and incremental search to find a location.
4196 When pressing RET or `Q', the command returns to the original buffer in
4197 which the visibility is still unchanged. After RET is will also jump to
4198 the location selected in the indirect buffer and expose the
4199 the headline hierarchy above."
4200 (interactive "P")
4201 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4202 (org-refile-use-outline-path t)
4203 (interface
4204 (if (not alternative-interface)
4205 org-goto-interface
4206 (if (eq org-goto-interface 'outline)
4207 'outline-path-completion
4208 'outline)))
4209 (org-goto-start-pos (point))
4210 (selected-point
4211 (if (eq interface 'outline)
4212 (car (org-get-location (current-buffer) org-goto-help))
4213 (nth 3 (org-refile-get-location "Goto: ")))))
4214 (if selected-point
4215 (progn
4216 (org-mark-ring-push org-goto-start-pos)
4217 (goto-char selected-point)
4218 (if (or (org-invisible-p) (org-invisible-p2))
4219 (org-show-context 'org-goto)))
4220 (message "Quit"))))
4222 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4223 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4224 (defvar org-goto-local-auto-isearch-map) ; defined below
4226 (defun org-get-location (buf help)
4227 "Let the user select a location in the Org-mode buffer BUF.
4228 This function uses a recursive edit. It returns the selected position
4229 or nil."
4230 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4231 (isearch-hide-immediately nil)
4232 (isearch-search-fun-function
4233 (lambda () 'org-goto-local-search-forward-headings))
4234 (org-goto-selected-point org-goto-exit-command))
4235 (save-excursion
4236 (save-window-excursion
4237 (delete-other-windows)
4238 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4239 (switch-to-buffer
4240 (condition-case nil
4241 (make-indirect-buffer (current-buffer) "*org-goto*")
4242 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4243 (with-output-to-temp-buffer "*Help*"
4244 (princ help))
4245 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4246 (setq buffer-read-only nil)
4247 (let ((org-startup-truncated t)
4248 (org-startup-folded nil)
4249 (org-startup-align-all-tables nil))
4250 (org-mode)
4251 (org-overview))
4252 (setq buffer-read-only t)
4253 (if (and (boundp 'org-goto-start-pos)
4254 (integer-or-marker-p org-goto-start-pos))
4255 (let ((org-show-hierarchy-above t)
4256 (org-show-siblings t)
4257 (org-show-following-heading t))
4258 (goto-char org-goto-start-pos)
4259 (and (org-invisible-p) (org-show-context)))
4260 (goto-char (point-min)))
4261 (org-beginning-of-line)
4262 (message "Select location and press RET")
4263 (use-local-map org-goto-map)
4264 (recursive-edit)
4266 (kill-buffer "*org-goto*")
4267 (cons org-goto-selected-point org-goto-exit-command)))
4269 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4270 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4271 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4272 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4274 (defun org-goto-local-search-forward-headings (string bound noerror)
4275 "Search and make sure that anu matches are in headlines."
4276 (catch 'return
4277 (while (search-forward string bound noerror)
4278 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4279 (and (member :headline context)
4280 (not (member :tags context))))
4281 (throw 'return (point))))))
4283 (defun org-goto-local-auto-isearch ()
4284 "Start isearch."
4285 (interactive)
4286 (goto-char (point-min))
4287 (let ((keys (this-command-keys)))
4288 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4289 (isearch-mode t)
4290 (isearch-process-search-char (string-to-char keys)))))
4292 (defun org-goto-ret (&optional arg)
4293 "Finish `org-goto' by going to the new location."
4294 (interactive "P")
4295 (setq org-goto-selected-point (point)
4296 org-goto-exit-command 'return)
4297 (throw 'exit nil))
4299 (defun org-goto-left ()
4300 "Finish `org-goto' by going to the new location."
4301 (interactive)
4302 (if (org-on-heading-p)
4303 (progn
4304 (beginning-of-line 1)
4305 (setq org-goto-selected-point (point)
4306 org-goto-exit-command 'left)
4307 (throw 'exit nil))
4308 (error "Not on a heading")))
4310 (defun org-goto-right ()
4311 "Finish `org-goto' by going to the new location."
4312 (interactive)
4313 (if (org-on-heading-p)
4314 (progn
4315 (setq org-goto-selected-point (point)
4316 org-goto-exit-command 'right)
4317 (throw 'exit nil))
4318 (error "Not on a heading")))
4320 (defun org-goto-quit ()
4321 "Finish `org-goto' without cursor motion."
4322 (interactive)
4323 (setq org-goto-selected-point nil)
4324 (setq org-goto-exit-command 'quit)
4325 (throw 'exit nil))
4327 ;;; Indirect buffer display of subtrees
4329 (defvar org-indirect-dedicated-frame nil
4330 "This is the frame being used for indirect tree display.")
4331 (defvar org-last-indirect-buffer nil)
4333 (defun org-tree-to-indirect-buffer (&optional arg)
4334 "Create indirect buffer and narrow it to current subtree.
4335 With numerical prefix ARG, go up to this level and then take that tree.
4336 If ARG is negative, go up that many levels.
4337 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4338 indirect buffer previously made with this command, to avoid proliferation of
4339 indirect buffers. However, when you call the command with a `C-u' prefix, or
4340 when `org-indirect-buffer-display' is `new-frame', the last buffer
4341 is kept so that you can work with several indirect buffers at the same time.
4342 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4343 requests that a new frame be made for the new buffer, so that the dedicated
4344 frame is not changed."
4345 (interactive "P")
4346 (let ((cbuf (current-buffer))
4347 (cwin (selected-window))
4348 (pos (point))
4349 beg end level heading ibuf)
4350 (save-excursion
4351 (org-back-to-heading t)
4352 (when (numberp arg)
4353 (setq level (org-outline-level))
4354 (if (< arg 0) (setq arg (+ level arg)))
4355 (while (> (setq level (org-outline-level)) arg)
4356 (outline-up-heading 1 t)))
4357 (setq beg (point)
4358 heading (org-get-heading))
4359 (org-end-of-subtree t) (setq end (point)))
4360 (if (and (buffer-live-p org-last-indirect-buffer)
4361 (not (eq org-indirect-buffer-display 'new-frame))
4362 (not arg))
4363 (kill-buffer org-last-indirect-buffer))
4364 (setq ibuf (org-get-indirect-buffer cbuf)
4365 org-last-indirect-buffer ibuf)
4366 (cond
4367 ((or (eq org-indirect-buffer-display 'new-frame)
4368 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4369 (select-frame (make-frame))
4370 (delete-other-windows)
4371 (switch-to-buffer ibuf)
4372 (org-set-frame-title heading))
4373 ((eq org-indirect-buffer-display 'dedicated-frame)
4374 (raise-frame
4375 (select-frame (or (and org-indirect-dedicated-frame
4376 (frame-live-p org-indirect-dedicated-frame)
4377 org-indirect-dedicated-frame)
4378 (setq org-indirect-dedicated-frame (make-frame)))))
4379 (delete-other-windows)
4380 (switch-to-buffer ibuf)
4381 (org-set-frame-title (concat "Indirect: " heading)))
4382 ((eq org-indirect-buffer-display 'current-window)
4383 (switch-to-buffer ibuf))
4384 ((eq org-indirect-buffer-display 'other-window)
4385 (pop-to-buffer ibuf))
4386 (t (error "Invalid value.")))
4387 (if (featurep 'xemacs)
4388 (save-excursion (org-mode) (turn-on-font-lock)))
4389 (narrow-to-region beg end)
4390 (show-all)
4391 (goto-char pos)
4392 (and (window-live-p cwin) (select-window cwin))))
4394 (defun org-get-indirect-buffer (&optional buffer)
4395 (setq buffer (or buffer (current-buffer)))
4396 (let ((n 1) (base (buffer-name buffer)) bname)
4397 (while (buffer-live-p
4398 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4399 (setq n (1+ n)))
4400 (condition-case nil
4401 (make-indirect-buffer buffer bname 'clone)
4402 (error (make-indirect-buffer buffer bname)))))
4404 (defun org-set-frame-title (title)
4405 "Set the title of the current frame to the string TITLE."
4406 ;; FIXME: how to name a single frame in XEmacs???
4407 (unless (featurep 'xemacs)
4408 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4410 ;;;; Structure editing
4412 ;;; Inserting headlines
4414 (defun org-insert-heading (&optional force-heading)
4415 "Insert a new heading or item with same depth at point.
4416 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4417 If point is at the beginning of a headline, insert a sibling before the
4418 current headline. If point is not at the beginning, do not split the line,
4419 but create the new hedline after the current line."
4420 (interactive "P")
4421 (if (= (buffer-size) 0)
4422 (insert "\n* ")
4423 (when (or force-heading (not (org-insert-item)))
4424 (let* ((head (save-excursion
4425 (condition-case nil
4426 (progn
4427 (org-back-to-heading)
4428 (match-string 0))
4429 (error "*"))))
4430 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4431 pos)
4432 (cond
4433 ((and (org-on-heading-p) (bolp)
4434 (or (bobp)
4435 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4436 ;; insert before the current line
4437 (open-line (if blank 2 1)))
4438 ((and (bolp)
4439 (or (bobp)
4440 (save-excursion
4441 (backward-char 1) (not (org-invisible-p)))))
4442 ;; insert right here
4443 nil)
4445 ;; in the middle of the line
4446 (org-show-entry)
4447 (let ((split
4448 (org-get-alist-option org-M-RET-may-split-line 'headline))
4449 tags pos)
4450 (if (org-on-heading-p)
4451 (progn
4452 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4453 (setq tags (and (match-end 2) (match-string 2)))
4454 (and (match-end 1)
4455 (delete-region (match-beginning 1) (match-end 1)))
4456 (setq pos (point-at-bol))
4457 (or split (end-of-line 1))
4458 (delete-horizontal-space)
4459 (newline (if blank 2 1))
4460 (when tags
4461 (save-excursion
4462 (goto-char pos)
4463 (end-of-line 1)
4464 (insert " " tags)
4465 (org-set-tags nil 'align))))
4466 (or split (end-of-line 1))
4467 (newline (if blank 2 1))))))
4468 (insert head) (just-one-space)
4469 (setq pos (point))
4470 (end-of-line 1)
4471 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4472 (run-hooks 'org-insert-heading-hook)))))
4474 (defun org-get-heading (&optional no-tags)
4475 "Return the heading of the current entry, without the stars."
4476 (save-excursion
4477 (org-back-to-heading t)
4478 (if (looking-at
4479 (if no-tags
4480 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4481 "\\*+[ \t]+\\([^\r\n]*\\)"))
4482 (match-string 1) "")))
4484 (defun org-insert-heading-after-current ()
4485 "Insert a new heading with same level as current, after current subtree."
4486 (interactive)
4487 (org-back-to-heading)
4488 (org-insert-heading)
4489 (org-move-subtree-down)
4490 (end-of-line 1))
4492 (defun org-insert-todo-heading (arg)
4493 "Insert a new heading with the same level and TODO state as current heading.
4494 If the heading has no TODO state, or if the state is DONE, use the first
4495 state (TODO by default). Also with prefix arg, force first state."
4496 (interactive "P")
4497 (when (not (org-insert-item 'checkbox))
4498 (org-insert-heading)
4499 (save-excursion
4500 (org-back-to-heading)
4501 (outline-previous-heading)
4502 (looking-at org-todo-line-regexp))
4503 (if (or arg
4504 (not (match-beginning 2))
4505 (member (match-string 2) org-done-keywords))
4506 (insert (car org-todo-keywords-1) " ")
4507 (insert (match-string 2) " "))))
4509 (defun org-insert-subheading (arg)
4510 "Insert a new subheading and demote it.
4511 Works for outline headings and for plain lists alike."
4512 (interactive "P")
4513 (org-insert-heading arg)
4514 (cond
4515 ((org-on-heading-p) (org-do-demote))
4516 ((org-at-item-p) (org-indent-item 1))))
4518 (defun org-insert-todo-subheading (arg)
4519 "Insert a new subheading with TODO keyword or checkbox and demote it.
4520 Works for outline headings and for plain lists alike."
4521 (interactive "P")
4522 (org-insert-todo-heading arg)
4523 (cond
4524 ((org-on-heading-p) (org-do-demote))
4525 ((org-at-item-p) (org-indent-item 1))))
4527 ;;; Promotion and Demotion
4529 (defun org-promote-subtree ()
4530 "Promote the entire subtree.
4531 See also `org-promote'."
4532 (interactive)
4533 (save-excursion
4534 (org-map-tree 'org-promote))
4535 (org-fix-position-after-promote))
4537 (defun org-demote-subtree ()
4538 "Demote the entire subtree. See `org-demote'.
4539 See also `org-promote'."
4540 (interactive)
4541 (save-excursion
4542 (org-map-tree 'org-demote))
4543 (org-fix-position-after-promote))
4546 (defun org-do-promote ()
4547 "Promote the current heading higher up the tree.
4548 If the region is active in `transient-mark-mode', promote all headings
4549 in the region."
4550 (interactive)
4551 (save-excursion
4552 (if (org-region-active-p)
4553 (org-map-region 'org-promote (region-beginning) (region-end))
4554 (org-promote)))
4555 (org-fix-position-after-promote))
4557 (defun org-do-demote ()
4558 "Demote the current heading lower down the tree.
4559 If the region is active in `transient-mark-mode', demote all headings
4560 in the region."
4561 (interactive)
4562 (save-excursion
4563 (if (org-region-active-p)
4564 (org-map-region 'org-demote (region-beginning) (region-end))
4565 (org-demote)))
4566 (org-fix-position-after-promote))
4568 (defun org-fix-position-after-promote ()
4569 "Make sure that after pro/demotion cursor position is right."
4570 (let ((pos (point)))
4571 (when (save-excursion
4572 (beginning-of-line 1)
4573 (looking-at org-todo-line-regexp)
4574 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4575 (cond ((eobp) (insert " "))
4576 ((eolp) (insert " "))
4577 ((equal (char-after) ?\ ) (forward-char 1))))))
4579 (defun org-reduced-level (l)
4580 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4582 (defun org-get-valid-level (level &optional change)
4583 "Rectify a level change under the influence of `org-odd-levels-only'
4584 LEVEL is a current level, CHANGE is by how much the level should be
4585 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4586 even level numbers will become the next higher odd number."
4587 (if org-odd-levels-only
4588 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4589 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4590 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4591 (max 1 (+ level change))))
4593 (if (boundp 'define-obsolete-function-alias)
4594 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4595 (define-obsolete-function-alias 'org-get-legal-level
4596 'org-get-valid-level)
4597 (define-obsolete-function-alias 'org-get-legal-level
4598 'org-get-valid-level "23.1")))
4600 (defun org-promote ()
4601 "Promote the current heading higher up the tree.
4602 If the region is active in `transient-mark-mode', promote all headings
4603 in the region."
4604 (org-back-to-heading t)
4605 (let* ((level (save-match-data (funcall outline-level)))
4606 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4607 (diff (abs (- level (length up-head) -1))))
4608 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4609 (replace-match up-head nil t)
4610 ;; Fixup tag positioning
4611 (and org-auto-align-tags (org-set-tags nil t))
4612 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4614 (defun org-demote ()
4615 "Demote the current heading lower down the tree.
4616 If the region is active in `transient-mark-mode', demote all headings
4617 in the region."
4618 (org-back-to-heading t)
4619 (let* ((level (save-match-data (funcall outline-level)))
4620 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4621 (diff (abs (- level (length down-head) -1))))
4622 (replace-match down-head nil t)
4623 ;; Fixup tag positioning
4624 (and org-auto-align-tags (org-set-tags nil t))
4625 (if org-adapt-indentation (org-fixup-indentation diff))))
4627 (defun org-map-tree (fun)
4628 "Call FUN for every heading underneath the current one."
4629 (org-back-to-heading)
4630 (let ((level (funcall outline-level)))
4631 (save-excursion
4632 (funcall fun)
4633 (while (and (progn
4634 (outline-next-heading)
4635 (> (funcall outline-level) level))
4636 (not (eobp)))
4637 (funcall fun)))))
4639 (defun org-map-region (fun beg end)
4640 "Call FUN for every heading between BEG and END."
4641 (let ((org-ignore-region t))
4642 (save-excursion
4643 (setq end (copy-marker end))
4644 (goto-char beg)
4645 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4646 (< (point) end))
4647 (funcall fun))
4648 (while (and (progn
4649 (outline-next-heading)
4650 (< (point) end))
4651 (not (eobp)))
4652 (funcall fun)))))
4654 (defun org-fixup-indentation (diff)
4655 "Change the indentation in the current entry by DIFF
4656 However, if any line in the current entry has no indentation, or if it
4657 would end up with no indentation after the change, nothing at all is done."
4658 (save-excursion
4659 (let ((end (save-excursion (outline-next-heading)
4660 (point-marker)))
4661 (prohibit (if (> diff 0)
4662 "^\\S-"
4663 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4664 col)
4665 (unless (save-excursion (end-of-line 1)
4666 (re-search-forward prohibit end t))
4667 (while (and (< (point) end)
4668 (re-search-forward "^[ \t]+" end t))
4669 (goto-char (match-end 0))
4670 (setq col (current-column))
4671 (if (< diff 0) (replace-match ""))
4672 (indent-to (+ diff col))))
4673 (move-marker end nil))))
4675 (defun org-convert-to-odd-levels ()
4676 "Convert an org-mode file with all levels allowed to one with odd levels.
4677 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4678 level 5 etc."
4679 (interactive)
4680 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4681 (let ((org-odd-levels-only nil) n)
4682 (save-excursion
4683 (goto-char (point-min))
4684 (while (re-search-forward "^\\*\\*+ " nil t)
4685 (setq n (- (length (match-string 0)) 2))
4686 (while (>= (setq n (1- n)) 0)
4687 (org-demote))
4688 (end-of-line 1))))))
4691 (defun org-convert-to-oddeven-levels ()
4692 "Convert an org-mode file with only odd levels to one with odd and even levels.
4693 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4694 section with an even level, conversion would destroy the structure of the file. An error
4695 is signaled in this case."
4696 (interactive)
4697 (goto-char (point-min))
4698 ;; First check if there are no even levels
4699 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4700 (org-show-context t)
4701 (error "Not all levels are odd in this file. Conversion not possible."))
4702 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4703 (let ((org-odd-levels-only nil) n)
4704 (save-excursion
4705 (goto-char (point-min))
4706 (while (re-search-forward "^\\*\\*+ " nil t)
4707 (setq n (/ (1- (length (match-string 0))) 2))
4708 (while (>= (setq n (1- n)) 0)
4709 (org-promote))
4710 (end-of-line 1))))))
4712 (defun org-tr-level (n)
4713 "Make N odd if required."
4714 (if org-odd-levels-only (1+ (/ n 2)) n))
4716 ;;; Vertical tree motion, cutting and pasting of subtrees
4718 (defun org-move-subtree-up (&optional arg)
4719 "Move the current subtree up past ARG headlines of the same level."
4720 (interactive "p")
4721 (org-move-subtree-down (- (prefix-numeric-value arg))))
4723 (defun org-move-subtree-down (&optional arg)
4724 "Move the current subtree down past ARG headlines of the same level."
4725 (interactive "p")
4726 (setq arg (prefix-numeric-value arg))
4727 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4728 'outline-get-last-sibling))
4729 (ins-point (make-marker))
4730 (cnt (abs arg))
4731 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4732 ;; Select the tree
4733 (org-back-to-heading)
4734 (setq beg0 (point))
4735 (save-excursion
4736 (setq ne-beg (org-back-over-empty-lines))
4737 (setq beg (point)))
4738 (save-match-data
4739 (save-excursion (outline-end-of-heading)
4740 (setq folded (org-invisible-p)))
4741 (outline-end-of-subtree))
4742 (outline-next-heading)
4743 (setq ne-end (org-back-over-empty-lines))
4744 (setq end (point))
4745 (goto-char beg0)
4746 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4747 ;; include less whitespace
4748 (save-excursion
4749 (goto-char beg)
4750 (forward-line (- ne-beg ne-end))
4751 (setq beg (point))))
4752 ;; Find insertion point, with error handling
4753 (while (> cnt 0)
4754 (or (and (funcall movfunc) (looking-at outline-regexp))
4755 (progn (goto-char beg0)
4756 (error "Cannot move past superior level or buffer limit")))
4757 (setq cnt (1- cnt)))
4758 (if (> arg 0)
4759 ;; Moving forward - still need to move over subtree
4760 (progn (org-end-of-subtree t t)
4761 (save-excursion
4762 (org-back-over-empty-lines)
4763 (or (bolp) (newline)))))
4764 (setq ne-ins (org-back-over-empty-lines))
4765 (move-marker ins-point (point))
4766 (setq txt (buffer-substring beg end))
4767 (org-save-markers-in-region beg end)
4768 (delete-region beg end)
4769 (outline-flag-region (1- beg) beg nil)
4770 (outline-flag-region (1- (point)) (point) nil)
4771 (let ((bbb (point)))
4772 (insert-before-markers txt)
4773 (org-reinstall-markers-in-region bbb)
4774 (move-marker ins-point bbb))
4775 (or (bolp) (insert "\n"))
4776 (setq ins-end (point))
4777 (goto-char ins-point)
4778 (org-skip-whitespace)
4779 (when (and (< arg 0)
4780 (org-first-sibling-p)
4781 (> ne-ins ne-beg))
4782 ;; Move whitespace back to beginning
4783 (save-excursion
4784 (goto-char ins-end)
4785 (let ((kill-whole-line t))
4786 (kill-line (- ne-ins ne-beg)) (point)))
4787 (insert (make-string (- ne-ins ne-beg) ?\n)))
4788 (move-marker ins-point nil)
4789 (org-compact-display-after-subtree-move)
4790 (unless folded
4791 (org-show-entry)
4792 (show-children)
4793 (org-cycle-hide-drawers 'children))))
4795 (defvar org-subtree-clip ""
4796 "Clipboard for cut and paste of subtrees.
4797 This is actually only a copy of the kill, because we use the normal kill
4798 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4800 (defvar org-subtree-clip-folded nil
4801 "Was the last copied subtree folded?
4802 This is used to fold the tree back after pasting.")
4804 (defun org-cut-subtree (&optional n)
4805 "Cut the current subtree into the clipboard.
4806 With prefix arg N, cut this many sequential subtrees.
4807 This is a short-hand for marking the subtree and then cutting it."
4808 (interactive "p")
4809 (org-copy-subtree n 'cut))
4811 (defun org-copy-subtree (&optional n cut force-store-markers)
4812 "Cut the current subtree into the clipboard.
4813 With prefix arg N, cut this many sequential subtrees.
4814 This is a short-hand for marking the subtree and then copying it.
4815 If CUT is non-nil, actually cut the subtree.
4816 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4817 of some markers in the region, even if CUT is non-nil. This is
4818 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4819 (interactive "p")
4820 (let (beg end folded (beg0 (point)))
4821 (if (interactive-p)
4822 (org-back-to-heading nil) ; take what looks like a subtree
4823 (org-back-to-heading t)) ; take what is really there
4824 (org-back-over-empty-lines)
4825 (setq beg (point))
4826 (skip-chars-forward " \t\r\n")
4827 (save-match-data
4828 (save-excursion (outline-end-of-heading)
4829 (setq folded (org-invisible-p)))
4830 (condition-case nil
4831 (outline-forward-same-level (1- n))
4832 (error nil))
4833 (org-end-of-subtree t t))
4834 (org-back-over-empty-lines)
4835 (setq end (point))
4836 (goto-char beg0)
4837 (when (> end beg)
4838 (setq org-subtree-clip-folded folded)
4839 (when (or cut force-store-markers)
4840 (org-save-markers-in-region beg end))
4841 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4842 (setq org-subtree-clip (current-kill 0))
4843 (message "%s: Subtree(s) with %d characters"
4844 (if cut "Cut" "Copied")
4845 (length org-subtree-clip)))))
4847 (defun org-paste-subtree (&optional level tree)
4848 "Paste the clipboard as a subtree, with modification of headline level.
4849 The entire subtree is promoted or demoted in order to match a new headline
4850 level. By default, the new level is derived from the visible headings
4851 before and after the insertion point, and taken to be the inferior headline
4852 level of the two. So if the previous visible heading is level 3 and the
4853 next is level 4 (or vice versa), level 4 will be used for insertion.
4854 This makes sure that the subtree remains an independent subtree and does
4855 not swallow low level entries.
4857 You can also force a different level, either by using a numeric prefix
4858 argument, or by inserting the heading marker by hand. For example, if the
4859 cursor is after \"*****\", then the tree will be shifted to level 5.
4861 If you want to insert the tree as is, just use \\[yank].
4863 If optional TREE is given, use this text instead of the kill ring."
4864 (interactive "P")
4865 (unless (org-kill-is-subtree-p tree)
4866 (error "%s"
4867 (substitute-command-keys
4868 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4869 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4870 (^re (concat "^\\(" outline-regexp "\\)"))
4871 (re (concat "\\(" outline-regexp "\\)"))
4872 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4874 (old-level (if (string-match ^re txt)
4875 (- (match-end 0) (match-beginning 0) 1)
4876 -1))
4877 (force-level (cond (level (prefix-numeric-value level))
4878 ((string-match
4879 ^re_ (buffer-substring (point-at-bol) (point)))
4880 (- (match-end 1) (match-beginning 1)))
4881 (t nil)))
4882 (previous-level (save-excursion
4883 (condition-case nil
4884 (progn
4885 (outline-previous-visible-heading 1)
4886 (if (looking-at re)
4887 (- (match-end 0) (match-beginning 0) 1)
4889 (error 1))))
4890 (next-level (save-excursion
4891 (condition-case nil
4892 (progn
4893 (or (looking-at outline-regexp)
4894 (outline-next-visible-heading 1))
4895 (if (looking-at re)
4896 (- (match-end 0) (match-beginning 0) 1)
4898 (error 1))))
4899 (new-level (or force-level (max previous-level next-level)))
4900 (shift (if (or (= old-level -1)
4901 (= new-level -1)
4902 (= old-level new-level))
4904 (- new-level old-level)))
4905 (delta (if (> shift 0) -1 1))
4906 (func (if (> shift 0) 'org-demote 'org-promote))
4907 (org-odd-levels-only nil)
4908 beg end)
4909 ;; Remove the forced level indicator
4910 (if force-level
4911 (delete-region (point-at-bol) (point)))
4912 ;; Paste
4913 (beginning-of-line 1)
4914 (org-back-over-empty-lines)
4915 (setq beg (point))
4916 (insert-before-markers txt)
4917 (unless (string-match "\n\\'" txt) (insert "\n"))
4918 (org-reinstall-markers-in-region beg)
4919 (setq end (point))
4920 (goto-char beg)
4921 (skip-chars-forward " \t\n\r")
4922 (setq beg (point))
4923 ;; Shift if necessary
4924 (unless (= shift 0)
4925 (save-restriction
4926 (narrow-to-region beg end)
4927 (while (not (= shift 0))
4928 (org-map-region func (point-min) (point-max))
4929 (setq shift (+ delta shift)))
4930 (goto-char (point-min))))
4931 (when (interactive-p)
4932 (message "Clipboard pasted as level %d subtree" new-level))
4933 (if (and kill-ring
4934 (eq org-subtree-clip (current-kill 0))
4935 org-subtree-clip-folded)
4936 ;; The tree was folded before it was killed/copied
4937 (hide-subtree))))
4939 (defun org-kill-is-subtree-p (&optional txt)
4940 "Check if the current kill is an outline subtree, or a set of trees.
4941 Returns nil if kill does not start with a headline, or if the first
4942 headline level is not the largest headline level in the tree.
4943 So this will actually accept several entries of equal levels as well,
4944 which is OK for `org-paste-subtree'.
4945 If optional TXT is given, check this string instead of the current kill."
4946 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4947 (start-level (and kill
4948 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4949 org-outline-regexp "\\)")
4950 kill)
4951 (- (match-end 2) (match-beginning 2) 1)))
4952 (re (concat "^" org-outline-regexp))
4953 (start (1+ (match-beginning 2))))
4954 (if (not start-level)
4955 (progn
4956 nil) ;; does not even start with a heading
4957 (catch 'exit
4958 (while (setq start (string-match re kill (1+ start)))
4959 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4960 (throw 'exit nil)))
4961 t))))
4963 (defvar org-markers-to-move nil
4964 "Markers that should be moved with a cut-and-paste operation.
4965 Those markers are stored together with their positions relative to
4966 the start of the region.")
4968 (defun org-save-markers-in-region (beg end)
4969 "Check markers in region.
4970 If these markers are between BEG and END, record their position relative
4971 to BEG, so that after moving the block of text, we can put the markers back
4972 into place.
4973 This function gets called just before an entry or tree gets cut from the
4974 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4975 called immediately, to move the markers with the entries."
4976 (setq org-markers-to-move nil)
4977 (when (featurep 'org-clock)
4978 (org-clock-save-markers-for-cut-and-paste beg end))
4979 (when (featurep 'org-agenda)
4980 (org-agenda-save-markers-for-cut-and-paste beg end)))
4982 (defun org-check-and-save-marker (marker beg end)
4983 "Check if MARKER is between BEG and END.
4984 If yes, remember the marker and the distance to BEG."
4985 (when (and (marker-buffer marker)
4986 (equal (marker-buffer marker) (current-buffer)))
4987 (if (and (>= marker beg) (< marker end))
4988 (push (cons marker (- marker beg)) org-markers-to-move))))
4990 (defun org-reinstall-markers-in-region (beg)
4991 "Move all remembered markers to their position relative to BEG."
4992 (mapc (lambda (x)
4993 (move-marker (car x) (+ beg (cdr x))))
4994 org-markers-to-move)
4995 (setq org-markers-to-move nil))
4997 (defun org-narrow-to-subtree ()
4998 "Narrow buffer to the current subtree."
4999 (interactive)
5000 (save-excursion
5001 (save-match-data
5002 (narrow-to-region
5003 (progn (org-back-to-heading) (point))
5004 (progn (org-end-of-subtree t t) (point))))))
5007 ;;; Outline Sorting
5009 (defun org-sort (with-case)
5010 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5011 Optional argument WITH-CASE means sort case-sensitively."
5012 (interactive "P")
5013 (if (org-at-table-p)
5014 (org-call-with-arg 'org-table-sort-lines with-case)
5015 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5017 (defun org-sort-remove-invisible (s)
5018 (remove-text-properties 0 (length s) org-rm-props s)
5019 (while (string-match org-bracket-link-regexp s)
5020 (setq s (replace-match (if (match-end 2)
5021 (match-string 3 s)
5022 (match-string 1 s)) t t s)))
5025 (defvar org-priority-regexp) ; defined later in the file
5027 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5028 "Sort entries on a certain level of an outline tree.
5029 If there is an active region, the entries in the region are sorted.
5030 Else, if the cursor is before the first entry, sort the top-level items.
5031 Else, the children of the entry at point are sorted.
5033 Sorting can be alphabetically, numerically, and by date/time as given by
5034 the first time stamp in the entry. The command prompts for the sorting
5035 type unless it has been given to the function through the SORTING-TYPE
5036 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5037 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5038 called with point at the beginning of the record. It must return either
5039 a string or a number that should serve as the sorting key for that record.
5041 Comparing entries ignores case by default. However, with an optional argument
5042 WITH-CASE, the sorting considers case as well."
5043 (interactive "P")
5044 (let ((case-func (if with-case 'identity 'downcase))
5045 start beg end stars re re2
5046 txt what tmp plain-list-p)
5047 ;; Find beginning and end of region to sort
5048 (cond
5049 ((org-region-active-p)
5050 ;; we will sort the region
5051 (setq end (region-end)
5052 what "region")
5053 (goto-char (region-beginning))
5054 (if (not (org-on-heading-p)) (outline-next-heading))
5055 (setq start (point)))
5056 ((org-at-item-p)
5057 ;; we will sort this plain list
5058 (org-beginning-of-item-list) (setq start (point))
5059 (org-end-of-item-list) (setq end (point))
5060 (goto-char start)
5061 (setq plain-list-p t
5062 what "plain list"))
5063 ((or (org-on-heading-p)
5064 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5065 ;; we will sort the children of the current headline
5066 (org-back-to-heading)
5067 (setq start (point)
5068 end (progn (org-end-of-subtree t t)
5069 (org-back-over-empty-lines)
5070 (point))
5071 what "children")
5072 (goto-char start)
5073 (show-subtree)
5074 (outline-next-heading))
5076 ;; we will sort the top-level entries in this file
5077 (goto-char (point-min))
5078 (or (org-on-heading-p) (outline-next-heading))
5079 (setq start (point) end (point-max) what "top-level")
5080 (goto-char start)
5081 (show-all)))
5083 (setq beg (point))
5084 (if (>= beg end) (error "Nothing to sort"))
5086 (unless plain-list-p
5087 (looking-at "\\(\\*+\\)")
5088 (setq stars (match-string 1)
5089 re (concat "^" (regexp-quote stars) " +")
5090 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5091 txt (buffer-substring beg end))
5092 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5093 (if (and (not (equal stars "*")) (string-match re2 txt))
5094 (error "Region to sort contains a level above the first entry")))
5096 (unless sorting-type
5097 (message
5098 (if plain-list-p
5099 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5100 "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:")
5101 what)
5102 (setq sorting-type (read-char-exclusive))
5104 (and (= (downcase sorting-type) ?f)
5105 (setq getkey-func
5106 (completing-read "Sort using function: "
5107 obarray 'fboundp t nil nil))
5108 (setq getkey-func (intern getkey-func)))
5110 (and (= (downcase sorting-type) ?r)
5111 (setq property
5112 (completing-read "Property: "
5113 (mapcar 'list (org-buffer-property-keys t))
5114 nil t))))
5116 (message "Sorting entries...")
5118 (save-restriction
5119 (narrow-to-region start end)
5121 (let ((dcst (downcase sorting-type))
5122 (now (current-time)))
5123 (sort-subr
5124 (/= dcst sorting-type)
5125 ;; This function moves to the beginning character of the "record" to
5126 ;; be sorted.
5127 (if plain-list-p
5128 (lambda nil
5129 (if (org-at-item-p) t (goto-char (point-max))))
5130 (lambda nil
5131 (if (re-search-forward re nil t)
5132 (goto-char (match-beginning 0))
5133 (goto-char (point-max)))))
5134 ;; This function moves to the last character of the "record" being
5135 ;; sorted.
5136 (if plain-list-p
5137 'org-end-of-item
5138 (lambda nil
5139 (save-match-data
5140 (condition-case nil
5141 (outline-forward-same-level 1)
5142 (error
5143 (goto-char (point-max)))))))
5145 ;; This function returns the value that gets sorted against.
5146 (if plain-list-p
5147 (lambda nil
5148 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5149 (cond
5150 ((= dcst ?n)
5151 (string-to-number (buffer-substring (match-end 0)
5152 (point-at-eol))))
5153 ((= dcst ?a)
5154 (buffer-substring (match-end 0) (point-at-eol)))
5155 ((= dcst ?t)
5156 (if (re-search-forward org-ts-regexp
5157 (point-at-eol) t)
5158 (org-time-string-to-time (match-string 0))
5159 now))
5160 ((= dcst ?f)
5161 (if getkey-func
5162 (progn
5163 (setq tmp (funcall getkey-func))
5164 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5165 tmp)
5166 (error "Invalid key function `%s'" getkey-func)))
5167 (t (error "Invalid sorting type `%c'" sorting-type)))))
5168 (lambda nil
5169 (cond
5170 ((= dcst ?n)
5171 (if (looking-at outline-regexp)
5172 (string-to-number (buffer-substring (match-end 0)
5173 (point-at-eol)))
5174 nil))
5175 ((= dcst ?a)
5176 (funcall case-func (buffer-substring (point-at-bol)
5177 (point-at-eol))))
5178 ((= dcst ?t)
5179 (if (re-search-forward org-ts-regexp
5180 (save-excursion
5181 (forward-line 2)
5182 (point)) t)
5183 (org-time-string-to-time (match-string 0))
5184 now))
5185 ((= dcst ?p)
5186 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5187 (string-to-char (match-string 2))
5188 org-default-priority))
5189 ((= dcst ?r)
5190 (or (org-entry-get nil property) ""))
5191 ((= dcst ?o)
5192 (if (looking-at org-complex-heading-regexp)
5193 (- 9999 (length (member (match-string 2)
5194 org-todo-keywords-1)))))
5195 ((= dcst ?f)
5196 (if getkey-func
5197 (progn
5198 (setq tmp (funcall getkey-func))
5199 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5200 tmp)
5201 (error "Invalid key function `%s'" getkey-func)))
5202 (t (error "Invalid sorting type `%c'" sorting-type)))))
5204 (cond
5205 ((= dcst ?a) 'string<)
5206 ((= dcst ?t) 'time-less-p)
5207 (t nil)))))
5208 (message "Sorting entries...done")))
5210 (defun org-do-sort (table what &optional with-case sorting-type)
5211 "Sort TABLE of WHAT according to SORTING-TYPE.
5212 The user will be prompted for the SORTING-TYPE if the call to this
5213 function does not specify it. WHAT is only for the prompt, to indicate
5214 what is being sorted. The sorting key will be extracted from
5215 the car of the elements of the table.
5216 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5217 (unless sorting-type
5218 (message
5219 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5220 what)
5221 (setq sorting-type (read-char-exclusive)))
5222 (let ((dcst (downcase sorting-type))
5223 extractfun comparefun)
5224 ;; Define the appropriate functions
5225 (cond
5226 ((= dcst ?n)
5227 (setq extractfun 'string-to-number
5228 comparefun (if (= dcst sorting-type) '< '>)))
5229 ((= dcst ?a)
5230 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5231 (lambda(x) (downcase (org-sort-remove-invisible x))))
5232 comparefun (if (= dcst sorting-type)
5233 'string<
5234 (lambda (a b) (and (not (string< a b))
5235 (not (string= a b)))))))
5236 ((= dcst ?t)
5237 (setq extractfun
5238 (lambda (x)
5239 (if (string-match org-ts-regexp x)
5240 (time-to-seconds
5241 (org-time-string-to-time (match-string 0 x)))
5243 comparefun (if (= dcst sorting-type) '< '>)))
5244 (t (error "Invalid sorting type `%c'" sorting-type)))
5246 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5247 table)
5248 (lambda (a b) (funcall comparefun (car a) (car b))))))
5250 ;;;; Plain list items, including checkboxes
5252 ;;; Plain list items
5254 (defun org-at-item-p ()
5255 "Is point in a line starting a hand-formatted item?"
5256 (let ((llt org-plain-list-ordered-item-terminator))
5257 (save-excursion
5258 (goto-char (point-at-bol))
5259 (looking-at
5260 (cond
5261 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5262 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5263 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5264 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5266 (defun org-in-item-p ()
5267 "It the cursor inside a plain list item.
5268 Does not have to be the first line."
5269 (save-excursion
5270 (condition-case nil
5271 (progn
5272 (org-beginning-of-item)
5273 (org-at-item-p)
5275 (error nil))))
5277 (defun org-insert-item (&optional checkbox)
5278 "Insert a new item at the current level.
5279 Return t when things worked, nil when we are not in an item."
5280 (when (save-excursion
5281 (condition-case nil
5282 (progn
5283 (org-beginning-of-item)
5284 (org-at-item-p)
5285 (if (org-invisible-p) (error "Invisible item"))
5287 (error nil)))
5288 (let* ((bul (match-string 0))
5289 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5290 (match-end 0)))
5291 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5292 pos)
5293 (cond
5294 ((and (org-at-item-p) (<= (point) eow))
5295 ;; before the bullet
5296 (beginning-of-line 1)
5297 (open-line (if blank 2 1)))
5298 ((<= (point) eow)
5299 (beginning-of-line 1))
5301 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5302 (end-of-line 1)
5303 (delete-horizontal-space))
5304 (newline (if blank 2 1))))
5305 (insert bul (if checkbox "[ ]" ""))
5306 (just-one-space)
5307 (setq pos (point))
5308 (end-of-line 1)
5309 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5310 (org-maybe-renumber-ordered-list)
5311 (and checkbox (org-update-checkbox-count-maybe))
5314 ;;; Checkboxes
5316 (defun org-at-item-checkbox-p ()
5317 "Is point at a line starting a plain-list item with a checklet?"
5318 (and (org-at-item-p)
5319 (save-excursion
5320 (goto-char (match-end 0))
5321 (skip-chars-forward " \t")
5322 (looking-at "\\[[- X]\\]"))))
5324 (defun org-toggle-checkbox (&optional arg)
5325 "Toggle the checkbox in the current line."
5326 (interactive "P")
5327 (catch 'exit
5328 (let (beg end status (firstnew 'unknown))
5329 (cond
5330 ((org-region-active-p)
5331 (setq beg (region-beginning) end (region-end)))
5332 ((org-on-heading-p)
5333 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5334 ((org-at-item-checkbox-p)
5335 (let ((pos (point)))
5336 (replace-match
5337 (cond (arg "[-]")
5338 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5339 (t "[ ]"))
5340 t t)
5341 (goto-char pos))
5342 (throw 'exit t))
5343 (t (error "Not at a checkbox or heading, and no active region")))
5344 (save-excursion
5345 (goto-char beg)
5346 (while (< (point) end)
5347 (when (org-at-item-checkbox-p)
5348 (setq status (equal (match-string 0) "[X]"))
5349 (when (eq firstnew 'unknown)
5350 (setq firstnew (not status)))
5351 (replace-match
5352 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5353 (beginning-of-line 2)))))
5354 (org-update-checkbox-count-maybe))
5356 (defun org-update-checkbox-count-maybe ()
5357 "Update checkbox statistics unless turned off by user."
5358 (when org-provide-checkbox-statistics
5359 (org-update-checkbox-count)))
5361 (defun org-update-checkbox-count (&optional all)
5362 "Update the checkbox statistics in the current section.
5363 This will find all statistic cookies like [57%] and [6/12] and update them
5364 with the current numbers. With optional prefix argument ALL, do this for
5365 the whole buffer."
5366 (interactive "P")
5367 (save-excursion
5368 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5369 (beg (condition-case nil
5370 (progn (outline-back-to-heading) (point))
5371 (error (point-min))))
5372 (end (move-marker (make-marker)
5373 (progn (outline-next-heading) (point))))
5374 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5375 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5376 (re-find (concat re "\\|" re-box))
5377 beg-cookie end-cookie is-percent c-on c-off lim
5378 eline curr-ind next-ind continue-from startsearch
5379 (cstat 0)
5381 (when all
5382 (goto-char (point-min))
5383 (outline-next-heading)
5384 (setq beg (point) end (point-max)))
5385 (goto-char end)
5386 ;; find each statistic cookie
5387 (while (re-search-backward re-find beg t)
5388 (setq beg-cookie (match-beginning 1)
5389 end-cookie (match-end 1)
5390 cstat (+ cstat (if end-cookie 1 0))
5391 startsearch (point-at-eol)
5392 continue-from (point-at-bol)
5393 is-percent (match-beginning 2)
5394 lim (cond
5395 ((org-on-heading-p) (outline-next-heading) (point))
5396 ((org-at-item-p) (org-end-of-item) (point))
5397 (t nil))
5398 c-on 0
5399 c-off 0)
5400 (when lim
5401 ;; find first checkbox for this cookie and gather
5402 ;; statistics from all that are at this indentation level
5403 (goto-char startsearch)
5404 (if (re-search-forward re-box lim t)
5405 (progn
5406 (org-beginning-of-item)
5407 (setq curr-ind (org-get-indentation))
5408 (setq next-ind curr-ind)
5409 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5410 (save-excursion (end-of-line) (setq eline (point)))
5411 (if (re-search-forward re-box eline t)
5412 (if (member (match-string 2) '("[ ]" "[-]"))
5413 (setq c-off (1+ c-off))
5414 (setq c-on (1+ c-on))
5417 (org-end-of-item)
5418 (setq next-ind (org-get-indentation))
5420 (goto-char continue-from)
5421 ;; update cookie
5422 (when end-cookie
5423 (delete-region beg-cookie end-cookie)
5424 (goto-char beg-cookie)
5425 (insert
5426 (if is-percent
5427 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5428 (format "[%d/%d]" c-on (+ c-on c-off)))))
5429 ;; update items checkbox if it has one
5430 (when (org-at-item-p)
5431 (org-beginning-of-item)
5432 (when (and (> (+ c-on c-off) 0)
5433 (re-search-forward re-box (point-at-eol) t))
5434 (setq beg-cookie (match-beginning 2)
5435 end-cookie (match-end 2))
5436 (delete-region beg-cookie end-cookie)
5437 (goto-char beg-cookie)
5438 (cond ((= c-off 0) (insert "[X]"))
5439 ((= c-on 0) (insert "[ ]"))
5440 (t (insert "[-]")))
5442 (goto-char continue-from))
5443 (when (interactive-p)
5444 (message "Checkbox satistics updated %s (%d places)"
5445 (if all "in entire file" "in current outline entry") cstat)))))
5447 (defun org-get-checkbox-statistics-face ()
5448 "Select the face for checkbox statistics.
5449 The face will be `org-done' when all relevant boxes are checked. Otherwise
5450 it will be `org-todo'."
5451 (if (match-end 1)
5452 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5453 (if (and (> (match-end 2) (match-beginning 2))
5454 (equal (match-string 2) (match-string 3)))
5455 'org-done
5456 'org-todo)))
5458 (defun org-get-indentation (&optional line)
5459 "Get the indentation of the current line, interpreting tabs.
5460 When LINE is given, assume it represents a line and compute its indentation."
5461 (if line
5462 (if (string-match "^ *" (org-remove-tabs line))
5463 (match-end 0))
5464 (save-excursion
5465 (beginning-of-line 1)
5466 (skip-chars-forward " \t")
5467 (current-column))))
5469 (defun org-remove-tabs (s &optional width)
5470 "Replace tabulators in S with spaces.
5471 Assumes that s is a single line, starting in column 0."
5472 (setq width (or width tab-width))
5473 (while (string-match "\t" s)
5474 (setq s (replace-match
5475 (make-string
5476 (- (* width (/ (+ (match-beginning 0) width) width))
5477 (match-beginning 0)) ?\ )
5478 t t s)))
5481 (defun org-fix-indentation (line ind)
5482 "Fix indentation in LINE.
5483 IND is a cons cell with target and minimum indentation.
5484 If the current indenation in LINE is smaller than the minimum,
5485 leave it alone. If it is larger than ind, set it to the target."
5486 (let* ((l (org-remove-tabs line))
5487 (i (org-get-indentation l))
5488 (i1 (car ind)) (i2 (cdr ind)))
5489 (if (>= i i2) (setq l (substring line i2)))
5490 (if (> i1 0)
5491 (concat (make-string i1 ?\ ) l)
5492 l)))
5494 (defun org-beginning-of-item ()
5495 "Go to the beginning of the current hand-formatted item.
5496 If the cursor is not in an item, throw an error."
5497 (interactive)
5498 (let ((pos (point))
5499 (limit (save-excursion
5500 (condition-case nil
5501 (progn
5502 (org-back-to-heading)
5503 (beginning-of-line 2) (point))
5504 (error (point-min)))))
5505 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5506 ind ind1)
5507 (if (org-at-item-p)
5508 (beginning-of-line 1)
5509 (beginning-of-line 1)
5510 (skip-chars-forward " \t")
5511 (setq ind (current-column))
5512 (if (catch 'exit
5513 (while t
5514 (beginning-of-line 0)
5515 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5517 (if (looking-at "[ \t]*$")
5518 (setq ind1 ind-empty)
5519 (skip-chars-forward " \t")
5520 (setq ind1 (current-column)))
5521 (if (< ind1 ind)
5522 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5524 (goto-char pos)
5525 (error "Not in an item")))))
5527 (defun org-end-of-item ()
5528 "Go to the end of the current hand-formatted item.
5529 If the cursor is not in an item, throw an error."
5530 (interactive)
5531 (let* ((pos (point))
5532 ind1
5533 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5534 (limit (save-excursion (outline-next-heading) (point)))
5535 (ind (save-excursion
5536 (org-beginning-of-item)
5537 (skip-chars-forward " \t")
5538 (current-column)))
5539 (end (catch 'exit
5540 (while t
5541 (beginning-of-line 2)
5542 (if (eobp) (throw 'exit (point)))
5543 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5544 (if (looking-at "[ \t]*$")
5545 (setq ind1 ind-empty)
5546 (skip-chars-forward " \t")
5547 (setq ind1 (current-column)))
5548 (if (<= ind1 ind)
5549 (throw 'exit (point-at-bol)))))))
5550 (if end
5551 (goto-char end)
5552 (goto-char pos)
5553 (error "Not in an item"))))
5555 (defun org-next-item ()
5556 "Move to the beginning of the next item in the current plain list.
5557 Error if not at a plain list, or if this is the last item in the list."
5558 (interactive)
5559 (let (ind ind1 (pos (point)))
5560 (org-beginning-of-item)
5561 (setq ind (org-get-indentation))
5562 (org-end-of-item)
5563 (setq ind1 (org-get-indentation))
5564 (unless (and (org-at-item-p) (= ind ind1))
5565 (goto-char pos)
5566 (error "On last item"))))
5568 (defun org-previous-item ()
5569 "Move to the beginning of the previous item in the current plain list.
5570 Error if not at a plain list, or if this is the first item in the list."
5571 (interactive)
5572 (let (beg ind ind1 (pos (point)))
5573 (org-beginning-of-item)
5574 (setq beg (point))
5575 (setq ind (org-get-indentation))
5576 (goto-char beg)
5577 (catch 'exit
5578 (while t
5579 (beginning-of-line 0)
5580 (if (looking-at "[ \t]*$")
5582 (if (<= (setq ind1 (org-get-indentation)) ind)
5583 (throw 'exit t)))))
5584 (condition-case nil
5585 (if (or (not (org-at-item-p))
5586 (< ind1 (1- ind)))
5587 (error "")
5588 (org-beginning-of-item))
5589 (error (goto-char pos)
5590 (error "On first item")))))
5592 (defun org-first-list-item-p ()
5593 "Is this heading the item in a plain list?"
5594 (unless (org-at-item-p)
5595 (error "Not at a plain list item"))
5596 (org-beginning-of-item)
5597 (= (point) (save-excursion (org-beginning-of-item-list))))
5599 (defun org-move-item-down ()
5600 "Move the plain list item at point down, i.e. swap with following item.
5601 Subitems (items with larger indentation) are considered part of the item,
5602 so this really moves item trees."
5603 (interactive)
5604 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5605 (org-beginning-of-item)
5606 (setq beg0 (point))
5607 (save-excursion
5608 (setq ne-beg (org-back-over-empty-lines))
5609 (setq beg (point)))
5610 (goto-char beg0)
5611 (setq ind (org-get-indentation))
5612 (org-end-of-item)
5613 (setq end0 (point))
5614 (setq ind1 (org-get-indentation))
5615 (setq ne-end (org-back-over-empty-lines))
5616 (setq end (point))
5617 (goto-char beg0)
5618 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5619 ;; include less whitespace
5620 (save-excursion
5621 (goto-char beg)
5622 (forward-line (- ne-beg ne-end))
5623 (setq beg (point))))
5624 (goto-char end0)
5625 (if (and (org-at-item-p) (= ind ind1))
5626 (progn
5627 (org-end-of-item)
5628 (org-back-over-empty-lines)
5629 (setq txt (buffer-substring beg end))
5630 (save-excursion
5631 (delete-region beg end))
5632 (setq pos (point))
5633 (insert txt)
5634 (goto-char pos) (org-skip-whitespace)
5635 (org-maybe-renumber-ordered-list))
5636 (goto-char pos)
5637 (error "Cannot move this item further down"))))
5639 (defun org-move-item-up (arg)
5640 "Move the plain list item at point up, i.e. swap with previous item.
5641 Subitems (items with larger indentation) are considered part of the item,
5642 so this really moves item trees."
5643 (interactive "p")
5644 (let (beg beg0 end ind ind1 (pos (point)) txt
5645 ne-beg ne-ins ins-end)
5646 (org-beginning-of-item)
5647 (setq beg0 (point))
5648 (setq ind (org-get-indentation))
5649 (save-excursion
5650 (setq ne-beg (org-back-over-empty-lines))
5651 (setq beg (point)))
5652 (goto-char beg0)
5653 (org-end-of-item)
5654 (setq end (point))
5655 (goto-char beg0)
5656 (catch 'exit
5657 (while t
5658 (beginning-of-line 0)
5659 (if (looking-at "[ \t]*$")
5660 (if org-empty-line-terminates-plain-lists
5661 (progn
5662 (goto-char pos)
5663 (error "Cannot move this item further up"))
5664 nil)
5665 (if (<= (setq ind1 (org-get-indentation)) ind)
5666 (throw 'exit t)))))
5667 (condition-case nil
5668 (org-beginning-of-item)
5669 (error (goto-char beg)
5670 (error "Cannot move this item further up")))
5671 (setq ind1 (org-get-indentation))
5672 (if (and (org-at-item-p) (= ind ind1))
5673 (progn
5674 (setq ne-ins (org-back-over-empty-lines))
5675 (setq txt (buffer-substring beg end))
5676 (save-excursion
5677 (delete-region beg end))
5678 (setq pos (point))
5679 (insert txt)
5680 (setq ins-end (point))
5681 (goto-char pos) (org-skip-whitespace)
5683 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5684 ;; Move whitespace back to beginning
5685 (save-excursion
5686 (goto-char ins-end)
5687 (let ((kill-whole-line t))
5688 (kill-line (- ne-ins ne-beg)) (point)))
5689 (insert (make-string (- ne-ins ne-beg) ?\n)))
5691 (org-maybe-renumber-ordered-list))
5692 (goto-char pos)
5693 (error "Cannot move this item further up"))))
5695 (defun org-maybe-renumber-ordered-list ()
5696 "Renumber the ordered list at point if setup allows it.
5697 This tests the user option `org-auto-renumber-ordered-lists' before
5698 doing the renumbering."
5699 (interactive)
5700 (when (and org-auto-renumber-ordered-lists
5701 (org-at-item-p))
5702 (if (match-beginning 3)
5703 (org-renumber-ordered-list 1)
5704 (org-fix-bullet-type))))
5706 (defun org-maybe-renumber-ordered-list-safe ()
5707 (condition-case nil
5708 (save-excursion
5709 (org-maybe-renumber-ordered-list))
5710 (error nil)))
5712 (defun org-cycle-list-bullet (&optional which)
5713 "Cycle through the different itemize/enumerate bullets.
5714 This cycle the entire list level through the sequence:
5716 `-' -> `+' -> `*' -> `1.' -> `1)'
5718 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5719 0 meand `-', 1 means `+' etc."
5720 (interactive "P")
5721 (org-preserve-lc
5722 (org-beginning-of-item-list)
5723 (org-at-item-p)
5724 (beginning-of-line 1)
5725 (let ((current (match-string 0))
5726 (prevp (eq which 'previous))
5727 new)
5728 (setq new (cond
5729 ((and (numberp which)
5730 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5731 ((string-match "-" current) (if prevp "1)" "+"))
5732 ((string-match "\\+" current)
5733 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5734 ((string-match "\\*" current) (if prevp "+" "1."))
5735 ((string-match "\\." current) (if prevp "*" "1)"))
5736 ((string-match ")" current) (if prevp "1." "-"))
5737 (t (error "This should not happen"))))
5738 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5739 (org-fix-bullet-type)
5740 (org-maybe-renumber-ordered-list))))
5742 (defun org-get-string-indentation (s)
5743 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5744 (let ((n -1) (i 0) (w tab-width) c)
5745 (catch 'exit
5746 (while (< (setq n (1+ n)) (length s))
5747 (setq c (aref s n))
5748 (cond ((= c ?\ ) (setq i (1+ i)))
5749 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5750 (t (throw 'exit t)))))
5753 (defun org-renumber-ordered-list (arg)
5754 "Renumber an ordered plain list.
5755 Cursor needs to be in the first line of an item, the line that starts
5756 with something like \"1.\" or \"2)\"."
5757 (interactive "p")
5758 (unless (and (org-at-item-p)
5759 (match-beginning 3))
5760 (error "This is not an ordered list"))
5761 (let ((line (org-current-line))
5762 (col (current-column))
5763 (ind (org-get-string-indentation
5764 (buffer-substring (point-at-bol) (match-beginning 3))))
5765 ;; (term (substring (match-string 3) -1))
5766 ind1 (n (1- arg))
5767 fmt)
5768 ;; find where this list begins
5769 (org-beginning-of-item-list)
5770 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5771 (setq fmt (concat "%d" (match-string 1)))
5772 (beginning-of-line 0)
5773 ;; walk forward and replace these numbers
5774 (catch 'exit
5775 (while t
5776 (catch 'next
5777 (beginning-of-line 2)
5778 (if (eobp) (throw 'exit nil))
5779 (if (looking-at "[ \t]*$") (throw 'next nil))
5780 (skip-chars-forward " \t") (setq ind1 (current-column))
5781 (if (> ind1 ind) (throw 'next t))
5782 (if (< ind1 ind) (throw 'exit t))
5783 (if (not (org-at-item-p)) (throw 'exit nil))
5784 (delete-region (match-beginning 2) (match-end 2))
5785 (goto-char (match-beginning 2))
5786 (insert (format fmt (setq n (1+ n)))))))
5787 (goto-line line)
5788 (org-move-to-column col)))
5790 (defun org-fix-bullet-type ()
5791 "Make sure all items in this list have the same bullet as the firsst item."
5792 (interactive)
5793 (unless (org-at-item-p) (error "This is not a list"))
5794 (let ((line (org-current-line))
5795 (col (current-column))
5796 (ind (current-indentation))
5797 ind1 bullet)
5798 ;; find where this list begins
5799 (org-beginning-of-item-list)
5800 (beginning-of-line 1)
5801 ;; find out what the bullet type is
5802 (looking-at "[ \t]*\\(\\S-+\\)")
5803 (setq bullet (match-string 1))
5804 ;; walk forward and replace these numbers
5805 (beginning-of-line 0)
5806 (catch 'exit
5807 (while t
5808 (catch 'next
5809 (beginning-of-line 2)
5810 (if (eobp) (throw 'exit nil))
5811 (if (looking-at "[ \t]*$") (throw 'next nil))
5812 (skip-chars-forward " \t") (setq ind1 (current-column))
5813 (if (> ind1 ind) (throw 'next t))
5814 (if (< ind1 ind) (throw 'exit t))
5815 (if (not (org-at-item-p)) (throw 'exit nil))
5816 (skip-chars-forward " \t")
5817 (looking-at "\\S-+")
5818 (replace-match bullet))))
5819 (goto-line line)
5820 (org-move-to-column col)
5821 (if (string-match "[0-9]" bullet)
5822 (org-renumber-ordered-list 1))))
5824 (defun org-beginning-of-item-list ()
5825 "Go to the beginning of the current item list.
5826 I.e. to the first item in this list."
5827 (interactive)
5828 (org-beginning-of-item)
5829 (let ((pos (point-at-bol))
5830 (ind (org-get-indentation))
5831 ind1)
5832 ;; find where this list begins
5833 (catch 'exit
5834 (while t
5835 (catch 'next
5836 (beginning-of-line 0)
5837 (if (looking-at "[ \t]*$")
5838 (throw (if (bobp) 'exit 'next) t))
5839 (skip-chars-forward " \t") (setq ind1 (current-column))
5840 (if (or (< ind1 ind)
5841 (and (= ind1 ind)
5842 (not (org-at-item-p)))
5843 (bobp))
5844 (throw 'exit t)
5845 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5846 (goto-char pos)))
5849 (defun org-end-of-item-list ()
5850 "Go to the end of the current item list.
5851 I.e. to the text after the last item."
5852 (interactive)
5853 (org-beginning-of-item)
5854 (let ((pos (point-at-bol))
5855 (ind (org-get-indentation))
5856 ind1)
5857 ;; find where this list begins
5858 (catch 'exit
5859 (while t
5860 (catch 'next
5861 (beginning-of-line 2)
5862 (if (looking-at "[ \t]*$")
5863 (throw (if (eobp) 'exit 'next) t))
5864 (skip-chars-forward " \t") (setq ind1 (current-column))
5865 (if (or (< ind1 ind)
5866 (and (= ind1 ind)
5867 (not (org-at-item-p)))
5868 (eobp))
5869 (progn
5870 (setq pos (point-at-bol))
5871 (throw 'exit t))))))
5872 (goto-char pos)))
5875 (defvar org-last-indent-begin-marker (make-marker))
5876 (defvar org-last-indent-end-marker (make-marker))
5878 (defun org-outdent-item (arg)
5879 "Outdent a local list item."
5880 (interactive "p")
5881 (org-indent-item (- arg)))
5883 (defun org-indent-item (arg)
5884 "Indent a local list item."
5885 (interactive "p")
5886 (unless (org-at-item-p)
5887 (error "Not on an item"))
5888 (save-excursion
5889 (let (beg end ind ind1 tmp delta ind-down ind-up)
5890 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5891 (setq beg org-last-indent-begin-marker
5892 end org-last-indent-end-marker)
5893 (org-beginning-of-item)
5894 (setq beg (move-marker org-last-indent-begin-marker (point)))
5895 (org-end-of-item)
5896 (setq end (move-marker org-last-indent-end-marker (point))))
5897 (goto-char beg)
5898 (setq tmp (org-item-indent-positions)
5899 ind (car tmp)
5900 ind-down (nth 2 tmp)
5901 ind-up (nth 1 tmp)
5902 delta (if (> arg 0)
5903 (if ind-down (- ind-down ind) 2)
5904 (if ind-up (- ind-up ind) -2)))
5905 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5906 (while (< (point) end)
5907 (beginning-of-line 1)
5908 (skip-chars-forward " \t") (setq ind1 (current-column))
5909 (delete-region (point-at-bol) (point))
5910 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5911 (beginning-of-line 2))))
5912 (org-fix-bullet-type)
5913 (org-maybe-renumber-ordered-list-safe)
5914 (save-excursion
5915 (beginning-of-line 0)
5916 (condition-case nil (org-beginning-of-item) (error nil))
5917 (org-maybe-renumber-ordered-list-safe)))
5919 (defun org-item-indent-positions ()
5920 "Return indentation for plain list items.
5921 This returns a list with three values: The current indentation, the
5922 parent indentation and the indentation a child should habe.
5923 Assumes cursor in item line."
5924 (let* ((bolpos (point-at-bol))
5925 (ind (org-get-indentation))
5926 ind-down ind-up pos)
5927 (save-excursion
5928 (org-beginning-of-item-list)
5929 (skip-chars-backward "\n\r \t")
5930 (when (org-in-item-p)
5931 (org-beginning-of-item)
5932 (setq ind-up (org-get-indentation))))
5933 (setq pos (point))
5934 (save-excursion
5935 (cond
5936 ((and (condition-case nil (progn (org-previous-item) t)
5937 (error nil))
5938 (or (forward-char 1) t)
5939 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5940 (setq ind-down (org-get-indentation)))
5941 ((and (goto-char pos)
5942 (org-at-item-p))
5943 (goto-char (match-end 0))
5944 (skip-chars-forward " \t")
5945 (setq ind-down (current-column)))))
5946 (list ind ind-up ind-down)))
5948 ;;; The orgstruct minor mode
5950 ;; Define a minor mode which can be used in other modes in order to
5951 ;; integrate the org-mode structure editing commands.
5953 ;; This is really a hack, because the org-mode structure commands use
5954 ;; keys which normally belong to the major mode. Here is how it
5955 ;; works: The minor mode defines all the keys necessary to operate the
5956 ;; structure commands, but wraps the commands into a function which
5957 ;; tests if the cursor is currently at a headline or a plain list
5958 ;; item. If that is the case, the structure command is used,
5959 ;; temporarily setting many Org-mode variables like regular
5960 ;; expressions for filling etc. However, when any of those keys is
5961 ;; used at a different location, function uses `key-binding' to look
5962 ;; up if the key has an associated command in another currently active
5963 ;; keymap (minor modes, major mode, global), and executes that
5964 ;; command. There might be problems if any of the keys is otherwise
5965 ;; used as a prefix key.
5967 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5968 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5969 ;; addresses this by checking explicitly for both bindings.
5971 (defvar orgstruct-mode-map (make-sparse-keymap)
5972 "Keymap for the minor `orgstruct-mode'.")
5974 (defvar org-local-vars nil
5975 "List of local variables, for use by `orgstruct-mode'")
5977 ;;;###autoload
5978 (define-minor-mode orgstruct-mode
5979 "Toggle the minor more `orgstruct-mode'.
5980 This mode is for using Org-mode structure commands in other modes.
5981 The following key behave as if Org-mode was active, if the cursor
5982 is on a headline, or on a plain list item (both in the definition
5983 of Org-mode).
5985 M-up Move entry/item up
5986 M-down Move entry/item down
5987 M-left Promote
5988 M-right Demote
5989 M-S-up Move entry/item up
5990 M-S-down Move entry/item down
5991 M-S-left Promote subtree
5992 M-S-right Demote subtree
5993 M-q Fill paragraph and items like in Org-mode
5994 C-c ^ Sort entries
5995 C-c - Cycle list bullet
5996 TAB Cycle item visibility
5997 M-RET Insert new heading/item
5998 S-M-RET Insert new TODO heading / Chekbox item
5999 C-c C-c Set tags / toggle checkbox"
6000 nil " OrgStruct" nil
6001 (org-load-modules-maybe)
6002 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6004 ;;;###autoload
6005 (defun turn-on-orgstruct ()
6006 "Unconditionally turn on `orgstruct-mode'."
6007 (orgstruct-mode 1))
6009 ;;;###autoload
6010 (defun turn-on-orgstruct++ ()
6011 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6012 In addition to setting orgstruct-mode, this also exports all indentation and
6013 autofilling variables from org-mode into the buffer. Note that turning
6014 off orgstruct-mode will *not* remove these additional settings."
6015 (orgstruct-mode 1)
6016 (let (var val)
6017 (mapc
6018 (lambda (x)
6019 (when (string-match
6020 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6021 (symbol-name (car x)))
6022 (setq var (car x) val (nth 1 x))
6023 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6024 org-local-vars)))
6026 (defun orgstruct-error ()
6027 "Error when there is no default binding for a structure key."
6028 (interactive)
6029 (error "This key has no function outside structure elements"))
6031 (defun orgstruct-setup ()
6032 "Setup orgstruct keymaps."
6033 (let ((nfunc 0)
6034 (bindings
6035 (list
6036 '([(meta up)] org-metaup)
6037 '([(meta down)] org-metadown)
6038 '([(meta left)] org-metaleft)
6039 '([(meta right)] org-metaright)
6040 '([(meta shift up)] org-shiftmetaup)
6041 '([(meta shift down)] org-shiftmetadown)
6042 '([(meta shift left)] org-shiftmetaleft)
6043 '([(meta shift right)] org-shiftmetaright)
6044 '([(shift up)] org-shiftup)
6045 '([(shift down)] org-shiftdown)
6046 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6047 '("\M-q" fill-paragraph)
6048 '("\C-c^" org-sort)
6049 '("\C-c-" org-cycle-list-bullet)))
6050 elt key fun cmd)
6051 (while (setq elt (pop bindings))
6052 (setq nfunc (1+ nfunc))
6053 (setq key (org-key (car elt))
6054 fun (nth 1 elt)
6055 cmd (orgstruct-make-binding fun nfunc key))
6056 (org-defkey orgstruct-mode-map key cmd))
6058 ;; Special treatment needed for TAB and RET
6059 (org-defkey orgstruct-mode-map [(tab)]
6060 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6061 (org-defkey orgstruct-mode-map "\C-i"
6062 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6064 (org-defkey orgstruct-mode-map "\M-\C-m"
6065 (orgstruct-make-binding 'org-insert-heading 105
6066 "\M-\C-m" [(meta return)]))
6067 (org-defkey orgstruct-mode-map [(meta return)]
6068 (orgstruct-make-binding 'org-insert-heading 106
6069 [(meta return)] "\M-\C-m"))
6071 (org-defkey orgstruct-mode-map [(shift meta return)]
6072 (orgstruct-make-binding 'org-insert-todo-heading 107
6073 [(meta return)] "\M-\C-m"))
6075 (unless org-local-vars
6076 (setq org-local-vars (org-get-local-variables)))
6080 (defun orgstruct-make-binding (fun n &rest keys)
6081 "Create a function for binding in the structure minor mode.
6082 FUN is the command to call inside a table. N is used to create a unique
6083 command name. KEYS are keys that should be checked in for a command
6084 to execute outside of tables."
6085 (eval
6086 (list 'defun
6087 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6088 '(arg)
6089 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6090 "Outside of structure, run the binding of `"
6091 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6092 "'.")
6093 '(interactive "p")
6094 (list 'if
6095 '(org-context-p 'headline 'item)
6096 (list 'org-run-like-in-org-mode (list 'quote fun))
6097 (list 'let '(orgstruct-mode)
6098 (list 'call-interactively
6099 (append '(or)
6100 (mapcar (lambda (k)
6101 (list 'key-binding k))
6102 keys)
6103 '('orgstruct-error))))))))
6105 (defun org-context-p (&rest contexts)
6106 "Check if local context is and of CONTEXTS.
6107 Possible values in the list of contexts are `table', `headline', and `item'."
6108 (let ((pos (point)))
6109 (goto-char (point-at-bol))
6110 (prog1 (or (and (memq 'table contexts)
6111 (looking-at "[ \t]*|"))
6112 (and (memq 'headline contexts)
6113 (looking-at "\\*+"))
6114 (and (memq 'item contexts)
6115 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6116 (goto-char pos))))
6118 (defun org-get-local-variables ()
6119 "Return a list of all local variables in an org-mode buffer."
6120 (let (varlist)
6121 (with-current-buffer (get-buffer-create "*Org tmp*")
6122 (erase-buffer)
6123 (org-mode)
6124 (setq varlist (buffer-local-variables)))
6125 (kill-buffer "*Org tmp*")
6126 (delq nil
6127 (mapcar
6128 (lambda (x)
6129 (setq x
6130 (if (symbolp x)
6131 (list x)
6132 (list (car x) (list 'quote (cdr x)))))
6133 (if (string-match
6134 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6135 (symbol-name (car x)))
6136 x nil))
6137 varlist))))
6139 ;;;###autoload
6140 (defun org-run-like-in-org-mode (cmd)
6141 (org-load-modules-maybe)
6142 (unless org-local-vars
6143 (setq org-local-vars (org-get-local-variables)))
6144 (eval (list 'let org-local-vars
6145 (list 'call-interactively (list 'quote cmd)))))
6147 ;;;; Archiving
6149 (defun org-get-category (&optional pos)
6150 "Get the category applying to position POS."
6151 (get-text-property (or pos (point)) 'org-category))
6153 (defun org-refresh-category-properties ()
6154 "Refresh category text properties in the buffer."
6155 (let ((def-cat (cond
6156 ((null org-category)
6157 (if buffer-file-name
6158 (file-name-sans-extension
6159 (file-name-nondirectory buffer-file-name))
6160 "???"))
6161 ((symbolp org-category) (symbol-name org-category))
6162 (t org-category)))
6163 beg end cat pos optionp)
6164 (org-unmodified
6165 (save-excursion
6166 (save-restriction
6167 (widen)
6168 (goto-char (point-min))
6169 (put-text-property (point) (point-max) 'org-category def-cat)
6170 (while (re-search-forward
6171 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6172 (setq pos (match-end 0)
6173 optionp (equal (char-after (match-beginning 0)) ?#)
6174 cat (org-trim (match-string 2)))
6175 (if optionp
6176 (setq beg (point-at-bol) end (point-max))
6177 (org-back-to-heading t)
6178 (setq beg (point) end (org-end-of-subtree t t)))
6179 (put-text-property beg end 'org-category cat)
6180 (goto-char pos)))))))
6183 ;;;; Link Stuff
6185 ;;; Link abbreviations
6187 (defun org-link-expand-abbrev (link)
6188 "Apply replacements as defined in `org-link-abbrev-alist."
6189 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6190 (let* ((key (match-string 1 link))
6191 (as (or (assoc key org-link-abbrev-alist-local)
6192 (assoc key org-link-abbrev-alist)))
6193 (tag (and (match-end 2) (match-string 3 link)))
6194 rpl)
6195 (if (not as)
6196 link
6197 (setq rpl (cdr as))
6198 (cond
6199 ((symbolp rpl) (funcall rpl tag))
6200 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6201 (t (concat rpl tag)))))
6202 link))
6204 ;;; Storing and inserting links
6206 (defvar org-insert-link-history nil
6207 "Minibuffer history for links inserted with `org-insert-link'.")
6209 (defvar org-stored-links nil
6210 "Contains the links stored with `org-store-link'.")
6212 (defvar org-store-link-plist nil
6213 "Plist with info about the most recently link created with `org-store-link'.")
6215 (defvar org-link-protocols nil
6216 "Link protocols added to Org-mode using `org-add-link-type'.")
6218 (defvar org-store-link-functions nil
6219 "List of functions that are called to create and store a link.
6220 Each function will be called in turn until one returns a non-nil
6221 value. Each function should check if it is responsible for creating
6222 this link (for example by looking at the major mode).
6223 If not, it must exit and return nil.
6224 If yes, it should return a non-nil value after a calling
6225 `org-store-link-props' with a list of properties and values.
6226 Special properties are:
6228 :type The link prefix. like \"http\". This must be given.
6229 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6230 This is obligatory as well.
6231 :description Optional default description for the second pair
6232 of brackets in an Org-mode link. The user can still change
6233 this when inserting this link into an Org-mode buffer.
6235 In addition to these, any additional properties can be specified
6236 and then used in remember templates.")
6238 (defun org-add-link-type (type &optional follow export)
6239 "Add TYPE to the list of `org-link-types'.
6240 Re-compute all regular expressions depending on `org-link-types'
6242 FOLLOW and EXPORT are two functions.
6244 FOLLOW should take the link path as the single argument and do whatever
6245 is necessary to follow the link, for example find a file or display
6246 a mail message.
6248 EXPORT should format the link path for export to one of the export formats.
6249 It should be a function accepting three arguments:
6251 path the path of the link, the text after the prefix (like \"http:\")
6252 desc the description of the link, if any, nil if there was no descripton
6253 format the export format, a symbol like `html' or `latex'.
6255 The function may use the FORMAT information to return different values
6256 depending on the format. The return value will be put literally into
6257 the exported file.
6258 Org-mode has a built-in default for exporting links. If you are happy with
6259 this default, there is no need to define an export function for the link
6260 type. For a simple example of an export function, see `org-bbdb.el'."
6261 (add-to-list 'org-link-types type t)
6262 (org-make-link-regexps)
6263 (if (assoc type org-link-protocols)
6264 (setcdr (assoc type org-link-protocols) (list follow export))
6265 (push (list type follow export) org-link-protocols)))
6268 ;;;###autoload
6269 (defun org-store-link (arg)
6270 "\\<org-mode-map>Store an org-link to the current location.
6271 This link is added to `org-stored-links' and can later be inserted
6272 into an org-buffer with \\[org-insert-link].
6274 For some link types, a prefix arg is interpreted:
6275 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6276 For file links, arg negates `org-context-in-file-links'."
6277 (interactive "P")
6278 (org-load-modules-maybe)
6279 (setq org-store-link-plist nil) ; reset
6280 (let (link cpltxt desc description search txt)
6281 (cond
6283 ((run-hook-with-args-until-success 'org-store-link-functions)
6284 (setq link (plist-get org-store-link-plist :link)
6285 desc (or (plist-get org-store-link-plist :description) link)))
6287 ((eq major-mode 'calendar-mode)
6288 (let ((cd (calendar-cursor-to-date)))
6289 (setq link
6290 (format-time-string
6291 (car org-time-stamp-formats)
6292 (apply 'encode-time
6293 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6294 nil nil nil))))
6295 (org-store-link-props :type "calendar" :date cd)))
6297 ((eq major-mode 'w3-mode)
6298 (setq cpltxt (url-view-url t)
6299 link (org-make-link cpltxt))
6300 (org-store-link-props :type "w3" :url (url-view-url t)))
6302 ((eq major-mode 'w3m-mode)
6303 (setq cpltxt (or w3m-current-title w3m-current-url)
6304 link (org-make-link w3m-current-url))
6305 (org-store-link-props :type "w3m" :url (url-view-url t)))
6307 ((setq search (run-hook-with-args-until-success
6308 'org-create-file-search-functions))
6309 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6310 "::" search))
6311 (setq cpltxt (or description link)))
6313 ((eq major-mode 'image-mode)
6314 (setq cpltxt (concat "file:"
6315 (abbreviate-file-name buffer-file-name))
6316 link (org-make-link cpltxt))
6317 (org-store-link-props :type "image" :file buffer-file-name))
6319 ((eq major-mode 'dired-mode)
6320 ;; link to the file in the current line
6321 (setq cpltxt (concat "file:"
6322 (abbreviate-file-name
6323 (expand-file-name
6324 (dired-get-filename nil t))))
6325 link (org-make-link cpltxt)))
6327 ((and buffer-file-name (org-mode-p))
6328 ;; Just link to current headline
6329 (setq cpltxt (concat "file:"
6330 (abbreviate-file-name buffer-file-name)))
6331 ;; Add a context search string
6332 (when (org-xor org-context-in-file-links arg)
6333 ;; Check if we are on a target
6334 (if (org-in-regexp "<<\\(.*?\\)>>")
6335 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6336 (setq txt (cond
6337 ((org-on-heading-p) nil)
6338 ((org-region-active-p)
6339 (buffer-substring (region-beginning) (region-end)))
6340 (t nil)))
6341 (when (or (null txt) (string-match "\\S-" txt))
6342 (setq cpltxt
6343 (concat cpltxt "::"
6344 (condition-case nil
6345 (org-make-org-heading-search-string txt)
6346 (error "")))
6347 desc "NONE"))))
6348 (if (string-match "::\\'" cpltxt)
6349 (setq cpltxt (substring cpltxt 0 -2)))
6350 (setq link (org-make-link cpltxt)))
6352 ((buffer-file-name (buffer-base-buffer))
6353 ;; Just link to this file here.
6354 (setq cpltxt (concat "file:"
6355 (abbreviate-file-name
6356 (buffer-file-name (buffer-base-buffer)))))
6357 ;; Add a context string
6358 (when (org-xor org-context-in-file-links arg)
6359 (setq txt (if (org-region-active-p)
6360 (buffer-substring (region-beginning) (region-end))
6361 (buffer-substring (point-at-bol) (point-at-eol))))
6362 ;; Only use search option if there is some text.
6363 (when (string-match "\\S-" txt)
6364 (setq cpltxt
6365 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6366 desc "NONE")))
6367 (setq link (org-make-link cpltxt)))
6369 ((interactive-p)
6370 (error "Cannot link to a buffer which is not visiting a file"))
6372 (t (setq link nil)))
6374 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6375 (setq link (or link cpltxt)
6376 desc (or desc cpltxt))
6377 (if (equal desc "NONE") (setq desc nil))
6379 (if (and (interactive-p) link)
6380 (progn
6381 (setq org-stored-links
6382 (cons (list link desc) org-stored-links))
6383 (message "Stored: %s" (or desc link)))
6384 (and link (org-make-link-string link desc)))))
6386 (defun org-store-link-props (&rest plist)
6387 "Store link properties, extract names and addresses."
6388 (let (x adr)
6389 (when (setq x (plist-get plist :from))
6390 (setq adr (mail-extract-address-components x))
6391 (plist-put plist :fromname (car adr))
6392 (plist-put plist :fromaddress (nth 1 adr)))
6393 (when (setq x (plist-get plist :to))
6394 (setq adr (mail-extract-address-components x))
6395 (plist-put plist :toname (car adr))
6396 (plist-put plist :toaddress (nth 1 adr))))
6397 (let ((from (plist-get plist :from))
6398 (to (plist-get plist :to)))
6399 (when (and from to org-from-is-user-regexp)
6400 (plist-put plist :fromto
6401 (if (string-match org-from-is-user-regexp from)
6402 (concat "to %t")
6403 (concat "from %f")))))
6404 (setq org-store-link-plist plist))
6406 (defun org-add-link-props (&rest plist)
6407 "Add these properties to the link property list."
6408 (let (key value)
6409 (while plist
6410 (setq key (pop plist) value (pop plist))
6411 (setq org-store-link-plist
6412 (plist-put org-store-link-plist key value)))))
6414 (defun org-email-link-description (&optional fmt)
6415 "Return the description part of an email link.
6416 This takes information from `org-store-link-plist' and formats it
6417 according to FMT (default from `org-email-link-description-format')."
6418 (setq fmt (or fmt org-email-link-description-format))
6419 (let* ((p org-store-link-plist)
6420 (to (plist-get p :toaddress))
6421 (from (plist-get p :fromaddress))
6422 (table
6423 (list
6424 (cons "%c" (plist-get p :fromto))
6425 (cons "%F" (plist-get p :from))
6426 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6427 (cons "%T" (plist-get p :to))
6428 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6429 (cons "%s" (plist-get p :subject))
6430 (cons "%m" (plist-get p :message-id)))))
6431 (when (string-match "%c" fmt)
6432 ;; Check if the user wrote this message
6433 (if (and org-from-is-user-regexp from to
6434 (save-match-data (string-match org-from-is-user-regexp from)))
6435 (setq fmt (replace-match "to %t" t t fmt))
6436 (setq fmt (replace-match "from %f" t t fmt))))
6437 (org-replace-escapes fmt table)))
6439 (defun org-make-org-heading-search-string (&optional string heading)
6440 "Make search string for STRING or current headline."
6441 (interactive)
6442 (let ((s (or string (org-get-heading))))
6443 (unless (and string (not heading))
6444 ;; We are using a headline, clean up garbage in there.
6445 (if (string-match org-todo-regexp s)
6446 (setq s (replace-match "" t t s)))
6447 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6448 (setq s (replace-match "" t t s)))
6449 (setq s (org-trim s))
6450 (if (string-match (concat "^\\(" org-quote-string "\\|"
6451 org-comment-string "\\)") s)
6452 (setq s (replace-match "" t t s)))
6453 (while (string-match org-ts-regexp s)
6454 (setq s (replace-match "" t t s))))
6455 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6456 (setq s (replace-match " " t t s)))
6457 (or string (setq s (concat "*" s))) ; Add * for headlines
6458 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6460 (defun org-make-link (&rest strings)
6461 "Concatenate STRINGS."
6462 (apply 'concat strings))
6464 (defun org-make-link-string (link &optional description)
6465 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6466 (unless (string-match "\\S-" link)
6467 (error "Empty link"))
6468 (when (stringp description)
6469 ;; Remove brackets from the description, they are fatal.
6470 (while (string-match "\\[" description)
6471 (setq description (replace-match "{" t t description)))
6472 (while (string-match "\\]" description)
6473 (setq description (replace-match "}" t t description))))
6474 (when (equal (org-link-escape link) description)
6475 ;; No description needed, it is identical
6476 (setq description nil))
6477 (when (and (not description)
6478 (not (equal link (org-link-escape link))))
6479 (setq description link))
6480 (concat "[[" (org-link-escape link) "]"
6481 (if description (concat "[" description "]") "")
6482 "]"))
6484 (defconst org-link-escape-chars
6485 '((?\ . "%20")
6486 (?\[ . "%5B")
6487 (?\] . "%5D")
6488 (?\340 . "%E0") ; `a
6489 (?\342 . "%E2") ; ^a
6490 (?\347 . "%E7") ; ,c
6491 (?\350 . "%E8") ; `e
6492 (?\351 . "%E9") ; 'e
6493 (?\352 . "%EA") ; ^e
6494 (?\356 . "%EE") ; ^i
6495 (?\364 . "%F4") ; ^o
6496 (?\371 . "%F9") ; `u
6497 (?\373 . "%FB") ; ^u
6498 (?\; . "%3B")
6499 (?? . "%3F")
6500 (?= . "%3D")
6501 (?+ . "%2B")
6503 "Association list of escapes for some characters problematic in links.
6504 This is the list that is used for internal purposes.")
6506 (defconst org-link-escape-chars-browser
6507 '((?\ . "%20")) ; 32 for the SPC char
6508 "Association list of escapes for some characters problematic in links.
6509 This is the list that is used before handing over to the browser.")
6511 (defun org-link-escape (text &optional table)
6512 "Escape charaters in TEXT that are problematic for links."
6513 (setq table (or table org-link-escape-chars))
6514 (when text
6515 (let ((re (mapconcat (lambda (x) (regexp-quote
6516 (char-to-string (car x))))
6517 table "\\|")))
6518 (while (string-match re text)
6519 (setq text
6520 (replace-match
6521 (cdr (assoc (string-to-char (match-string 0 text))
6522 table))
6523 t t text)))
6524 text)))
6526 (defun org-link-unescape (text &optional table)
6527 "Reverse the action of `org-link-escape'."
6528 (setq table (or table org-link-escape-chars))
6529 (when text
6530 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6531 table "\\|")))
6532 (while (string-match re text)
6533 (setq text
6534 (replace-match
6535 (char-to-string (car (rassoc (match-string 0 text) table)))
6536 t t text)))
6537 text)))
6539 (defun org-xor (a b)
6540 "Exclusive or."
6541 (if a (not b) b))
6543 (defun org-get-header (header)
6544 "Find a header field in the current buffer."
6545 (save-excursion
6546 (goto-char (point-min))
6547 (let ((case-fold-search t) s)
6548 (cond
6549 ((eq header 'from)
6550 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6551 (setq s (match-string 1)))
6552 (while (string-match "\"" s)
6553 (setq s (replace-match "" t t s)))
6554 (if (string-match "[<(].*" s)
6555 (setq s (replace-match "" t t s))))
6556 ((eq header 'message-id)
6557 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6558 (setq s (match-string 1))))
6559 ((eq header 'subject)
6560 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6561 (setq s (match-string 1)))))
6562 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6563 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6564 s)))
6567 (defun org-fixup-message-id-for-http (s)
6568 "Replace special characters in a message id, so it can be used in an http query."
6569 (while (string-match "<" s)
6570 (setq s (replace-match "%3C" t t s)))
6571 (while (string-match ">" s)
6572 (setq s (replace-match "%3E" t t s)))
6573 (while (string-match "@" s)
6574 (setq s (replace-match "%40" t t s)))
6577 ;;;###autoload
6578 (defun org-insert-link-global ()
6579 "Insert a link like Org-mode does.
6580 This command can be called in any mode to insert a link in Org-mode syntax."
6581 (interactive)
6582 (org-load-modules-maybe)
6583 (org-run-like-in-org-mode 'org-insert-link))
6585 (defun org-insert-link (&optional complete-file link-location)
6586 "Insert a link. At the prompt, enter the link.
6588 Completion can be used to select a link previously stored with
6589 `org-store-link'. When the empty string is entered (i.e. if you just
6590 press RET at the prompt), the link defaults to the most recently
6591 stored link. As SPC triggers completion in the minibuffer, you need to
6592 use M-SPC or C-q SPC to force the insertion of a space character.
6594 You will also be prompted for a description, and if one is given, it will
6595 be displayed in the buffer instead of the link.
6597 If there is already a link at point, this command will allow you to edit link
6598 and description parts.
6600 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6601 be selected using completion. The path to the file will be relative to the
6602 current directory if the file is in the current directory or a subdirectory.
6603 Otherwise, the link will be the absolute path as completed in the minibuffer
6604 \(i.e. normally ~/path/to/file).
6606 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6607 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6608 of `org-keep-stored-link-after-insertion'.
6610 If `org-make-link-description-function' is non-nil, this function will be
6611 called with the link target, and the result will be the default
6612 link description.
6614 If the LINK-LOCATION parameter is non-nil, this value will be
6615 used as the link location instead of reading one interactively."
6616 (interactive "P")
6617 (let* ((wcf (current-window-configuration))
6618 (region (if (org-region-active-p)
6619 (buffer-substring (region-beginning) (region-end))))
6620 (remove (and region (list (region-beginning) (region-end))))
6621 (desc region)
6622 tmphist ; byte-compile incorrectly complains about this
6623 (link link-location)
6624 entry file)
6625 (cond
6626 (link-location) ; specified by arg, just use it.
6627 ((org-in-regexp org-bracket-link-regexp 1)
6628 ;; We do have a link at point, and we are going to edit it.
6629 (setq remove (list (match-beginning 0) (match-end 0)))
6630 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6631 (setq link (read-string "Link: "
6632 (org-link-unescape
6633 (org-match-string-no-properties 1)))))
6634 ((or (org-in-regexp org-angle-link-re)
6635 (org-in-regexp org-plain-link-re))
6636 ;; Convert to bracket link
6637 (setq remove (list (match-beginning 0) (match-end 0))
6638 link (read-string "Link: "
6639 (org-remove-angle-brackets (match-string 0)))))
6640 ((equal complete-file '(4))
6641 ;; Completing read for file names.
6642 (setq file (read-file-name "File: "))
6643 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6644 (pwd1 (file-name-as-directory (abbreviate-file-name
6645 (expand-file-name ".")))))
6646 (cond
6647 ((equal complete-file '(16))
6648 (setq link (org-make-link
6649 "file:"
6650 (abbreviate-file-name (expand-file-name file)))))
6651 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6652 (setq link (org-make-link "file:" (match-string 1 file))))
6653 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6654 (expand-file-name file))
6655 (setq link (org-make-link
6656 "file:" (match-string 1 (expand-file-name file)))))
6657 (t (setq link (org-make-link "file:" file))))))
6659 ;; Read link, with completion for stored links.
6660 (with-output-to-temp-buffer "*Org Links*"
6661 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6662 (when org-stored-links
6663 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6664 (princ (mapconcat
6665 (lambda (x)
6666 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6667 (reverse org-stored-links) "\n"))))
6668 (let ((cw (selected-window)))
6669 (select-window (get-buffer-window "*Org Links*"))
6670 (shrink-window-if-larger-than-buffer)
6671 (setq truncate-lines t)
6672 (select-window cw))
6673 ;; Fake a link history, containing the stored links.
6674 (setq tmphist (append (mapcar 'car org-stored-links)
6675 org-insert-link-history))
6676 (unwind-protect
6677 (setq link (org-completing-read
6678 "Link: "
6679 (append
6680 (mapcar (lambda (x) (list (concat (car x) ":")))
6681 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6682 (mapcar (lambda (x) (list (concat x ":")))
6683 org-link-types))
6684 nil nil nil
6685 'tmphist
6686 (or (car (car org-stored-links)))))
6687 (set-window-configuration wcf)
6688 (kill-buffer "*Org Links*"))
6689 (setq entry (assoc link org-stored-links))
6690 (or entry (push link org-insert-link-history))
6691 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6692 (not org-keep-stored-link-after-insertion))
6693 (setq org-stored-links (delq (assoc link org-stored-links)
6694 org-stored-links)))
6695 (setq desc (or desc (nth 1 entry)))))
6697 (if (string-match org-plain-link-re link)
6698 ;; URL-like link, normalize the use of angular brackets.
6699 (setq link (org-make-link (org-remove-angle-brackets link))))
6701 ;; Check if we are linking to the current file with a search option
6702 ;; If yes, simplify the link by using only the search option.
6703 (when (and buffer-file-name
6704 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6705 (let* ((path (match-string 1 link))
6706 (case-fold-search nil)
6707 (search (match-string 2 link)))
6708 (save-match-data
6709 (if (equal (file-truename buffer-file-name) (file-truename path))
6710 ;; We are linking to this same file, with a search option
6711 (setq link search)))))
6713 ;; Check if we can/should use a relative path. If yes, simplify the link
6714 (when (string-match "\\<file:\\(.*\\)" link)
6715 (let* ((path (match-string 1 link))
6716 (origpath path)
6717 (case-fold-search nil))
6718 (cond
6719 ((eq org-link-file-path-type 'absolute)
6720 (setq path (abbreviate-file-name (expand-file-name path))))
6721 ((eq org-link-file-path-type 'noabbrev)
6722 (setq path (expand-file-name path)))
6723 ((eq org-link-file-path-type 'relative)
6724 (setq path (file-relative-name path)))
6726 (save-match-data
6727 (if (string-match (concat "^" (regexp-quote
6728 (file-name-as-directory
6729 (expand-file-name "."))))
6730 (expand-file-name path))
6731 ;; We are linking a file with relative path name.
6732 (setq path (substring (expand-file-name path)
6733 (match-end 0)))))))
6734 (setq link (concat "file:" path))
6735 (if (equal desc origpath)
6736 (setq desc path))))
6738 (if org-make-link-description-function
6739 (setq desc (funcall org-make-link-description-function link desc)))
6741 (setq desc (read-string "Description: " desc))
6742 (unless (string-match "\\S-" desc) (setq desc nil))
6743 (if remove (apply 'delete-region remove))
6744 (insert (org-make-link-string link desc))))
6746 (defun org-completing-read (&rest args)
6747 (let ((minibuffer-local-completion-map
6748 (copy-keymap minibuffer-local-completion-map)))
6749 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6750 (apply 'completing-read args)))
6752 ;;; Opening/following a link
6754 (defvar org-link-search-failed nil)
6756 (defun org-next-link ()
6757 "Move forward to the next link.
6758 If the link is in hidden text, expose it."
6759 (interactive)
6760 (when (and org-link-search-failed (eq this-command last-command))
6761 (goto-char (point-min))
6762 (message "Link search wrapped back to beginning of buffer"))
6763 (setq org-link-search-failed nil)
6764 (let* ((pos (point))
6765 (ct (org-context))
6766 (a (assoc :link ct)))
6767 (if a (goto-char (nth 2 a)))
6768 (if (re-search-forward org-any-link-re nil t)
6769 (progn
6770 (goto-char (match-beginning 0))
6771 (if (org-invisible-p) (org-show-context)))
6772 (goto-char pos)
6773 (setq org-link-search-failed t)
6774 (error "No further link found"))))
6776 (defun org-previous-link ()
6777 "Move backward to the previous link.
6778 If the link is in hidden text, expose it."
6779 (interactive)
6780 (when (and org-link-search-failed (eq this-command last-command))
6781 (goto-char (point-max))
6782 (message "Link search wrapped back to end of buffer"))
6783 (setq org-link-search-failed nil)
6784 (let* ((pos (point))
6785 (ct (org-context))
6786 (a (assoc :link ct)))
6787 (if a (goto-char (nth 1 a)))
6788 (if (re-search-backward org-any-link-re nil t)
6789 (progn
6790 (goto-char (match-beginning 0))
6791 (if (org-invisible-p) (org-show-context)))
6792 (goto-char pos)
6793 (setq org-link-search-failed t)
6794 (error "No further link found"))))
6796 (defun org-find-file-at-mouse (ev)
6797 "Open file link or URL at mouse."
6798 (interactive "e")
6799 (mouse-set-point ev)
6800 (org-open-at-point 'in-emacs))
6802 (defun org-open-at-mouse (ev)
6803 "Open file link or URL at mouse."
6804 (interactive "e")
6805 (mouse-set-point ev)
6806 (org-open-at-point))
6808 (defvar org-window-config-before-follow-link nil
6809 "The window configuration before following a link.
6810 This is saved in case the need arises to restore it.")
6812 (defvar org-open-link-marker (make-marker)
6813 "Marker pointing to the location where `org-open-at-point; was called.")
6815 ;;;###autoload
6816 (defun org-open-at-point-global ()
6817 "Follow a link like Org-mode does.
6818 This command can be called in any mode to follow a link that has
6819 Org-mode syntax."
6820 (interactive)
6821 (org-run-like-in-org-mode 'org-open-at-point))
6823 ;;;###autoload
6824 (defun org-open-link-from-string (s &optional arg)
6825 "Open a link in the string S, as if it was in Org-mode."
6826 (interactive "sLink: \nP")
6827 (with-temp-buffer
6828 (let ((org-inhibit-startup t))
6829 (org-mode)
6830 (insert s)
6831 (goto-char (point-min))
6832 (org-open-at-point arg))))
6834 (defun org-open-at-point (&optional in-emacs)
6835 "Open link at or after point.
6836 If there is no link at point, this function will search forward up to
6837 the end of the current subtree.
6838 Normally, files will be opened by an appropriate application. If the
6839 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6840 (interactive "P")
6841 (org-load-modules-maybe)
6842 (move-marker org-open-link-marker (point))
6843 (setq org-window-config-before-follow-link (current-window-configuration))
6844 (org-remove-occur-highlights nil nil t)
6845 (if (org-at-timestamp-p t)
6846 (org-follow-timestamp-link)
6847 (let (type path link line search (pos (point)))
6848 (catch 'match
6849 (save-excursion
6850 (skip-chars-forward "^]\n\r")
6851 (when (org-in-regexp org-bracket-link-regexp)
6852 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6853 (while (string-match " *\n *" link)
6854 (setq link (replace-match " " t t link)))
6855 (setq link (org-link-expand-abbrev link))
6856 (if (string-match org-link-re-with-space2 link)
6857 (setq type (match-string 1 link) path (match-string 2 link))
6858 (setq type "thisfile" path link))
6859 (throw 'match t)))
6861 (when (get-text-property (point) 'org-linked-text)
6862 (setq type "thisfile"
6863 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6864 (1+ (point)) (point))
6865 path (buffer-substring
6866 (previous-single-property-change pos 'org-linked-text)
6867 (next-single-property-change pos 'org-linked-text)))
6868 (throw 'match t))
6870 (save-excursion
6871 (when (or (org-in-regexp org-angle-link-re)
6872 (org-in-regexp org-plain-link-re))
6873 (setq type (match-string 1) path (match-string 2))
6874 (throw 'match t)))
6875 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6876 (setq type "tree-match"
6877 path (match-string 1))
6878 (throw 'match t))
6879 (save-excursion
6880 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6881 (setq type "tags"
6882 path (match-string 1))
6883 (while (string-match ":" path)
6884 (setq path (replace-match "+" t t path)))
6885 (throw 'match t))))
6886 (unless path
6887 (error "No link found"))
6888 ;; Remove any trailing spaces in path
6889 (if (string-match " +\\'" path)
6890 (setq path (replace-match "" t t path)))
6892 (cond
6894 ((assoc type org-link-protocols)
6895 (funcall (nth 1 (assoc type org-link-protocols)) path))
6897 ((equal type "mailto")
6898 (let ((cmd (car org-link-mailto-program))
6899 (args (cdr org-link-mailto-program)) args1
6900 (address path) (subject "") a)
6901 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6902 (setq address (match-string 1 path)
6903 subject (org-link-escape (match-string 2 path))))
6904 (while args
6905 (cond
6906 ((not (stringp (car args))) (push (pop args) args1))
6907 (t (setq a (pop args))
6908 (if (string-match "%a" a)
6909 (setq a (replace-match address t t a)))
6910 (if (string-match "%s" a)
6911 (setq a (replace-match subject t t a)))
6912 (push a args1))))
6913 (apply cmd (nreverse args1))))
6915 ((member type '("http" "https" "ftp" "news"))
6916 (browse-url (concat type ":" (org-link-escape
6917 path org-link-escape-chars-browser))))
6919 ((member type '("message"))
6920 (browse-url (concat type ":" path)))
6922 ((string= type "tags")
6923 (org-tags-view in-emacs path))
6924 ((string= type "thisfile")
6925 (if in-emacs
6926 (switch-to-buffer-other-window
6927 (org-get-buffer-for-internal-link (current-buffer)))
6928 (org-mark-ring-push))
6929 (let ((cmd `(org-link-search
6930 ,path
6931 ,(cond ((equal in-emacs '(4)) 'occur)
6932 ((equal in-emacs '(16)) 'org-occur)
6933 (t nil))
6934 ,pos)))
6935 (condition-case nil (eval cmd)
6936 (error (progn (widen) (eval cmd))))))
6938 ((string= type "tree-match")
6939 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6941 ((string= type "file")
6942 (if (string-match "::\\([0-9]+\\)\\'" path)
6943 (setq line (string-to-number (match-string 1 path))
6944 path (substring path 0 (match-beginning 0)))
6945 (if (string-match "::\\(.+\\)\\'" path)
6946 (setq search (match-string 1 path)
6947 path (substring path 0 (match-beginning 0)))))
6948 (if (string-match "[*?{]" (file-name-nondirectory path))
6949 (dired path)
6950 (org-open-file path in-emacs line search)))
6952 ((string= type "news")
6953 (require 'org-gnus)
6954 (org-gnus-follow-link path))
6956 ((string= type "shell")
6957 (let ((cmd path))
6958 (if (or (not org-confirm-shell-link-function)
6959 (funcall org-confirm-shell-link-function
6960 (format "Execute \"%s\" in shell? "
6961 (org-add-props cmd nil
6962 'face 'org-warning))))
6963 (progn
6964 (message "Executing %s" cmd)
6965 (shell-command cmd))
6966 (error "Abort"))))
6968 ((string= type "elisp")
6969 (let ((cmd path))
6970 (if (or (not org-confirm-elisp-link-function)
6971 (funcall org-confirm-elisp-link-function
6972 (format "Execute \"%s\" as elisp? "
6973 (org-add-props cmd nil
6974 'face 'org-warning))))
6975 (message "%s => %s" cmd (eval (read cmd)))
6976 (error "Abort"))))
6979 (browse-url-at-point)))))
6980 (move-marker org-open-link-marker nil)
6981 (run-hook-with-args 'org-follow-link-hook))
6983 ;;;; Time estimates
6985 (defun org-get-effort (&optional pom)
6986 "Get the effort estimate for the current entry."
6987 (org-entry-get pom org-effort-property))
6989 ;;; File search
6991 (defvar org-create-file-search-functions nil
6992 "List of functions to construct the right search string for a file link.
6993 These functions are called in turn with point at the location to
6994 which the link should point.
6996 A function in the hook should first test if it would like to
6997 handle this file type, for example by checking the major-mode or
6998 the file extension. If it decides not to handle this file, it
6999 should just return nil to give other functions a chance. If it
7000 does handle the file, it must return the search string to be used
7001 when following the link. The search string will be part of the
7002 file link, given after a double colon, and `org-open-at-point'
7003 will automatically search for it. If special measures must be
7004 taken to make the search successful, another function should be
7005 added to the companion hook `org-execute-file-search-functions',
7006 which see.
7008 A function in this hook may also use `setq' to set the variable
7009 `description' to provide a suggestion for the descriptive text to
7010 be used for this link when it gets inserted into an Org-mode
7011 buffer with \\[org-insert-link].")
7013 (defvar org-execute-file-search-functions nil
7014 "List of functions to execute a file search triggered by a link.
7016 Functions added to this hook must accept a single argument, the
7017 search string that was part of the file link, the part after the
7018 double colon. The function must first check if it would like to
7019 handle this search, for example by checking the major-mode or the
7020 file extension. If it decides not to handle this search, it
7021 should just return nil to give other functions a chance. If it
7022 does handle the search, it must return a non-nil value to keep
7023 other functions from trying.
7025 Each function can access the current prefix argument through the
7026 variable `current-prefix-argument'. Note that a single prefix is
7027 used to force opening a link in Emacs, so it may be good to only
7028 use a numeric or double prefix to guide the search function.
7030 In case this is needed, a function in this hook can also restore
7031 the window configuration before `org-open-at-point' was called using:
7033 (set-window-configuration org-window-config-before-follow-link)")
7035 (defun org-link-search (s &optional type avoid-pos)
7036 "Search for a link search option.
7037 If S is surrounded by forward slashes, it is interpreted as a
7038 regular expression. In org-mode files, this will create an `org-occur'
7039 sparse tree. In ordinary files, `occur' will be used to list matches.
7040 If the current buffer is in `dired-mode', grep will be used to search
7041 in all files. If AVOID-POS is given, ignore matches near that position."
7042 (let ((case-fold-search t)
7043 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7044 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7045 (append '(("") (" ") ("\t") ("\n"))
7046 org-emphasis-alist)
7047 "\\|") "\\)"))
7048 (pos (point))
7049 (pre nil) (post nil)
7050 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7051 (cond
7052 ;; First check if there are any special
7053 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7054 ;; Now try the builtin stuff
7055 ((save-excursion
7056 (goto-char (point-min))
7057 (and
7058 (re-search-forward
7059 (concat "<<" (regexp-quote s0) ">>") nil t)
7060 (setq type 'dedicated
7061 pos (match-beginning 0))))
7062 ;; There is an exact target for this
7063 (goto-char pos))
7064 ((string-match "^/\\(.*\\)/$" s)
7065 ;; A regular expression
7066 (cond
7067 ((org-mode-p)
7068 (org-occur (match-string 1 s)))
7069 ;;((eq major-mode 'dired-mode)
7070 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7071 (t (org-do-occur (match-string 1 s)))))
7073 ;; A normal search strings
7074 (when (equal (string-to-char s) ?*)
7075 ;; Anchor on headlines, post may include tags.
7076 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7077 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7078 s (substring s 1)))
7079 (remove-text-properties
7080 0 (length s)
7081 '(face nil mouse-face nil keymap nil fontified nil) s)
7082 ;; Make a series of regular expressions to find a match
7083 (setq words (org-split-string s "[ \n\r\t]+")
7085 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7086 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7087 "\\)" markers)
7088 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7089 re2a (concat "[ \t\r\n]" re2a_)
7090 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7091 re4 (concat "[^a-zA-Z_]" re4_)
7093 re1 (concat pre re2 post)
7094 re3 (concat pre (if pre re4_ re4) post)
7095 re5 (concat pre ".*" re4)
7096 re2 (concat pre re2)
7097 re2a (concat pre (if pre re2a_ re2a))
7098 re4 (concat pre (if pre re4_ re4))
7099 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7100 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7101 re5 "\\)"
7103 (cond
7104 ((eq type 'org-occur) (org-occur reall))
7105 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7106 (t (goto-char (point-min))
7107 (setq type 'fuzzy)
7108 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7109 (org-search-not-self 1 re1 nil t)
7110 (org-search-not-self 1 re2 nil t)
7111 (org-search-not-self 1 re2a nil t)
7112 (org-search-not-self 1 re3 nil t)
7113 (org-search-not-self 1 re4 nil t)
7114 (org-search-not-self 1 re5 nil t)
7116 (goto-char (match-beginning 1))
7117 (goto-char pos)
7118 (error "No match")))))
7120 ;; Normal string-search
7121 (goto-char (point-min))
7122 (if (search-forward s nil t)
7123 (goto-char (match-beginning 0))
7124 (error "No match"))))
7125 (and (org-mode-p) (org-show-context 'link-search))
7126 type))
7128 (defun org-search-not-self (group &rest args)
7129 "Execute `re-search-forward', but only accept matches that do not
7130 enclose the position of `org-open-link-marker'."
7131 (let ((m org-open-link-marker))
7132 (catch 'exit
7133 (while (apply 're-search-forward args)
7134 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7135 (goto-char (match-end group))
7136 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7137 (> (match-beginning 0) (marker-position m))
7138 (< (match-end 0) (marker-position m)))
7139 (save-match-data
7140 (or (not (org-in-regexp
7141 org-bracket-link-analytic-regexp 1))
7142 (not (match-end 4)) ; no description
7143 (and (<= (match-beginning 4) (point))
7144 (>= (match-end 4) (point))))))
7145 (throw 'exit (point))))))))
7147 (defun org-get-buffer-for-internal-link (buffer)
7148 "Return a buffer to be used for displaying the link target of internal links."
7149 (cond
7150 ((not org-display-internal-link-with-indirect-buffer)
7151 buffer)
7152 ((string-match "(Clone)$" (buffer-name buffer))
7153 (message "Buffer is already a clone, not making another one")
7154 ;; we also do not modify visibility in this case
7155 buffer)
7156 (t ; make a new indirect buffer for displaying the link
7157 (let* ((bn (buffer-name buffer))
7158 (ibn (concat bn "(Clone)"))
7159 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7160 (with-current-buffer ib (org-overview))
7161 ib))))
7163 (defun org-do-occur (regexp &optional cleanup)
7164 "Call the Emacs command `occur'.
7165 If CLEANUP is non-nil, remove the printout of the regular expression
7166 in the *Occur* buffer. This is useful if the regex is long and not useful
7167 to read."
7168 (occur regexp)
7169 (when cleanup
7170 (let ((cwin (selected-window)) win beg end)
7171 (when (setq win (get-buffer-window "*Occur*"))
7172 (select-window win))
7173 (goto-char (point-min))
7174 (when (re-search-forward "match[a-z]+" nil t)
7175 (setq beg (match-end 0))
7176 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7177 (setq end (1- (match-beginning 0)))))
7178 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7179 (goto-char (point-min))
7180 (select-window cwin))))
7182 ;;; The mark ring for links jumps
7184 (defvar org-mark-ring nil
7185 "Mark ring for positions before jumps in Org-mode.")
7186 (defvar org-mark-ring-last-goto nil
7187 "Last position in the mark ring used to go back.")
7188 ;; Fill and close the ring
7189 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7190 (loop for i from 1 to org-mark-ring-length do
7191 (push (make-marker) org-mark-ring))
7192 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7193 org-mark-ring)
7195 (defun org-mark-ring-push (&optional pos buffer)
7196 "Put the current position or POS into the mark ring and rotate it."
7197 (interactive)
7198 (setq pos (or pos (point)))
7199 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7200 (move-marker (car org-mark-ring)
7201 (or pos (point))
7202 (or buffer (current-buffer)))
7203 (message "%s"
7204 (substitute-command-keys
7205 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7207 (defun org-mark-ring-goto (&optional n)
7208 "Jump to the previous position in the mark ring.
7209 With prefix arg N, jump back that many stored positions. When
7210 called several times in succession, walk through the entire ring.
7211 Org-mode commands jumping to a different position in the current file,
7212 or to another Org-mode file, automatically push the old position
7213 onto the ring."
7214 (interactive "p")
7215 (let (p m)
7216 (if (eq last-command this-command)
7217 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7218 (setq p org-mark-ring))
7219 (setq org-mark-ring-last-goto p)
7220 (setq m (car p))
7221 (switch-to-buffer (marker-buffer m))
7222 (goto-char m)
7223 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7225 (defun org-remove-angle-brackets (s)
7226 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7227 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7229 (defun org-add-angle-brackets (s)
7230 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7231 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7233 (defun org-remove-double-quotes (s)
7234 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7235 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7238 ;;; Following specific links
7240 (defun org-follow-timestamp-link ()
7241 (cond
7242 ((org-at-date-range-p t)
7243 (let ((org-agenda-start-on-weekday)
7244 (t1 (match-string 1))
7245 (t2 (match-string 2)))
7246 (setq t1 (time-to-days (org-time-string-to-time t1))
7247 t2 (time-to-days (org-time-string-to-time t2)))
7248 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7249 ((org-at-timestamp-p t)
7250 (org-agenda-list nil (time-to-days (org-time-string-to-time
7251 (substring (match-string 1) 0 10)))
7253 (t (error "This should not happen"))))
7256 ;;; Following file links
7257 (defvar org-wait nil)
7258 (defun org-open-file (path &optional in-emacs line search)
7259 "Open the file at PATH.
7260 First, this expands any special file name abbreviations. Then the
7261 configuration variable `org-file-apps' is checked if it contains an
7262 entry for this file type, and if yes, the corresponding command is launched.
7263 If no application is found, Emacs simply visits the file.
7264 With optional argument IN-EMACS, Emacs will visit the file.
7265 Optional LINE specifies a line to go to, optional SEARCH a string to
7266 search for. If LINE or SEARCH is given, the file will always be
7267 opened in Emacs.
7268 If the file does not exist, an error is thrown."
7269 (setq in-emacs (or in-emacs line search))
7270 (let* ((file (if (equal path "")
7271 buffer-file-name
7272 (substitute-in-file-name (expand-file-name path))))
7273 (apps (append org-file-apps (org-default-apps)))
7274 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7275 (dirp (if remp nil (file-directory-p file)))
7276 (dfile (downcase file))
7277 (old-buffer (current-buffer))
7278 (old-pos (point))
7279 (old-mode major-mode)
7280 ext cmd)
7281 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7282 (setq ext (match-string 1 dfile))
7283 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7284 (setq ext (match-string 1 dfile))))
7285 (if in-emacs
7286 (setq cmd 'emacs)
7287 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7288 (and dirp (cdr (assoc 'directory apps)))
7289 (cdr (assoc ext apps))
7290 (cdr (assoc t apps)))))
7291 (when (eq cmd 'mailcap)
7292 (require 'mailcap)
7293 (mailcap-parse-mailcaps)
7294 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7295 (command (mailcap-mime-info mime-type)))
7296 (if (stringp command)
7297 (setq cmd command)
7298 (setq cmd 'emacs))))
7299 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7300 (not (file-exists-p file))
7301 (not org-open-non-existing-files))
7302 (error "No such file: %s" file))
7303 (cond
7304 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7305 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7306 (while (string-match "['\"]%s['\"]" cmd)
7307 (setq cmd (replace-match "%s" t t cmd)))
7308 (while (string-match "%s" cmd)
7309 (setq cmd (replace-match
7310 (save-match-data (shell-quote-argument file))
7311 t t cmd)))
7312 (save-window-excursion
7313 (start-process-shell-command cmd nil cmd)
7314 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7316 ((or (stringp cmd)
7317 (eq cmd 'emacs))
7318 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7319 (widen)
7320 (if line (goto-line line)
7321 (if search (org-link-search search))))
7322 ((consp cmd)
7323 (eval cmd))
7324 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7325 (and (org-mode-p) (eq old-mode 'org-mode)
7326 (or (not (equal old-buffer (current-buffer)))
7327 (not (equal old-pos (point))))
7328 (org-mark-ring-push old-pos old-buffer))))
7330 (defun org-default-apps ()
7331 "Return the default applications for this operating system."
7332 (cond
7333 ((eq system-type 'darwin)
7334 org-file-apps-defaults-macosx)
7335 ((eq system-type 'windows-nt)
7336 org-file-apps-defaults-windowsnt)
7337 (t org-file-apps-defaults-gnu)))
7339 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7340 (defun org-file-remote-p (file)
7341 "Test whether FILE specifies a location on a remote system.
7342 Return non-nil if the location is indeed remote.
7344 For example, the filename \"/user@host:/foo\" specifies a location
7345 on the system \"/user@host:\"."
7346 (cond ((fboundp 'file-remote-p)
7347 (file-remote-p file))
7348 ((fboundp 'tramp-handle-file-remote-p)
7349 (tramp-handle-file-remote-p file))
7350 ((and (boundp 'ange-ftp-name-format)
7351 (string-match (car ange-ftp-name-format) file))
7353 (t nil)))
7356 ;;;; Refiling
7358 (defun org-get-org-file ()
7359 "Read a filename, with default directory `org-directory'."
7360 (let ((default (or org-default-notes-file remember-data-file)))
7361 (read-file-name (format "File name [%s]: " default)
7362 (file-name-as-directory org-directory)
7363 default)))
7365 (defun org-notes-order-reversed-p ()
7366 "Check if the current file should receive notes in reversed order."
7367 (cond
7368 ((not org-reverse-note-order) nil)
7369 ((eq t org-reverse-note-order) t)
7370 ((not (listp org-reverse-note-order)) nil)
7371 (t (catch 'exit
7372 (let ((all org-reverse-note-order)
7373 entry)
7374 (while (setq entry (pop all))
7375 (if (string-match (car entry) buffer-file-name)
7376 (throw 'exit (cdr entry))))
7377 nil)))))
7379 (defvar org-refile-target-table nil
7380 "The list of refile targets, created by `org-refile'.")
7382 (defvar org-agenda-new-buffers nil
7383 "Buffers created to visit agenda files.")
7385 (defun org-get-refile-targets (&optional default-buffer)
7386 "Produce a table with refile targets."
7387 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7388 targets txt re files f desc descre)
7389 (with-current-buffer (or default-buffer (current-buffer))
7390 (while (setq entry (pop entries))
7391 (setq files (car entry) desc (cdr entry))
7392 (cond
7393 ((null files) (setq files (list (current-buffer))))
7394 ((eq files 'org-agenda-files)
7395 (setq files (org-agenda-files 'unrestricted)))
7396 ((and (symbolp files) (fboundp files))
7397 (setq files (funcall files)))
7398 ((and (symbolp files) (boundp files))
7399 (setq files (symbol-value files))))
7400 (if (stringp files) (setq files (list files)))
7401 (cond
7402 ((eq (car desc) :tag)
7403 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7404 ((eq (car desc) :todo)
7405 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7406 ((eq (car desc) :regexp)
7407 (setq descre (cdr desc)))
7408 ((eq (car desc) :level)
7409 (setq descre (concat "^\\*\\{" (number-to-string
7410 (if org-odd-levels-only
7411 (1- (* 2 (cdr desc)))
7412 (cdr desc)))
7413 "\\}[ \t]")))
7414 ((eq (car desc) :maxlevel)
7415 (setq descre (concat "^\\*\\{1," (number-to-string
7416 (if org-odd-levels-only
7417 (1- (* 2 (cdr desc)))
7418 (cdr desc)))
7419 "\\}[ \t]")))
7420 (t (error "Bad refiling target description %s" desc)))
7421 (while (setq f (pop files))
7422 (save-excursion
7423 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7424 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7425 (save-excursion
7426 (save-restriction
7427 (widen)
7428 (goto-char (point-min))
7429 (while (re-search-forward descre nil t)
7430 (goto-char (point-at-bol))
7431 (when (looking-at org-complex-heading-regexp)
7432 (setq txt (match-string 4)
7433 re (concat "^" (regexp-quote
7434 (buffer-substring (match-beginning 1)
7435 (match-end 4)))))
7436 (if (match-end 5) (setq re (concat re "[ \t]+"
7437 (regexp-quote
7438 (match-string 5)))))
7439 (setq re (concat re "[ \t]*$"))
7440 (when org-refile-use-outline-path
7441 (setq txt (mapconcat 'identity
7442 (append
7443 (if (eq org-refile-use-outline-path 'file)
7444 (list (file-name-nondirectory
7445 (buffer-file-name (buffer-base-buffer))))
7446 (if (eq org-refile-use-outline-path 'full-file-path)
7447 (list (buffer-file-name (buffer-base-buffer)))))
7448 (org-get-outline-path)
7449 (list txt))
7450 "/")))
7451 (push (list txt f re (point)) targets))
7452 (goto-char (point-at-eol))))))))
7453 (nreverse targets))))
7455 (defun org-get-outline-path ()
7456 "Return the outline path to the current entry, as a list."
7457 (let (rtn)
7458 (save-excursion
7459 (while (org-up-heading-safe)
7460 (when (looking-at org-complex-heading-regexp)
7461 (push (org-match-string-no-properties 4) rtn)))
7462 rtn)))
7464 (defvar org-refile-history nil
7465 "History for refiling operations.")
7467 (defun org-refile (&optional goto default-buffer)
7468 "Move the entry at point to another heading.
7469 The list of target headings is compiled using the information in
7470 `org-refile-targets', which see. This list is created before each use
7471 and will therefore always be up-to-date.
7473 At the target location, the entry is filed as a subitem of the target heading.
7474 Depending on `org-reverse-note-order', the new subitem will either be the
7475 first of the last subitem.
7477 With prefix arg GOTO, the command will only visit the target location,
7478 not actually move anything.
7479 With a double prefix `C-c C-c', go to the location where the last refiling
7480 operation has put the subtree."
7481 (interactive "P")
7482 (let* ((cbuf (current-buffer))
7483 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7484 pos it nbuf file re level reversed)
7485 (if (equal goto '(16))
7486 (org-refile-goto-last-stored)
7487 (when (setq it (org-refile-get-location
7488 (if goto "Goto: " "Refile to: ") default-buffer))
7489 (setq file (nth 1 it)
7490 re (nth 2 it)
7491 pos (nth 3 it))
7492 (setq nbuf (or (find-buffer-visiting file)
7493 (find-file-noselect file)))
7494 (if goto
7495 (progn
7496 (switch-to-buffer nbuf)
7497 (goto-char pos)
7498 (org-show-context 'org-goto))
7499 (org-copy-subtree 1 nil t)
7500 (save-excursion
7501 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7502 (find-file-noselect file))))
7503 (setq reversed (org-notes-order-reversed-p))
7504 (save-excursion
7505 (save-restriction
7506 (widen)
7507 (goto-char pos)
7508 (looking-at outline-regexp)
7509 (setq level (org-get-valid-level (funcall outline-level) 1))
7510 (goto-char
7511 (if reversed
7512 (outline-next-heading)
7513 (or (save-excursion (outline-get-next-sibling))
7514 (org-end-of-subtree t t)
7515 (point-max))))
7516 (bookmark-set "org-refile-last-stored")
7517 (org-paste-subtree level))))
7518 (org-cut-subtree)
7519 (setq org-markers-to-move nil)
7520 (message "Entry refiled to \"%s\"" (car it)))))))
7522 (defun org-refile-goto-last-stored ()
7523 "Go to the location where the last refile was stored."
7524 (interactive)
7525 (bookmark-jump "org-refile-last-stored")
7526 (message "This is the location of the last refile"))
7528 (defun org-refile-get-location (&optional prompt default-buffer)
7529 "Prompt the user for a refile location, using PROMPT."
7530 (let ((org-refile-targets org-refile-targets)
7531 (org-refile-use-outline-path org-refile-use-outline-path))
7532 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7533 (unless org-refile-target-table
7534 (error "No refile targets"))
7535 (let* ((cbuf (current-buffer))
7536 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7537 (fname (and filename (file-truename filename)))
7538 (tbl (mapcar
7539 (lambda (x)
7540 (if (not (equal fname (file-truename (nth 1 x))))
7541 (cons (concat (car x) " (" (file-name-nondirectory
7542 (nth 1 x)) ")")
7543 (cdr x))
7545 org-refile-target-table))
7546 (completion-ignore-case t))
7547 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7548 tbl)))
7550 ;;;; Dynamic blocks
7552 (defun org-find-dblock (name)
7553 "Find the first dynamic block with name NAME in the buffer.
7554 If not found, stay at current position and return nil."
7555 (let (pos)
7556 (save-excursion
7557 (goto-char (point-min))
7558 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7559 nil t)
7560 (match-beginning 0))))
7561 (if pos (goto-char pos))
7562 pos))
7564 (defconst org-dblock-start-re
7565 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7566 "Matches the startline of a dynamic block, with parameters.")
7568 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7569 "Matches the end of a dyhamic block.")
7571 (defun org-create-dblock (plist)
7572 "Create a dynamic block section, with parameters taken from PLIST.
7573 PLIST must containe a :name entry which is used as name of the block."
7574 (unless (bolp) (newline))
7575 (let ((name (plist-get plist :name)))
7576 (insert "#+BEGIN: " name)
7577 (while plist
7578 (if (eq (car plist) :name)
7579 (setq plist (cddr plist))
7580 (insert " " (prin1-to-string (pop plist)))))
7581 (insert "\n\n#+END:\n")
7582 (beginning-of-line -2)))
7584 (defun org-prepare-dblock ()
7585 "Prepare dynamic block for refresh.
7586 This empties the block, puts the cursor at the insert position and returns
7587 the property list including an extra property :name with the block name."
7588 (unless (looking-at org-dblock-start-re)
7589 (error "Not at a dynamic block"))
7590 (let* ((begdel (1+ (match-end 0)))
7591 (name (org-no-properties (match-string 1)))
7592 (params (append (list :name name)
7593 (read (concat "(" (match-string 3) ")")))))
7594 (unless (re-search-forward org-dblock-end-re nil t)
7595 (error "Dynamic block not terminated"))
7596 (setq params
7597 (append params
7598 (list :content (buffer-substring
7599 begdel (match-beginning 0)))))
7600 (delete-region begdel (match-beginning 0))
7601 (goto-char begdel)
7602 (open-line 1)
7603 params))
7605 (defun org-map-dblocks (&optional command)
7606 "Apply COMMAND to all dynamic blocks in the current buffer.
7607 If COMMAND is not given, use `org-update-dblock'."
7608 (let ((cmd (or command 'org-update-dblock))
7609 pos)
7610 (save-excursion
7611 (goto-char (point-min))
7612 (while (re-search-forward org-dblock-start-re nil t)
7613 (goto-char (setq pos (match-beginning 0)))
7614 (condition-case nil
7615 (funcall cmd)
7616 (error (message "Error during update of dynamic block")))
7617 (goto-char pos)
7618 (unless (re-search-forward org-dblock-end-re nil t)
7619 (error "Dynamic block not terminated"))))))
7621 (defun org-dblock-update (&optional arg)
7622 "User command for updating dynamic blocks.
7623 Update the dynamic block at point. With prefix ARG, update all dynamic
7624 blocks in the buffer."
7625 (interactive "P")
7626 (if arg
7627 (org-update-all-dblocks)
7628 (or (looking-at org-dblock-start-re)
7629 (org-beginning-of-dblock))
7630 (org-update-dblock)))
7632 (defun org-update-dblock ()
7633 "Update the dynamic block at point
7634 This means to empty the block, parse for parameters and then call
7635 the correct writing function."
7636 (save-window-excursion
7637 (let* ((pos (point))
7638 (line (org-current-line))
7639 (params (org-prepare-dblock))
7640 (name (plist-get params :name))
7641 (cmd (intern (concat "org-dblock-write:" name))))
7642 (message "Updating dynamic block `%s' at line %d..." name line)
7643 (funcall cmd params)
7644 (message "Updating dynamic block `%s' at line %d...done" name line)
7645 (goto-char pos))))
7647 (defun org-beginning-of-dblock ()
7648 "Find the beginning of the dynamic block at point.
7649 Error if there is no scuh block at point."
7650 (let ((pos (point))
7651 beg)
7652 (end-of-line 1)
7653 (if (and (re-search-backward org-dblock-start-re nil t)
7654 (setq beg (match-beginning 0))
7655 (re-search-forward org-dblock-end-re nil t)
7656 (> (match-end 0) pos))
7657 (goto-char beg)
7658 (goto-char pos)
7659 (error "Not in a dynamic block"))))
7661 (defun org-update-all-dblocks ()
7662 "Update all dynamic blocks in the buffer.
7663 This function can be used in a hook."
7664 (when (org-mode-p)
7665 (org-map-dblocks 'org-update-dblock)))
7668 ;;;; Completion
7670 (defconst org-additional-option-like-keywords
7671 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7672 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7673 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7675 (defcustom org-structure-template-alist
7677 ("s" "#+begin_src ?\n\n#+end_src")
7678 ("e" "#+begin_example\n?\n#+end_example")
7679 ("q" "#+begin_quote\n?\n#+end_quote")
7680 ("v" "#+begin_verse\n?\n#+end_verse")
7681 ("l" "#+begin_latex\n?\n#+end_latex")
7682 ("L" "#+latex: ")
7683 ("h" "#+begin_html\n?\n#+end_html")
7684 ("H" "#+html: ")
7685 ("a" "#+begin_ascii\n?\n#+end_ascii")
7686 ("A" "#+ascii: ")
7687 ("i" "#+include: %file ?")
7689 "Structure completion elements.
7690 This is a list of abbreviation keys and values. The value gets inserted
7691 it you type @samp{.} followed by the key and then the completion key,
7692 usually `M-TAB'. %file will be replaced by a file name after prompting
7693 for the file uning completion.
7694 This is an experimental feature, it is undecided if it is going to stay in."
7695 :group 'org-completion
7696 :type '(repeat
7697 (string :tag "Key") (string :tag "Template")))
7699 (defun org-complete-expand-structure-template (start cell)
7700 "Expand a structure template."
7701 (let ((rpl (nth 1 cell)))
7702 (delete-region start (point))
7703 (when (string-match "\\`#\\+" rpl)
7704 (cond
7705 ((bolp))
7706 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7707 (delete-region (point-at-bol) (point)))
7708 (t (newline))))
7709 (setq start (point))
7710 (if (string-match "%file" rpl)
7711 (setq rpl (replace-match
7712 (concat
7713 "\""
7714 (save-match-data
7715 (abbreviate-file-name (read-file-name "Include file: ")))
7716 "\"")
7717 t t rpl)))
7718 (insert rpl)
7719 (if (re-search-backward "\\?" start t) (delete-char 1))))
7722 (defun org-complete (&optional arg)
7723 "Perform completion on word at point.
7724 At the beginning of a headline, this completes TODO keywords as given in
7725 `org-todo-keywords'.
7726 If the current word is preceded by a backslash, completes the TeX symbols
7727 that are supported for HTML support.
7728 If the current word is preceded by \"#+\", completes special words for
7729 setting file options.
7730 In the line after \"#+STARTUP:, complete valid keywords.\"
7731 At all other locations, this simply calls the value of
7732 `org-completion-fallback-command'."
7733 (interactive "P")
7734 (org-without-partial-completion
7735 (catch 'exit
7736 (let* ((a nil)
7737 (end (point))
7738 (beg1 (save-excursion
7739 (skip-chars-backward (org-re "[:alnum:]_@"))
7740 (point)))
7741 (beg (save-excursion
7742 (skip-chars-backward "a-zA-Z0-9_:$")
7743 (point)))
7744 (confirm (lambda (x) (stringp (car x))))
7745 (searchhead (equal (char-before beg) ?*))
7746 (struct
7747 (when (and (equal (char-before beg1) ?.)
7748 (setq a (assoc (buffer-substring beg1 (point))
7749 org-structure-template-alist)))
7750 (org-complete-expand-structure-template (1- beg1) a)
7751 (throw 'exit t)))
7752 (tag (and (equal (char-before beg1) ?:)
7753 (equal (char-after (point-at-bol)) ?*)))
7754 (prop (and (equal (char-before beg1) ?:)
7755 (not (equal (char-after (point-at-bol)) ?*))))
7756 (texp (equal (char-before beg) ?\\))
7757 (link (equal (char-before beg) ?\[))
7758 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7759 beg)
7760 "#+"))
7761 (startup (string-match "^#\\+STARTUP:.*"
7762 (buffer-substring (point-at-bol) (point))))
7763 (completion-ignore-case opt)
7764 (type nil)
7765 (tbl nil)
7766 (table (cond
7767 (opt
7768 (setq type :opt)
7769 (require 'org-exp)
7770 (append
7771 (mapcar
7772 (lambda (x)
7773 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7774 (cons (match-string 2 x) (match-string 1 x)))
7775 (org-split-string (org-get-current-options) "\n"))
7776 (mapcar 'list org-additional-option-like-keywords)))
7777 (startup
7778 (setq type :startup)
7779 org-startup-options)
7780 (link (append org-link-abbrev-alist-local
7781 org-link-abbrev-alist))
7782 (texp
7783 (setq type :tex)
7784 org-html-entities)
7785 ((string-match "\\`\\*+[ \t]+\\'"
7786 (buffer-substring (point-at-bol) beg))
7787 (setq type :todo)
7788 (mapcar 'list org-todo-keywords-1))
7789 (searchhead
7790 (setq type :searchhead)
7791 (save-excursion
7792 (goto-char (point-min))
7793 (while (re-search-forward org-todo-line-regexp nil t)
7794 (push (list
7795 (org-make-org-heading-search-string
7796 (match-string 3) t))
7797 tbl)))
7798 tbl)
7799 (tag (setq type :tag beg beg1)
7800 (or org-tag-alist (org-get-buffer-tags)))
7801 (prop (setq type :prop beg beg1)
7802 (mapcar 'list (org-buffer-property-keys nil t t)))
7803 (t (progn
7804 (call-interactively org-completion-fallback-command)
7805 (throw 'exit nil)))))
7806 (pattern (buffer-substring-no-properties beg end))
7807 (completion (try-completion pattern table confirm)))
7808 (cond ((eq completion t)
7809 (if (not (assoc (upcase pattern) table))
7810 (message "Already complete")
7811 (if (and (equal type :opt)
7812 (not (member (car (assoc (upcase pattern) table))
7813 org-additional-option-like-keywords)))
7814 (insert (substring (cdr (assoc (upcase pattern) table))
7815 (length pattern)))
7816 (if (memq type '(:tag :prop)) (insert ":")))))
7817 ((null completion)
7818 (message "Can't find completion for \"%s\"" pattern)
7819 (ding))
7820 ((not (string= pattern completion))
7821 (delete-region beg end)
7822 (if (string-match " +$" completion)
7823 (setq completion (replace-match "" t t completion)))
7824 (insert completion)
7825 (if (get-buffer-window "*Completions*")
7826 (delete-window (get-buffer-window "*Completions*")))
7827 (if (assoc completion table)
7828 (if (eq type :todo) (insert " ")
7829 (if (memq type '(:tag :prop)) (insert ":"))))
7830 (if (and (equal type :opt) (assoc completion table))
7831 (message "%s" (substitute-command-keys
7832 "Press \\[org-complete] again to insert example settings"))))
7834 (message "Making completion list...")
7835 (let ((list (sort (all-completions pattern table confirm)
7836 'string<)))
7837 (with-output-to-temp-buffer "*Completions*"
7838 (condition-case nil
7839 ;; Protection needed for XEmacs and emacs 21
7840 (display-completion-list list pattern)
7841 (error (display-completion-list list)))))
7842 (message "Making completion list...%s" "done")))))))
7844 ;;;; TODO, DEADLINE, Comments
7846 (defun org-toggle-comment ()
7847 "Change the COMMENT state of an entry."
7848 (interactive)
7849 (save-excursion
7850 (org-back-to-heading)
7851 (let (case-fold-search)
7852 (if (looking-at (concat outline-regexp
7853 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7854 (replace-match "" t t nil 1)
7855 (if (looking-at outline-regexp)
7856 (progn
7857 (goto-char (match-end 0))
7858 (insert org-comment-string " ")))))))
7860 (defvar org-last-todo-state-is-todo nil
7861 "This is non-nil when the last TODO state change led to a TODO state.
7862 If the last change removed the TODO tag or switched to DONE, then
7863 this is nil.")
7865 (defvar org-setting-tags nil) ; dynamically skiped
7867 (defun org-parse-local-options (string var)
7868 "Parse STRING for startup setting relevant for variable VAR."
7869 (let ((rtn (symbol-value var))
7870 e opts)
7871 (save-match-data
7872 (if (or (not string) (not (string-match "\\S-" string)))
7874 (setq opts (delq nil (mapcar (lambda (x)
7875 (setq e (assoc x org-startup-options))
7876 (if (eq (nth 1 e) var) e nil))
7877 (org-split-string string "[ \t]+"))))
7878 (if (not opts)
7880 (setq rtn nil)
7881 (while (setq e (pop opts))
7882 (if (not (nth 3 e))
7883 (setq rtn (nth 2 e))
7884 (if (not (listp rtn)) (setq rtn nil))
7885 (push (nth 2 e) rtn)))
7886 rtn)))))
7888 (defvar org-blocker-hook nil
7889 "Hook for functions that are allowed to block a state change.
7891 Each function gets as its single argument a property list, see
7892 `org-trigger-hook' for more information about this list.
7894 If any of the functions in this hook returns nil, the state change
7895 is blocked.")
7897 (defvar org-trigger-hook nil
7898 "Hook for functions that are triggered by a state change.
7900 Each function gets as its single argument a property list with at least
7901 the following elements:
7903 (:type type-of-change :position pos-at-entry-start
7904 :from old-state :to new-state)
7906 Depending on the type, more properties may be present.
7908 This mechanism is currently implemented for:
7910 TODO state changes
7911 ------------------
7912 :type todo-state-change
7913 :from previous state (keyword as a string), or nil
7914 :to new state (keyword as a string), or nil")
7917 (defun org-todo (&optional arg)
7918 "Change the TODO state of an item.
7919 The state of an item is given by a keyword at the start of the heading,
7920 like
7921 *** TODO Write paper
7922 *** DONE Call mom
7924 The different keywords are specified in the variable `org-todo-keywords'.
7925 By default the available states are \"TODO\" and \"DONE\".
7926 So for this example: when the item starts with TODO, it is changed to DONE.
7927 When it starts with DONE, the DONE is removed. And when neither TODO nor
7928 DONE are present, add TODO at the beginning of the heading.
7930 With C-u prefix arg, use completion to determine the new state.
7931 With numeric prefix arg, switch to that state.
7933 For calling through lisp, arg is also interpreted in the following way:
7934 'none -> empty state
7935 \"\"(empty string) -> switch to empty state
7936 'done -> switch to DONE
7937 'nextset -> switch to the next set of keywords
7938 'previousset -> switch to the previous set of keywords
7939 \"WAITING\" -> switch to the specified keyword, but only if it
7940 really is a member of `org-todo-keywords'."
7941 (interactive "P")
7942 (save-excursion
7943 (catch 'exit
7944 (org-back-to-heading)
7945 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7946 (or (looking-at (concat " +" org-todo-regexp " *"))
7947 (looking-at " *"))
7948 (let* ((match-data (match-data))
7949 (startpos (point-at-bol))
7950 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7951 (org-log-done org-log-done)
7952 (org-log-repeat org-log-repeat)
7953 (org-todo-log-states org-todo-log-states)
7954 (this (match-string 1))
7955 (hl-pos (match-beginning 0))
7956 (head (org-get-todo-sequence-head this))
7957 (ass (assoc head org-todo-kwd-alist))
7958 (interpret (nth 1 ass))
7959 (done-word (nth 3 ass))
7960 (final-done-word (nth 4 ass))
7961 (last-state (or this ""))
7962 (completion-ignore-case t)
7963 (member (member this org-todo-keywords-1))
7964 (tail (cdr member))
7965 (state (cond
7966 ((and org-todo-key-trigger
7967 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7968 (and (not arg) org-use-fast-todo-selection
7969 (not (eq org-use-fast-todo-selection 'prefix)))))
7970 ;; Use fast selection
7971 (org-fast-todo-selection))
7972 ((and (equal arg '(4))
7973 (or (not org-use-fast-todo-selection)
7974 (not org-todo-key-trigger)))
7975 ;; Read a state with completion
7976 (completing-read "State: " (mapcar (lambda(x) (list x))
7977 org-todo-keywords-1)
7978 nil t))
7979 ((eq arg 'right)
7980 (if this
7981 (if tail (car tail) nil)
7982 (car org-todo-keywords-1)))
7983 ((eq arg 'left)
7984 (if (equal member org-todo-keywords-1)
7986 (if this
7987 (nth (- (length org-todo-keywords-1) (length tail) 2)
7988 org-todo-keywords-1)
7989 (org-last org-todo-keywords-1))))
7990 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7991 (setq arg nil))) ; hack to fall back to cycling
7992 (arg
7993 ;; user or caller requests a specific state
7994 (cond
7995 ((equal arg "") nil)
7996 ((eq arg 'none) nil)
7997 ((eq arg 'done) (or done-word (car org-done-keywords)))
7998 ((eq arg 'nextset)
7999 (or (car (cdr (member head org-todo-heads)))
8000 (car org-todo-heads)))
8001 ((eq arg 'previousset)
8002 (let ((org-todo-heads (reverse org-todo-heads)))
8003 (or (car (cdr (member head org-todo-heads)))
8004 (car org-todo-heads))))
8005 ((car (member arg org-todo-keywords-1)))
8006 ((nth (1- (prefix-numeric-value arg))
8007 org-todo-keywords-1))))
8008 ((null member) (or head (car org-todo-keywords-1)))
8009 ((equal this final-done-word) nil) ;; -> make empty
8010 ((null tail) nil) ;; -> first entry
8011 ((eq interpret 'sequence)
8012 (car tail))
8013 ((memq interpret '(type priority))
8014 (if (eq this-command last-command)
8015 (car tail)
8016 (if (> (length tail) 0)
8017 (or done-word (car org-done-keywords))
8018 nil)))
8019 (t nil)))
8020 (next (if state (concat " " state " ") " "))
8021 (change-plist (list :type 'todo-state-change :from this :to state
8022 :position startpos))
8023 dolog now-done-p)
8024 (when org-blocker-hook
8025 (unless (save-excursion
8026 (save-match-data
8027 (run-hook-with-args-until-failure
8028 'org-blocker-hook change-plist)))
8029 (if (interactive-p)
8030 (error "TODO state change from %s to %s blocked" this state)
8031 ;; fail silently
8032 (message "TODO state change from %s to %s blocked" this state)
8033 (throw 'exit nil))))
8034 (store-match-data match-data)
8035 (replace-match next t t)
8036 (unless (pos-visible-in-window-p hl-pos)
8037 (message "TODO state changed to %s" (org-trim next)))
8038 (unless head
8039 (setq head (org-get-todo-sequence-head state)
8040 ass (assoc head org-todo-kwd-alist)
8041 interpret (nth 1 ass)
8042 done-word (nth 3 ass)
8043 final-done-word (nth 4 ass)))
8044 (when (memq arg '(nextset previousset))
8045 (message "Keyword-Set %d/%d: %s"
8046 (- (length org-todo-sets) -1
8047 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8048 (length org-todo-sets)
8049 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8050 (setq org-last-todo-state-is-todo
8051 (not (member state org-done-keywords)))
8052 (setq now-done-p (and (member state org-done-keywords)
8053 (not (member this org-done-keywords))))
8054 (and logging (org-local-logging logging))
8055 (when (and (or org-todo-log-states org-log-done)
8056 (not (memq arg '(nextset previousset))))
8057 ;; we need to look at recording a time and note
8058 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8059 (nth 2 (assoc this org-todo-log-states))))
8060 (when (and state
8061 (member state org-not-done-keywords)
8062 (not (member this org-not-done-keywords)))
8063 ;; This is now a todo state and was not one before
8064 ;; If there was a CLOSED time stamp, get rid of it.
8065 (org-add-planning-info nil nil 'closed))
8066 (when (and now-done-p org-log-done)
8067 ;; It is now done, and it was not done before
8068 (org-add-planning-info 'closed (org-current-time))
8069 (if (and (not dolog) (eq 'note org-log-done))
8070 (org-add-log-setup 'done state 'findpos 'note)))
8071 (when (and state dolog)
8072 ;; This is a non-nil state, and we need to log it
8073 (org-add-log-setup 'state state 'findpos dolog)))
8074 ;; Fixup tag positioning
8075 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8076 (run-hooks 'org-after-todo-state-change-hook)
8077 (if (and arg (not (member state org-done-keywords)))
8078 (setq head (org-get-todo-sequence-head state)))
8079 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8080 ;; Do we need to trigger a repeat?
8081 (when now-done-p (org-auto-repeat-maybe state))
8082 ;; Fixup cursor location if close to the keyword
8083 (if (and (outline-on-heading-p)
8084 (not (bolp))
8085 (save-excursion (beginning-of-line 1)
8086 (looking-at org-todo-line-regexp))
8087 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8088 (progn
8089 (goto-char (or (match-end 2) (match-end 1)))
8090 (just-one-space)))
8091 (when org-trigger-hook
8092 (save-excursion
8093 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8095 (defun org-local-logging (value)
8096 "Get logging settings from a property VALUE."
8097 (let* (words w a)
8098 ;; directly set the variables, they are already local.
8099 (setq org-log-done nil
8100 org-log-repeat nil
8101 org-todo-log-states nil)
8102 (setq words (org-split-string value))
8103 (while (setq w (pop words))
8104 (cond
8105 ((setq a (assoc w org-startup-options))
8106 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8107 (set (nth 1 a) (nth 2 a))))
8108 ((setq a (org-extract-log-state-settings w))
8109 (and (member (car a) org-todo-keywords-1)
8110 (push a org-todo-log-states)))))))
8112 (defun org-get-todo-sequence-head (kwd)
8113 "Return the head of the TODO sequence to which KWD belongs.
8114 If KWD is not set, check if there is a text property remembering the
8115 right sequence."
8116 (let (p)
8117 (cond
8118 ((not kwd)
8119 (or (get-text-property (point-at-bol) 'org-todo-head)
8120 (progn
8121 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8122 nil (point-at-eol)))
8123 (get-text-property p 'org-todo-head))))
8124 ((not (member kwd org-todo-keywords-1))
8125 (car org-todo-keywords-1))
8126 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8128 (defun org-fast-todo-selection ()
8129 "Fast TODO keyword selection with single keys.
8130 Returns the new TODO keyword, or nil if no state change should occur."
8131 (let* ((fulltable org-todo-key-alist)
8132 (done-keywords org-done-keywords) ;; needed for the faces.
8133 (maxlen (apply 'max (mapcar
8134 (lambda (x)
8135 (if (stringp (car x)) (string-width (car x)) 0))
8136 fulltable)))
8137 (expert nil)
8138 (fwidth (+ maxlen 3 1 3))
8139 (ncol (/ (- (window-width) 4) fwidth))
8140 tg cnt e c tbl
8141 groups ingroup)
8142 (save-window-excursion
8143 (if expert
8144 (set-buffer (get-buffer-create " *Org todo*"))
8145 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8146 (erase-buffer)
8147 (org-set-local 'org-done-keywords done-keywords)
8148 (setq tbl fulltable cnt 0)
8149 (while (setq e (pop tbl))
8150 (cond
8151 ((equal e '(:startgroup))
8152 (push '() groups) (setq ingroup t)
8153 (when (not (= cnt 0))
8154 (setq cnt 0)
8155 (insert "\n"))
8156 (insert "{ "))
8157 ((equal e '(:endgroup))
8158 (setq ingroup nil cnt 0)
8159 (insert "}\n"))
8161 (setq tg (car e) c (cdr e))
8162 (if ingroup (push tg (car groups)))
8163 (setq tg (org-add-props tg nil 'face
8164 (org-get-todo-face tg)))
8165 (if (and (= cnt 0) (not ingroup)) (insert " "))
8166 (insert "[" c "] " tg (make-string
8167 (- fwidth 4 (length tg)) ?\ ))
8168 (when (= (setq cnt (1+ cnt)) ncol)
8169 (insert "\n")
8170 (if ingroup (insert " "))
8171 (setq cnt 0)))))
8172 (insert "\n")
8173 (goto-char (point-min))
8174 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8175 (fit-window-to-buffer))
8176 (message "[a-z..]:Set [SPC]:clear")
8177 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8178 (cond
8179 ((or (= c ?\C-g)
8180 (and (= c ?q) (not (rassoc c fulltable))))
8181 (setq quit-flag t))
8182 ((= c ?\ ) nil)
8183 ((setq e (rassoc c fulltable) tg (car e))
8185 (t (setq quit-flag t))))))
8187 (defun org-entry-is-todo-p ()
8188 (member (org-get-todo-state) org-not-done-keywords))
8190 (defun org-entry-is-done-p ()
8191 (member (org-get-todo-state) org-done-keywords))
8193 (defun org-get-todo-state ()
8194 (save-excursion
8195 (org-back-to-heading t)
8196 (and (looking-at org-todo-line-regexp)
8197 (match-end 2)
8198 (match-string 2))))
8200 (defun org-at-date-range-p (&optional inactive-ok)
8201 "Is the cursor inside a date range?"
8202 (interactive)
8203 (save-excursion
8204 (catch 'exit
8205 (let ((pos (point)))
8206 (skip-chars-backward "^[<\r\n")
8207 (skip-chars-backward "<[")
8208 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8209 (>= (match-end 0) pos)
8210 (throw 'exit t))
8211 (skip-chars-backward "^<[\r\n")
8212 (skip-chars-backward "<[")
8213 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8214 (>= (match-end 0) pos)
8215 (throw 'exit t)))
8216 nil)))
8218 (defun org-get-repeat ()
8219 "Check if tere is a deadline/schedule with repeater in this entry."
8220 (save-match-data
8221 (save-excursion
8222 (org-back-to-heading t)
8223 (if (re-search-forward
8224 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8225 (match-string 1)))))
8227 (defvar org-last-changed-timestamp)
8228 (defvar org-log-post-message)
8229 (defvar org-log-note-purpose)
8230 (defvar org-log-note-how)
8231 (defun org-auto-repeat-maybe (done-word)
8232 "Check if the current headline contains a repeated deadline/schedule.
8233 If yes, set TODO state back to what it was and change the base date
8234 of repeating deadline/scheduled time stamps to new date.
8235 This function is run automatically after each state change to a DONE state."
8236 ;; last-state is dynamically scoped into this function
8237 (let* ((repeat (org-get-repeat))
8238 (aa (assoc last-state org-todo-kwd-alist))
8239 (interpret (nth 1 aa))
8240 (head (nth 2 aa))
8241 (whata '(("d" . day) ("m" . month) ("y" . year)))
8242 (msg "Entry repeats: ")
8243 (org-log-done nil)
8244 (org-todo-log-states nil)
8245 (nshiftmax 10) (nshift 0)
8246 re type n what ts mb0 time)
8247 (when repeat
8248 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8249 (org-todo (if (eq interpret 'type) last-state head))
8250 (when org-log-repeat
8251 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8252 (memq 'org-add-log-note post-command-hook))
8253 ;; OK, we are already setup for some record
8254 (if (eq org-log-repeat 'note)
8255 ;; make sure we take a note, not only a time stamp
8256 (setq org-log-note-how 'note))
8257 ;; Set up for taking a record
8258 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8259 'findpos org-log-repeat)))
8260 (org-back-to-heading t)
8261 (org-add-planning-info nil nil 'closed)
8262 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8263 org-deadline-time-regexp "\\)\\|\\("
8264 org-ts-regexp "\\)"))
8265 (while (re-search-forward
8266 re (save-excursion (outline-next-heading) (point)) t)
8267 (setq type (if (match-end 1) org-scheduled-string
8268 (if (match-end 3) org-deadline-string "Plain:"))
8269 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8270 mb0 (match-beginning 0))
8271 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8272 (setq n (string-to-number (match-string 2 ts))
8273 what (match-string 3 ts))
8274 (if (equal what "w") (setq n (* n 7) what "d"))
8275 ;; Preparation, see if we need to modify the start date for the change
8276 (when (match-end 1)
8277 (setq time (save-match-data (org-time-string-to-time ts)))
8278 (cond
8279 ((equal (match-string 1 ts) ".")
8280 ;; Shift starting date to today
8281 (org-timestamp-change
8282 (- (time-to-days (current-time)) (time-to-days time))
8283 'day))
8284 ((equal (match-string 1 ts) "+")
8285 (while (or (= nshift 0)
8286 (<= (time-to-days time) (time-to-days (current-time))))
8287 (when (= (incf nshift) nshiftmax)
8288 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8289 (error "Abort")))
8290 (org-timestamp-change n (cdr (assoc what whata)))
8291 (org-at-timestamp-p t)
8292 (setq ts (match-string 1))
8293 (setq time (save-match-data (org-time-string-to-time ts))))
8294 (org-timestamp-change (- n) (cdr (assoc what whata)))
8295 ;; rematch, so that we have everything in place for the real shift
8296 (org-at-timestamp-p t)
8297 (setq ts (match-string 1))
8298 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8299 (org-timestamp-change n (cdr (assoc what whata)))
8300 (setq msg (concat msg type org-last-changed-timestamp " "))))
8301 (setq org-log-post-message msg)
8302 (message "%s" msg))))
8304 (defun org-show-todo-tree (arg)
8305 "Make a compact tree which shows all headlines marked with TODO.
8306 The tree will show the lines where the regexp matches, and all higher
8307 headlines above the match.
8308 With a \\[universal-argument] prefix, also show the DONE entries.
8309 With a numeric prefix N, construct a sparse tree for the Nth element
8310 of `org-todo-keywords-1'."
8311 (interactive "P")
8312 (let ((case-fold-search nil)
8313 (kwd-re
8314 (cond ((null arg) org-not-done-regexp)
8315 ((equal arg '(4))
8316 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8317 (mapcar 'list org-todo-keywords-1))))
8318 (concat "\\("
8319 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8320 "\\)\\>")))
8321 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8322 (regexp-quote (nth (1- (prefix-numeric-value arg))
8323 org-todo-keywords-1)))
8324 (t (error "Invalid prefix argument: %s" arg)))))
8325 (message "%d TODO entries found"
8326 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8328 (defun org-deadline (&optional remove)
8329 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8330 With argument REMOVE, remove any deadline from the item."
8331 (interactive "P")
8332 (if remove
8333 (progn
8334 (org-remove-timestamp-with-keyword org-deadline-string)
8335 (message "Item no longer has a deadline."))
8336 (org-add-planning-info 'deadline nil 'closed)))
8338 (defun org-schedule (&optional remove)
8339 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8340 With argument REMOVE, remove any scheduling date from the item."
8341 (interactive "P")
8342 (if remove
8343 (progn
8344 (org-remove-timestamp-with-keyword org-scheduled-string)
8345 (message "Item is no longer scheduled."))
8346 (org-add-planning-info 'scheduled nil 'closed)))
8348 (defun org-remove-timestamp-with-keyword (keyword)
8349 "Remove all time stamps with KEYWORD in the current entry."
8350 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8351 beg)
8352 (save-excursion
8353 (org-back-to-heading t)
8354 (setq beg (point))
8355 (org-end-of-subtree t t)
8356 (while (re-search-backward re beg t)
8357 (replace-match "")
8358 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8359 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8361 (defun org-add-planning-info (what &optional time &rest remove)
8362 "Insert new timestamp with keyword in the line directly after the headline.
8363 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8364 If non is given, the user is prompted for a date.
8365 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8366 be removed."
8367 (interactive)
8368 (let (org-time-was-given org-end-time-was-given ts
8369 end default-time default-input)
8371 (when (and (not time) (memq what '(scheduled deadline)))
8372 ;; Try to get a default date/time from existing timestamp
8373 (save-excursion
8374 (org-back-to-heading t)
8375 (setq end (save-excursion (outline-next-heading) (point)))
8376 (when (re-search-forward (if (eq what 'scheduled)
8377 org-scheduled-time-regexp
8378 org-deadline-time-regexp)
8379 end t)
8380 (setq ts (match-string 1)
8381 default-time
8382 (apply 'encode-time (org-parse-time-string ts))
8383 default-input (and ts (org-get-compact-tod ts))))))
8384 (when what
8385 ;; If necessary, get the time from the user
8386 (setq time (or time (org-read-date nil 'to-time nil nil
8387 default-time default-input))))
8389 (when (and org-insert-labeled-timestamps-at-point
8390 (member what '(scheduled deadline)))
8391 (insert
8392 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8393 (org-insert-time-stamp time org-time-was-given
8394 nil nil nil (list org-end-time-was-given))
8395 (setq what nil))
8396 (save-excursion
8397 (save-restriction
8398 (let (col list elt ts buffer-invisibility-spec)
8399 (org-back-to-heading t)
8400 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8401 (goto-char (match-end 1))
8402 (setq col (current-column))
8403 (goto-char (match-end 0))
8404 (if (eobp) (insert "\n") (forward-char 1))
8405 (if (and (not (looking-at outline-regexp))
8406 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8407 "[^\r\n]*"))
8408 (not (equal (match-string 1) org-clock-string)))
8409 (narrow-to-region (match-beginning 0) (match-end 0))
8410 (insert-before-markers "\n")
8411 (backward-char 1)
8412 (narrow-to-region (point) (point))
8413 (org-indent-to-column col))
8414 ;; Check if we have to remove something.
8415 (setq list (cons what remove))
8416 (while list
8417 (setq elt (pop list))
8418 (goto-char (point-min))
8419 (when (or (and (eq elt 'scheduled)
8420 (re-search-forward org-scheduled-time-regexp nil t))
8421 (and (eq elt 'deadline)
8422 (re-search-forward org-deadline-time-regexp nil t))
8423 (and (eq elt 'closed)
8424 (re-search-forward org-closed-time-regexp nil t)))
8425 (replace-match "")
8426 (if (looking-at "--+<[^>]+>") (replace-match ""))
8427 (if (looking-at " +") (replace-match ""))))
8428 (goto-char (point-max))
8429 (when what
8430 (insert
8431 (if (not (equal (char-before) ?\ )) " " "")
8432 (cond ((eq what 'scheduled) org-scheduled-string)
8433 ((eq what 'deadline) org-deadline-string)
8434 ((eq what 'closed) org-closed-string))
8435 " ")
8436 (setq ts (org-insert-time-stamp
8437 time
8438 (or org-time-was-given
8439 (and (eq what 'closed) org-log-done-with-time))
8440 (eq what 'closed)
8441 nil nil (list org-end-time-was-given)))
8442 (end-of-line 1))
8443 (goto-char (point-min))
8444 (widen)
8445 (if (and (looking-at "[ \t]+\n")
8446 (equal (char-before) ?\n))
8447 (backward-delete-char 1))
8448 ts)))))
8450 (defvar org-log-note-marker (make-marker))
8451 (defvar org-log-note-purpose nil)
8452 (defvar org-log-note-state nil)
8453 (defvar org-log-note-how nil)
8454 (defvar org-log-note-window-configuration nil)
8455 (defvar org-log-note-return-to (make-marker))
8456 (defvar org-log-post-message nil
8457 "Message to be displayed after a log note has been stored.
8458 The auto-repeater uses this.")
8460 (defun org-add-note ()
8461 "Add a note to the current entry.
8462 This is done in the same way as adding a state change note."
8463 (interactive)
8464 (org-add-log-setup 'note nil t nil))
8466 (defun org-add-log-setup (&optional purpose state findpos how)
8467 "Set up the post command hook to take a note.
8468 If this is about to TODO state change, the new state is expected in STATE.
8469 When FINDPOS is non-nil, find the correct position for the note in
8470 the current entry. If not, assume that it can be inserted at point."
8471 (save-excursion
8472 (when findpos
8473 (org-back-to-heading t)
8474 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8475 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8476 "[^\r\n]*\\)?"))
8477 (goto-char (match-end 0))
8478 (unless org-log-states-order-reversed
8479 (and (= (char-after) ?\n) (forward-char 1))
8480 (org-skip-over-state-notes)
8481 (skip-chars-backward " \t\n\r")))
8482 (move-marker org-log-note-marker (point))
8483 (setq org-log-note-purpose purpose
8484 org-log-note-state state
8485 org-log-note-how how)
8486 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8488 (defun org-skip-over-state-notes ()
8489 "Skip past the list of State notes in an entry."
8490 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8491 (while (looking-at "[ \t]*- State")
8492 (condition-case nil
8493 (org-next-item)
8494 (error (org-end-of-item)))))
8496 (defun org-add-log-note (&optional purpose)
8497 "Pop up a window for taking a note, and add this note later at point."
8498 (remove-hook 'post-command-hook 'org-add-log-note)
8499 (setq org-log-note-window-configuration (current-window-configuration))
8500 (delete-other-windows)
8501 (move-marker org-log-note-return-to (point))
8502 (switch-to-buffer (marker-buffer org-log-note-marker))
8503 (goto-char org-log-note-marker)
8504 (org-switch-to-buffer-other-window "*Org Note*")
8505 (erase-buffer)
8506 (if (memq org-log-note-how '(time state))
8507 (org-store-log-note)
8508 (let ((org-inhibit-startup t)) (org-mode))
8509 (insert (format "# Insert note for %s.
8510 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8511 (cond
8512 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8513 ((eq org-log-note-purpose 'done) "closed todo item")
8514 ((eq org-log-note-purpose 'state)
8515 (format "state change to \"%s\"" org-log-note-state))
8516 ((eq org-log-note-purpose 'note)
8517 "this entry")
8518 (t (error "This should not happen")))))
8519 (org-set-local 'org-finish-function 'org-store-log-note)))
8521 (defvar org-note-abort nil) ; dynamically scoped
8522 (defun org-store-log-note ()
8523 "Finish taking a log note, and insert it to where it belongs."
8524 (let ((txt (buffer-string))
8525 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8526 lines ind)
8527 (kill-buffer (current-buffer))
8528 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8529 (setq txt (replace-match "" t t txt)))
8530 (if (string-match "\\s-+\\'" txt)
8531 (setq txt (replace-match "" t t txt)))
8532 (setq lines (org-split-string txt "\n"))
8533 (when (and note (string-match "\\S-" note))
8534 (setq note
8535 (org-replace-escapes
8536 note
8537 (list (cons "%u" (user-login-name))
8538 (cons "%U" user-full-name)
8539 (cons "%t" (format-time-string
8540 (org-time-stamp-format 'long 'inactive)
8541 (current-time)))
8542 (cons "%s" (if org-log-note-state
8543 (concat "\"" org-log-note-state "\"")
8544 "")))))
8545 (if lines (setq note (concat note " \\\\")))
8546 (push note lines))
8547 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8548 (when lines
8549 (save-excursion
8550 (set-buffer (marker-buffer org-log-note-marker))
8551 (save-excursion
8552 (goto-char org-log-note-marker)
8553 (move-marker org-log-note-marker nil)
8554 (end-of-line 1)
8555 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8556 (indent-relative nil)
8557 (insert "- " (pop lines))
8558 (org-indent-line-function)
8559 (beginning-of-line 1)
8560 (looking-at "[ \t]*")
8561 (setq ind (concat (match-string 0) " "))
8562 (end-of-line 1)
8563 (while lines (insert "\n" ind (pop lines)))))))
8564 (set-window-configuration org-log-note-window-configuration)
8565 (with-current-buffer (marker-buffer org-log-note-return-to)
8566 (goto-char org-log-note-return-to))
8567 (move-marker org-log-note-return-to nil)
8568 (and org-log-post-message (message "%s" org-log-post-message)))
8570 (defun org-sparse-tree (&optional arg)
8571 "Create a sparse tree, prompt for the details.
8572 This command can create sparse trees. You first need to select the type
8573 of match used to create the tree:
8575 t Show entries with a specific TODO keyword.
8576 T Show entries selected by a tags match.
8577 p Enter a property name and its value (both with completion on existing
8578 names/values) and show entries with that property.
8579 r Show entries matching a regular expression
8580 d Show deadlines due within `org-deadline-warning-days'."
8581 (interactive "P")
8582 (let (ans kwd value)
8583 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8584 (setq ans (read-char-exclusive))
8585 (cond
8586 ((equal ans ?d)
8587 (call-interactively 'org-check-deadlines))
8588 ((equal ans ?b)
8589 (call-interactively 'org-check-before-date))
8590 ((equal ans ?t)
8591 (org-show-todo-tree '(4)))
8592 ((equal ans ?T)
8593 (call-interactively 'org-tags-sparse-tree))
8594 ((member ans '(?p ?P))
8595 (setq kwd (completing-read "Property: "
8596 (mapcar 'list (org-buffer-property-keys))))
8597 (setq value (completing-read "Value: "
8598 (mapcar 'list (org-property-values kwd))))
8599 (unless (string-match "\\`{.*}\\'" value)
8600 (setq value (concat "\"" value "\"")))
8601 (org-tags-sparse-tree arg (concat kwd "=" value)))
8602 ((member ans '(?r ?R ?/))
8603 (call-interactively 'org-occur))
8604 (t (error "No such sparse tree command \"%c\"" ans)))))
8606 (defvar org-occur-highlights nil
8607 "List of overlays used for occur matches.")
8608 (make-variable-buffer-local 'org-occur-highlights)
8609 (defvar org-occur-parameters nil
8610 "Parameters of the active org-occur calls.
8611 This is a list, each call to org-occur pushes as cons cell,
8612 containing the regular expression and the callback, onto the list.
8613 The list can contain several entries if `org-occur' has been called
8614 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8615 will only contain one set of parameters. When the highlights are
8616 removed (for example with `C-c C-c', or with the next edit (depending
8617 on `org-remove-highlights-with-change'), this variable is emptied
8618 as well.")
8619 (make-variable-buffer-local 'org-occur-parameters)
8621 (defun org-occur (regexp &optional keep-previous callback)
8622 "Make a compact tree which shows all matches of REGEXP.
8623 The tree will show the lines where the regexp matches, and all higher
8624 headlines above the match. It will also show the heading after the match,
8625 to make sure editing the matching entry is easy.
8626 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8627 call to `org-occur' will be kept, to allow stacking of calls to this
8628 command.
8629 If CALLBACK is non-nil, it is a function which is called to confirm
8630 that the match should indeed be shown."
8631 (interactive "sRegexp: \nP")
8632 (unless keep-previous
8633 (org-remove-occur-highlights nil nil t))
8634 (push (cons regexp callback) org-occur-parameters)
8635 (let ((cnt 0))
8636 (save-excursion
8637 (goto-char (point-min))
8638 (if (or (not keep-previous) ; do not want to keep
8639 (not org-occur-highlights)) ; no previous matches
8640 ;; hide everything
8641 (org-overview))
8642 (while (re-search-forward regexp nil t)
8643 (when (or (not callback)
8644 (save-match-data (funcall callback)))
8645 (setq cnt (1+ cnt))
8646 (when org-highlight-sparse-tree-matches
8647 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8648 (org-show-context 'occur-tree))))
8649 (when org-remove-highlights-with-change
8650 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8651 nil 'local))
8652 (unless org-sparse-tree-open-archived-trees
8653 (org-hide-archived-subtrees (point-min) (point-max)))
8654 (run-hooks 'org-occur-hook)
8655 (if (interactive-p)
8656 (message "%d match(es) for regexp %s" cnt regexp))
8657 cnt))
8659 (defun org-show-context (&optional key)
8660 "Make sure point and context and visible.
8661 How much context is shown depends upon the variables
8662 `org-show-hierarchy-above', `org-show-following-heading'. and
8663 `org-show-siblings'."
8664 (let ((heading-p (org-on-heading-p t))
8665 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8666 (following-p (org-get-alist-option org-show-following-heading key))
8667 (entry-p (org-get-alist-option org-show-entry-below key))
8668 (siblings-p (org-get-alist-option org-show-siblings key)))
8669 (catch 'exit
8670 ;; Show heading or entry text
8671 (if (and heading-p (not entry-p))
8672 (org-flag-heading nil) ; only show the heading
8673 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8674 (org-show-hidden-entry))) ; show entire entry
8675 (when following-p
8676 ;; Show next sibling, or heading below text
8677 (save-excursion
8678 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8679 (org-flag-heading nil))))
8680 (when siblings-p (org-show-siblings))
8681 (when hierarchy-p
8682 ;; show all higher headings, possibly with siblings
8683 (save-excursion
8684 (while (and (condition-case nil
8685 (progn (org-up-heading-all 1) t)
8686 (error nil))
8687 (not (bobp)))
8688 (org-flag-heading nil)
8689 (when siblings-p (org-show-siblings))))))))
8691 (defun org-reveal (&optional siblings)
8692 "Show current entry, hierarchy above it, and the following headline.
8693 This can be used to show a consistent set of context around locations
8694 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8695 not t for the search context.
8697 With optional argument SIBLINGS, on each level of the hierarchy all
8698 siblings are shown. This repairs the tree structure to what it would
8699 look like when opened with hierarchical calls to `org-cycle'."
8700 (interactive "P")
8701 (let ((org-show-hierarchy-above t)
8702 (org-show-following-heading t)
8703 (org-show-siblings (if siblings t org-show-siblings)))
8704 (org-show-context nil)))
8706 (defun org-highlight-new-match (beg end)
8707 "Highlight from BEG to END and mark the highlight is an occur headline."
8708 (let ((ov (org-make-overlay beg end)))
8709 (org-overlay-put ov 'face 'secondary-selection)
8710 (push ov org-occur-highlights)))
8712 (defun org-remove-occur-highlights (&optional beg end noremove)
8713 "Remove the occur highlights from the buffer.
8714 BEG and END are ignored. If NOREMOVE is nil, remove this function
8715 from the `before-change-functions' in the current buffer."
8716 (interactive)
8717 (unless org-inhibit-highlight-removal
8718 (mapc 'org-delete-overlay org-occur-highlights)
8719 (setq org-occur-highlights nil)
8720 (setq org-occur-parameters nil)
8721 (unless noremove
8722 (remove-hook 'before-change-functions
8723 'org-remove-occur-highlights 'local))))
8725 ;;;; Priorities
8727 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8728 "Regular expression matching the priority indicator.")
8730 (defvar org-remove-priority-next-time nil)
8732 (defun org-priority-up ()
8733 "Increase the priority of the current item."
8734 (interactive)
8735 (org-priority 'up))
8737 (defun org-priority-down ()
8738 "Decrease the priority of the current item."
8739 (interactive)
8740 (org-priority 'down))
8742 (defun org-priority (&optional action)
8743 "Change the priority of an item by ARG.
8744 ACTION can be `set', `up', `down', or a character."
8745 (interactive)
8746 (setq action (or action 'set))
8747 (let (current new news have remove)
8748 (save-excursion
8749 (org-back-to-heading)
8750 (if (looking-at org-priority-regexp)
8751 (setq current (string-to-char (match-string 2))
8752 have t)
8753 (setq current org-default-priority))
8754 (cond
8755 ((or (eq action 'set)
8756 (if (featurep 'xemacs) (characterp action) (integerp action)))
8757 (if (not (eq action 'set))
8758 (setq new action)
8759 (message "Priority %c-%c, SPC to remove: "
8760 org-highest-priority org-lowest-priority)
8761 (setq new (read-char-exclusive)))
8762 (if (and (= (upcase org-highest-priority) org-highest-priority)
8763 (= (upcase org-lowest-priority) org-lowest-priority))
8764 (setq new (upcase new)))
8765 (cond ((equal new ?\ ) (setq remove t))
8766 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8767 (error "Priority must be between `%c' and `%c'"
8768 org-highest-priority org-lowest-priority))))
8769 ((eq action 'up)
8770 (if (and (not have) (eq last-command this-command))
8771 (setq new org-lowest-priority)
8772 (setq new (if (and org-priority-start-cycle-with-default (not have))
8773 org-default-priority (1- current)))))
8774 ((eq action 'down)
8775 (if (and (not have) (eq last-command this-command))
8776 (setq new org-highest-priority)
8777 (setq new (if (and org-priority-start-cycle-with-default (not have))
8778 org-default-priority (1+ current)))))
8779 (t (error "Invalid action")))
8780 (if (or (< (upcase new) org-highest-priority)
8781 (> (upcase new) org-lowest-priority))
8782 (setq remove t))
8783 (setq news (format "%c" new))
8784 (if have
8785 (if remove
8786 (replace-match "" t t nil 1)
8787 (replace-match news t t nil 2))
8788 (if remove
8789 (error "No priority cookie found in line")
8790 (looking-at org-todo-line-regexp)
8791 (if (match-end 2)
8792 (progn
8793 (goto-char (match-end 2))
8794 (insert " [#" news "]"))
8795 (goto-char (match-beginning 3))
8796 (insert "[#" news "] ")))))
8797 (org-preserve-lc (org-set-tags nil 'align))
8798 (if remove
8799 (message "Priority removed")
8800 (message "Priority of current item set to %s" news))))
8803 (defun org-get-priority (s)
8804 "Find priority cookie and return priority."
8805 (save-match-data
8806 (if (not (string-match org-priority-regexp s))
8807 (* 1000 (- org-lowest-priority org-default-priority))
8808 (* 1000 (- org-lowest-priority
8809 (string-to-char (match-string 2 s)))))))
8811 ;;;; Tags
8813 (defun org-scan-tags (action matcher &optional todo-only)
8814 "Scan headline tags with inheritance and produce output ACTION.
8815 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8816 evaluated, testing if a given set of tags qualifies a headline for
8817 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8818 are included in the output."
8819 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8820 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8821 (org-re
8822 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8823 (props (list 'face nil
8824 'done-face 'org-done
8825 'undone-face nil
8826 'mouse-face 'highlight
8827 'org-not-done-regexp org-not-done-regexp
8828 'org-todo-regexp org-todo-regexp
8829 'keymap org-agenda-keymap
8830 'help-echo
8831 (format "mouse-2 or RET jump to org file %s"
8832 (abbreviate-file-name
8833 (or (buffer-file-name (buffer-base-buffer))
8834 (buffer-name (buffer-base-buffer)))))))
8835 (case-fold-search nil)
8836 lspos
8837 tags tags-list tags-alist (llast 0) rtn level category i txt
8838 todo marker entry priority)
8839 (save-excursion
8840 (goto-char (point-min))
8841 (when (eq action 'sparse-tree)
8842 (org-overview)
8843 (org-remove-occur-highlights))
8844 (while (re-search-forward re nil t)
8845 (catch :skip
8846 (setq todo (if (match-end 1) (match-string 2))
8847 tags (if (match-end 4) (match-string 4)))
8848 (goto-char (setq lspos (1+ (match-beginning 0))))
8849 (setq level (org-reduced-level (funcall outline-level))
8850 category (org-get-category))
8851 (setq i llast llast level)
8852 ;; remove tag lists from same and sublevels
8853 (while (>= i level)
8854 (when (setq entry (assoc i tags-alist))
8855 (setq tags-alist (delete entry tags-alist)))
8856 (setq i (1- i)))
8857 ;; add the next tags
8858 (when tags
8859 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8860 tags-alist
8861 (cons (cons level tags) tags-alist)))
8862 ;; compile tags for current headline
8863 (setq tags-list
8864 (if org-use-tag-inheritance
8865 (apply 'append (mapcar 'cdr tags-alist))
8866 tags))
8867 (when (and tags org-use-tag-inheritance
8868 (not (eq t org-use-tag-inheritance)))
8869 ;; selective inheritance, remove uninherited ones
8870 (setcdr (car tags-alist)
8871 (org-remove-uniherited-tags (cdar tags-alist))))
8872 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8873 (eval matcher)
8874 (or (not org-agenda-skip-archived-trees)
8875 (not (member org-archive-tag tags-list))))
8876 (and (eq action 'agenda) (org-agenda-skip))
8877 ;; list this headline
8879 (if (eq action 'sparse-tree)
8880 (progn
8881 (and org-highlight-sparse-tree-matches
8882 (org-get-heading) (match-end 0)
8883 (org-highlight-new-match
8884 (match-beginning 0) (match-beginning 1)))
8885 (org-show-context 'tags-tree))
8886 (setq txt (org-format-agenda-item
8888 (concat
8889 (if org-tags-match-list-sublevels
8890 (make-string (1- level) ?.) "")
8891 (org-get-heading))
8892 category tags-list)
8893 priority (org-get-priority txt))
8894 (goto-char lspos)
8895 (setq marker (org-agenda-new-marker))
8896 (org-add-props txt props
8897 'org-marker marker 'org-hd-marker marker 'org-category category
8898 'priority priority 'type "tagsmatch")
8899 (push txt rtn))
8900 ;; if we are to skip sublevels, jump to end of subtree
8901 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8902 (when (and (eq action 'sparse-tree)
8903 (not org-sparse-tree-open-archived-trees))
8904 (org-hide-archived-subtrees (point-min) (point-max)))
8905 (nreverse rtn)))
8907 (defun org-remove-uniherited-tags (tags)
8908 "Remove all tags that are not inherited from the list TAGS."
8909 (cond
8910 ((eq org-use-tag-inheritance t) tags)
8911 ((not org-use-tag-inheritance) nil)
8912 ((stringp org-use-tag-inheritance)
8913 (delq nil (mapcar
8914 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8915 tags)))
8916 ((listp org-use-tag-inheritance)
8917 (org-delete-all org-use-tag-inheritance tags))))
8919 (defvar todo-only) ;; dynamically scoped
8921 (defun org-tags-sparse-tree (&optional todo-only match)
8922 "Create a sparse tree according to tags string MATCH.
8923 MATCH can contain positive and negative selection of tags, like
8924 \"+WORK+URGENT-WITHBOSS\".
8925 If optional argument TODO_ONLY is non-nil, only select lines that are
8926 also TODO lines."
8927 (interactive "P")
8928 (org-prepare-agenda-buffers (list (current-buffer)))
8929 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8931 (defvar org-cached-props nil)
8932 (defun org-cached-entry-get (pom property)
8933 (if (or (eq t org-use-property-inheritance)
8934 (and (stringp org-use-property-inheritance)
8935 (string-match org-use-property-inheritance property))
8936 (and (listp org-use-property-inheritance)
8937 (member property org-use-property-inheritance)))
8938 ;; Caching is not possible, check it directly
8939 (org-entry-get pom property 'inherit)
8940 ;; Get all properties, so that we can do complicated checks easily
8941 (cdr (assoc property (or org-cached-props
8942 (setq org-cached-props
8943 (org-entry-properties pom)))))))
8945 (defun org-global-tags-completion-table (&optional files)
8946 "Return the list of all tags in all agenda buffer/files."
8947 (save-excursion
8948 (org-uniquify
8949 (delq nil
8950 (apply 'append
8951 (mapcar
8952 (lambda (file)
8953 (set-buffer (find-file-noselect file))
8954 (append (org-get-buffer-tags)
8955 (mapcar (lambda (x) (if (stringp (car-safe x))
8956 (list (car-safe x)) nil))
8957 org-tag-alist)))
8958 (if (and files (car files))
8959 files
8960 (org-agenda-files))))))))
8962 (defun org-make-tags-matcher (match)
8963 "Create the TAGS//TODO matcher form for the selection string MATCH."
8964 ;; todo-only is scoped dynamically into this function, and the function
8965 ;; may change it it the matcher asksk for it.
8966 (unless match
8967 ;; Get a new match request, with completion
8968 (let ((org-last-tags-completion-table
8969 (org-global-tags-completion-table)))
8970 (setq match (completing-read
8971 "Match: " 'org-tags-completion-function nil nil nil
8972 'org-tags-history))))
8974 ;; Parse the string and create a lisp form
8975 (let ((match0 match)
8976 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8977 minus tag mm
8978 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8979 orterms term orlist re-p str-p level-p level-op
8980 prop-p pn pv po cat-p gv)
8981 (if (string-match "/+" match)
8982 ;; match contains also a todo-matching request
8983 (progn
8984 (setq tagsmatch (substring match 0 (match-beginning 0))
8985 todomatch (substring match (match-end 0)))
8986 (if (string-match "^!" todomatch)
8987 (setq todo-only t todomatch (substring todomatch 1)))
8988 (if (string-match "^\\s-*$" todomatch)
8989 (setq todomatch nil)))
8990 ;; only matching tags
8991 (setq tagsmatch match todomatch nil))
8993 ;; Make the tags matcher
8994 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8995 (setq tagsmatcher t)
8996 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8997 (while (setq term (pop orterms))
8998 (while (and (equal (substring term -1) "\\") orterms)
8999 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9000 (while (string-match re term)
9001 (setq minus (and (match-end 1)
9002 (equal (match-string 1 term) "-"))
9003 tag (match-string 2 term)
9004 re-p (equal (string-to-char tag) ?{)
9005 level-p (match-end 4)
9006 prop-p (match-end 5)
9007 mm (cond
9008 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9009 (level-p
9010 (setq level-op (org-op-to-function (match-string 3 term)))
9011 `(,level-op level ,(string-to-number
9012 (match-string 4 term))))
9013 (prop-p
9014 (setq pn (match-string 5 term)
9015 po (match-string 6 term)
9016 pv (match-string 7 term)
9017 cat-p (equal pn "CATEGORY")
9018 re-p (equal (string-to-char pv) ?{)
9019 str-p (equal (string-to-char pv) ?\")
9020 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9021 (setq po (org-op-to-function po str-p))
9022 (if (equal pn "CATEGORY")
9023 (setq gv '(get-text-property (point) 'org-category))
9024 (setq gv `(org-cached-entry-get nil ,pn)))
9025 (if re-p
9026 (if (eq po 'org<>)
9027 `(not (string-match ,pv (or ,gv "")))
9028 `(string-match ,pv (or ,gv "")))
9029 (if str-p
9030 `(,po (or ,gv "") ,pv)
9031 `(,po (string-to-number (or ,gv ""))
9032 ,(string-to-number pv) ))))
9033 (t `(member ,(downcase tag) tags-list)))
9034 mm (if minus (list 'not mm) mm)
9035 term (substring term (match-end 0)))
9036 (push mm tagsmatcher))
9037 (push (if (> (length tagsmatcher) 1)
9038 (cons 'and tagsmatcher)
9039 (car tagsmatcher))
9040 orlist)
9041 (setq tagsmatcher nil))
9042 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9043 (setq tagsmatcher
9044 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9045 ;; Make the todo matcher
9046 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9047 (setq todomatcher t)
9048 (setq orterms (org-split-string todomatch "|") orlist nil)
9049 (while (setq term (pop orterms))
9050 (while (string-match re term)
9051 (setq minus (and (match-end 1)
9052 (equal (match-string 1 term) "-"))
9053 kwd (match-string 2 term)
9054 re-p (equal (string-to-char kwd) ?{)
9055 term (substring term (match-end 0))
9056 mm (if re-p
9057 `(string-match ,(substring kwd 1 -1) todo)
9058 (list 'equal 'todo kwd))
9059 mm (if minus (list 'not mm) mm))
9060 (push mm todomatcher))
9061 (push (if (> (length todomatcher) 1)
9062 (cons 'and todomatcher)
9063 (car todomatcher))
9064 orlist)
9065 (setq todomatcher nil))
9066 (setq todomatcher (if (> (length orlist) 1)
9067 (cons 'or orlist) (car orlist))))
9069 ;; Return the string and lisp forms of the matcher
9070 (setq matcher (if todomatcher
9071 (list 'and tagsmatcher todomatcher)
9072 tagsmatcher))
9073 (cons match0 matcher)))
9075 (defun org-op-to-function (op &optional stringp)
9076 (setq op
9077 (cond
9078 ((equal op "<" ) '(< string< ))
9079 ((equal op ">" ) '(> org-string> ))
9080 ((member op '("<=" "=<")) '(<= org-string<= ))
9081 ((member op '(">=" "=>")) '(>= org-string>= ))
9082 ((member op '("=" "==")) '(= string= ))
9083 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9084 (nth (if stringp 1 0) op))
9086 (defun org<> (a b) (not (= a b)))
9087 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9088 (defun org-string>= (a b) (not (string< a b)))
9089 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9090 (defun org-string<> (a b) (not (string= a b)))
9092 (defun org-match-any-p (re list)
9093 "Does re match any element of list?"
9094 (setq list (mapcar (lambda (x) (string-match re x)) list))
9095 (delq nil list))
9097 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9098 (defvar org-tags-overlay (org-make-overlay 1 1))
9099 (org-detach-overlay org-tags-overlay)
9101 (defun org-get-tags-at (&optional pos)
9102 "Get a list of all headline tags applicable at POS.
9103 POS defaults to point. If tags are inherited, the list contains
9104 the targets in the same sequence as the headlines appear, i.e.
9105 sthe tags of the current headline come last."
9106 (interactive)
9107 (let (tags ltags lastpos parent)
9108 (save-excursion
9109 (save-restriction
9110 (widen)
9111 (goto-char (or pos (point)))
9112 (save-match-data
9113 (condition-case nil
9114 (progn
9115 (org-back-to-heading t)
9116 (while (not (equal lastpos (point)))
9117 (setq lastpos (point))
9118 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9119 (setq ltags (org-split-string
9120 (org-match-string-no-properties 1) ":"))
9121 (setq tags (append (org-remove-uniherited-tags ltags)
9122 tags)))
9123 (or org-use-tag-inheritance (error ""))
9124 (org-up-heading-all 1)
9125 (setq parent t)))
9126 (error nil))))
9127 tags)))
9129 (defun org-toggle-tag (tag &optional onoff)
9130 "Toggle the tag TAG for the current line.
9131 If ONOFF is `on' or `off', don't toggle but set to this state."
9132 (unless (org-on-heading-p t) (error "Not on headling"))
9133 (let (res current)
9134 (save-excursion
9135 (beginning-of-line)
9136 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9137 (point-at-eol) t)
9138 (progn
9139 (setq current (match-string 1))
9140 (replace-match ""))
9141 (setq current ""))
9142 (setq current (nreverse (org-split-string current ":")))
9143 (cond
9144 ((eq onoff 'on)
9145 (setq res t)
9146 (or (member tag current) (push tag current)))
9147 ((eq onoff 'off)
9148 (or (not (member tag current)) (setq current (delete tag current))))
9149 (t (if (member tag current)
9150 (setq current (delete tag current))
9151 (setq res t)
9152 (push tag current))))
9153 (end-of-line 1)
9154 (if current
9155 (progn
9156 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9157 (org-set-tags nil t))
9158 (delete-horizontal-space))
9159 (run-hooks 'org-after-tags-change-hook))
9160 res))
9162 (defun org-align-tags-here (to-col)
9163 ;; Assumes that this is a headline
9164 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9165 (beginning-of-line 1)
9166 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9167 (< pos (match-beginning 2)))
9168 (progn
9169 (setq tags-l (- (match-end 2) (match-beginning 2)))
9170 (goto-char (match-beginning 1))
9171 (insert " ")
9172 (delete-region (point) (1+ (match-beginning 2)))
9173 (setq ncol (max (1+ (current-column))
9174 (1+ col)
9175 (if (> to-col 0)
9176 to-col
9177 (- (abs to-col) tags-l))))
9178 (setq p (point))
9179 (insert (make-string (- ncol (current-column)) ?\ ))
9180 (setq ncol (current-column))
9181 (tabify p (point-at-eol))
9182 (org-move-to-column (min ncol col) t))
9183 (goto-char pos))))
9185 (defun org-set-tags (&optional arg just-align)
9186 "Set the tags for the current headline.
9187 With prefix ARG, realign all tags in headings in the current buffer."
9188 (interactive "P")
9189 (let* ((re (concat "^" outline-regexp))
9190 (current (org-get-tags-string))
9191 (col (current-column))
9192 (org-setting-tags t)
9193 table current-tags inherited-tags ; computed below when needed
9194 tags p0 c0 c1 rpl)
9195 (if arg
9196 (save-excursion
9197 (goto-char (point-min))
9198 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9199 (while (re-search-forward re nil t)
9200 (org-set-tags nil t)
9201 (end-of-line 1)))
9202 (message "All tags realigned to column %d" org-tags-column))
9203 (if just-align
9204 (setq tags current)
9205 ;; Get a new set of tags from the user
9206 (save-excursion
9207 (setq table (or org-tag-alist (org-get-buffer-tags))
9208 org-last-tags-completion-table table
9209 current-tags (org-split-string current ":")
9210 inherited-tags (nreverse
9211 (nthcdr (length current-tags)
9212 (nreverse (org-get-tags-at))))
9213 tags
9214 (if (or (eq t org-use-fast-tag-selection)
9215 (and org-use-fast-tag-selection
9216 (delq nil (mapcar 'cdr table))))
9217 (org-fast-tag-selection
9218 current-tags inherited-tags table
9219 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9220 (let ((org-add-colon-after-tag-completion t))
9221 (org-trim
9222 (org-without-partial-completion
9223 (completing-read "Tags: " 'org-tags-completion-function
9224 nil nil current 'org-tags-history)))))))
9225 (while (string-match "[-+&]+" tags)
9226 ;; No boolean logic, just a list
9227 (setq tags (replace-match ":" t t tags))))
9229 (if (string-match "\\`[\t ]*\\'" tags)
9230 (setq tags "")
9231 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9232 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9234 ;; Insert new tags at the correct column
9235 (beginning-of-line 1)
9236 (cond
9237 ((and (equal current "") (equal tags "")))
9238 ((re-search-forward
9239 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9240 (point-at-eol) t)
9241 (if (equal tags "")
9242 (setq rpl "")
9243 (goto-char (match-beginning 0))
9244 (setq c0 (current-column) p0 (point)
9245 c1 (max (1+ c0) (if (> org-tags-column 0)
9246 org-tags-column
9247 (- (- org-tags-column) (length tags))))
9248 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9249 (replace-match rpl t t)
9250 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9251 tags)
9252 (t (error "Tags alignment failed")))
9253 (org-move-to-column col)
9254 (unless just-align
9255 (run-hooks 'org-after-tags-change-hook)))))
9257 (defun org-change-tag-in-region (beg end tag off)
9258 "Add or remove TAG for each entry in the region.
9259 This works in the agenda, and also in an org-mode buffer."
9260 (interactive
9261 (list (region-beginning) (region-end)
9262 (let ((org-last-tags-completion-table
9263 (if (org-mode-p)
9264 (org-get-buffer-tags)
9265 (org-global-tags-completion-table))))
9266 (completing-read
9267 "Tag: " 'org-tags-completion-function nil nil nil
9268 'org-tags-history))
9269 (progn
9270 (message "[s]et or [r]emove? ")
9271 (equal (read-char-exclusive) ?r))))
9272 (if (fboundp 'deactivate-mark) (deactivate-mark))
9273 (let ((agendap (equal major-mode 'org-agenda-mode))
9274 l1 l2 m buf pos newhead (cnt 0))
9275 (goto-char end)
9276 (setq l2 (1- (org-current-line)))
9277 (goto-char beg)
9278 (setq l1 (org-current-line))
9279 (loop for l from l1 to l2 do
9280 (goto-line l)
9281 (setq m (get-text-property (point) 'org-hd-marker))
9282 (when (or (and (org-mode-p) (org-on-heading-p))
9283 (and agendap m))
9284 (setq buf (if agendap (marker-buffer m) (current-buffer))
9285 pos (if agendap m (point)))
9286 (with-current-buffer buf
9287 (save-excursion
9288 (save-restriction
9289 (goto-char pos)
9290 (setq cnt (1+ cnt))
9291 (org-toggle-tag tag (if off 'off 'on))
9292 (setq newhead (org-get-heading)))))
9293 (and agendap (org-agenda-change-all-lines newhead m))))
9294 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9296 (defun org-tags-completion-function (string predicate &optional flag)
9297 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9298 (confirm (lambda (x) (stringp (car x)))))
9299 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9300 (setq s1 (match-string 1 string)
9301 s2 (match-string 2 string))
9302 (setq s1 "" s2 string))
9303 (cond
9304 ((eq flag nil)
9305 ;; try completion
9306 (setq rtn (try-completion s2 ctable confirm))
9307 (if (stringp rtn)
9308 (setq rtn
9309 (concat s1 s2 (substring rtn (length s2))
9310 (if (and org-add-colon-after-tag-completion
9311 (assoc rtn ctable))
9312 ":" ""))))
9313 rtn)
9314 ((eq flag t)
9315 ;; all-completions
9316 (all-completions s2 ctable confirm)
9318 ((eq flag 'lambda)
9319 ;; exact match?
9320 (assoc s2 ctable)))
9323 (defun org-fast-tag-insert (kwd tags face &optional end)
9324 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9325 (insert (format "%-12s" (concat kwd ":"))
9326 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9327 (or end "")))
9329 (defun org-fast-tag-show-exit (flag)
9330 (save-excursion
9331 (goto-line 3)
9332 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9333 (replace-match ""))
9334 (when flag
9335 (end-of-line 1)
9336 (org-move-to-column (- (window-width) 19) t)
9337 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9339 (defun org-set-current-tags-overlay (current prefix)
9340 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9341 (if (featurep 'xemacs)
9342 (org-overlay-display org-tags-overlay (concat prefix s)
9343 'secondary-selection)
9344 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9345 (org-overlay-display org-tags-overlay (concat prefix s)))))
9347 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9348 "Fast tag selection with single keys.
9349 CURRENT is the current list of tags in the headline, INHERITED is the
9350 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9351 possibly with grouping information. TODO-TABLE is a similar table with
9352 TODO keywords, should these have keys assigned to them.
9353 If the keys are nil, a-z are automatically assigned.
9354 Returns the new tags string, or nil to not change the current settings."
9355 (let* ((fulltable (append table todo-table))
9356 (maxlen (apply 'max (mapcar
9357 (lambda (x)
9358 (if (stringp (car x)) (string-width (car x)) 0))
9359 fulltable)))
9360 (buf (current-buffer))
9361 (expert (eq org-fast-tag-selection-single-key 'expert))
9362 (buffer-tags nil)
9363 (fwidth (+ maxlen 3 1 3))
9364 (ncol (/ (- (window-width) 4) fwidth))
9365 (i-face 'org-done)
9366 (c-face 'org-todo)
9367 tg cnt e c char c1 c2 ntable tbl rtn
9368 ov-start ov-end ov-prefix
9369 (exit-after-next org-fast-tag-selection-single-key)
9370 (done-keywords org-done-keywords)
9371 groups ingroup)
9372 (save-excursion
9373 (beginning-of-line 1)
9374 (if (looking-at
9375 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9376 (setq ov-start (match-beginning 1)
9377 ov-end (match-end 1)
9378 ov-prefix "")
9379 (setq ov-start (1- (point-at-eol))
9380 ov-end (1+ ov-start))
9381 (skip-chars-forward "^\n\r")
9382 (setq ov-prefix
9383 (concat
9384 (buffer-substring (1- (point)) (point))
9385 (if (> (current-column) org-tags-column)
9387 (make-string (- org-tags-column (current-column)) ?\ ))))))
9388 (org-move-overlay org-tags-overlay ov-start ov-end)
9389 (save-window-excursion
9390 (if expert
9391 (set-buffer (get-buffer-create " *Org tags*"))
9392 (delete-other-windows)
9393 (split-window-vertically)
9394 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9395 (erase-buffer)
9396 (org-set-local 'org-done-keywords done-keywords)
9397 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9398 (org-fast-tag-insert "Current" current c-face "\n\n")
9399 (org-fast-tag-show-exit exit-after-next)
9400 (org-set-current-tags-overlay current ov-prefix)
9401 (setq tbl fulltable char ?a cnt 0)
9402 (while (setq e (pop tbl))
9403 (cond
9404 ((equal e '(:startgroup))
9405 (push '() groups) (setq ingroup t)
9406 (when (not (= cnt 0))
9407 (setq cnt 0)
9408 (insert "\n"))
9409 (insert "{ "))
9410 ((equal e '(:endgroup))
9411 (setq ingroup nil cnt 0)
9412 (insert "}\n"))
9414 (setq tg (car e) c2 nil)
9415 (if (cdr e)
9416 (setq c (cdr e))
9417 ;; automatically assign a character.
9418 (setq c1 (string-to-char
9419 (downcase (substring
9420 tg (if (= (string-to-char tg) ?@) 1 0)))))
9421 (if (or (rassoc c1 ntable) (rassoc c1 table))
9422 (while (or (rassoc char ntable) (rassoc char table))
9423 (setq char (1+ char)))
9424 (setq c2 c1))
9425 (setq c (or c2 char)))
9426 (if ingroup (push tg (car groups)))
9427 (setq tg (org-add-props tg nil 'face
9428 (cond
9429 ((not (assoc tg table))
9430 (org-get-todo-face tg))
9431 ((member tg current) c-face)
9432 ((member tg inherited) i-face)
9433 (t nil))))
9434 (if (and (= cnt 0) (not ingroup)) (insert " "))
9435 (insert "[" c "] " tg (make-string
9436 (- fwidth 4 (length tg)) ?\ ))
9437 (push (cons tg c) ntable)
9438 (when (= (setq cnt (1+ cnt)) ncol)
9439 (insert "\n")
9440 (if ingroup (insert " "))
9441 (setq cnt 0)))))
9442 (setq ntable (nreverse ntable))
9443 (insert "\n")
9444 (goto-char (point-min))
9445 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9446 (fit-window-to-buffer))
9447 (setq rtn
9448 (catch 'exit
9449 (while t
9450 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9451 (if groups " [!] no groups" " [!]groups")
9452 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9453 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9454 (cond
9455 ((= c ?\r) (throw 'exit t))
9456 ((= c ?!)
9457 (setq groups (not groups))
9458 (goto-char (point-min))
9459 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9460 ((= c ?\C-c)
9461 (if (not expert)
9462 (org-fast-tag-show-exit
9463 (setq exit-after-next (not exit-after-next)))
9464 (setq expert nil)
9465 (delete-other-windows)
9466 (split-window-vertically)
9467 (org-switch-to-buffer-other-window " *Org tags*")
9468 (and (fboundp 'fit-window-to-buffer)
9469 (fit-window-to-buffer))))
9470 ((or (= c ?\C-g)
9471 (and (= c ?q) (not (rassoc c ntable))))
9472 (org-detach-overlay org-tags-overlay)
9473 (setq quit-flag t))
9474 ((= c ?\ )
9475 (setq current nil)
9476 (if exit-after-next (setq exit-after-next 'now)))
9477 ((= c ?\t)
9478 (condition-case nil
9479 (setq tg (completing-read
9480 "Tag: "
9481 (or buffer-tags
9482 (with-current-buffer buf
9483 (org-get-buffer-tags)))))
9484 (quit (setq tg "")))
9485 (when (string-match "\\S-" tg)
9486 (add-to-list 'buffer-tags (list tg))
9487 (if (member tg current)
9488 (setq current (delete tg current))
9489 (push tg current)))
9490 (if exit-after-next (setq exit-after-next 'now)))
9491 ((setq e (rassoc c todo-table) tg (car e))
9492 (with-current-buffer buf
9493 (save-excursion (org-todo tg)))
9494 (if exit-after-next (setq exit-after-next 'now)))
9495 ((setq e (rassoc c ntable) tg (car e))
9496 (if (member tg current)
9497 (setq current (delete tg current))
9498 (loop for g in groups do
9499 (if (member tg g)
9500 (mapc (lambda (x)
9501 (setq current (delete x current)))
9502 g)))
9503 (push tg current))
9504 (if exit-after-next (setq exit-after-next 'now))))
9506 ;; Create a sorted list
9507 (setq current
9508 (sort current
9509 (lambda (a b)
9510 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9511 (if (eq exit-after-next 'now) (throw 'exit t))
9512 (goto-char (point-min))
9513 (beginning-of-line 2)
9514 (delete-region (point) (point-at-eol))
9515 (org-fast-tag-insert "Current" current c-face)
9516 (org-set-current-tags-overlay current ov-prefix)
9517 (while (re-search-forward
9518 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9519 (setq tg (match-string 1))
9520 (add-text-properties
9521 (match-beginning 1) (match-end 1)
9522 (list 'face
9523 (cond
9524 ((member tg current) c-face)
9525 ((member tg inherited) i-face)
9526 (t (get-text-property (match-beginning 1) 'face))))))
9527 (goto-char (point-min)))))
9528 (org-detach-overlay org-tags-overlay)
9529 (if rtn
9530 (mapconcat 'identity current ":")
9531 nil))))
9533 (defun org-get-tags-string ()
9534 "Get the TAGS string in the current headline."
9535 (unless (org-on-heading-p t)
9536 (error "Not on a heading"))
9537 (save-excursion
9538 (beginning-of-line 1)
9539 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9540 (org-match-string-no-properties 1)
9541 "")))
9543 (defun org-get-tags ()
9544 "Get the list of tags specified in the current headline."
9545 (org-split-string (org-get-tags-string) ":"))
9547 (defun org-get-buffer-tags ()
9548 "Get a table of all tags used in the buffer, for completion."
9549 (let (tags)
9550 (save-excursion
9551 (goto-char (point-min))
9552 (while (re-search-forward
9553 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9554 (when (equal (char-after (point-at-bol 0)) ?*)
9555 (mapc (lambda (x) (add-to-list 'tags x))
9556 (org-split-string (org-match-string-no-properties 1) ":")))))
9557 (mapcar 'list tags)))
9560 ;;;; Properties
9562 ;;; Setting and retrieving properties
9564 (defconst org-special-properties
9565 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9566 "TIMESTAMP" "TIMESTAMP_IA")
9567 "The special properties valid in Org-mode.
9569 These are properties that are not defined in the property drawer,
9570 but in some other way.")
9572 (defconst org-default-properties
9573 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9574 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY")
9575 "Some properties that are used by Org-mode for various purposes.
9576 Being in this list makes sure that they are offered for completion.")
9578 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9579 "Regular expression matching the first line of a property drawer.")
9581 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9582 "Regular expression matching the first line of a property drawer.")
9584 (defun org-property-action ()
9585 "Do an action on properties."
9586 (interactive)
9587 (let (c)
9588 (org-at-property-p)
9589 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9590 (setq c (read-char-exclusive))
9591 (cond
9592 ((equal c ?s)
9593 (call-interactively 'org-set-property))
9594 ((equal c ?d)
9595 (call-interactively 'org-delete-property))
9596 ((equal c ?D)
9597 (call-interactively 'org-delete-property-globally))
9598 ((equal c ?c)
9599 (call-interactively 'org-compute-property-at-point))
9600 (t (error "No such property action %c" c)))))
9602 (defun org-at-property-p ()
9603 "Is the cursor in a property line?"
9604 ;; FIXME: Does not check if we are actually in the drawer.
9605 ;; FIXME: also returns true on any drawers.....
9606 ;; This is used by C-c C-c for property action.
9607 (save-excursion
9608 (beginning-of-line 1)
9609 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9611 (defun org-get-property-block (&optional beg end force)
9612 "Return the (beg . end) range of the body of the property drawer.
9613 BEG and END can be beginning and end of subtree, if not given
9614 they will be found.
9615 If the drawer does not exist and FORCE is non-nil, create the drawer."
9616 (catch 'exit
9617 (save-excursion
9618 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9619 (end (or end (progn (outline-next-heading) (point)))))
9620 (goto-char beg)
9621 (if (re-search-forward org-property-start-re end t)
9622 (setq beg (1+ (match-end 0)))
9623 (if force
9624 (save-excursion
9625 (org-insert-property-drawer)
9626 (setq end (progn (outline-next-heading) (point))))
9627 (throw 'exit nil))
9628 (goto-char beg)
9629 (if (re-search-forward org-property-start-re end t)
9630 (setq beg (1+ (match-end 0)))))
9631 (if (re-search-forward org-property-end-re end t)
9632 (setq end (match-beginning 0))
9633 (or force (throw 'exit nil))
9634 (goto-char beg)
9635 (setq end beg)
9636 (org-indent-line-function)
9637 (insert ":END:\n"))
9638 (cons beg end)))))
9640 (defun org-entry-properties (&optional pom which)
9641 "Get all properties of the entry at point-or-marker POM.
9642 This includes the TODO keyword, the tags, time strings for deadline,
9643 scheduled, and clocking, and any additional properties defined in the
9644 entry. The return value is an alist, keys may occur multiple times
9645 if the property key was used several times.
9646 POM may also be nil, in which case the current entry is used.
9647 If WHICH is nil or `all', get all properties. If WHICH is
9648 `special' or `standard', only get that subclass."
9649 (setq which (or which 'all))
9650 (org-with-point-at pom
9651 (let ((clockstr (substring org-clock-string 0 -1))
9652 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9653 beg end range props sum-props key value string clocksum)
9654 (save-excursion
9655 (when (condition-case nil (org-back-to-heading t) (error nil))
9656 (setq beg (point))
9657 (setq sum-props (get-text-property (point) 'org-summaries))
9658 (setq clocksum (get-text-property (point) :org-clock-minutes))
9659 (outline-next-heading)
9660 (setq end (point))
9661 (when (memq which '(all special))
9662 ;; Get the special properties, like TODO and tags
9663 (goto-char beg)
9664 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9665 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9666 (when (looking-at org-priority-regexp)
9667 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9668 (when (and (setq value (org-get-tags-string))
9669 (string-match "\\S-" value))
9670 (push (cons "TAGS" value) props))
9671 (when (setq value (org-get-tags-at))
9672 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9673 props))
9674 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9675 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9676 string (if (equal key clockstr)
9677 (org-no-properties
9678 (org-trim
9679 (buffer-substring
9680 (match-beginning 3) (goto-char (point-at-eol)))))
9681 (substring (org-match-string-no-properties 3) 1 -1)))
9682 (unless key
9683 (if (= (char-after (match-beginning 3)) ?\[)
9684 (setq key "TIMESTAMP_IA")
9685 (setq key "TIMESTAMP")))
9686 (when (or (equal key clockstr) (not (assoc key props)))
9687 (push (cons key string) props)))
9691 (when (memq which '(all standard))
9692 ;; Get the standard properties, like :PORP: ...
9693 (setq range (org-get-property-block beg end))
9694 (when range
9695 (goto-char (car range))
9696 (while (re-search-forward
9697 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9698 (cdr range) t)
9699 (setq key (org-match-string-no-properties 1)
9700 value (org-trim (or (org-match-string-no-properties 2) "")))
9701 (unless (member key excluded)
9702 (push (cons key (or value "")) props)))))
9703 (if clocksum
9704 (push (cons "CLOCKSUM"
9705 (org-columns-number-to-string (/ (float clocksum) 60.)
9706 'add_times))
9707 props))
9708 (append sum-props (nreverse props)))))))
9710 (defun org-entry-get (pom property &optional inherit)
9711 "Get value of PROPERTY for entry at point-or-marker POM.
9712 If INHERIT is non-nil and the entry does not have the property,
9713 then also check higher levels of the hierarchy.
9714 If INHERIT is the symbol `selective', use inheritance only if the setting
9715 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9716 If the property is present but empty, the return value is the empty string.
9717 If the property is not present at all, nil is returned."
9718 (org-with-point-at pom
9719 (if (and inherit (if (eq inherit 'selective)
9720 (org-property-inherit-p property)
9722 (org-entry-get-with-inheritance property)
9723 (if (member property org-special-properties)
9724 ;; We need a special property. Use brute force, get all properties.
9725 (cdr (assoc property (org-entry-properties nil 'special)))
9726 (let ((range (org-get-property-block)))
9727 (if (and range
9728 (goto-char (car range))
9729 (re-search-forward
9730 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9731 (cdr range) t))
9732 ;; Found the property, return it.
9733 (if (match-end 1)
9734 (org-match-string-no-properties 1)
9735 "")))))))
9737 (defun org-property-or-variable-value (var &optional inherit)
9738 "Check if there is a property fixing the value of VAR.
9739 If yes, return this value. If not, return the current value of the variable."
9740 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9741 (if (and prop (stringp prop) (string-match "\\S-" prop))
9742 (read prop)
9743 (symbol-value var))))
9745 (defun org-entry-delete (pom property)
9746 "Delete the property PROPERTY from entry at point-or-marker POM."
9747 (org-with-point-at pom
9748 (if (member property org-special-properties)
9749 nil ; cannot delete these properties.
9750 (let ((range (org-get-property-block)))
9751 (if (and range
9752 (goto-char (car range))
9753 (re-search-forward
9754 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9755 (cdr range) t))
9756 (progn
9757 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9759 nil)))))
9761 ;; Multi-values properties are properties that contain multiple values
9762 ;; These values are assumed to be single words, separated by whitespace.
9763 (defun org-entry-add-to-multivalued-property (pom property value)
9764 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9765 (let* ((old (org-entry-get pom property))
9766 (values (and old (org-split-string old "[ \t]"))))
9767 (unless (member value values)
9768 (setq values (cons value values))
9769 (org-entry-put pom property
9770 (mapconcat 'identity values " ")))))
9772 (defun org-entry-remove-from-multivalued-property (pom property value)
9773 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9774 (let* ((old (org-entry-get pom property))
9775 (values (and old (org-split-string old "[ \t]"))))
9776 (when (member value values)
9777 (setq values (delete value values))
9778 (org-entry-put pom property
9779 (mapconcat 'identity values " ")))))
9781 (defun org-entry-member-in-multivalued-property (pom property value)
9782 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9783 (let* ((old (org-entry-get pom property))
9784 (values (and old (org-split-string old "[ \t]"))))
9785 (member value values)))
9787 (defvar org-entry-property-inherited-from (make-marker))
9789 (defun org-entry-get-with-inheritance (property)
9790 "Get entry property, and search higher levels if not present."
9791 (let (tmp)
9792 (save-excursion
9793 (save-restriction
9794 (widen)
9795 (catch 'ex
9796 (while t
9797 (when (setq tmp (org-entry-get nil property))
9798 (org-back-to-heading t)
9799 (move-marker org-entry-property-inherited-from (point))
9800 (throw 'ex tmp))
9801 (or (org-up-heading-safe) (throw 'ex nil)))))
9802 (or tmp
9803 (cdr (assoc property org-local-properties))
9804 (cdr (assoc property org-global-properties))
9805 (cdr (assoc property org-global-properties-fixed))))))
9807 (defun org-entry-put (pom property value)
9808 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9809 (org-with-point-at pom
9810 (org-back-to-heading t)
9811 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9812 range)
9813 (cond
9814 ((equal property "TODO")
9815 (when (and (stringp value) (string-match "\\S-" value)
9816 (not (member value org-todo-keywords-1)))
9817 (error "\"%s\" is not a valid TODO state" value))
9818 (if (or (not value)
9819 (not (string-match "\\S-" value)))
9820 (setq value 'none))
9821 (org-todo value)
9822 (org-set-tags nil 'align))
9823 ((equal property "PRIORITY")
9824 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9825 (string-to-char value) ?\ ))
9826 (org-set-tags nil 'align))
9827 ((equal property "SCHEDULED")
9828 (if (re-search-forward org-scheduled-time-regexp end t)
9829 (cond
9830 ((eq value 'earlier) (org-timestamp-change -1 'day))
9831 ((eq value 'later) (org-timestamp-change 1 'day))
9832 (t (call-interactively 'org-schedule)))
9833 (call-interactively 'org-schedule)))
9834 ((equal property "DEADLINE")
9835 (if (re-search-forward org-deadline-time-regexp end t)
9836 (cond
9837 ((eq value 'earlier) (org-timestamp-change -1 'day))
9838 ((eq value 'later) (org-timestamp-change 1 'day))
9839 (t (call-interactively 'org-deadline)))
9840 (call-interactively 'org-deadline)))
9841 ((member property org-special-properties)
9842 (error "The %s property can not yet be set with `org-entry-put'"
9843 property))
9844 (t ; a non-special property
9845 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9846 (setq range (org-get-property-block beg end 'force))
9847 (goto-char (car range))
9848 (if (re-search-forward
9849 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9850 (progn
9851 (delete-region (match-beginning 1) (match-end 1))
9852 (goto-char (match-beginning 1)))
9853 (goto-char (cdr range))
9854 (insert "\n")
9855 (backward-char 1)
9856 (org-indent-line-function)
9857 (insert ":" property ":"))
9858 (and value (insert " " value))
9859 (org-indent-line-function)))))))
9861 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9862 "Get all property keys in the current buffer.
9863 With INCLUDE-SPECIALS, also list the special properties that relect things
9864 like tags and TODO state.
9865 With INCLUDE-DEFAULTS, also include properties that has special meaning
9866 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9867 With INCLUDE-COLUMNS, also include property names given in COLUMN
9868 formats in the current buffer."
9869 (let (rtn range cfmt cols s p)
9870 (save-excursion
9871 (save-restriction
9872 (widen)
9873 (goto-char (point-min))
9874 (while (re-search-forward org-property-start-re nil t)
9875 (setq range (org-get-property-block))
9876 (goto-char (car range))
9877 (while (re-search-forward
9878 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9879 (cdr range) t)
9880 (add-to-list 'rtn (org-match-string-no-properties 1)))
9881 (outline-next-heading))))
9883 (when include-specials
9884 (setq rtn (append org-special-properties rtn)))
9886 (when include-defaults
9887 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9889 (when include-columns
9890 (save-excursion
9891 (save-restriction
9892 (widen)
9893 (goto-char (point-min))
9894 (while (re-search-forward
9895 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9896 nil t)
9897 (setq cfmt (match-string 2) s 0)
9898 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9899 cfmt s)
9900 (setq s (match-end 0)
9901 p (match-string 1 cfmt))
9902 (unless (or (equal p "ITEM")
9903 (member p org-special-properties))
9904 (add-to-list 'rtn (match-string 1 cfmt))))))))
9906 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9908 (defun org-property-values (key)
9909 "Return a list of all values of property KEY."
9910 (save-excursion
9911 (save-restriction
9912 (widen)
9913 (goto-char (point-min))
9914 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9915 values)
9916 (while (re-search-forward re nil t)
9917 (add-to-list 'values (org-trim (match-string 1))))
9918 (delete "" values)))))
9920 (defun org-insert-property-drawer ()
9921 "Insert a property drawer into the current entry."
9922 (interactive)
9923 (org-back-to-heading t)
9924 (looking-at outline-regexp)
9925 (let ((indent (- (match-end 0)(match-beginning 0)))
9926 (beg (point))
9927 (re (concat "^[ \t]*" org-keyword-time-regexp))
9928 end hiddenp)
9929 (outline-next-heading)
9930 (setq end (point))
9931 (goto-char beg)
9932 (while (re-search-forward re end t))
9933 (setq hiddenp (org-invisible-p))
9934 (end-of-line 1)
9935 (and (equal (char-after) ?\n) (forward-char 1))
9936 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9937 (beginning-of-line 2))
9938 (org-skip-over-state-notes)
9939 (skip-chars-backward " \t\n\r")
9940 (if (eq (char-before) ?*) (forward-char 1))
9941 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9942 (beginning-of-line 0)
9943 (org-indent-to-column indent)
9944 (beginning-of-line 2)
9945 (org-indent-to-column indent)
9946 (beginning-of-line 0)
9947 (if hiddenp
9948 (save-excursion
9949 (org-back-to-heading t)
9950 (hide-entry))
9951 (org-flag-drawer t))))
9953 (defun org-set-property (property value)
9954 "In the current entry, set PROPERTY to VALUE.
9955 When called interactively, this will prompt for a property name, offering
9956 completion on existing and default properties. And then it will prompt
9957 for a value, offering competion either on allowed values (via an inherited
9958 xxx_ALL property) or on existing values in other instances of this property
9959 in the current file."
9960 (interactive
9961 (let* ((completion-ignore-case t)
9962 (keys (org-buffer-property-keys nil t t))
9963 (prop0 (completing-read "Property: " (mapcar 'list keys)))
9964 (prop (if (member prop0 keys)
9965 prop0
9966 (or (cdr (assoc (downcase prop0)
9967 (mapcar (lambda (x) (cons (downcase x) x))
9968 keys)))
9969 prop0)))
9970 (cur (org-entry-get nil prop))
9971 (allowed (org-property-get-allowed-values nil prop 'table))
9972 (existing (mapcar 'list (org-property-values prop)))
9973 (val (if allowed
9974 (org-completing-read "Value: " allowed nil 'req-match)
9975 (org-completing-read
9976 (concat "Value" (if (and cur (string-match "\\S-" cur))
9977 (concat "[" cur "]") "")
9978 ": ")
9979 existing nil nil "" nil cur))))
9980 (list prop (if (equal val "") cur val))))
9981 (unless (equal (org-entry-get nil property) value)
9982 (org-entry-put nil property value)))
9984 (defun org-delete-property (property)
9985 "In the current entry, delete PROPERTY."
9986 (interactive
9987 (let* ((completion-ignore-case t)
9988 (prop (completing-read
9989 "Property: " (org-entry-properties nil 'standard))))
9990 (list prop)))
9991 (message "Property %s %s" property
9992 (if (org-entry-delete nil property)
9993 "deleted"
9994 "was not present in the entry")))
9996 (defun org-delete-property-globally (property)
9997 "Remove PROPERTY globally, from all entries."
9998 (interactive
9999 (let* ((completion-ignore-case t)
10000 (prop (completing-read
10001 "Globally remove property: "
10002 (mapcar 'list (org-buffer-property-keys)))))
10003 (list prop)))
10004 (save-excursion
10005 (save-restriction
10006 (widen)
10007 (goto-char (point-min))
10008 (let ((cnt 0))
10009 (while (re-search-forward
10010 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10011 nil t)
10012 (setq cnt (1+ cnt))
10013 (replace-match ""))
10014 (message "Property \"%s\" removed from %d entries" property cnt)))))
10016 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10018 (defun org-compute-property-at-point ()
10019 "Compute the property at point.
10020 This looks for an enclosing column format, extracts the operator and
10021 then applies it to the proerty in the column format's scope."
10022 (interactive)
10023 (unless (org-at-property-p)
10024 (error "Not at a property"))
10025 (let ((prop (org-match-string-no-properties 2)))
10026 (org-columns-get-format-and-top-level)
10027 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10028 (error "No operator defined for property %s" prop))
10029 (org-columns-compute prop)))
10031 (defun org-property-get-allowed-values (pom property &optional table)
10032 "Get allowed values for the property PROPERTY.
10033 When TABLE is non-nil, return an alist that can directly be used for
10034 completion."
10035 (let (vals)
10036 (cond
10037 ((equal property "TODO")
10038 (setq vals (org-with-point-at pom
10039 (append org-todo-keywords-1 '("")))))
10040 ((equal property "PRIORITY")
10041 (let ((n org-lowest-priority))
10042 (while (>= n org-highest-priority)
10043 (push (char-to-string n) vals)
10044 (setq n (1- n)))))
10045 ((member property org-special-properties))
10047 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10049 (when (and vals (string-match "\\S-" vals))
10050 (setq vals (car (read-from-string (concat "(" vals ")"))))
10051 (setq vals (mapcar (lambda (x)
10052 (cond ((stringp x) x)
10053 ((numberp x) (number-to-string x))
10054 ((symbolp x) (symbol-name x))
10055 (t "???")))
10056 vals)))))
10057 (if table (mapcar 'list vals) vals)))
10059 (defun org-property-previous-allowed-value (&optional previous)
10060 "Switch to the next allowed value for this property."
10061 (interactive)
10062 (org-property-next-allowed-value t))
10064 (defun org-property-next-allowed-value (&optional previous)
10065 "Switch to the next allowed value for this property."
10066 (interactive)
10067 (unless (org-at-property-p)
10068 (error "Not at a property"))
10069 (let* ((key (match-string 2))
10070 (value (match-string 3))
10071 (allowed (or (org-property-get-allowed-values (point) key)
10072 (and (member value '("[ ]" "[-]" "[X]"))
10073 '("[ ]" "[X]"))))
10074 nval)
10075 (unless allowed
10076 (error "Allowed values for this property have not been defined"))
10077 (if previous (setq allowed (reverse allowed)))
10078 (if (member value allowed)
10079 (setq nval (car (cdr (member value allowed)))))
10080 (setq nval (or nval (car allowed)))
10081 (if (equal nval value)
10082 (error "Only one allowed value for this property"))
10083 (org-at-property-p)
10084 (replace-match (concat " :" key ": " nval) t t)
10085 (org-indent-line-function)
10086 (beginning-of-line 1)
10087 (skip-chars-forward " \t")))
10089 (defun org-find-entry-with-id (ident)
10090 "Locate the entry that contains the ID property with exact value IDENT.
10091 IDENT can be a string, a symbol or a number, this function will search for
10092 the string representation of it.
10093 Return the position where this entry starts, or nil if there is no such entry."
10094 (let ((id (cond
10095 ((stringp ident) ident)
10096 ((symbol-name ident) (symbol-name ident))
10097 ((numberp ident) (number-to-string ident))
10098 (t (error "IDENT %s must be a string, symbol or number" ident))))
10099 (case-fold-search nil))
10100 (save-excursion
10101 (save-restriction
10102 (widen)
10103 (goto-char (point-min))
10104 (when (re-search-forward
10105 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10106 nil t)
10107 (org-back-to-heading)
10108 (point))))))
10110 ;;;; Timestamps
10112 (defvar org-last-changed-timestamp nil)
10113 (defvar org-time-was-given) ; dynamically scoped parameter
10114 (defvar org-end-time-was-given) ; dynamically scoped parameter
10115 (defvar org-ts-what) ; dynamically scoped parameter
10117 (defun org-time-stamp (arg)
10118 "Prompt for a date/time and insert a time stamp.
10119 If the user specifies a time like HH:MM, or if this command is called
10120 with a prefix argument, the time stamp will contain date and time.
10121 Otherwise, only the date will be included. All parts of a date not
10122 specified by the user will be filled in from the current date/time.
10123 So if you press just return without typing anything, the time stamp
10124 will represent the current date/time. If there is already a timestamp
10125 at the cursor, it will be modified."
10126 (interactive "P")
10127 (let* ((ts nil)
10128 (default-time
10129 ;; Default time is either today, or, when entering a range,
10130 ;; the range start.
10131 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10132 (save-excursion
10133 (re-search-backward
10134 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10135 (- (point) 20) t)))
10136 (apply 'encode-time (org-parse-time-string (match-string 1)))
10137 (current-time)))
10138 (default-input (and ts (org-get-compact-tod ts)))
10139 org-time-was-given org-end-time-was-given time)
10140 (cond
10141 ((and (org-at-timestamp-p)
10142 (eq last-command 'org-time-stamp)
10143 (eq this-command 'org-time-stamp))
10144 (insert "--")
10145 (setq time (let ((this-command this-command))
10146 (org-read-date arg 'totime nil nil default-time default-input)))
10147 (org-insert-time-stamp time (or org-time-was-given arg)))
10148 ((org-at-timestamp-p)
10149 (setq time (let ((this-command this-command))
10150 (org-read-date arg 'totime nil nil default-time default-input)))
10151 (when (org-at-timestamp-p) ; just to get the match data
10152 (replace-match "")
10153 (setq org-last-changed-timestamp
10154 (org-insert-time-stamp
10155 time (or org-time-was-given arg)
10156 nil nil nil (list org-end-time-was-given))))
10157 (message "Timestamp updated"))
10159 (setq time (let ((this-command this-command))
10160 (org-read-date arg 'totime nil nil default-time default-input)))
10161 (org-insert-time-stamp time (or org-time-was-given arg)
10162 nil nil nil (list org-end-time-was-given))))))
10164 ;; FIXME: can we use this for something else, like computing time differences?
10165 (defun org-get-compact-tod (s)
10166 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10167 (let* ((t1 (match-string 1 s))
10168 (h1 (string-to-number (match-string 2 s)))
10169 (m1 (string-to-number (match-string 3 s)))
10170 (t2 (and (match-end 4) (match-string 5 s)))
10171 (h2 (and t2 (string-to-number (match-string 6 s))))
10172 (m2 (and t2 (string-to-number (match-string 7 s))))
10173 dh dm)
10174 (if (not t2)
10176 (setq dh (- h2 h1) dm (- m2 m1))
10177 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10178 (concat t1 "+" (number-to-string dh)
10179 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10181 (defun org-time-stamp-inactive (&optional arg)
10182 "Insert an inactive time stamp.
10183 An inactive time stamp is enclosed in square brackets instead of angle
10184 brackets. It is inactive in the sense that it does not trigger agenda entries,
10185 does not link to the calendar and cannot be changed with the S-cursor keys.
10186 So these are more for recording a certain time/date."
10187 (interactive "P")
10188 (let (org-time-was-given org-end-time-was-given time)
10189 (setq time (org-read-date arg 'totime))
10190 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10191 nil nil (list org-end-time-was-given))))
10193 (defvar org-date-ovl (org-make-overlay 1 1))
10194 (org-overlay-put org-date-ovl 'face 'org-warning)
10195 (org-detach-overlay org-date-ovl)
10197 (defvar org-ans1) ; dynamically scoped parameter
10198 (defvar org-ans2) ; dynamically scoped parameter
10200 (defvar org-plain-time-of-day-regexp) ; defined below
10202 (defvar org-read-date-overlay nil)
10203 (defvar org-dcst nil) ; dynamically scoped
10205 (defun org-read-date (&optional with-time to-time from-string prompt
10206 default-time default-input)
10207 "Read a date, possibly a time, and make things smooth for the user.
10208 The prompt will suggest to enter an ISO date, but you can also enter anything
10209 which will at least partially be understood by `parse-time-string'.
10210 Unrecognized parts of the date will default to the current day, month, year,
10211 hour and minute. If this command is called to replace a timestamp at point,
10212 of to enter the second timestamp of a range, the default time is taken from the
10213 existing stamp. For example,
10214 3-2-5 --> 2003-02-05
10215 feb 15 --> currentyear-02-15
10216 sep 12 9 --> 2009-09-12
10217 12:45 --> today 12:45
10218 22 sept 0:34 --> currentyear-09-22 0:34
10219 12 --> currentyear-currentmonth-12
10220 Fri --> nearest Friday (today or later)
10221 etc.
10223 Furthermore you can specify a relative date by giving, as the *first* thing
10224 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10225 change in days weeks, months, years.
10226 With a single plus or minus, the date is relative to today. With a double
10227 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10228 +4d --> four days from today
10229 +4 --> same as above
10230 +2w --> two weeks from today
10231 ++5 --> five days from default date
10233 The function understands only English month and weekday abbreviations,
10234 but this can be configured with the variables `parse-time-months' and
10235 `parse-time-weekdays'.
10237 While prompting, a calendar is popped up - you can also select the
10238 date with the mouse (button 1). The calendar shows a period of three
10239 months. To scroll it to other months, use the keys `>' and `<'.
10240 If you don't like the calendar, turn it off with
10241 \(setq org-read-date-popup-calendar nil)
10243 With optional argument TO-TIME, the date will immediately be converted
10244 to an internal time.
10245 With an optional argument WITH-TIME, the prompt will suggest to also
10246 insert a time. Note that when WITH-TIME is not set, you can still
10247 enter a time, and this function will inform the calling routine about
10248 this change. The calling routine may then choose to change the format
10249 used to insert the time stamp into the buffer to include the time.
10250 With optional argument FROM-STRING, read from this string instead from
10251 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10252 the time/date that is used for everything that is not specified by the
10253 user."
10254 (require 'parse-time)
10255 (let* ((org-time-stamp-rounding-minutes
10256 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10257 (org-dcst org-display-custom-times)
10258 (ct (org-current-time))
10259 (def (or default-time ct))
10260 (defdecode (decode-time def))
10261 (dummy (progn
10262 (when (< (nth 2 defdecode) org-extend-today-until)
10263 (setcar (nthcdr 2 defdecode) -1)
10264 (setcar (nthcdr 1 defdecode) 59)
10265 (setq def (apply 'encode-time defdecode)
10266 defdecode (decode-time def)))))
10267 (calendar-move-hook nil)
10268 (calendar-view-diary-initially-flag nil)
10269 (view-diary-entries-initially nil)
10270 (calendar-view-holidays-initially-flag nil)
10271 (view-calendar-holidays-initially nil)
10272 (timestr (format-time-string
10273 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10274 (prompt (concat (if prompt (concat prompt " ") "")
10275 (format "Date+time [%s]: " timestr)))
10276 ans (org-ans0 "") org-ans1 org-ans2 final)
10278 (cond
10279 (from-string (setq ans from-string))
10280 (org-read-date-popup-calendar
10281 (save-excursion
10282 (save-window-excursion
10283 (calendar)
10284 (calendar-forward-day (- (time-to-days def)
10285 (calendar-absolute-from-gregorian
10286 (calendar-current-date))))
10287 (org-eval-in-calendar nil t)
10288 (let* ((old-map (current-local-map))
10289 (map (copy-keymap calendar-mode-map))
10290 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10291 (org-defkey map (kbd "RET") 'org-calendar-select)
10292 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10293 'org-calendar-select-mouse)
10294 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10295 'org-calendar-select-mouse)
10296 (org-defkey minibuffer-local-map [(meta shift left)]
10297 (lambda () (interactive)
10298 (org-eval-in-calendar '(calendar-backward-month 1))))
10299 (org-defkey minibuffer-local-map [(meta shift right)]
10300 (lambda () (interactive)
10301 (org-eval-in-calendar '(calendar-forward-month 1))))
10302 (org-defkey minibuffer-local-map [(meta shift up)]
10303 (lambda () (interactive)
10304 (org-eval-in-calendar '(calendar-backward-year 1))))
10305 (org-defkey minibuffer-local-map [(meta shift down)]
10306 (lambda () (interactive)
10307 (org-eval-in-calendar '(calendar-forward-year 1))))
10308 (org-defkey minibuffer-local-map [(shift up)]
10309 (lambda () (interactive)
10310 (org-eval-in-calendar '(calendar-backward-week 1))))
10311 (org-defkey minibuffer-local-map [(shift down)]
10312 (lambda () (interactive)
10313 (org-eval-in-calendar '(calendar-forward-week 1))))
10314 (org-defkey minibuffer-local-map [(shift left)]
10315 (lambda () (interactive)
10316 (org-eval-in-calendar '(calendar-backward-day 1))))
10317 (org-defkey minibuffer-local-map [(shift right)]
10318 (lambda () (interactive)
10319 (org-eval-in-calendar '(calendar-forward-day 1))))
10320 (org-defkey minibuffer-local-map ">"
10321 (lambda () (interactive)
10322 (org-eval-in-calendar '(scroll-calendar-left 1))))
10323 (org-defkey minibuffer-local-map "<"
10324 (lambda () (interactive)
10325 (org-eval-in-calendar '(scroll-calendar-right 1))))
10326 (unwind-protect
10327 (progn
10328 (use-local-map map)
10329 (add-hook 'post-command-hook 'org-read-date-display)
10330 (setq org-ans0 (read-string prompt default-input nil nil))
10331 ;; org-ans0: from prompt
10332 ;; org-ans1: from mouse click
10333 ;; org-ans2: from calendar motion
10334 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10335 (remove-hook 'post-command-hook 'org-read-date-display)
10336 (use-local-map old-map)
10337 (when org-read-date-overlay
10338 (org-delete-overlay org-read-date-overlay)
10339 (setq org-read-date-overlay nil)))))))
10341 (t ; Naked prompt only
10342 (unwind-protect
10343 (setq ans (read-string prompt default-input nil timestr))
10344 (when org-read-date-overlay
10345 (org-delete-overlay org-read-date-overlay)
10346 (setq org-read-date-overlay nil)))))
10348 (setq final (org-read-date-analyze ans def defdecode))
10350 (if to-time
10351 (apply 'encode-time final)
10352 (if (and (boundp 'org-time-was-given) org-time-was-given)
10353 (format "%04d-%02d-%02d %02d:%02d"
10354 (nth 5 final) (nth 4 final) (nth 3 final)
10355 (nth 2 final) (nth 1 final))
10356 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10357 (defvar def)
10358 (defvar defdecode)
10359 (defvar with-time)
10360 (defun org-read-date-display ()
10361 "Display the currrent date prompt interpretation in the minibuffer."
10362 (when org-read-date-display-live
10363 (when org-read-date-overlay
10364 (org-delete-overlay org-read-date-overlay))
10365 (let ((p (point)))
10366 (end-of-line 1)
10367 (while (not (equal (buffer-substring
10368 (max (point-min) (- (point) 4)) (point))
10369 " "))
10370 (insert " "))
10371 (goto-char p))
10372 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10373 " " (or org-ans1 org-ans2)))
10374 (org-end-time-was-given nil)
10375 (f (org-read-date-analyze ans def defdecode))
10376 (fmts (if org-dcst
10377 org-time-stamp-custom-formats
10378 org-time-stamp-formats))
10379 (fmt (if (or with-time
10380 (and (boundp 'org-time-was-given) org-time-was-given))
10381 (cdr fmts)
10382 (car fmts)))
10383 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10384 (when (and org-end-time-was-given
10385 (string-match org-plain-time-of-day-regexp txt))
10386 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10387 org-end-time-was-given
10388 (substring txt (match-end 0)))))
10389 (setq org-read-date-overlay
10390 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10391 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10393 (defun org-read-date-analyze (ans def defdecode)
10394 "Analyze the combined answer of the date prompt."
10395 ;; FIXME: cleanup and comment
10396 (let (delta deltan deltaw deltadef year month day
10397 hour minute second wday pm h2 m2 tl wday1
10398 iso-year iso-weekday iso-week iso-year iso-date)
10400 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10401 (setq ans "+0"))
10403 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10404 (setq ans (replace-match "" t t ans)
10405 deltan (car delta)
10406 deltaw (nth 1 delta)
10407 deltadef (nth 2 delta)))
10409 ;; Check if there is an iso week date in there
10410 ;; If yes, sore the info and ostpone interpreting it until the rest
10411 ;; of the parsing is done
10412 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10413 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10414 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10415 iso-week (string-to-number (match-string 2 ans)))
10416 (setq ans (replace-match "" t t ans)))
10418 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10419 (when (string-match
10420 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10421 (setq year (if (match-end 2)
10422 (string-to-number (match-string 2 ans))
10423 (string-to-number (format-time-string "%Y")))
10424 month (string-to-number (match-string 3 ans))
10425 day (string-to-number (match-string 4 ans)))
10426 (if (< year 100) (setq year (+ 2000 year)))
10427 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10428 t nil ans)))
10429 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10430 ;; If there is a time with am/pm, and *no* time without it, we convert
10431 ;; so that matching will be successful.
10432 (loop for i from 1 to 2 do ; twice, for end time as well
10433 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10434 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10435 (setq hour (string-to-number (match-string 1 ans))
10436 minute (if (match-end 3)
10437 (string-to-number (match-string 3 ans))
10439 pm (equal ?p
10440 (string-to-char (downcase (match-string 4 ans)))))
10441 (if (and (= hour 12) (not pm))
10442 (setq hour 0)
10443 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10444 (setq ans (replace-match (format "%02d:%02d" hour minute)
10445 t t ans))))
10447 ;; Check if a time range is given as a duration
10448 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10449 (setq hour (string-to-number (match-string 1 ans))
10450 h2 (+ hour (string-to-number (match-string 3 ans)))
10451 minute (string-to-number (match-string 2 ans))
10452 m2 (+ minute (if (match-end 5) (string-to-number
10453 (match-string 5 ans))0)))
10454 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10455 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10456 t t ans)))
10458 ;; Check if there is a time range
10459 (when (boundp 'org-end-time-was-given)
10460 (setq org-time-was-given nil)
10461 (when (and (string-match org-plain-time-of-day-regexp ans)
10462 (match-end 8))
10463 (setq org-end-time-was-given (match-string 8 ans))
10464 (setq ans (concat (substring ans 0 (match-beginning 7))
10465 (substring ans (match-end 7))))))
10467 (setq tl (parse-time-string ans)
10468 day (or (nth 3 tl) (nth 3 defdecode))
10469 month (or (nth 4 tl)
10470 (if (and org-read-date-prefer-future
10471 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10472 (1+ (nth 4 defdecode))
10473 (nth 4 defdecode)))
10474 year (or (nth 5 tl)
10475 (if (and org-read-date-prefer-future
10476 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10477 (1+ (nth 5 defdecode))
10478 (nth 5 defdecode)))
10479 hour (or (nth 2 tl) (nth 2 defdecode))
10480 minute (or (nth 1 tl) (nth 1 defdecode))
10481 second (or (nth 0 tl) 0)
10482 wday (nth 6 tl))
10484 ;; Special date definitions below
10485 (cond
10486 (iso-week
10487 ;; There was an iso week
10488 (setq year (or iso-year year)
10489 day (or iso-weekday wday 1)
10490 wday nil ; to make sure that the trigger below does not match
10491 iso-date (calendar-gregorian-from-absolute
10492 (calendar-absolute-from-iso
10493 (list iso-week day year))))
10494 ; FIXME: Should we also push ISO weeks into the future?
10495 ; (when (and org-read-date-prefer-future
10496 ; (not iso-year)
10497 ; (< (calendar-absolute-from-gregorian iso-date)
10498 ; (time-to-days (current-time))))
10499 ; (setq year (1+ year)
10500 ; iso-date (calendar-gregorian-from-absolute
10501 ; (calendar-absolute-from-iso
10502 ; (list iso-week day year)))))
10503 (setq month (car iso-date)
10504 year (nth 2 iso-date)
10505 day (nth 1 iso-date)))
10506 (deltan
10507 (unless deltadef
10508 (let ((now (decode-time (current-time))))
10509 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10510 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10511 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10512 ((equal deltaw "m") (setq month (+ month deltan)))
10513 ((equal deltaw "y") (setq year (+ year deltan)))))
10514 ((and wday (not (nth 3 tl)))
10515 ;; Weekday was given, but no day, so pick that day in the week
10516 ;; on or after the derived date.
10517 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10518 (unless (equal wday wday1)
10519 (setq day (+ day (% (- wday wday1 -7) 7))))))
10520 (if (and (boundp 'org-time-was-given)
10521 (nth 2 tl))
10522 (setq org-time-was-given t))
10523 (if (< year 100) (setq year (+ 2000 year)))
10524 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10525 (list second minute hour day month year)))
10527 (defvar parse-time-weekdays)
10529 (defun org-read-date-get-relative (s today default)
10530 "Check string S for special relative date string.
10531 TODAY and DEFAULT are internal times, for today and for a default.
10532 Return shift list (N what def-flag)
10533 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10534 N is the number of WHATs to shift.
10535 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10536 the DEFAULT date rather than TODAY."
10537 (when (and
10538 (string-match
10539 (concat
10540 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10541 "\\([0-9]+\\)?"
10542 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10543 "\\([ \t]\\|$\\)") s)
10544 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10545 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10546 (string-to-char (substring (match-string 1 s) -1))
10547 ?+))
10548 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10549 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10550 (what (if (match-end 3) (match-string 3 s) "d"))
10551 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10552 (date (if rel default today))
10553 (wday (nth 6 (decode-time date)))
10554 delta)
10555 (if wday1
10556 (progn
10557 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10558 (if (= dir ?-) (setq delta (- delta 7)))
10559 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10560 (list delta "d" rel))
10561 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10563 (defun org-eval-in-calendar (form &optional keepdate)
10564 "Eval FORM in the calendar window and return to current window.
10565 Also, store the cursor date in variable org-ans2."
10566 (let ((sw (selected-window)))
10567 (select-window (get-buffer-window "*Calendar*"))
10568 (eval form)
10569 (when (and (not keepdate) (calendar-cursor-to-date))
10570 (let* ((date (calendar-cursor-to-date))
10571 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10572 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10573 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10574 (select-window sw)))
10576 ; ;; Update the prompt to show new default date
10577 ; (save-excursion
10578 ; (goto-char (point-min))
10579 ; (when (and org-ans2
10580 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10581 ; (get-text-property (match-end 0) 'field))
10582 ; (let ((inhibit-read-only t))
10583 ; (replace-match (concat "[" org-ans2 "]") t t)
10584 ; (add-text-properties (point-min) (1+ (match-end 0))
10585 ; (text-properties-at (1+ (point-min)))))))))
10587 (defun org-calendar-select ()
10588 "Return to `org-read-date' with the date currently selected.
10589 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10590 (interactive)
10591 (when (calendar-cursor-to-date)
10592 (let* ((date (calendar-cursor-to-date))
10593 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10594 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10595 (if (active-minibuffer-window) (exit-minibuffer))))
10597 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10598 "Insert a date stamp for the date given by the internal TIME.
10599 WITH-HM means, use the stamp format that includes the time of the day.
10600 INACTIVE means use square brackets instead of angular ones, so that the
10601 stamp will not contribute to the agenda.
10602 PRE and POST are optional strings to be inserted before and after the
10603 stamp.
10604 The command returns the inserted time stamp."
10605 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10606 stamp)
10607 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10608 (insert-before-markers (or pre ""))
10609 (insert-before-markers (setq stamp (format-time-string fmt time)))
10610 (when (listp extra)
10611 (setq extra (car extra))
10612 (if (and (stringp extra)
10613 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10614 (setq extra (format "-%02d:%02d"
10615 (string-to-number (match-string 1 extra))
10616 (string-to-number (match-string 2 extra))))
10617 (setq extra nil)))
10618 (when extra
10619 (backward-char 1)
10620 (insert-before-markers extra)
10621 (forward-char 1))
10622 (insert-before-markers (or post ""))
10623 stamp))
10625 (defun org-toggle-time-stamp-overlays ()
10626 "Toggle the use of custom time stamp formats."
10627 (interactive)
10628 (setq org-display-custom-times (not org-display-custom-times))
10629 (unless org-display-custom-times
10630 (let ((p (point-min)) (bmp (buffer-modified-p)))
10631 (while (setq p (next-single-property-change p 'display))
10632 (if (and (get-text-property p 'display)
10633 (eq (get-text-property p 'face) 'org-date))
10634 (remove-text-properties
10635 p (setq p (next-single-property-change p 'display))
10636 '(display t))))
10637 (set-buffer-modified-p bmp)))
10638 (if (featurep 'xemacs)
10639 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10640 (org-restart-font-lock)
10641 (setq org-table-may-need-update t)
10642 (if org-display-custom-times
10643 (message "Time stamps are overlayed with custom format")
10644 (message "Time stamp overlays removed")))
10646 (defun org-display-custom-time (beg end)
10647 "Overlay modified time stamp format over timestamp between BEG and END."
10648 (let* ((ts (buffer-substring beg end))
10649 t1 w1 with-hm tf time str w2 (off 0))
10650 (save-match-data
10651 (setq t1 (org-parse-time-string ts t))
10652 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10653 (setq off (- (match-end 0) (match-beginning 0)))))
10654 (setq end (- end off))
10655 (setq w1 (- end beg)
10656 with-hm (and (nth 1 t1) (nth 2 t1))
10657 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10658 time (org-fix-decoded-time t1)
10659 str (org-add-props
10660 (format-time-string
10661 (substring tf 1 -1) (apply 'encode-time time))
10662 nil 'mouse-face 'highlight)
10663 w2 (length str))
10664 (if (not (= w2 w1))
10665 (add-text-properties (1+ beg) (+ 2 beg)
10666 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10667 (if (featurep 'xemacs)
10668 (progn
10669 (put-text-property beg end 'invisible t)
10670 (put-text-property beg end 'end-glyph (make-glyph str)))
10671 (put-text-property beg end 'display str))))
10673 (defun org-translate-time (string)
10674 "Translate all timestamps in STRING to custom format.
10675 But do this only if the variable `org-display-custom-times' is set."
10676 (when org-display-custom-times
10677 (save-match-data
10678 (let* ((start 0)
10679 (re org-ts-regexp-both)
10680 t1 with-hm inactive tf time str beg end)
10681 (while (setq start (string-match re string start))
10682 (setq beg (match-beginning 0)
10683 end (match-end 0)
10684 t1 (save-match-data
10685 (org-parse-time-string (substring string beg end) t))
10686 with-hm (and (nth 1 t1) (nth 2 t1))
10687 inactive (equal (substring string beg (1+ beg)) "[")
10688 tf (funcall (if with-hm 'cdr 'car)
10689 org-time-stamp-custom-formats)
10690 time (org-fix-decoded-time t1)
10691 str (format-time-string
10692 (concat
10693 (if inactive "[" "<") (substring tf 1 -1)
10694 (if inactive "]" ">"))
10695 (apply 'encode-time time))
10696 string (replace-match str t t string)
10697 start (+ start (length str)))))))
10698 string)
10700 (defun org-fix-decoded-time (time)
10701 "Set 0 instead of nil for the first 6 elements of time.
10702 Don't touch the rest."
10703 (let ((n 0))
10704 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10706 (defun org-days-to-time (timestamp-string)
10707 "Difference between TIMESTAMP-STRING and now in days."
10708 (- (time-to-days (org-time-string-to-time timestamp-string))
10709 (time-to-days (current-time))))
10711 (defun org-deadline-close (timestamp-string &optional ndays)
10712 "Is the time in TIMESTAMP-STRING close to the current date?"
10713 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10714 (and (< (org-days-to-time timestamp-string) ndays)
10715 (not (org-entry-is-done-p))))
10717 (defun org-get-wdays (ts)
10718 "Get the deadline lead time appropriate for timestring TS."
10719 (cond
10720 ((<= org-deadline-warning-days 0)
10721 ;; 0 or negative, enforce this value no matter what
10722 (- org-deadline-warning-days))
10723 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10724 ;; lead time is specified.
10725 (floor (* (string-to-number (match-string 1 ts))
10726 (cdr (assoc (match-string 2 ts)
10727 '(("d" . 1) ("w" . 7)
10728 ("m" . 30.4) ("y" . 365.25)))))))
10729 ;; go for the default.
10730 (t org-deadline-warning-days)))
10732 (defun org-calendar-select-mouse (ev)
10733 "Return to `org-read-date' with the date currently selected.
10734 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10735 (interactive "e")
10736 (mouse-set-point ev)
10737 (when (calendar-cursor-to-date)
10738 (let* ((date (calendar-cursor-to-date))
10739 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10740 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10741 (if (active-minibuffer-window) (exit-minibuffer))))
10743 (defun org-check-deadlines (ndays)
10744 "Check if there are any deadlines due or past due.
10745 A deadline is considered due if it happens within `org-deadline-warning-days'
10746 days from today's date. If the deadline appears in an entry marked DONE,
10747 it is not shown. The prefix arg NDAYS can be used to test that many
10748 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10749 (interactive "P")
10750 (let* ((org-warn-days
10751 (cond
10752 ((equal ndays '(4)) 100000)
10753 (ndays (prefix-numeric-value ndays))
10754 (t (abs org-deadline-warning-days))))
10755 (case-fold-search nil)
10756 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10757 (callback
10758 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10760 (message "%d deadlines past-due or due within %d days"
10761 (org-occur regexp nil callback)
10762 org-warn-days)))
10764 (defun org-check-before-date (date)
10765 "Check if there are deadlines or scheduled entries before DATE."
10766 (interactive (list (org-read-date)))
10767 (let ((case-fold-search nil)
10768 (regexp (concat "\\<\\(" org-deadline-string
10769 "\\|" org-scheduled-string
10770 "\\) *<\\([^>]+\\)>"))
10771 (callback
10772 (lambda () (time-less-p
10773 (org-time-string-to-time (match-string 2))
10774 (org-time-string-to-time date)))))
10775 (message "%d entries before %s"
10776 (org-occur regexp nil callback) date)))
10778 (defun org-evaluate-time-range (&optional to-buffer)
10779 "Evaluate a time range by computing the difference between start and end.
10780 Normally the result is just printed in the echo area, but with prefix arg
10781 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10782 If the time range is actually in a table, the result is inserted into the
10783 next column.
10784 For time difference computation, a year is assumed to be exactly 365
10785 days in order to avoid rounding problems."
10786 (interactive "P")
10788 (org-clock-update-time-maybe)
10789 (save-excursion
10790 (unless (org-at-date-range-p t)
10791 (goto-char (point-at-bol))
10792 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10793 (if (not (org-at-date-range-p t))
10794 (error "Not at a time-stamp range, and none found in current line")))
10795 (let* ((ts1 (match-string 1))
10796 (ts2 (match-string 2))
10797 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10798 (match-end (match-end 0))
10799 (time1 (org-time-string-to-time ts1))
10800 (time2 (org-time-string-to-time ts2))
10801 (t1 (time-to-seconds time1))
10802 (t2 (time-to-seconds time2))
10803 (diff (abs (- t2 t1)))
10804 (negative (< (- t2 t1) 0))
10805 ;; (ys (floor (* 365 24 60 60)))
10806 (ds (* 24 60 60))
10807 (hs (* 60 60))
10808 (fy "%dy %dd %02d:%02d")
10809 (fy1 "%dy %dd")
10810 (fd "%dd %02d:%02d")
10811 (fd1 "%dd")
10812 (fh "%02d:%02d")
10813 y d h m align)
10814 (if havetime
10815 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10817 d (floor (/ diff ds)) diff (mod diff ds)
10818 h (floor (/ diff hs)) diff (mod diff hs)
10819 m (floor (/ diff 60)))
10820 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10822 d (floor (+ (/ diff ds) 0.5))
10823 h 0 m 0))
10824 (if (not to-buffer)
10825 (message "%s" (org-make-tdiff-string y d h m))
10826 (if (org-at-table-p)
10827 (progn
10828 (goto-char match-end)
10829 (setq align t)
10830 (and (looking-at " *|") (goto-char (match-end 0))))
10831 (goto-char match-end))
10832 (if (looking-at
10833 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10834 (replace-match ""))
10835 (if negative (insert " -"))
10836 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10837 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10838 (insert " " (format fh h m))))
10839 (if align (org-table-align))
10840 (message "Time difference inserted")))))
10842 (defun org-make-tdiff-string (y d h m)
10843 (let ((fmt "")
10844 (l nil))
10845 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10846 l (push y l)))
10847 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10848 l (push d l)))
10849 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10850 l (push h l)))
10851 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10852 l (push m l)))
10853 (apply 'format fmt (nreverse l))))
10855 (defun org-time-string-to-time (s)
10856 (apply 'encode-time (org-parse-time-string s)))
10858 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10859 "Convert a time stamp to an absolute day number.
10860 If there is a specifyer for a cyclic time stamp, get the closest date to
10861 DAYNR.
10862 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10863 (cond
10864 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10865 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10866 daynr
10867 (+ daynr 1000)))
10868 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10869 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10870 (time-to-days (current-time))) (match-string 0 s)
10871 prefer show-all))
10872 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10874 (defun org-days-to-iso-week (days)
10875 "Return the iso week number."
10876 (require 'cal-iso)
10877 (car (calendar-iso-from-absolute days)))
10879 (defun org-small-year-to-year (year)
10880 "Convert 2-digit years into 4-digit years.
10881 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10882 The year 2000 cannot be abbreviated. Any year lager than 99
10883 is retrned unchanged."
10884 (if (< year 38)
10885 (setq year (+ 2000 year))
10886 (if (< year 100)
10887 (setq year (+ 1900 year))))
10888 year)
10890 (defun org-time-from-absolute (d)
10891 "Return the time corresponding to date D.
10892 D may be an absolute day number, or a calendar-type list (month day year)."
10893 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10894 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10896 (defun org-calendar-holiday ()
10897 "List of holidays, for Diary display in Org-mode."
10898 (require 'holidays)
10899 (let ((hl (funcall
10900 (if (fboundp 'calendar-check-holidays)
10901 'calendar-check-holidays 'check-calendar-holidays) date)))
10902 (if hl (mapconcat 'identity hl "; "))))
10904 (defun org-diary-sexp-entry (sexp entry date)
10905 "Process a SEXP diary ENTRY for DATE."
10906 (require 'diary-lib)
10907 (let ((result (if calendar-debug-sexp
10908 (let ((stack-trace-on-error t))
10909 (eval (car (read-from-string sexp))))
10910 (condition-case nil
10911 (eval (car (read-from-string sexp)))
10912 (error
10913 (beep)
10914 (message "Bad sexp at line %d in %s: %s"
10915 (org-current-line)
10916 (buffer-file-name) sexp)
10917 (sleep-for 2))))))
10918 (cond ((stringp result) result)
10919 ((and (consp result)
10920 (stringp (cdr result))) (cdr result))
10921 (result entry)
10922 (t nil))))
10924 (defun org-diary-to-ical-string (frombuf)
10925 "Get iCalendar entries from diary entries in buffer FROMBUF.
10926 This uses the icalendar.el library."
10927 (let* ((tmpdir (if (featurep 'xemacs)
10928 (temp-directory)
10929 temporary-file-directory))
10930 (tmpfile (make-temp-name
10931 (expand-file-name "orgics" tmpdir)))
10932 buf rtn b e)
10933 (save-excursion
10934 (set-buffer frombuf)
10935 (icalendar-export-region (point-min) (point-max) tmpfile)
10936 (setq buf (find-buffer-visiting tmpfile))
10937 (set-buffer buf)
10938 (goto-char (point-min))
10939 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10940 (setq b (match-beginning 0)))
10941 (goto-char (point-max))
10942 (if (re-search-backward "^END:VEVENT" nil t)
10943 (setq e (match-end 0)))
10944 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10945 (kill-buffer buf)
10946 (kill-buffer frombuf)
10947 (delete-file tmpfile)
10948 rtn))
10950 (defun org-closest-date (start current change prefer show-all)
10951 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10952 When PREFER is `past' return a date that is either CURRENT or past.
10953 When PREFER is `future', return a date that is either CURRENT or future.
10954 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10955 ;; Make the proper lists from the dates
10956 (catch 'exit
10957 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10958 dn dw sday cday n1 n2
10959 d m y y1 y2 date1 date2 nmonths nm ny m2)
10961 (setq start (org-date-to-gregorian start)
10962 current (org-date-to-gregorian
10963 (if show-all
10964 current
10965 (time-to-days (current-time))))
10966 sday (calendar-absolute-from-gregorian start)
10967 cday (calendar-absolute-from-gregorian current))
10969 (if (<= cday sday) (throw 'exit sday))
10971 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10972 (setq dn (string-to-number (match-string 1 change))
10973 dw (cdr (assoc (match-string 2 change) a1)))
10974 (error "Invalid change specifyer: %s" change))
10975 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10976 (cond
10977 ((eq dw 'day)
10978 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10979 n2 (+ n1 dn)))
10980 ((eq dw 'year)
10981 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10982 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10983 (setq date1 (list m d y1)
10984 n1 (calendar-absolute-from-gregorian date1)
10985 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10986 n2 (calendar-absolute-from-gregorian date2)))
10987 ((eq dw 'month)
10988 ;; approx number of month between the tow dates
10989 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10990 ;; How often does dn fit in there?
10991 (setq d (nth 1 start) m (car start) y (nth 2 start)
10992 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10993 m (+ m nm)
10994 ny (floor (/ m 12))
10995 y (+ y ny)
10996 m (- m (* ny 12)))
10997 (while (> m 12) (setq m (- m 12) y (1+ y)))
10998 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10999 (setq m2 (+ m dn) y2 y)
11000 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11001 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11002 (while (< n2 cday)
11003 (setq n1 n2 m m2 y y2)
11004 (setq m2 (+ m dn) y2 y)
11005 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11006 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11008 (if show-all
11009 (cond
11010 ((eq prefer 'past) n1)
11011 ((eq prefer 'future) (if (= cday n1) n1 n2))
11012 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11013 (cond
11014 ((eq prefer 'past) n1)
11015 ((eq prefer 'future) (if (= cday n1) n1 n2))
11016 (t (if (= cday n1) n1 n2)))))))
11018 (defun org-date-to-gregorian (date)
11019 "Turn any specification of DATE into a gregorian date for the calendar."
11020 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11021 ((and (listp date) (= (length date) 3)) date)
11022 ((stringp date)
11023 (setq date (org-parse-time-string date))
11024 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11025 ((listp date)
11026 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11028 (defun org-parse-time-string (s &optional nodefault)
11029 "Parse the standard Org-mode time string.
11030 This should be a lot faster than the normal `parse-time-string'.
11031 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11032 hour and minute fields will be nil if not given."
11033 (if (string-match org-ts-regexp0 s)
11034 (list 0
11035 (if (or (match-beginning 8) (not nodefault))
11036 (string-to-number (or (match-string 8 s) "0")))
11037 (if (or (match-beginning 7) (not nodefault))
11038 (string-to-number (or (match-string 7 s) "0")))
11039 (string-to-number (match-string 4 s))
11040 (string-to-number (match-string 3 s))
11041 (string-to-number (match-string 2 s))
11042 nil nil nil)
11043 (make-list 9 0)))
11045 (defun org-timestamp-up (&optional arg)
11046 "Increase the date item at the cursor by one.
11047 If the cursor is on the year, change the year. If it is on the month or
11048 the day, change that.
11049 With prefix ARG, change by that many units."
11050 (interactive "p")
11051 (org-timestamp-change (prefix-numeric-value arg)))
11053 (defun org-timestamp-down (&optional arg)
11054 "Decrease the date item at the cursor by one.
11055 If the cursor is on the year, change the year. If it is on the month or
11056 the day, change that.
11057 With prefix ARG, change by that many units."
11058 (interactive "p")
11059 (org-timestamp-change (- (prefix-numeric-value arg))))
11061 (defun org-timestamp-up-day (&optional arg)
11062 "Increase the date in the time stamp by one day.
11063 With prefix ARG, change that many days."
11064 (interactive "p")
11065 (if (and (not (org-at-timestamp-p t))
11066 (org-on-heading-p))
11067 (org-todo 'up)
11068 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11070 (defun org-timestamp-down-day (&optional arg)
11071 "Decrease the date in the time stamp by one day.
11072 With prefix ARG, change that many days."
11073 (interactive "p")
11074 (if (and (not (org-at-timestamp-p t))
11075 (org-on-heading-p))
11076 (org-todo 'down)
11077 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11079 (defun org-at-timestamp-p (&optional inactive-ok)
11080 "Determine if the cursor is in or at a timestamp."
11081 (interactive)
11082 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11083 (pos (point))
11084 (ans (or (looking-at tsr)
11085 (save-excursion
11086 (skip-chars-backward "^[<\n\r\t")
11087 (if (> (point) (point-min)) (backward-char 1))
11088 (and (looking-at tsr)
11089 (> (- (match-end 0) pos) -1))))))
11090 (and ans
11091 (boundp 'org-ts-what)
11092 (setq org-ts-what
11093 (cond
11094 ((= pos (match-beginning 0)) 'bracket)
11095 ((= pos (1- (match-end 0))) 'bracket)
11096 ((org-pos-in-match-range pos 2) 'year)
11097 ((org-pos-in-match-range pos 3) 'month)
11098 ((org-pos-in-match-range pos 7) 'hour)
11099 ((org-pos-in-match-range pos 8) 'minute)
11100 ((or (org-pos-in-match-range pos 4)
11101 (org-pos-in-match-range pos 5)) 'day)
11102 ((and (> pos (or (match-end 8) (match-end 5)))
11103 (< pos (match-end 0)))
11104 (- pos (or (match-end 8) (match-end 5))))
11105 (t 'day))))
11106 ans))
11108 (defun org-toggle-timestamp-type ()
11109 "Toggle the type (<active> or [inactive]) of a time stamp."
11110 (interactive)
11111 (when (org-at-timestamp-p t)
11112 (save-excursion
11113 (goto-char (match-beginning 0))
11114 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11115 (goto-char (1- (match-end 0)))
11116 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11117 (message "Timestamp is now %sactive"
11118 (if (equal (char-before) ?>) "in" ""))))
11120 (defun org-timestamp-change (n &optional what)
11121 "Change the date in the time stamp at point.
11122 The date will be changed by N times WHAT. WHAT can be `day', `month',
11123 `year', `minute', `second'. If WHAT is not given, the cursor position
11124 in the timestamp determines what will be changed."
11125 (let ((pos (point))
11126 with-hm inactive
11127 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11128 org-ts-what
11129 extra rem
11130 ts time time0)
11131 (if (not (org-at-timestamp-p t))
11132 (error "Not at a timestamp"))
11133 (if (and (not what) (eq org-ts-what 'bracket))
11134 (org-toggle-timestamp-type)
11135 (if (and (not what) (not (eq org-ts-what 'day))
11136 org-display-custom-times
11137 (get-text-property (point) 'display)
11138 (not (get-text-property (1- (point)) 'display)))
11139 (setq org-ts-what 'day))
11140 (setq org-ts-what (or what org-ts-what)
11141 inactive (= (char-after (match-beginning 0)) ?\[)
11142 ts (match-string 0))
11143 (replace-match "")
11144 (if (string-match
11145 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11147 (setq extra (match-string 1 ts)))
11148 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11149 (setq with-hm t))
11150 (setq time0 (org-parse-time-string ts))
11151 (when (and (eq org-ts-what 'minute)
11152 (eq current-prefix-arg nil))
11153 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11154 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11155 (setcar (cdr time0) (+ (nth 1 time0)
11156 (if (> n 0) (- rem) (- dm rem))))))
11157 (setq time
11158 (encode-time (or (car time0) 0)
11159 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11160 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11161 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11162 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11163 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11164 (nthcdr 6 time0)))
11165 (when (integerp org-ts-what)
11166 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11167 (if (eq what 'calendar)
11168 (let ((cal-date (org-get-date-from-calendar)))
11169 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11170 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11171 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11172 (setcar time0 (or (car time0) 0))
11173 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11174 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11175 (setq time (apply 'encode-time time0))))
11176 (setq org-last-changed-timestamp
11177 (org-insert-time-stamp time with-hm inactive nil nil extra))
11178 (org-clock-update-time-maybe)
11179 (goto-char pos)
11180 ;; Try to recenter the calendar window, if any
11181 (if (and org-calendar-follow-timestamp-change
11182 (get-buffer-window "*Calendar*" t)
11183 (memq org-ts-what '(day month year)))
11184 (org-recenter-calendar (time-to-days time))))))
11186 (defun org-modify-ts-extra (s pos n dm)
11187 "Change the different parts of the lead-time and repeat fields in timestamp."
11188 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11189 ng h m new rem)
11190 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11191 (cond
11192 ((or (org-pos-in-match-range pos 2)
11193 (org-pos-in-match-range pos 3))
11194 (setq m (string-to-number (match-string 3 s))
11195 h (string-to-number (match-string 2 s)))
11196 (if (org-pos-in-match-range pos 2)
11197 (setq h (+ h n))
11198 (setq n (* dm (org-no-warnings (signum n))))
11199 (when (not (= 0 (setq rem (% m dm))))
11200 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11201 (setq m (+ m n)))
11202 (if (< m 0) (setq m (+ m 60) h (1- h)))
11203 (if (> m 59) (setq m (- m 60) h (1+ h)))
11204 (setq h (min 24 (max 0 h)))
11205 (setq ng 1 new (format "-%02d:%02d" h m)))
11206 ((org-pos-in-match-range pos 6)
11207 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11208 ((org-pos-in-match-range pos 5)
11209 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11211 ((org-pos-in-match-range pos 9)
11212 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11213 ((org-pos-in-match-range pos 8)
11214 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11216 (when ng
11217 (setq s (concat
11218 (substring s 0 (match-beginning ng))
11220 (substring s (match-end ng))))))
11223 (defun org-recenter-calendar (date)
11224 "If the calendar is visible, recenter it to DATE."
11225 (let* ((win (selected-window))
11226 (cwin (get-buffer-window "*Calendar*" t))
11227 (calendar-move-hook nil))
11228 (when cwin
11229 (select-window cwin)
11230 (calendar-goto-date (if (listp date) date
11231 (calendar-gregorian-from-absolute date)))
11232 (select-window win))))
11234 (defun org-goto-calendar (&optional arg)
11235 "Go to the Emacs calendar at the current date.
11236 If there is a time stamp in the current line, go to that date.
11237 A prefix ARG can be used to force the current date."
11238 (interactive "P")
11239 (let ((tsr org-ts-regexp) diff
11240 (calendar-move-hook nil)
11241 (calendar-view-holidays-initially-flag nil)
11242 (view-calendar-holidays-initially nil)
11243 (calendar-view-diary-initially-flag nil)
11244 (view-diary-entries-initially nil))
11245 (if (or (org-at-timestamp-p)
11246 (save-excursion
11247 (beginning-of-line 1)
11248 (looking-at (concat ".*" tsr))))
11249 (let ((d1 (time-to-days (current-time)))
11250 (d2 (time-to-days
11251 (org-time-string-to-time (match-string 1)))))
11252 (setq diff (- d2 d1))))
11253 (calendar)
11254 (calendar-goto-today)
11255 (if (and diff (not arg)) (calendar-forward-day diff))))
11257 (defun org-get-date-from-calendar ()
11258 "Return a list (month day year) of date at point in calendar."
11259 (with-current-buffer "*Calendar*"
11260 (save-match-data
11261 (calendar-cursor-to-date))))
11263 (defun org-date-from-calendar ()
11264 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11265 If there is already a time stamp at the cursor position, update it."
11266 (interactive)
11267 (if (org-at-timestamp-p t)
11268 (org-timestamp-change 0 'calendar)
11269 (let ((cal-date (org-get-date-from-calendar)))
11270 (org-insert-time-stamp
11271 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11273 (defun org-minutes-to-hh:mm-string (m)
11274 "Compute H:MM from a number of minutes."
11275 (let ((h (/ m 60)))
11276 (setq m (- m (* 60 h)))
11277 (format "%d:%02d" h m)))
11279 (defun org-hh:mm-string-to-minutes (s)
11280 "Convert a string H:MM to a number of minutes."
11281 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11282 (+ (* (string-to-number (match-string 1 s)) 60)
11283 (string-to-number (match-string 2 s)))
11286 ;;;; Agenda files
11288 ;;;###autoload
11289 (defun org-iswitchb (&optional arg)
11290 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11291 With a prefix argument, restrict available to files.
11292 With two prefix arguments, restrict available buffers to agenda files.
11294 Due to some yet unresolved reason, global function
11295 `iswitchb-mode' needs to be active for this function to work."
11296 (interactive "P")
11297 (require 'iswitchb)
11298 (let ((enabled iswitchb-mode) blist)
11299 (or enabled (iswitchb-mode 1))
11300 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11301 ((equal arg '(16)) (org-buffer-list 'agenda))
11302 (t (org-buffer-list))))
11303 (unwind-protect
11304 (let ((iswitchb-make-buflist-hook
11305 (lambda ()
11306 (setq iswitchb-temp-buflist
11307 (mapcar 'buffer-name blist)))))
11308 (switch-to-buffer
11309 (iswitchb-read-buffer
11310 "Switch-to: " nil t))
11311 (or enabled (iswitchb-mode -1))))))
11313 (defun org-buffer-list (&optional predicate tmp)
11314 "Return a list of Org buffers.
11315 PREDICATE can be either 'export, 'files or 'agenda.
11317 'export restrict the list to Export buffers.
11318 'files restrict the list to buffers visiting Org files.
11319 'agenda restrict the list to buffers visiting agenda files.
11321 If TMP is non-nil, don't include temporary buffers."
11322 (let (filter blist)
11323 (setq filter
11324 (cond ((eq predicate 'files) "\.org$")
11325 ((eq predicate 'export) "\*Org .*Export")
11326 (t "\*Org \\|\.org$")))
11327 (setq blist
11328 (mapcar
11329 (lambda(b)
11330 (let ((bname (buffer-name b))
11331 (bfile (buffer-file-name b)))
11332 (if (and (string-match filter bname)
11333 (if (eq predicate 'agenda)
11334 (member bfile
11335 (mapcar (lambda(f) (file-truename f))
11336 org-agenda-files)) t)
11337 (if tmp (not (string-match "tmp" bname)) t)) b)))
11338 (buffer-list)))
11339 (delete nil blist)))
11341 (defun org-agenda-files (&optional unrestricted ext)
11342 "Get the list of agenda files.
11343 Optional UNRESTRICTED means return the full list even if a restriction
11344 is currently in place.
11345 When EXT is non-nil, try to add all files that are created by adding EXT
11346 to the file nemes. Basically, this is a way to add the archive files
11347 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11348 a string, \"_archive\" will be used."
11349 (let ((files
11350 (cond
11351 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11352 ((stringp org-agenda-files) (org-read-agenda-file-list))
11353 ((listp org-agenda-files) org-agenda-files)
11354 (t (error "Invalid value of `org-agenda-files'")))))
11355 (setq files (apply 'append
11356 (mapcar (lambda (f)
11357 (if (file-directory-p f)
11358 (directory-files
11359 f t org-agenda-file-regexp)
11360 (list f)))
11361 files)))
11362 (when org-agenda-skip-unavailable-files
11363 (setq files (delq nil
11364 (mapcar (function
11365 (lambda (file)
11366 (and (file-readable-p file) file)))
11367 files))))
11368 (when ext
11369 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11370 ext "_archive"))
11371 (setq files (apply 'append
11372 (mapcar
11373 (lambda (f)
11374 (if (file-exists-p (concat f ext))
11375 (list f (concat f ext))
11376 (list f)))
11377 files))))
11378 files))
11380 (defun org-edit-agenda-file-list ()
11381 "Edit the list of agenda files.
11382 Depending on setup, this either uses customize to edit the variable
11383 `org-agenda-files', or it visits the file that is holding the list. In the
11384 latter case, the buffer is set up in a way that saving it automatically kills
11385 the buffer and restores the previous window configuration."
11386 (interactive)
11387 (if (stringp org-agenda-files)
11388 (let ((cw (current-window-configuration)))
11389 (find-file org-agenda-files)
11390 (org-set-local 'org-window-configuration cw)
11391 (org-add-hook 'after-save-hook
11392 (lambda ()
11393 (set-window-configuration
11394 (prog1 org-window-configuration
11395 (kill-buffer (current-buffer))))
11396 (org-install-agenda-files-menu)
11397 (message "New agenda file list installed"))
11398 nil 'local)
11399 (message "%s" (substitute-command-keys
11400 "Edit list and finish with \\[save-buffer]")))
11401 (customize-variable 'org-agenda-files)))
11403 (defun org-store-new-agenda-file-list (list)
11404 "Set new value for the agenda file list and save it correcly."
11405 (if (stringp org-agenda-files)
11406 (let ((f org-agenda-files) b)
11407 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11408 (with-temp-file f
11409 (insert (mapconcat 'identity list "\n") "\n")))
11410 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11411 (setq org-agenda-files list)
11412 (customize-save-variable 'org-agenda-files org-agenda-files))))
11414 (defun org-read-agenda-file-list ()
11415 "Read the list of agenda files from a file."
11416 (when (file-directory-p org-agenda-files)
11417 (error "`org-agenda-files' cannot be a single directory"))
11418 (when (stringp org-agenda-files)
11419 (with-temp-buffer
11420 (insert-file-contents org-agenda-files)
11421 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11424 ;;;###autoload
11425 (defun org-cycle-agenda-files ()
11426 "Cycle through the files in `org-agenda-files'.
11427 If the current buffer visits an agenda file, find the next one in the list.
11428 If the current buffer does not, find the first agenda file."
11429 (interactive)
11430 (let* ((fs (org-agenda-files t))
11431 (files (append fs (list (car fs))))
11432 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11433 file)
11434 (unless files (error "No agenda files"))
11435 (catch 'exit
11436 (while (setq file (pop files))
11437 (if (equal (file-truename file) tcf)
11438 (when (car files)
11439 (find-file (car files))
11440 (throw 'exit t))))
11441 (find-file (car fs)))
11442 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11444 (defun org-agenda-file-to-front (&optional to-end)
11445 "Move/add the current file to the top of the agenda file list.
11446 If the file is not present in the list, it is added to the front. If it is
11447 present, it is moved there. With optional argument TO-END, add/move to the
11448 end of the list."
11449 (interactive "P")
11450 (let ((org-agenda-skip-unavailable-files nil)
11451 (file-alist (mapcar (lambda (x)
11452 (cons (file-truename x) x))
11453 (org-agenda-files t)))
11454 (ctf (file-truename buffer-file-name))
11455 x had)
11456 (setq x (assoc ctf file-alist) had x)
11458 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11459 (if to-end
11460 (setq file-alist (append (delq x file-alist) (list x)))
11461 (setq file-alist (cons x (delq x file-alist))))
11462 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11463 (org-install-agenda-files-menu)
11464 (message "File %s to %s of agenda file list"
11465 (if had "moved" "added") (if to-end "end" "front"))))
11467 (defun org-remove-file (&optional file)
11468 "Remove current file from the list of files in variable `org-agenda-files'.
11469 These are the files which are being checked for agenda entries.
11470 Optional argument FILE means, use this file instead of the current."
11471 (interactive)
11472 (let* ((org-agenda-skip-unavailable-files nil)
11473 (file (or file buffer-file-name))
11474 (true-file (file-truename file))
11475 (afile (abbreviate-file-name file))
11476 (files (delq nil (mapcar
11477 (lambda (x)
11478 (if (equal true-file
11479 (file-truename x))
11480 nil x))
11481 (org-agenda-files t)))))
11482 (if (not (= (length files) (length (org-agenda-files t))))
11483 (progn
11484 (org-store-new-agenda-file-list files)
11485 (org-install-agenda-files-menu)
11486 (message "Removed file: %s" afile))
11487 (message "File was not in list: %s (not removed)" afile))))
11489 (defun org-file-menu-entry (file)
11490 (vector file (list 'find-file file) t))
11492 (defun org-check-agenda-file (file)
11493 "Make sure FILE exists. If not, ask user what to do."
11494 (when (not (file-exists-p file))
11495 (message "non-existent file %s. [R]emove from list or [A]bort?"
11496 (abbreviate-file-name file))
11497 (let ((r (downcase (read-char-exclusive))))
11498 (cond
11499 ((equal r ?r)
11500 (org-remove-file file)
11501 (throw 'nextfile t))
11502 (t (error "Abort"))))))
11504 (defun org-get-agenda-file-buffer (file)
11505 "Get a buffer visiting FILE. If the buffer needs to be created, add
11506 it to the list of buffers which might be released later."
11507 (let ((buf (org-find-base-buffer-visiting file)))
11508 (if buf
11509 buf ; just return it
11510 ;; Make a new buffer and remember it
11511 (setq buf (find-file-noselect file))
11512 (if buf (push buf org-agenda-new-buffers))
11513 buf)))
11515 (defun org-release-buffers (blist)
11516 "Release all buffers in list, asking the user for confirmation when needed.
11517 When a buffer is unmodified, it is just killed. When modified, it is saved
11518 \(if the user agrees) and then killed."
11519 (let (buf file)
11520 (while (setq buf (pop blist))
11521 (setq file (buffer-file-name buf))
11522 (when (and (buffer-modified-p buf)
11523 file
11524 (y-or-n-p (format "Save file %s? " file)))
11525 (with-current-buffer buf (save-buffer)))
11526 (kill-buffer buf))))
11528 (defun org-prepare-agenda-buffers (files)
11529 "Create buffers for all agenda files, protect archived trees and comments."
11530 (interactive)
11531 (let ((pa '(:org-archived t))
11532 (pc '(:org-comment t))
11533 (pall '(:org-archived t :org-comment t))
11534 (inhibit-read-only t)
11535 (rea (concat ":" org-archive-tag ":"))
11536 bmp file re)
11537 (save-excursion
11538 (save-restriction
11539 (while (setq file (pop files))
11540 (if (bufferp file)
11541 (set-buffer file)
11542 (org-check-agenda-file file)
11543 (set-buffer (org-get-agenda-file-buffer file)))
11544 (widen)
11545 (setq bmp (buffer-modified-p))
11546 (org-refresh-category-properties)
11547 (setq org-todo-keywords-for-agenda
11548 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11549 (setq org-done-keywords-for-agenda
11550 (append org-done-keywords-for-agenda org-done-keywords))
11551 (save-excursion
11552 (remove-text-properties (point-min) (point-max) pall)
11553 (when org-agenda-skip-archived-trees
11554 (goto-char (point-min))
11555 (while (re-search-forward rea nil t)
11556 (if (org-on-heading-p t)
11557 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11558 (goto-char (point-min))
11559 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11560 (while (re-search-forward re nil t)
11561 (add-text-properties
11562 (match-beginning 0) (org-end-of-subtree t) pc)))
11563 (set-buffer-modified-p bmp))))))
11565 ;;;; Embedded LaTeX
11567 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11568 "Keymap for the minor `org-cdlatex-mode'.")
11570 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11571 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11572 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11573 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11574 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11576 (defvar org-cdlatex-texmathp-advice-is-done nil
11577 "Flag remembering if we have applied the advice to texmathp already.")
11579 (define-minor-mode org-cdlatex-mode
11580 "Toggle the minor `org-cdlatex-mode'.
11581 This mode supports entering LaTeX environment and math in LaTeX fragments
11582 in Org-mode.
11583 \\{org-cdlatex-mode-map}"
11584 nil " OCDL" nil
11585 (when org-cdlatex-mode (require 'cdlatex))
11586 (unless org-cdlatex-texmathp-advice-is-done
11587 (setq org-cdlatex-texmathp-advice-is-done t)
11588 (defadvice texmathp (around org-math-always-on activate)
11589 "Always return t in org-mode buffers.
11590 This is because we want to insert math symbols without dollars even outside
11591 the LaTeX math segments. If Orgmode thinks that point is actually inside
11592 en embedded LaTeX fragement, let texmathp do its job.
11593 \\[org-cdlatex-mode-map]"
11594 (interactive)
11595 (let (p)
11596 (cond
11597 ((not (org-mode-p)) ad-do-it)
11598 ((eq this-command 'cdlatex-math-symbol)
11599 (setq ad-return-value t
11600 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11602 (let ((p (org-inside-LaTeX-fragment-p)))
11603 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11604 (setq ad-return-value t
11605 texmathp-why '("Org-mode embedded math" . 0))
11606 (if p ad-do-it)))))))))
11608 (defun turn-on-org-cdlatex ()
11609 "Unconditionally turn on `org-cdlatex-mode'."
11610 (org-cdlatex-mode 1))
11612 (defun org-inside-LaTeX-fragment-p ()
11613 "Test if point is inside a LaTeX fragment.
11614 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11615 sequence appearing also before point.
11616 Even though the matchers for math are configurable, this function assumes
11617 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11618 delimiters are skipped when they have been removed by customization.
11619 The return value is nil, or a cons cell with the delimiter and
11620 and the position of this delimiter.
11622 This function does a reasonably good job, but can locally be fooled by
11623 for example currency specifications. For example it will assume being in
11624 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11625 fragments that are properly closed, but during editing, we have to live
11626 with the uncertainty caused by missing closing delimiters. This function
11627 looks only before point, not after."
11628 (catch 'exit
11629 (let ((pos (point))
11630 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11631 (lim (progn
11632 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11633 (point)))
11634 dd-on str (start 0) m re)
11635 (goto-char pos)
11636 (when dodollar
11637 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11638 re (nth 1 (assoc "$" org-latex-regexps)))
11639 (while (string-match re str start)
11640 (cond
11641 ((= (match-end 0) (length str))
11642 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11643 ((= (match-end 0) (- (length str) 5))
11644 (throw 'exit nil))
11645 (t (setq start (match-end 0))))))
11646 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11647 (goto-char pos)
11648 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11649 (and (match-beginning 2) (throw 'exit nil))
11650 ;; count $$
11651 (while (re-search-backward "\\$\\$" lim t)
11652 (setq dd-on (not dd-on)))
11653 (goto-char pos)
11654 (if dd-on (cons "$$" m))))))
11657 (defun org-try-cdlatex-tab ()
11658 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11659 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11660 - inside a LaTeX fragment, or
11661 - after the first word in a line, where an abbreviation expansion could
11662 insert a LaTeX environment."
11663 (when org-cdlatex-mode
11664 (cond
11665 ((save-excursion
11666 (skip-chars-backward "a-zA-Z0-9*")
11667 (skip-chars-backward " \t")
11668 (bolp))
11669 (cdlatex-tab) t)
11670 ((org-inside-LaTeX-fragment-p)
11671 (cdlatex-tab) t)
11672 (t nil))))
11674 (defun org-cdlatex-underscore-caret (&optional arg)
11675 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11676 Revert to the normal definition outside of these fragments."
11677 (interactive "P")
11678 (if (org-inside-LaTeX-fragment-p)
11679 (call-interactively 'cdlatex-sub-superscript)
11680 (let (org-cdlatex-mode)
11681 (call-interactively (key-binding (vector last-input-event))))))
11683 (defun org-cdlatex-math-modify (&optional arg)
11684 "Execute `cdlatex-math-modify' in LaTeX fragments.
11685 Revert to the normal definition outside of these fragments."
11686 (interactive "P")
11687 (if (org-inside-LaTeX-fragment-p)
11688 (call-interactively 'cdlatex-math-modify)
11689 (let (org-cdlatex-mode)
11690 (call-interactively (key-binding (vector last-input-event))))))
11692 (defvar org-latex-fragment-image-overlays nil
11693 "List of overlays carrying the images of latex fragments.")
11694 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11696 (defun org-remove-latex-fragment-image-overlays ()
11697 "Remove all overlays with LaTeX fragment images in current buffer."
11698 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11699 (setq org-latex-fragment-image-overlays nil))
11701 (defun org-preview-latex-fragment (&optional subtree)
11702 "Preview the LaTeX fragment at point, or all locally or globally.
11703 If the cursor is in a LaTeX fragment, create the image and overlay
11704 it over the source code. If there is no fragment at point, display
11705 all fragments in the current text, from one headline to the next. With
11706 prefix SUBTREE, display all fragments in the current subtree. With a
11707 double prefix `C-u C-u', or when the cursor is before the first headline,
11708 display all fragments in the buffer.
11709 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11710 (interactive "P")
11711 (org-remove-latex-fragment-image-overlays)
11712 (save-excursion
11713 (save-restriction
11714 (let (beg end at msg)
11715 (cond
11716 ((or (equal subtree '(16))
11717 (not (save-excursion
11718 (re-search-backward (concat "^" outline-regexp) nil t))))
11719 (setq beg (point-min) end (point-max)
11720 msg "Creating images for buffer...%s"))
11721 ((equal subtree '(4))
11722 (org-back-to-heading)
11723 (setq beg (point) end (org-end-of-subtree t)
11724 msg "Creating images for subtree...%s"))
11726 (if (setq at (org-inside-LaTeX-fragment-p))
11727 (goto-char (max (point-min) (- (cdr at) 2)))
11728 (org-back-to-heading))
11729 (setq beg (point) end (progn (outline-next-heading) (point))
11730 msg (if at "Creating image...%s"
11731 "Creating images for entry...%s"))))
11732 (message msg "")
11733 (narrow-to-region beg end)
11734 (goto-char beg)
11735 (org-format-latex
11736 (concat "ltxpng/" (file-name-sans-extension
11737 (file-name-nondirectory
11738 buffer-file-name)))
11739 default-directory 'overlays msg at 'forbuffer)
11740 (message msg "done. Use `C-c C-c' to remove images.")))))
11742 (defvar org-latex-regexps
11743 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11744 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11745 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11746 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11747 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11748 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11749 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11750 "Regular expressions for matching embedded LaTeX.")
11752 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11753 "Replace LaTeX fragments with links to an image, and produce images."
11754 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11755 (let* ((prefixnodir (file-name-nondirectory prefix))
11756 (absprefix (expand-file-name prefix dir))
11757 (todir (file-name-directory absprefix))
11758 (opt org-format-latex-options)
11759 (matchers (plist-get opt :matchers))
11760 (re-list org-latex-regexps)
11761 (cnt 0) txt link beg end re e checkdir
11762 m n block linkfile movefile ov)
11763 ;; Check if there are old images files with this prefix, and remove them
11764 (when (file-directory-p todir)
11765 (mapc 'delete-file
11766 (directory-files
11767 todir 'full
11768 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11769 ;; Check the different regular expressions
11770 (while (setq e (pop re-list))
11771 (setq m (car e) re (nth 1 e) n (nth 2 e)
11772 block (if (nth 3 e) "\n\n" ""))
11773 (when (member m matchers)
11774 (goto-char (point-min))
11775 (while (re-search-forward re nil t)
11776 (when (or (not at) (equal (cdr at) (match-beginning n)))
11777 (setq txt (match-string n)
11778 beg (match-beginning n) end (match-end n)
11779 cnt (1+ cnt)
11780 linkfile (format "%s_%04d.png" prefix cnt)
11781 movefile (format "%s_%04d.png" absprefix cnt)
11782 link (concat block "[[file:" linkfile "]]" block))
11783 (if msg (message msg cnt))
11784 (goto-char beg)
11785 (unless checkdir ; make sure the directory exists
11786 (setq checkdir t)
11787 (or (file-directory-p todir) (make-directory todir)))
11788 (org-create-formula-image
11789 txt movefile opt forbuffer)
11790 (if overlays
11791 (progn
11792 (setq ov (org-make-overlay beg end))
11793 (if (featurep 'xemacs)
11794 (progn
11795 (org-overlay-put ov 'invisible t)
11796 (org-overlay-put
11797 ov 'end-glyph
11798 (make-glyph (vector 'png :file movefile))))
11799 (org-overlay-put
11800 ov 'display
11801 (list 'image :type 'png :file movefile :ascent 'center)))
11802 (push ov org-latex-fragment-image-overlays)
11803 (goto-char end))
11804 (delete-region beg end)
11805 (insert link))))))))
11807 ;; This function borrows from Ganesh Swami's latex2png.el
11808 (defun org-create-formula-image (string tofile options buffer)
11809 (let* ((tmpdir (if (featurep 'xemacs)
11810 (temp-directory)
11811 temporary-file-directory))
11812 (texfilebase (make-temp-name
11813 (expand-file-name "orgtex" tmpdir)))
11814 (texfile (concat texfilebase ".tex"))
11815 (dvifile (concat texfilebase ".dvi"))
11816 (pngfile (concat texfilebase ".png"))
11817 (fnh (if (featurep 'xemacs)
11818 (font-height (get-face-font 'default))
11819 (face-attribute 'default :height nil)))
11820 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11821 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11822 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11823 "Black"))
11824 (bg (or (plist-get options (if buffer :background :html-background))
11825 "Transparent")))
11826 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11827 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11828 (with-temp-file texfile
11829 (insert org-format-latex-header
11830 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11831 (let ((dir default-directory))
11832 (condition-case nil
11833 (progn
11834 (cd tmpdir)
11835 (call-process "latex" nil nil nil texfile))
11836 (error nil))
11837 (cd dir))
11838 (if (not (file-exists-p dvifile))
11839 (progn (message "Failed to create dvi file from %s" texfile) nil)
11840 (call-process "dvipng" nil nil nil
11841 "-E" "-fg" fg "-bg" bg
11842 "-D" dpi
11843 ;;"-x" scale "-y" scale
11844 "-T" "tight"
11845 "-o" pngfile
11846 dvifile)
11847 (if (not (file-exists-p pngfile))
11848 (progn (message "Failed to create png file from %s" texfile) nil)
11849 ;; Use the requested file name and clean up
11850 (copy-file pngfile tofile 'replace)
11851 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11852 (delete-file (concat texfilebase e)))
11853 pngfile))))
11855 (defun org-dvipng-color (attr)
11856 "Return an rgb color specification for dvipng."
11857 (apply 'format "rgb %s %s %s"
11858 (mapcar 'org-normalize-color
11859 (color-values (face-attribute 'default attr nil)))))
11861 (defun org-normalize-color (value)
11862 "Return string to be used as color value for an RGB component."
11863 (format "%g" (/ value 65535.0)))
11866 ;;;; Key bindings
11868 ;; Make `C-c C-x' a prefix key
11869 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11871 ;; TAB key with modifiers
11872 (org-defkey org-mode-map "\C-i" 'org-cycle)
11873 (org-defkey org-mode-map [(tab)] 'org-cycle)
11874 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11875 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11876 (org-defkey org-mode-map "\M-\t" 'org-complete)
11877 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11878 ;; The following line is necessary under Suse GNU/Linux
11879 (unless (featurep 'xemacs)
11880 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11881 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11882 (define-key org-mode-map [backtab] 'org-shifttab)
11884 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11885 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11886 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11888 ;; Cursor keys with modifiers
11889 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11890 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11891 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11892 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11894 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11895 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11896 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11897 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11899 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11900 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11901 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11902 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11904 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11905 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11907 ;;; Extra keys for tty access.
11908 ;; We only set them when really needed because otherwise the
11909 ;; menus don't show the simple keys
11911 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11912 (not window-system))
11913 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11914 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11915 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11916 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11917 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11918 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11919 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11920 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11921 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11922 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11923 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11924 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11925 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11926 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11927 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11928 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11929 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11930 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11931 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11932 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11933 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11934 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11936 ;; All the other keys
11938 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11939 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11940 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11941 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11942 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11943 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11944 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11945 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11946 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11947 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11948 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11949 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11950 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11951 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11952 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11953 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11954 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11955 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11956 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11957 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11958 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11959 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11960 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11961 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11962 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11963 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11964 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11965 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11966 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11967 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11968 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11969 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11970 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11971 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11972 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11973 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11974 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11975 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11976 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11977 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11978 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11979 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11980 (org-defkey org-mode-map "\C-c^" 'org-sort)
11981 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11982 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11983 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11984 (org-defkey org-mode-map "\C-m" 'org-return)
11985 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11986 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11987 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11988 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11989 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11990 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11991 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11992 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11993 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11994 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11995 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11996 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11997 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11998 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11999 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12000 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12002 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12003 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12004 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12005 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12007 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12008 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12009 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12010 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12011 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12012 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12013 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12014 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12015 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12016 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12017 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12018 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12020 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12022 (when (featurep 'xemacs)
12023 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12025 (defvar org-table-auto-blank-field) ; defined in org-table.el
12026 (defun org-self-insert-command (N)
12027 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12028 If the cursor is in a table looking at whitespace, the whitespace is
12029 overwritten, and the table is not marked as requiring realignment."
12030 (interactive "p")
12031 (if (and (org-table-p)
12032 (progn
12033 ;; check if we blank the field, and if that triggers align
12034 (and (featurep 'org-table) org-table-auto-blank-field
12035 (member last-command
12036 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12037 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12038 ;; got extra space, this field does not determine column width
12039 (let (org-table-may-need-update) (org-table-blank-field))
12040 ;; no extra space, this field may determine column width
12041 (org-table-blank-field)))
12043 (eq N 1)
12044 (looking-at "[^|\n]* |"))
12045 (let (org-table-may-need-update)
12046 (goto-char (1- (match-end 0)))
12047 (delete-backward-char 1)
12048 (goto-char (match-beginning 0))
12049 (self-insert-command N))
12050 (setq org-table-may-need-update t)
12051 (self-insert-command N)
12052 (org-fix-tags-on-the-fly)))
12054 (defun org-fix-tags-on-the-fly ()
12055 (when (and (equal (char-after (point-at-bol)) ?*)
12056 (org-on-heading-p))
12057 (org-align-tags-here org-tags-column)))
12059 (defun org-delete-backward-char (N)
12060 "Like `delete-backward-char', insert whitespace at field end in tables.
12061 When deleting backwards, in tables this function will insert whitespace in
12062 front of the next \"|\" separator, to keep the table aligned. The table will
12063 still be marked for re-alignment if the field did fill the entire column,
12064 because, in this case the deletion might narrow the column."
12065 (interactive "p")
12066 (if (and (org-table-p)
12067 (eq N 1)
12068 (string-match "|" (buffer-substring (point-at-bol) (point)))
12069 (looking-at ".*?|"))
12070 (let ((pos (point))
12071 (noalign (looking-at "[^|\n\r]* |"))
12072 (c org-table-may-need-update))
12073 (backward-delete-char N)
12074 (skip-chars-forward "^|")
12075 (insert " ")
12076 (goto-char (1- pos))
12077 ;; noalign: if there were two spaces at the end, this field
12078 ;; does not determine the width of the column.
12079 (if noalign (setq org-table-may-need-update c)))
12080 (backward-delete-char N)
12081 (org-fix-tags-on-the-fly)))
12083 (defun org-delete-char (N)
12084 "Like `delete-char', but insert whitespace at field end in tables.
12085 When deleting characters, in tables this function will insert whitespace in
12086 front of the next \"|\" separator, to keep the table aligned. The table will
12087 still be marked for re-alignment if the field did fill the entire column,
12088 because, in this case the deletion might narrow the column."
12089 (interactive "p")
12090 (if (and (org-table-p)
12091 (not (bolp))
12092 (not (= (char-after) ?|))
12093 (eq N 1))
12094 (if (looking-at ".*?|")
12095 (let ((pos (point))
12096 (noalign (looking-at "[^|\n\r]* |"))
12097 (c org-table-may-need-update))
12098 (replace-match (concat
12099 (substring (match-string 0) 1 -1)
12100 " |"))
12101 (goto-char pos)
12102 ;; noalign: if there were two spaces at the end, this field
12103 ;; does not determine the width of the column.
12104 (if noalign (setq org-table-may-need-update c)))
12105 (delete-char N))
12106 (delete-char N)
12107 (org-fix-tags-on-the-fly)))
12109 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12110 (put 'org-self-insert-command 'delete-selection t)
12111 (put 'orgtbl-self-insert-command 'delete-selection t)
12112 (put 'org-delete-char 'delete-selection 'supersede)
12113 (put 'org-delete-backward-char 'delete-selection 'supersede)
12115 ;; Make `flyspell-mode' delay after some commands
12116 (put 'org-self-insert-command 'flyspell-delayed t)
12117 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12118 (put 'org-delete-char 'flyspell-delayed t)
12119 (put 'org-delete-backward-char 'flyspell-delayed t)
12121 ;; Make pabbrev-mode expand after org-mode commands
12122 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12123 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12125 ;; How to do this: Measure non-white length of current string
12126 ;; If equal to column width, we should realign.
12128 (defun org-remap (map &rest commands)
12129 "In MAP, remap the functions given in COMMANDS.
12130 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12131 (let (new old)
12132 (while commands
12133 (setq old (pop commands) new (pop commands))
12134 (if (fboundp 'command-remapping)
12135 (org-defkey map (vector 'remap old) new)
12136 (substitute-key-definition old new map global-map)))))
12138 (when (eq org-enable-table-editor 'optimized)
12139 ;; If the user wants maximum table support, we need to hijack
12140 ;; some standard editing functions
12141 (org-remap org-mode-map
12142 'self-insert-command 'org-self-insert-command
12143 'delete-char 'org-delete-char
12144 'delete-backward-char 'org-delete-backward-char)
12145 (org-defkey org-mode-map "|" 'org-force-self-insert))
12147 (defun org-shiftcursor-error ()
12148 "Throw an error because Shift-Cursor command was applied in wrong context."
12149 (error "This command is active in special context like tables, headlines or timestamps"))
12151 (defun org-shifttab (&optional arg)
12152 "Global visibility cycling or move to previous table field.
12153 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12154 on context.
12155 See the individual commands for more information."
12156 (interactive "P")
12157 (cond
12158 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12159 ((integerp arg)
12160 (message "Content view to level: " arg)
12161 (org-content (prefix-numeric-value arg))
12162 (setq org-cycle-global-status 'overview))
12163 (t (call-interactively 'org-global-cycle))))
12165 (defun org-shiftmetaleft ()
12166 "Promote subtree or delete table column.
12167 Calls `org-promote-subtree', `org-outdent-item',
12168 or `org-table-delete-column', depending on context.
12169 See the individual commands for more information."
12170 (interactive)
12171 (cond
12172 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12173 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12174 ((org-at-item-p) (call-interactively 'org-outdent-item))
12175 (t (org-shiftcursor-error))))
12177 (defun org-shiftmetaright ()
12178 "Demote subtree or insert table column.
12179 Calls `org-demote-subtree', `org-indent-item',
12180 or `org-table-insert-column', depending on context.
12181 See the individual commands for more information."
12182 (interactive)
12183 (cond
12184 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12185 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12186 ((org-at-item-p) (call-interactively 'org-indent-item))
12187 (t (org-shiftcursor-error))))
12189 (defun org-shiftmetaup (&optional arg)
12190 "Move subtree up or kill table row.
12191 Calls `org-move-subtree-up' or `org-table-kill-row' or
12192 `org-move-item-up' depending on context. See the individual commands
12193 for more information."
12194 (interactive "P")
12195 (cond
12196 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12197 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12198 ((org-at-item-p) (call-interactively 'org-move-item-up))
12199 (t (org-shiftcursor-error))))
12200 (defun org-shiftmetadown (&optional arg)
12201 "Move subtree down or insert table row.
12202 Calls `org-move-subtree-down' or `org-table-insert-row' or
12203 `org-move-item-down', depending on context. See the individual
12204 commands for more information."
12205 (interactive "P")
12206 (cond
12207 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12208 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12209 ((org-at-item-p) (call-interactively 'org-move-item-down))
12210 (t (org-shiftcursor-error))))
12212 (defun org-metaleft (&optional arg)
12213 "Promote heading or move table column to left.
12214 Calls `org-do-promote' or `org-table-move-column', depending on context.
12215 With no specific context, calls the Emacs default `backward-word'.
12216 See the individual commands for more information."
12217 (interactive "P")
12218 (cond
12219 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12220 ((or (org-on-heading-p) (org-region-active-p))
12221 (call-interactively 'org-do-promote))
12222 ((org-at-item-p) (call-interactively 'org-outdent-item))
12223 (t (call-interactively 'backward-word))))
12225 (defun org-metaright (&optional arg)
12226 "Demote subtree or move table column to right.
12227 Calls `org-do-demote' or `org-table-move-column', depending on context.
12228 With no specific context, calls the Emacs default `forward-word'.
12229 See the individual commands for more information."
12230 (interactive "P")
12231 (cond
12232 ((org-at-table-p) (call-interactively 'org-table-move-column))
12233 ((or (org-on-heading-p) (org-region-active-p))
12234 (call-interactively 'org-do-demote))
12235 ((org-at-item-p) (call-interactively 'org-indent-item))
12236 (t (call-interactively 'forward-word))))
12238 (defun org-metaup (&optional arg)
12239 "Move subtree up or move table row up.
12240 Calls `org-move-subtree-up' or `org-table-move-row' or
12241 `org-move-item-up', depending on context. See the individual commands
12242 for more information."
12243 (interactive "P")
12244 (cond
12245 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12246 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12247 ((org-at-item-p) (call-interactively 'org-move-item-up))
12248 (t (transpose-lines 1) (beginning-of-line -1))))
12250 (defun org-metadown (&optional arg)
12251 "Move subtree down or move table row down.
12252 Calls `org-move-subtree-down' or `org-table-move-row' or
12253 `org-move-item-down', depending on context. See the individual
12254 commands for more information."
12255 (interactive "P")
12256 (cond
12257 ((org-at-table-p) (call-interactively 'org-table-move-row))
12258 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12259 ((org-at-item-p) (call-interactively 'org-move-item-down))
12260 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12262 (defun org-shiftup (&optional arg)
12263 "Increase item in timestamp or increase priority of current headline.
12264 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12265 depending on context. See the individual commands for more information."
12266 (interactive "P")
12267 (cond
12268 ((org-at-timestamp-p t)
12269 (call-interactively (if org-edit-timestamp-down-means-later
12270 'org-timestamp-down 'org-timestamp-up)))
12271 ((org-on-heading-p) (call-interactively 'org-priority-up))
12272 ((org-at-item-p) (call-interactively 'org-previous-item))
12273 ((org-clocktable-try-shift 'up arg))
12274 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12276 (defun org-shiftdown (&optional arg)
12277 "Decrease item in timestamp or decrease priority of current headline.
12278 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12279 depending on context. See the individual commands for more information."
12280 (interactive "P")
12281 (cond
12282 ((org-at-timestamp-p t)
12283 (call-interactively (if org-edit-timestamp-down-means-later
12284 'org-timestamp-up 'org-timestamp-down)))
12285 ((org-on-heading-p) (call-interactively 'org-priority-down))
12286 ((org-clocktable-try-shift 'down arg))
12287 (t (call-interactively 'org-next-item))))
12289 (defun org-shiftright (&optional arg)
12290 "Next TODO keyword or timestamp one day later, depending on context."
12291 (interactive "P")
12292 (cond
12293 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12294 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12295 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12296 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12297 ((org-clocktable-try-shift 'right arg))
12298 (t (org-shiftcursor-error))))
12300 (defun org-shiftleft (&optional arg)
12301 "Previous TODO keyword or timestamp one day earlier, depending on context."
12302 (interactive "P")
12303 (cond
12304 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12305 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12306 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12307 ((org-at-property-p)
12308 (call-interactively 'org-property-previous-allowed-value))
12309 ((org-clocktable-try-shift 'left arg))
12310 (t (org-shiftcursor-error))))
12312 (defun org-shiftcontrolright ()
12313 "Switch to next TODO set."
12314 (interactive)
12315 (cond
12316 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12317 (t (org-shiftcursor-error))))
12319 (defun org-shiftcontrolleft ()
12320 "Switch to previous TODO set."
12321 (interactive)
12322 (cond
12323 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12324 (t (org-shiftcursor-error))))
12326 (defun org-ctrl-c-ret ()
12327 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12328 (interactive)
12329 (cond
12330 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12331 (t (call-interactively 'org-insert-heading))))
12333 (defun org-copy-special ()
12334 "Copy region in table or copy current subtree.
12335 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12336 See the individual commands for more information."
12337 (interactive)
12338 (call-interactively
12339 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12341 (defun org-cut-special ()
12342 "Cut region in table or cut current subtree.
12343 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12344 See the individual commands for more information."
12345 (interactive)
12346 (call-interactively
12347 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12349 (defun org-paste-special (arg)
12350 "Paste rectangular region into table, or past subtree relative to level.
12351 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12352 See the individual commands for more information."
12353 (interactive "P")
12354 (if (org-at-table-p)
12355 (org-table-paste-rectangle)
12356 (org-paste-subtree arg)))
12358 (defun org-ctrl-c-ctrl-c (&optional arg)
12359 "Set tags in headline, or update according to changed information at point.
12361 This command does many different things, depending on context:
12363 - If the cursor is in a headline, prompt for tags and insert them
12364 into the current line, aligned to `org-tags-column'. When called
12365 with prefix arg, realign all tags in the current buffer.
12367 - If the cursor is in one of the special #+KEYWORD lines, this
12368 triggers scanning the buffer for these lines and updating the
12369 information.
12371 - If the cursor is inside a table, realign the table. This command
12372 works even if the automatic table editor has been turned off.
12374 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12375 the entire table.
12377 - If the cursor is a the beginning of a dynamic block, update it.
12379 - If the cursor is inside a table created by the table.el package,
12380 activate that table.
12382 - If the current buffer is a remember buffer, close note and file it.
12383 with a prefix argument, file it without further interaction to the default
12384 location.
12386 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12387 links in this buffer.
12389 - If the cursor is on a numbered item in a plain list, renumber the
12390 ordered list.
12392 - If the cursor is on a checkbox, toggle it."
12393 (interactive "P")
12394 (let ((org-enable-table-editor t))
12395 (cond
12396 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12397 org-occur-highlights
12398 org-latex-fragment-image-overlays)
12399 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12400 (org-remove-occur-highlights)
12401 (org-remove-latex-fragment-image-overlays)
12402 (message "Temporary highlights/overlays removed from current buffer"))
12403 ((and (local-variable-p 'org-finish-function (current-buffer))
12404 (fboundp org-finish-function))
12405 (funcall org-finish-function))
12406 ((org-at-property-p)
12407 (call-interactively 'org-property-action))
12408 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12409 ((org-on-heading-p) (call-interactively 'org-set-tags))
12410 ((org-at-table.el-p)
12411 (require 'table)
12412 (beginning-of-line 1)
12413 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12414 (call-interactively 'table-recognize-table))
12415 ((org-at-table-p)
12416 (org-table-maybe-eval-formula)
12417 (if arg
12418 (call-interactively 'org-table-recalculate)
12419 (org-table-maybe-recalculate-line))
12420 (call-interactively 'org-table-align))
12421 ((org-at-item-checkbox-p)
12422 (call-interactively 'org-toggle-checkbox))
12423 ((org-at-item-p)
12424 (call-interactively 'org-maybe-renumber-ordered-list))
12425 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12426 ;; Dynamic block
12427 (beginning-of-line 1)
12428 (org-update-dblock))
12429 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12430 (cond
12431 ((equal (match-string 1) "TBLFM")
12432 ;; Recalculate the table before this line
12433 (save-excursion
12434 (beginning-of-line 1)
12435 (skip-chars-backward " \r\n\t")
12436 (if (org-at-table-p)
12437 (org-call-with-arg 'org-table-recalculate t))))
12439 (org-set-regexps-and-options)
12440 (org-restart-font-lock)
12441 (message "Local setup has been refreshed"))))
12442 (t (error "C-c C-c can do nothing useful at this location.")))))
12444 (defun org-mode-restart ()
12445 "Restart Org-mode, to scan again for special lines.
12446 Also updates the keyword regular expressions."
12447 (interactive)
12448 (org-mode)
12449 (message "Org-mode restarted"))
12451 (defun org-kill-note-or-show-branches ()
12452 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12453 (interactive)
12454 (if (not org-finish-function)
12455 (call-interactively 'show-branches)
12456 (let ((org-note-abort t))
12457 (funcall org-finish-function))))
12459 (defun org-return (&optional indent)
12460 "Goto next table row or insert a newline.
12461 Calls `org-table-next-row' or `newline', depending on context.
12462 See the individual commands for more information."
12463 (interactive)
12464 (cond
12465 ((bobp) (if indent (newline-and-indent) (newline)))
12466 ((and (org-at-heading-p)
12467 (looking-at
12468 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12469 (org-show-entry)
12470 (end-of-line 1)
12471 (newline))
12472 ((org-at-table-p)
12473 (org-table-justify-field-maybe)
12474 (call-interactively 'org-table-next-row))
12475 (t (if indent (newline-and-indent) (newline)))))
12477 (defun org-return-indent ()
12478 "Goto next table row or insert a newline and indent.
12479 Calls `org-table-next-row' or `newline-and-indent', depending on
12480 context. See the individual commands for more information."
12481 (interactive)
12482 (org-return t))
12484 (defun org-ctrl-c-star ()
12485 "Compute table, or change heading status of lines.
12486 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12487 depending on context. This will also turn a plain list item or a normal
12488 line into a subheading."
12489 (interactive)
12490 (cond
12491 ((org-at-table-p)
12492 (call-interactively 'org-table-recalculate))
12493 ((org-region-active-p)
12494 ;; Convert all lines in region to list items
12495 (call-interactively 'org-toggle-region-headings))
12496 ((org-on-heading-p)
12497 (org-toggle-region-headings (point-at-bol)
12498 (min (1+ (point-at-eol)) (point-max))))
12499 ((org-at-item-p)
12500 ;; Convert to heading
12501 (let ((level (save-match-data
12502 (save-excursion
12503 (condition-case nil
12504 (progn
12505 (org-back-to-heading t)
12506 (funcall outline-level))
12507 (error 0))))))
12508 (replace-match
12509 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12510 (t (org-toggle-region-headings (point-at-bol)
12511 (min (1+ (point-at-eol)) (point-max))))))
12513 (defun org-ctrl-c-minus ()
12514 "Insert separator line in table or modify bullet status of line.
12515 Also turns a plain line or a region of lines into list items.
12516 Calls `org-table-insert-hline', `org-toggle-region-items', or
12517 `org-cycle-list-bullet', depending on context."
12518 (interactive)
12519 (cond
12520 ((org-at-table-p)
12521 (call-interactively 'org-table-insert-hline))
12522 ((org-on-heading-p)
12523 ;; Convert to item
12524 (save-excursion
12525 (beginning-of-line 1)
12526 (if (looking-at "\\*+ ")
12527 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12528 ((org-region-active-p)
12529 ;; Convert all lines in region to list items
12530 (call-interactively 'org-toggle-region-items))
12531 ((org-in-item-p)
12532 (call-interactively 'org-cycle-list-bullet))
12533 (t (org-toggle-region-items (point-at-bol)
12534 (min (1+ (point-at-eol)) (point-max))))))
12536 (defun org-toggle-region-items (beg end)
12537 "Convert all lines in region to list items.
12538 If the first line is already an item, convert all list items in the region
12539 to normal lines."
12540 (interactive "r")
12541 (let (l2 l)
12542 (save-excursion
12543 (goto-char end)
12544 (setq l2 (org-current-line))
12545 (goto-char beg)
12546 (beginning-of-line 1)
12547 (setq l (1- (org-current-line)))
12548 (if (org-at-item-p)
12549 ;; We already have items, de-itemize
12550 (while (< (setq l (1+ l)) l2)
12551 (when (org-at-item-p)
12552 (goto-char (match-beginning 2))
12553 (delete-region (match-beginning 2) (match-end 2))
12554 (and (looking-at "[ \t]+") (replace-match "")))
12555 (beginning-of-line 2))
12556 (while (< (setq l (1+ l)) l2)
12557 (unless (org-at-item-p)
12558 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12559 (replace-match "\\1- \\2")))
12560 (beginning-of-line 2))))))
12562 (defun org-toggle-region-headings (beg end)
12563 "Convert all lines in region to list items.
12564 If the first line is already an item, convert all list items in the region
12565 to normal lines."
12566 (interactive "r")
12567 (let (l2 l)
12568 (save-excursion
12569 (goto-char end)
12570 (setq l2 (org-current-line))
12571 (goto-char beg)
12572 (beginning-of-line 1)
12573 (setq l (1- (org-current-line)))
12574 (if (org-on-heading-p)
12575 ;; We already have headlines, de-star them
12576 (while (< (setq l (1+ l)) l2)
12577 (when (org-on-heading-p t)
12578 (and (looking-at outline-regexp) (replace-match "")))
12579 (beginning-of-line 2))
12580 (let* ((stars (save-excursion
12581 (re-search-backward org-complex-heading-regexp nil t)
12582 (or (match-string 1) "*")))
12583 (add-stars (if org-odd-levels-only "**" "*"))
12584 (rpl (concat stars add-stars " \\2")))
12585 (while (< (setq l (1+ l)) l2)
12586 (unless (org-on-heading-p)
12587 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12588 (replace-match rpl)))
12589 (beginning-of-line 2)))))))
12591 (defun org-meta-return (&optional arg)
12592 "Insert a new heading or wrap a region in a table.
12593 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12594 See the individual commands for more information."
12595 (interactive "P")
12596 (cond
12597 ((org-at-table-p)
12598 (call-interactively 'org-table-wrap-region))
12599 (t (call-interactively 'org-insert-heading))))
12601 ;;; Menu entries
12603 ;; Define the Org-mode menus
12604 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12605 '("Tbl"
12606 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12607 ["Next Field" org-cycle (org-at-table-p)]
12608 ["Previous Field" org-shifttab (org-at-table-p)]
12609 ["Next Row" org-return (org-at-table-p)]
12610 "--"
12611 ["Blank Field" org-table-blank-field (org-at-table-p)]
12612 ["Edit Field" org-table-edit-field (org-at-table-p)]
12613 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12614 "--"
12615 ("Column"
12616 ["Move Column Left" org-metaleft (org-at-table-p)]
12617 ["Move Column Right" org-metaright (org-at-table-p)]
12618 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12619 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12620 ("Row"
12621 ["Move Row Up" org-metaup (org-at-table-p)]
12622 ["Move Row Down" org-metadown (org-at-table-p)]
12623 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12624 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12625 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12626 "--"
12627 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12628 ("Rectangle"
12629 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12630 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12631 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12632 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12633 "--"
12634 ("Calculate"
12635 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12636 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12637 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12638 "--"
12639 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12640 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12641 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12642 "--"
12643 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12644 "--"
12645 ["Sum Column/Rectangle" org-table-sum
12646 (or (org-at-table-p) (org-region-active-p))]
12647 ["Which Column?" org-table-current-column (org-at-table-p)])
12648 ["Debug Formulas"
12649 org-table-toggle-formula-debugger
12650 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12651 ["Show Col/Row Numbers"
12652 org-table-toggle-coordinate-overlays
12653 :style toggle
12654 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12655 "--"
12656 ["Create" org-table-create (and (not (org-at-table-p))
12657 org-enable-table-editor)]
12658 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12659 ["Import from File" org-table-import (not (org-at-table-p))]
12660 ["Export to File" org-table-export (org-at-table-p)]
12661 "--"
12662 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12664 (easy-menu-define org-org-menu org-mode-map "Org menu"
12665 '("Org"
12666 ("Show/Hide"
12667 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12668 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12669 ["Sparse Tree..." org-sparse-tree t]
12670 ["Reveal Context" org-reveal t]
12671 ["Show All" show-all t]
12672 "--"
12673 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12674 "--"
12675 ["New Heading" org-insert-heading t]
12676 ("Navigate Headings"
12677 ["Up" outline-up-heading t]
12678 ["Next" outline-next-visible-heading t]
12679 ["Previous" outline-previous-visible-heading t]
12680 ["Next Same Level" outline-forward-same-level t]
12681 ["Previous Same Level" outline-backward-same-level t]
12682 "--"
12683 ["Jump" org-goto t])
12684 ("Edit Structure"
12685 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12686 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12687 "--"
12688 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12689 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12690 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12691 "--"
12692 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12693 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12694 ["Demote Heading" org-metaright (not (org-at-table-p))]
12695 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12696 "--"
12697 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12698 "--"
12699 ["Convert to odd levels" org-convert-to-odd-levels t]
12700 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12701 ("Editing"
12702 ["Emphasis..." org-emphasize t])
12703 ("Archive"
12704 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12705 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12706 ; :active t :keys "C-u C-c C-x C-a"]
12707 ["Sparse trees open ARCHIVE trees"
12708 (setq org-sparse-tree-open-archived-trees
12709 (not org-sparse-tree-open-archived-trees))
12710 :style toggle :selected org-sparse-tree-open-archived-trees]
12711 ["Cycling opens ARCHIVE trees"
12712 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12713 :style toggle :selected org-cycle-open-archived-trees]
12714 ["Agenda includes ARCHIVE trees"
12715 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12716 :style toggle :selected (not org-agenda-skip-archived-trees)]
12717 "--"
12718 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12719 ; ["Check and Move Children" (org-archive-subtree '(4))
12720 ; :active t :keys "C-u C-c C-x C-s"]
12722 "--"
12723 ("TODO Lists"
12724 ["TODO/DONE/-" org-todo t]
12725 ("Select keyword"
12726 ["Next keyword" org-shiftright (org-on-heading-p)]
12727 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12728 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12729 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12730 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12731 ["Show TODO Tree" org-show-todo-tree t]
12732 ["Global TODO list" org-todo-list t]
12733 "--"
12734 ["Set Priority" org-priority t]
12735 ["Priority Up" org-shiftup t]
12736 ["Priority Down" org-shiftdown t])
12737 ("TAGS and Properties"
12738 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12739 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12740 "--"
12741 ["Set property" 'org-set-property t]
12742 ["Column view of properties" org-columns t]
12743 ["Insert Column View DBlock" org-insert-columns-dblock t])
12744 ("Dates and Scheduling"
12745 ["Timestamp" org-time-stamp t]
12746 ["Timestamp (inactive)" org-time-stamp-inactive t]
12747 ("Change Date"
12748 ["1 Day Later" org-shiftright t]
12749 ["1 Day Earlier" org-shiftleft t]
12750 ["1 ... Later" org-shiftup t]
12751 ["1 ... Earlier" org-shiftdown t])
12752 ["Compute Time Range" org-evaluate-time-range t]
12753 ["Schedule Item" org-schedule t]
12754 ["Deadline" org-deadline t]
12755 "--"
12756 ["Custom time format" org-toggle-time-stamp-overlays
12757 :style radio :selected org-display-custom-times]
12758 "--"
12759 ["Goto Calendar" org-goto-calendar t]
12760 ["Date from Calendar" org-date-from-calendar t])
12761 ("Logging work"
12762 ["Clock in" org-clock-in t]
12763 ["Clock out" org-clock-out t]
12764 ["Clock cancel" org-clock-cancel t]
12765 ["Goto running clock" org-clock-goto t]
12766 ["Display times" org-clock-display t]
12767 ["Create clock table" org-clock-report t]
12768 "--"
12769 ["Record DONE time"
12770 (progn (setq org-log-done (not org-log-done))
12771 (message "Switching to %s will %s record a timestamp"
12772 (car org-done-keywords)
12773 (if org-log-done "automatically" "not")))
12774 :style toggle :selected org-log-done])
12775 "--"
12776 ["Agenda Command..." org-agenda t]
12777 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12778 ("File List for Agenda")
12779 ("Special views current file"
12780 ["TODO Tree" org-show-todo-tree t]
12781 ["Check Deadlines" org-check-deadlines t]
12782 ["Timeline" org-timeline t]
12783 ["Tags Tree" org-tags-sparse-tree t])
12784 "--"
12785 ("Hyperlinks"
12786 ["Store Link (Global)" org-store-link t]
12787 ["Insert Link" org-insert-link t]
12788 ["Follow Link" org-open-at-point t]
12789 "--"
12790 ["Next link" org-next-link t]
12791 ["Previous link" org-previous-link t]
12792 "--"
12793 ["Descriptive Links"
12794 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12795 :style radio
12796 :selected (member '(org-link) buffer-invisibility-spec)]
12797 ["Literal Links"
12798 (progn
12799 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12800 :style radio
12801 :selected (not (member '(org-link) buffer-invisibility-spec))])
12802 "--"
12803 ["Export/Publish..." org-export t]
12804 ("LaTeX"
12805 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12806 :selected org-cdlatex-mode]
12807 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12808 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12809 ["Modify math symbol" org-cdlatex-math-modify
12810 (org-inside-LaTeX-fragment-p)]
12811 ["Export LaTeX fragments as images"
12812 (if (featurep 'org-exp)
12813 (setq org-export-with-LaTeX-fragments
12814 (not org-export-with-LaTeX-fragments))
12815 (require 'org-exp))
12816 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12817 org-export-with-LaTeX-fragments)])
12818 "--"
12819 ("Documentation"
12820 ["Show Version" org-version t]
12821 ["Info Documentation" org-info t])
12822 ("Customize"
12823 ["Browse Org Group" org-customize t]
12824 "--"
12825 ["Expand This Menu" org-create-customize-menu
12826 (fboundp 'customize-menu-create)])
12827 "--"
12828 ["Refresh setup" org-mode-restart t]
12831 (defun org-info (&optional node)
12832 "Read documentation for Org-mode in the info system.
12833 With optional NODE, go directly to that node."
12834 (interactive)
12835 (info (format "(org)%s" (or node ""))))
12837 (defun org-install-agenda-files-menu ()
12838 (let ((bl (buffer-list)))
12839 (save-excursion
12840 (while bl
12841 (set-buffer (pop bl))
12842 (if (org-mode-p) (setq bl nil)))
12843 (when (org-mode-p)
12844 (easy-menu-change
12845 '("Org") "File List for Agenda"
12846 (append
12847 (list
12848 ["Edit File List" (org-edit-agenda-file-list) t]
12849 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12850 ["Remove Current File from List" org-remove-file t]
12851 ["Cycle through agenda files" org-cycle-agenda-files t]
12852 ["Occur in all agenda files" org-occur-in-agenda-files t]
12853 "--")
12854 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12856 ;;;; Documentation
12858 (defun org-require-autoloaded-modules ()
12859 (interactive)
12860 (mapc 'require
12861 '(org-agenda org-archive org-clock org-colview
12862 org-exp org-export-latex org-publish
12863 org-remember org-table)))
12865 (defun org-customize ()
12866 "Call the customize function with org as argument."
12867 (interactive)
12868 (org-load-modules-maybe)
12869 (org-require-autoloaded-modules)
12870 (customize-browse 'org))
12872 (defun org-create-customize-menu ()
12873 "Create a full customization menu for Org-mode, insert it into the menu."
12874 (interactive)
12875 (org-load-modules-maybe)
12876 (org-require-autoloaded-modules)
12877 (if (fboundp 'customize-menu-create)
12878 (progn
12879 (easy-menu-change
12880 '("Org") "Customize"
12881 `(["Browse Org group" org-customize t]
12882 "--"
12883 ,(customize-menu-create 'org)
12884 ["Set" Custom-set t]
12885 ["Save" Custom-save t]
12886 ["Reset to Current" Custom-reset-current t]
12887 ["Reset to Saved" Custom-reset-saved t]
12888 ["Reset to Standard Settings" Custom-reset-standard t]))
12889 (message "\"Org\"-menu now contains full customization menu"))
12890 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12892 ;;;; Miscellaneous stuff
12894 ;;; Generally useful functions
12896 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12897 "Display the given MESSAGE as a warning."
12898 (if (fboundp 'display-warning)
12899 (display-warning 'org message
12900 (if (featurep 'xemacs)
12901 'warning
12902 :warning))
12903 (let ((buf (get-buffer-create "*Org warnings*")))
12904 (with-current-buffer buf
12905 (goto-char (point-max))
12906 (insert "Warning (Org): " message)
12907 (unless (bolp)
12908 (newline)))
12909 (display-buffer buf)
12910 (sit-for 0))))
12912 (defun org-plist-delete (plist property)
12913 "Delete PROPERTY from PLIST.
12914 This is in contrast to merely setting it to 0."
12915 (let (p)
12916 (while plist
12917 (if (not (eq property (car plist)))
12918 (setq p (plist-put p (car plist) (nth 1 plist))))
12919 (setq plist (cddr plist)))
12922 (defun org-force-self-insert (N)
12923 "Needed to enforce self-insert under remapping."
12924 (interactive "p")
12925 (self-insert-command N))
12927 (defun org-string-width (s)
12928 "Compute width of string, ignoring invisible characters.
12929 This ignores character with invisibility property `org-link', and also
12930 characters with property `org-cwidth', because these will become invisible
12931 upon the next fontification round."
12932 (let (b l)
12933 (when (or (eq t buffer-invisibility-spec)
12934 (assq 'org-link buffer-invisibility-spec))
12935 (while (setq b (text-property-any 0 (length s)
12936 'invisible 'org-link s))
12937 (setq s (concat (substring s 0 b)
12938 (substring s (or (next-single-property-change
12939 b 'invisible s) (length s)))))))
12940 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12941 (setq s (concat (substring s 0 b)
12942 (substring s (or (next-single-property-change
12943 b 'org-cwidth s) (length s))))))
12944 (setq l (string-width s) b -1)
12945 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12946 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12949 (defun org-base-buffer (buffer)
12950 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12951 (if (not buffer)
12952 buffer
12953 (or (buffer-base-buffer buffer)
12954 buffer)))
12956 (defun org-trim (s)
12957 "Remove whitespace at beginning and end of string."
12958 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12959 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12962 (defun org-wrap (string &optional width lines)
12963 "Wrap string to either a number of lines, or a width in characters.
12964 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12965 that costs. If there is a word longer than WIDTH, the text is actually
12966 wrapped to the length of that word.
12967 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12968 many lines, whatever width that takes.
12969 The return value is a list of lines, without newlines at the end."
12970 (let* ((words (org-split-string string "[ \t\n]+"))
12971 (maxword (apply 'max (mapcar 'org-string-width words)))
12972 w ll)
12973 (cond (width
12974 (org-do-wrap words (max maxword width)))
12975 (lines
12976 (setq w maxword)
12977 (setq ll (org-do-wrap words maxword))
12978 (if (<= (length ll) lines)
12980 (setq ll words)
12981 (while (> (length ll) lines)
12982 (setq w (1+ w))
12983 (setq ll (org-do-wrap words w)))
12984 ll))
12985 (t (error "Cannot wrap this")))))
12987 (defun org-do-wrap (words width)
12988 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12989 (let (lines line)
12990 (while words
12991 (setq line (pop words))
12992 (while (and words (< (+ (length line) (length (car words))) width))
12993 (setq line (concat line " " (pop words))))
12994 (setq lines (push line lines)))
12995 (nreverse lines)))
12997 (defun org-split-string (string &optional separators)
12998 "Splits STRING into substrings at SEPARATORS.
12999 No empty strings are returned if there are matches at the beginning
13000 and end of string."
13001 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13002 (start 0)
13003 notfirst
13004 (list nil))
13005 (while (and (string-match rexp string
13006 (if (and notfirst
13007 (= start (match-beginning 0))
13008 (< start (length string)))
13009 (1+ start) start))
13010 (< (match-beginning 0) (length string)))
13011 (setq notfirst t)
13012 (or (eq (match-beginning 0) 0)
13013 (and (eq (match-beginning 0) (match-end 0))
13014 (eq (match-beginning 0) start))
13015 (setq list
13016 (cons (substring string start (match-beginning 0))
13017 list)))
13018 (setq start (match-end 0)))
13019 (or (eq start (length string))
13020 (setq list
13021 (cons (substring string start)
13022 list)))
13023 (nreverse list)))
13025 (defun org-context ()
13026 "Return a list of contexts of the current cursor position.
13027 If several contexts apply, all are returned.
13028 Each context entry is a list with a symbol naming the context, and
13029 two positions indicating start and end of the context. Possible
13030 contexts are:
13032 :headline anywhere in a headline
13033 :headline-stars on the leading stars in a headline
13034 :todo-keyword on a TODO keyword (including DONE) in a headline
13035 :tags on the TAGS in a headline
13036 :priority on the priority cookie in a headline
13037 :item on the first line of a plain list item
13038 :item-bullet on the bullet/number of a plain list item
13039 :checkbox on the checkbox in a plain list item
13040 :table in an org-mode table
13041 :table-special on a special filed in a table
13042 :table-table in a table.el table
13043 :link on a hyperlink
13044 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13045 :target on a <<target>>
13046 :radio-target on a <<<radio-target>>>
13047 :latex-fragment on a LaTeX fragment
13048 :latex-preview on a LaTeX fragment with overlayed preview image
13050 This function expects the position to be visible because it uses font-lock
13051 faces as a help to recognize the following contexts: :table-special, :link,
13052 and :keyword."
13053 (let* ((f (get-text-property (point) 'face))
13054 (faces (if (listp f) f (list f)))
13055 (p (point)) clist o)
13056 ;; First the large context
13057 (cond
13058 ((org-on-heading-p t)
13059 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13060 (when (progn
13061 (beginning-of-line 1)
13062 (looking-at org-todo-line-tags-regexp))
13063 (push (org-point-in-group p 1 :headline-stars) clist)
13064 (push (org-point-in-group p 2 :todo-keyword) clist)
13065 (push (org-point-in-group p 4 :tags) clist))
13066 (goto-char p)
13067 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13068 (if (looking-at "\\[#[A-Z0-9]\\]")
13069 (push (org-point-in-group p 0 :priority) clist)))
13071 ((org-at-item-p)
13072 (push (org-point-in-group p 2 :item-bullet) clist)
13073 (push (list :item (point-at-bol)
13074 (save-excursion (org-end-of-item) (point)))
13075 clist)
13076 (and (org-at-item-checkbox-p)
13077 (push (org-point-in-group p 0 :checkbox) clist)))
13079 ((org-at-table-p)
13080 (push (list :table (org-table-begin) (org-table-end)) clist)
13081 (if (memq 'org-formula faces)
13082 (push (list :table-special
13083 (previous-single-property-change p 'face)
13084 (next-single-property-change p 'face)) clist)))
13085 ((org-at-table-p 'any)
13086 (push (list :table-table) clist)))
13087 (goto-char p)
13089 ;; Now the small context
13090 (cond
13091 ((org-at-timestamp-p)
13092 (push (org-point-in-group p 0 :timestamp) clist))
13093 ((memq 'org-link faces)
13094 (push (list :link
13095 (previous-single-property-change p 'face)
13096 (next-single-property-change p 'face)) clist))
13097 ((memq 'org-special-keyword faces)
13098 (push (list :keyword
13099 (previous-single-property-change p 'face)
13100 (next-single-property-change p 'face)) clist))
13101 ((org-on-target-p)
13102 (push (org-point-in-group p 0 :target) clist)
13103 (goto-char (1- (match-beginning 0)))
13104 (if (looking-at org-radio-target-regexp)
13105 (push (org-point-in-group p 0 :radio-target) clist))
13106 (goto-char p))
13107 ((setq o (car (delq nil
13108 (mapcar
13109 (lambda (x)
13110 (if (memq x org-latex-fragment-image-overlays) x))
13111 (org-overlays-at (point))))))
13112 (push (list :latex-fragment
13113 (org-overlay-start o) (org-overlay-end o)) clist)
13114 (push (list :latex-preview
13115 (org-overlay-start o) (org-overlay-end o)) clist))
13116 ((org-inside-LaTeX-fragment-p)
13117 ;; FIXME: positions wrong.
13118 (push (list :latex-fragment (point) (point)) clist)))
13120 (setq clist (nreverse (delq nil clist)))
13121 clist))
13123 ;; FIXME: Compare with at-regexp-p Do we need both?
13124 (defun org-in-regexp (re &optional nlines visually)
13125 "Check if point is inside a match of regexp.
13126 Normally only the current line is checked, but you can include NLINES extra
13127 lines both before and after point into the search.
13128 If VISUALLY is set, require that the cursor is not after the match but
13129 really on, so that the block visually is on the match."
13130 (catch 'exit
13131 (let ((pos (point))
13132 (eol (point-at-eol (+ 1 (or nlines 0))))
13133 (inc (if visually 1 0)))
13134 (save-excursion
13135 (beginning-of-line (- 1 (or nlines 0)))
13136 (while (re-search-forward re eol t)
13137 (if (and (<= (match-beginning 0) pos)
13138 (>= (+ inc (match-end 0)) pos))
13139 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13141 (defun org-at-regexp-p (regexp)
13142 "Is point inside a match of REGEXP in the current line?"
13143 (catch 'exit
13144 (save-excursion
13145 (let ((pos (point)) (end (point-at-eol)))
13146 (beginning-of-line 1)
13147 (while (re-search-forward regexp end t)
13148 (if (and (<= (match-beginning 0) pos)
13149 (>= (match-end 0) pos))
13150 (throw 'exit t)))
13151 nil))))
13153 (defun org-occur-in-agenda-files (regexp &optional nlines)
13154 "Call `multi-occur' with buffers for all agenda files."
13155 (interactive "sOrg-files matching: \np")
13156 (let* ((files (org-agenda-files))
13157 (tnames (mapcar 'file-truename files))
13158 (extra org-agenda-text-search-extra-files)
13160 (when (eq (car extra) 'agenda-archives)
13161 (setq extra (cdr extra))
13162 (setq files (org-add-archive-files files)))
13163 (while (setq f (pop extra))
13164 (unless (member (file-truename f) tnames)
13165 (add-to-list 'files f 'append)
13166 (add-to-list 'tnames (file-truename f) 'append)))
13167 (multi-occur
13168 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13169 regexp)))
13171 (if (boundp 'occur-mode-find-occurrence-hook)
13172 ;; Emacs 23
13173 (add-hook 'occur-mode-find-occurrence-hook
13174 (lambda ()
13175 (when (org-mode-p)
13176 (org-reveal))))
13177 ;; Emacs 22
13178 (defadvice occur-mode-goto-occurrence
13179 (after org-occur-reveal activate)
13180 (and (org-mode-p) (org-reveal)))
13181 (defadvice occur-mode-goto-occurrence-other-window
13182 (after org-occur-reveal activate)
13183 (and (org-mode-p) (org-reveal)))
13184 (defadvice occur-mode-display-occurrence
13185 (after org-occur-reveal activate)
13186 (when (org-mode-p)
13187 (let ((pos (occur-mode-find-occurrence)))
13188 (with-current-buffer (marker-buffer pos)
13189 (save-excursion
13190 (goto-char pos)
13191 (org-reveal)))))))
13193 (defun org-uniquify (list)
13194 "Remove duplicate elements from LIST."
13195 (let (res)
13196 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13197 res))
13199 (defun org-delete-all (elts list)
13200 "Remove all elements in ELTS from LIST."
13201 (while elts
13202 (setq list (delete (pop elts) list)))
13203 list)
13205 (defun org-back-over-empty-lines ()
13206 "Move backwards over witespace, to the beginning of the first empty line.
13207 Returns the number of empty lines passed."
13208 (let ((pos (point)))
13209 (skip-chars-backward " \t\n\r")
13210 (beginning-of-line 2)
13211 (goto-char (min (point) pos))
13212 (count-lines (point) pos)))
13214 (defun org-skip-whitespace ()
13215 (skip-chars-forward " \t\n\r"))
13217 (defun org-point-in-group (point group &optional context)
13218 "Check if POINT is in match-group GROUP.
13219 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13220 match. If the match group does ot exist or point is not inside it,
13221 return nil."
13222 (and (match-beginning group)
13223 (>= point (match-beginning group))
13224 (<= point (match-end group))
13225 (if context
13226 (list context (match-beginning group) (match-end group))
13227 t)))
13229 (defun org-switch-to-buffer-other-window (&rest args)
13230 "Switch to buffer in a second window on the current frame.
13231 In particular, do not allow pop-up frames."
13232 (let (pop-up-frames special-display-buffer-names special-display-regexps
13233 special-display-function)
13234 (apply 'switch-to-buffer-other-window args)))
13236 (defun org-combine-plists (&rest plists)
13237 "Create a single property list from all plists in PLISTS.
13238 The process starts by copying the first list, and then setting properties
13239 from the other lists. Settings in the last list are the most significant
13240 ones and overrule settings in the other lists."
13241 (let ((rtn (copy-sequence (pop plists)))
13242 p v ls)
13243 (while plists
13244 (setq ls (pop plists))
13245 (while ls
13246 (setq p (pop ls) v (pop ls))
13247 (setq rtn (plist-put rtn p v))))
13248 rtn))
13250 (defun org-move-line-down (arg)
13251 "Move the current line down. With prefix argument, move it past ARG lines."
13252 (interactive "p")
13253 (let ((col (current-column))
13254 beg end pos)
13255 (beginning-of-line 1) (setq beg (point))
13256 (beginning-of-line 2) (setq end (point))
13257 (beginning-of-line (+ 1 arg))
13258 (setq pos (move-marker (make-marker) (point)))
13259 (insert (delete-and-extract-region beg end))
13260 (goto-char pos)
13261 (org-move-to-column col)))
13263 (defun org-move-line-up (arg)
13264 "Move the current line up. With prefix argument, move it past ARG lines."
13265 (interactive "p")
13266 (let ((col (current-column))
13267 beg end pos)
13268 (beginning-of-line 1) (setq beg (point))
13269 (beginning-of-line 2) (setq end (point))
13270 (beginning-of-line (- arg))
13271 (setq pos (move-marker (make-marker) (point)))
13272 (insert (delete-and-extract-region beg end))
13273 (goto-char pos)
13274 (org-move-to-column col)))
13276 (defun org-replace-escapes (string table)
13277 "Replace %-escapes in STRING with values in TABLE.
13278 TABLE is an association list with keys like \"%a\" and string values.
13279 The sequences in STRING may contain normal field width and padding information,
13280 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13281 so values can contain further %-escapes if they are define later in TABLE."
13282 (let ((case-fold-search nil)
13283 e re rpl)
13284 (while (setq e (pop table))
13285 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13286 (while (string-match re string)
13287 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13288 (cdr e)))
13289 (setq string (replace-match rpl t t string))))
13290 string))
13293 (defun org-sublist (list start end)
13294 "Return a section of LIST, from START to END.
13295 Counting starts at 1."
13296 (let (rtn (c start))
13297 (setq list (nthcdr (1- start) list))
13298 (while (and list (<= c end))
13299 (push (pop list) rtn)
13300 (setq c (1+ c)))
13301 (nreverse rtn)))
13303 (defun org-find-base-buffer-visiting (file)
13304 "Like `find-buffer-visiting' but alway return the base buffer and
13305 not an indirect buffer."
13306 (let ((buf (find-buffer-visiting file)))
13307 (if buf
13308 (or (buffer-base-buffer buf) buf)
13309 nil)))
13311 (defun org-image-file-name-regexp ()
13312 "Return regexp matching the file names of images."
13313 (if (fboundp 'image-file-name-regexp)
13314 (image-file-name-regexp)
13315 (let ((image-file-name-extensions
13316 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13317 "xbm" "xpm" "pbm" "pgm" "ppm")))
13318 (concat "\\."
13319 (regexp-opt (nconc (mapcar 'upcase
13320 image-file-name-extensions)
13321 image-file-name-extensions)
13323 "\\'"))))
13325 (defun org-file-image-p (file)
13326 "Return non-nil if FILE is an image."
13327 (save-match-data
13328 (string-match (org-image-file-name-regexp) file)))
13330 ;;; Paragraph filling stuff.
13331 ;; We want this to be just right, so use the full arsenal.
13333 (defun org-indent-line-function ()
13334 "Indent line like previous, but further if previous was headline or item."
13335 (interactive)
13336 (let* ((pos (point))
13337 (itemp (org-at-item-p))
13338 column bpos bcol tpos tcol bullet btype bullet-type)
13339 ;; Find the previous relevant line
13340 (beginning-of-line 1)
13341 (cond
13342 ((looking-at "#") (setq column 0))
13343 ((looking-at "\\*+ ") (setq column 0))
13345 (beginning-of-line 0)
13346 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13347 (beginning-of-line 0))
13348 (cond
13349 ((looking-at "\\*+[ \t]+")
13350 (goto-char (match-end 0))
13351 (setq column (current-column)))
13352 ((org-in-item-p)
13353 (org-beginning-of-item)
13354 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13355 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13356 (setq bpos (match-beginning 1) tpos (match-end 0)
13357 bcol (progn (goto-char bpos) (current-column))
13358 tcol (progn (goto-char tpos) (current-column))
13359 bullet (match-string 1)
13360 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13361 (if (not itemp)
13362 (setq column tcol)
13363 (goto-char pos)
13364 (beginning-of-line 1)
13365 (if (looking-at "\\S-")
13366 (progn
13367 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13368 (setq bullet (match-string 1)
13369 btype (if (string-match "[0-9]" bullet) "n" bullet))
13370 (setq column (if (equal btype bullet-type) bcol tcol)))
13371 (setq column (org-get-indentation)))))
13372 (t (setq column (org-get-indentation))))))
13373 (goto-char pos)
13374 (if (<= (current-column) (current-indentation))
13375 (org-indent-line-to column)
13376 (save-excursion (org-indent-line-to column)))
13377 (setq column (current-column))
13378 (beginning-of-line 1)
13379 (if (looking-at
13380 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13381 (replace-match (concat "\\1" (format org-property-format
13382 (match-string 2) (match-string 3)))
13383 t nil))
13384 (org-move-to-column column)))
13386 (defun org-set-autofill-regexps ()
13387 (interactive)
13388 ;; In the paragraph separator we include headlines, because filling
13389 ;; text in a line directly attached to a headline would otherwise
13390 ;; fill the headline as well.
13391 (org-set-local 'comment-start-skip "^#+[ \t]*")
13392 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13393 ;; The paragraph starter includes hand-formatted lists.
13394 (org-set-local 'paragraph-start
13395 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13396 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13397 ;; But only if the user has not turned off tables or fixed-width regions
13398 (org-set-local
13399 'auto-fill-inhibit-regexp
13400 (concat "\\*+ \\|#\\+"
13401 "\\|[ \t]*" org-keyword-time-regexp
13402 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13403 (concat
13404 "\\|[ \t]*["
13405 (if org-enable-table-editor "|" "")
13406 (if org-enable-fixed-width-editor ":" "")
13407 "]"))))
13408 ;; We use our own fill-paragraph function, to make sure that tables
13409 ;; and fixed-width regions are not wrapped. That function will pass
13410 ;; through to `fill-paragraph' when appropriate.
13411 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13412 ; Adaptive filling: To get full control, first make sure that
13413 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13414 (org-set-local 'adaptive-fill-regexp "\000")
13415 (org-set-local 'adaptive-fill-function
13416 'org-adaptive-fill-function)
13417 (org-set-local
13418 'align-mode-rules-list
13419 '((org-in-buffer-settings
13420 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13421 (modes . '(org-mode))))))
13423 (defun org-fill-paragraph (&optional justify)
13424 "Re-align a table, pass through to fill-paragraph if no table."
13425 (let ((table-p (org-at-table-p))
13426 (table.el-p (org-at-table.el-p)))
13427 (cond ((and (equal (char-after (point-at-bol)) ?*)
13428 (save-excursion (goto-char (point-at-bol))
13429 (looking-at outline-regexp)))
13430 t) ; skip headlines
13431 (table.el-p t) ; skip table.el tables
13432 (table-p (org-table-align) t) ; align org-mode tables
13433 (t nil)))) ; call paragraph-fill
13435 ;; For reference, this is the default value of adaptive-fill-regexp
13436 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13438 (defun org-adaptive-fill-function ()
13439 "Return a fill prefix for org-mode files.
13440 In particular, this makes sure hanging paragraphs for hand-formatted lists
13441 work correctly."
13442 (cond ((looking-at "#[ \t]+")
13443 (match-string 0))
13444 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13445 (save-excursion
13446 (goto-char (match-end 0))
13447 (make-string (current-column) ?\ )))
13448 (t nil)))
13450 ;;; Other stuff.
13452 (defun org-toggle-fixed-width-section (arg)
13453 "Toggle the fixed-width export.
13454 If there is no active region, the QUOTE keyword at the current headline is
13455 inserted or removed. When present, it causes the text between this headline
13456 and the next to be exported as fixed-width text, and unmodified.
13457 If there is an active region, this command adds or removes a colon as the
13458 first character of this line. If the first character of a line is a colon,
13459 this line is also exported in fixed-width font."
13460 (interactive "P")
13461 (let* ((cc 0)
13462 (regionp (org-region-active-p))
13463 (beg (if regionp (region-beginning) (point)))
13464 (end (if regionp (region-end)))
13465 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13466 (case-fold-search nil)
13467 (re "[ \t]*\\(:\\)")
13468 off)
13469 (if regionp
13470 (save-excursion
13471 (goto-char beg)
13472 (setq cc (current-column))
13473 (beginning-of-line 1)
13474 (setq off (looking-at re))
13475 (while (> nlines 0)
13476 (setq nlines (1- nlines))
13477 (beginning-of-line 1)
13478 (cond
13479 (arg
13480 (org-move-to-column cc t)
13481 (insert ":\n")
13482 (forward-line -1))
13483 ((and off (looking-at re))
13484 (replace-match "" t t nil 1))
13485 ((not off) (org-move-to-column cc t) (insert ":")))
13486 (forward-line 1)))
13487 (save-excursion
13488 (org-back-to-heading)
13489 (if (looking-at (concat outline-regexp
13490 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13491 (replace-match "" t t nil 1)
13492 (if (looking-at outline-regexp)
13493 (progn
13494 (goto-char (match-end 0))
13495 (insert org-quote-string " "))))))))
13497 ;;;; Functions extending outline functionality
13499 (defun org-beginning-of-line (&optional arg)
13500 "Go to the beginning of the current line. If that is invisible, continue
13501 to a visible line beginning. This makes the function of C-a more intuitive.
13502 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13503 first attempt, and only move to after the tags when the cursor is already
13504 beyond the end of the headline."
13505 (interactive "P")
13506 (let ((pos (point)))
13507 (beginning-of-line 1)
13508 (if (bobp)
13510 (backward-char 1)
13511 (if (org-invisible-p)
13512 (while (and (not (bobp)) (org-invisible-p))
13513 (backward-char 1)
13514 (beginning-of-line 1))
13515 (forward-char 1)))
13516 (when org-special-ctrl-a/e
13517 (cond
13518 ((and (looking-at org-todo-line-regexp)
13519 (= (char-after (match-end 1)) ?\ ))
13520 (goto-char
13521 (if (eq org-special-ctrl-a/e t)
13522 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13523 ((= pos (point)) (match-beginning 3))
13524 (t (point)))
13525 (cond ((> pos (point)) (point))
13526 ((not (eq last-command this-command)) (point))
13527 (t (match-beginning 3))))))
13528 ((org-at-item-p)
13529 (goto-char
13530 (if (eq org-special-ctrl-a/e t)
13531 (cond ((> pos (match-end 4)) (match-end 4))
13532 ((= pos (point)) (match-end 4))
13533 (t (point)))
13534 (cond ((> pos (point)) (point))
13535 ((not (eq last-command this-command)) (point))
13536 (t (match-end 4))))))))))
13538 (defun org-end-of-line (&optional arg)
13539 "Go to the end of the line.
13540 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13541 first attempt, and only move to after the tags when the cursor is already
13542 beyond the end of the headline."
13543 (interactive "P")
13544 (if (or (not org-special-ctrl-a/e)
13545 (not (org-on-heading-p)))
13546 (end-of-line arg)
13547 (let ((pos (point)))
13548 (beginning-of-line 1)
13549 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13550 (if (eq org-special-ctrl-a/e t)
13551 (if (or (< pos (match-beginning 1))
13552 (= pos (match-end 0)))
13553 (goto-char (match-beginning 1))
13554 (goto-char (match-end 0)))
13555 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13556 (goto-char (match-end 0))
13557 (goto-char (match-beginning 1))))
13558 (end-of-line arg)))))
13560 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13561 (define-key org-mode-map "\C-e" 'org-end-of-line)
13563 (defun org-kill-line (&optional arg)
13564 "Kill line, to tags or end of line."
13565 (interactive "P")
13566 (cond
13567 ((or (not org-special-ctrl-k)
13568 (bolp)
13569 (not (org-on-heading-p)))
13570 (call-interactively 'kill-line))
13571 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13572 (kill-region (point) (match-beginning 1))
13573 (org-set-tags nil t))
13574 (t (kill-region (point) (point-at-eol)))))
13576 (define-key org-mode-map "\C-k" 'org-kill-line)
13578 (defun org-invisible-p ()
13579 "Check if point is at a character currently not visible."
13580 ;; Early versions of noutline don't have `outline-invisible-p'.
13581 (if (fboundp 'outline-invisible-p)
13582 (outline-invisible-p)
13583 (get-char-property (point) 'invisible)))
13585 (defun org-invisible-p2 ()
13586 "Check if point is at a character currently not visible."
13587 (save-excursion
13588 (if (and (eolp) (not (bobp))) (backward-char 1))
13589 ;; Early versions of noutline don't have `outline-invisible-p'.
13590 (if (fboundp 'outline-invisible-p)
13591 (outline-invisible-p)
13592 (get-char-property (point) 'invisible))))
13594 (defalias 'org-back-to-heading 'outline-back-to-heading)
13595 (defalias 'org-on-heading-p 'outline-on-heading-p)
13596 (defalias 'org-at-heading-p 'outline-on-heading-p)
13597 (defun org-at-heading-or-item-p ()
13598 (or (org-on-heading-p) (org-at-item-p)))
13600 (defun org-on-target-p ()
13601 (or (org-in-regexp org-radio-target-regexp)
13602 (org-in-regexp org-target-regexp)))
13604 (defun org-up-heading-all (arg)
13605 "Move to the heading line of which the present line is a subheading.
13606 This function considers both visible and invisible heading lines.
13607 With argument, move up ARG levels."
13608 (if (fboundp 'outline-up-heading-all)
13609 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13610 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13612 (defun org-up-heading-safe ()
13613 "Move to the heading line of which the present line is a subheading.
13614 This version will not throw an error. It will return the level of the
13615 headline found, or nil if no higher level is found."
13616 (let ((pos (point)) start-level level
13617 (re (concat "^" outline-regexp)))
13618 (catch 'exit
13619 (outline-back-to-heading t)
13620 (setq start-level (funcall outline-level))
13621 (if (equal start-level 1) (throw 'exit nil))
13622 (while (re-search-backward re nil t)
13623 (setq level (funcall outline-level))
13624 (if (< level start-level) (throw 'exit level)))
13625 nil)))
13627 (defun org-first-sibling-p ()
13628 "Is this heading the first child of its parents?"
13629 (interactive)
13630 (let ((re (concat "^" outline-regexp))
13631 level l)
13632 (unless (org-at-heading-p t)
13633 (error "Not at a heading"))
13634 (setq level (funcall outline-level))
13635 (save-excursion
13636 (if (not (re-search-backward re nil t))
13638 (setq l (funcall outline-level))
13639 (< l level)))))
13641 (defun org-goto-sibling (&optional previous)
13642 "Goto the next sibling, even if it is invisible.
13643 When PREVIOUS is set, go to the previous sibling instead. Returns t
13644 when a sibling was found. When none is found, return nil and don't
13645 move point."
13646 (let ((fun (if previous 're-search-backward 're-search-forward))
13647 (pos (point))
13648 (re (concat "^" outline-regexp))
13649 level l)
13650 (when (condition-case nil (org-back-to-heading t) (error nil))
13651 (setq level (funcall outline-level))
13652 (catch 'exit
13653 (or previous (forward-char 1))
13654 (while (funcall fun re nil t)
13655 (setq l (funcall outline-level))
13656 (when (< l level) (goto-char pos) (throw 'exit nil))
13657 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13658 (goto-char pos)
13659 nil))))
13661 (defun org-show-siblings ()
13662 "Show all siblings of the current headline."
13663 (save-excursion
13664 (while (org-goto-sibling) (org-flag-heading nil)))
13665 (save-excursion
13666 (while (org-goto-sibling 'previous)
13667 (org-flag-heading nil))))
13669 (defun org-show-hidden-entry ()
13670 "Show an entry where even the heading is hidden."
13671 (save-excursion
13672 (org-show-entry)))
13674 (defun org-flag-heading (flag &optional entry)
13675 "Flag the current heading. FLAG non-nil means make invisible.
13676 When ENTRY is non-nil, show the entire entry."
13677 (save-excursion
13678 (org-back-to-heading t)
13679 ;; Check if we should show the entire entry
13680 (if entry
13681 (progn
13682 (org-show-entry)
13683 (save-excursion
13684 (and (outline-next-heading)
13685 (org-flag-heading nil))))
13686 (outline-flag-region (max (point-min) (1- (point)))
13687 (save-excursion (outline-end-of-heading) (point))
13688 flag))))
13690 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13691 ;; This is an exact copy of the original function, but it uses
13692 ;; `org-back-to-heading', to make it work also in invisible
13693 ;; trees. And is uses an invisible-OK argument.
13694 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13695 (org-back-to-heading invisible-OK)
13696 (let ((first t)
13697 (level (funcall outline-level)))
13698 (while (and (not (eobp))
13699 (or first (> (funcall outline-level) level)))
13700 (setq first nil)
13701 (outline-next-heading))
13702 (unless to-heading
13703 (if (memq (preceding-char) '(?\n ?\^M))
13704 (progn
13705 ;; Go to end of line before heading
13706 (forward-char -1)
13707 (if (memq (preceding-char) '(?\n ?\^M))
13708 ;; leave blank line before heading
13709 (forward-char -1))))))
13710 (point))
13712 (defun org-show-subtree ()
13713 "Show everything after this heading at deeper levels."
13714 (outline-flag-region
13715 (point)
13716 (save-excursion
13717 (outline-end-of-subtree) (outline-next-heading) (point))
13718 nil))
13720 (defun org-show-entry ()
13721 "Show the body directly following this heading.
13722 Show the heading too, if it is currently invisible."
13723 (interactive)
13724 (save-excursion
13725 (condition-case nil
13726 (progn
13727 (org-back-to-heading t)
13728 (outline-flag-region
13729 (max (point-min) (1- (point)))
13730 (save-excursion
13731 (re-search-forward
13732 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13733 (or (match-beginning 1) (point-max)))
13734 nil))
13735 (error nil))))
13737 (defun org-make-options-regexp (kwds)
13738 "Make a regular expression for keyword lines."
13739 (concat
13741 "#?[ \t]*\\+\\("
13742 (mapconcat 'regexp-quote kwds "\\|")
13743 "\\):[ \t]*"
13744 "\\(.+\\)"))
13746 ;; Make isearch reveal the necessary context
13747 (defun org-isearch-end ()
13748 "Reveal context after isearch exits."
13749 (when isearch-success ; only if search was successful
13750 (if (featurep 'xemacs)
13751 ;; Under XEmacs, the hook is run in the correct place,
13752 ;; we directly show the context.
13753 (org-show-context 'isearch)
13754 ;; In Emacs the hook runs *before* restoring the overlays.
13755 ;; So we have to use a one-time post-command-hook to do this.
13756 ;; (Emacs 22 has a special variable, see function `org-mode')
13757 (unless (and (boundp 'isearch-mode-end-hook-quit)
13758 isearch-mode-end-hook-quit)
13759 ;; Only when the isearch was not quitted.
13760 (org-add-hook 'post-command-hook 'org-isearch-post-command
13761 'append 'local)))))
13763 (defun org-isearch-post-command ()
13764 "Remove self from hook, and show context."
13765 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13766 (org-show-context 'isearch))
13769 ;;;; Integration with and fixes for other packages
13771 ;;; Imenu support
13773 (defvar org-imenu-markers nil
13774 "All markers currently used by Imenu.")
13775 (make-variable-buffer-local 'org-imenu-markers)
13777 (defun org-imenu-new-marker (&optional pos)
13778 "Return a new marker for use by Imenu, and remember the marker."
13779 (let ((m (make-marker)))
13780 (move-marker m (or pos (point)))
13781 (push m org-imenu-markers)
13784 (defun org-imenu-get-tree ()
13785 "Produce the index for Imenu."
13786 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13787 (setq org-imenu-markers nil)
13788 (let* ((n org-imenu-depth)
13789 (re (concat "^" outline-regexp))
13790 (subs (make-vector (1+ n) nil))
13791 (last-level 0)
13792 m tree level head)
13793 (save-excursion
13794 (save-restriction
13795 (widen)
13796 (goto-char (point-max))
13797 (while (re-search-backward re nil t)
13798 (setq level (org-reduced-level (funcall outline-level)))
13799 (when (<= level n)
13800 (looking-at org-complex-heading-regexp)
13801 (setq head (org-match-string-no-properties 4)
13802 m (org-imenu-new-marker))
13803 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13804 (if (>= level last-level)
13805 (push (cons head m) (aref subs level))
13806 (push (cons head (aref subs (1+ level))) (aref subs level))
13807 (loop for i from (1+ level) to n do (aset subs i nil)))
13808 (setq last-level level)))))
13809 (aref subs 1)))
13811 (eval-after-load "imenu"
13812 '(progn
13813 (add-hook 'imenu-after-jump-hook
13814 (lambda () (org-show-context 'org-goto)))))
13816 ;; Speedbar support
13818 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13819 "Overlay marking the agenda restriction line in speedbar.")
13820 (org-overlay-put org-speedbar-restriction-lock-overlay
13821 'face 'org-agenda-restriction-lock)
13822 (org-overlay-put org-speedbar-restriction-lock-overlay
13823 'help-echo "Agendas are currently limited to this item.")
13824 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13826 (defun org-speedbar-set-agenda-restriction ()
13827 "Restrict future agenda commands to the location at point in speedbar.
13828 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13829 (interactive)
13830 (require 'org-agenda)
13831 (let (p m tp np dir txt w)
13832 (cond
13833 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13834 'org-imenu t))
13835 (setq m (get-text-property p 'org-imenu-marker))
13836 (save-excursion
13837 (save-restriction
13838 (set-buffer (marker-buffer m))
13839 (goto-char m)
13840 (org-agenda-set-restriction-lock 'subtree))))
13841 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13842 'speedbar-function 'speedbar-find-file))
13843 (setq tp (previous-single-property-change
13844 (1+ p) 'speedbar-function)
13845 np (next-single-property-change
13846 tp 'speedbar-function)
13847 dir (speedbar-line-directory)
13848 txt (buffer-substring-no-properties (or tp (point-min))
13849 (or np (point-max))))
13850 (save-excursion
13851 (save-restriction
13852 (set-buffer (find-file-noselect
13853 (let ((default-directory dir))
13854 (expand-file-name txt))))
13855 (unless (org-mode-p)
13856 (error "Cannot restrict to non-Org-mode file"))
13857 (org-agenda-set-restriction-lock 'file))))
13858 (t (error "Don't know how to restrict Org-mode's agenda")))
13859 (org-move-overlay org-speedbar-restriction-lock-overlay
13860 (point-at-bol) (point-at-eol))
13861 (setq current-prefix-arg nil)
13862 (org-agenda-maybe-redo)))
13864 (eval-after-load "speedbar"
13865 '(progn
13866 (speedbar-add-supported-extension ".org")
13867 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13868 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13869 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13870 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13871 (add-hook 'speedbar-visiting-tag-hook
13872 (lambda () (org-show-context 'org-goto)))))
13875 ;;; Fixes and Hacks for problems with other packages
13877 ;; Make flyspell not check words in links, to not mess up our keymap
13878 (defun org-mode-flyspell-verify ()
13879 "Don't let flyspell put overlays at active buttons."
13880 (not (get-text-property (point) 'keymap)))
13882 ;; Make `bookmark-jump' show the jump location if it was hidden.
13883 (eval-after-load "bookmark"
13884 '(if (boundp 'bookmark-after-jump-hook)
13885 ;; We can use the hook
13886 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13887 ;; Hook not available, use advice
13888 (defadvice bookmark-jump (after org-make-visible activate)
13889 "Make the position visible."
13890 (org-bookmark-jump-unhide))))
13892 (defun org-bookmark-jump-unhide ()
13893 "Unhide the current position, to show the bookmark location."
13894 (and (org-mode-p)
13895 (or (org-invisible-p)
13896 (save-excursion (goto-char (max (point-min) (1- (point))))
13897 (org-invisible-p)))
13898 (org-show-context 'bookmark-jump)))
13900 ;; Make session.el ignore our circular variable
13901 (eval-after-load "session"
13902 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13904 ;;;; Experimental code
13906 (defun org-closed-in-range ()
13907 "Sparse tree of items closed in a certain time range.
13908 Still experimental, may disappear in the future."
13909 (interactive)
13910 ;; Get the time interval from the user.
13911 (let* ((time1 (time-to-seconds
13912 (org-read-date nil 'to-time nil "Starting date: ")))
13913 (time2 (time-to-seconds
13914 (org-read-date nil 'to-time nil "End date:")))
13915 ;; callback function
13916 (callback (lambda ()
13917 (let ((time
13918 (time-to-seconds
13919 (apply 'encode-time
13920 (org-parse-time-string
13921 (match-string 1))))))
13922 ;; check if time in interval
13923 (and (>= time time1) (<= time time2))))))
13924 ;; make tree, check each match with the callback
13925 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13928 ;;;; Finish up
13930 (provide 'org)
13932 (run-hooks 'org-load-hook)
13934 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13936 ;;; org.el ends here