Remove duplicate entry for org-mew.el in org-modules.
[org-mode/org-tableheadings.git] / lisp / org.el
blobf6fdc81cd1cc45ad4b8abbafe2426dafd8eeaa58
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 (defcustom org-global-properties nil
1846 "List of property/value pairs that can be inherited by any entry.
1847 You can set buffer-local values for this by adding lines like
1849 #+PROPERTY: NAME VALUE"
1850 :group 'org-properties
1851 :type '(repeat
1852 (cons (string :tag "Property")
1853 (string :tag "Value"))))
1855 (defvar org-local-properties nil
1856 "List of property/value pairs that can be inherited by any entry.
1857 Valid for the current buffer.
1858 This variable is populated from #+PROPERTY lines.")
1860 (defgroup org-agenda nil
1861 "Options concerning agenda views in Org-mode."
1862 :tag "Org Agenda"
1863 :group 'org)
1865 (defvar org-category nil
1866 "Variable used by org files to set a category for agenda display.
1867 Such files should use a file variable to set it, for example
1869 # -*- mode: org; org-category: \"ELisp\"
1871 or contain a special line
1873 #+CATEGORY: ELisp
1875 If the file does not specify a category, then file's base name
1876 is used instead.")
1877 (make-variable-buffer-local 'org-category)
1879 (defcustom org-agenda-files nil
1880 "The files to be used for agenda display.
1881 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1882 \\[org-remove-file]. You can also use customize to edit the list.
1884 If an entry is a directory, all files in that directory that are matched by
1885 `org-agenda-file-regexp' will be part of the file list.
1887 If the value of the variable is not a list but a single file name, then
1888 the list of agenda files is actually stored and maintained in that file, one
1889 agenda file per line."
1890 :group 'org-agenda
1891 :type '(choice
1892 (repeat :tag "List of files and directories" file)
1893 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1895 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1896 "Regular expression to match files for `org-agenda-files'.
1897 If any element in the list in that variable contains a directory instead
1898 of a normal file, all files in that directory that are matched by this
1899 regular expression will be included."
1900 :group 'org-agenda
1901 :type 'regexp)
1903 (defcustom org-agenda-text-search-extra-files nil
1904 "List of extra files to be searched by text search commands.
1905 These files will be search in addition to the agenda files by the
1906 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1907 Note that these files will only be searched for text search commands,
1908 not for the other agenda views like todo lists, tag searches or the weekly
1909 agenda. This variable is intended to list notes and possibly archive files
1910 that should also be searched by these two commands.
1911 In fact, if the first element in the list is the symbol `agenda-archives',
1912 than all archive files of all agenda files will be added to the search
1913 scope."
1914 :group 'org-agenda
1915 :type '(set :greedy t
1916 (const :tag "Agenda Archives" agenda-archives)
1917 (repeat :inline t (file))))
1919 (if (fboundp 'defvaralias)
1920 (defvaralias 'org-agenda-multi-occur-extra-files
1921 'org-agenda-text-search-extra-files))
1923 (defcustom org-agenda-skip-unavailable-files nil
1924 "t means to just skip non-reachable files in `org-agenda-files'.
1925 Nil means to remove them, after a query, from the list."
1926 :group 'org-agenda
1927 :type 'boolean)
1929 (defcustom org-calendar-to-agenda-key [?c]
1930 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1931 The command `org-calendar-goto-agenda' will be bound to this key. The
1932 default is the character `c' because then `c' can be used to switch back and
1933 forth between agenda and calendar."
1934 :group 'org-agenda
1935 :type 'sexp)
1937 (eval-after-load "calendar"
1938 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1939 'org-calendar-goto-agenda))
1941 (defgroup org-latex nil
1942 "Options for embedding LaTeX code into Org-mode."
1943 :tag "Org LaTeX"
1944 :group 'org)
1946 (defcustom org-format-latex-options
1947 '(:foreground default :background default :scale 1.0
1948 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1949 :matchers ("begin" "$" "$$" "\\(" "\\["))
1950 "Options for creating images from LaTeX fragments.
1951 This is a property list with the following properties:
1952 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1953 `default' means use the forground of the default face.
1954 :background the background color, or \"Transparent\".
1955 `default' means use the background of the default face.
1956 :scale a scaling factor for the size of the images
1957 :html-foreground, :html-background, :html-scale
1958 The same numbers for HTML export.
1959 :matchers a list indicating which matchers should be used to
1960 find LaTeX fragments. Valid members of this list are:
1961 \"begin\" find environments
1962 \"$\" find math expressions surrounded by $...$
1963 \"$$\" find math expressions surrounded by $$....$$
1964 \"\\(\" find math expressions surrounded by \\(...\\)
1965 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1966 :group 'org-latex
1967 :type 'plist)
1969 (defcustom org-format-latex-header "\\documentclass{article}
1970 \\usepackage{fullpage} % do not remove
1971 \\usepackage{amssymb}
1972 \\usepackage[usenames]{color}
1973 \\usepackage{amsmath}
1974 \\usepackage{latexsym}
1975 \\usepackage[mathscr]{eucal}
1976 \\pagestyle{empty} % do not remove"
1977 "The document header used for processing LaTeX fragments."
1978 :group 'org-latex
1979 :type 'string)
1982 (defgroup org-font-lock nil
1983 "Font-lock settings for highlighting in Org-mode."
1984 :tag "Org Font Lock"
1985 :group 'org)
1987 (defcustom org-level-color-stars-only nil
1988 "Non-nil means fontify only the stars in each headline.
1989 When nil, the entire headline is fontified.
1990 Changing it requires restart of `font-lock-mode' to become effective
1991 also in regions already fontified."
1992 :group 'org-font-lock
1993 :type 'boolean)
1995 (defcustom org-hide-leading-stars nil
1996 "Non-nil means, hide the first N-1 stars in a headline.
1997 This works by using the face `org-hide' for these stars. This
1998 face is white for a light background, and black for a dark
1999 background. You may have to customize the face `org-hide' to
2000 make this work.
2001 Changing it requires restart of `font-lock-mode' to become effective
2002 also in regions already fontified.
2003 You may also set this on a per-file basis by adding one of the following
2004 lines to the buffer:
2006 #+STARTUP: hidestars
2007 #+STARTUP: showstars"
2008 :group 'org-font-lock
2009 :type 'boolean)
2011 (defcustom org-fontify-done-headline nil
2012 "Non-nil means, change the face of a headline if it is marked DONE.
2013 Normally, only the TODO/DONE keyword indicates the state of a headline.
2014 When this is non-nil, the headline after the keyword is set to the
2015 `org-headline-done' as an additional indication."
2016 :group 'org-font-lock
2017 :type 'boolean)
2019 (defcustom org-fontify-emphasized-text t
2020 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2021 Changing this variable requires a restart of Emacs to take effect."
2022 :group 'org-font-lock
2023 :type 'boolean)
2025 (defcustom org-highlight-latex-fragments-and-specials nil
2026 "Non-nil means, fontify what is treated specially by the exporters."
2027 :group 'org-font-lock
2028 :type 'boolean)
2030 (defcustom org-hide-emphasis-markers nil
2031 "Non-nil mean font-lock should hide the emphasis marker characters."
2032 :group 'org-font-lock
2033 :type 'boolean)
2035 (defvar org-emph-re nil
2036 "Regular expression for matching emphasis.")
2037 (defvar org-verbatim-re nil
2038 "Regular expression for matching verbatim text.")
2039 (defvar org-emphasis-regexp-components) ; defined just below
2040 (defvar org-emphasis-alist) ; defined just below
2041 (defun org-set-emph-re (var val)
2042 "Set variable and compute the emphasis regular expression."
2043 (set var val)
2044 (when (and (boundp 'org-emphasis-alist)
2045 (boundp 'org-emphasis-regexp-components)
2046 org-emphasis-alist org-emphasis-regexp-components)
2047 (let* ((e org-emphasis-regexp-components)
2048 (pre (car e))
2049 (post (nth 1 e))
2050 (border (nth 2 e))
2051 (body (nth 3 e))
2052 (nl (nth 4 e))
2053 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2054 (body1 (concat body "*?"))
2055 (markers (mapconcat 'car org-emphasis-alist ""))
2056 (vmarkers (mapconcat
2057 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2058 org-emphasis-alist "")))
2059 ;; make sure special characters appear at the right position in the class
2060 (if (string-match "\\^" markers)
2061 (setq markers (concat (replace-match "" t t markers) "^")))
2062 (if (string-match "-" markers)
2063 (setq markers (concat (replace-match "" t t markers) "-")))
2064 (if (string-match "\\^" vmarkers)
2065 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2066 (if (string-match "-" vmarkers)
2067 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2068 (if (> nl 0)
2069 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2070 (int-to-string nl) "\\}")))
2071 ;; Make the regexp
2072 (setq org-emph-re
2073 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2074 "\\("
2075 "\\([" markers "]\\)"
2076 "\\("
2077 "[^" border "]\\|"
2078 "[^" border (if (and nil stacked) markers) "]"
2079 body1
2080 "[^" border (if (and nil stacked) markers) "]"
2081 "\\)"
2082 "\\3\\)"
2083 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2084 (setq org-verbatim-re
2085 (concat "\\([" pre "]\\|^\\)"
2086 "\\("
2087 "\\([" vmarkers "]\\)"
2088 "\\("
2089 "[^" border "]\\|"
2090 "[^" border "]"
2091 body1
2092 "[^" border "]"
2093 "\\)"
2094 "\\3\\)"
2095 "\\([" post "]\\|$\\)")))))
2097 (defcustom org-emphasis-regexp-components
2098 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2099 "Components used to build the regular expression for emphasis.
2100 This is a list with 6 entries. Terminology: In an emphasis string
2101 like \" *strong word* \", we call the initial space PREMATCH, the final
2102 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2103 and \"trong wor\" is the body. The different components in this variable
2104 specify what is allowed/forbidden in each part:
2106 pre Chars allowed as prematch. Beginning of line will be allowed too.
2107 post Chars allowed as postmatch. End of line will be allowed too.
2108 border The chars *forbidden* as border characters.
2109 body-regexp A regexp like \".\" to match a body character. Don't use
2110 non-shy groups here, and don't allow newline here.
2111 newline The maximum number of newlines allowed in an emphasis exp.
2113 Use customize to modify this, or restart Emacs after changing it."
2114 :group 'org-font-lock
2115 :set 'org-set-emph-re
2116 :type '(list
2117 (sexp :tag "Allowed chars in pre ")
2118 (sexp :tag "Allowed chars in post ")
2119 (sexp :tag "Forbidden chars in border ")
2120 (sexp :tag "Regexp for body ")
2121 (integer :tag "number of newlines allowed")
2122 (option (boolean :tag "Stacking (DISABLED) "))))
2124 (defcustom org-emphasis-alist
2125 `(("*" bold "<b>" "</b>")
2126 ("/" italic "<i>" "</i>")
2127 ("_" underline "<u>" "</u>")
2128 ("=" org-code "<code>" "</code>" verbatim)
2129 ("~" org-verbatim "" "" verbatim)
2130 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2131 "<del>" "</del>")
2133 "Special syntax for emphasized text.
2134 Text starting and ending with a special character will be emphasized, for
2135 example *bold*, _underlined_ and /italic/. This variable sets the marker
2136 characters, the face to be used by font-lock for highlighting in Org-mode
2137 Emacs buffers, and the HTML tags to be used for this.
2138 Use customize to modify this, or restart Emacs after changing it."
2139 :group 'org-font-lock
2140 :set 'org-set-emph-re
2141 :type '(repeat
2142 (list
2143 (string :tag "Marker character")
2144 (choice
2145 (face :tag "Font-lock-face")
2146 (plist :tag "Face property list"))
2147 (string :tag "HTML start tag")
2148 (string :tag "HTML end tag")
2149 (option (const verbatim)))))
2151 ;;; Miscellaneous options
2153 (defgroup org-completion nil
2154 "Completion in Org-mode."
2155 :tag "Org Completion"
2156 :group 'org)
2158 (defcustom org-completion-fallback-command 'hippie-expand
2159 "The expansion command called by \\[org-complete] in normal context.
2160 Normal means, no org-mode-specific context."
2161 :group 'org-completion
2162 :type 'function)
2164 ;;; Functions and variables from ther packages
2165 ;; Declared here to avoid compiler warnings
2167 ;; XEmacs only
2168 (defvar outline-mode-menu-heading)
2169 (defvar outline-mode-menu-show)
2170 (defvar outline-mode-menu-hide)
2171 (defvar zmacs-regions) ; XEmacs regions
2173 ;; Emacs only
2174 (defvar mark-active)
2176 ;; Various packages
2177 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2178 (declare-function calendar-forward-day "cal-move" (arg))
2179 (declare-function calendar-goto-date "cal-move" (date))
2180 (declare-function calendar-goto-today "cal-move" ())
2181 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2182 (defvar calc-embedded-close-formula)
2183 (defvar calc-embedded-open-formula)
2184 (declare-function cdlatex-tab "ext:cdlatex" ())
2185 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2186 (defvar font-lock-unfontify-region-function)
2187 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2188 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2189 (defvar iswitchb-temp-buflist)
2190 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2191 (declare-function org-agenda-skip "org-agenda" ())
2192 (declare-function org-format-agenda-item "org-agenda"
2193 (extra txt &optional category tags dotime noprefix remove-re))
2194 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2195 (declare-function org-agenda-change-all-lines "org-agenda"
2196 (newhead hdmarker &optional fixface))
2197 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2198 (declare-function org-agenda-maybe-redo "org-agenda" ())
2199 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2200 (beg end))
2201 (declare-function parse-time-string "parse-time" (string))
2202 (declare-function remember "remember" (&optional initial))
2203 (declare-function remember-buffer-desc "remember" ())
2204 (declare-function remember-finalize "remember" ())
2205 (defvar remember-save-after-remembering)
2206 (defvar remember-data-file)
2207 (defvar remember-register)
2208 (defvar remember-buffer)
2209 (defvar remember-handler-functions)
2210 (defvar remember-annotation-functions)
2211 (defvar texmathp-why)
2212 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2213 (declare-function table--at-cell-p "table" (position &optional object at-column))
2215 (defvar w3m-current-url)
2216 (defvar w3m-current-title)
2218 (defvar org-latex-regexps)
2220 ;;; Autoload and prepare some org modules
2222 ;; Some table stuff that needs to be defined here, because it is used
2223 ;; by the functions setting up org-mode or checking for table context.
2225 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2226 "Detects an org-type or table-type table.")
2227 (defconst org-table-line-regexp "^[ \t]*|"
2228 "Detects an org-type table line.")
2229 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2230 "Detects an org-type table line.")
2231 (defconst org-table-hline-regexp "^[ \t]*|-"
2232 "Detects an org-type table hline.")
2233 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2234 "Detects a table-type table hline.")
2235 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2236 "Searching from within a table (any type) this finds the first line
2237 outside the table.")
2239 ;; Autoload the functions in org-table.el that are needed by functions here.
2241 (eval-and-compile
2242 (org-autoload "org-table"
2243 '(org-table-align org-table-begin org-table-blank-field
2244 org-table-convert org-table-convert-region org-table-copy-down
2245 org-table-copy-region org-table-create
2246 org-table-create-or-convert-from-region
2247 org-table-create-with-table.el org-table-current-dline
2248 org-table-cut-region org-table-delete-column org-table-edit-field
2249 org-table-edit-formulas org-table-end org-table-eval-formula
2250 org-table-export org-table-field-info
2251 org-table-get-stored-formulas org-table-goto-column
2252 org-table-hline-and-move org-table-import org-table-insert-column
2253 org-table-insert-hline org-table-insert-row org-table-iterate
2254 org-table-justify-field-maybe org-table-kill-row
2255 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2256 org-table-move-column org-table-move-column-left
2257 org-table-move-column-right org-table-move-row
2258 org-table-move-row-down org-table-move-row-up
2259 org-table-next-field org-table-next-row org-table-paste-rectangle
2260 org-table-previous-field org-table-recalculate
2261 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2262 org-table-toggle-coordinate-overlays
2263 org-table-toggle-formula-debugger org-table-wrap-region
2264 orgtbl-mode turn-on-orgtbl)))
2266 (defun org-at-table-p (&optional table-type)
2267 "Return t if the cursor is inside an org-type table.
2268 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2269 (if org-enable-table-editor
2270 (save-excursion
2271 (beginning-of-line 1)
2272 (looking-at (if table-type org-table-any-line-regexp
2273 org-table-line-regexp)))
2274 nil))
2275 (defsubst org-table-p () (org-at-table-p))
2277 (defun org-at-table.el-p ()
2278 "Return t if and only if we are at a table.el table."
2279 (and (org-at-table-p 'any)
2280 (save-excursion
2281 (goto-char (org-table-begin 'any))
2282 (looking-at org-table1-hline-regexp))))
2283 (defun org-table-recognize-table.el ()
2284 "If there is a table.el table nearby, recognize it and move into it."
2285 (if org-table-tab-recognizes-table.el
2286 (if (org-at-table.el-p)
2287 (progn
2288 (beginning-of-line 1)
2289 (if (looking-at org-table-dataline-regexp)
2291 (if (looking-at org-table1-hline-regexp)
2292 (progn
2293 (beginning-of-line 2)
2294 (if (looking-at org-table-any-border-regexp)
2295 (beginning-of-line -1)))))
2296 (if (re-search-forward "|" (org-table-end t) t)
2297 (progn
2298 (require 'table)
2299 (if (table--at-cell-p (point))
2301 (message "recognizing table.el table...")
2302 (table-recognize-table)
2303 (message "recognizing table.el table...done")))
2304 (error "This should not happen..."))
2306 nil)
2307 nil))
2309 (defun org-at-table-hline-p ()
2310 "Return t if the cursor is inside a hline in a table."
2311 (if org-enable-table-editor
2312 (save-excursion
2313 (beginning-of-line 1)
2314 (looking-at org-table-hline-regexp))
2315 nil))
2317 (defvar org-table-clean-did-remove-column nil)
2319 (defun org-table-map-tables (function)
2320 "Apply FUNCTION to the start of all tables in the buffer."
2321 (save-excursion
2322 (save-restriction
2323 (widen)
2324 (goto-char (point-min))
2325 (while (re-search-forward org-table-any-line-regexp nil t)
2326 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2327 (beginning-of-line 1)
2328 (if (looking-at org-table-line-regexp)
2329 (save-excursion (funcall function)))
2330 (re-search-forward org-table-any-border-regexp nil 1))))
2331 (message "Mapping tables: done"))
2333 ;; Declare and autoload functions from org-exp.el
2335 (declare-function org-default-export-plist "org-exp")
2336 (declare-function org-infile-export-plist "org-exp")
2337 (declare-function org-get-current-options "org-exp")
2338 (eval-and-compile
2339 (org-autoload "org-exp"
2340 '(org-export org-export-as-ascii org-export-visible
2341 org-insert-export-options-template org-export-as-html-and-open
2342 org-export-as-html-batch org-export-as-html-to-buffer
2343 org-replace-region-by-html org-export-region-as-html
2344 org-export-as-html org-export-icalendar-this-file
2345 org-export-icalendar-all-agenda-files
2346 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2348 ;; Declare and autoload functions from org-exp.el
2350 (eval-and-compile
2351 (org-autoload "org-exp"
2352 '(org-agenda org-agenda-list org-search-view
2353 org-todo-list org-tags-view org-agenda-list-stuck-projects
2354 org-diary org-agenda-to-appt)))
2356 ;; Autoload org-remember
2358 (eval-and-compile
2359 (org-autoload "org-remember"
2360 '(org-remember-insinuate org-remember-annotation
2361 org-remember-apply-template org-remember org-remember-handler)))
2363 ;; Autoload org-clock.el
2366 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2367 (beg end))
2368 (defvar org-clock-marker (make-marker)
2369 "Marker recording the last clock-in.")
2371 (eval-and-compile
2372 (org-autoload
2373 "org-clock"
2374 '(org-clock-in org-clock-out org-clock-cancel
2375 org-clock-goto org-clock-sum org-clock-display
2376 org-remove-clock-overlays org-clock-report
2377 org-clocktable-shift org-dblock-write:clocktable
2378 org-get-clocktable)))
2380 (defun org-clock-update-time-maybe ()
2381 "If this is a CLOCK line, update it and return t.
2382 Otherwise, return nil."
2383 (interactive)
2384 (save-excursion
2385 (beginning-of-line 1)
2386 (skip-chars-forward " \t")
2387 (when (looking-at org-clock-string)
2388 (let ((re (concat "[ \t]*" org-clock-string
2389 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2390 "\\([ \t]*=>.*\\)?"))
2391 ts te h m s)
2392 (if (not (looking-at re))
2394 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2395 (end-of-line 1)
2396 (setq ts (match-string 1)
2397 te (match-string 2))
2398 (setq s (- (time-to-seconds
2399 (apply 'encode-time (org-parse-time-string te)))
2400 (time-to-seconds
2401 (apply 'encode-time (org-parse-time-string ts))))
2402 h (floor (/ s 3600))
2403 s (- s (* 3600 h))
2404 m (floor (/ s 60))
2405 s (- s (* 60 s)))
2406 (insert " => " (format "%2d:%02d" h m))
2407 t)))))
2409 (defun org-check-running-clock ()
2410 "Check if the current buffer contains the running clock.
2411 If yes, offer to stop it and to save the buffer with the changes."
2412 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2413 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2414 (buffer-name))))
2415 (org-clock-out)
2416 (when (y-or-n-p "Save changed buffer?")
2417 (save-buffer))))
2419 (defun org-clocktable-try-shift (dir n)
2420 "Check if this line starts a clock table, if yes, shift the time block."
2421 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2422 (org-clocktable-shift dir n)))
2424 ;; Autoload archiving code
2425 ;; The stuff that is needed for cycling and tags has to be defined here.
2427 (defgroup org-archive nil
2428 "Options concerning archiving in Org-mode."
2429 :tag "Org Archive"
2430 :group 'org-structure)
2432 (defcustom org-archive-location "%s_archive::"
2433 "The location where subtrees should be archived.
2435 Otherwise, the value of this variable is a string, consisting of two
2436 parts, separated by a double-colon.
2438 The first part is a file name - when omitted, archiving happens in the same
2439 file. %s will be replaced by the current file name (without directory part).
2440 Archiving to a different file is useful to keep archived entries from
2441 contributing to the Org-mode Agenda.
2443 The part after the double colon is a headline. The archived entries will be
2444 filed under that headline. When omitted, the subtrees are simply filed away
2445 at the end of the file, as top-level entries.
2447 Here are a few examples:
2448 \"%s_archive::\"
2449 If the current file is Projects.org, archive in file
2450 Projects.org_archive, as top-level trees. This is the default.
2452 \"::* Archived Tasks\"
2453 Archive in the current file, under the top-level headline
2454 \"* Archived Tasks\".
2456 \"~/org/archive.org::\"
2457 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2459 \"basement::** Finished Tasks\"
2460 Archive in file ./basement (relative path), as level 3 trees
2461 below the level 2 heading \"** Finished Tasks\".
2463 You may set this option on a per-file basis by adding to the buffer a
2464 line like
2466 #+ARCHIVE: basement::** Finished Tasks
2468 You may also define it locally for a subtree by setting an ARCHIVE property
2469 in the entry. If such a property is found in an entry, or anywhere up
2470 the hierarchy, it will be used."
2471 :group 'org-archive
2472 :type 'string)
2474 (defcustom org-archive-tag "ARCHIVE"
2475 "The tag that marks a subtree as archived.
2476 An archived subtree does not open during visibility cycling, and does
2477 not contribute to the agenda listings.
2478 After changing this, font-lock must be restarted in the relevant buffers to
2479 get the proper fontification."
2480 :group 'org-archive
2481 :group 'org-keywords
2482 :type 'string)
2484 (defcustom org-agenda-skip-archived-trees t
2485 "Non-nil means, the agenda will skip any items located in archived trees.
2486 An archived tree is a tree marked with the tag ARCHIVE."
2487 :group 'org-archive
2488 :group 'org-agenda-skip
2489 :type 'boolean)
2491 (defcustom org-cycle-open-archived-trees nil
2492 "Non-nil means, `org-cycle' will open archived trees.
2493 An archived tree is a tree marked with the tag ARCHIVE.
2494 When nil, archived trees will stay folded. You can still open them with
2495 normal outline commands like `show-all', but not with the cycling commands."
2496 :group 'org-archive
2497 :group 'org-cycle
2498 :type 'boolean)
2500 (defcustom org-sparse-tree-open-archived-trees nil
2501 "Non-nil means sparse tree construction shows matches in archived trees.
2502 When nil, matches in these trees are highlighted, but the trees are kept in
2503 collapsed state."
2504 :group 'org-archive
2505 :group 'org-sparse-trees
2506 :type 'boolean)
2508 (defun org-cycle-hide-archived-subtrees (state)
2509 "Re-hide all archived subtrees after a visibility state change."
2510 (when (and (not org-cycle-open-archived-trees)
2511 (not (memq state '(overview folded))))
2512 (save-excursion
2513 (let* ((globalp (memq state '(contents all)))
2514 (beg (if globalp (point-min) (point)))
2515 (end (if globalp (point-max) (org-end-of-subtree t))))
2516 (org-hide-archived-subtrees beg end)
2517 (goto-char beg)
2518 (if (looking-at (concat ".*:" org-archive-tag ":"))
2519 (message "%s" (substitute-command-keys
2520 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2522 (defun org-force-cycle-archived ()
2523 "Cycle subtree even if it is archived."
2524 (interactive)
2525 (setq this-command 'org-cycle)
2526 (let ((org-cycle-open-archived-trees t))
2527 (call-interactively 'org-cycle)))
2529 (defun org-hide-archived-subtrees (beg end)
2530 "Re-hide all archived subtrees after a visibility state change."
2531 (save-excursion
2532 (let* ((re (concat ":" org-archive-tag ":")))
2533 (goto-char beg)
2534 (while (re-search-forward re end t)
2535 (and (org-on-heading-p) (hide-subtree))
2536 (org-end-of-subtree t)))))
2538 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2540 (eval-and-compile
2541 (org-autoload "org-archive"
2542 '(org-add-archive-files org-archive-subtree
2543 org-archive-to-archive-sibling org-toggle-archive-tag)))
2545 ;; Autoload Column View Code
2547 (declare-function org-columns-number-to-string "org-colview")
2548 (declare-function org-columns-get-format-and-top-level "org-colview")
2549 (declare-function org-columns-compute "org-colview")
2551 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2552 '(org-columns-number-to-string org-columns-get-format-and-top-level
2553 org-columns-compute org-agenda-columns org-columns-remove-overlays
2554 org-columns org-insert-columns-dblock))
2556 ;;; Variables for pre-computed regular expressions, all buffer local
2558 (defvar org-drawer-regexp nil
2559 "Matches first line of a hidden block.")
2560 (make-variable-buffer-local 'org-drawer-regexp)
2561 (defvar org-todo-regexp nil
2562 "Matches any of the TODO state keywords.")
2563 (make-variable-buffer-local 'org-todo-regexp)
2564 (defvar org-not-done-regexp nil
2565 "Matches any of the TODO state keywords except the last one.")
2566 (make-variable-buffer-local 'org-not-done-regexp)
2567 (defvar org-todo-line-regexp nil
2568 "Matches a headline and puts TODO state into group 2 if present.")
2569 (make-variable-buffer-local 'org-todo-line-regexp)
2570 (defvar org-complex-heading-regexp nil
2571 "Matches a headline and puts everything into groups:
2572 group 1: the stars
2573 group 2: The todo keyword, maybe
2574 group 3: Priority cookie
2575 group 4: True headline
2576 group 5: Tags")
2577 (make-variable-buffer-local 'org-complex-heading-regexp)
2578 (defvar org-todo-line-tags-regexp nil
2579 "Matches a headline and puts TODO state into group 2 if present.
2580 Also put tags into group 4 if tags are present.")
2581 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2582 (defvar org-nl-done-regexp nil
2583 "Matches newline followed by a headline with the DONE keyword.")
2584 (make-variable-buffer-local 'org-nl-done-regexp)
2585 (defvar org-looking-at-done-regexp nil
2586 "Matches the DONE keyword a point.")
2587 (make-variable-buffer-local 'org-looking-at-done-regexp)
2588 (defvar org-ds-keyword-length 12
2589 "Maximum length of the Deadline and SCHEDULED keywords.")
2590 (make-variable-buffer-local 'org-ds-keyword-length)
2591 (defvar org-deadline-regexp nil
2592 "Matches the DEADLINE keyword.")
2593 (make-variable-buffer-local 'org-deadline-regexp)
2594 (defvar org-deadline-time-regexp nil
2595 "Matches the DEADLINE keyword together with a time stamp.")
2596 (make-variable-buffer-local 'org-deadline-time-regexp)
2597 (defvar org-deadline-line-regexp nil
2598 "Matches the DEADLINE keyword and the rest of the line.")
2599 (make-variable-buffer-local 'org-deadline-line-regexp)
2600 (defvar org-scheduled-regexp nil
2601 "Matches the SCHEDULED keyword.")
2602 (make-variable-buffer-local 'org-scheduled-regexp)
2603 (defvar org-scheduled-time-regexp nil
2604 "Matches the SCHEDULED keyword together with a time stamp.")
2605 (make-variable-buffer-local 'org-scheduled-time-regexp)
2606 (defvar org-closed-time-regexp nil
2607 "Matches the CLOSED keyword together with a time stamp.")
2608 (make-variable-buffer-local 'org-closed-time-regexp)
2610 (defvar org-keyword-time-regexp nil
2611 "Matches any of the 4 keywords, together with the time stamp.")
2612 (make-variable-buffer-local 'org-keyword-time-regexp)
2613 (defvar org-keyword-time-not-clock-regexp nil
2614 "Matches any of the 3 keywords, together with the time stamp.")
2615 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2616 (defvar org-maybe-keyword-time-regexp nil
2617 "Matches a timestamp, possibly preceeded by a keyword.")
2618 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2619 (defvar org-planning-or-clock-line-re nil
2620 "Matches a line with planning or clock info.")
2621 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2623 (defconst org-plain-time-of-day-regexp
2624 (concat
2625 "\\(\\<[012]?[0-9]"
2626 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2627 "\\(--?"
2628 "\\(\\<[012]?[0-9]"
2629 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2630 "\\)?")
2631 "Regular expression to match a plain time or time range.
2632 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2633 groups carry important information:
2634 0 the full match
2635 1 the first time, range or not
2636 8 the second time, if it is a range.")
2638 (defconst org-plain-time-extension-regexp
2639 (concat
2640 "\\(\\<[012]?[0-9]"
2641 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2642 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2643 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2644 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2645 groups carry important information:
2646 0 the full match
2647 7 hours of duration
2648 9 minutes of duration")
2650 (defconst org-stamp-time-of-day-regexp
2651 (concat
2652 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2653 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2654 "\\(--?"
2655 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2656 "Regular expression to match a timestamp time or time range.
2657 After a match, the following groups carry important information:
2658 0 the full match
2659 1 date plus weekday, for backreferencing to make sure both times on same day
2660 2 the first time, range or not
2661 4 the second time, if it is a range.")
2663 (defconst org-startup-options
2664 '(("fold" org-startup-folded t)
2665 ("overview" org-startup-folded t)
2666 ("nofold" org-startup-folded nil)
2667 ("showall" org-startup-folded nil)
2668 ("content" org-startup-folded content)
2669 ("hidestars" org-hide-leading-stars t)
2670 ("showstars" org-hide-leading-stars nil)
2671 ("odd" org-odd-levels-only t)
2672 ("oddeven" org-odd-levels-only nil)
2673 ("align" org-startup-align-all-tables t)
2674 ("noalign" org-startup-align-all-tables nil)
2675 ("customtime" org-display-custom-times t)
2676 ("logdone" org-log-done time)
2677 ("lognotedone" org-log-done note)
2678 ("nologdone" org-log-done nil)
2679 ("lognoteclock-out" org-log-note-clock-out t)
2680 ("nolognoteclock-out" org-log-note-clock-out nil)
2681 ("logrepeat" org-log-repeat state)
2682 ("lognoterepeat" org-log-repeat note)
2683 ("nologrepeat" org-log-repeat nil)
2684 ("constcgs" constants-unit-system cgs)
2685 ("constSI" constants-unit-system SI))
2686 "Variable associated with STARTUP options for org-mode.
2687 Each element is a list of three items: The startup options as written
2688 in the #+STARTUP line, the corresponding variable, and the value to
2689 set this variable to if the option is found. An optional forth element PUSH
2690 means to push this value onto the list in the variable.")
2692 (defun org-set-regexps-and-options ()
2693 "Precompute regular expressions for current buffer."
2694 (when (org-mode-p)
2695 (org-set-local 'org-todo-kwd-alist nil)
2696 (org-set-local 'org-todo-key-alist nil)
2697 (org-set-local 'org-todo-key-trigger nil)
2698 (org-set-local 'org-todo-keywords-1 nil)
2699 (org-set-local 'org-done-keywords nil)
2700 (org-set-local 'org-todo-heads nil)
2701 (org-set-local 'org-todo-sets nil)
2702 (org-set-local 'org-todo-log-states nil)
2703 (let ((re (org-make-options-regexp
2704 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2705 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2706 "CONSTANTS" "PROPERTY" "DRAWERS")))
2707 (splitre "[ \t]+")
2708 kwds kws0 kwsa key log value cat arch tags const links hw dws
2709 tail sep kws1 prio props drawers)
2710 (save-excursion
2711 (save-restriction
2712 (widen)
2713 (goto-char (point-min))
2714 (while (re-search-forward re nil t)
2715 (setq key (match-string 1) value (org-match-string-no-properties 2))
2716 (cond
2717 ((equal key "CATEGORY")
2718 (if (string-match "[ \t]+$" value)
2719 (setq value (replace-match "" t t value)))
2720 (setq cat value))
2721 ((member key '("SEQ_TODO" "TODO"))
2722 (push (cons 'sequence (org-split-string value splitre)) kwds))
2723 ((equal key "TYP_TODO")
2724 (push (cons 'type (org-split-string value splitre)) kwds))
2725 ((equal key "TAGS")
2726 (setq tags (append tags (org-split-string value splitre))))
2727 ((equal key "COLUMNS")
2728 (org-set-local 'org-columns-default-format value))
2729 ((equal key "LINK")
2730 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2731 (push (cons (match-string 1 value)
2732 (org-trim (match-string 2 value)))
2733 links)))
2734 ((equal key "PRIORITIES")
2735 (setq prio (org-split-string value " +")))
2736 ((equal key "PROPERTY")
2737 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2738 (push (cons (match-string 1 value) (match-string 2 value))
2739 props)))
2740 ((equal key "DRAWERS")
2741 (setq drawers (org-split-string value splitre)))
2742 ((equal key "CONSTANTS")
2743 (setq const (append const (org-split-string value splitre))))
2744 ((equal key "STARTUP")
2745 (let ((opts (org-split-string value splitre))
2746 l var val)
2747 (while (setq l (pop opts))
2748 (when (setq l (assoc l org-startup-options))
2749 (setq var (nth 1 l) val (nth 2 l))
2750 (if (not (nth 3 l))
2751 (set (make-local-variable var) val)
2752 (if (not (listp (symbol-value var)))
2753 (set (make-local-variable var) nil))
2754 (set (make-local-variable var) (symbol-value var))
2755 (add-to-list var val))))))
2756 ((equal key "ARCHIVE")
2757 (string-match " *$" value)
2758 (setq arch (replace-match "" t t value))
2759 (remove-text-properties 0 (length arch)
2760 '(face t fontified t) arch)))
2762 (when cat
2763 (org-set-local 'org-category (intern cat))
2764 (push (cons "CATEGORY" cat) props))
2765 (when prio
2766 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2767 (setq prio (mapcar 'string-to-char prio))
2768 (org-set-local 'org-highest-priority (nth 0 prio))
2769 (org-set-local 'org-lowest-priority (nth 1 prio))
2770 (org-set-local 'org-default-priority (nth 2 prio)))
2771 (and props (org-set-local 'org-local-properties (nreverse props)))
2772 (and drawers (org-set-local 'org-drawers drawers))
2773 (and arch (org-set-local 'org-archive-location arch))
2774 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2775 ;; Process the TODO keywords
2776 (unless kwds
2777 ;; Use the global values as if they had been given locally.
2778 (setq kwds (default-value 'org-todo-keywords))
2779 (if (stringp (car kwds))
2780 (setq kwds (list (cons org-todo-interpretation
2781 (default-value 'org-todo-keywords)))))
2782 (setq kwds (reverse kwds)))
2783 (setq kwds (nreverse kwds))
2784 (let (inter kws kw)
2785 (while (setq kws (pop kwds))
2786 (setq inter (pop kws) sep (member "|" kws)
2787 kws0 (delete "|" (copy-sequence kws))
2788 kwsa nil
2789 kws1 (mapcar
2790 (lambda (x)
2791 ;; 1 2
2792 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2793 (progn
2794 (setq kw (match-string 1 x)
2795 key (and (match-end 2) (match-string 2 x))
2796 log (org-extract-log-state-settings x))
2797 (push (cons kw (and key (string-to-char key))) kwsa)
2798 (and log (push log org-todo-log-states))
2800 (error "Invalid TODO keyword %s" x)))
2801 kws0)
2802 kwsa (if kwsa (append '((:startgroup))
2803 (nreverse kwsa)
2804 '((:endgroup))))
2805 hw (car kws1)
2806 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2807 tail (list inter hw (car dws) (org-last dws)))
2808 (add-to-list 'org-todo-heads hw 'append)
2809 (push kws1 org-todo-sets)
2810 (setq org-done-keywords (append org-done-keywords dws nil))
2811 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2812 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2813 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2814 (setq org-todo-sets (nreverse org-todo-sets)
2815 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2816 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2817 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2818 ;; Process the constants
2819 (when const
2820 (let (e cst)
2821 (while (setq e (pop const))
2822 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2823 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2824 (setq org-table-formula-constants-local cst)))
2826 ;; Process the tags.
2827 (when tags
2828 (let (e tgs)
2829 (while (setq e (pop tags))
2830 (cond
2831 ((equal e "{") (push '(:startgroup) tgs))
2832 ((equal e "}") (push '(:endgroup) tgs))
2833 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2834 (push (cons (match-string 1 e)
2835 (string-to-char (match-string 2 e)))
2836 tgs))
2837 (t (push (list e) tgs))))
2838 (org-set-local 'org-tag-alist nil)
2839 (while (setq e (pop tgs))
2840 (or (and (stringp (car e))
2841 (assoc (car e) org-tag-alist))
2842 (push e org-tag-alist))))))
2844 ;; Compute the regular expressions and other local variables
2845 (if (not org-done-keywords)
2846 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2847 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2848 (length org-scheduled-string)
2849 (length org-clock-string)
2850 (length org-closed-string)))
2851 org-drawer-regexp
2852 (concat "^[ \t]*:\\("
2853 (mapconcat 'regexp-quote org-drawers "\\|")
2854 "\\):[ \t]*$")
2855 org-not-done-keywords
2856 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2857 org-todo-regexp
2858 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2859 "\\|") "\\)\\>")
2860 org-not-done-regexp
2861 (concat "\\<\\("
2862 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2863 "\\)\\>")
2864 org-todo-line-regexp
2865 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2866 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2867 "\\)\\>\\)?[ \t]*\\(.*\\)")
2868 org-complex-heading-regexp
2869 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2870 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2871 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2872 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2873 org-nl-done-regexp
2874 (concat "\n\\*+[ \t]+"
2875 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2876 "\\)" "\\>")
2877 org-todo-line-tags-regexp
2878 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2879 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2880 (org-re
2881 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2882 org-looking-at-done-regexp
2883 (concat "^" "\\(?:"
2884 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2885 "\\>")
2886 org-deadline-regexp (concat "\\<" org-deadline-string)
2887 org-deadline-time-regexp
2888 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2889 org-deadline-line-regexp
2890 (concat "\\<\\(" org-deadline-string "\\).*")
2891 org-scheduled-regexp
2892 (concat "\\<" org-scheduled-string)
2893 org-scheduled-time-regexp
2894 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2895 org-closed-time-regexp
2896 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2897 org-keyword-time-regexp
2898 (concat "\\<\\(" org-scheduled-string
2899 "\\|" org-deadline-string
2900 "\\|" org-closed-string
2901 "\\|" org-clock-string "\\)"
2902 " *[[<]\\([^]>]+\\)[]>]")
2903 org-keyword-time-not-clock-regexp
2904 (concat "\\<\\(" org-scheduled-string
2905 "\\|" org-deadline-string
2906 "\\|" org-closed-string
2907 "\\)"
2908 " *[[<]\\([^]>]+\\)[]>]")
2909 org-maybe-keyword-time-regexp
2910 (concat "\\(\\<\\(" org-scheduled-string
2911 "\\|" org-deadline-string
2912 "\\|" org-closed-string
2913 "\\|" org-clock-string "\\)\\)?"
2914 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2915 org-planning-or-clock-line-re
2916 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2917 "\\|" org-deadline-string
2918 "\\|" org-closed-string "\\|" org-clock-string
2919 "\\)\\>\\)")
2921 (org-compute-latex-and-specials-regexp)
2922 (org-set-font-lock-defaults)))
2924 (defun org-extract-log-state-settings (x)
2925 "Extract the log state setting from a TODO keyword string.
2926 This will extract info from a string like \"WAIT(w@/!)\"."
2927 (let (kw key log1 log2)
2928 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2929 (setq kw (match-string 1 x)
2930 key (and (match-end 2) (match-string 2 x))
2931 log1 (and (match-end 3) (match-string 3 x))
2932 log2 (and (match-end 4) (match-string 4 x)))
2933 (and (or log1 log2)
2934 (list kw
2935 (and log1 (if (equal log1 "!") 'time 'note))
2936 (and log2 (if (equal log2 "!") 'time 'note)))))))
2938 (defun org-remove-keyword-keys (list)
2939 "Remove a pair of parenthesis at the end of each string in LIST."
2940 (mapcar (lambda (x)
2941 (if (string-match "(.*)$" x)
2942 (substring x 0 (match-beginning 0))
2944 list))
2946 ;; FIXME: this could be done much better, using second characters etc.
2947 (defun org-assign-fast-keys (alist)
2948 "Assign fast keys to a keyword-key alist.
2949 Respect keys that are already there."
2950 (let (new e k c c1 c2 (char ?a))
2951 (while (setq e (pop alist))
2952 (cond
2953 ((equal e '(:startgroup)) (push e new))
2954 ((equal e '(:endgroup)) (push e new))
2956 (setq k (car e) c2 nil)
2957 (if (cdr e)
2958 (setq c (cdr e))
2959 ;; automatically assign a character.
2960 (setq c1 (string-to-char
2961 (downcase (substring
2962 k (if (= (string-to-char k) ?@) 1 0)))))
2963 (if (or (rassoc c1 new) (rassoc c1 alist))
2964 (while (or (rassoc char new) (rassoc char alist))
2965 (setq char (1+ char)))
2966 (setq c2 c1))
2967 (setq c (or c2 char)))
2968 (push (cons k c) new))))
2969 (nreverse new)))
2971 ;;; Some variables used in various places
2973 (defvar org-window-configuration nil
2974 "Used in various places to store a window configuration.")
2975 (defvar org-finish-function nil
2976 "Function to be called when `C-c C-c' is used.
2977 This is for getting out of special buffers like remember.")
2980 ;; FIXME: Occasionally check by commenting these, to make sure
2981 ;; no other functions uses these, forgetting to let-bind them.
2982 (defvar entry)
2983 (defvar state)
2984 (defvar last-state)
2985 (defvar date)
2986 (defvar description)
2988 ;; Defined somewhere in this file, but used before definition.
2989 (defvar org-html-entities)
2990 (defvar org-struct-menu)
2991 (defvar org-org-menu)
2992 (defvar org-tbl-menu)
2993 (defvar org-agenda-keymap)
2995 ;;;; Define the Org-mode
2997 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2998 (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."))
3001 ;; We use a before-change function to check if a table might need
3002 ;; an update.
3003 (defvar org-table-may-need-update t
3004 "Indicates that a table might need an update.
3005 This variable is set by `org-before-change-function'.
3006 `org-table-align' sets it back to nil.")
3007 (defun org-before-change-function (beg end)
3008 "Every change indicates that a table might need an update."
3009 (setq org-table-may-need-update t))
3010 (defvar org-mode-map)
3011 (defvar org-mode-hook nil)
3012 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3013 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3014 (defvar org-table-buffer-is-an nil)
3015 (defconst org-outline-regexp "\\*+ ")
3017 ;;;###autoload
3018 (define-derived-mode org-mode outline-mode "Org"
3019 "Outline-based notes management and organizer, alias
3020 \"Carsten's outline-mode for keeping track of everything.\"
3022 Org-mode develops organizational tasks around a NOTES file which
3023 contains information about projects as plain text. Org-mode is
3024 implemented on top of outline-mode, which is ideal to keep the content
3025 of large files well structured. It supports ToDo items, deadlines and
3026 time stamps, which magically appear in the diary listing of the Emacs
3027 calendar. Tables are easily created with a built-in table editor.
3028 Plain text URL-like links connect to websites, emails (VM), Usenet
3029 messages (Gnus), BBDB entries, and any files related to the project.
3030 For printing and sharing of notes, an Org-mode file (or a part of it)
3031 can be exported as a structured ASCII or HTML file.
3033 The following commands are available:
3035 \\{org-mode-map}"
3037 ;; Get rid of Outline menus, they are not needed
3038 ;; Need to do this here because define-derived-mode sets up
3039 ;; the keymap so late. Still, it is a waste to call this each time
3040 ;; we switch another buffer into org-mode.
3041 (if (featurep 'xemacs)
3042 (when (boundp 'outline-mode-menu-heading)
3043 ;; Assume this is Greg's port, it used easymenu
3044 (easy-menu-remove outline-mode-menu-heading)
3045 (easy-menu-remove outline-mode-menu-show)
3046 (easy-menu-remove outline-mode-menu-hide))
3047 (define-key org-mode-map [menu-bar headings] 'undefined)
3048 (define-key org-mode-map [menu-bar hide] 'undefined)
3049 (define-key org-mode-map [menu-bar show] 'undefined))
3051 (org-load-modules-maybe)
3052 (easy-menu-add org-org-menu)
3053 (easy-menu-add org-tbl-menu)
3054 (org-install-agenda-files-menu)
3055 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3056 (org-add-to-invisibility-spec '(org-cwidth))
3057 (when (featurep 'xemacs)
3058 (org-set-local 'line-move-ignore-invisible t))
3059 (org-set-local 'outline-regexp org-outline-regexp)
3060 (org-set-local 'outline-level 'org-outline-level)
3061 (when (and org-ellipsis
3062 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3063 (fboundp 'make-glyph-code))
3064 (unless org-display-table
3065 (setq org-display-table (make-display-table)))
3066 (set-display-table-slot
3067 org-display-table 4
3068 (vconcat (mapcar
3069 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3070 org-ellipsis)))
3071 (if (stringp org-ellipsis) org-ellipsis "..."))))
3072 (setq buffer-display-table org-display-table))
3073 (org-set-regexps-and-options)
3074 ;; Calc embedded
3075 (org-set-local 'calc-embedded-open-mode "# ")
3076 (modify-syntax-entry ?# "<")
3077 (modify-syntax-entry ?@ "w")
3078 (if org-startup-truncated (setq truncate-lines t))
3079 (org-set-local 'font-lock-unfontify-region-function
3080 'org-unfontify-region)
3081 ;; Activate before-change-function
3082 (org-set-local 'org-table-may-need-update t)
3083 (org-add-hook 'before-change-functions 'org-before-change-function nil
3084 'local)
3085 ;; Check for running clock before killing a buffer
3086 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3087 ;; Paragraphs and auto-filling
3088 (org-set-autofill-regexps)
3089 (setq indent-line-function 'org-indent-line-function)
3090 (org-update-radio-target-regexp)
3092 ;; Comment characters
3093 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3094 (org-set-local 'comment-padding " ")
3096 ;; Align options lines
3097 (org-set-local
3098 'align-mode-rules-list
3099 '((org-in-buffer-settings
3100 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3101 (modes . '(org-mode)))))
3103 ;; Imenu
3104 (org-set-local 'imenu-create-index-function
3105 'org-imenu-get-tree)
3107 ;; Make isearch reveal context
3108 (if (or (featurep 'xemacs)
3109 (not (boundp 'outline-isearch-open-invisible-function)))
3110 ;; Emacs 21 and XEmacs make use of the hook
3111 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3112 ;; Emacs 22 deals with this through a special variable
3113 (org-set-local 'outline-isearch-open-invisible-function
3114 (lambda (&rest ignore) (org-show-context 'isearch))))
3116 ;; If empty file that did not turn on org-mode automatically, make it to.
3117 (if (and org-insert-mode-line-in-empty-file
3118 (interactive-p)
3119 (= (point-min) (point-max)))
3120 (insert "# -*- mode: org -*-\n\n"))
3122 (unless org-inhibit-startup
3123 (when org-startup-align-all-tables
3124 (let ((bmp (buffer-modified-p)))
3125 (org-table-map-tables 'org-table-align)
3126 (set-buffer-modified-p bmp)))
3127 (org-cycle-hide-drawers 'all)
3128 (cond
3129 ((eq org-startup-folded t)
3130 (org-cycle '(4)))
3131 ((eq org-startup-folded 'content)
3132 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3133 (org-cycle '(4)) (org-cycle '(4)))))))
3135 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3137 (defun org-current-time ()
3138 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3139 (if (> (car org-time-stamp-rounding-minutes) 1)
3140 (let ((r (car org-time-stamp-rounding-minutes))
3141 (time (decode-time)))
3142 (apply 'encode-time
3143 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3144 (nthcdr 2 time))))
3145 (current-time)))
3147 ;;;; Font-Lock stuff, including the activators
3149 (defvar org-mouse-map (make-sparse-keymap))
3150 (org-defkey org-mouse-map
3151 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3152 (org-defkey org-mouse-map
3153 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3154 (when org-mouse-1-follows-link
3155 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3156 (when org-tab-follows-link
3157 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3158 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3159 (when org-return-follows-link
3160 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3161 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3163 (require 'font-lock)
3165 (defconst org-non-link-chars "]\t\n\r<>")
3166 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3167 "shell" "elisp"))
3168 (defvar org-link-types-re nil
3169 "Matches a link that has a url-like prefix like \"http:\"")
3170 (defvar org-link-re-with-space nil
3171 "Matches a link with spaces, optional angular brackets around it.")
3172 (defvar org-link-re-with-space2 nil
3173 "Matches a link with spaces, optional angular brackets around it.")
3174 (defvar org-angle-link-re nil
3175 "Matches link with angular brackets, spaces are allowed.")
3176 (defvar org-plain-link-re nil
3177 "Matches plain link, without spaces.")
3178 (defvar org-bracket-link-regexp nil
3179 "Matches a link in double brackets.")
3180 (defvar org-bracket-link-analytic-regexp nil
3181 "Regular expression used to analyze links.
3182 Here is what the match groups contain after a match:
3183 1: http:
3184 2: http
3185 3: path
3186 4: [desc]
3187 5: desc")
3188 (defvar org-any-link-re nil
3189 "Regular expression matching any link.")
3191 (defun org-make-link-regexps ()
3192 "Update the link regular expressions.
3193 This should be called after the variable `org-link-types' has changed."
3194 (setq org-link-types-re
3195 (concat
3196 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3197 org-link-re-with-space
3198 (concat
3199 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3200 "\\([^" org-non-link-chars " ]"
3201 "[^" org-non-link-chars "]*"
3202 "[^" org-non-link-chars " ]\\)>?")
3203 org-link-re-with-space2
3204 (concat
3205 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3206 "\\([^" org-non-link-chars " ]"
3207 "[^]\t\n\r]*"
3208 "[^" org-non-link-chars " ]\\)>?")
3209 org-angle-link-re
3210 (concat
3211 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3212 "\\([^" org-non-link-chars " ]"
3213 "[^" org-non-link-chars "]*"
3214 "\\)>")
3215 org-plain-link-re
3216 (concat
3217 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3218 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3219 org-bracket-link-regexp
3220 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3221 org-bracket-link-analytic-regexp
3222 (concat
3223 "\\[\\["
3224 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3225 "\\([^]]+\\)"
3226 "\\]"
3227 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3228 "\\]")
3229 org-any-link-re
3230 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3231 org-angle-link-re "\\)\\|\\("
3232 org-plain-link-re "\\)")))
3234 (org-make-link-regexps)
3236 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3237 "Regular expression for fast time stamp matching.")
3238 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3239 "Regular expression for fast time stamp matching.")
3240 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3241 "Regular expression matching time strings for analysis.
3242 This one does not require the space after the date, so it can be used
3243 on a string that terminates immediately after the date.")
3244 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3245 "Regular expression matching time strings for analysis.")
3246 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3247 "Regular expression matching time stamps, with groups.")
3248 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3249 "Regular expression matching time stamps (also [..]), with groups.")
3250 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3251 "Regular expression matching a time stamp range.")
3252 (defconst org-tr-regexp-both
3253 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3254 "Regular expression matching a time stamp range.")
3255 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3256 org-ts-regexp "\\)?")
3257 "Regular expression matching a time stamp or time stamp range.")
3258 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3259 org-ts-regexp-both "\\)?")
3260 "Regular expression matching a time stamp or time stamp range.
3261 The time stamps may be either active or inactive.")
3263 (defvar org-emph-face nil)
3265 (defun org-do-emphasis-faces (limit)
3266 "Run through the buffer and add overlays to links."
3267 (let (rtn)
3268 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3269 (if (not (= (char-after (match-beginning 3))
3270 (char-after (match-beginning 4))))
3271 (progn
3272 (setq rtn t)
3273 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3274 'face
3275 (nth 1 (assoc (match-string 3)
3276 org-emphasis-alist)))
3277 (add-text-properties (match-beginning 2) (match-end 2)
3278 '(font-lock-multiline t))
3279 (when org-hide-emphasis-markers
3280 (add-text-properties (match-end 4) (match-beginning 5)
3281 '(invisible org-link))
3282 (add-text-properties (match-beginning 3) (match-end 3)
3283 '(invisible org-link)))))
3284 (backward-char 1))
3285 rtn))
3287 (defun org-emphasize (&optional char)
3288 "Insert or change an emphasis, i.e. a font like bold or italic.
3289 If there is an active region, change that region to a new emphasis.
3290 If there is no region, just insert the marker characters and position
3291 the cursor between them.
3292 CHAR should be either the marker character, or the first character of the
3293 HTML tag associated with that emphasis. If CHAR is a space, the means
3294 to remove the emphasis of the selected region.
3295 If char is not given (for example in an interactive call) it
3296 will be prompted for."
3297 (interactive)
3298 (let ((eal org-emphasis-alist) e det
3299 (erc org-emphasis-regexp-components)
3300 (prompt "")
3301 (string "") beg end move tag c s)
3302 (if (org-region-active-p)
3303 (setq beg (region-beginning) end (region-end)
3304 string (buffer-substring beg end))
3305 (setq move t))
3307 (while (setq e (pop eal))
3308 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3309 c (aref tag 0))
3310 (push (cons c (string-to-char (car e))) det)
3311 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3312 (substring tag 1)))))
3313 (unless char
3314 (message "%s" (concat "Emphasis marker or tag:" prompt))
3315 (setq char (read-char-exclusive)))
3316 (setq char (or (cdr (assoc char det)) char))
3317 (if (equal char ?\ )
3318 (setq s "" move nil)
3319 (unless (assoc (char-to-string char) org-emphasis-alist)
3320 (error "No such emphasis marker: \"%c\"" char))
3321 (setq s (char-to-string char)))
3322 (while (and (> (length string) 1)
3323 (equal (substring string 0 1) (substring string -1))
3324 (assoc (substring string 0 1) org-emphasis-alist))
3325 (setq string (substring string 1 -1)))
3326 (setq string (concat s string s))
3327 (if beg (delete-region beg end))
3328 (unless (or (bolp)
3329 (string-match (concat "[" (nth 0 erc) "\n]")
3330 (char-to-string (char-before (point)))))
3331 (insert " "))
3332 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3333 (char-to-string (char-after (point))))
3334 (insert " ") (backward-char 1))
3335 (insert string)
3336 (and move (backward-char 1))))
3338 (defconst org-nonsticky-props
3339 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3342 (defun org-activate-plain-links (limit)
3343 "Run through the buffer and add overlays to links."
3344 (catch 'exit
3345 (let (f)
3346 (while (re-search-forward org-plain-link-re limit t)
3347 (setq f (get-text-property (match-beginning 0) 'face))
3348 (if (or (eq f 'org-tag)
3349 (and (listp f) (memq 'org-tag f)))
3351 (add-text-properties (match-beginning 0) (match-end 0)
3352 (list 'mouse-face 'highlight
3353 'rear-nonsticky org-nonsticky-props
3354 'keymap org-mouse-map
3356 (throw 'exit t))))))
3358 (defun org-activate-code (limit)
3359 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3360 (unless (get-text-property (match-beginning 1) 'face)
3361 (remove-text-properties (match-beginning 0) (match-end 0)
3362 '(display t invisible t intangible t))
3363 t)))
3365 (defun org-activate-angle-links (limit)
3366 "Run through the buffer and add overlays to links."
3367 (if (re-search-forward org-angle-link-re limit t)
3368 (progn
3369 (add-text-properties (match-beginning 0) (match-end 0)
3370 (list 'mouse-face 'highlight
3371 'rear-nonsticky org-nonsticky-props
3372 'keymap org-mouse-map
3374 t)))
3376 (defun org-activate-bracket-links (limit)
3377 "Run through the buffer and add overlays to bracketed links."
3378 (if (re-search-forward org-bracket-link-regexp limit t)
3379 (let* ((help (concat "LINK: "
3380 (org-match-string-no-properties 1)))
3381 ;; FIXME: above we should remove the escapes.
3382 ;; but that requires another match, protecting match data,
3383 ;; a lot of overhead for font-lock.
3384 (ip (org-maybe-intangible
3385 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3386 'keymap org-mouse-map 'mouse-face 'highlight
3387 'font-lock-multiline t 'help-echo help)))
3388 (vp (list 'rear-nonsticky org-nonsticky-props
3389 'keymap org-mouse-map 'mouse-face 'highlight
3390 ' font-lock-multiline t 'help-echo help)))
3391 ;; We need to remove the invisible property here. Table narrowing
3392 ;; may have made some of this invisible.
3393 (remove-text-properties (match-beginning 0) (match-end 0)
3394 '(invisible nil))
3395 (if (match-end 3)
3396 (progn
3397 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3398 (add-text-properties (match-beginning 3) (match-end 3) vp)
3399 (add-text-properties (match-end 3) (match-end 0) ip))
3400 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3401 (add-text-properties (match-beginning 1) (match-end 1) vp)
3402 (add-text-properties (match-end 1) (match-end 0) ip))
3403 t)))
3405 (defun org-activate-dates (limit)
3406 "Run through the buffer and add overlays to dates."
3407 (if (re-search-forward org-tsr-regexp-both limit t)
3408 (progn
3409 (add-text-properties (match-beginning 0) (match-end 0)
3410 (list 'mouse-face 'highlight
3411 'rear-nonsticky org-nonsticky-props
3412 'keymap org-mouse-map))
3413 (when org-display-custom-times
3414 (if (match-end 3)
3415 (org-display-custom-time (match-beginning 3) (match-end 3)))
3416 (org-display-custom-time (match-beginning 1) (match-end 1)))
3417 t)))
3419 (defvar org-target-link-regexp nil
3420 "Regular expression matching radio targets in plain text.")
3421 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3422 "Regular expression matching a link target.")
3423 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3424 "Regular expression matching a radio target.")
3425 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3426 "Regular expression matching any target.")
3428 (defun org-activate-target-links (limit)
3429 "Run through the buffer and add overlays to target matches."
3430 (when org-target-link-regexp
3431 (let ((case-fold-search t))
3432 (if (re-search-forward org-target-link-regexp limit t)
3433 (progn
3434 (add-text-properties (match-beginning 0) (match-end 0)
3435 (list 'mouse-face 'highlight
3436 'rear-nonsticky org-nonsticky-props
3437 'keymap org-mouse-map
3438 'help-echo "Radio target link"
3439 'org-linked-text t))
3440 t)))))
3442 (defun org-update-radio-target-regexp ()
3443 "Find all radio targets in this file and update the regular expression."
3444 (interactive)
3445 (when (memq 'radio org-activate-links)
3446 (setq org-target-link-regexp
3447 (org-make-target-link-regexp (org-all-targets 'radio)))
3448 (org-restart-font-lock)))
3450 (defun org-hide-wide-columns (limit)
3451 (let (s e)
3452 (setq s (text-property-any (point) (or limit (point-max))
3453 'org-cwidth t))
3454 (when s
3455 (setq e (next-single-property-change s 'org-cwidth))
3456 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3457 (goto-char e)
3458 t)))
3460 (defvar org-latex-and-specials-regexp nil
3461 "Regular expression for highlighting export special stuff.")
3462 (defvar org-match-substring-regexp)
3463 (defvar org-match-substring-with-braces-regexp)
3464 (defvar org-export-html-special-string-regexps)
3466 (defun org-compute-latex-and-specials-regexp ()
3467 "Compute regular expression for stuff treated specially by exporters."
3468 (if (not org-highlight-latex-fragments-and-specials)
3469 (org-set-local 'org-latex-and-specials-regexp nil)
3470 (require 'org-exp)
3471 (let*
3472 ((matchers (plist-get org-format-latex-options :matchers))
3473 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3474 org-latex-regexps)))
3475 (options (org-combine-plists (org-default-export-plist)
3476 (org-infile-export-plist)))
3477 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3478 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3479 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3480 (org-export-html-expand (plist-get options :expand-quoted-html))
3481 (org-export-with-special-strings (plist-get options :special-strings))
3482 (re-sub
3483 (cond
3484 ((equal org-export-with-sub-superscripts '{})
3485 (list org-match-substring-with-braces-regexp))
3486 (org-export-with-sub-superscripts
3487 (list org-match-substring-regexp))
3488 (t nil)))
3489 (re-latex
3490 (if org-export-with-LaTeX-fragments
3491 (mapcar (lambda (x) (nth 1 x)) latexs)))
3492 (re-macros
3493 (if org-export-with-TeX-macros
3494 (list (concat "\\\\"
3495 (regexp-opt
3496 (append (mapcar 'car org-html-entities)
3497 (if (boundp 'org-latex-entities)
3498 org-latex-entities nil))
3499 'words))) ; FIXME
3501 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3502 (re-special (if org-export-with-special-strings
3503 (mapcar (lambda (x) (car x))
3504 org-export-html-special-string-regexps)))
3505 (re-rest
3506 (delq nil
3507 (list
3508 (if org-export-html-expand "@<[^>\n]+>")
3509 ))))
3510 (org-set-local
3511 'org-latex-and-specials-regexp
3512 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3513 re-rest) "\\|")))))
3515 (defun org-do-latex-and-special-faces (limit)
3516 "Run through the buffer and add overlays to links."
3517 (when org-latex-and-specials-regexp
3518 (let (rtn d)
3519 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3520 limit t))
3521 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3522 'face))
3523 '(org-code org-verbatim underline)))
3524 (progn
3525 (setq rtn t
3526 d (cond ((member (char-after (1+ (match-beginning 0)))
3527 '(?_ ?^)) 1)
3528 (t 0)))
3529 (font-lock-prepend-text-property
3530 (+ d (match-beginning 0)) (match-end 0)
3531 'face 'org-latex-and-export-specials)
3532 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3533 '(font-lock-multiline t)))))
3534 rtn)))
3536 (defun org-restart-font-lock ()
3537 "Restart font-lock-mode, to force refontification."
3538 (when (and (boundp 'font-lock-mode) font-lock-mode)
3539 (font-lock-mode -1)
3540 (font-lock-mode 1)))
3542 (defun org-all-targets (&optional radio)
3543 "Return a list of all targets in this file.
3544 With optional argument RADIO, only find radio targets."
3545 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3546 rtn)
3547 (save-excursion
3548 (goto-char (point-min))
3549 (while (re-search-forward re nil t)
3550 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3551 rtn)))
3553 (defun org-make-target-link-regexp (targets)
3554 "Make regular expression matching all strings in TARGETS.
3555 The regular expression finds the targets also if there is a line break
3556 between words."
3557 (and targets
3558 (concat
3559 "\\<\\("
3560 (mapconcat
3561 (lambda (x)
3562 (while (string-match " +" x)
3563 (setq x (replace-match "\\s-+" t t x)))
3565 targets
3566 "\\|")
3567 "\\)\\>")))
3569 (defun org-activate-tags (limit)
3570 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3571 (progn
3572 (add-text-properties (match-beginning 1) (match-end 1)
3573 (list 'mouse-face 'highlight
3574 'rear-nonsticky org-nonsticky-props
3575 'keymap org-mouse-map))
3576 t)))
3578 (defun org-outline-level ()
3579 (save-excursion
3580 (looking-at outline-regexp)
3581 (if (match-beginning 1)
3582 (+ (org-get-string-indentation (match-string 1)) 1000)
3583 (1- (- (match-end 0) (match-beginning 0))))))
3585 (defvar org-font-lock-keywords nil)
3587 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3588 "Regular expression matching a property line.")
3590 (defvar org-font-lock-hook nil
3591 "Functions to be called for special font loch stuff.")
3593 (defun org-font-lock-hook (limit)
3594 (run-hook-with-args 'org-font-lock-hook limit))
3596 (defun org-set-font-lock-defaults ()
3597 (let* ((em org-fontify-emphasized-text)
3598 (lk org-activate-links)
3599 (org-font-lock-extra-keywords
3600 (list
3601 ;; Call the hook
3602 '(org-font-lock-hook)
3603 ;; Headlines
3604 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3605 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3606 ;; Table lines
3607 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3608 (1 'org-table t))
3609 ;; Table internals
3610 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3611 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3612 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3613 ;; Drawers
3614 (list org-drawer-regexp '(0 'org-special-keyword t))
3615 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3616 ;; Properties
3617 (list org-property-re
3618 '(1 'org-special-keyword t)
3619 '(3 'org-property-value t))
3620 (if org-format-transports-properties-p
3621 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3622 ;; Links
3623 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3624 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3625 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3626 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3627 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3628 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3629 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3630 '(org-hide-wide-columns (0 nil append))
3631 ;; TODO lines
3632 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3633 '(1 (org-get-todo-face 1) t))
3634 ;; DONE
3635 (if org-fontify-done-headline
3636 (list (concat "^[*]+ +\\<\\("
3637 (mapconcat 'regexp-quote org-done-keywords "\\|")
3638 "\\)\\(.*\\)")
3639 '(2 'org-headline-done t))
3640 nil)
3641 ;; Priorities
3642 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3643 ;; Special keywords
3644 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3645 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3646 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3647 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3648 ;; Emphasis
3649 (if em
3650 (if (featurep 'xemacs)
3651 '(org-do-emphasis-faces (0 nil append))
3652 '(org-do-emphasis-faces)))
3653 ;; Checkboxes
3654 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3655 2 'bold prepend)
3656 (if org-provide-checkbox-statistics
3657 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3658 (0 (org-get-checkbox-statistics-face) t)))
3659 ;; Description list items
3660 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*?\\) ::"
3661 2 'bold prepend)
3662 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3663 '(1 'org-archived prepend))
3664 ;; Specials
3665 '(org-do-latex-and-special-faces)
3666 ;; Code
3667 '(org-activate-code (1 'org-code t))
3668 ;; COMMENT
3669 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3670 "\\|" org-quote-string "\\)\\>")
3671 '(1 'org-special-keyword t))
3672 '("^#.*" (0 'font-lock-comment-face t))
3674 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3675 ;; Now set the full font-lock-keywords
3676 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3677 (org-set-local 'font-lock-defaults
3678 '(org-font-lock-keywords t nil nil backward-paragraph))
3679 (kill-local-variable 'font-lock-keywords) nil))
3681 (defvar org-m nil)
3682 (defvar org-l nil)
3683 (defvar org-f nil)
3684 (defun org-get-level-face (n)
3685 "Get the right face for match N in font-lock matching of healdines."
3686 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3687 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3688 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3689 (cond
3690 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3691 ((eq n 2) org-f)
3692 (t (if org-level-color-stars-only nil org-f))))
3694 (defun org-get-todo-face (kwd)
3695 "Get the right face for a TODO keyword KWD.
3696 If KWD is a number, get the corresponding match group."
3697 (if (numberp kwd) (setq kwd (match-string kwd)))
3698 (or (cdr (assoc kwd org-todo-keyword-faces))
3699 (and (member kwd org-done-keywords) 'org-done)
3700 'org-todo))
3702 (defun org-unfontify-region (beg end &optional maybe_loudly)
3703 "Remove fontification and activation overlays from links."
3704 (font-lock-default-unfontify-region beg end)
3705 (let* ((buffer-undo-list t)
3706 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3707 (inhibit-modification-hooks t)
3708 deactivate-mark buffer-file-name buffer-file-truename)
3709 (remove-text-properties beg end
3710 '(mouse-face t keymap t org-linked-text t
3711 invisible t intangible t))))
3713 ;;;; Visibility cycling, including org-goto and indirect buffer
3715 ;;; Cycling
3717 (defvar org-cycle-global-status nil)
3718 (make-variable-buffer-local 'org-cycle-global-status)
3719 (defvar org-cycle-subtree-status nil)
3720 (make-variable-buffer-local 'org-cycle-subtree-status)
3722 ;;;###autoload
3723 (defun org-cycle (&optional arg)
3724 "Visibility cycling for Org-mode.
3726 - When this function is called with a prefix argument, rotate the entire
3727 buffer through 3 states (global cycling)
3728 1. OVERVIEW: Show only top-level headlines.
3729 2. CONTENTS: Show all headlines of all levels, but no body text.
3730 3. SHOW ALL: Show everything.
3732 - When point is at the beginning of a headline, rotate the subtree started
3733 by this line through 3 different states (local cycling)
3734 1. FOLDED: Only the main headline is shown.
3735 2. CHILDREN: The main headline and the direct children are shown.
3736 From this state, you can move to one of the children
3737 and zoom in further.
3738 3. SUBTREE: Show the entire subtree, including body text.
3740 - When there is a numeric prefix, go up to a heading with level ARG, do
3741 a `show-subtree' and return to the previous cursor position. If ARG
3742 is negative, go up that many levels.
3744 - When point is not at the beginning of a headline, execute
3745 `indent-relative', like TAB normally does. See the option
3746 `org-cycle-emulate-tab' for details.
3748 - Special case: if point is at the beginning of the buffer and there is
3749 no headline in line 1, this function will act as if called with prefix arg.
3750 But only if also the variable `org-cycle-global-at-bob' is t."
3751 (interactive "P")
3752 (org-load-modules-maybe)
3753 (let* ((outline-regexp
3754 (if (and (org-mode-p) org-cycle-include-plain-lists)
3755 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3756 outline-regexp))
3757 (bob-special (and org-cycle-global-at-bob (bobp)
3758 (not (looking-at outline-regexp))))
3759 (org-cycle-hook
3760 (if bob-special
3761 (delq 'org-optimize-window-after-visibility-change
3762 (copy-sequence org-cycle-hook))
3763 org-cycle-hook))
3764 (pos (point)))
3766 (if (or bob-special (equal arg '(4)))
3767 ;; special case: use global cycling
3768 (setq arg t))
3770 (cond
3772 ((org-at-table-p 'any)
3773 ;; Enter the table or move to the next field in the table
3774 (or (org-table-recognize-table.el)
3775 (progn
3776 (if arg (org-table-edit-field t)
3777 (org-table-justify-field-maybe)
3778 (call-interactively 'org-table-next-field)))))
3780 ((eq arg t) ;; Global cycling
3782 (cond
3783 ((and (eq last-command this-command)
3784 (eq org-cycle-global-status 'overview))
3785 ;; We just created the overview - now do table of contents
3786 ;; This can be slow in very large buffers, so indicate action
3787 (message "CONTENTS...")
3788 (org-content)
3789 (message "CONTENTS...done")
3790 (setq org-cycle-global-status 'contents)
3791 (run-hook-with-args 'org-cycle-hook 'contents))
3793 ((and (eq last-command this-command)
3794 (eq org-cycle-global-status 'contents))
3795 ;; We just showed the table of contents - now show everything
3796 (show-all)
3797 (message "SHOW ALL")
3798 (setq org-cycle-global-status 'all)
3799 (run-hook-with-args 'org-cycle-hook 'all))
3802 ;; Default action: go to overview
3803 (org-overview)
3804 (message "OVERVIEW")
3805 (setq org-cycle-global-status 'overview)
3806 (run-hook-with-args 'org-cycle-hook 'overview))))
3808 ((and org-drawers org-drawer-regexp
3809 (save-excursion
3810 (beginning-of-line 1)
3811 (looking-at org-drawer-regexp)))
3812 ;; Toggle block visibility
3813 (org-flag-drawer
3814 (not (get-char-property (match-end 0) 'invisible))))
3816 ((integerp arg)
3817 ;; Show-subtree, ARG levels up from here.
3818 (save-excursion
3819 (org-back-to-heading)
3820 (outline-up-heading (if (< arg 0) (- arg)
3821 (- (funcall outline-level) arg)))
3822 (org-show-subtree)))
3824 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3825 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3826 ;; At a heading: rotate between three different views
3827 (org-back-to-heading)
3828 (let ((goal-column 0) eoh eol eos)
3829 ;; First, some boundaries
3830 (save-excursion
3831 (org-back-to-heading)
3832 (save-excursion
3833 (beginning-of-line 2)
3834 (while (and (not (eobp)) ;; this is like `next-line'
3835 (get-char-property (1- (point)) 'invisible))
3836 (beginning-of-line 2)) (setq eol (point)))
3837 (outline-end-of-heading) (setq eoh (point))
3838 (org-end-of-subtree t)
3839 (unless (eobp)
3840 (skip-chars-forward " \t\n")
3841 (beginning-of-line 1) ; in case this is an item
3843 (setq eos (1- (point))))
3844 ;; Find out what to do next and set `this-command'
3845 (cond
3846 ((= eos eoh)
3847 ;; Nothing is hidden behind this heading
3848 (message "EMPTY ENTRY")
3849 (setq org-cycle-subtree-status nil)
3850 (save-excursion
3851 (goto-char eos)
3852 (outline-next-heading)
3853 (if (org-invisible-p) (org-flag-heading nil))))
3854 ((or (>= eol eos)
3855 (not (string-match "\\S-" (buffer-substring eol eos))))
3856 ;; Entire subtree is hidden in one line: open it
3857 (org-show-entry)
3858 (show-children)
3859 (message "CHILDREN")
3860 (save-excursion
3861 (goto-char eos)
3862 (outline-next-heading)
3863 (if (org-invisible-p) (org-flag-heading nil)))
3864 (setq org-cycle-subtree-status 'children)
3865 (run-hook-with-args 'org-cycle-hook 'children))
3866 ((and (eq last-command this-command)
3867 (eq org-cycle-subtree-status 'children))
3868 ;; We just showed the children, now show everything.
3869 (org-show-subtree)
3870 (message "SUBTREE")
3871 (setq org-cycle-subtree-status 'subtree)
3872 (run-hook-with-args 'org-cycle-hook 'subtree))
3874 ;; Default action: hide the subtree.
3875 (hide-subtree)
3876 (message "FOLDED")
3877 (setq org-cycle-subtree-status 'folded)
3878 (run-hook-with-args 'org-cycle-hook 'folded)))))
3880 ;; TAB emulation
3881 (buffer-read-only (org-back-to-heading))
3883 ((org-try-cdlatex-tab))
3885 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3886 (or (not (bolp))
3887 (not (looking-at outline-regexp))))
3888 (call-interactively (global-key-binding "\t")))
3890 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3891 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3892 (or (and (eq org-cycle-emulate-tab 'white)
3893 (= (match-end 0) (point-at-eol)))
3894 (and (eq org-cycle-emulate-tab 'whitestart)
3895 (>= (match-end 0) pos))))
3897 (eq org-cycle-emulate-tab t))
3898 (call-interactively (global-key-binding "\t")))
3900 (t (save-excursion
3901 (org-back-to-heading)
3902 (org-cycle))))))
3904 ;;;###autoload
3905 (defun org-global-cycle (&optional arg)
3906 "Cycle the global visibility. For details see `org-cycle'."
3907 (interactive "P")
3908 (let ((org-cycle-include-plain-lists
3909 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3910 (if (integerp arg)
3911 (progn
3912 (show-all)
3913 (hide-sublevels arg)
3914 (setq org-cycle-global-status 'contents))
3915 (org-cycle '(4)))))
3917 (defun org-overview ()
3918 "Switch to overview mode, shoing only top-level headlines.
3919 Really, this shows all headlines with level equal or greater than the level
3920 of the first headline in the buffer. This is important, because if the
3921 first headline is not level one, then (hide-sublevels 1) gives confusing
3922 results."
3923 (interactive)
3924 (let ((level (save-excursion
3925 (goto-char (point-min))
3926 (if (re-search-forward (concat "^" outline-regexp) nil t)
3927 (progn
3928 (goto-char (match-beginning 0))
3929 (funcall outline-level))))))
3930 (and level (hide-sublevels level))))
3932 (defun org-content (&optional arg)
3933 "Show all headlines in the buffer, like a table of contents.
3934 With numerical argument N, show content up to level N."
3935 (interactive "P")
3936 (save-excursion
3937 ;; Visit all headings and show their offspring
3938 (and (integerp arg) (org-overview))
3939 (goto-char (point-max))
3940 (catch 'exit
3941 (while (and (progn (condition-case nil
3942 (outline-previous-visible-heading 1)
3943 (error (goto-char (point-min))))
3945 (looking-at outline-regexp))
3946 (if (integerp arg)
3947 (show-children (1- arg))
3948 (show-branches))
3949 (if (bobp) (throw 'exit nil))))))
3952 (defun org-optimize-window-after-visibility-change (state)
3953 "Adjust the window after a change in outline visibility.
3954 This function is the default value of the hook `org-cycle-hook'."
3955 (when (get-buffer-window (current-buffer))
3956 (cond
3957 ; ((eq state 'overview) (org-first-headline-recenter 1))
3958 ; ((eq state 'overview) (org-beginning-of-line))
3959 ((eq state 'content) nil)
3960 ((eq state 'all) nil)
3961 ((eq state 'folded) nil)
3962 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3963 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3965 (defun org-compact-display-after-subtree-move ()
3966 (let (beg end)
3967 (save-excursion
3968 (if (org-up-heading-safe)
3969 (progn
3970 (hide-subtree)
3971 (show-entry)
3972 (show-children)
3973 (org-cycle-show-empty-lines 'children)
3974 (org-cycle-hide-drawers 'children))
3975 (org-overview)))))
3977 (defun org-cycle-show-empty-lines (state)
3978 "Show empty lines above all visible headlines.
3979 The region to be covered depends on STATE when called through
3980 `org-cycle-hook'. Lisp program can use t for STATE to get the
3981 entire buffer covered. Note that an empty line is only shown if there
3982 are at least `org-cycle-separator-lines' empty lines before the headeline."
3983 (when (> org-cycle-separator-lines 0)
3984 (save-excursion
3985 (let* ((n org-cycle-separator-lines)
3986 (re (cond
3987 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3988 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3989 (t (let ((ns (number-to-string (- n 2))))
3990 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3991 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3992 beg end)
3993 (cond
3994 ((memq state '(overview contents t))
3995 (setq beg (point-min) end (point-max)))
3996 ((memq state '(children folded))
3997 (setq beg (point) end (progn (org-end-of-subtree t t)
3998 (beginning-of-line 2)
3999 (point)))))
4000 (when beg
4001 (goto-char beg)
4002 (while (re-search-forward re end t)
4003 (if (not (get-char-property (match-end 1) 'invisible))
4004 (outline-flag-region
4005 (match-beginning 1) (match-end 1) nil)))))))
4006 ;; Never hide empty lines at the end of the file.
4007 (save-excursion
4008 (goto-char (point-max))
4009 (outline-previous-heading)
4010 (outline-end-of-heading)
4011 (if (and (looking-at "[ \t\n]+")
4012 (= (match-end 0) (point-max)))
4013 (outline-flag-region (point) (match-end 0) nil))))
4015 (defun org-cycle-hide-drawers (state)
4016 "Re-hide all drawers after a visibility state change."
4017 (when (and (org-mode-p)
4018 (not (memq state '(overview folded))))
4019 (save-excursion
4020 (let* ((globalp (memq state '(contents all)))
4021 (beg (if globalp (point-min) (point)))
4022 (end (if globalp (point-max) (org-end-of-subtree t))))
4023 (goto-char beg)
4024 (while (re-search-forward org-drawer-regexp end t)
4025 (org-flag-drawer t))))))
4027 (defun org-flag-drawer (flag)
4028 (save-excursion
4029 (beginning-of-line 1)
4030 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4031 (let ((b (match-end 0))
4032 (outline-regexp org-outline-regexp))
4033 (if (re-search-forward
4034 "^[ \t]*:END:"
4035 (save-excursion (outline-next-heading) (point)) t)
4036 (outline-flag-region b (point-at-eol) flag)
4037 (error ":END: line missing"))))))
4039 (defun org-subtree-end-visible-p ()
4040 "Is the end of the current subtree visible?"
4041 (pos-visible-in-window-p
4042 (save-excursion (org-end-of-subtree t) (point))))
4044 (defun org-first-headline-recenter (&optional N)
4045 "Move cursor to the first headline and recenter the headline.
4046 Optional argument N means, put the headline into the Nth line of the window."
4047 (goto-char (point-min))
4048 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4049 (beginning-of-line)
4050 (recenter (prefix-numeric-value N))))
4052 ;;; Org-goto
4054 (defvar org-goto-window-configuration nil)
4055 (defvar org-goto-marker nil)
4056 (defvar org-goto-map
4057 (let ((map (make-sparse-keymap)))
4058 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4059 (while (setq cmd (pop cmds))
4060 (substitute-key-definition cmd cmd map global-map)))
4061 (suppress-keymap map)
4062 (org-defkey map "\C-m" 'org-goto-ret)
4063 (org-defkey map [(return)] 'org-goto-ret)
4064 (org-defkey map [(left)] 'org-goto-left)
4065 (org-defkey map [(right)] 'org-goto-right)
4066 (org-defkey map [(control ?g)] 'org-goto-quit)
4067 (org-defkey map "\C-i" 'org-cycle)
4068 (org-defkey map [(tab)] 'org-cycle)
4069 (org-defkey map [(down)] 'outline-next-visible-heading)
4070 (org-defkey map [(up)] 'outline-previous-visible-heading)
4071 (if org-goto-auto-isearch
4072 (if (fboundp 'define-key-after)
4073 (define-key-after map [t] 'org-goto-local-auto-isearch)
4074 nil)
4075 (org-defkey map "q" 'org-goto-quit)
4076 (org-defkey map "n" 'outline-next-visible-heading)
4077 (org-defkey map "p" 'outline-previous-visible-heading)
4078 (org-defkey map "f" 'outline-forward-same-level)
4079 (org-defkey map "b" 'outline-backward-same-level)
4080 (org-defkey map "u" 'outline-up-heading))
4081 (org-defkey map "/" 'org-occur)
4082 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4083 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4084 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4085 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4086 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4087 map))
4089 (defconst org-goto-help
4090 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4091 RET=jump to location [Q]uit and return to previous location
4092 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4094 (defvar org-goto-start-pos) ; dynamically scoped parameter
4096 (defun org-goto (&optional alternative-interface)
4097 "Look up a different location in the current file, keeping current visibility.
4099 When you want look-up or go to a different location in a document, the
4100 fastest way is often to fold the entire buffer and then dive into the tree.
4101 This method has the disadvantage, that the previous location will be folded,
4102 which may not be what you want.
4104 This command works around this by showing a copy of the current buffer
4105 in an indirect buffer, in overview mode. You can dive into the tree in
4106 that copy, use org-occur and incremental search to find a location.
4107 When pressing RET or `Q', the command returns to the original buffer in
4108 which the visibility is still unchanged. After RET is will also jump to
4109 the location selected in the indirect buffer and expose the
4110 the headline hierarchy above."
4111 (interactive "P")
4112 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4113 (org-refile-use-outline-path t)
4114 (interface
4115 (if (not alternative-interface)
4116 org-goto-interface
4117 (if (eq org-goto-interface 'outline)
4118 'outline-path-completion
4119 'outline)))
4120 (org-goto-start-pos (point))
4121 (selected-point
4122 (if (eq interface 'outline)
4123 (car (org-get-location (current-buffer) org-goto-help))
4124 (nth 3 (org-refile-get-location "Goto: ")))))
4125 (if selected-point
4126 (progn
4127 (org-mark-ring-push org-goto-start-pos)
4128 (goto-char selected-point)
4129 (if (or (org-invisible-p) (org-invisible-p2))
4130 (org-show-context 'org-goto)))
4131 (message "Quit"))))
4133 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4134 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4135 (defvar org-goto-local-auto-isearch-map) ; defined below
4137 (defun org-get-location (buf help)
4138 "Let the user select a location in the Org-mode buffer BUF.
4139 This function uses a recursive edit. It returns the selected position
4140 or nil."
4141 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4142 (isearch-hide-immediately nil)
4143 (isearch-search-fun-function
4144 (lambda () 'org-goto-local-search-forward-headings))
4145 (org-goto-selected-point org-goto-exit-command))
4146 (save-excursion
4147 (save-window-excursion
4148 (delete-other-windows)
4149 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4150 (switch-to-buffer
4151 (condition-case nil
4152 (make-indirect-buffer (current-buffer) "*org-goto*")
4153 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4154 (with-output-to-temp-buffer "*Help*"
4155 (princ help))
4156 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4157 (setq buffer-read-only nil)
4158 (let ((org-startup-truncated t)
4159 (org-startup-folded nil)
4160 (org-startup-align-all-tables nil))
4161 (org-mode)
4162 (org-overview))
4163 (setq buffer-read-only t)
4164 (if (and (boundp 'org-goto-start-pos)
4165 (integer-or-marker-p org-goto-start-pos))
4166 (let ((org-show-hierarchy-above t)
4167 (org-show-siblings t)
4168 (org-show-following-heading t))
4169 (goto-char org-goto-start-pos)
4170 (and (org-invisible-p) (org-show-context)))
4171 (goto-char (point-min)))
4172 (org-beginning-of-line)
4173 (message "Select location and press RET")
4174 (use-local-map org-goto-map)
4175 (recursive-edit)
4177 (kill-buffer "*org-goto*")
4178 (cons org-goto-selected-point org-goto-exit-command)))
4180 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4181 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4182 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4183 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4185 (defun org-goto-local-search-forward-headings (string bound noerror)
4186 "Search and make sure that anu matches are in headlines."
4187 (catch 'return
4188 (while (search-forward string bound noerror)
4189 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4190 (and (member :headline context)
4191 (not (member :tags context))))
4192 (throw 'return (point))))))
4194 (defun org-goto-local-auto-isearch ()
4195 "Start isearch."
4196 (interactive)
4197 (goto-char (point-min))
4198 (let ((keys (this-command-keys)))
4199 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4200 (isearch-mode t)
4201 (isearch-process-search-char (string-to-char keys)))))
4203 (defun org-goto-ret (&optional arg)
4204 "Finish `org-goto' by going to the new location."
4205 (interactive "P")
4206 (setq org-goto-selected-point (point)
4207 org-goto-exit-command 'return)
4208 (throw 'exit nil))
4210 (defun org-goto-left ()
4211 "Finish `org-goto' by going to the new location."
4212 (interactive)
4213 (if (org-on-heading-p)
4214 (progn
4215 (beginning-of-line 1)
4216 (setq org-goto-selected-point (point)
4217 org-goto-exit-command 'left)
4218 (throw 'exit nil))
4219 (error "Not on a heading")))
4221 (defun org-goto-right ()
4222 "Finish `org-goto' by going to the new location."
4223 (interactive)
4224 (if (org-on-heading-p)
4225 (progn
4226 (setq org-goto-selected-point (point)
4227 org-goto-exit-command 'right)
4228 (throw 'exit nil))
4229 (error "Not on a heading")))
4231 (defun org-goto-quit ()
4232 "Finish `org-goto' without cursor motion."
4233 (interactive)
4234 (setq org-goto-selected-point nil)
4235 (setq org-goto-exit-command 'quit)
4236 (throw 'exit nil))
4238 ;;; Indirect buffer display of subtrees
4240 (defvar org-indirect-dedicated-frame nil
4241 "This is the frame being used for indirect tree display.")
4242 (defvar org-last-indirect-buffer nil)
4244 (defun org-tree-to-indirect-buffer (&optional arg)
4245 "Create indirect buffer and narrow it to current subtree.
4246 With numerical prefix ARG, go up to this level and then take that tree.
4247 If ARG is negative, go up that many levels.
4248 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4249 indirect buffer previously made with this command, to avoid proliferation of
4250 indirect buffers. However, when you call the command with a `C-u' prefix, or
4251 when `org-indirect-buffer-display' is `new-frame', the last buffer
4252 is kept so that you can work with several indirect buffers at the same time.
4253 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4254 requests that a new frame be made for the new buffer, so that the dedicated
4255 frame is not changed."
4256 (interactive "P")
4257 (let ((cbuf (current-buffer))
4258 (cwin (selected-window))
4259 (pos (point))
4260 beg end level heading ibuf)
4261 (save-excursion
4262 (org-back-to-heading t)
4263 (when (numberp arg)
4264 (setq level (org-outline-level))
4265 (if (< arg 0) (setq arg (+ level arg)))
4266 (while (> (setq level (org-outline-level)) arg)
4267 (outline-up-heading 1 t)))
4268 (setq beg (point)
4269 heading (org-get-heading))
4270 (org-end-of-subtree t) (setq end (point)))
4271 (if (and (buffer-live-p org-last-indirect-buffer)
4272 (not (eq org-indirect-buffer-display 'new-frame))
4273 (not arg))
4274 (kill-buffer org-last-indirect-buffer))
4275 (setq ibuf (org-get-indirect-buffer cbuf)
4276 org-last-indirect-buffer ibuf)
4277 (cond
4278 ((or (eq org-indirect-buffer-display 'new-frame)
4279 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4280 (select-frame (make-frame))
4281 (delete-other-windows)
4282 (switch-to-buffer ibuf)
4283 (org-set-frame-title heading))
4284 ((eq org-indirect-buffer-display 'dedicated-frame)
4285 (raise-frame
4286 (select-frame (or (and org-indirect-dedicated-frame
4287 (frame-live-p org-indirect-dedicated-frame)
4288 org-indirect-dedicated-frame)
4289 (setq org-indirect-dedicated-frame (make-frame)))))
4290 (delete-other-windows)
4291 (switch-to-buffer ibuf)
4292 (org-set-frame-title (concat "Indirect: " heading)))
4293 ((eq org-indirect-buffer-display 'current-window)
4294 (switch-to-buffer ibuf))
4295 ((eq org-indirect-buffer-display 'other-window)
4296 (pop-to-buffer ibuf))
4297 (t (error "Invalid value.")))
4298 (if (featurep 'xemacs)
4299 (save-excursion (org-mode) (turn-on-font-lock)))
4300 (narrow-to-region beg end)
4301 (show-all)
4302 (goto-char pos)
4303 (and (window-live-p cwin) (select-window cwin))))
4305 (defun org-get-indirect-buffer (&optional buffer)
4306 (setq buffer (or buffer (current-buffer)))
4307 (let ((n 1) (base (buffer-name buffer)) bname)
4308 (while (buffer-live-p
4309 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4310 (setq n (1+ n)))
4311 (condition-case nil
4312 (make-indirect-buffer buffer bname 'clone)
4313 (error (make-indirect-buffer buffer bname)))))
4315 (defun org-set-frame-title (title)
4316 "Set the title of the current frame to the string TITLE."
4317 ;; FIXME: how to name a single frame in XEmacs???
4318 (unless (featurep 'xemacs)
4319 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4321 ;;;; Structure editing
4323 ;;; Inserting headlines
4325 (defun org-insert-heading (&optional force-heading)
4326 "Insert a new heading or item with same depth at point.
4327 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4328 If point is at the beginning of a headline, insert a sibling before the
4329 current headline. If point is not at the beginning, do not split the line,
4330 but create the new hedline after the current line."
4331 (interactive "P")
4332 (if (= (buffer-size) 0)
4333 (insert "\n* ")
4334 (when (or force-heading (not (org-insert-item)))
4335 (let* ((head (save-excursion
4336 (condition-case nil
4337 (progn
4338 (org-back-to-heading)
4339 (match-string 0))
4340 (error "*"))))
4341 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4342 pos)
4343 (cond
4344 ((and (org-on-heading-p) (bolp)
4345 (or (bobp)
4346 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4347 ;; insert before the current line
4348 (open-line (if blank 2 1)))
4349 ((and (bolp)
4350 (or (bobp)
4351 (save-excursion
4352 (backward-char 1) (not (org-invisible-p)))))
4353 ;; insert right here
4354 nil)
4356 ;; in the middle of the line
4357 (org-show-entry)
4358 (let ((split
4359 (org-get-alist-option org-M-RET-may-split-line 'headline))
4360 tags pos)
4361 (if (org-on-heading-p)
4362 (progn
4363 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4364 (setq tags (and (match-end 2) (match-string 2)))
4365 (and (match-end 1)
4366 (delete-region (match-beginning 1) (match-end 1)))
4367 (setq pos (point-at-bol))
4368 (or split (end-of-line 1))
4369 (delete-horizontal-space)
4370 (newline (if blank 2 1))
4371 (when tags
4372 (save-excursion
4373 (goto-char pos)
4374 (end-of-line 1)
4375 (insert " " tags)
4376 (org-set-tags nil 'align))))
4377 (or split (end-of-line 1))
4378 (newline (if blank 2 1))))))
4379 (insert head) (just-one-space)
4380 (setq pos (point))
4381 (end-of-line 1)
4382 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4383 (run-hooks 'org-insert-heading-hook)))))
4385 (defun org-get-heading (&optional no-tags)
4386 "Return the heading of the current entry, without the stars."
4387 (save-excursion
4388 (org-back-to-heading t)
4389 (if (looking-at
4390 (if no-tags
4391 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4392 "\\*+[ \t]+\\([^\r\n]*\\)"))
4393 (match-string 1) "")))
4395 (defun org-insert-heading-after-current ()
4396 "Insert a new heading with same level as current, after current subtree."
4397 (interactive)
4398 (org-back-to-heading)
4399 (org-insert-heading)
4400 (org-move-subtree-down)
4401 (end-of-line 1))
4403 (defun org-insert-todo-heading (arg)
4404 "Insert a new heading with the same level and TODO state as current heading.
4405 If the heading has no TODO state, or if the state is DONE, use the first
4406 state (TODO by default). Also with prefix arg, force first state."
4407 (interactive "P")
4408 (when (not (org-insert-item 'checkbox))
4409 (org-insert-heading)
4410 (save-excursion
4411 (org-back-to-heading)
4412 (outline-previous-heading)
4413 (looking-at org-todo-line-regexp))
4414 (if (or arg
4415 (not (match-beginning 2))
4416 (member (match-string 2) org-done-keywords))
4417 (insert (car org-todo-keywords-1) " ")
4418 (insert (match-string 2) " "))))
4420 (defun org-insert-subheading (arg)
4421 "Insert a new subheading and demote it.
4422 Works for outline headings and for plain lists alike."
4423 (interactive "P")
4424 (org-insert-heading arg)
4425 (cond
4426 ((org-on-heading-p) (org-do-demote))
4427 ((org-at-item-p) (org-indent-item 1))))
4429 (defun org-insert-todo-subheading (arg)
4430 "Insert a new subheading with TODO keyword or checkbox and demote it.
4431 Works for outline headings and for plain lists alike."
4432 (interactive "P")
4433 (org-insert-todo-heading arg)
4434 (cond
4435 ((org-on-heading-p) (org-do-demote))
4436 ((org-at-item-p) (org-indent-item 1))))
4438 ;;; Promotion and Demotion
4440 (defun org-promote-subtree ()
4441 "Promote the entire subtree.
4442 See also `org-promote'."
4443 (interactive)
4444 (save-excursion
4445 (org-map-tree 'org-promote))
4446 (org-fix-position-after-promote))
4448 (defun org-demote-subtree ()
4449 "Demote the entire subtree. See `org-demote'.
4450 See also `org-promote'."
4451 (interactive)
4452 (save-excursion
4453 (org-map-tree 'org-demote))
4454 (org-fix-position-after-promote))
4457 (defun org-do-promote ()
4458 "Promote the current heading higher up the tree.
4459 If the region is active in `transient-mark-mode', promote all headings
4460 in the region."
4461 (interactive)
4462 (save-excursion
4463 (if (org-region-active-p)
4464 (org-map-region 'org-promote (region-beginning) (region-end))
4465 (org-promote)))
4466 (org-fix-position-after-promote))
4468 (defun org-do-demote ()
4469 "Demote the current heading lower down the tree.
4470 If the region is active in `transient-mark-mode', demote all headings
4471 in the region."
4472 (interactive)
4473 (save-excursion
4474 (if (org-region-active-p)
4475 (org-map-region 'org-demote (region-beginning) (region-end))
4476 (org-demote)))
4477 (org-fix-position-after-promote))
4479 (defun org-fix-position-after-promote ()
4480 "Make sure that after pro/demotion cursor position is right."
4481 (let ((pos (point)))
4482 (when (save-excursion
4483 (beginning-of-line 1)
4484 (looking-at org-todo-line-regexp)
4485 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4486 (cond ((eobp) (insert " "))
4487 ((eolp) (insert " "))
4488 ((equal (char-after) ?\ ) (forward-char 1))))))
4490 (defun org-reduced-level (l)
4491 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4493 (defun org-get-valid-level (level &optional change)
4494 "Rectify a level change under the influence of `org-odd-levels-only'
4495 LEVEL is a current level, CHANGE is by how much the level should be
4496 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4497 even level numbers will become the next higher odd number."
4498 (if org-odd-levels-only
4499 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4500 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4501 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4502 (max 1 (+ level change))))
4504 (if (boundp 'define-obsolete-function-alias)
4505 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4506 (define-obsolete-function-alias 'org-get-legal-level
4507 'org-get-valid-level)
4508 (define-obsolete-function-alias 'org-get-legal-level
4509 'org-get-valid-level "23.1")))
4511 (defun org-promote ()
4512 "Promote the current heading higher up the tree.
4513 If the region is active in `transient-mark-mode', promote all headings
4514 in the region."
4515 (org-back-to-heading t)
4516 (let* ((level (save-match-data (funcall outline-level)))
4517 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4518 (diff (abs (- level (length up-head) -1))))
4519 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4520 (replace-match up-head nil t)
4521 ;; Fixup tag positioning
4522 (and org-auto-align-tags (org-set-tags nil t))
4523 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4525 (defun org-demote ()
4526 "Demote the current heading lower down the tree.
4527 If the region is active in `transient-mark-mode', demote all headings
4528 in the region."
4529 (org-back-to-heading t)
4530 (let* ((level (save-match-data (funcall outline-level)))
4531 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4532 (diff (abs (- level (length down-head) -1))))
4533 (replace-match down-head nil t)
4534 ;; Fixup tag positioning
4535 (and org-auto-align-tags (org-set-tags nil t))
4536 (if org-adapt-indentation (org-fixup-indentation diff))))
4538 (defun org-map-tree (fun)
4539 "Call FUN for every heading underneath the current one."
4540 (org-back-to-heading)
4541 (let ((level (funcall outline-level)))
4542 (save-excursion
4543 (funcall fun)
4544 (while (and (progn
4545 (outline-next-heading)
4546 (> (funcall outline-level) level))
4547 (not (eobp)))
4548 (funcall fun)))))
4550 (defun org-map-region (fun beg end)
4551 "Call FUN for every heading between BEG and END."
4552 (let ((org-ignore-region t))
4553 (save-excursion
4554 (setq end (copy-marker end))
4555 (goto-char beg)
4556 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4557 (< (point) end))
4558 (funcall fun))
4559 (while (and (progn
4560 (outline-next-heading)
4561 (< (point) end))
4562 (not (eobp)))
4563 (funcall fun)))))
4565 (defun org-fixup-indentation (diff)
4566 "Change the indentation in the current entry by DIFF
4567 However, if any line in the current entry has no indentation, or if it
4568 would end up with no indentation after the change, nothing at all is done."
4569 (save-excursion
4570 (let ((end (save-excursion (outline-next-heading)
4571 (point-marker)))
4572 (prohibit (if (> diff 0)
4573 "^\\S-"
4574 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4575 col)
4576 (unless (save-excursion (end-of-line 1)
4577 (re-search-forward prohibit end t))
4578 (while (and (< (point) end)
4579 (re-search-forward "^[ \t]+" end t))
4580 (goto-char (match-end 0))
4581 (setq col (current-column))
4582 (if (< diff 0) (replace-match ""))
4583 (indent-to (+ diff col))))
4584 (move-marker end nil))))
4586 (defun org-convert-to-odd-levels ()
4587 "Convert an org-mode file with all levels allowed to one with odd levels.
4588 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4589 level 5 etc."
4590 (interactive)
4591 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4592 (let ((org-odd-levels-only nil) n)
4593 (save-excursion
4594 (goto-char (point-min))
4595 (while (re-search-forward "^\\*\\*+ " nil t)
4596 (setq n (- (length (match-string 0)) 2))
4597 (while (>= (setq n (1- n)) 0)
4598 (org-demote))
4599 (end-of-line 1))))))
4602 (defun org-convert-to-oddeven-levels ()
4603 "Convert an org-mode file with only odd levels to one with odd and even levels.
4604 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4605 section with an even level, conversion would destroy the structure of the file. An error
4606 is signaled in this case."
4607 (interactive)
4608 (goto-char (point-min))
4609 ;; First check if there are no even levels
4610 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4611 (org-show-context t)
4612 (error "Not all levels are odd in this file. Conversion not possible."))
4613 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4614 (let ((org-odd-levels-only nil) n)
4615 (save-excursion
4616 (goto-char (point-min))
4617 (while (re-search-forward "^\\*\\*+ " nil t)
4618 (setq n (/ (1- (length (match-string 0))) 2))
4619 (while (>= (setq n (1- n)) 0)
4620 (org-promote))
4621 (end-of-line 1))))))
4623 (defun org-tr-level (n)
4624 "Make N odd if required."
4625 (if org-odd-levels-only (1+ (/ n 2)) n))
4627 ;;; Vertical tree motion, cutting and pasting of subtrees
4629 (defun org-move-subtree-up (&optional arg)
4630 "Move the current subtree up past ARG headlines of the same level."
4631 (interactive "p")
4632 (org-move-subtree-down (- (prefix-numeric-value arg))))
4634 (defun org-move-subtree-down (&optional arg)
4635 "Move the current subtree down past ARG headlines of the same level."
4636 (interactive "p")
4637 (setq arg (prefix-numeric-value arg))
4638 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4639 'outline-get-last-sibling))
4640 (ins-point (make-marker))
4641 (cnt (abs arg))
4642 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4643 ;; Select the tree
4644 (org-back-to-heading)
4645 (setq beg0 (point))
4646 (save-excursion
4647 (setq ne-beg (org-back-over-empty-lines))
4648 (setq beg (point)))
4649 (save-match-data
4650 (save-excursion (outline-end-of-heading)
4651 (setq folded (org-invisible-p)))
4652 (outline-end-of-subtree))
4653 (outline-next-heading)
4654 (setq ne-end (org-back-over-empty-lines))
4655 (setq end (point))
4656 (goto-char beg0)
4657 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4658 ;; include less whitespace
4659 (save-excursion
4660 (goto-char beg)
4661 (forward-line (- ne-beg ne-end))
4662 (setq beg (point))))
4663 ;; Find insertion point, with error handling
4664 (while (> cnt 0)
4665 (or (and (funcall movfunc) (looking-at outline-regexp))
4666 (progn (goto-char beg0)
4667 (error "Cannot move past superior level or buffer limit")))
4668 (setq cnt (1- cnt)))
4669 (if (> arg 0)
4670 ;; Moving forward - still need to move over subtree
4671 (progn (org-end-of-subtree t t)
4672 (save-excursion
4673 (org-back-over-empty-lines)
4674 (or (bolp) (newline)))))
4675 (setq ne-ins (org-back-over-empty-lines))
4676 (move-marker ins-point (point))
4677 (setq txt (buffer-substring beg end))
4678 (org-save-markers-in-region beg end)
4679 (delete-region beg end)
4680 (outline-flag-region (1- beg) beg nil)
4681 (outline-flag-region (1- (point)) (point) nil)
4682 (let ((bbb (point)))
4683 (insert-before-markers txt)
4684 (org-reinstall-markers-in-region bbb)
4685 (move-marker ins-point bbb))
4686 (or (bolp) (insert "\n"))
4687 (setq ins-end (point))
4688 (goto-char ins-point)
4689 (org-skip-whitespace)
4690 (when (and (< arg 0)
4691 (org-first-sibling-p)
4692 (> ne-ins ne-beg))
4693 ;; Move whitespace back to beginning
4694 (save-excursion
4695 (goto-char ins-end)
4696 (let ((kill-whole-line t))
4697 (kill-line (- ne-ins ne-beg)) (point)))
4698 (insert (make-string (- ne-ins ne-beg) ?\n)))
4699 (move-marker ins-point nil)
4700 (org-compact-display-after-subtree-move)
4701 (unless folded
4702 (org-show-entry)
4703 (show-children)
4704 (org-cycle-hide-drawers 'children))))
4706 (defvar org-subtree-clip ""
4707 "Clipboard for cut and paste of subtrees.
4708 This is actually only a copy of the kill, because we use the normal kill
4709 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4711 (defvar org-subtree-clip-folded nil
4712 "Was the last copied subtree folded?
4713 This is used to fold the tree back after pasting.")
4715 (defun org-cut-subtree (&optional n)
4716 "Cut the current subtree into the clipboard.
4717 With prefix arg N, cut this many sequential subtrees.
4718 This is a short-hand for marking the subtree and then cutting it."
4719 (interactive "p")
4720 (org-copy-subtree n 'cut))
4722 (defun org-copy-subtree (&optional n cut force-store-markers)
4723 "Cut the current subtree into the clipboard.
4724 With prefix arg N, cut this many sequential subtrees.
4725 This is a short-hand for marking the subtree and then copying it.
4726 If CUT is non-nil, actually cut the subtree.
4727 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4728 of some markers in the region, even if CUT is non-nil. This is
4729 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4730 (interactive "p")
4731 (let (beg end folded (beg0 (point)))
4732 (if (interactive-p)
4733 (org-back-to-heading nil) ; take what looks like a subtree
4734 (org-back-to-heading t)) ; take what is really there
4735 (org-back-over-empty-lines)
4736 (setq beg (point))
4737 (skip-chars-forward " \t\r\n")
4738 (save-match-data
4739 (save-excursion (outline-end-of-heading)
4740 (setq folded (org-invisible-p)))
4741 (condition-case nil
4742 (outline-forward-same-level (1- n))
4743 (error nil))
4744 (org-end-of-subtree t t))
4745 (org-back-over-empty-lines)
4746 (setq end (point))
4747 (goto-char beg0)
4748 (when (> end beg)
4749 (setq org-subtree-clip-folded folded)
4750 (when (or cut force-store-markers)
4751 (org-save-markers-in-region beg end))
4752 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4753 (setq org-subtree-clip (current-kill 0))
4754 (message "%s: Subtree(s) with %d characters"
4755 (if cut "Cut" "Copied")
4756 (length org-subtree-clip)))))
4758 (defun org-paste-subtree (&optional level tree)
4759 "Paste the clipboard as a subtree, with modification of headline level.
4760 The entire subtree is promoted or demoted in order to match a new headline
4761 level. By default, the new level is derived from the visible headings
4762 before and after the insertion point, and taken to be the inferior headline
4763 level of the two. So if the previous visible heading is level 3 and the
4764 next is level 4 (or vice versa), level 4 will be used for insertion.
4765 This makes sure that the subtree remains an independent subtree and does
4766 not swallow low level entries.
4768 You can also force a different level, either by using a numeric prefix
4769 argument, or by inserting the heading marker by hand. For example, if the
4770 cursor is after \"*****\", then the tree will be shifted to level 5.
4772 If you want to insert the tree as is, just use \\[yank].
4774 If optional TREE is given, use this text instead of the kill ring."
4775 (interactive "P")
4776 (unless (org-kill-is-subtree-p tree)
4777 (error "%s"
4778 (substitute-command-keys
4779 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4780 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4781 (^re (concat "^\\(" outline-regexp "\\)"))
4782 (re (concat "\\(" outline-regexp "\\)"))
4783 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4785 (old-level (if (string-match ^re txt)
4786 (- (match-end 0) (match-beginning 0) 1)
4787 -1))
4788 (force-level (cond (level (prefix-numeric-value level))
4789 ((string-match
4790 ^re_ (buffer-substring (point-at-bol) (point)))
4791 (- (match-end 1) (match-beginning 1)))
4792 (t nil)))
4793 (previous-level (save-excursion
4794 (condition-case nil
4795 (progn
4796 (outline-previous-visible-heading 1)
4797 (if (looking-at re)
4798 (- (match-end 0) (match-beginning 0) 1)
4800 (error 1))))
4801 (next-level (save-excursion
4802 (condition-case nil
4803 (progn
4804 (or (looking-at outline-regexp)
4805 (outline-next-visible-heading 1))
4806 (if (looking-at re)
4807 (- (match-end 0) (match-beginning 0) 1)
4809 (error 1))))
4810 (new-level (or force-level (max previous-level next-level)))
4811 (shift (if (or (= old-level -1)
4812 (= new-level -1)
4813 (= old-level new-level))
4815 (- new-level old-level)))
4816 (delta (if (> shift 0) -1 1))
4817 (func (if (> shift 0) 'org-demote 'org-promote))
4818 (org-odd-levels-only nil)
4819 beg end)
4820 ;; Remove the forced level indicator
4821 (if force-level
4822 (delete-region (point-at-bol) (point)))
4823 ;; Paste
4824 (beginning-of-line 1)
4825 (org-back-over-empty-lines)
4826 (setq beg (point))
4827 (insert-before-markers txt)
4828 (unless (string-match "\n\\'" txt) (insert "\n"))
4829 (org-reinstall-markers-in-region beg)
4830 (setq end (point))
4831 (goto-char beg)
4832 (skip-chars-forward " \t\n\r")
4833 (setq beg (point))
4834 ;; Shift if necessary
4835 (unless (= shift 0)
4836 (save-restriction
4837 (narrow-to-region beg end)
4838 (while (not (= shift 0))
4839 (org-map-region func (point-min) (point-max))
4840 (setq shift (+ delta shift)))
4841 (goto-char (point-min))))
4842 (when (interactive-p)
4843 (message "Clipboard pasted as level %d subtree" new-level))
4844 (if (and kill-ring
4845 (eq org-subtree-clip (current-kill 0))
4846 org-subtree-clip-folded)
4847 ;; The tree was folded before it was killed/copied
4848 (hide-subtree))))
4850 (defun org-kill-is-subtree-p (&optional txt)
4851 "Check if the current kill is an outline subtree, or a set of trees.
4852 Returns nil if kill does not start with a headline, or if the first
4853 headline level is not the largest headline level in the tree.
4854 So this will actually accept several entries of equal levels as well,
4855 which is OK for `org-paste-subtree'.
4856 If optional TXT is given, check this string instead of the current kill."
4857 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4858 (start-level (and kill
4859 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4860 org-outline-regexp "\\)")
4861 kill)
4862 (- (match-end 2) (match-beginning 2) 1)))
4863 (re (concat "^" org-outline-regexp))
4864 (start (1+ (match-beginning 2))))
4865 (if (not start-level)
4866 (progn
4867 nil) ;; does not even start with a heading
4868 (catch 'exit
4869 (while (setq start (string-match re kill (1+ start)))
4870 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4871 (throw 'exit nil)))
4872 t))))
4874 (defvar org-markers-to-move nil
4875 "Markers that should be moved with a cut-and-paste operation.
4876 Those markers are stored together with their positions relative to
4877 the start of the region.")
4879 (defun org-save-markers-in-region (beg end)
4880 "Check markers in region.
4881 If these markers are between BEG and END, record their position relative
4882 to BEG, so that after moving the block of text, we can put the markers back
4883 into place.
4884 This function gets called just before an entry or tree gets cut from the
4885 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4886 called immediately, to move the markers with the entries."
4887 (setq org-markers-to-move nil)
4888 (when (featurep 'org-clock)
4889 (org-clock-save-markers-for-cut-and-paste beg end))
4890 (when (featurep 'org-agenda)
4891 (org-agenda-save-markers-for-cut-and-paste beg end)))
4893 (defun org-check-and-save-marker (marker beg end)
4894 "Check if MARKER is between BEG and END.
4895 If yes, remember the marker and the distance to BEG."
4896 (when (and (marker-buffer marker)
4897 (equal (marker-buffer marker) (current-buffer)))
4898 (if (and (>= marker beg) (< marker end))
4899 (push (cons marker (- marker beg)) org-markers-to-move))))
4901 (defun org-reinstall-markers-in-region (beg)
4902 "Move all remembered markers to their position relative to BEG."
4903 (mapc (lambda (x)
4904 (move-marker (car x) (+ beg (cdr x))))
4905 org-markers-to-move)
4906 (setq org-markers-to-move nil))
4908 (defun org-narrow-to-subtree ()
4909 "Narrow buffer to the current subtree."
4910 (interactive)
4911 (save-excursion
4912 (save-match-data
4913 (narrow-to-region
4914 (progn (org-back-to-heading) (point))
4915 (progn (org-end-of-subtree t t) (point))))))
4918 ;;; Outline Sorting
4920 (defun org-sort (with-case)
4921 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4922 Optional argument WITH-CASE means sort case-sensitively."
4923 (interactive "P")
4924 (if (org-at-table-p)
4925 (org-call-with-arg 'org-table-sort-lines with-case)
4926 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4928 (defun org-sort-remove-invisible (s)
4929 (remove-text-properties 0 (length s) org-rm-props s)
4930 (while (string-match org-bracket-link-regexp s)
4931 (setq s (replace-match (if (match-end 2)
4932 (match-string 3 s)
4933 (match-string 1 s)) t t s)))
4936 (defvar org-priority-regexp) ; defined later in the file
4938 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4939 "Sort entries on a certain level of an outline tree.
4940 If there is an active region, the entries in the region are sorted.
4941 Else, if the cursor is before the first entry, sort the top-level items.
4942 Else, the children of the entry at point are sorted.
4944 Sorting can be alphabetically, numerically, and by date/time as given by
4945 the first time stamp in the entry. The command prompts for the sorting
4946 type unless it has been given to the function through the SORTING-TYPE
4947 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4948 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4949 called with point at the beginning of the record. It must return either
4950 a string or a number that should serve as the sorting key for that record.
4952 Comparing entries ignores case by default. However, with an optional argument
4953 WITH-CASE, the sorting considers case as well."
4954 (interactive "P")
4955 (let ((case-func (if with-case 'identity 'downcase))
4956 start beg end stars re re2
4957 txt what tmp plain-list-p)
4958 ;; Find beginning and end of region to sort
4959 (cond
4960 ((org-region-active-p)
4961 ;; we will sort the region
4962 (setq end (region-end)
4963 what "region")
4964 (goto-char (region-beginning))
4965 (if (not (org-on-heading-p)) (outline-next-heading))
4966 (setq start (point)))
4967 ((org-at-item-p)
4968 ;; we will sort this plain list
4969 (org-beginning-of-item-list) (setq start (point))
4970 (org-end-of-item-list) (setq end (point))
4971 (goto-char start)
4972 (setq plain-list-p t
4973 what "plain list"))
4974 ((or (org-on-heading-p)
4975 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4976 ;; we will sort the children of the current headline
4977 (org-back-to-heading)
4978 (setq start (point)
4979 end (progn (org-end-of-subtree t t)
4980 (org-back-over-empty-lines)
4981 (point))
4982 what "children")
4983 (goto-char start)
4984 (show-subtree)
4985 (outline-next-heading))
4987 ;; we will sort the top-level entries in this file
4988 (goto-char (point-min))
4989 (or (org-on-heading-p) (outline-next-heading))
4990 (setq start (point) end (point-max) what "top-level")
4991 (goto-char start)
4992 (show-all)))
4994 (setq beg (point))
4995 (if (>= beg end) (error "Nothing to sort"))
4997 (unless plain-list-p
4998 (looking-at "\\(\\*+\\)")
4999 (setq stars (match-string 1)
5000 re (concat "^" (regexp-quote stars) " +")
5001 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5002 txt (buffer-substring beg end))
5003 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5004 (if (and (not (equal stars "*")) (string-match re2 txt))
5005 (error "Region to sort contains a level above the first entry")))
5007 (unless sorting-type
5008 (message
5009 (if plain-list-p
5010 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5011 "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:")
5012 what)
5013 (setq sorting-type (read-char-exclusive))
5015 (and (= (downcase sorting-type) ?f)
5016 (setq getkey-func
5017 (completing-read "Sort using function: "
5018 obarray 'fboundp t nil nil))
5019 (setq getkey-func (intern getkey-func)))
5021 (and (= (downcase sorting-type) ?r)
5022 (setq property
5023 (completing-read "Property: "
5024 (mapcar 'list (org-buffer-property-keys t))
5025 nil t))))
5027 (message "Sorting entries...")
5029 (save-restriction
5030 (narrow-to-region start end)
5032 (let ((dcst (downcase sorting-type))
5033 (now (current-time)))
5034 (sort-subr
5035 (/= dcst sorting-type)
5036 ;; This function moves to the beginning character of the "record" to
5037 ;; be sorted.
5038 (if plain-list-p
5039 (lambda nil
5040 (if (org-at-item-p) t (goto-char (point-max))))
5041 (lambda nil
5042 (if (re-search-forward re nil t)
5043 (goto-char (match-beginning 0))
5044 (goto-char (point-max)))))
5045 ;; This function moves to the last character of the "record" being
5046 ;; sorted.
5047 (if plain-list-p
5048 'org-end-of-item
5049 (lambda nil
5050 (save-match-data
5051 (condition-case nil
5052 (outline-forward-same-level 1)
5053 (error
5054 (goto-char (point-max)))))))
5056 ;; This function returns the value that gets sorted against.
5057 (if plain-list-p
5058 (lambda nil
5059 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5060 (cond
5061 ((= dcst ?n)
5062 (string-to-number (buffer-substring (match-end 0)
5063 (point-at-eol))))
5064 ((= dcst ?a)
5065 (buffer-substring (match-end 0) (point-at-eol)))
5066 ((= dcst ?t)
5067 (if (re-search-forward org-ts-regexp
5068 (point-at-eol) t)
5069 (org-time-string-to-time (match-string 0))
5070 now))
5071 ((= dcst ?f)
5072 (if getkey-func
5073 (progn
5074 (setq tmp (funcall getkey-func))
5075 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5076 tmp)
5077 (error "Invalid key function `%s'" getkey-func)))
5078 (t (error "Invalid sorting type `%c'" sorting-type)))))
5079 (lambda nil
5080 (cond
5081 ((= dcst ?n)
5082 (if (looking-at outline-regexp)
5083 (string-to-number (buffer-substring (match-end 0)
5084 (point-at-eol)))
5085 nil))
5086 ((= dcst ?a)
5087 (funcall case-func (buffer-substring (point-at-bol)
5088 (point-at-eol))))
5089 ((= dcst ?t)
5090 (if (re-search-forward org-ts-regexp
5091 (save-excursion
5092 (forward-line 2)
5093 (point)) t)
5094 (org-time-string-to-time (match-string 0))
5095 now))
5096 ((= dcst ?p)
5097 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5098 (string-to-char (match-string 2))
5099 org-default-priority))
5100 ((= dcst ?r)
5101 (or (org-entry-get nil property) ""))
5102 ((= dcst ?o)
5103 (if (looking-at org-complex-heading-regexp)
5104 (- 9999 (length (member (match-string 2)
5105 org-todo-keywords-1)))))
5106 ((= dcst ?f)
5107 (if getkey-func
5108 (progn
5109 (setq tmp (funcall getkey-func))
5110 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5111 tmp)
5112 (error "Invalid key function `%s'" getkey-func)))
5113 (t (error "Invalid sorting type `%c'" sorting-type)))))
5115 (cond
5116 ((= dcst ?a) 'string<)
5117 ((= dcst ?t) 'time-less-p)
5118 (t nil)))))
5119 (message "Sorting entries...done")))
5121 (defun org-do-sort (table what &optional with-case sorting-type)
5122 "Sort TABLE of WHAT according to SORTING-TYPE.
5123 The user will be prompted for the SORTING-TYPE if the call to this
5124 function does not specify it. WHAT is only for the prompt, to indicate
5125 what is being sorted. The sorting key will be extracted from
5126 the car of the elements of the table.
5127 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5128 (unless sorting-type
5129 (message
5130 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5131 what)
5132 (setq sorting-type (read-char-exclusive)))
5133 (let ((dcst (downcase sorting-type))
5134 extractfun comparefun)
5135 ;; Define the appropriate functions
5136 (cond
5137 ((= dcst ?n)
5138 (setq extractfun 'string-to-number
5139 comparefun (if (= dcst sorting-type) '< '>)))
5140 ((= dcst ?a)
5141 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5142 (lambda(x) (downcase (org-sort-remove-invisible x))))
5143 comparefun (if (= dcst sorting-type)
5144 'string<
5145 (lambda (a b) (and (not (string< a b))
5146 (not (string= a b)))))))
5147 ((= dcst ?t)
5148 (setq extractfun
5149 (lambda (x)
5150 (if (string-match org-ts-regexp x)
5151 (time-to-seconds
5152 (org-time-string-to-time (match-string 0 x)))
5154 comparefun (if (= dcst sorting-type) '< '>)))
5155 (t (error "Invalid sorting type `%c'" sorting-type)))
5157 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5158 table)
5159 (lambda (a b) (funcall comparefun (car a) (car b))))))
5161 ;;;; Plain list items, including checkboxes
5163 ;;; Plain list items
5165 (defun org-at-item-p ()
5166 "Is point in a line starting a hand-formatted item?"
5167 (let ((llt org-plain-list-ordered-item-terminator))
5168 (save-excursion
5169 (goto-char (point-at-bol))
5170 (looking-at
5171 (cond
5172 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5173 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5174 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5175 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5177 (defun org-in-item-p ()
5178 "It the cursor inside a plain list item.
5179 Does not have to be the first line."
5180 (save-excursion
5181 (condition-case nil
5182 (progn
5183 (org-beginning-of-item)
5184 (org-at-item-p)
5186 (error nil))))
5188 (defun org-insert-item (&optional checkbox)
5189 "Insert a new item at the current level.
5190 Return t when things worked, nil when we are not in an item."
5191 (when (save-excursion
5192 (condition-case nil
5193 (progn
5194 (org-beginning-of-item)
5195 (org-at-item-p)
5196 (if (org-invisible-p) (error "Invisible item"))
5198 (error nil)))
5199 (let* ((bul (match-string 0))
5200 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5201 (match-end 0)))
5202 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5203 pos)
5204 (cond
5205 ((and (org-at-item-p) (<= (point) eow))
5206 ;; before the bullet
5207 (beginning-of-line 1)
5208 (open-line (if blank 2 1)))
5209 ((<= (point) eow)
5210 (beginning-of-line 1))
5212 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5213 (end-of-line 1)
5214 (delete-horizontal-space))
5215 (newline (if blank 2 1))))
5216 (insert bul (if checkbox "[ ]" ""))
5217 (just-one-space)
5218 (setq pos (point))
5219 (end-of-line 1)
5220 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5221 (org-maybe-renumber-ordered-list)
5222 (and checkbox (org-update-checkbox-count-maybe))
5225 ;;; Checkboxes
5227 (defun org-at-item-checkbox-p ()
5228 "Is point at a line starting a plain-list item with a checklet?"
5229 (and (org-at-item-p)
5230 (save-excursion
5231 (goto-char (match-end 0))
5232 (skip-chars-forward " \t")
5233 (looking-at "\\[[- X]\\]"))))
5235 (defun org-toggle-checkbox (&optional arg)
5236 "Toggle the checkbox in the current line."
5237 (interactive "P")
5238 (catch 'exit
5239 (let (beg end status (firstnew 'unknown))
5240 (cond
5241 ((org-region-active-p)
5242 (setq beg (region-beginning) end (region-end)))
5243 ((org-on-heading-p)
5244 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5245 ((org-at-item-checkbox-p)
5246 (let ((pos (point)))
5247 (replace-match
5248 (cond (arg "[-]")
5249 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5250 (t "[ ]"))
5251 t t)
5252 (goto-char pos))
5253 (throw 'exit t))
5254 (t (error "Not at a checkbox or heading, and no active region")))
5255 (save-excursion
5256 (goto-char beg)
5257 (while (< (point) end)
5258 (when (org-at-item-checkbox-p)
5259 (setq status (equal (match-string 0) "[X]"))
5260 (when (eq firstnew 'unknown)
5261 (setq firstnew (not status)))
5262 (replace-match
5263 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5264 (beginning-of-line 2)))))
5265 (org-update-checkbox-count-maybe))
5267 (defun org-update-checkbox-count-maybe ()
5268 "Update checkbox statistics unless turned off by user."
5269 (when org-provide-checkbox-statistics
5270 (org-update-checkbox-count)))
5272 (defun org-update-checkbox-count (&optional all)
5273 "Update the checkbox statistics in the current section.
5274 This will find all statistic cookies like [57%] and [6/12] and update them
5275 with the current numbers. With optional prefix argument ALL, do this for
5276 the whole buffer."
5277 (interactive "P")
5278 (save-excursion
5279 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5280 (beg (condition-case nil
5281 (progn (outline-back-to-heading) (point))
5282 (error (point-min))))
5283 (end (move-marker (make-marker)
5284 (progn (outline-next-heading) (point))))
5285 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5286 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5287 (re-find (concat re "\\|" re-box))
5288 beg-cookie end-cookie is-percent c-on c-off lim
5289 eline curr-ind next-ind continue-from startsearch
5290 (cstat 0)
5292 (when all
5293 (goto-char (point-min))
5294 (outline-next-heading)
5295 (setq beg (point) end (point-max)))
5296 (goto-char end)
5297 ;; find each statistic cookie
5298 (while (re-search-backward re-find beg t)
5299 (setq beg-cookie (match-beginning 1)
5300 end-cookie (match-end 1)
5301 cstat (+ cstat (if end-cookie 1 0))
5302 startsearch (point-at-eol)
5303 continue-from (point-at-bol)
5304 is-percent (match-beginning 2)
5305 lim (cond
5306 ((org-on-heading-p) (outline-next-heading) (point))
5307 ((org-at-item-p) (org-end-of-item) (point))
5308 (t nil))
5309 c-on 0
5310 c-off 0)
5311 (when lim
5312 ;; find first checkbox for this cookie and gather
5313 ;; statistics from all that are at this indentation level
5314 (goto-char startsearch)
5315 (if (re-search-forward re-box lim t)
5316 (progn
5317 (org-beginning-of-item)
5318 (setq curr-ind (org-get-indentation))
5319 (setq next-ind curr-ind)
5320 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5321 (save-excursion (end-of-line) (setq eline (point)))
5322 (if (re-search-forward re-box eline t)
5323 (if (member (match-string 2) '("[ ]" "[-]"))
5324 (setq c-off (1+ c-off))
5325 (setq c-on (1+ c-on))
5328 (org-end-of-item)
5329 (setq next-ind (org-get-indentation))
5331 (goto-char continue-from)
5332 ;; update cookie
5333 (when end-cookie
5334 (delete-region beg-cookie end-cookie)
5335 (goto-char beg-cookie)
5336 (insert
5337 (if is-percent
5338 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5339 (format "[%d/%d]" c-on (+ c-on c-off)))))
5340 ;; update items checkbox if it has one
5341 (when (org-at-item-p)
5342 (org-beginning-of-item)
5343 (when (and (> (+ c-on c-off) 0)
5344 (re-search-forward re-box (point-at-eol) t))
5345 (setq beg-cookie (match-beginning 2)
5346 end-cookie (match-end 2))
5347 (delete-region beg-cookie end-cookie)
5348 (goto-char beg-cookie)
5349 (cond ((= c-off 0) (insert "[X]"))
5350 ((= c-on 0) (insert "[ ]"))
5351 (t (insert "[-]")))
5353 (goto-char continue-from))
5354 (when (interactive-p)
5355 (message "Checkbox satistics updated %s (%d places)"
5356 (if all "in entire file" "in current outline entry") cstat)))))
5358 (defun org-get-checkbox-statistics-face ()
5359 "Select the face for checkbox statistics.
5360 The face will be `org-done' when all relevant boxes are checked. Otherwise
5361 it will be `org-todo'."
5362 (if (match-end 1)
5363 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5364 (if (and (> (match-end 2) (match-beginning 2))
5365 (equal (match-string 2) (match-string 3)))
5366 'org-done
5367 'org-todo)))
5369 (defun org-get-indentation (&optional line)
5370 "Get the indentation of the current line, interpreting tabs.
5371 When LINE is given, assume it represents a line and compute its indentation."
5372 (if line
5373 (if (string-match "^ *" (org-remove-tabs line))
5374 (match-end 0))
5375 (save-excursion
5376 (beginning-of-line 1)
5377 (skip-chars-forward " \t")
5378 (current-column))))
5380 (defun org-remove-tabs (s &optional width)
5381 "Replace tabulators in S with spaces.
5382 Assumes that s is a single line, starting in column 0."
5383 (setq width (or width tab-width))
5384 (while (string-match "\t" s)
5385 (setq s (replace-match
5386 (make-string
5387 (- (* width (/ (+ (match-beginning 0) width) width))
5388 (match-beginning 0)) ?\ )
5389 t t s)))
5392 (defun org-fix-indentation (line ind)
5393 "Fix indentation in LINE.
5394 IND is a cons cell with target and minimum indentation.
5395 If the current indenation in LINE is smaller than the minimum,
5396 leave it alone. If it is larger than ind, set it to the target."
5397 (let* ((l (org-remove-tabs line))
5398 (i (org-get-indentation l))
5399 (i1 (car ind)) (i2 (cdr ind)))
5400 (if (>= i i2) (setq l (substring line i2)))
5401 (if (> i1 0)
5402 (concat (make-string i1 ?\ ) l)
5403 l)))
5405 (defun org-beginning-of-item ()
5406 "Go to the beginning of the current hand-formatted item.
5407 If the cursor is not in an item, throw an error."
5408 (interactive)
5409 (let ((pos (point))
5410 (limit (save-excursion
5411 (condition-case nil
5412 (progn
5413 (org-back-to-heading)
5414 (beginning-of-line 2) (point))
5415 (error (point-min)))))
5416 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5417 ind ind1)
5418 (if (org-at-item-p)
5419 (beginning-of-line 1)
5420 (beginning-of-line 1)
5421 (skip-chars-forward " \t")
5422 (setq ind (current-column))
5423 (if (catch 'exit
5424 (while t
5425 (beginning-of-line 0)
5426 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5428 (if (looking-at "[ \t]*$")
5429 (setq ind1 ind-empty)
5430 (skip-chars-forward " \t")
5431 (setq ind1 (current-column)))
5432 (if (< ind1 ind)
5433 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5435 (goto-char pos)
5436 (error "Not in an item")))))
5438 (defun org-end-of-item ()
5439 "Go to the end of the current hand-formatted item.
5440 If the cursor is not in an item, throw an error."
5441 (interactive)
5442 (let* ((pos (point))
5443 ind1
5444 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5445 (limit (save-excursion (outline-next-heading) (point)))
5446 (ind (save-excursion
5447 (org-beginning-of-item)
5448 (skip-chars-forward " \t")
5449 (current-column)))
5450 (end (catch 'exit
5451 (while t
5452 (beginning-of-line 2)
5453 (if (eobp) (throw 'exit (point)))
5454 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5455 (if (looking-at "[ \t]*$")
5456 (setq ind1 ind-empty)
5457 (skip-chars-forward " \t")
5458 (setq ind1 (current-column)))
5459 (if (<= ind1 ind)
5460 (throw 'exit (point-at-bol)))))))
5461 (if end
5462 (goto-char end)
5463 (goto-char pos)
5464 (error "Not in an item"))))
5466 (defun org-next-item ()
5467 "Move to the beginning of the next item in the current plain list.
5468 Error if not at a plain list, or if this is the last item in the list."
5469 (interactive)
5470 (let (ind ind1 (pos (point)))
5471 (org-beginning-of-item)
5472 (setq ind (org-get-indentation))
5473 (org-end-of-item)
5474 (setq ind1 (org-get-indentation))
5475 (unless (and (org-at-item-p) (= ind ind1))
5476 (goto-char pos)
5477 (error "On last item"))))
5479 (defun org-previous-item ()
5480 "Move to the beginning of the previous item in the current plain list.
5481 Error if not at a plain list, or if this is the first item in the list."
5482 (interactive)
5483 (let (beg ind ind1 (pos (point)))
5484 (org-beginning-of-item)
5485 (setq beg (point))
5486 (setq ind (org-get-indentation))
5487 (goto-char beg)
5488 (catch 'exit
5489 (while t
5490 (beginning-of-line 0)
5491 (if (looking-at "[ \t]*$")
5493 (if (<= (setq ind1 (org-get-indentation)) ind)
5494 (throw 'exit t)))))
5495 (condition-case nil
5496 (if (or (not (org-at-item-p))
5497 (< ind1 (1- ind)))
5498 (error "")
5499 (org-beginning-of-item))
5500 (error (goto-char pos)
5501 (error "On first item")))))
5503 (defun org-first-list-item-p ()
5504 "Is this heading the item in a plain list?"
5505 (unless (org-at-item-p)
5506 (error "Not at a plain list item"))
5507 (org-beginning-of-item)
5508 (= (point) (save-excursion (org-beginning-of-item-list))))
5510 (defun org-move-item-down ()
5511 "Move the plain list item at point down, i.e. swap with following item.
5512 Subitems (items with larger indentation) are considered part of the item,
5513 so this really moves item trees."
5514 (interactive)
5515 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5516 (org-beginning-of-item)
5517 (setq beg0 (point))
5518 (save-excursion
5519 (setq ne-beg (org-back-over-empty-lines))
5520 (setq beg (point)))
5521 (goto-char beg0)
5522 (setq ind (org-get-indentation))
5523 (org-end-of-item)
5524 (setq end0 (point))
5525 (setq ind1 (org-get-indentation))
5526 (setq ne-end (org-back-over-empty-lines))
5527 (setq end (point))
5528 (goto-char beg0)
5529 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5530 ;; include less whitespace
5531 (save-excursion
5532 (goto-char beg)
5533 (forward-line (- ne-beg ne-end))
5534 (setq beg (point))))
5535 (goto-char end0)
5536 (if (and (org-at-item-p) (= ind ind1))
5537 (progn
5538 (org-end-of-item)
5539 (org-back-over-empty-lines)
5540 (setq txt (buffer-substring beg end))
5541 (save-excursion
5542 (delete-region beg end))
5543 (setq pos (point))
5544 (insert txt)
5545 (goto-char pos) (org-skip-whitespace)
5546 (org-maybe-renumber-ordered-list))
5547 (goto-char pos)
5548 (error "Cannot move this item further down"))))
5550 (defun org-move-item-up (arg)
5551 "Move the plain list item at point up, i.e. swap with previous item.
5552 Subitems (items with larger indentation) are considered part of the item,
5553 so this really moves item trees."
5554 (interactive "p")
5555 (let (beg beg0 end ind ind1 (pos (point)) txt
5556 ne-beg ne-ins ins-end)
5557 (org-beginning-of-item)
5558 (setq beg0 (point))
5559 (setq ind (org-get-indentation))
5560 (save-excursion
5561 (setq ne-beg (org-back-over-empty-lines))
5562 (setq beg (point)))
5563 (goto-char beg0)
5564 (org-end-of-item)
5565 (setq end (point))
5566 (goto-char beg0)
5567 (catch 'exit
5568 (while t
5569 (beginning-of-line 0)
5570 (if (looking-at "[ \t]*$")
5571 (if org-empty-line-terminates-plain-lists
5572 (progn
5573 (goto-char pos)
5574 (error "Cannot move this item further up"))
5575 nil)
5576 (if (<= (setq ind1 (org-get-indentation)) ind)
5577 (throw 'exit t)))))
5578 (condition-case nil
5579 (org-beginning-of-item)
5580 (error (goto-char beg)
5581 (error "Cannot move this item further up")))
5582 (setq ind1 (org-get-indentation))
5583 (if (and (org-at-item-p) (= ind ind1))
5584 (progn
5585 (setq ne-ins (org-back-over-empty-lines))
5586 (setq txt (buffer-substring beg end))
5587 (save-excursion
5588 (delete-region beg end))
5589 (setq pos (point))
5590 (insert txt)
5591 (setq ins-end (point))
5592 (goto-char pos) (org-skip-whitespace)
5594 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5595 ;; Move whitespace back to beginning
5596 (save-excursion
5597 (goto-char ins-end)
5598 (let ((kill-whole-line t))
5599 (kill-line (- ne-ins ne-beg)) (point)))
5600 (insert (make-string (- ne-ins ne-beg) ?\n)))
5602 (org-maybe-renumber-ordered-list))
5603 (goto-char pos)
5604 (error "Cannot move this item further up"))))
5606 (defun org-maybe-renumber-ordered-list ()
5607 "Renumber the ordered list at point if setup allows it.
5608 This tests the user option `org-auto-renumber-ordered-lists' before
5609 doing the renumbering."
5610 (interactive)
5611 (when (and org-auto-renumber-ordered-lists
5612 (org-at-item-p))
5613 (if (match-beginning 3)
5614 (org-renumber-ordered-list 1)
5615 (org-fix-bullet-type))))
5617 (defun org-maybe-renumber-ordered-list-safe ()
5618 (condition-case nil
5619 (save-excursion
5620 (org-maybe-renumber-ordered-list))
5621 (error nil)))
5623 (defun org-cycle-list-bullet (&optional which)
5624 "Cycle through the different itemize/enumerate bullets.
5625 This cycle the entire list level through the sequence:
5627 `-' -> `+' -> `*' -> `1.' -> `1)'
5629 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5630 0 meand `-', 1 means `+' etc."
5631 (interactive "P")
5632 (org-preserve-lc
5633 (org-beginning-of-item-list)
5634 (org-at-item-p)
5635 (beginning-of-line 1)
5636 (let ((current (match-string 0))
5637 (prevp (eq which 'previous))
5638 new)
5639 (setq new (cond
5640 ((and (numberp which)
5641 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5642 ((string-match "-" current) (if prevp "1)" "+"))
5643 ((string-match "\\+" current)
5644 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5645 ((string-match "\\*" current) (if prevp "+" "1."))
5646 ((string-match "\\." current) (if prevp "*" "1)"))
5647 ((string-match ")" current) (if prevp "1." "-"))
5648 (t (error "This should not happen"))))
5649 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5650 (org-fix-bullet-type)
5651 (org-maybe-renumber-ordered-list))))
5653 (defun org-get-string-indentation (s)
5654 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5655 (let ((n -1) (i 0) (w tab-width) c)
5656 (catch 'exit
5657 (while (< (setq n (1+ n)) (length s))
5658 (setq c (aref s n))
5659 (cond ((= c ?\ ) (setq i (1+ i)))
5660 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5661 (t (throw 'exit t)))))
5664 (defun org-renumber-ordered-list (arg)
5665 "Renumber an ordered plain list.
5666 Cursor needs to be in the first line of an item, the line that starts
5667 with something like \"1.\" or \"2)\"."
5668 (interactive "p")
5669 (unless (and (org-at-item-p)
5670 (match-beginning 3))
5671 (error "This is not an ordered list"))
5672 (let ((line (org-current-line))
5673 (col (current-column))
5674 (ind (org-get-string-indentation
5675 (buffer-substring (point-at-bol) (match-beginning 3))))
5676 ;; (term (substring (match-string 3) -1))
5677 ind1 (n (1- arg))
5678 fmt)
5679 ;; find where this list begins
5680 (org-beginning-of-item-list)
5681 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5682 (setq fmt (concat "%d" (match-string 1)))
5683 (beginning-of-line 0)
5684 ;; walk forward and replace these numbers
5685 (catch 'exit
5686 (while t
5687 (catch 'next
5688 (beginning-of-line 2)
5689 (if (eobp) (throw 'exit nil))
5690 (if (looking-at "[ \t]*$") (throw 'next nil))
5691 (skip-chars-forward " \t") (setq ind1 (current-column))
5692 (if (> ind1 ind) (throw 'next t))
5693 (if (< ind1 ind) (throw 'exit t))
5694 (if (not (org-at-item-p)) (throw 'exit nil))
5695 (delete-region (match-beginning 2) (match-end 2))
5696 (goto-char (match-beginning 2))
5697 (insert (format fmt (setq n (1+ n)))))))
5698 (goto-line line)
5699 (org-move-to-column col)))
5701 (defun org-fix-bullet-type ()
5702 "Make sure all items in this list have the same bullet as the firsst item."
5703 (interactive)
5704 (unless (org-at-item-p) (error "This is not a list"))
5705 (let ((line (org-current-line))
5706 (col (current-column))
5707 (ind (current-indentation))
5708 ind1 bullet)
5709 ;; find where this list begins
5710 (org-beginning-of-item-list)
5711 (beginning-of-line 1)
5712 ;; find out what the bullet type is
5713 (looking-at "[ \t]*\\(\\S-+\\)")
5714 (setq bullet (match-string 1))
5715 ;; walk forward and replace these numbers
5716 (beginning-of-line 0)
5717 (catch 'exit
5718 (while t
5719 (catch 'next
5720 (beginning-of-line 2)
5721 (if (eobp) (throw 'exit nil))
5722 (if (looking-at "[ \t]*$") (throw 'next nil))
5723 (skip-chars-forward " \t") (setq ind1 (current-column))
5724 (if (> ind1 ind) (throw 'next t))
5725 (if (< ind1 ind) (throw 'exit t))
5726 (if (not (org-at-item-p)) (throw 'exit nil))
5727 (skip-chars-forward " \t")
5728 (looking-at "\\S-+")
5729 (replace-match bullet))))
5730 (goto-line line)
5731 (org-move-to-column col)
5732 (if (string-match "[0-9]" bullet)
5733 (org-renumber-ordered-list 1))))
5735 (defun org-beginning-of-item-list ()
5736 "Go to the beginning of the current item list.
5737 I.e. to the first item in this list."
5738 (interactive)
5739 (org-beginning-of-item)
5740 (let ((pos (point-at-bol))
5741 (ind (org-get-indentation))
5742 ind1)
5743 ;; find where this list begins
5744 (catch 'exit
5745 (while t
5746 (catch 'next
5747 (beginning-of-line 0)
5748 (if (looking-at "[ \t]*$")
5749 (throw (if (bobp) 'exit 'next) t))
5750 (skip-chars-forward " \t") (setq ind1 (current-column))
5751 (if (or (< ind1 ind)
5752 (and (= ind1 ind)
5753 (not (org-at-item-p)))
5754 (bobp))
5755 (throw 'exit t)
5756 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5757 (goto-char pos)))
5760 (defun org-end-of-item-list ()
5761 "Go to the end of the current item list.
5762 I.e. to the text after the last item."
5763 (interactive)
5764 (org-beginning-of-item)
5765 (let ((pos (point-at-bol))
5766 (ind (org-get-indentation))
5767 ind1)
5768 ;; find where this list begins
5769 (catch 'exit
5770 (while t
5771 (catch 'next
5772 (beginning-of-line 2)
5773 (if (looking-at "[ \t]*$")
5774 (throw (if (eobp) 'exit 'next) t))
5775 (skip-chars-forward " \t") (setq ind1 (current-column))
5776 (if (or (< ind1 ind)
5777 (and (= ind1 ind)
5778 (not (org-at-item-p)))
5779 (eobp))
5780 (progn
5781 (setq pos (point-at-bol))
5782 (throw 'exit t))))))
5783 (goto-char pos)))
5786 (defvar org-last-indent-begin-marker (make-marker))
5787 (defvar org-last-indent-end-marker (make-marker))
5789 (defun org-outdent-item (arg)
5790 "Outdent a local list item."
5791 (interactive "p")
5792 (org-indent-item (- arg)))
5794 (defun org-indent-item (arg)
5795 "Indent a local list item."
5796 (interactive "p")
5797 (unless (org-at-item-p)
5798 (error "Not on an item"))
5799 (save-excursion
5800 (let (beg end ind ind1 tmp delta ind-down ind-up)
5801 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5802 (setq beg org-last-indent-begin-marker
5803 end org-last-indent-end-marker)
5804 (org-beginning-of-item)
5805 (setq beg (move-marker org-last-indent-begin-marker (point)))
5806 (org-end-of-item)
5807 (setq end (move-marker org-last-indent-end-marker (point))))
5808 (goto-char beg)
5809 (setq tmp (org-item-indent-positions)
5810 ind (car tmp)
5811 ind-down (nth 2 tmp)
5812 ind-up (nth 1 tmp)
5813 delta (if (> arg 0)
5814 (if ind-down (- ind-down ind) 2)
5815 (if ind-up (- ind-up ind) -2)))
5816 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5817 (while (< (point) end)
5818 (beginning-of-line 1)
5819 (skip-chars-forward " \t") (setq ind1 (current-column))
5820 (delete-region (point-at-bol) (point))
5821 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5822 (beginning-of-line 2))))
5823 (org-fix-bullet-type)
5824 (org-maybe-renumber-ordered-list-safe)
5825 (save-excursion
5826 (beginning-of-line 0)
5827 (condition-case nil (org-beginning-of-item) (error nil))
5828 (org-maybe-renumber-ordered-list-safe)))
5830 (defun org-item-indent-positions ()
5831 "Return indentation for plain list items.
5832 This returns a list with three values: The current indentation, the
5833 parent indentation and the indentation a child should habe.
5834 Assumes cursor in item line."
5835 (let* ((bolpos (point-at-bol))
5836 (ind (org-get-indentation))
5837 ind-down ind-up pos)
5838 (save-excursion
5839 (org-beginning-of-item-list)
5840 (skip-chars-backward "\n\r \t")
5841 (when (org-in-item-p)
5842 (org-beginning-of-item)
5843 (setq ind-up (org-get-indentation))))
5844 (setq pos (point))
5845 (save-excursion
5846 (cond
5847 ((and (condition-case nil (progn (org-previous-item) t)
5848 (error nil))
5849 (or (forward-char 1) t)
5850 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5851 (setq ind-down (org-get-indentation)))
5852 ((and (goto-char pos)
5853 (org-at-item-p))
5854 (goto-char (match-end 0))
5855 (skip-chars-forward " \t")
5856 (setq ind-down (current-column)))))
5857 (list ind ind-up ind-down)))
5859 ;;; The orgstruct minor mode
5861 ;; Define a minor mode which can be used in other modes in order to
5862 ;; integrate the org-mode structure editing commands.
5864 ;; This is really a hack, because the org-mode structure commands use
5865 ;; keys which normally belong to the major mode. Here is how it
5866 ;; works: The minor mode defines all the keys necessary to operate the
5867 ;; structure commands, but wraps the commands into a function which
5868 ;; tests if the cursor is currently at a headline or a plain list
5869 ;; item. If that is the case, the structure command is used,
5870 ;; temporarily setting many Org-mode variables like regular
5871 ;; expressions for filling etc. However, when any of those keys is
5872 ;; used at a different location, function uses `key-binding' to look
5873 ;; up if the key has an associated command in another currently active
5874 ;; keymap (minor modes, major mode, global), and executes that
5875 ;; command. There might be problems if any of the keys is otherwise
5876 ;; used as a prefix key.
5878 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5879 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5880 ;; addresses this by checking explicitly for both bindings.
5882 (defvar orgstruct-mode-map (make-sparse-keymap)
5883 "Keymap for the minor `orgstruct-mode'.")
5885 (defvar org-local-vars nil
5886 "List of local variables, for use by `orgstruct-mode'")
5888 ;;;###autoload
5889 (define-minor-mode orgstruct-mode
5890 "Toggle the minor more `orgstruct-mode'.
5891 This mode is for using Org-mode structure commands in other modes.
5892 The following key behave as if Org-mode was active, if the cursor
5893 is on a headline, or on a plain list item (both in the definition
5894 of Org-mode).
5896 M-up Move entry/item up
5897 M-down Move entry/item down
5898 M-left Promote
5899 M-right Demote
5900 M-S-up Move entry/item up
5901 M-S-down Move entry/item down
5902 M-S-left Promote subtree
5903 M-S-right Demote subtree
5904 M-q Fill paragraph and items like in Org-mode
5905 C-c ^ Sort entries
5906 C-c - Cycle list bullet
5907 TAB Cycle item visibility
5908 M-RET Insert new heading/item
5909 S-M-RET Insert new TODO heading / Chekbox item
5910 C-c C-c Set tags / toggle checkbox"
5911 nil " OrgStruct" nil
5912 (org-load-modules-maybe)
5913 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5915 ;;;###autoload
5916 (defun turn-on-orgstruct ()
5917 "Unconditionally turn on `orgstruct-mode'."
5918 (orgstruct-mode 1))
5920 ;;;###autoload
5921 (defun turn-on-orgstruct++ ()
5922 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5923 In addition to setting orgstruct-mode, this also exports all indentation and
5924 autofilling variables from org-mode into the buffer. Note that turning
5925 off orgstruct-mode will *not* remove these additional settings."
5926 (orgstruct-mode 1)
5927 (let (var val)
5928 (mapc
5929 (lambda (x)
5930 (when (string-match
5931 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5932 (symbol-name (car x)))
5933 (setq var (car x) val (nth 1 x))
5934 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5935 org-local-vars)))
5937 (defun orgstruct-error ()
5938 "Error when there is no default binding for a structure key."
5939 (interactive)
5940 (error "This key has no function outside structure elements"))
5942 (defun orgstruct-setup ()
5943 "Setup orgstruct keymaps."
5944 (let ((nfunc 0)
5945 (bindings
5946 (list
5947 '([(meta up)] org-metaup)
5948 '([(meta down)] org-metadown)
5949 '([(meta left)] org-metaleft)
5950 '([(meta right)] org-metaright)
5951 '([(meta shift up)] org-shiftmetaup)
5952 '([(meta shift down)] org-shiftmetadown)
5953 '([(meta shift left)] org-shiftmetaleft)
5954 '([(meta shift right)] org-shiftmetaright)
5955 '([(shift up)] org-shiftup)
5956 '([(shift down)] org-shiftdown)
5957 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5958 '("\M-q" fill-paragraph)
5959 '("\C-c^" org-sort)
5960 '("\C-c-" org-cycle-list-bullet)))
5961 elt key fun cmd)
5962 (while (setq elt (pop bindings))
5963 (setq nfunc (1+ nfunc))
5964 (setq key (org-key (car elt))
5965 fun (nth 1 elt)
5966 cmd (orgstruct-make-binding fun nfunc key))
5967 (org-defkey orgstruct-mode-map key cmd))
5969 ;; Special treatment needed for TAB and RET
5970 (org-defkey orgstruct-mode-map [(tab)]
5971 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5972 (org-defkey orgstruct-mode-map "\C-i"
5973 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5975 (org-defkey orgstruct-mode-map "\M-\C-m"
5976 (orgstruct-make-binding 'org-insert-heading 105
5977 "\M-\C-m" [(meta return)]))
5978 (org-defkey orgstruct-mode-map [(meta return)]
5979 (orgstruct-make-binding 'org-insert-heading 106
5980 [(meta return)] "\M-\C-m"))
5982 (org-defkey orgstruct-mode-map [(shift meta return)]
5983 (orgstruct-make-binding 'org-insert-todo-heading 107
5984 [(meta return)] "\M-\C-m"))
5986 (unless org-local-vars
5987 (setq org-local-vars (org-get-local-variables)))
5991 (defun orgstruct-make-binding (fun n &rest keys)
5992 "Create a function for binding in the structure minor mode.
5993 FUN is the command to call inside a table. N is used to create a unique
5994 command name. KEYS are keys that should be checked in for a command
5995 to execute outside of tables."
5996 (eval
5997 (list 'defun
5998 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5999 '(arg)
6000 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6001 "Outside of structure, run the binding of `"
6002 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6003 "'.")
6004 '(interactive "p")
6005 (list 'if
6006 '(org-context-p 'headline 'item)
6007 (list 'org-run-like-in-org-mode (list 'quote fun))
6008 (list 'let '(orgstruct-mode)
6009 (list 'call-interactively
6010 (append '(or)
6011 (mapcar (lambda (k)
6012 (list 'key-binding k))
6013 keys)
6014 '('orgstruct-error))))))))
6016 (defun org-context-p (&rest contexts)
6017 "Check if local context is and of CONTEXTS.
6018 Possible values in the list of contexts are `table', `headline', and `item'."
6019 (let ((pos (point)))
6020 (goto-char (point-at-bol))
6021 (prog1 (or (and (memq 'table contexts)
6022 (looking-at "[ \t]*|"))
6023 (and (memq 'headline contexts)
6024 (looking-at "\\*+"))
6025 (and (memq 'item contexts)
6026 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6027 (goto-char pos))))
6029 (defun org-get-local-variables ()
6030 "Return a list of all local variables in an org-mode buffer."
6031 (let (varlist)
6032 (with-current-buffer (get-buffer-create "*Org tmp*")
6033 (erase-buffer)
6034 (org-mode)
6035 (setq varlist (buffer-local-variables)))
6036 (kill-buffer "*Org tmp*")
6037 (delq nil
6038 (mapcar
6039 (lambda (x)
6040 (setq x
6041 (if (symbolp x)
6042 (list x)
6043 (list (car x) (list 'quote (cdr x)))))
6044 (if (string-match
6045 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6046 (symbol-name (car x)))
6047 x nil))
6048 varlist))))
6050 ;;;###autoload
6051 (defun org-run-like-in-org-mode (cmd)
6052 (org-load-modules-maybe)
6053 (unless org-local-vars
6054 (setq org-local-vars (org-get-local-variables)))
6055 (eval (list 'let org-local-vars
6056 (list 'call-interactively (list 'quote cmd)))))
6058 ;;;; Archiving
6060 (defun org-get-category (&optional pos)
6061 "Get the category applying to position POS."
6062 (get-text-property (or pos (point)) 'org-category))
6064 (defun org-refresh-category-properties ()
6065 "Refresh category text properties in the buffer."
6066 (let ((def-cat (cond
6067 ((null org-category)
6068 (if buffer-file-name
6069 (file-name-sans-extension
6070 (file-name-nondirectory buffer-file-name))
6071 "???"))
6072 ((symbolp org-category) (symbol-name org-category))
6073 (t org-category)))
6074 beg end cat pos optionp)
6075 (org-unmodified
6076 (save-excursion
6077 (save-restriction
6078 (widen)
6079 (goto-char (point-min))
6080 (put-text-property (point) (point-max) 'org-category def-cat)
6081 (while (re-search-forward
6082 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6083 (setq pos (match-end 0)
6084 optionp (equal (char-after (match-beginning 0)) ?#)
6085 cat (org-trim (match-string 2)))
6086 (if optionp
6087 (setq beg (point-at-bol) end (point-max))
6088 (org-back-to-heading t)
6089 (setq beg (point) end (org-end-of-subtree t t)))
6090 (put-text-property beg end 'org-category cat)
6091 (goto-char pos)))))))
6094 ;;;; Link Stuff
6096 ;;; Link abbreviations
6098 (defun org-link-expand-abbrev (link)
6099 "Apply replacements as defined in `org-link-abbrev-alist."
6100 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6101 (let* ((key (match-string 1 link))
6102 (as (or (assoc key org-link-abbrev-alist-local)
6103 (assoc key org-link-abbrev-alist)))
6104 (tag (and (match-end 2) (match-string 3 link)))
6105 rpl)
6106 (if (not as)
6107 link
6108 (setq rpl (cdr as))
6109 (cond
6110 ((symbolp rpl) (funcall rpl tag))
6111 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6112 (t (concat rpl tag)))))
6113 link))
6115 ;;; Storing and inserting links
6117 (defvar org-insert-link-history nil
6118 "Minibuffer history for links inserted with `org-insert-link'.")
6120 (defvar org-stored-links nil
6121 "Contains the links stored with `org-store-link'.")
6123 (defvar org-store-link-plist nil
6124 "Plist with info about the most recently link created with `org-store-link'.")
6126 (defvar org-link-protocols nil
6127 "Link protocols added to Org-mode using `org-add-link-type'.")
6129 (defvar org-store-link-functions nil
6130 "List of functions that are called to create and store a link.
6131 Each function will be called in turn until one returns a non-nil
6132 value. Each function should check if it is responsible for creating
6133 this link (for example by looking at the major mode).
6134 If not, it must exit and return nil.
6135 If yes, it should return a non-nil value after a calling
6136 `org-store-link-props' with a list of properties and values.
6137 Special properties are:
6139 :type The link prefix. like \"http\". This must be given.
6140 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6141 This is obligatory as well.
6142 :description Optional default description for the second pair
6143 of brackets in an Org-mode link. The user can still change
6144 this when inserting this link into an Org-mode buffer.
6146 In addition to these, any additional properties can be specified
6147 and then used in remember templates.")
6149 (defun org-add-link-type (type &optional follow export)
6150 "Add TYPE to the list of `org-link-types'.
6151 Re-compute all regular expressions depending on `org-link-types'
6153 FOLLOW and EXPORT are two functions.
6155 FOLLOW should take the link path as the single argument and do whatever
6156 is necessary to follow the link, for example find a file or display
6157 a mail message.
6159 EXPORT should format the link path for export to one of the export formats.
6160 It should be a function accepting three arguments:
6162 path the path of the link, the text after the prefix (like \"http:\")
6163 desc the description of the link, if any, nil if there was no descripton
6164 format the export format, a symbol like `html' or `latex'.
6166 The function may use the FORMAT information to return different values
6167 depending on the format. The return value will be put literally into
6168 the exported file.
6169 Org-mode has a built-in default for exporting links. If you are happy with
6170 this default, there is no need to define an export function for the link
6171 type. For a simple example of an export function, see `org-bbdb.el'."
6172 (add-to-list 'org-link-types type t)
6173 (org-make-link-regexps)
6174 (if (assoc type org-link-protocols)
6175 (setcdr (assoc type org-link-protocols) (list follow export))
6176 (push (list type follow export) org-link-protocols)))
6179 ;;;###autoload
6180 (defun org-store-link (arg)
6181 "\\<org-mode-map>Store an org-link to the current location.
6182 This link is added to `org-stored-links' and can later be inserted
6183 into an org-buffer with \\[org-insert-link].
6185 For some link types, a prefix arg is interpreted:
6186 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6187 For file links, arg negates `org-context-in-file-links'."
6188 (interactive "P")
6189 (org-load-modules-maybe)
6190 (setq org-store-link-plist nil) ; reset
6191 (let (link cpltxt desc description search txt)
6192 (cond
6194 ((run-hook-with-args-until-success 'org-store-link-functions)
6195 (setq link (plist-get org-store-link-plist :link)
6196 desc (or (plist-get org-store-link-plist :description) link)))
6198 ((eq major-mode 'calendar-mode)
6199 (let ((cd (calendar-cursor-to-date)))
6200 (setq link
6201 (format-time-string
6202 (car org-time-stamp-formats)
6203 (apply 'encode-time
6204 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6205 nil nil nil))))
6206 (org-store-link-props :type "calendar" :date cd)))
6208 ((eq major-mode 'w3-mode)
6209 (setq cpltxt (url-view-url t)
6210 link (org-make-link cpltxt))
6211 (org-store-link-props :type "w3" :url (url-view-url t)))
6213 ((eq major-mode 'w3m-mode)
6214 (setq cpltxt (or w3m-current-title w3m-current-url)
6215 link (org-make-link w3m-current-url))
6216 (org-store-link-props :type "w3m" :url (url-view-url t)))
6218 ((setq search (run-hook-with-args-until-success
6219 'org-create-file-search-functions))
6220 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6221 "::" search))
6222 (setq cpltxt (or description link)))
6224 ((eq major-mode 'image-mode)
6225 (setq cpltxt (concat "file:"
6226 (abbreviate-file-name buffer-file-name))
6227 link (org-make-link cpltxt))
6228 (org-store-link-props :type "image" :file buffer-file-name))
6230 ((eq major-mode 'dired-mode)
6231 ;; link to the file in the current line
6232 (setq cpltxt (concat "file:"
6233 (abbreviate-file-name
6234 (expand-file-name
6235 (dired-get-filename nil t))))
6236 link (org-make-link cpltxt)))
6238 ((and buffer-file-name (org-mode-p))
6239 ;; Just link to current headline
6240 (setq cpltxt (concat "file:"
6241 (abbreviate-file-name buffer-file-name)))
6242 ;; Add a context search string
6243 (when (org-xor org-context-in-file-links arg)
6244 ;; Check if we are on a target
6245 (if (org-in-regexp "<<\\(.*?\\)>>")
6246 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6247 (setq txt (cond
6248 ((org-on-heading-p) nil)
6249 ((org-region-active-p)
6250 (buffer-substring (region-beginning) (region-end)))
6251 (t nil)))
6252 (when (or (null txt) (string-match "\\S-" txt))
6253 (setq cpltxt
6254 (concat cpltxt "::"
6255 (condition-case nil
6256 (org-make-org-heading-search-string txt)
6257 (error "")))
6258 desc "NONE"))))
6259 (if (string-match "::\\'" cpltxt)
6260 (setq cpltxt (substring cpltxt 0 -2)))
6261 (setq link (org-make-link cpltxt)))
6263 ((buffer-file-name (buffer-base-buffer))
6264 ;; Just link to this file here.
6265 (setq cpltxt (concat "file:"
6266 (abbreviate-file-name
6267 (buffer-file-name (buffer-base-buffer)))))
6268 ;; Add a context string
6269 (when (org-xor org-context-in-file-links arg)
6270 (setq txt (if (org-region-active-p)
6271 (buffer-substring (region-beginning) (region-end))
6272 (buffer-substring (point-at-bol) (point-at-eol))))
6273 ;; Only use search option if there is some text.
6274 (when (string-match "\\S-" txt)
6275 (setq cpltxt
6276 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6277 desc "NONE")))
6278 (setq link (org-make-link cpltxt)))
6280 ((interactive-p)
6281 (error "Cannot link to a buffer which is not visiting a file"))
6283 (t (setq link nil)))
6285 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6286 (setq link (or link cpltxt)
6287 desc (or desc cpltxt))
6288 (if (equal desc "NONE") (setq desc nil))
6290 (if (and (interactive-p) link)
6291 (progn
6292 (setq org-stored-links
6293 (cons (list link desc) org-stored-links))
6294 (message "Stored: %s" (or desc link)))
6295 (and link (org-make-link-string link desc)))))
6297 (defun org-store-link-props (&rest plist)
6298 "Store link properties, extract names and addresses."
6299 (let (x adr)
6300 (when (setq x (plist-get plist :from))
6301 (setq adr (mail-extract-address-components x))
6302 (plist-put plist :fromname (car adr))
6303 (plist-put plist :fromaddress (nth 1 adr)))
6304 (when (setq x (plist-get plist :to))
6305 (setq adr (mail-extract-address-components x))
6306 (plist-put plist :toname (car adr))
6307 (plist-put plist :toaddress (nth 1 adr))))
6308 (let ((from (plist-get plist :from))
6309 (to (plist-get plist :to)))
6310 (when (and from to org-from-is-user-regexp)
6311 (plist-put plist :fromto
6312 (if (string-match org-from-is-user-regexp from)
6313 (concat "to %t")
6314 (concat "from %f")))))
6315 (setq org-store-link-plist plist))
6317 (defun org-add-link-props (&rest plist)
6318 "Add these properties to the link property list."
6319 (let (key value)
6320 (while plist
6321 (setq key (pop plist) value (pop plist))
6322 (setq org-store-link-plist
6323 (plist-put org-store-link-plist key value)))))
6325 (defun org-email-link-description (&optional fmt)
6326 "Return the description part of an email link.
6327 This takes information from `org-store-link-plist' and formats it
6328 according to FMT (default from `org-email-link-description-format')."
6329 (setq fmt (or fmt org-email-link-description-format))
6330 (let* ((p org-store-link-plist)
6331 (to (plist-get p :toaddress))
6332 (from (plist-get p :fromaddress))
6333 (table
6334 (list
6335 (cons "%c" (plist-get p :fromto))
6336 (cons "%F" (plist-get p :from))
6337 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6338 (cons "%T" (plist-get p :to))
6339 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6340 (cons "%s" (plist-get p :subject))
6341 (cons "%m" (plist-get p :message-id)))))
6342 (when (string-match "%c" fmt)
6343 ;; Check if the user wrote this message
6344 (if (and org-from-is-user-regexp from to
6345 (save-match-data (string-match org-from-is-user-regexp from)))
6346 (setq fmt (replace-match "to %t" t t fmt))
6347 (setq fmt (replace-match "from %f" t t fmt))))
6348 (org-replace-escapes fmt table)))
6350 (defun org-make-org-heading-search-string (&optional string heading)
6351 "Make search string for STRING or current headline."
6352 (interactive)
6353 (let ((s (or string (org-get-heading))))
6354 (unless (and string (not heading))
6355 ;; We are using a headline, clean up garbage in there.
6356 (if (string-match org-todo-regexp s)
6357 (setq s (replace-match "" t t s)))
6358 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6359 (setq s (replace-match "" t t s)))
6360 (setq s (org-trim s))
6361 (if (string-match (concat "^\\(" org-quote-string "\\|"
6362 org-comment-string "\\)") s)
6363 (setq s (replace-match "" t t s)))
6364 (while (string-match org-ts-regexp s)
6365 (setq s (replace-match "" t t s))))
6366 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6367 (setq s (replace-match " " t t s)))
6368 (or string (setq s (concat "*" s))) ; Add * for headlines
6369 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6371 (defun org-make-link (&rest strings)
6372 "Concatenate STRINGS."
6373 (apply 'concat strings))
6375 (defun org-make-link-string (link &optional description)
6376 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6377 (unless (string-match "\\S-" link)
6378 (error "Empty link"))
6379 (when (stringp description)
6380 ;; Remove brackets from the description, they are fatal.
6381 (while (string-match "\\[" description)
6382 (setq description (replace-match "{" t t description)))
6383 (while (string-match "\\]" description)
6384 (setq description (replace-match "}" t t description))))
6385 (when (equal (org-link-escape link) description)
6386 ;; No description needed, it is identical
6387 (setq description nil))
6388 (when (and (not description)
6389 (not (equal link (org-link-escape link))))
6390 (setq description link))
6391 (concat "[[" (org-link-escape link) "]"
6392 (if description (concat "[" description "]") "")
6393 "]"))
6395 (defconst org-link-escape-chars
6396 '((?\ . "%20")
6397 (?\[ . "%5B")
6398 (?\] . "%5D")
6399 (?\340 . "%E0") ; `a
6400 (?\342 . "%E2") ; ^a
6401 (?\347 . "%E7") ; ,c
6402 (?\350 . "%E8") ; `e
6403 (?\351 . "%E9") ; 'e
6404 (?\352 . "%EA") ; ^e
6405 (?\356 . "%EE") ; ^i
6406 (?\364 . "%F4") ; ^o
6407 (?\371 . "%F9") ; `u
6408 (?\373 . "%FB") ; ^u
6409 (?\; . "%3B")
6410 (?? . "%3F")
6411 (?= . "%3D")
6412 (?+ . "%2B")
6414 "Association list of escapes for some characters problematic in links.
6415 This is the list that is used for internal purposes.")
6417 (defconst org-link-escape-chars-browser
6418 '((?\ . "%20")) ; 32 for the SPC char
6419 "Association list of escapes for some characters problematic in links.
6420 This is the list that is used before handing over to the browser.")
6422 (defun org-link-escape (text &optional table)
6423 "Escape charaters in TEXT that are problematic for links."
6424 (setq table (or table org-link-escape-chars))
6425 (when text
6426 (let ((re (mapconcat (lambda (x) (regexp-quote
6427 (char-to-string (car x))))
6428 table "\\|")))
6429 (while (string-match re text)
6430 (setq text
6431 (replace-match
6432 (cdr (assoc (string-to-char (match-string 0 text))
6433 table))
6434 t t text)))
6435 text)))
6437 (defun org-link-unescape (text &optional table)
6438 "Reverse the action of `org-link-escape'."
6439 (setq table (or table org-link-escape-chars))
6440 (when text
6441 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6442 table "\\|")))
6443 (while (string-match re text)
6444 (setq text
6445 (replace-match
6446 (char-to-string (car (rassoc (match-string 0 text) table)))
6447 t t text)))
6448 text)))
6450 (defun org-xor (a b)
6451 "Exclusive or."
6452 (if a (not b) b))
6454 (defun org-get-header (header)
6455 "Find a header field in the current buffer."
6456 (save-excursion
6457 (goto-char (point-min))
6458 (let ((case-fold-search t) s)
6459 (cond
6460 ((eq header 'from)
6461 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6462 (setq s (match-string 1)))
6463 (while (string-match "\"" s)
6464 (setq s (replace-match "" t t s)))
6465 (if (string-match "[<(].*" s)
6466 (setq s (replace-match "" t t s))))
6467 ((eq header 'message-id)
6468 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6469 (setq s (match-string 1))))
6470 ((eq header 'subject)
6471 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6472 (setq s (match-string 1)))))
6473 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6474 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6475 s)))
6478 (defun org-fixup-message-id-for-http (s)
6479 "Replace special characters in a message id, so it can be used in an http query."
6480 (while (string-match "<" s)
6481 (setq s (replace-match "%3C" t t s)))
6482 (while (string-match ">" s)
6483 (setq s (replace-match "%3E" t t s)))
6484 (while (string-match "@" s)
6485 (setq s (replace-match "%40" t t s)))
6488 ;;;###autoload
6489 (defun org-insert-link-global ()
6490 "Insert a link like Org-mode does.
6491 This command can be called in any mode to insert a link in Org-mode syntax."
6492 (interactive)
6493 (org-load-modules-maybe)
6494 (org-run-like-in-org-mode 'org-insert-link))
6496 (defun org-insert-link (&optional complete-file link-location)
6497 "Insert a link. At the prompt, enter the link.
6499 Completion can be used to select a link previously stored with
6500 `org-store-link'. When the empty string is entered (i.e. if you just
6501 press RET at the prompt), the link defaults to the most recently
6502 stored link. As SPC triggers completion in the minibuffer, you need to
6503 use M-SPC or C-q SPC to force the insertion of a space character.
6505 You will also be prompted for a description, and if one is given, it will
6506 be displayed in the buffer instead of the link.
6508 If there is already a link at point, this command will allow you to edit link
6509 and description parts.
6511 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6512 be selected using completion. The path to the file will be relative to the
6513 current directory if the file is in the current directory or a subdirectory.
6514 Otherwise, the link will be the absolute path as completed in the minibuffer
6515 \(i.e. normally ~/path/to/file).
6517 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6518 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6519 of `org-keep-stored-link-after-insertion'.
6521 If `org-make-link-description-function' is non-nil, this function will be
6522 called with the link target, and the result will be the default
6523 link description.
6525 If the LINK-LOCATION parameter is non-nil, this value will be
6526 used as the link location instead of reading one interactively."
6527 (interactive "P")
6528 (let* ((wcf (current-window-configuration))
6529 (region (if (org-region-active-p)
6530 (buffer-substring (region-beginning) (region-end))))
6531 (remove (and region (list (region-beginning) (region-end))))
6532 (desc region)
6533 tmphist ; byte-compile incorrectly complains about this
6534 (link link-location)
6535 entry file)
6536 (cond
6537 (link-location) ; specified by arg, just use it.
6538 ((org-in-regexp org-bracket-link-regexp 1)
6539 ;; We do have a link at point, and we are going to edit it.
6540 (setq remove (list (match-beginning 0) (match-end 0)))
6541 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6542 (setq link (read-string "Link: "
6543 (org-link-unescape
6544 (org-match-string-no-properties 1)))))
6545 ((or (org-in-regexp org-angle-link-re)
6546 (org-in-regexp org-plain-link-re))
6547 ;; Convert to bracket link
6548 (setq remove (list (match-beginning 0) (match-end 0))
6549 link (read-string "Link: "
6550 (org-remove-angle-brackets (match-string 0)))))
6551 ((equal complete-file '(4))
6552 ;; Completing read for file names.
6553 (setq file (read-file-name "File: "))
6554 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6555 (pwd1 (file-name-as-directory (abbreviate-file-name
6556 (expand-file-name ".")))))
6557 (cond
6558 ((equal complete-file '(16))
6559 (setq link (org-make-link
6560 "file:"
6561 (abbreviate-file-name (expand-file-name file)))))
6562 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6563 (setq link (org-make-link "file:" (match-string 1 file))))
6564 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6565 (expand-file-name file))
6566 (setq link (org-make-link
6567 "file:" (match-string 1 (expand-file-name file)))))
6568 (t (setq link (org-make-link "file:" file))))))
6570 ;; Read link, with completion for stored links.
6571 (with-output-to-temp-buffer "*Org Links*"
6572 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6573 (when org-stored-links
6574 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6575 (princ (mapconcat
6576 (lambda (x)
6577 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6578 (reverse org-stored-links) "\n"))))
6579 (let ((cw (selected-window)))
6580 (select-window (get-buffer-window "*Org Links*"))
6581 (shrink-window-if-larger-than-buffer)
6582 (setq truncate-lines t)
6583 (select-window cw))
6584 ;; Fake a link history, containing the stored links.
6585 (setq tmphist (append (mapcar 'car org-stored-links)
6586 org-insert-link-history))
6587 (unwind-protect
6588 (setq link (org-completing-read
6589 "Link: "
6590 (append
6591 (mapcar (lambda (x) (list (concat (car x) ":")))
6592 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6593 (mapcar (lambda (x) (list (concat x ":")))
6594 org-link-types))
6595 nil nil nil
6596 'tmphist
6597 (or (car (car org-stored-links)))))
6598 (set-window-configuration wcf)
6599 (kill-buffer "*Org Links*"))
6600 (setq entry (assoc link org-stored-links))
6601 (or entry (push link org-insert-link-history))
6602 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6603 (not org-keep-stored-link-after-insertion))
6604 (setq org-stored-links (delq (assoc link org-stored-links)
6605 org-stored-links)))
6606 (setq desc (or desc (nth 1 entry)))))
6608 (if (string-match org-plain-link-re link)
6609 ;; URL-like link, normalize the use of angular brackets.
6610 (setq link (org-make-link (org-remove-angle-brackets link))))
6612 ;; Check if we are linking to the current file with a search option
6613 ;; If yes, simplify the link by using only the search option.
6614 (when (and buffer-file-name
6615 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6616 (let* ((path (match-string 1 link))
6617 (case-fold-search nil)
6618 (search (match-string 2 link)))
6619 (save-match-data
6620 (if (equal (file-truename buffer-file-name) (file-truename path))
6621 ;; We are linking to this same file, with a search option
6622 (setq link search)))))
6624 ;; Check if we can/should use a relative path. If yes, simplify the link
6625 (when (string-match "\\<file:\\(.*\\)" link)
6626 (let* ((path (match-string 1 link))
6627 (origpath path)
6628 (case-fold-search nil))
6629 (cond
6630 ((eq org-link-file-path-type 'absolute)
6631 (setq path (abbreviate-file-name (expand-file-name path))))
6632 ((eq org-link-file-path-type 'noabbrev)
6633 (setq path (expand-file-name path)))
6634 ((eq org-link-file-path-type 'relative)
6635 (setq path (file-relative-name path)))
6637 (save-match-data
6638 (if (string-match (concat "^" (regexp-quote
6639 (file-name-as-directory
6640 (expand-file-name "."))))
6641 (expand-file-name path))
6642 ;; We are linking a file with relative path name.
6643 (setq path (substring (expand-file-name path)
6644 (match-end 0)))))))
6645 (setq link (concat "file:" path))
6646 (if (equal desc origpath)
6647 (setq desc path))))
6649 (if org-make-link-description-function
6650 (setq desc (funcall org-make-link-description-function link desc)))
6652 (setq desc (read-string "Description: " desc))
6653 (unless (string-match "\\S-" desc) (setq desc nil))
6654 (if remove (apply 'delete-region remove))
6655 (insert (org-make-link-string link desc))))
6657 (defun org-completing-read (&rest args)
6658 (let ((minibuffer-local-completion-map
6659 (copy-keymap minibuffer-local-completion-map)))
6660 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6661 (apply 'completing-read args)))
6663 ;;; Opening/following a link
6665 (defvar org-link-search-failed nil)
6667 (defun org-next-link ()
6668 "Move forward to the next link.
6669 If the link is in hidden text, expose it."
6670 (interactive)
6671 (when (and org-link-search-failed (eq this-command last-command))
6672 (goto-char (point-min))
6673 (message "Link search wrapped back to beginning of buffer"))
6674 (setq org-link-search-failed nil)
6675 (let* ((pos (point))
6676 (ct (org-context))
6677 (a (assoc :link ct)))
6678 (if a (goto-char (nth 2 a)))
6679 (if (re-search-forward org-any-link-re nil t)
6680 (progn
6681 (goto-char (match-beginning 0))
6682 (if (org-invisible-p) (org-show-context)))
6683 (goto-char pos)
6684 (setq org-link-search-failed t)
6685 (error "No further link found"))))
6687 (defun org-previous-link ()
6688 "Move backward to the previous link.
6689 If the link is in hidden text, expose it."
6690 (interactive)
6691 (when (and org-link-search-failed (eq this-command last-command))
6692 (goto-char (point-max))
6693 (message "Link search wrapped back to end of buffer"))
6694 (setq org-link-search-failed nil)
6695 (let* ((pos (point))
6696 (ct (org-context))
6697 (a (assoc :link ct)))
6698 (if a (goto-char (nth 1 a)))
6699 (if (re-search-backward org-any-link-re nil t)
6700 (progn
6701 (goto-char (match-beginning 0))
6702 (if (org-invisible-p) (org-show-context)))
6703 (goto-char pos)
6704 (setq org-link-search-failed t)
6705 (error "No further link found"))))
6707 (defun org-find-file-at-mouse (ev)
6708 "Open file link or URL at mouse."
6709 (interactive "e")
6710 (mouse-set-point ev)
6711 (org-open-at-point 'in-emacs))
6713 (defun org-open-at-mouse (ev)
6714 "Open file link or URL at mouse."
6715 (interactive "e")
6716 (mouse-set-point ev)
6717 (org-open-at-point))
6719 (defvar org-window-config-before-follow-link nil
6720 "The window configuration before following a link.
6721 This is saved in case the need arises to restore it.")
6723 (defvar org-open-link-marker (make-marker)
6724 "Marker pointing to the location where `org-open-at-point; was called.")
6726 ;;;###autoload
6727 (defun org-open-at-point-global ()
6728 "Follow a link like Org-mode does.
6729 This command can be called in any mode to follow a link that has
6730 Org-mode syntax."
6731 (interactive)
6732 (org-run-like-in-org-mode 'org-open-at-point))
6734 ;;;###autoload
6735 (defun org-open-link-from-string (s &optional arg)
6736 "Open a link in the string S, as if it was in Org-mode."
6737 (interactive "sLink: \nP")
6738 (with-temp-buffer
6739 (let ((org-inhibit-startup t))
6740 (org-mode)
6741 (insert s)
6742 (goto-char (point-min))
6743 (org-open-at-point arg))))
6745 (defun org-open-at-point (&optional in-emacs)
6746 "Open link at or after point.
6747 If there is no link at point, this function will search forward up to
6748 the end of the current subtree.
6749 Normally, files will be opened by an appropriate application. If the
6750 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6751 (interactive "P")
6752 (org-load-modules-maybe)
6753 (move-marker org-open-link-marker (point))
6754 (setq org-window-config-before-follow-link (current-window-configuration))
6755 (org-remove-occur-highlights nil nil t)
6756 (if (org-at-timestamp-p t)
6757 (org-follow-timestamp-link)
6758 (let (type path link line search (pos (point)))
6759 (catch 'match
6760 (save-excursion
6761 (skip-chars-forward "^]\n\r")
6762 (when (org-in-regexp org-bracket-link-regexp)
6763 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6764 (while (string-match " *\n *" link)
6765 (setq link (replace-match " " t t link)))
6766 (setq link (org-link-expand-abbrev link))
6767 (if (string-match org-link-re-with-space2 link)
6768 (setq type (match-string 1 link) path (match-string 2 link))
6769 (setq type "thisfile" path link))
6770 (throw 'match t)))
6772 (when (get-text-property (point) 'org-linked-text)
6773 (setq type "thisfile"
6774 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6775 (1+ (point)) (point))
6776 path (buffer-substring
6777 (previous-single-property-change pos 'org-linked-text)
6778 (next-single-property-change pos 'org-linked-text)))
6779 (throw 'match t))
6781 (save-excursion
6782 (when (or (org-in-regexp org-angle-link-re)
6783 (org-in-regexp org-plain-link-re))
6784 (setq type (match-string 1) path (match-string 2))
6785 (throw 'match t)))
6786 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6787 (setq type "tree-match"
6788 path (match-string 1))
6789 (throw 'match t))
6790 (save-excursion
6791 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6792 (setq type "tags"
6793 path (match-string 1))
6794 (while (string-match ":" path)
6795 (setq path (replace-match "+" t t path)))
6796 (throw 'match t))))
6797 (unless path
6798 (error "No link found"))
6799 ;; Remove any trailing spaces in path
6800 (if (string-match " +\\'" path)
6801 (setq path (replace-match "" t t path)))
6803 (cond
6805 ((assoc type org-link-protocols)
6806 (funcall (nth 1 (assoc type org-link-protocols)) path))
6808 ((equal type "mailto")
6809 (let ((cmd (car org-link-mailto-program))
6810 (args (cdr org-link-mailto-program)) args1
6811 (address path) (subject "") a)
6812 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6813 (setq address (match-string 1 path)
6814 subject (org-link-escape (match-string 2 path))))
6815 (while args
6816 (cond
6817 ((not (stringp (car args))) (push (pop args) args1))
6818 (t (setq a (pop args))
6819 (if (string-match "%a" a)
6820 (setq a (replace-match address t t a)))
6821 (if (string-match "%s" a)
6822 (setq a (replace-match subject t t a)))
6823 (push a args1))))
6824 (apply cmd (nreverse args1))))
6826 ((member type '("http" "https" "ftp" "news"))
6827 (browse-url (concat type ":" (org-link-escape
6828 path org-link-escape-chars-browser))))
6830 ((member type '("message"))
6831 (browse-url (concat type ":" path)))
6833 ((string= type "tags")
6834 (org-tags-view in-emacs path))
6835 ((string= type "thisfile")
6836 (if in-emacs
6837 (switch-to-buffer-other-window
6838 (org-get-buffer-for-internal-link (current-buffer)))
6839 (org-mark-ring-push))
6840 (let ((cmd `(org-link-search
6841 ,path
6842 ,(cond ((equal in-emacs '(4)) 'occur)
6843 ((equal in-emacs '(16)) 'org-occur)
6844 (t nil))
6845 ,pos)))
6846 (condition-case nil (eval cmd)
6847 (error (progn (widen) (eval cmd))))))
6849 ((string= type "tree-match")
6850 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6852 ((string= type "file")
6853 (if (string-match "::\\([0-9]+\\)\\'" path)
6854 (setq line (string-to-number (match-string 1 path))
6855 path (substring path 0 (match-beginning 0)))
6856 (if (string-match "::\\(.+\\)\\'" path)
6857 (setq search (match-string 1 path)
6858 path (substring path 0 (match-beginning 0)))))
6859 (if (string-match "[*?{]" (file-name-nondirectory path))
6860 (dired path)
6861 (org-open-file path in-emacs line search)))
6863 ((string= type "news")
6864 (require 'org-gnus)
6865 (org-gnus-follow-link path))
6867 ((string= type "shell")
6868 (let ((cmd path))
6869 (if (or (not org-confirm-shell-link-function)
6870 (funcall org-confirm-shell-link-function
6871 (format "Execute \"%s\" in shell? "
6872 (org-add-props cmd nil
6873 'face 'org-warning))))
6874 (progn
6875 (message "Executing %s" cmd)
6876 (shell-command cmd))
6877 (error "Abort"))))
6879 ((string= type "elisp")
6880 (let ((cmd path))
6881 (if (or (not org-confirm-elisp-link-function)
6882 (funcall org-confirm-elisp-link-function
6883 (format "Execute \"%s\" as elisp? "
6884 (org-add-props cmd nil
6885 'face 'org-warning))))
6886 (message "%s => %s" cmd (eval (read cmd)))
6887 (error "Abort"))))
6890 (browse-url-at-point)))))
6891 (move-marker org-open-link-marker nil)
6892 (run-hook-with-args 'org-follow-link-hook))
6894 ;;;; Time estimates
6896 (defun org-get-effort (&optional pom)
6897 "Get the effort estimate for the current entry."
6898 (org-entry-get pom org-effort-property))
6900 ;;; File search
6902 (defvar org-create-file-search-functions nil
6903 "List of functions to construct the right search string for a file link.
6904 These functions are called in turn with point at the location to
6905 which the link should point.
6907 A function in the hook should first test if it would like to
6908 handle this file type, for example by checking the major-mode or
6909 the file extension. If it decides not to handle this file, it
6910 should just return nil to give other functions a chance. If it
6911 does handle the file, it must return the search string to be used
6912 when following the link. The search string will be part of the
6913 file link, given after a double colon, and `org-open-at-point'
6914 will automatically search for it. If special measures must be
6915 taken to make the search successful, another function should be
6916 added to the companion hook `org-execute-file-search-functions',
6917 which see.
6919 A function in this hook may also use `setq' to set the variable
6920 `description' to provide a suggestion for the descriptive text to
6921 be used for this link when it gets inserted into an Org-mode
6922 buffer with \\[org-insert-link].")
6924 (defvar org-execute-file-search-functions nil
6925 "List of functions to execute a file search triggered by a link.
6927 Functions added to this hook must accept a single argument, the
6928 search string that was part of the file link, the part after the
6929 double colon. The function must first check if it would like to
6930 handle this search, for example by checking the major-mode or the
6931 file extension. If it decides not to handle this search, it
6932 should just return nil to give other functions a chance. If it
6933 does handle the search, it must return a non-nil value to keep
6934 other functions from trying.
6936 Each function can access the current prefix argument through the
6937 variable `current-prefix-argument'. Note that a single prefix is
6938 used to force opening a link in Emacs, so it may be good to only
6939 use a numeric or double prefix to guide the search function.
6941 In case this is needed, a function in this hook can also restore
6942 the window configuration before `org-open-at-point' was called using:
6944 (set-window-configuration org-window-config-before-follow-link)")
6946 (defun org-link-search (s &optional type avoid-pos)
6947 "Search for a link search option.
6948 If S is surrounded by forward slashes, it is interpreted as a
6949 regular expression. In org-mode files, this will create an `org-occur'
6950 sparse tree. In ordinary files, `occur' will be used to list matches.
6951 If the current buffer is in `dired-mode', grep will be used to search
6952 in all files. If AVOID-POS is given, ignore matches near that position."
6953 (let ((case-fold-search t)
6954 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6955 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6956 (append '(("") (" ") ("\t") ("\n"))
6957 org-emphasis-alist)
6958 "\\|") "\\)"))
6959 (pos (point))
6960 (pre nil) (post nil)
6961 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6962 (cond
6963 ;; First check if there are any special
6964 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6965 ;; Now try the builtin stuff
6966 ((save-excursion
6967 (goto-char (point-min))
6968 (and
6969 (re-search-forward
6970 (concat "<<" (regexp-quote s0) ">>") nil t)
6971 (setq type 'dedicated
6972 pos (match-beginning 0))))
6973 ;; There is an exact target for this
6974 (goto-char pos))
6975 ((string-match "^/\\(.*\\)/$" s)
6976 ;; A regular expression
6977 (cond
6978 ((org-mode-p)
6979 (org-occur (match-string 1 s)))
6980 ;;((eq major-mode 'dired-mode)
6981 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6982 (t (org-do-occur (match-string 1 s)))))
6984 ;; A normal search strings
6985 (when (equal (string-to-char s) ?*)
6986 ;; Anchor on headlines, post may include tags.
6987 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6988 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6989 s (substring s 1)))
6990 (remove-text-properties
6991 0 (length s)
6992 '(face nil mouse-face nil keymap nil fontified nil) s)
6993 ;; Make a series of regular expressions to find a match
6994 (setq words (org-split-string s "[ \n\r\t]+")
6996 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6997 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6998 "\\)" markers)
6999 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7000 re2a (concat "[ \t\r\n]" re2a_)
7001 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7002 re4 (concat "[^a-zA-Z_]" re4_)
7004 re1 (concat pre re2 post)
7005 re3 (concat pre (if pre re4_ re4) post)
7006 re5 (concat pre ".*" re4)
7007 re2 (concat pre re2)
7008 re2a (concat pre (if pre re2a_ re2a))
7009 re4 (concat pre (if pre re4_ re4))
7010 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7011 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7012 re5 "\\)"
7014 (cond
7015 ((eq type 'org-occur) (org-occur reall))
7016 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7017 (t (goto-char (point-min))
7018 (setq type 'fuzzy)
7019 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7020 (org-search-not-self 1 re1 nil t)
7021 (org-search-not-self 1 re2 nil t)
7022 (org-search-not-self 1 re2a nil t)
7023 (org-search-not-self 1 re3 nil t)
7024 (org-search-not-self 1 re4 nil t)
7025 (org-search-not-self 1 re5 nil t)
7027 (goto-char (match-beginning 1))
7028 (goto-char pos)
7029 (error "No match")))))
7031 ;; Normal string-search
7032 (goto-char (point-min))
7033 (if (search-forward s nil t)
7034 (goto-char (match-beginning 0))
7035 (error "No match"))))
7036 (and (org-mode-p) (org-show-context 'link-search))
7037 type))
7039 (defun org-search-not-self (group &rest args)
7040 "Execute `re-search-forward', but only accept matches that do not
7041 enclose the position of `org-open-link-marker'."
7042 (let ((m org-open-link-marker))
7043 (catch 'exit
7044 (while (apply 're-search-forward args)
7045 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7046 (goto-char (match-end group))
7047 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7048 (> (match-beginning 0) (marker-position m))
7049 (< (match-end 0) (marker-position m)))
7050 (save-match-data
7051 (or (not (org-in-regexp
7052 org-bracket-link-analytic-regexp 1))
7053 (not (match-end 4)) ; no description
7054 (and (<= (match-beginning 4) (point))
7055 (>= (match-end 4) (point))))))
7056 (throw 'exit (point))))))))
7058 (defun org-get-buffer-for-internal-link (buffer)
7059 "Return a buffer to be used for displaying the link target of internal links."
7060 (cond
7061 ((not org-display-internal-link-with-indirect-buffer)
7062 buffer)
7063 ((string-match "(Clone)$" (buffer-name buffer))
7064 (message "Buffer is already a clone, not making another one")
7065 ;; we also do not modify visibility in this case
7066 buffer)
7067 (t ; make a new indirect buffer for displaying the link
7068 (let* ((bn (buffer-name buffer))
7069 (ibn (concat bn "(Clone)"))
7070 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7071 (with-current-buffer ib (org-overview))
7072 ib))))
7074 (defun org-do-occur (regexp &optional cleanup)
7075 "Call the Emacs command `occur'.
7076 If CLEANUP is non-nil, remove the printout of the regular expression
7077 in the *Occur* buffer. This is useful if the regex is long and not useful
7078 to read."
7079 (occur regexp)
7080 (when cleanup
7081 (let ((cwin (selected-window)) win beg end)
7082 (when (setq win (get-buffer-window "*Occur*"))
7083 (select-window win))
7084 (goto-char (point-min))
7085 (when (re-search-forward "match[a-z]+" nil t)
7086 (setq beg (match-end 0))
7087 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7088 (setq end (1- (match-beginning 0)))))
7089 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7090 (goto-char (point-min))
7091 (select-window cwin))))
7093 ;;; The mark ring for links jumps
7095 (defvar org-mark-ring nil
7096 "Mark ring for positions before jumps in Org-mode.")
7097 (defvar org-mark-ring-last-goto nil
7098 "Last position in the mark ring used to go back.")
7099 ;; Fill and close the ring
7100 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7101 (loop for i from 1 to org-mark-ring-length do
7102 (push (make-marker) org-mark-ring))
7103 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7104 org-mark-ring)
7106 (defun org-mark-ring-push (&optional pos buffer)
7107 "Put the current position or POS into the mark ring and rotate it."
7108 (interactive)
7109 (setq pos (or pos (point)))
7110 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7111 (move-marker (car org-mark-ring)
7112 (or pos (point))
7113 (or buffer (current-buffer)))
7114 (message "%s"
7115 (substitute-command-keys
7116 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7118 (defun org-mark-ring-goto (&optional n)
7119 "Jump to the previous position in the mark ring.
7120 With prefix arg N, jump back that many stored positions. When
7121 called several times in succession, walk through the entire ring.
7122 Org-mode commands jumping to a different position in the current file,
7123 or to another Org-mode file, automatically push the old position
7124 onto the ring."
7125 (interactive "p")
7126 (let (p m)
7127 (if (eq last-command this-command)
7128 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7129 (setq p org-mark-ring))
7130 (setq org-mark-ring-last-goto p)
7131 (setq m (car p))
7132 (switch-to-buffer (marker-buffer m))
7133 (goto-char m)
7134 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7136 (defun org-remove-angle-brackets (s)
7137 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7138 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7140 (defun org-add-angle-brackets (s)
7141 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7142 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7145 ;;; Following specific links
7147 (defun org-follow-timestamp-link ()
7148 (cond
7149 ((org-at-date-range-p t)
7150 (let ((org-agenda-start-on-weekday)
7151 (t1 (match-string 1))
7152 (t2 (match-string 2)))
7153 (setq t1 (time-to-days (org-time-string-to-time t1))
7154 t2 (time-to-days (org-time-string-to-time t2)))
7155 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7156 ((org-at-timestamp-p t)
7157 (org-agenda-list nil (time-to-days (org-time-string-to-time
7158 (substring (match-string 1) 0 10)))
7160 (t (error "This should not happen"))))
7163 ;;; Following file links
7164 (defvar org-wait nil)
7165 (defun org-open-file (path &optional in-emacs line search)
7166 "Open the file at PATH.
7167 First, this expands any special file name abbreviations. Then the
7168 configuration variable `org-file-apps' is checked if it contains an
7169 entry for this file type, and if yes, the corresponding command is launched.
7170 If no application is found, Emacs simply visits the file.
7171 With optional argument IN-EMACS, Emacs will visit the file.
7172 Optional LINE specifies a line to go to, optional SEARCH a string to
7173 search for. If LINE or SEARCH is given, the file will always be
7174 opened in Emacs.
7175 If the file does not exist, an error is thrown."
7176 (setq in-emacs (or in-emacs line search))
7177 (let* ((file (if (equal path "")
7178 buffer-file-name
7179 (substitute-in-file-name (expand-file-name path))))
7180 (apps (append org-file-apps (org-default-apps)))
7181 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7182 (dirp (if remp nil (file-directory-p file)))
7183 (dfile (downcase file))
7184 (old-buffer (current-buffer))
7185 (old-pos (point))
7186 (old-mode major-mode)
7187 ext cmd)
7188 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7189 (setq ext (match-string 1 dfile))
7190 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7191 (setq ext (match-string 1 dfile))))
7192 (if in-emacs
7193 (setq cmd 'emacs)
7194 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7195 (and dirp (cdr (assoc 'directory apps)))
7196 (cdr (assoc ext apps))
7197 (cdr (assoc t apps)))))
7198 (when (eq cmd 'mailcap)
7199 (require 'mailcap)
7200 (mailcap-parse-mailcaps)
7201 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7202 (command (mailcap-mime-info mime-type)))
7203 (if (stringp command)
7204 (setq cmd command)
7205 (setq cmd 'emacs))))
7206 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7207 (not (file-exists-p file))
7208 (not org-open-non-existing-files))
7209 (error "No such file: %s" file))
7210 (cond
7211 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7212 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7213 (while (string-match "['\"]%s['\"]" cmd)
7214 (setq cmd (replace-match "%s" t t cmd)))
7215 (while (string-match "%s" cmd)
7216 (setq cmd (replace-match
7217 (save-match-data (shell-quote-argument file))
7218 t t cmd)))
7219 (save-window-excursion
7220 (start-process-shell-command cmd nil cmd)
7221 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7223 ((or (stringp cmd)
7224 (eq cmd 'emacs))
7225 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7226 (widen)
7227 (if line (goto-line line)
7228 (if search (org-link-search search))))
7229 ((consp cmd)
7230 (eval cmd))
7231 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7232 (and (org-mode-p) (eq old-mode 'org-mode)
7233 (or (not (equal old-buffer (current-buffer)))
7234 (not (equal old-pos (point))))
7235 (org-mark-ring-push old-pos old-buffer))))
7237 (defun org-default-apps ()
7238 "Return the default applications for this operating system."
7239 (cond
7240 ((eq system-type 'darwin)
7241 org-file-apps-defaults-macosx)
7242 ((eq system-type 'windows-nt)
7243 org-file-apps-defaults-windowsnt)
7244 (t org-file-apps-defaults-gnu)))
7246 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7247 (defun org-file-remote-p (file)
7248 "Test whether FILE specifies a location on a remote system.
7249 Return non-nil if the location is indeed remote.
7251 For example, the filename \"/user@host:/foo\" specifies a location
7252 on the system \"/user@host:\"."
7253 (cond ((fboundp 'file-remote-p)
7254 (file-remote-p file))
7255 ((fboundp 'tramp-handle-file-remote-p)
7256 (tramp-handle-file-remote-p file))
7257 ((and (boundp 'ange-ftp-name-format)
7258 (string-match (car ange-ftp-name-format) file))
7260 (t nil)))
7263 ;;;; Refiling
7265 (defun org-get-org-file ()
7266 "Read a filename, with default directory `org-directory'."
7267 (let ((default (or org-default-notes-file remember-data-file)))
7268 (read-file-name (format "File name [%s]: " default)
7269 (file-name-as-directory org-directory)
7270 default)))
7272 (defun org-notes-order-reversed-p ()
7273 "Check if the current file should receive notes in reversed order."
7274 (cond
7275 ((not org-reverse-note-order) nil)
7276 ((eq t org-reverse-note-order) t)
7277 ((not (listp org-reverse-note-order)) nil)
7278 (t (catch 'exit
7279 (let ((all org-reverse-note-order)
7280 entry)
7281 (while (setq entry (pop all))
7282 (if (string-match (car entry) buffer-file-name)
7283 (throw 'exit (cdr entry))))
7284 nil)))))
7286 (defvar org-refile-target-table nil
7287 "The list of refile targets, created by `org-refile'.")
7289 (defvar org-agenda-new-buffers nil
7290 "Buffers created to visit agenda files.")
7292 (defun org-get-refile-targets (&optional default-buffer)
7293 "Produce a table with refile targets."
7294 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7295 targets txt re files f desc descre)
7296 (with-current-buffer (or default-buffer (current-buffer))
7297 (while (setq entry (pop entries))
7298 (setq files (car entry) desc (cdr entry))
7299 (cond
7300 ((null files) (setq files (list (current-buffer))))
7301 ((eq files 'org-agenda-files)
7302 (setq files (org-agenda-files 'unrestricted)))
7303 ((and (symbolp files) (fboundp files))
7304 (setq files (funcall files)))
7305 ((and (symbolp files) (boundp files))
7306 (setq files (symbol-value files))))
7307 (if (stringp files) (setq files (list files)))
7308 (cond
7309 ((eq (car desc) :tag)
7310 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7311 ((eq (car desc) :todo)
7312 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7313 ((eq (car desc) :regexp)
7314 (setq descre (cdr desc)))
7315 ((eq (car desc) :level)
7316 (setq descre (concat "^\\*\\{" (number-to-string
7317 (if org-odd-levels-only
7318 (1- (* 2 (cdr desc)))
7319 (cdr desc)))
7320 "\\}[ \t]")))
7321 ((eq (car desc) :maxlevel)
7322 (setq descre (concat "^\\*\\{1," (number-to-string
7323 (if org-odd-levels-only
7324 (1- (* 2 (cdr desc)))
7325 (cdr desc)))
7326 "\\}[ \t]")))
7327 (t (error "Bad refiling target description %s" desc)))
7328 (while (setq f (pop files))
7329 (save-excursion
7330 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7331 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7332 (save-excursion
7333 (save-restriction
7334 (widen)
7335 (goto-char (point-min))
7336 (while (re-search-forward descre nil t)
7337 (goto-char (point-at-bol))
7338 (when (looking-at org-complex-heading-regexp)
7339 (setq txt (match-string 4)
7340 re (concat "^" (regexp-quote
7341 (buffer-substring (match-beginning 1)
7342 (match-end 4)))))
7343 (if (match-end 5) (setq re (concat re "[ \t]+"
7344 (regexp-quote
7345 (match-string 5)))))
7346 (setq re (concat re "[ \t]*$"))
7347 (when org-refile-use-outline-path
7348 (setq txt (mapconcat 'identity
7349 (append
7350 (if (eq org-refile-use-outline-path 'file)
7351 (list (file-name-nondirectory
7352 (buffer-file-name (buffer-base-buffer))))
7353 (if (eq org-refile-use-outline-path 'full-file-path)
7354 (list (buffer-file-name (buffer-base-buffer)))))
7355 (org-get-outline-path)
7356 (list txt))
7357 "/")))
7358 (push (list txt f re (point)) targets))
7359 (goto-char (point-at-eol))))))))
7360 (nreverse targets))))
7362 (defun org-get-outline-path ()
7363 "Return the outline path to the current entry, as a list."
7364 (let (rtn)
7365 (save-excursion
7366 (while (org-up-heading-safe)
7367 (when (looking-at org-complex-heading-regexp)
7368 (push (org-match-string-no-properties 4) rtn)))
7369 rtn)))
7371 (defvar org-refile-history nil
7372 "History for refiling operations.")
7374 (defun org-refile (&optional goto default-buffer)
7375 "Move the entry at point to another heading.
7376 The list of target headings is compiled using the information in
7377 `org-refile-targets', which see. This list is created before each use
7378 and will therefore always be up-to-date.
7380 At the target location, the entry is filed as a subitem of the target heading.
7381 Depending on `org-reverse-note-order', the new subitem will either be the
7382 first of the last subitem.
7384 With prefix arg GOTO, the command will only visit the target location,
7385 not actually move anything.
7386 With a double prefix `C-c C-c', go to the location where the last refiling
7387 operation has put the subtree."
7388 (interactive "P")
7389 (let* ((cbuf (current-buffer))
7390 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7391 pos it nbuf file re level reversed)
7392 (if (equal goto '(16))
7393 (org-refile-goto-last-stored)
7394 (when (setq it (org-refile-get-location
7395 (if goto "Goto: " "Refile to: ") default-buffer))
7396 (setq file (nth 1 it)
7397 re (nth 2 it)
7398 pos (nth 3 it))
7399 (setq nbuf (or (find-buffer-visiting file)
7400 (find-file-noselect file)))
7401 (if goto
7402 (progn
7403 (switch-to-buffer nbuf)
7404 (goto-char pos)
7405 (org-show-context 'org-goto))
7406 (org-copy-subtree 1 nil t)
7407 (save-excursion
7408 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7409 (find-file-noselect file))))
7410 (setq reversed (org-notes-order-reversed-p))
7411 (save-excursion
7412 (save-restriction
7413 (widen)
7414 (goto-char pos)
7415 (looking-at outline-regexp)
7416 (setq level (org-get-valid-level (funcall outline-level) 1))
7417 (goto-char
7418 (if reversed
7419 (outline-next-heading)
7420 (or (save-excursion (outline-get-next-sibling))
7421 (org-end-of-subtree t t)
7422 (point-max))))
7423 (bookmark-set "org-refile-last-stored")
7424 (org-paste-subtree level))))
7425 (org-cut-subtree)
7426 (setq org-markers-to-move nil)
7427 (message "Entry refiled to \"%s\"" (car it)))))))
7429 (defun org-refile-goto-last-stored ()
7430 "Go to the location where the last refile was stored."
7431 (interactive)
7432 (bookmark-jump "org-refile-last-stored")
7433 (message "This is the location of the last refile"))
7435 (defun org-refile-get-location (&optional prompt default-buffer)
7436 "Prompt the user for a refile location, using PROMPT."
7437 (let ((org-refile-targets org-refile-targets)
7438 (org-refile-use-outline-path org-refile-use-outline-path))
7439 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7440 (unless org-refile-target-table
7441 (error "No refile targets"))
7442 (let* ((cbuf (current-buffer))
7443 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7444 (fname (and filename (file-truename filename)))
7445 (tbl (mapcar
7446 (lambda (x)
7447 (if (not (equal fname (file-truename (nth 1 x))))
7448 (cons (concat (car x) " (" (file-name-nondirectory
7449 (nth 1 x)) ")")
7450 (cdr x))
7452 org-refile-target-table))
7453 (completion-ignore-case t))
7454 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7455 tbl)))
7457 ;;;; Dynamic blocks
7459 (defun org-find-dblock (name)
7460 "Find the first dynamic block with name NAME in the buffer.
7461 If not found, stay at current position and return nil."
7462 (let (pos)
7463 (save-excursion
7464 (goto-char (point-min))
7465 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7466 nil t)
7467 (match-beginning 0))))
7468 (if pos (goto-char pos))
7469 pos))
7471 (defconst org-dblock-start-re
7472 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7473 "Matches the startline of a dynamic block, with parameters.")
7475 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7476 "Matches the end of a dyhamic block.")
7478 (defun org-create-dblock (plist)
7479 "Create a dynamic block section, with parameters taken from PLIST.
7480 PLIST must containe a :name entry which is used as name of the block."
7481 (unless (bolp) (newline))
7482 (let ((name (plist-get plist :name)))
7483 (insert "#+BEGIN: " name)
7484 (while plist
7485 (if (eq (car plist) :name)
7486 (setq plist (cddr plist))
7487 (insert " " (prin1-to-string (pop plist)))))
7488 (insert "\n\n#+END:\n")
7489 (beginning-of-line -2)))
7491 (defun org-prepare-dblock ()
7492 "Prepare dynamic block for refresh.
7493 This empties the block, puts the cursor at the insert position and returns
7494 the property list including an extra property :name with the block name."
7495 (unless (looking-at org-dblock-start-re)
7496 (error "Not at a dynamic block"))
7497 (let* ((begdel (1+ (match-end 0)))
7498 (name (org-no-properties (match-string 1)))
7499 (params (append (list :name name)
7500 (read (concat "(" (match-string 3) ")")))))
7501 (unless (re-search-forward org-dblock-end-re nil t)
7502 (error "Dynamic block not terminated"))
7503 (setq params
7504 (append params
7505 (list :content (buffer-substring
7506 begdel (match-beginning 0)))))
7507 (delete-region begdel (match-beginning 0))
7508 (goto-char begdel)
7509 (open-line 1)
7510 params))
7512 (defun org-map-dblocks (&optional command)
7513 "Apply COMMAND to all dynamic blocks in the current buffer.
7514 If COMMAND is not given, use `org-update-dblock'."
7515 (let ((cmd (or command 'org-update-dblock))
7516 pos)
7517 (save-excursion
7518 (goto-char (point-min))
7519 (while (re-search-forward org-dblock-start-re nil t)
7520 (goto-char (setq pos (match-beginning 0)))
7521 (condition-case nil
7522 (funcall cmd)
7523 (error (message "Error during update of dynamic block")))
7524 (goto-char pos)
7525 (unless (re-search-forward org-dblock-end-re nil t)
7526 (error "Dynamic block not terminated"))))))
7528 (defun org-dblock-update (&optional arg)
7529 "User command for updating dynamic blocks.
7530 Update the dynamic block at point. With prefix ARG, update all dynamic
7531 blocks in the buffer."
7532 (interactive "P")
7533 (if arg
7534 (org-update-all-dblocks)
7535 (or (looking-at org-dblock-start-re)
7536 (org-beginning-of-dblock))
7537 (org-update-dblock)))
7539 (defun org-update-dblock ()
7540 "Update the dynamic block at point
7541 This means to empty the block, parse for parameters and then call
7542 the correct writing function."
7543 (save-window-excursion
7544 (let* ((pos (point))
7545 (line (org-current-line))
7546 (params (org-prepare-dblock))
7547 (name (plist-get params :name))
7548 (cmd (intern (concat "org-dblock-write:" name))))
7549 (message "Updating dynamic block `%s' at line %d..." name line)
7550 (funcall cmd params)
7551 (message "Updating dynamic block `%s' at line %d...done" name line)
7552 (goto-char pos))))
7554 (defun org-beginning-of-dblock ()
7555 "Find the beginning of the dynamic block at point.
7556 Error if there is no scuh block at point."
7557 (let ((pos (point))
7558 beg)
7559 (end-of-line 1)
7560 (if (and (re-search-backward org-dblock-start-re nil t)
7561 (setq beg (match-beginning 0))
7562 (re-search-forward org-dblock-end-re nil t)
7563 (> (match-end 0) pos))
7564 (goto-char beg)
7565 (goto-char pos)
7566 (error "Not in a dynamic block"))))
7568 (defun org-update-all-dblocks ()
7569 "Update all dynamic blocks in the buffer.
7570 This function can be used in a hook."
7571 (when (org-mode-p)
7572 (org-map-dblocks 'org-update-dblock)))
7575 ;;;; Completion
7577 (defconst org-additional-option-like-keywords
7578 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7579 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7580 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7582 (defun org-complete (&optional arg)
7583 "Perform completion on word at point.
7584 At the beginning of a headline, this completes TODO keywords as given in
7585 `org-todo-keywords'.
7586 If the current word is preceded by a backslash, completes the TeX symbols
7587 that are supported for HTML support.
7588 If the current word is preceded by \"#+\", completes special words for
7589 setting file options.
7590 In the line after \"#+STARTUP:, complete valid keywords.\"
7591 At all other locations, this simply calls the value of
7592 `org-completion-fallback-command'."
7593 (interactive "P")
7594 (org-without-partial-completion
7595 (catch 'exit
7596 (let* ((end (point))
7597 (beg1 (save-excursion
7598 (skip-chars-backward (org-re "[:alnum:]_@"))
7599 (point)))
7600 (beg (save-excursion
7601 (skip-chars-backward "a-zA-Z0-9_:$")
7602 (point)))
7603 (confirm (lambda (x) (stringp (car x))))
7604 (searchhead (equal (char-before beg) ?*))
7605 (tag (and (equal (char-before beg1) ?:)
7606 (equal (char-after (point-at-bol)) ?*)))
7607 (prop (and (equal (char-before beg1) ?:)
7608 (not (equal (char-after (point-at-bol)) ?*))))
7609 (texp (equal (char-before beg) ?\\))
7610 (link (equal (char-before beg) ?\[))
7611 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7612 beg)
7613 "#+"))
7614 (startup (string-match "^#\\+STARTUP:.*"
7615 (buffer-substring (point-at-bol) (point))))
7616 (completion-ignore-case opt)
7617 (type nil)
7618 (tbl nil)
7619 (table (cond
7620 (opt
7621 (setq type :opt)
7622 (require 'org-exp)
7623 (append
7624 (mapcar
7625 (lambda (x)
7626 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7627 (cons (match-string 2 x) (match-string 1 x)))
7628 (org-split-string (org-get-current-options) "\n"))
7629 (mapcar 'list org-additional-option-like-keywords)))
7630 (startup
7631 (setq type :startup)
7632 org-startup-options)
7633 (link (append org-link-abbrev-alist-local
7634 org-link-abbrev-alist))
7635 (texp
7636 (setq type :tex)
7637 org-html-entities)
7638 ((string-match "\\`\\*+[ \t]+\\'"
7639 (buffer-substring (point-at-bol) beg))
7640 (setq type :todo)
7641 (mapcar 'list org-todo-keywords-1))
7642 (searchhead
7643 (setq type :searchhead)
7644 (save-excursion
7645 (goto-char (point-min))
7646 (while (re-search-forward org-todo-line-regexp nil t)
7647 (push (list
7648 (org-make-org-heading-search-string
7649 (match-string 3) t))
7650 tbl)))
7651 tbl)
7652 (tag (setq type :tag beg beg1)
7653 (or org-tag-alist (org-get-buffer-tags)))
7654 (prop (setq type :prop beg beg1)
7655 (mapcar 'list (org-buffer-property-keys nil t t)))
7656 (t (progn
7657 (call-interactively org-completion-fallback-command)
7658 (throw 'exit nil)))))
7659 (pattern (buffer-substring-no-properties beg end))
7660 (completion (try-completion pattern table confirm)))
7661 (cond ((eq completion t)
7662 (if (not (assoc (upcase pattern) table))
7663 (message "Already complete")
7664 (if (and (equal type :opt)
7665 (not (member (car (assoc (upcase pattern) table))
7666 org-additional-option-like-keywords)))
7667 (insert (substring (cdr (assoc (upcase pattern) table))
7668 (length pattern)))
7669 (if (memq type '(:tag :prop)) (insert ":")))))
7670 ((null completion)
7671 (message "Can't find completion for \"%s\"" pattern)
7672 (ding))
7673 ((not (string= pattern completion))
7674 (delete-region beg end)
7675 (if (string-match " +$" completion)
7676 (setq completion (replace-match "" t t completion)))
7677 (insert completion)
7678 (if (get-buffer-window "*Completions*")
7679 (delete-window (get-buffer-window "*Completions*")))
7680 (if (assoc completion table)
7681 (if (eq type :todo) (insert " ")
7682 (if (memq type '(:tag :prop)) (insert ":"))))
7683 (if (and (equal type :opt) (assoc completion table))
7684 (message "%s" (substitute-command-keys
7685 "Press \\[org-complete] again to insert example settings"))))
7687 (message "Making completion list...")
7688 (let ((list (sort (all-completions pattern table confirm)
7689 'string<)))
7690 (with-output-to-temp-buffer "*Completions*"
7691 (condition-case nil
7692 ;; Protection needed for XEmacs and emacs 21
7693 (display-completion-list list pattern)
7694 (error (display-completion-list list)))))
7695 (message "Making completion list...%s" "done")))))))
7697 ;;;; TODO, DEADLINE, Comments
7699 (defun org-toggle-comment ()
7700 "Change the COMMENT state of an entry."
7701 (interactive)
7702 (save-excursion
7703 (org-back-to-heading)
7704 (let (case-fold-search)
7705 (if (looking-at (concat outline-regexp
7706 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7707 (replace-match "" t t nil 1)
7708 (if (looking-at outline-regexp)
7709 (progn
7710 (goto-char (match-end 0))
7711 (insert org-comment-string " ")))))))
7713 (defvar org-last-todo-state-is-todo nil
7714 "This is non-nil when the last TODO state change led to a TODO state.
7715 If the last change removed the TODO tag or switched to DONE, then
7716 this is nil.")
7718 (defvar org-setting-tags nil) ; dynamically skiped
7720 (defun org-parse-local-options (string var)
7721 "Parse STRING for startup setting relevant for variable VAR."
7722 (let ((rtn (symbol-value var))
7723 e opts)
7724 (save-match-data
7725 (if (or (not string) (not (string-match "\\S-" string)))
7727 (setq opts (delq nil (mapcar (lambda (x)
7728 (setq e (assoc x org-startup-options))
7729 (if (eq (nth 1 e) var) e nil))
7730 (org-split-string string "[ \t]+"))))
7731 (if (not opts)
7733 (setq rtn nil)
7734 (while (setq e (pop opts))
7735 (if (not (nth 3 e))
7736 (setq rtn (nth 2 e))
7737 (if (not (listp rtn)) (setq rtn nil))
7738 (push (nth 2 e) rtn)))
7739 rtn)))))
7741 (defvar org-blocker-hook nil
7742 "Hook for functions that are allowed to block a state change.
7744 Each function gets as its single argument a property list, see
7745 `org-trigger-hook' for more information about this list.
7747 If any of the functions in this hook returns nil, the state change
7748 is blocked.")
7750 (defvar org-trigger-hook nil
7751 "Hook for functions that are triggered by a state change.
7753 Each function gets as its single argument a property list with at least
7754 the following elements:
7756 (:type type-of-change :position pos-at-entry-start
7757 :from old-state :to new-state)
7759 Depending on the type, more properties may be present.
7761 This mechanism is currently implemented for:
7763 TODO state changes
7764 ------------------
7765 :type todo-state-change
7766 :from previous state (keyword as a string), or nil
7767 :to new state (keyword as a string), or nil")
7770 (defun org-todo (&optional arg)
7771 "Change the TODO state of an item.
7772 The state of an item is given by a keyword at the start of the heading,
7773 like
7774 *** TODO Write paper
7775 *** DONE Call mom
7777 The different keywords are specified in the variable `org-todo-keywords'.
7778 By default the available states are \"TODO\" and \"DONE\".
7779 So for this example: when the item starts with TODO, it is changed to DONE.
7780 When it starts with DONE, the DONE is removed. And when neither TODO nor
7781 DONE are present, add TODO at the beginning of the heading.
7783 With C-u prefix arg, use completion to determine the new state.
7784 With numeric prefix arg, switch to that state.
7786 For calling through lisp, arg is also interpreted in the following way:
7787 'none -> empty state
7788 \"\"(empty string) -> switch to empty state
7789 'done -> switch to DONE
7790 'nextset -> switch to the next set of keywords
7791 'previousset -> switch to the previous set of keywords
7792 \"WAITING\" -> switch to the specified keyword, but only if it
7793 really is a member of `org-todo-keywords'."
7794 (interactive "P")
7795 (save-excursion
7796 (catch 'exit
7797 (org-back-to-heading)
7798 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7799 (or (looking-at (concat " +" org-todo-regexp " *"))
7800 (looking-at " *"))
7801 (let* ((match-data (match-data))
7802 (startpos (point-at-bol))
7803 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7804 (org-log-done org-log-done)
7805 (org-log-repeat org-log-repeat)
7806 (org-todo-log-states org-todo-log-states)
7807 (this (match-string 1))
7808 (hl-pos (match-beginning 0))
7809 (head (org-get-todo-sequence-head this))
7810 (ass (assoc head org-todo-kwd-alist))
7811 (interpret (nth 1 ass))
7812 (done-word (nth 3 ass))
7813 (final-done-word (nth 4 ass))
7814 (last-state (or this ""))
7815 (completion-ignore-case t)
7816 (member (member this org-todo-keywords-1))
7817 (tail (cdr member))
7818 (state (cond
7819 ((and org-todo-key-trigger
7820 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7821 (and (not arg) org-use-fast-todo-selection
7822 (not (eq org-use-fast-todo-selection 'prefix)))))
7823 ;; Use fast selection
7824 (org-fast-todo-selection))
7825 ((and (equal arg '(4))
7826 (or (not org-use-fast-todo-selection)
7827 (not org-todo-key-trigger)))
7828 ;; Read a state with completion
7829 (completing-read "State: " (mapcar (lambda(x) (list x))
7830 org-todo-keywords-1)
7831 nil t))
7832 ((eq arg 'right)
7833 (if this
7834 (if tail (car tail) nil)
7835 (car org-todo-keywords-1)))
7836 ((eq arg 'left)
7837 (if (equal member org-todo-keywords-1)
7839 (if this
7840 (nth (- (length org-todo-keywords-1) (length tail) 2)
7841 org-todo-keywords-1)
7842 (org-last org-todo-keywords-1))))
7843 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7844 (setq arg nil))) ; hack to fall back to cycling
7845 (arg
7846 ;; user or caller requests a specific state
7847 (cond
7848 ((equal arg "") nil)
7849 ((eq arg 'none) nil)
7850 ((eq arg 'done) (or done-word (car org-done-keywords)))
7851 ((eq arg 'nextset)
7852 (or (car (cdr (member head org-todo-heads)))
7853 (car org-todo-heads)))
7854 ((eq arg 'previousset)
7855 (let ((org-todo-heads (reverse org-todo-heads)))
7856 (or (car (cdr (member head org-todo-heads)))
7857 (car org-todo-heads))))
7858 ((car (member arg org-todo-keywords-1)))
7859 ((nth (1- (prefix-numeric-value arg))
7860 org-todo-keywords-1))))
7861 ((null member) (or head (car org-todo-keywords-1)))
7862 ((equal this final-done-word) nil) ;; -> make empty
7863 ((null tail) nil) ;; -> first entry
7864 ((eq interpret 'sequence)
7865 (car tail))
7866 ((memq interpret '(type priority))
7867 (if (eq this-command last-command)
7868 (car tail)
7869 (if (> (length tail) 0)
7870 (or done-word (car org-done-keywords))
7871 nil)))
7872 (t nil)))
7873 (next (if state (concat " " state " ") " "))
7874 (change-plist (list :type 'todo-state-change :from this :to state
7875 :position startpos))
7876 dolog now-done-p)
7877 (when org-blocker-hook
7878 (unless (save-excursion
7879 (save-match-data
7880 (run-hook-with-args-until-failure
7881 'org-blocker-hook change-plist)))
7882 (if (interactive-p)
7883 (error "TODO state change from %s to %s blocked" this state)
7884 ;; fail silently
7885 (message "TODO state change from %s to %s blocked" this state)
7886 (throw 'exit nil))))
7887 (store-match-data match-data)
7888 (replace-match next t t)
7889 (unless (pos-visible-in-window-p hl-pos)
7890 (message "TODO state changed to %s" (org-trim next)))
7891 (unless head
7892 (setq head (org-get-todo-sequence-head state)
7893 ass (assoc head org-todo-kwd-alist)
7894 interpret (nth 1 ass)
7895 done-word (nth 3 ass)
7896 final-done-word (nth 4 ass)))
7897 (when (memq arg '(nextset previousset))
7898 (message "Keyword-Set %d/%d: %s"
7899 (- (length org-todo-sets) -1
7900 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7901 (length org-todo-sets)
7902 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7903 (setq org-last-todo-state-is-todo
7904 (not (member state org-done-keywords)))
7905 (setq now-done-p (and (member state org-done-keywords)
7906 (not (member this org-done-keywords))))
7907 (and logging (org-local-logging logging))
7908 (when (and (or org-todo-log-states org-log-done)
7909 (not (memq arg '(nextset previousset))))
7910 ;; we need to look at recording a time and note
7911 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7912 (nth 2 (assoc this org-todo-log-states))))
7913 (when (and state
7914 (member state org-not-done-keywords)
7915 (not (member this org-not-done-keywords)))
7916 ;; This is now a todo state and was not one before
7917 ;; If there was a CLOSED time stamp, get rid of it.
7918 (org-add-planning-info nil nil 'closed))
7919 (when (and now-done-p org-log-done)
7920 ;; It is now done, and it was not done before
7921 (org-add-planning-info 'closed (org-current-time))
7922 (if (and (not dolog) (eq 'note org-log-done))
7923 (org-add-log-setup 'done state 'findpos 'note)))
7924 (when (and state dolog)
7925 ;; This is a non-nil state, and we need to log it
7926 (org-add-log-setup 'state state 'findpos dolog)))
7927 ;; Fixup tag positioning
7928 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7929 (run-hooks 'org-after-todo-state-change-hook)
7930 (if (and arg (not (member state org-done-keywords)))
7931 (setq head (org-get-todo-sequence-head state)))
7932 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7933 ;; Do we need to trigger a repeat?
7934 (when now-done-p (org-auto-repeat-maybe state))
7935 ;; Fixup cursor location if close to the keyword
7936 (if (and (outline-on-heading-p)
7937 (not (bolp))
7938 (save-excursion (beginning-of-line 1)
7939 (looking-at org-todo-line-regexp))
7940 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7941 (progn
7942 (goto-char (or (match-end 2) (match-end 1)))
7943 (just-one-space)))
7944 (when org-trigger-hook
7945 (save-excursion
7946 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7948 (defun org-local-logging (value)
7949 "Get logging settings from a property VALUE."
7950 (let* (words w a)
7951 ;; directly set the variables, they are already local.
7952 (setq org-log-done nil
7953 org-log-repeat nil
7954 org-todo-log-states nil)
7955 (setq words (org-split-string value))
7956 (while (setq w (pop words))
7957 (cond
7958 ((setq a (assoc w org-startup-options))
7959 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7960 (set (nth 1 a) (nth 2 a))))
7961 ((setq a (org-extract-log-state-settings w))
7962 (and (member (car a) org-todo-keywords-1)
7963 (push a org-todo-log-states)))))))
7965 (defun org-get-todo-sequence-head (kwd)
7966 "Return the head of the TODO sequence to which KWD belongs.
7967 If KWD is not set, check if there is a text property remembering the
7968 right sequence."
7969 (let (p)
7970 (cond
7971 ((not kwd)
7972 (or (get-text-property (point-at-bol) 'org-todo-head)
7973 (progn
7974 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7975 nil (point-at-eol)))
7976 (get-text-property p 'org-todo-head))))
7977 ((not (member kwd org-todo-keywords-1))
7978 (car org-todo-keywords-1))
7979 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7981 (defun org-fast-todo-selection ()
7982 "Fast TODO keyword selection with single keys.
7983 Returns the new TODO keyword, or nil if no state change should occur."
7984 (let* ((fulltable org-todo-key-alist)
7985 (done-keywords org-done-keywords) ;; needed for the faces.
7986 (maxlen (apply 'max (mapcar
7987 (lambda (x)
7988 (if (stringp (car x)) (string-width (car x)) 0))
7989 fulltable)))
7990 (expert nil)
7991 (fwidth (+ maxlen 3 1 3))
7992 (ncol (/ (- (window-width) 4) fwidth))
7993 tg cnt e c tbl
7994 groups ingroup)
7995 (save-window-excursion
7996 (if expert
7997 (set-buffer (get-buffer-create " *Org todo*"))
7998 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7999 (erase-buffer)
8000 (org-set-local 'org-done-keywords done-keywords)
8001 (setq tbl fulltable cnt 0)
8002 (while (setq e (pop tbl))
8003 (cond
8004 ((equal e '(:startgroup))
8005 (push '() groups) (setq ingroup t)
8006 (when (not (= cnt 0))
8007 (setq cnt 0)
8008 (insert "\n"))
8009 (insert "{ "))
8010 ((equal e '(:endgroup))
8011 (setq ingroup nil cnt 0)
8012 (insert "}\n"))
8014 (setq tg (car e) c (cdr e))
8015 (if ingroup (push tg (car groups)))
8016 (setq tg (org-add-props tg nil 'face
8017 (org-get-todo-face tg)))
8018 (if (and (= cnt 0) (not ingroup)) (insert " "))
8019 (insert "[" c "] " tg (make-string
8020 (- fwidth 4 (length tg)) ?\ ))
8021 (when (= (setq cnt (1+ cnt)) ncol)
8022 (insert "\n")
8023 (if ingroup (insert " "))
8024 (setq cnt 0)))))
8025 (insert "\n")
8026 (goto-char (point-min))
8027 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8028 (fit-window-to-buffer))
8029 (message "[a-z..]:Set [SPC]:clear")
8030 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8031 (cond
8032 ((or (= c ?\C-g)
8033 (and (= c ?q) (not (rassoc c fulltable))))
8034 (setq quit-flag t))
8035 ((= c ?\ ) nil)
8036 ((setq e (rassoc c fulltable) tg (car e))
8038 (t (setq quit-flag t))))))
8040 (defun org-entry-is-todo-p ()
8041 (member (org-get-todo-state) org-not-done-keywords))
8043 (defun org-entry-is-done-p ()
8044 (member (org-get-todo-state) org-done-keywords))
8046 (defun org-get-todo-state ()
8047 (save-excursion
8048 (org-back-to-heading t)
8049 (and (looking-at org-todo-line-regexp)
8050 (match-end 2)
8051 (match-string 2))))
8053 (defun org-at-date-range-p (&optional inactive-ok)
8054 "Is the cursor inside a date range?"
8055 (interactive)
8056 (save-excursion
8057 (catch 'exit
8058 (let ((pos (point)))
8059 (skip-chars-backward "^[<\r\n")
8060 (skip-chars-backward "<[")
8061 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8062 (>= (match-end 0) pos)
8063 (throw 'exit t))
8064 (skip-chars-backward "^<[\r\n")
8065 (skip-chars-backward "<[")
8066 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8067 (>= (match-end 0) pos)
8068 (throw 'exit t)))
8069 nil)))
8071 (defun org-get-repeat ()
8072 "Check if tere is a deadline/schedule with repeater in this entry."
8073 (save-match-data
8074 (save-excursion
8075 (org-back-to-heading t)
8076 (if (re-search-forward
8077 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8078 (match-string 1)))))
8080 (defvar org-last-changed-timestamp)
8081 (defvar org-log-post-message)
8082 (defvar org-log-note-purpose)
8083 (defvar org-log-note-how)
8084 (defun org-auto-repeat-maybe (done-word)
8085 "Check if the current headline contains a repeated deadline/schedule.
8086 If yes, set TODO state back to what it was and change the base date
8087 of repeating deadline/scheduled time stamps to new date.
8088 This function is run automatically after each state change to a DONE state."
8089 ;; last-state is dynamically scoped into this function
8090 (let* ((repeat (org-get-repeat))
8091 (aa (assoc last-state org-todo-kwd-alist))
8092 (interpret (nth 1 aa))
8093 (head (nth 2 aa))
8094 (whata '(("d" . day) ("m" . month) ("y" . year)))
8095 (msg "Entry repeats: ")
8096 (org-log-done nil)
8097 (org-todo-log-states nil)
8098 (nshiftmax 10) (nshift 0)
8099 re type n what ts mb0 time)
8100 (when repeat
8101 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8102 (org-todo (if (eq interpret 'type) last-state head))
8103 (when org-log-repeat
8104 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8105 (memq 'org-add-log-note post-command-hook))
8106 ;; OK, we are already setup for some record
8107 (if (eq org-log-repeat 'note)
8108 ;; make sure we take a note, not only a time stamp
8109 (setq org-log-note-how 'note))
8110 ;; Set up for taking a record
8111 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8112 'findpos org-log-repeat)))
8113 (org-back-to-heading t)
8114 (org-add-planning-info nil nil 'closed)
8115 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8116 org-deadline-time-regexp "\\)\\|\\("
8117 org-ts-regexp "\\)"))
8118 (while (re-search-forward
8119 re (save-excursion (outline-next-heading) (point)) t)
8120 (setq type (if (match-end 1) org-scheduled-string
8121 (if (match-end 3) org-deadline-string "Plain:"))
8122 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8123 mb0 (match-beginning 0))
8124 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8125 (setq n (string-to-number (match-string 2 ts))
8126 what (match-string 3 ts))
8127 (if (equal what "w") (setq n (* n 7) what "d"))
8128 ;; Preparation, see if we need to modify the start date for the change
8129 (when (match-end 1)
8130 (setq time (save-match-data (org-time-string-to-time ts)))
8131 (cond
8132 ((equal (match-string 1 ts) ".")
8133 ;; Shift starting date to today
8134 (org-timestamp-change
8135 (- (time-to-days (current-time)) (time-to-days time))
8136 'day))
8137 ((equal (match-string 1 ts) "+")
8138 (while (or (= nshift 0)
8139 (<= (time-to-days time) (time-to-days (current-time))))
8140 (when (= (incf nshift) nshiftmax)
8141 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8142 (error "Abort")))
8143 (org-timestamp-change n (cdr (assoc what whata)))
8144 (org-at-timestamp-p t)
8145 (setq ts (match-string 1))
8146 (setq time (save-match-data (org-time-string-to-time ts))))
8147 (org-timestamp-change (- n) (cdr (assoc what whata)))
8148 ;; rematch, so that we have everything in place for the real shift
8149 (org-at-timestamp-p t)
8150 (setq ts (match-string 1))
8151 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8152 (org-timestamp-change n (cdr (assoc what whata)))
8153 (setq msg (concat msg type org-last-changed-timestamp " "))))
8154 (setq org-log-post-message msg)
8155 (message "%s" msg))))
8157 (defun org-show-todo-tree (arg)
8158 "Make a compact tree which shows all headlines marked with TODO.
8159 The tree will show the lines where the regexp matches, and all higher
8160 headlines above the match.
8161 With a \\[universal-argument] prefix, also show the DONE entries.
8162 With a numeric prefix N, construct a sparse tree for the Nth element
8163 of `org-todo-keywords-1'."
8164 (interactive "P")
8165 (let ((case-fold-search nil)
8166 (kwd-re
8167 (cond ((null arg) org-not-done-regexp)
8168 ((equal arg '(4))
8169 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8170 (mapcar 'list org-todo-keywords-1))))
8171 (concat "\\("
8172 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8173 "\\)\\>")))
8174 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8175 (regexp-quote (nth (1- (prefix-numeric-value arg))
8176 org-todo-keywords-1)))
8177 (t (error "Invalid prefix argument: %s" arg)))))
8178 (message "%d TODO entries found"
8179 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8181 (defun org-deadline (&optional remove)
8182 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8183 With argument REMOVE, remove any deadline from the item."
8184 (interactive "P")
8185 (if remove
8186 (progn
8187 (org-remove-timestamp-with-keyword org-deadline-string)
8188 (message "Item no longer has a deadline."))
8189 (org-add-planning-info 'deadline nil 'closed)))
8191 (defun org-schedule (&optional remove)
8192 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8193 With argument REMOVE, remove any scheduling date from the item."
8194 (interactive "P")
8195 (if remove
8196 (progn
8197 (org-remove-timestamp-with-keyword org-scheduled-string)
8198 (message "Item is no longer scheduled."))
8199 (org-add-planning-info 'scheduled nil 'closed)))
8201 (defun org-remove-timestamp-with-keyword (keyword)
8202 "Remove all time stamps with KEYWORD in the current entry."
8203 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8204 beg)
8205 (save-excursion
8206 (org-back-to-heading t)
8207 (setq beg (point))
8208 (org-end-of-subtree t t)
8209 (while (re-search-backward re beg t)
8210 (replace-match "")
8211 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8212 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8214 (defun org-add-planning-info (what &optional time &rest remove)
8215 "Insert new timestamp with keyword in the line directly after the headline.
8216 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8217 If non is given, the user is prompted for a date.
8218 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8219 be removed."
8220 (interactive)
8221 (let (org-time-was-given org-end-time-was-given ts
8222 end default-time default-input)
8224 (when (and (not time) (memq what '(scheduled deadline)))
8225 ;; Try to get a default date/time from existing timestamp
8226 (save-excursion
8227 (org-back-to-heading t)
8228 (setq end (save-excursion (outline-next-heading) (point)))
8229 (when (re-search-forward (if (eq what 'scheduled)
8230 org-scheduled-time-regexp
8231 org-deadline-time-regexp)
8232 end t)
8233 (setq ts (match-string 1)
8234 default-time
8235 (apply 'encode-time (org-parse-time-string ts))
8236 default-input (and ts (org-get-compact-tod ts))))))
8237 (when what
8238 ;; If necessary, get the time from the user
8239 (setq time (or time (org-read-date nil 'to-time nil nil
8240 default-time default-input))))
8242 (when (and org-insert-labeled-timestamps-at-point
8243 (member what '(scheduled deadline)))
8244 (insert
8245 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8246 (org-insert-time-stamp time org-time-was-given
8247 nil nil nil (list org-end-time-was-given))
8248 (setq what nil))
8249 (save-excursion
8250 (save-restriction
8251 (let (col list elt ts buffer-invisibility-spec)
8252 (org-back-to-heading t)
8253 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8254 (goto-char (match-end 1))
8255 (setq col (current-column))
8256 (goto-char (match-end 0))
8257 (if (eobp) (insert "\n") (forward-char 1))
8258 (if (and (not (looking-at outline-regexp))
8259 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8260 "[^\r\n]*"))
8261 (not (equal (match-string 1) org-clock-string)))
8262 (narrow-to-region (match-beginning 0) (match-end 0))
8263 (insert-before-markers "\n")
8264 (backward-char 1)
8265 (narrow-to-region (point) (point))
8266 (org-indent-to-column col))
8267 ;; Check if we have to remove something.
8268 (setq list (cons what remove))
8269 (while list
8270 (setq elt (pop list))
8271 (goto-char (point-min))
8272 (when (or (and (eq elt 'scheduled)
8273 (re-search-forward org-scheduled-time-regexp nil t))
8274 (and (eq elt 'deadline)
8275 (re-search-forward org-deadline-time-regexp nil t))
8276 (and (eq elt 'closed)
8277 (re-search-forward org-closed-time-regexp nil t)))
8278 (replace-match "")
8279 (if (looking-at "--+<[^>]+>") (replace-match ""))
8280 (if (looking-at " +") (replace-match ""))))
8281 (goto-char (point-max))
8282 (when what
8283 (insert
8284 (if (not (equal (char-before) ?\ )) " " "")
8285 (cond ((eq what 'scheduled) org-scheduled-string)
8286 ((eq what 'deadline) org-deadline-string)
8287 ((eq what 'closed) org-closed-string))
8288 " ")
8289 (setq ts (org-insert-time-stamp
8290 time
8291 (or org-time-was-given
8292 (and (eq what 'closed) org-log-done-with-time))
8293 (eq what 'closed)
8294 nil nil (list org-end-time-was-given)))
8295 (end-of-line 1))
8296 (goto-char (point-min))
8297 (widen)
8298 (if (and (looking-at "[ \t]+\n")
8299 (equal (char-before) ?\n))
8300 (backward-delete-char 1))
8301 ts)))))
8303 (defvar org-log-note-marker (make-marker))
8304 (defvar org-log-note-purpose nil)
8305 (defvar org-log-note-state nil)
8306 (defvar org-log-note-how nil)
8307 (defvar org-log-note-window-configuration nil)
8308 (defvar org-log-note-return-to (make-marker))
8309 (defvar org-log-post-message nil
8310 "Message to be displayed after a log note has been stored.
8311 The auto-repeater uses this.")
8313 (defun org-add-note ()
8314 "Add a note to the current entry.
8315 This is done in the same way as adding a state change note."
8316 (interactive)
8317 (org-add-log-setup 'note nil t nil))
8319 (defun org-add-log-setup (&optional purpose state findpos how)
8320 "Set up the post command hook to take a note.
8321 If this is about to TODO state change, the new state is expected in STATE.
8322 When FINDPOS is non-nil, find the correct position for the note in
8323 the current entry. If not, assume that it can be inserted at point."
8324 (save-excursion
8325 (when findpos
8326 (org-back-to-heading t)
8327 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8328 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8329 "[^\r\n]*\\)?"))
8330 (goto-char (match-end 0))
8331 (unless org-log-states-order-reversed
8332 (and (= (char-after) ?\n) (forward-char 1))
8333 (org-skip-over-state-notes)
8334 (skip-chars-backward " \t\n\r")))
8335 (move-marker org-log-note-marker (point))
8336 (setq org-log-note-purpose purpose
8337 org-log-note-state state
8338 org-log-note-how how)
8339 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8341 (defun org-skip-over-state-notes ()
8342 "Skip past the list of State notes in an entry."
8343 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8344 (while (looking-at "[ \t]*- State")
8345 (condition-case nil
8346 (org-next-item)
8347 (error (org-end-of-item)))))
8349 (defun org-add-log-note (&optional purpose)
8350 "Pop up a window for taking a note, and add this note later at point."
8351 (remove-hook 'post-command-hook 'org-add-log-note)
8352 (setq org-log-note-window-configuration (current-window-configuration))
8353 (delete-other-windows)
8354 (move-marker org-log-note-return-to (point))
8355 (switch-to-buffer (marker-buffer org-log-note-marker))
8356 (goto-char org-log-note-marker)
8357 (org-switch-to-buffer-other-window "*Org Note*")
8358 (erase-buffer)
8359 (if (memq org-log-note-how '(time state))
8360 (org-store-log-note)
8361 (let ((org-inhibit-startup t)) (org-mode))
8362 (insert (format "# Insert note for %s.
8363 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8364 (cond
8365 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8366 ((eq org-log-note-purpose 'done) "closed todo item")
8367 ((eq org-log-note-purpose 'state)
8368 (format "state change to \"%s\"" org-log-note-state))
8369 ((eq org-log-note-purpose 'note)
8370 "this entry")
8371 (t (error "This should not happen")))))
8372 (org-set-local 'org-finish-function 'org-store-log-note)))
8374 (defvar org-note-abort nil) ; dynamically scoped
8375 (defun org-store-log-note ()
8376 "Finish taking a log note, and insert it to where it belongs."
8377 (let ((txt (buffer-string))
8378 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8379 lines ind)
8380 (kill-buffer (current-buffer))
8381 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8382 (setq txt (replace-match "" t t txt)))
8383 (if (string-match "\\s-+\\'" txt)
8384 (setq txt (replace-match "" t t txt)))
8385 (setq lines (org-split-string txt "\n"))
8386 (when (and note (string-match "\\S-" note))
8387 (setq note
8388 (org-replace-escapes
8389 note
8390 (list (cons "%u" (user-login-name))
8391 (cons "%U" user-full-name)
8392 (cons "%t" (format-time-string
8393 (org-time-stamp-format 'long 'inactive)
8394 (current-time)))
8395 (cons "%s" (if org-log-note-state
8396 (concat "\"" org-log-note-state "\"")
8397 "")))))
8398 (if lines (setq note (concat note " \\\\")))
8399 (push note lines))
8400 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8401 (when lines
8402 (save-excursion
8403 (set-buffer (marker-buffer org-log-note-marker))
8404 (save-excursion
8405 (goto-char org-log-note-marker)
8406 (move-marker org-log-note-marker nil)
8407 (end-of-line 1)
8408 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8409 (indent-relative nil)
8410 (insert "- " (pop lines))
8411 (org-indent-line-function)
8412 (beginning-of-line 1)
8413 (looking-at "[ \t]*")
8414 (setq ind (concat (match-string 0) " "))
8415 (end-of-line 1)
8416 (while lines (insert "\n" ind (pop lines)))))))
8417 (set-window-configuration org-log-note-window-configuration)
8418 (with-current-buffer (marker-buffer org-log-note-return-to)
8419 (goto-char org-log-note-return-to))
8420 (move-marker org-log-note-return-to nil)
8421 (and org-log-post-message (message "%s" org-log-post-message)))
8423 (defun org-sparse-tree (&optional arg)
8424 "Create a sparse tree, prompt for the details.
8425 This command can create sparse trees. You first need to select the type
8426 of match used to create the tree:
8428 t Show entries with a specific TODO keyword.
8429 T Show entries selected by a tags match.
8430 p Enter a property name and its value (both with completion on existing
8431 names/values) and show entries with that property.
8432 r Show entries matching a regular expression
8433 d Show deadlines due within `org-deadline-warning-days'."
8434 (interactive "P")
8435 (let (ans kwd value)
8436 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8437 (setq ans (read-char-exclusive))
8438 (cond
8439 ((equal ans ?d)
8440 (call-interactively 'org-check-deadlines))
8441 ((equal ans ?b)
8442 (call-interactively 'org-check-before-date))
8443 ((equal ans ?t)
8444 (org-show-todo-tree '(4)))
8445 ((equal ans ?T)
8446 (call-interactively 'org-tags-sparse-tree))
8447 ((member ans '(?p ?P))
8448 (setq kwd (completing-read "Property: "
8449 (mapcar 'list (org-buffer-property-keys))))
8450 (setq value (completing-read "Value: "
8451 (mapcar 'list (org-property-values kwd))))
8452 (unless (string-match "\\`{.*}\\'" value)
8453 (setq value (concat "\"" value "\"")))
8454 (org-tags-sparse-tree arg (concat kwd "=" value)))
8455 ((member ans '(?r ?R ?/))
8456 (call-interactively 'org-occur))
8457 (t (error "No such sparse tree command \"%c\"" ans)))))
8459 (defvar org-occur-highlights nil
8460 "List of overlays used for occur matches.")
8461 (make-variable-buffer-local 'org-occur-highlights)
8462 (defvar org-occur-parameters nil
8463 "Parameters of the active org-occur calls.
8464 This is a list, each call to org-occur pushes as cons cell,
8465 containing the regular expression and the callback, onto the list.
8466 The list can contain several entries if `org-occur' has been called
8467 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8468 will only contain one set of parameters. When the highlights are
8469 removed (for example with `C-c C-c', or with the next edit (depending
8470 on `org-remove-highlights-with-change'), this variable is emptied
8471 as well.")
8472 (make-variable-buffer-local 'org-occur-parameters)
8474 (defun org-occur (regexp &optional keep-previous callback)
8475 "Make a compact tree which shows all matches of REGEXP.
8476 The tree will show the lines where the regexp matches, and all higher
8477 headlines above the match. It will also show the heading after the match,
8478 to make sure editing the matching entry is easy.
8479 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8480 call to `org-occur' will be kept, to allow stacking of calls to this
8481 command.
8482 If CALLBACK is non-nil, it is a function which is called to confirm
8483 that the match should indeed be shown."
8484 (interactive "sRegexp: \nP")
8485 (unless keep-previous
8486 (org-remove-occur-highlights nil nil t))
8487 (push (cons regexp callback) org-occur-parameters)
8488 (let ((cnt 0))
8489 (save-excursion
8490 (goto-char (point-min))
8491 (if (or (not keep-previous) ; do not want to keep
8492 (not org-occur-highlights)) ; no previous matches
8493 ;; hide everything
8494 (org-overview))
8495 (while (re-search-forward regexp nil t)
8496 (when (or (not callback)
8497 (save-match-data (funcall callback)))
8498 (setq cnt (1+ cnt))
8499 (when org-highlight-sparse-tree-matches
8500 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8501 (org-show-context 'occur-tree))))
8502 (when org-remove-highlights-with-change
8503 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8504 nil 'local))
8505 (unless org-sparse-tree-open-archived-trees
8506 (org-hide-archived-subtrees (point-min) (point-max)))
8507 (run-hooks 'org-occur-hook)
8508 (if (interactive-p)
8509 (message "%d match(es) for regexp %s" cnt regexp))
8510 cnt))
8512 (defun org-show-context (&optional key)
8513 "Make sure point and context and visible.
8514 How much context is shown depends upon the variables
8515 `org-show-hierarchy-above', `org-show-following-heading'. and
8516 `org-show-siblings'."
8517 (let ((heading-p (org-on-heading-p t))
8518 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8519 (following-p (org-get-alist-option org-show-following-heading key))
8520 (entry-p (org-get-alist-option org-show-entry-below key))
8521 (siblings-p (org-get-alist-option org-show-siblings key)))
8522 (catch 'exit
8523 ;; Show heading or entry text
8524 (if (and heading-p (not entry-p))
8525 (org-flag-heading nil) ; only show the heading
8526 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8527 (org-show-hidden-entry))) ; show entire entry
8528 (when following-p
8529 ;; Show next sibling, or heading below text
8530 (save-excursion
8531 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8532 (org-flag-heading nil))))
8533 (when siblings-p (org-show-siblings))
8534 (when hierarchy-p
8535 ;; show all higher headings, possibly with siblings
8536 (save-excursion
8537 (while (and (condition-case nil
8538 (progn (org-up-heading-all 1) t)
8539 (error nil))
8540 (not (bobp)))
8541 (org-flag-heading nil)
8542 (when siblings-p (org-show-siblings))))))))
8544 (defun org-reveal (&optional siblings)
8545 "Show current entry, hierarchy above it, and the following headline.
8546 This can be used to show a consistent set of context around locations
8547 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8548 not t for the search context.
8550 With optional argument SIBLINGS, on each level of the hierarchy all
8551 siblings are shown. This repairs the tree structure to what it would
8552 look like when opened with hierarchical calls to `org-cycle'."
8553 (interactive "P")
8554 (let ((org-show-hierarchy-above t)
8555 (org-show-following-heading t)
8556 (org-show-siblings (if siblings t org-show-siblings)))
8557 (org-show-context nil)))
8559 (defun org-highlight-new-match (beg end)
8560 "Highlight from BEG to END and mark the highlight is an occur headline."
8561 (let ((ov (org-make-overlay beg end)))
8562 (org-overlay-put ov 'face 'secondary-selection)
8563 (push ov org-occur-highlights)))
8565 (defun org-remove-occur-highlights (&optional beg end noremove)
8566 "Remove the occur highlights from the buffer.
8567 BEG and END are ignored. If NOREMOVE is nil, remove this function
8568 from the `before-change-functions' in the current buffer."
8569 (interactive)
8570 (unless org-inhibit-highlight-removal
8571 (mapc 'org-delete-overlay org-occur-highlights)
8572 (setq org-occur-highlights nil)
8573 (setq org-occur-parameters nil)
8574 (unless noremove
8575 (remove-hook 'before-change-functions
8576 'org-remove-occur-highlights 'local))))
8578 ;;;; Priorities
8580 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8581 "Regular expression matching the priority indicator.")
8583 (defvar org-remove-priority-next-time nil)
8585 (defun org-priority-up ()
8586 "Increase the priority of the current item."
8587 (interactive)
8588 (org-priority 'up))
8590 (defun org-priority-down ()
8591 "Decrease the priority of the current item."
8592 (interactive)
8593 (org-priority 'down))
8595 (defun org-priority (&optional action)
8596 "Change the priority of an item by ARG.
8597 ACTION can be `set', `up', `down', or a character."
8598 (interactive)
8599 (setq action (or action 'set))
8600 (let (current new news have remove)
8601 (save-excursion
8602 (org-back-to-heading)
8603 (if (looking-at org-priority-regexp)
8604 (setq current (string-to-char (match-string 2))
8605 have t)
8606 (setq current org-default-priority))
8607 (cond
8608 ((or (eq action 'set)
8609 (if (featurep 'xemacs) (characterp action) (integerp action)))
8610 (if (not (eq action 'set))
8611 (setq new action)
8612 (message "Priority %c-%c, SPC to remove: "
8613 org-highest-priority org-lowest-priority)
8614 (setq new (read-char-exclusive)))
8615 (if (and (= (upcase org-highest-priority) org-highest-priority)
8616 (= (upcase org-lowest-priority) org-lowest-priority))
8617 (setq new (upcase new)))
8618 (cond ((equal new ?\ ) (setq remove t))
8619 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8620 (error "Priority must be between `%c' and `%c'"
8621 org-highest-priority org-lowest-priority))))
8622 ((eq action 'up)
8623 (if (and (not have) (eq last-command this-command))
8624 (setq new org-lowest-priority)
8625 (setq new (if (and org-priority-start-cycle-with-default (not have))
8626 org-default-priority (1- current)))))
8627 ((eq action 'down)
8628 (if (and (not have) (eq last-command this-command))
8629 (setq new org-highest-priority)
8630 (setq new (if (and org-priority-start-cycle-with-default (not have))
8631 org-default-priority (1+ current)))))
8632 (t (error "Invalid action")))
8633 (if (or (< (upcase new) org-highest-priority)
8634 (> (upcase new) org-lowest-priority))
8635 (setq remove t))
8636 (setq news (format "%c" new))
8637 (if have
8638 (if remove
8639 (replace-match "" t t nil 1)
8640 (replace-match news t t nil 2))
8641 (if remove
8642 (error "No priority cookie found in line")
8643 (looking-at org-todo-line-regexp)
8644 (if (match-end 2)
8645 (progn
8646 (goto-char (match-end 2))
8647 (insert " [#" news "]"))
8648 (goto-char (match-beginning 3))
8649 (insert "[#" news "] ")))))
8650 (org-preserve-lc (org-set-tags nil 'align))
8651 (if remove
8652 (message "Priority removed")
8653 (message "Priority of current item set to %s" news))))
8656 (defun org-get-priority (s)
8657 "Find priority cookie and return priority."
8658 (save-match-data
8659 (if (not (string-match org-priority-regexp s))
8660 (* 1000 (- org-lowest-priority org-default-priority))
8661 (* 1000 (- org-lowest-priority
8662 (string-to-char (match-string 2 s)))))))
8664 ;;;; Tags
8666 (defun org-scan-tags (action matcher &optional todo-only)
8667 "Scan headline tags with inheritance and produce output ACTION.
8668 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8669 evaluated, testing if a given set of tags qualifies a headline for
8670 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8671 are included in the output."
8672 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8673 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8674 (org-re
8675 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8676 (props (list 'face nil
8677 'done-face 'org-done
8678 'undone-face nil
8679 'mouse-face 'highlight
8680 'org-not-done-regexp org-not-done-regexp
8681 'org-todo-regexp org-todo-regexp
8682 'keymap org-agenda-keymap
8683 'help-echo
8684 (format "mouse-2 or RET jump to org file %s"
8685 (abbreviate-file-name
8686 (or (buffer-file-name (buffer-base-buffer))
8687 (buffer-name (buffer-base-buffer)))))))
8688 (case-fold-search nil)
8689 lspos
8690 tags tags-list tags-alist (llast 0) rtn level category i txt
8691 todo marker entry priority)
8692 (save-excursion
8693 (goto-char (point-min))
8694 (when (eq action 'sparse-tree)
8695 (org-overview)
8696 (org-remove-occur-highlights))
8697 (while (re-search-forward re nil t)
8698 (catch :skip
8699 (setq todo (if (match-end 1) (match-string 2))
8700 tags (if (match-end 4) (match-string 4)))
8701 (goto-char (setq lspos (1+ (match-beginning 0))))
8702 (setq level (org-reduced-level (funcall outline-level))
8703 category (org-get-category))
8704 (setq i llast llast level)
8705 ;; remove tag lists from same and sublevels
8706 (while (>= i level)
8707 (when (setq entry (assoc i tags-alist))
8708 (setq tags-alist (delete entry tags-alist)))
8709 (setq i (1- i)))
8710 ;; add the next tags
8711 (when tags
8712 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8713 tags-alist
8714 (cons (cons level tags) tags-alist)))
8715 ;; compile tags for current headline
8716 (setq tags-list
8717 (if org-use-tag-inheritance
8718 (apply 'append (mapcar 'cdr tags-alist))
8719 tags))
8720 (when (and tags org-use-tag-inheritance
8721 (not (eq t org-use-tag-inheritance)))
8722 ;; selective inheritance, remove uninherited ones
8723 (setcdr (car tags-alist)
8724 (org-remove-uniherited-tags (cdar tags-alist))))
8725 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8726 (eval matcher)
8727 (or (not org-agenda-skip-archived-trees)
8728 (not (member org-archive-tag tags-list))))
8729 (and (eq action 'agenda) (org-agenda-skip))
8730 ;; list this headline
8732 (if (eq action 'sparse-tree)
8733 (progn
8734 (and org-highlight-sparse-tree-matches
8735 (org-get-heading) (match-end 0)
8736 (org-highlight-new-match
8737 (match-beginning 0) (match-beginning 1)))
8738 (org-show-context 'tags-tree))
8739 (setq txt (org-format-agenda-item
8741 (concat
8742 (if org-tags-match-list-sublevels
8743 (make-string (1- level) ?.) "")
8744 (org-get-heading))
8745 category tags-list)
8746 priority (org-get-priority txt))
8747 (goto-char lspos)
8748 (setq marker (org-agenda-new-marker))
8749 (org-add-props txt props
8750 'org-marker marker 'org-hd-marker marker 'org-category category
8751 'priority priority 'type "tagsmatch")
8752 (push txt rtn))
8753 ;; if we are to skip sublevels, jump to end of subtree
8754 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8755 (when (and (eq action 'sparse-tree)
8756 (not org-sparse-tree-open-archived-trees))
8757 (org-hide-archived-subtrees (point-min) (point-max)))
8758 (nreverse rtn)))
8760 (defun org-remove-uniherited-tags (tags)
8761 "Remove all tags that are not inherited from the list TAGS."
8762 (cond
8763 ((eq org-use-tag-inheritance t) tags)
8764 ((not org-use-tag-inheritance) nil)
8765 ((stringp org-use-tag-inheritance)
8766 (delq nil (mapcar
8767 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8768 tags)))
8769 ((listp org-use-tag-inheritance)
8770 (org-delete-all org-use-tag-inheritance tags))))
8772 (defvar todo-only) ;; dynamically scoped
8774 (defun org-tags-sparse-tree (&optional todo-only match)
8775 "Create a sparse tree according to tags string MATCH.
8776 MATCH can contain positive and negative selection of tags, like
8777 \"+WORK+URGENT-WITHBOSS\".
8778 If optional argument TODO_ONLY is non-nil, only select lines that are
8779 also TODO lines."
8780 (interactive "P")
8781 (org-prepare-agenda-buffers (list (current-buffer)))
8782 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8784 (defvar org-cached-props nil)
8785 (defun org-cached-entry-get (pom property)
8786 (if (or (eq t org-use-property-inheritance)
8787 (and (stringp org-use-property-inheritance)
8788 (string-match org-use-property-inheritance property))
8789 (and (listp org-use-property-inheritance)
8790 (member property org-use-property-inheritance)))
8791 ;; Caching is not possible, check it directly
8792 (org-entry-get pom property 'inherit)
8793 ;; Get all properties, so that we can do complicated checks easily
8794 (cdr (assoc property (or org-cached-props
8795 (setq org-cached-props
8796 (org-entry-properties pom)))))))
8798 (defun org-global-tags-completion-table (&optional files)
8799 "Return the list of all tags in all agenda buffer/files."
8800 (save-excursion
8801 (org-uniquify
8802 (delq nil
8803 (apply 'append
8804 (mapcar
8805 (lambda (file)
8806 (set-buffer (find-file-noselect file))
8807 (append (org-get-buffer-tags)
8808 (mapcar (lambda (x) (if (stringp (car-safe x))
8809 (list (car-safe x)) nil))
8810 org-tag-alist)))
8811 (if (and files (car files))
8812 files
8813 (org-agenda-files))))))))
8815 (defun org-make-tags-matcher (match)
8816 "Create the TAGS//TODO matcher form for the selection string MATCH."
8817 ;; todo-only is scoped dynamically into this function, and the function
8818 ;; may change it it the matcher asksk for it.
8819 (unless match
8820 ;; Get a new match request, with completion
8821 (let ((org-last-tags-completion-table
8822 (org-global-tags-completion-table)))
8823 (setq match (completing-read
8824 "Match: " 'org-tags-completion-function nil nil nil
8825 'org-tags-history))))
8827 ;; Parse the string and create a lisp form
8828 (let ((match0 match)
8829 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8830 minus tag mm
8831 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8832 orterms term orlist re-p str-p level-p level-op
8833 prop-p pn pv po cat-p gv)
8834 (if (string-match "/+" match)
8835 ;; match contains also a todo-matching request
8836 (progn
8837 (setq tagsmatch (substring match 0 (match-beginning 0))
8838 todomatch (substring match (match-end 0)))
8839 (if (string-match "^!" todomatch)
8840 (setq todo-only t todomatch (substring todomatch 1)))
8841 (if (string-match "^\\s-*$" todomatch)
8842 (setq todomatch nil)))
8843 ;; only matching tags
8844 (setq tagsmatch match todomatch nil))
8846 ;; Make the tags matcher
8847 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8848 (setq tagsmatcher t)
8849 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8850 (while (setq term (pop orterms))
8851 (while (and (equal (substring term -1) "\\") orterms)
8852 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8853 (while (string-match re term)
8854 (setq minus (and (match-end 1)
8855 (equal (match-string 1 term) "-"))
8856 tag (match-string 2 term)
8857 re-p (equal (string-to-char tag) ?{)
8858 level-p (match-end 4)
8859 prop-p (match-end 5)
8860 mm (cond
8861 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8862 (level-p
8863 (setq level-op (org-op-to-function (match-string 3 term)))
8864 `(,level-op level ,(string-to-number
8865 (match-string 4 term))))
8866 (prop-p
8867 (setq pn (match-string 5 term)
8868 po (match-string 6 term)
8869 pv (match-string 7 term)
8870 cat-p (equal pn "CATEGORY")
8871 re-p (equal (string-to-char pv) ?{)
8872 str-p (equal (string-to-char pv) ?\")
8873 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8874 (setq po (org-op-to-function po str-p))
8875 (if (equal pn "CATEGORY")
8876 (setq gv '(get-text-property (point) 'org-category))
8877 (setq gv `(org-cached-entry-get nil ,pn)))
8878 (if re-p
8879 (if (eq po 'org<>)
8880 `(not (string-match ,pv (or ,gv "")))
8881 `(string-match ,pv (or ,gv "")))
8882 (if str-p
8883 `(,po (or ,gv "") ,pv)
8884 `(,po (string-to-number (or ,gv ""))
8885 ,(string-to-number pv) ))))
8886 (t `(member ,(downcase tag) tags-list)))
8887 mm (if minus (list 'not mm) mm)
8888 term (substring term (match-end 0)))
8889 (push mm tagsmatcher))
8890 (push (if (> (length tagsmatcher) 1)
8891 (cons 'and tagsmatcher)
8892 (car tagsmatcher))
8893 orlist)
8894 (setq tagsmatcher nil))
8895 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8896 (setq tagsmatcher
8897 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8898 ;; Make the todo matcher
8899 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8900 (setq todomatcher t)
8901 (setq orterms (org-split-string todomatch "|") orlist nil)
8902 (while (setq term (pop orterms))
8903 (while (string-match re term)
8904 (setq minus (and (match-end 1)
8905 (equal (match-string 1 term) "-"))
8906 kwd (match-string 2 term)
8907 re-p (equal (string-to-char kwd) ?{)
8908 term (substring term (match-end 0))
8909 mm (if re-p
8910 `(string-match ,(substring kwd 1 -1) todo)
8911 (list 'equal 'todo kwd))
8912 mm (if minus (list 'not mm) mm))
8913 (push mm todomatcher))
8914 (push (if (> (length todomatcher) 1)
8915 (cons 'and todomatcher)
8916 (car todomatcher))
8917 orlist)
8918 (setq todomatcher nil))
8919 (setq todomatcher (if (> (length orlist) 1)
8920 (cons 'or orlist) (car orlist))))
8922 ;; Return the string and lisp forms of the matcher
8923 (setq matcher (if todomatcher
8924 (list 'and tagsmatcher todomatcher)
8925 tagsmatcher))
8926 (cons match0 matcher)))
8928 (defun org-op-to-function (op &optional stringp)
8929 (setq op
8930 (cond
8931 ((equal op "<" ) '(< string< ))
8932 ((equal op ">" ) '(> org-string> ))
8933 ((member op '("<=" "=<")) '(<= org-string<= ))
8934 ((member op '(">=" "=>")) '(>= org-string>= ))
8935 ((member op '("=" "==")) '(= string= ))
8936 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8937 (nth (if stringp 1 0) op))
8939 (defun org<> (a b) (not (= a b)))
8940 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8941 (defun org-string>= (a b) (not (string< a b)))
8942 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8943 (defun org-string<> (a b) (not (string= a b)))
8945 (defun org-match-any-p (re list)
8946 "Does re match any element of list?"
8947 (setq list (mapcar (lambda (x) (string-match re x)) list))
8948 (delq nil list))
8950 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8951 (defvar org-tags-overlay (org-make-overlay 1 1))
8952 (org-detach-overlay org-tags-overlay)
8954 (defun org-get-tags-at (&optional pos)
8955 "Get a list of all headline tags applicable at POS.
8956 POS defaults to point. If tags are inherited, the list contains
8957 the targets in the same sequence as the headlines appear, i.e.
8958 sthe tags of the current headline come last."
8959 (interactive)
8960 (let (tags ltags lastpos parent)
8961 (save-excursion
8962 (save-restriction
8963 (widen)
8964 (goto-char (or pos (point)))
8965 (save-match-data
8966 (condition-case nil
8967 (progn
8968 (org-back-to-heading t)
8969 (while (not (equal lastpos (point)))
8970 (setq lastpos (point))
8971 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8972 (setq ltags (org-split-string
8973 (org-match-string-no-properties 1) ":"))
8974 (setq tags (append (org-remove-uniherited-tags ltags)
8975 tags)))
8976 (or org-use-tag-inheritance (error ""))
8977 (org-up-heading-all 1)
8978 (setq parent t)))
8979 (error nil))))
8980 tags)))
8982 (defun org-toggle-tag (tag &optional onoff)
8983 "Toggle the tag TAG for the current line.
8984 If ONOFF is `on' or `off', don't toggle but set to this state."
8985 (unless (org-on-heading-p t) (error "Not on headling"))
8986 (let (res current)
8987 (save-excursion
8988 (beginning-of-line)
8989 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8990 (point-at-eol) t)
8991 (progn
8992 (setq current (match-string 1))
8993 (replace-match ""))
8994 (setq current ""))
8995 (setq current (nreverse (org-split-string current ":")))
8996 (cond
8997 ((eq onoff 'on)
8998 (setq res t)
8999 (or (member tag current) (push tag current)))
9000 ((eq onoff 'off)
9001 (or (not (member tag current)) (setq current (delete tag current))))
9002 (t (if (member tag current)
9003 (setq current (delete tag current))
9004 (setq res t)
9005 (push tag current))))
9006 (end-of-line 1)
9007 (if current
9008 (progn
9009 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9010 (org-set-tags nil t))
9011 (delete-horizontal-space))
9012 (run-hooks 'org-after-tags-change-hook))
9013 res))
9015 (defun org-align-tags-here (to-col)
9016 ;; Assumes that this is a headline
9017 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9018 (beginning-of-line 1)
9019 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9020 (< pos (match-beginning 2)))
9021 (progn
9022 (setq tags-l (- (match-end 2) (match-beginning 2)))
9023 (goto-char (match-beginning 1))
9024 (insert " ")
9025 (delete-region (point) (1+ (match-beginning 2)))
9026 (setq ncol (max (1+ (current-column))
9027 (1+ col)
9028 (if (> to-col 0)
9029 to-col
9030 (- (abs to-col) tags-l))))
9031 (setq p (point))
9032 (insert (make-string (- ncol (current-column)) ?\ ))
9033 (setq ncol (current-column))
9034 (tabify p (point-at-eol))
9035 (org-move-to-column (min ncol col) t))
9036 (goto-char pos))))
9038 (defun org-set-tags (&optional arg just-align)
9039 "Set the tags for the current headline.
9040 With prefix ARG, realign all tags in headings in the current buffer."
9041 (interactive "P")
9042 (let* ((re (concat "^" outline-regexp))
9043 (current (org-get-tags-string))
9044 (col (current-column))
9045 (org-setting-tags t)
9046 table current-tags inherited-tags ; computed below when needed
9047 tags p0 c0 c1 rpl)
9048 (if arg
9049 (save-excursion
9050 (goto-char (point-min))
9051 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9052 (while (re-search-forward re nil t)
9053 (org-set-tags nil t)
9054 (end-of-line 1)))
9055 (message "All tags realigned to column %d" org-tags-column))
9056 (if just-align
9057 (setq tags current)
9058 ;; Get a new set of tags from the user
9059 (save-excursion
9060 (setq table (or org-tag-alist (org-get-buffer-tags))
9061 org-last-tags-completion-table table
9062 current-tags (org-split-string current ":")
9063 inherited-tags (nreverse
9064 (nthcdr (length current-tags)
9065 (nreverse (org-get-tags-at))))
9066 tags
9067 (if (or (eq t org-use-fast-tag-selection)
9068 (and org-use-fast-tag-selection
9069 (delq nil (mapcar 'cdr table))))
9070 (org-fast-tag-selection
9071 current-tags inherited-tags table
9072 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9073 (let ((org-add-colon-after-tag-completion t))
9074 (org-trim
9075 (org-without-partial-completion
9076 (completing-read "Tags: " 'org-tags-completion-function
9077 nil nil current 'org-tags-history)))))))
9078 (while (string-match "[-+&]+" tags)
9079 ;; No boolean logic, just a list
9080 (setq tags (replace-match ":" t t tags))))
9082 (if (string-match "\\`[\t ]*\\'" tags)
9083 (setq tags "")
9084 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9085 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9087 ;; Insert new tags at the correct column
9088 (beginning-of-line 1)
9089 (cond
9090 ((and (equal current "") (equal tags "")))
9091 ((re-search-forward
9092 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9093 (point-at-eol) t)
9094 (if (equal tags "")
9095 (setq rpl "")
9096 (goto-char (match-beginning 0))
9097 (setq c0 (current-column) p0 (point)
9098 c1 (max (1+ c0) (if (> org-tags-column 0)
9099 org-tags-column
9100 (- (- org-tags-column) (length tags))))
9101 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9102 (replace-match rpl t t)
9103 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9104 tags)
9105 (t (error "Tags alignment failed")))
9106 (org-move-to-column col)
9107 (unless just-align
9108 (run-hooks 'org-after-tags-change-hook)))))
9110 (defun org-change-tag-in-region (beg end tag off)
9111 "Add or remove TAG for each entry in the region.
9112 This works in the agenda, and also in an org-mode buffer."
9113 (interactive
9114 (list (region-beginning) (region-end)
9115 (let ((org-last-tags-completion-table
9116 (if (org-mode-p)
9117 (org-get-buffer-tags)
9118 (org-global-tags-completion-table))))
9119 (completing-read
9120 "Tag: " 'org-tags-completion-function nil nil nil
9121 'org-tags-history))
9122 (progn
9123 (message "[s]et or [r]emove? ")
9124 (equal (read-char-exclusive) ?r))))
9125 (if (fboundp 'deactivate-mark) (deactivate-mark))
9126 (let ((agendap (equal major-mode 'org-agenda-mode))
9127 l1 l2 m buf pos newhead (cnt 0))
9128 (goto-char end)
9129 (setq l2 (1- (org-current-line)))
9130 (goto-char beg)
9131 (setq l1 (org-current-line))
9132 (loop for l from l1 to l2 do
9133 (goto-line l)
9134 (setq m (get-text-property (point) 'org-hd-marker))
9135 (when (or (and (org-mode-p) (org-on-heading-p))
9136 (and agendap m))
9137 (setq buf (if agendap (marker-buffer m) (current-buffer))
9138 pos (if agendap m (point)))
9139 (with-current-buffer buf
9140 (save-excursion
9141 (save-restriction
9142 (goto-char pos)
9143 (setq cnt (1+ cnt))
9144 (org-toggle-tag tag (if off 'off 'on))
9145 (setq newhead (org-get-heading)))))
9146 (and agendap (org-agenda-change-all-lines newhead m))))
9147 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9149 (defun org-tags-completion-function (string predicate &optional flag)
9150 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9151 (confirm (lambda (x) (stringp (car x)))))
9152 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9153 (setq s1 (match-string 1 string)
9154 s2 (match-string 2 string))
9155 (setq s1 "" s2 string))
9156 (cond
9157 ((eq flag nil)
9158 ;; try completion
9159 (setq rtn (try-completion s2 ctable confirm))
9160 (if (stringp rtn)
9161 (setq rtn
9162 (concat s1 s2 (substring rtn (length s2))
9163 (if (and org-add-colon-after-tag-completion
9164 (assoc rtn ctable))
9165 ":" ""))))
9166 rtn)
9167 ((eq flag t)
9168 ;; all-completions
9169 (all-completions s2 ctable confirm)
9171 ((eq flag 'lambda)
9172 ;; exact match?
9173 (assoc s2 ctable)))
9176 (defun org-fast-tag-insert (kwd tags face &optional end)
9177 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9178 (insert (format "%-12s" (concat kwd ":"))
9179 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9180 (or end "")))
9182 (defun org-fast-tag-show-exit (flag)
9183 (save-excursion
9184 (goto-line 3)
9185 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9186 (replace-match ""))
9187 (when flag
9188 (end-of-line 1)
9189 (org-move-to-column (- (window-width) 19) t)
9190 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9192 (defun org-set-current-tags-overlay (current prefix)
9193 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9194 (if (featurep 'xemacs)
9195 (org-overlay-display org-tags-overlay (concat prefix s)
9196 'secondary-selection)
9197 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9198 (org-overlay-display org-tags-overlay (concat prefix s)))))
9200 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9201 "Fast tag selection with single keys.
9202 CURRENT is the current list of tags in the headline, INHERITED is the
9203 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9204 possibly with grouping information. TODO-TABLE is a similar table with
9205 TODO keywords, should these have keys assigned to them.
9206 If the keys are nil, a-z are automatically assigned.
9207 Returns the new tags string, or nil to not change the current settings."
9208 (let* ((fulltable (append table todo-table))
9209 (maxlen (apply 'max (mapcar
9210 (lambda (x)
9211 (if (stringp (car x)) (string-width (car x)) 0))
9212 fulltable)))
9213 (buf (current-buffer))
9214 (expert (eq org-fast-tag-selection-single-key 'expert))
9215 (buffer-tags nil)
9216 (fwidth (+ maxlen 3 1 3))
9217 (ncol (/ (- (window-width) 4) fwidth))
9218 (i-face 'org-done)
9219 (c-face 'org-todo)
9220 tg cnt e c char c1 c2 ntable tbl rtn
9221 ov-start ov-end ov-prefix
9222 (exit-after-next org-fast-tag-selection-single-key)
9223 (done-keywords org-done-keywords)
9224 groups ingroup)
9225 (save-excursion
9226 (beginning-of-line 1)
9227 (if (looking-at
9228 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9229 (setq ov-start (match-beginning 1)
9230 ov-end (match-end 1)
9231 ov-prefix "")
9232 (setq ov-start (1- (point-at-eol))
9233 ov-end (1+ ov-start))
9234 (skip-chars-forward "^\n\r")
9235 (setq ov-prefix
9236 (concat
9237 (buffer-substring (1- (point)) (point))
9238 (if (> (current-column) org-tags-column)
9240 (make-string (- org-tags-column (current-column)) ?\ ))))))
9241 (org-move-overlay org-tags-overlay ov-start ov-end)
9242 (save-window-excursion
9243 (if expert
9244 (set-buffer (get-buffer-create " *Org tags*"))
9245 (delete-other-windows)
9246 (split-window-vertically)
9247 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9248 (erase-buffer)
9249 (org-set-local 'org-done-keywords done-keywords)
9250 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9251 (org-fast-tag-insert "Current" current c-face "\n\n")
9252 (org-fast-tag-show-exit exit-after-next)
9253 (org-set-current-tags-overlay current ov-prefix)
9254 (setq tbl fulltable char ?a cnt 0)
9255 (while (setq e (pop tbl))
9256 (cond
9257 ((equal e '(:startgroup))
9258 (push '() groups) (setq ingroup t)
9259 (when (not (= cnt 0))
9260 (setq cnt 0)
9261 (insert "\n"))
9262 (insert "{ "))
9263 ((equal e '(:endgroup))
9264 (setq ingroup nil cnt 0)
9265 (insert "}\n"))
9267 (setq tg (car e) c2 nil)
9268 (if (cdr e)
9269 (setq c (cdr e))
9270 ;; automatically assign a character.
9271 (setq c1 (string-to-char
9272 (downcase (substring
9273 tg (if (= (string-to-char tg) ?@) 1 0)))))
9274 (if (or (rassoc c1 ntable) (rassoc c1 table))
9275 (while (or (rassoc char ntable) (rassoc char table))
9276 (setq char (1+ char)))
9277 (setq c2 c1))
9278 (setq c (or c2 char)))
9279 (if ingroup (push tg (car groups)))
9280 (setq tg (org-add-props tg nil 'face
9281 (cond
9282 ((not (assoc tg table))
9283 (org-get-todo-face tg))
9284 ((member tg current) c-face)
9285 ((member tg inherited) i-face)
9286 (t nil))))
9287 (if (and (= cnt 0) (not ingroup)) (insert " "))
9288 (insert "[" c "] " tg (make-string
9289 (- fwidth 4 (length tg)) ?\ ))
9290 (push (cons tg c) ntable)
9291 (when (= (setq cnt (1+ cnt)) ncol)
9292 (insert "\n")
9293 (if ingroup (insert " "))
9294 (setq cnt 0)))))
9295 (setq ntable (nreverse ntable))
9296 (insert "\n")
9297 (goto-char (point-min))
9298 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9299 (fit-window-to-buffer))
9300 (setq rtn
9301 (catch 'exit
9302 (while t
9303 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9304 (if groups " [!] no groups" " [!]groups")
9305 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9306 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9307 (cond
9308 ((= c ?\r) (throw 'exit t))
9309 ((= c ?!)
9310 (setq groups (not groups))
9311 (goto-char (point-min))
9312 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9313 ((= c ?\C-c)
9314 (if (not expert)
9315 (org-fast-tag-show-exit
9316 (setq exit-after-next (not exit-after-next)))
9317 (setq expert nil)
9318 (delete-other-windows)
9319 (split-window-vertically)
9320 (org-switch-to-buffer-other-window " *Org tags*")
9321 (and (fboundp 'fit-window-to-buffer)
9322 (fit-window-to-buffer))))
9323 ((or (= c ?\C-g)
9324 (and (= c ?q) (not (rassoc c ntable))))
9325 (org-detach-overlay org-tags-overlay)
9326 (setq quit-flag t))
9327 ((= c ?\ )
9328 (setq current nil)
9329 (if exit-after-next (setq exit-after-next 'now)))
9330 ((= c ?\t)
9331 (condition-case nil
9332 (setq tg (completing-read
9333 "Tag: "
9334 (or buffer-tags
9335 (with-current-buffer buf
9336 (org-get-buffer-tags)))))
9337 (quit (setq tg "")))
9338 (when (string-match "\\S-" tg)
9339 (add-to-list 'buffer-tags (list tg))
9340 (if (member tg current)
9341 (setq current (delete tg current))
9342 (push tg current)))
9343 (if exit-after-next (setq exit-after-next 'now)))
9344 ((setq e (rassoc c todo-table) tg (car e))
9345 (with-current-buffer buf
9346 (save-excursion (org-todo tg)))
9347 (if exit-after-next (setq exit-after-next 'now)))
9348 ((setq e (rassoc c ntable) tg (car e))
9349 (if (member tg current)
9350 (setq current (delete tg current))
9351 (loop for g in groups do
9352 (if (member tg g)
9353 (mapc (lambda (x)
9354 (setq current (delete x current)))
9355 g)))
9356 (push tg current))
9357 (if exit-after-next (setq exit-after-next 'now))))
9359 ;; Create a sorted list
9360 (setq current
9361 (sort current
9362 (lambda (a b)
9363 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9364 (if (eq exit-after-next 'now) (throw 'exit t))
9365 (goto-char (point-min))
9366 (beginning-of-line 2)
9367 (delete-region (point) (point-at-eol))
9368 (org-fast-tag-insert "Current" current c-face)
9369 (org-set-current-tags-overlay current ov-prefix)
9370 (while (re-search-forward
9371 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9372 (setq tg (match-string 1))
9373 (add-text-properties
9374 (match-beginning 1) (match-end 1)
9375 (list 'face
9376 (cond
9377 ((member tg current) c-face)
9378 ((member tg inherited) i-face)
9379 (t (get-text-property (match-beginning 1) 'face))))))
9380 (goto-char (point-min)))))
9381 (org-detach-overlay org-tags-overlay)
9382 (if rtn
9383 (mapconcat 'identity current ":")
9384 nil))))
9386 (defun org-get-tags-string ()
9387 "Get the TAGS string in the current headline."
9388 (unless (org-on-heading-p t)
9389 (error "Not on a heading"))
9390 (save-excursion
9391 (beginning-of-line 1)
9392 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9393 (org-match-string-no-properties 1)
9394 "")))
9396 (defun org-get-tags ()
9397 "Get the list of tags specified in the current headline."
9398 (org-split-string (org-get-tags-string) ":"))
9400 (defun org-get-buffer-tags ()
9401 "Get a table of all tags used in the buffer, for completion."
9402 (let (tags)
9403 (save-excursion
9404 (goto-char (point-min))
9405 (while (re-search-forward
9406 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9407 (when (equal (char-after (point-at-bol 0)) ?*)
9408 (mapc (lambda (x) (add-to-list 'tags x))
9409 (org-split-string (org-match-string-no-properties 1) ":")))))
9410 (mapcar 'list tags)))
9413 ;;;; Properties
9415 ;;; Setting and retrieving properties
9417 (defconst org-special-properties
9418 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9419 "TIMESTAMP" "TIMESTAMP_IA")
9420 "The special properties valid in Org-mode.
9422 These are properties that are not defined in the property drawer,
9423 but in some other way.")
9425 (defconst org-default-properties
9426 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9427 "LOCATION" "LOGGING" "COLUMNS")
9428 "Some properties that are used by Org-mode for various purposes.
9429 Being in this list makes sure that they are offered for completion.")
9431 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9432 "Regular expression matching the first line of a property drawer.")
9434 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9435 "Regular expression matching the first line of a property drawer.")
9437 (defun org-property-action ()
9438 "Do an action on properties."
9439 (interactive)
9440 (let (c)
9441 (org-at-property-p)
9442 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9443 (setq c (read-char-exclusive))
9444 (cond
9445 ((equal c ?s)
9446 (call-interactively 'org-set-property))
9447 ((equal c ?d)
9448 (call-interactively 'org-delete-property))
9449 ((equal c ?D)
9450 (call-interactively 'org-delete-property-globally))
9451 ((equal c ?c)
9452 (call-interactively 'org-compute-property-at-point))
9453 (t (error "No such property action %c" c)))))
9455 (defun org-at-property-p ()
9456 "Is the cursor in a property line?"
9457 ;; FIXME: Does not check if we are actually in the drawer.
9458 ;; FIXME: also returns true on any drawers.....
9459 ;; This is used by C-c C-c for property action.
9460 (save-excursion
9461 (beginning-of-line 1)
9462 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9464 (defun org-get-property-block (&optional beg end force)
9465 "Return the (beg . end) range of the body of the property drawer.
9466 BEG and END can be beginning and end of subtree, if not given
9467 they will be found.
9468 If the drawer does not exist and FORCE is non-nil, create the drawer."
9469 (catch 'exit
9470 (save-excursion
9471 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9472 (end (or end (progn (outline-next-heading) (point)))))
9473 (goto-char beg)
9474 (if (re-search-forward org-property-start-re end t)
9475 (setq beg (1+ (match-end 0)))
9476 (if force
9477 (save-excursion
9478 (org-insert-property-drawer)
9479 (setq end (progn (outline-next-heading) (point))))
9480 (throw 'exit nil))
9481 (goto-char beg)
9482 (if (re-search-forward org-property-start-re end t)
9483 (setq beg (1+ (match-end 0)))))
9484 (if (re-search-forward org-property-end-re end t)
9485 (setq end (match-beginning 0))
9486 (or force (throw 'exit nil))
9487 (goto-char beg)
9488 (setq end beg)
9489 (org-indent-line-function)
9490 (insert ":END:\n"))
9491 (cons beg end)))))
9493 (defun org-entry-properties (&optional pom which)
9494 "Get all properties of the entry at point-or-marker POM.
9495 This includes the TODO keyword, the tags, time strings for deadline,
9496 scheduled, and clocking, and any additional properties defined in the
9497 entry. The return value is an alist, keys may occur multiple times
9498 if the property key was used several times.
9499 POM may also be nil, in which case the current entry is used.
9500 If WHICH is nil or `all', get all properties. If WHICH is
9501 `special' or `standard', only get that subclass."
9502 (setq which (or which 'all))
9503 (org-with-point-at pom
9504 (let ((clockstr (substring org-clock-string 0 -1))
9505 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9506 beg end range props sum-props key value string clocksum)
9507 (save-excursion
9508 (when (condition-case nil (org-back-to-heading t) (error nil))
9509 (setq beg (point))
9510 (setq sum-props (get-text-property (point) 'org-summaries))
9511 (setq clocksum (get-text-property (point) :org-clock-minutes))
9512 (outline-next-heading)
9513 (setq end (point))
9514 (when (memq which '(all special))
9515 ;; Get the special properties, like TODO and tags
9516 (goto-char beg)
9517 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9518 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9519 (when (looking-at org-priority-regexp)
9520 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9521 (when (and (setq value (org-get-tags-string))
9522 (string-match "\\S-" value))
9523 (push (cons "TAGS" value) props))
9524 (when (setq value (org-get-tags-at))
9525 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9526 props))
9527 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9528 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9529 string (if (equal key clockstr)
9530 (org-no-properties
9531 (org-trim
9532 (buffer-substring
9533 (match-beginning 3) (goto-char (point-at-eol)))))
9534 (substring (org-match-string-no-properties 3) 1 -1)))
9535 (unless key
9536 (if (= (char-after (match-beginning 3)) ?\[)
9537 (setq key "TIMESTAMP_IA")
9538 (setq key "TIMESTAMP")))
9539 (when (or (equal key clockstr) (not (assoc key props)))
9540 (push (cons key string) props)))
9544 (when (memq which '(all standard))
9545 ;; Get the standard properties, like :PORP: ...
9546 (setq range (org-get-property-block beg end))
9547 (when range
9548 (goto-char (car range))
9549 (while (re-search-forward
9550 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9551 (cdr range) t)
9552 (setq key (org-match-string-no-properties 1)
9553 value (org-trim (or (org-match-string-no-properties 2) "")))
9554 (unless (member key excluded)
9555 (push (cons key (or value "")) props)))))
9556 (if clocksum
9557 (push (cons "CLOCKSUM"
9558 (org-columns-number-to-string (/ (float clocksum) 60.)
9559 'add_times))
9560 props))
9561 (append sum-props (nreverse props)))))))
9563 (defun org-entry-get (pom property &optional inherit)
9564 "Get value of PROPERTY for entry at point-or-marker POM.
9565 If INHERIT is non-nil and the entry does not have the property,
9566 then also check higher levels of the hierarchy.
9567 If INHERIT is the symbol `selective', use inheritance only if the setting
9568 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9569 If the property is present but empty, the return value is the empty string.
9570 If the property is not present at all, nil is returned."
9571 (org-with-point-at pom
9572 (if (and inherit (if (eq inherit 'selective)
9573 (org-property-inherit-p property)
9575 (org-entry-get-with-inheritance property)
9576 (if (member property org-special-properties)
9577 ;; We need a special property. Use brute force, get all properties.
9578 (cdr (assoc property (org-entry-properties nil 'special)))
9579 (let ((range (org-get-property-block)))
9580 (if (and range
9581 (goto-char (car range))
9582 (re-search-forward
9583 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9584 (cdr range) t))
9585 ;; Found the property, return it.
9586 (if (match-end 1)
9587 (org-match-string-no-properties 1)
9588 "")))))))
9590 (defun org-property-or-variable-value (var &optional inherit)
9591 "Check if there is a property fixing the value of VAR.
9592 If yes, return this value. If not, return the current value of the variable."
9593 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9594 (if (and prop (stringp prop) (string-match "\\S-" prop))
9595 (read prop)
9596 (symbol-value var))))
9598 (defun org-entry-delete (pom property)
9599 "Delete the property PROPERTY from entry at point-or-marker POM."
9600 (org-with-point-at pom
9601 (if (member property org-special-properties)
9602 nil ; cannot delete these properties.
9603 (let ((range (org-get-property-block)))
9604 (if (and range
9605 (goto-char (car range))
9606 (re-search-forward
9607 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9608 (cdr range) t))
9609 (progn
9610 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9612 nil)))))
9614 ;; Multi-values properties are properties that contain multiple values
9615 ;; These values are assumed to be single words, separated by whitespace.
9616 (defun org-entry-add-to-multivalued-property (pom property value)
9617 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9618 (let* ((old (org-entry-get pom property))
9619 (values (and old (org-split-string old "[ \t]"))))
9620 (unless (member value values)
9621 (setq values (cons value values))
9622 (org-entry-put pom property
9623 (mapconcat 'identity values " ")))))
9625 (defun org-entry-remove-from-multivalued-property (pom property value)
9626 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9627 (let* ((old (org-entry-get pom property))
9628 (values (and old (org-split-string old "[ \t]"))))
9629 (when (member value values)
9630 (setq values (delete value values))
9631 (org-entry-put pom property
9632 (mapconcat 'identity values " ")))))
9634 (defun org-entry-member-in-multivalued-property (pom property value)
9635 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9636 (let* ((old (org-entry-get pom property))
9637 (values (and old (org-split-string old "[ \t]"))))
9638 (member value values)))
9640 (defvar org-entry-property-inherited-from (make-marker))
9642 (defun org-entry-get-with-inheritance (property)
9643 "Get entry property, and search higher levels if not present."
9644 (let (tmp)
9645 (save-excursion
9646 (save-restriction
9647 (widen)
9648 (catch 'ex
9649 (while t
9650 (when (setq tmp (org-entry-get nil property))
9651 (org-back-to-heading t)
9652 (move-marker org-entry-property-inherited-from (point))
9653 (throw 'ex tmp))
9654 (or (org-up-heading-safe) (throw 'ex nil)))))
9655 (or tmp (cdr (assoc property org-local-properties))
9656 (cdr (assoc property org-global-properties))))))
9658 (defun org-entry-put (pom property value)
9659 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9660 (org-with-point-at pom
9661 (org-back-to-heading t)
9662 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9663 range)
9664 (cond
9665 ((equal property "TODO")
9666 (when (and (stringp value) (string-match "\\S-" value)
9667 (not (member value org-todo-keywords-1)))
9668 (error "\"%s\" is not a valid TODO state" value))
9669 (if (or (not value)
9670 (not (string-match "\\S-" value)))
9671 (setq value 'none))
9672 (org-todo value)
9673 (org-set-tags nil 'align))
9674 ((equal property "PRIORITY")
9675 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9676 (string-to-char value) ?\ ))
9677 (org-set-tags nil 'align))
9678 ((equal property "SCHEDULED")
9679 (if (re-search-forward org-scheduled-time-regexp end t)
9680 (cond
9681 ((eq value 'earlier) (org-timestamp-change -1 'day))
9682 ((eq value 'later) (org-timestamp-change 1 'day))
9683 (t (call-interactively 'org-schedule)))
9684 (call-interactively 'org-schedule)))
9685 ((equal property "DEADLINE")
9686 (if (re-search-forward org-deadline-time-regexp end t)
9687 (cond
9688 ((eq value 'earlier) (org-timestamp-change -1 'day))
9689 ((eq value 'later) (org-timestamp-change 1 'day))
9690 (t (call-interactively 'org-deadline)))
9691 (call-interactively 'org-deadline)))
9692 ((member property org-special-properties)
9693 (error "The %s property can not yet be set with `org-entry-put'"
9694 property))
9695 (t ; a non-special property
9696 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9697 (setq range (org-get-property-block beg end 'force))
9698 (goto-char (car range))
9699 (if (re-search-forward
9700 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9701 (progn
9702 (delete-region (match-beginning 1) (match-end 1))
9703 (goto-char (match-beginning 1)))
9704 (goto-char (cdr range))
9705 (insert "\n")
9706 (backward-char 1)
9707 (org-indent-line-function)
9708 (insert ":" property ":"))
9709 (and value (insert " " value))
9710 (org-indent-line-function)))))))
9712 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9713 "Get all property keys in the current buffer.
9714 With INCLUDE-SPECIALS, also list the special properties that relect things
9715 like tags and TODO state.
9716 With INCLUDE-DEFAULTS, also include properties that has special meaning
9717 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9718 With INCLUDE-COLUMNS, also include property names given in COLUMN
9719 formats in the current buffer."
9720 (let (rtn range cfmt cols s p)
9721 (save-excursion
9722 (save-restriction
9723 (widen)
9724 (goto-char (point-min))
9725 (while (re-search-forward org-property-start-re nil t)
9726 (setq range (org-get-property-block))
9727 (goto-char (car range))
9728 (while (re-search-forward
9729 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9730 (cdr range) t)
9731 (add-to-list 'rtn (org-match-string-no-properties 1)))
9732 (outline-next-heading))))
9734 (when include-specials
9735 (setq rtn (append org-special-properties rtn)))
9737 (when include-defaults
9738 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9740 (when include-columns
9741 (save-excursion
9742 (save-restriction
9743 (widen)
9744 (goto-char (point-min))
9745 (while (re-search-forward
9746 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9747 nil t)
9748 (setq cfmt (match-string 2) s 0)
9749 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9750 cfmt s)
9751 (setq s (match-end 0)
9752 p (match-string 1 cfmt))
9753 (unless (or (equal p "ITEM")
9754 (member p org-special-properties))
9755 (add-to-list 'rtn (match-string 1 cfmt))))))))
9757 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9759 (defun org-property-values (key)
9760 "Return a list of all values of property KEY."
9761 (save-excursion
9762 (save-restriction
9763 (widen)
9764 (goto-char (point-min))
9765 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9766 values)
9767 (while (re-search-forward re nil t)
9768 (add-to-list 'values (org-trim (match-string 1))))
9769 (delete "" values)))))
9771 (defun org-insert-property-drawer ()
9772 "Insert a property drawer into the current entry."
9773 (interactive)
9774 (org-back-to-heading t)
9775 (looking-at outline-regexp)
9776 (let ((indent (- (match-end 0)(match-beginning 0)))
9777 (beg (point))
9778 (re (concat "^[ \t]*" org-keyword-time-regexp))
9779 end hiddenp)
9780 (outline-next-heading)
9781 (setq end (point))
9782 (goto-char beg)
9783 (while (re-search-forward re end t))
9784 (setq hiddenp (org-invisible-p))
9785 (end-of-line 1)
9786 (and (equal (char-after) ?\n) (forward-char 1))
9787 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9788 (beginning-of-line 2))
9789 (org-skip-over-state-notes)
9790 (skip-chars-backward " \t\n\r")
9791 (if (eq (char-before) ?*) (forward-char 1))
9792 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9793 (beginning-of-line 0)
9794 (org-indent-to-column indent)
9795 (beginning-of-line 2)
9796 (org-indent-to-column indent)
9797 (beginning-of-line 0)
9798 (if hiddenp
9799 (save-excursion
9800 (org-back-to-heading t)
9801 (hide-entry))
9802 (org-flag-drawer t))))
9804 (defun org-set-property (property value)
9805 "In the current entry, set PROPERTY to VALUE.
9806 When called interactively, this will prompt for a property name, offering
9807 completion on existing and default properties. And then it will prompt
9808 for a value, offering competion either on allowed values (via an inherited
9809 xxx_ALL property) or on existing values in other instances of this property
9810 in the current file."
9811 (interactive
9812 (let* ((prop (completing-read
9813 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9814 (cur (org-entry-get nil prop))
9815 (allowed (org-property-get-allowed-values nil prop 'table))
9816 (existing (mapcar 'list (org-property-values prop)))
9817 (val (if allowed
9818 (completing-read "Value: " allowed nil 'req-match)
9819 (completing-read
9820 (concat "Value" (if (and cur (string-match "\\S-" cur))
9821 (concat "[" cur "]") "")
9822 ": ")
9823 existing nil nil "" nil cur))))
9824 (list prop (if (equal val "") cur val))))
9825 (unless (equal (org-entry-get nil property) value)
9826 (org-entry-put nil property value)))
9828 (defun org-delete-property (property)
9829 "In the current entry, delete PROPERTY."
9830 (interactive
9831 (let* ((prop (completing-read
9832 "Property: " (org-entry-properties nil 'standard))))
9833 (list prop)))
9834 (message "Property %s %s" property
9835 (if (org-entry-delete nil property)
9836 "deleted"
9837 "was not present in the entry")))
9839 (defun org-delete-property-globally (property)
9840 "Remove PROPERTY globally, from all entries."
9841 (interactive
9842 (let* ((prop (completing-read
9843 "Globally remove property: "
9844 (mapcar 'list (org-buffer-property-keys)))))
9845 (list prop)))
9846 (save-excursion
9847 (save-restriction
9848 (widen)
9849 (goto-char (point-min))
9850 (let ((cnt 0))
9851 (while (re-search-forward
9852 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9853 nil t)
9854 (setq cnt (1+ cnt))
9855 (replace-match ""))
9856 (message "Property \"%s\" removed from %d entries" property cnt)))))
9858 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9860 (defun org-compute-property-at-point ()
9861 "Compute the property at point.
9862 This looks for an enclosing column format, extracts the operator and
9863 then applies it to the proerty in the column format's scope."
9864 (interactive)
9865 (unless (org-at-property-p)
9866 (error "Not at a property"))
9867 (let ((prop (org-match-string-no-properties 2)))
9868 (org-columns-get-format-and-top-level)
9869 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9870 (error "No operator defined for property %s" prop))
9871 (org-columns-compute prop)))
9873 (defun org-property-get-allowed-values (pom property &optional table)
9874 "Get allowed values for the property PROPERTY.
9875 When TABLE is non-nil, return an alist that can directly be used for
9876 completion."
9877 (let (vals)
9878 (cond
9879 ((equal property "TODO")
9880 (setq vals (org-with-point-at pom
9881 (append org-todo-keywords-1 '("")))))
9882 ((equal property "PRIORITY")
9883 (let ((n org-lowest-priority))
9884 (while (>= n org-highest-priority)
9885 (push (char-to-string n) vals)
9886 (setq n (1- n)))))
9887 ((member property org-special-properties))
9889 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9891 (when (and vals (string-match "\\S-" vals))
9892 (setq vals (car (read-from-string (concat "(" vals ")"))))
9893 (setq vals (mapcar (lambda (x)
9894 (cond ((stringp x) x)
9895 ((numberp x) (number-to-string x))
9896 ((symbolp x) (symbol-name x))
9897 (t "???")))
9898 vals)))))
9899 (if table (mapcar 'list vals) vals)))
9901 (defun org-property-previous-allowed-value (&optional previous)
9902 "Switch to the next allowed value for this property."
9903 (interactive)
9904 (org-property-next-allowed-value t))
9906 (defun org-property-next-allowed-value (&optional previous)
9907 "Switch to the next allowed value for this property."
9908 (interactive)
9909 (unless (org-at-property-p)
9910 (error "Not at a property"))
9911 (let* ((key (match-string 2))
9912 (value (match-string 3))
9913 (allowed (or (org-property-get-allowed-values (point) key)
9914 (and (member value '("[ ]" "[-]" "[X]"))
9915 '("[ ]" "[X]"))))
9916 nval)
9917 (unless allowed
9918 (error "Allowed values for this property have not been defined"))
9919 (if previous (setq allowed (reverse allowed)))
9920 (if (member value allowed)
9921 (setq nval (car (cdr (member value allowed)))))
9922 (setq nval (or nval (car allowed)))
9923 (if (equal nval value)
9924 (error "Only one allowed value for this property"))
9925 (org-at-property-p)
9926 (replace-match (concat " :" key ": " nval) t t)
9927 (org-indent-line-function)
9928 (beginning-of-line 1)
9929 (skip-chars-forward " \t")))
9931 (defun org-find-entry-with-id (ident)
9932 "Locate the entry that contains the ID property with exact value IDENT.
9933 IDENT can be a string, a symbol or a number, this function will search for
9934 the string representation of it.
9935 Return the position where this entry starts, or nil if there is no such entry."
9936 (let ((id (cond
9937 ((stringp ident) ident)
9938 ((symbol-name ident) (symbol-name ident))
9939 ((numberp ident) (number-to-string ident))
9940 (t (error "IDENT %s must be a string, symbol or number" ident))))
9941 (case-fold-search nil))
9942 (save-excursion
9943 (save-restriction
9944 (widen)
9945 (goto-char (point-min))
9946 (when (re-search-forward
9947 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9948 nil t)
9949 (org-back-to-heading)
9950 (point))))))
9952 ;;;; Timestamps
9954 (defvar org-last-changed-timestamp nil)
9955 (defvar org-time-was-given) ; dynamically scoped parameter
9956 (defvar org-end-time-was-given) ; dynamically scoped parameter
9957 (defvar org-ts-what) ; dynamically scoped parameter
9959 (defun org-time-stamp (arg)
9960 "Prompt for a date/time and insert a time stamp.
9961 If the user specifies a time like HH:MM, or if this command is called
9962 with a prefix argument, the time stamp will contain date and time.
9963 Otherwise, only the date will be included. All parts of a date not
9964 specified by the user will be filled in from the current date/time.
9965 So if you press just return without typing anything, the time stamp
9966 will represent the current date/time. If there is already a timestamp
9967 at the cursor, it will be modified."
9968 (interactive "P")
9969 (let* ((ts nil)
9970 (default-time
9971 ;; Default time is either today, or, when entering a range,
9972 ;; the range start.
9973 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9974 (save-excursion
9975 (re-search-backward
9976 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9977 (- (point) 20) t)))
9978 (apply 'encode-time (org-parse-time-string (match-string 1)))
9979 (current-time)))
9980 (default-input (and ts (org-get-compact-tod ts)))
9981 org-time-was-given org-end-time-was-given time)
9982 (cond
9983 ((and (org-at-timestamp-p)
9984 (eq last-command 'org-time-stamp)
9985 (eq this-command 'org-time-stamp))
9986 (insert "--")
9987 (setq time (let ((this-command this-command))
9988 (org-read-date arg 'totime nil nil default-time default-input)))
9989 (org-insert-time-stamp time (or org-time-was-given arg)))
9990 ((org-at-timestamp-p)
9991 (setq time (let ((this-command this-command))
9992 (org-read-date arg 'totime nil nil default-time default-input)))
9993 (when (org-at-timestamp-p) ; just to get the match data
9994 (replace-match "")
9995 (setq org-last-changed-timestamp
9996 (org-insert-time-stamp
9997 time (or org-time-was-given arg)
9998 nil nil nil (list org-end-time-was-given))))
9999 (message "Timestamp updated"))
10001 (setq time (let ((this-command this-command))
10002 (org-read-date arg 'totime nil nil default-time default-input)))
10003 (org-insert-time-stamp time (or org-time-was-given arg)
10004 nil nil nil (list org-end-time-was-given))))))
10006 ;; FIXME: can we use this for something else, like computing time differences?
10007 (defun org-get-compact-tod (s)
10008 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10009 (let* ((t1 (match-string 1 s))
10010 (h1 (string-to-number (match-string 2 s)))
10011 (m1 (string-to-number (match-string 3 s)))
10012 (t2 (and (match-end 4) (match-string 5 s)))
10013 (h2 (and t2 (string-to-number (match-string 6 s))))
10014 (m2 (and t2 (string-to-number (match-string 7 s))))
10015 dh dm)
10016 (if (not t2)
10018 (setq dh (- h2 h1) dm (- m2 m1))
10019 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10020 (concat t1 "+" (number-to-string dh)
10021 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10023 (defun org-time-stamp-inactive (&optional arg)
10024 "Insert an inactive time stamp.
10025 An inactive time stamp is enclosed in square brackets instead of angle
10026 brackets. It is inactive in the sense that it does not trigger agenda entries,
10027 does not link to the calendar and cannot be changed with the S-cursor keys.
10028 So these are more for recording a certain time/date."
10029 (interactive "P")
10030 (let (org-time-was-given org-end-time-was-given time)
10031 (setq time (org-read-date arg 'totime))
10032 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10033 nil nil (list org-end-time-was-given))))
10035 (defvar org-date-ovl (org-make-overlay 1 1))
10036 (org-overlay-put org-date-ovl 'face 'org-warning)
10037 (org-detach-overlay org-date-ovl)
10039 (defvar org-ans1) ; dynamically scoped parameter
10040 (defvar org-ans2) ; dynamically scoped parameter
10042 (defvar org-plain-time-of-day-regexp) ; defined below
10044 (defvar org-read-date-overlay nil)
10045 (defvar org-dcst nil) ; dynamically scoped
10047 (defun org-read-date (&optional with-time to-time from-string prompt
10048 default-time default-input)
10049 "Read a date, possibly a time, and make things smooth for the user.
10050 The prompt will suggest to enter an ISO date, but you can also enter anything
10051 which will at least partially be understood by `parse-time-string'.
10052 Unrecognized parts of the date will default to the current day, month, year,
10053 hour and minute. If this command is called to replace a timestamp at point,
10054 of to enter the second timestamp of a range, the default time is taken from the
10055 existing stamp. For example,
10056 3-2-5 --> 2003-02-05
10057 feb 15 --> currentyear-02-15
10058 sep 12 9 --> 2009-09-12
10059 12:45 --> today 12:45
10060 22 sept 0:34 --> currentyear-09-22 0:34
10061 12 --> currentyear-currentmonth-12
10062 Fri --> nearest Friday (today or later)
10063 etc.
10065 Furthermore you can specify a relative date by giving, as the *first* thing
10066 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10067 change in days weeks, months, years.
10068 With a single plus or minus, the date is relative to today. With a double
10069 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10070 +4d --> four days from today
10071 +4 --> same as above
10072 +2w --> two weeks from today
10073 ++5 --> five days from default date
10075 The function understands only English month and weekday abbreviations,
10076 but this can be configured with the variables `parse-time-months' and
10077 `parse-time-weekdays'.
10079 While prompting, a calendar is popped up - you can also select the
10080 date with the mouse (button 1). The calendar shows a period of three
10081 months. To scroll it to other months, use the keys `>' and `<'.
10082 If you don't like the calendar, turn it off with
10083 \(setq org-read-date-popup-calendar nil)
10085 With optional argument TO-TIME, the date will immediately be converted
10086 to an internal time.
10087 With an optional argument WITH-TIME, the prompt will suggest to also
10088 insert a time. Note that when WITH-TIME is not set, you can still
10089 enter a time, and this function will inform the calling routine about
10090 this change. The calling routine may then choose to change the format
10091 used to insert the time stamp into the buffer to include the time.
10092 With optional argument FROM-STRING, read from this string instead from
10093 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10094 the time/date that is used for everything that is not specified by the
10095 user."
10096 (require 'parse-time)
10097 (let* ((org-time-stamp-rounding-minutes
10098 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10099 (org-dcst org-display-custom-times)
10100 (ct (org-current-time))
10101 (def (or default-time ct))
10102 (defdecode (decode-time def))
10103 (dummy (progn
10104 (when (< (nth 2 defdecode) org-extend-today-until)
10105 (setcar (nthcdr 2 defdecode) -1)
10106 (setcar (nthcdr 1 defdecode) 59)
10107 (setq def (apply 'encode-time defdecode)
10108 defdecode (decode-time def)))))
10109 (calendar-move-hook nil)
10110 (calendar-view-diary-initially-flag nil)
10111 (view-diary-entries-initially nil)
10112 (calendar-view-holidays-initially-flag nil)
10113 (view-calendar-holidays-initially nil)
10114 (timestr (format-time-string
10115 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10116 (prompt (concat (if prompt (concat prompt " ") "")
10117 (format "Date+time [%s]: " timestr)))
10118 ans (org-ans0 "") org-ans1 org-ans2 final)
10120 (cond
10121 (from-string (setq ans from-string))
10122 (org-read-date-popup-calendar
10123 (save-excursion
10124 (save-window-excursion
10125 (calendar)
10126 (calendar-forward-day (- (time-to-days def)
10127 (calendar-absolute-from-gregorian
10128 (calendar-current-date))))
10129 (org-eval-in-calendar nil t)
10130 (let* ((old-map (current-local-map))
10131 (map (copy-keymap calendar-mode-map))
10132 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10133 (org-defkey map (kbd "RET") 'org-calendar-select)
10134 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10135 'org-calendar-select-mouse)
10136 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10137 'org-calendar-select-mouse)
10138 (org-defkey minibuffer-local-map [(meta shift left)]
10139 (lambda () (interactive)
10140 (org-eval-in-calendar '(calendar-backward-month 1))))
10141 (org-defkey minibuffer-local-map [(meta shift right)]
10142 (lambda () (interactive)
10143 (org-eval-in-calendar '(calendar-forward-month 1))))
10144 (org-defkey minibuffer-local-map [(meta shift up)]
10145 (lambda () (interactive)
10146 (org-eval-in-calendar '(calendar-backward-year 1))))
10147 (org-defkey minibuffer-local-map [(meta shift down)]
10148 (lambda () (interactive)
10149 (org-eval-in-calendar '(calendar-forward-year 1))))
10150 (org-defkey minibuffer-local-map [(shift up)]
10151 (lambda () (interactive)
10152 (org-eval-in-calendar '(calendar-backward-week 1))))
10153 (org-defkey minibuffer-local-map [(shift down)]
10154 (lambda () (interactive)
10155 (org-eval-in-calendar '(calendar-forward-week 1))))
10156 (org-defkey minibuffer-local-map [(shift left)]
10157 (lambda () (interactive)
10158 (org-eval-in-calendar '(calendar-backward-day 1))))
10159 (org-defkey minibuffer-local-map [(shift right)]
10160 (lambda () (interactive)
10161 (org-eval-in-calendar '(calendar-forward-day 1))))
10162 (org-defkey minibuffer-local-map ">"
10163 (lambda () (interactive)
10164 (org-eval-in-calendar '(scroll-calendar-left 1))))
10165 (org-defkey minibuffer-local-map "<"
10166 (lambda () (interactive)
10167 (org-eval-in-calendar '(scroll-calendar-right 1))))
10168 (unwind-protect
10169 (progn
10170 (use-local-map map)
10171 (add-hook 'post-command-hook 'org-read-date-display)
10172 (setq org-ans0 (read-string prompt default-input nil nil))
10173 ;; org-ans0: from prompt
10174 ;; org-ans1: from mouse click
10175 ;; org-ans2: from calendar motion
10176 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10177 (remove-hook 'post-command-hook 'org-read-date-display)
10178 (use-local-map old-map)
10179 (when org-read-date-overlay
10180 (org-delete-overlay org-read-date-overlay)
10181 (setq org-read-date-overlay nil)))))))
10183 (t ; Naked prompt only
10184 (unwind-protect
10185 (setq ans (read-string prompt default-input nil timestr))
10186 (when org-read-date-overlay
10187 (org-delete-overlay org-read-date-overlay)
10188 (setq org-read-date-overlay nil)))))
10190 (setq final (org-read-date-analyze ans def defdecode))
10192 (if to-time
10193 (apply 'encode-time final)
10194 (if (and (boundp 'org-time-was-given) org-time-was-given)
10195 (format "%04d-%02d-%02d %02d:%02d"
10196 (nth 5 final) (nth 4 final) (nth 3 final)
10197 (nth 2 final) (nth 1 final))
10198 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10199 (defvar def)
10200 (defvar defdecode)
10201 (defvar with-time)
10202 (defun org-read-date-display ()
10203 "Display the currrent date prompt interpretation in the minibuffer."
10204 (when org-read-date-display-live
10205 (when org-read-date-overlay
10206 (org-delete-overlay org-read-date-overlay))
10207 (let ((p (point)))
10208 (end-of-line 1)
10209 (while (not (equal (buffer-substring
10210 (max (point-min) (- (point) 4)) (point))
10211 " "))
10212 (insert " "))
10213 (goto-char p))
10214 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10215 " " (or org-ans1 org-ans2)))
10216 (org-end-time-was-given nil)
10217 (f (org-read-date-analyze ans def defdecode))
10218 (fmts (if org-dcst
10219 org-time-stamp-custom-formats
10220 org-time-stamp-formats))
10221 (fmt (if (or with-time
10222 (and (boundp 'org-time-was-given) org-time-was-given))
10223 (cdr fmts)
10224 (car fmts)))
10225 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10226 (when (and org-end-time-was-given
10227 (string-match org-plain-time-of-day-regexp txt))
10228 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10229 org-end-time-was-given
10230 (substring txt (match-end 0)))))
10231 (setq org-read-date-overlay
10232 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10233 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10235 (defun org-read-date-analyze (ans def defdecode)
10236 "Analyze the combined answer of the date prompt."
10237 ;; FIXME: cleanup and comment
10238 (let (delta deltan deltaw deltadef year month day
10239 hour minute second wday pm h2 m2 tl wday1
10240 iso-year iso-weekday iso-week iso-year iso-date)
10242 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10243 (setq ans "+0"))
10245 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10246 (setq ans (replace-match "" t t ans)
10247 deltan (car delta)
10248 deltaw (nth 1 delta)
10249 deltadef (nth 2 delta)))
10251 ;; Check if there is an iso week date in there
10252 ;; If yes, sore the info and ostpone interpreting it until the rest
10253 ;; of the parsing is done
10254 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10255 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10256 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10257 iso-week (string-to-number (match-string 2 ans)))
10258 (setq ans (replace-match "" t t ans)))
10260 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10261 (when (string-match
10262 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10263 (setq year (if (match-end 2)
10264 (string-to-number (match-string 2 ans))
10265 (string-to-number (format-time-string "%Y")))
10266 month (string-to-number (match-string 3 ans))
10267 day (string-to-number (match-string 4 ans)))
10268 (if (< year 100) (setq year (+ 2000 year)))
10269 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10270 t nil ans)))
10271 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10272 ;; If there is a time with am/pm, and *no* time without it, we convert
10273 ;; so that matching will be successful.
10274 (loop for i from 1 to 2 do ; twice, for end time as well
10275 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10276 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10277 (setq hour (string-to-number (match-string 1 ans))
10278 minute (if (match-end 3)
10279 (string-to-number (match-string 3 ans))
10281 pm (equal ?p
10282 (string-to-char (downcase (match-string 4 ans)))))
10283 (if (and (= hour 12) (not pm))
10284 (setq hour 0)
10285 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10286 (setq ans (replace-match (format "%02d:%02d" hour minute)
10287 t t ans))))
10289 ;; Check if a time range is given as a duration
10290 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10291 (setq hour (string-to-number (match-string 1 ans))
10292 h2 (+ hour (string-to-number (match-string 3 ans)))
10293 minute (string-to-number (match-string 2 ans))
10294 m2 (+ minute (if (match-end 5) (string-to-number
10295 (match-string 5 ans))0)))
10296 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10297 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10298 t t ans)))
10300 ;; Check if there is a time range
10301 (when (boundp 'org-end-time-was-given)
10302 (setq org-time-was-given nil)
10303 (when (and (string-match org-plain-time-of-day-regexp ans)
10304 (match-end 8))
10305 (setq org-end-time-was-given (match-string 8 ans))
10306 (setq ans (concat (substring ans 0 (match-beginning 7))
10307 (substring ans (match-end 7))))))
10309 (setq tl (parse-time-string ans)
10310 day (or (nth 3 tl) (nth 3 defdecode))
10311 month (or (nth 4 tl)
10312 (if (and org-read-date-prefer-future
10313 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10314 (1+ (nth 4 defdecode))
10315 (nth 4 defdecode)))
10316 year (or (nth 5 tl)
10317 (if (and org-read-date-prefer-future
10318 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10319 (1+ (nth 5 defdecode))
10320 (nth 5 defdecode)))
10321 hour (or (nth 2 tl) (nth 2 defdecode))
10322 minute (or (nth 1 tl) (nth 1 defdecode))
10323 second (or (nth 0 tl) 0)
10324 wday (nth 6 tl))
10326 ;; Special date definitions below
10327 (cond
10328 (iso-week
10329 ;; There was an iso week
10330 (setq year (or iso-year year)
10331 day (or iso-weekday wday 1)
10332 wday nil ; to make sure that the trigger below does not match
10333 iso-date (calendar-gregorian-from-absolute
10334 (calendar-absolute-from-iso
10335 (list iso-week day year))))
10336 ; FIXME: Should we also push ISO weeks into the future?
10337 ; (when (and org-read-date-prefer-future
10338 ; (not iso-year)
10339 ; (< (calendar-absolute-from-gregorian iso-date)
10340 ; (time-to-days (current-time))))
10341 ; (setq year (1+ year)
10342 ; iso-date (calendar-gregorian-from-absolute
10343 ; (calendar-absolute-from-iso
10344 ; (list iso-week day year)))))
10345 (setq month (car iso-date)
10346 year (nth 2 iso-date)
10347 day (nth 1 iso-date)))
10348 (deltan
10349 (unless deltadef
10350 (let ((now (decode-time (current-time))))
10351 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10352 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10353 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10354 ((equal deltaw "m") (setq month (+ month deltan)))
10355 ((equal deltaw "y") (setq year (+ year deltan)))))
10356 ((and wday (not (nth 3 tl)))
10357 ;; Weekday was given, but no day, so pick that day in the week
10358 ;; on or after the derived date.
10359 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10360 (unless (equal wday wday1)
10361 (setq day (+ day (% (- wday wday1 -7) 7))))))
10362 (if (and (boundp 'org-time-was-given)
10363 (nth 2 tl))
10364 (setq org-time-was-given t))
10365 (if (< year 100) (setq year (+ 2000 year)))
10366 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10367 (list second minute hour day month year)))
10369 (defvar parse-time-weekdays)
10371 (defun org-read-date-get-relative (s today default)
10372 "Check string S for special relative date string.
10373 TODAY and DEFAULT are internal times, for today and for a default.
10374 Return shift list (N what def-flag)
10375 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10376 N is the number of WHATs to shift.
10377 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10378 the DEFAULT date rather than TODAY."
10379 (when (and
10380 (string-match
10381 (concat
10382 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10383 "\\([0-9]+\\)?"
10384 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10385 "\\([ \t]\\|$\\)") s)
10386 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10387 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10388 (string-to-char (substring (match-string 1 s) -1))
10389 ?+))
10390 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10391 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10392 (what (if (match-end 3) (match-string 3 s) "d"))
10393 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10394 (date (if rel default today))
10395 (wday (nth 6 (decode-time date)))
10396 delta)
10397 (if wday1
10398 (progn
10399 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10400 (if (= dir ?-) (setq delta (- delta 7)))
10401 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10402 (list delta "d" rel))
10403 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10405 (defun org-eval-in-calendar (form &optional keepdate)
10406 "Eval FORM in the calendar window and return to current window.
10407 Also, store the cursor date in variable org-ans2."
10408 (let ((sw (selected-window)))
10409 (select-window (get-buffer-window "*Calendar*"))
10410 (eval form)
10411 (when (and (not keepdate) (calendar-cursor-to-date))
10412 (let* ((date (calendar-cursor-to-date))
10413 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10414 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10415 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10416 (select-window sw)))
10418 ; ;; Update the prompt to show new default date
10419 ; (save-excursion
10420 ; (goto-char (point-min))
10421 ; (when (and org-ans2
10422 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10423 ; (get-text-property (match-end 0) 'field))
10424 ; (let ((inhibit-read-only t))
10425 ; (replace-match (concat "[" org-ans2 "]") t t)
10426 ; (add-text-properties (point-min) (1+ (match-end 0))
10427 ; (text-properties-at (1+ (point-min)))))))))
10429 (defun org-calendar-select ()
10430 "Return to `org-read-date' with the date currently selected.
10431 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10432 (interactive)
10433 (when (calendar-cursor-to-date)
10434 (let* ((date (calendar-cursor-to-date))
10435 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10436 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10437 (if (active-minibuffer-window) (exit-minibuffer))))
10439 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10440 "Insert a date stamp for the date given by the internal TIME.
10441 WITH-HM means, use the stamp format that includes the time of the day.
10442 INACTIVE means use square brackets instead of angular ones, so that the
10443 stamp will not contribute to the agenda.
10444 PRE and POST are optional strings to be inserted before and after the
10445 stamp.
10446 The command returns the inserted time stamp."
10447 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10448 stamp)
10449 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10450 (insert-before-markers (or pre ""))
10451 (insert-before-markers (setq stamp (format-time-string fmt time)))
10452 (when (listp extra)
10453 (setq extra (car extra))
10454 (if (and (stringp extra)
10455 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10456 (setq extra (format "-%02d:%02d"
10457 (string-to-number (match-string 1 extra))
10458 (string-to-number (match-string 2 extra))))
10459 (setq extra nil)))
10460 (when extra
10461 (backward-char 1)
10462 (insert-before-markers extra)
10463 (forward-char 1))
10464 (insert-before-markers (or post ""))
10465 stamp))
10467 (defun org-toggle-time-stamp-overlays ()
10468 "Toggle the use of custom time stamp formats."
10469 (interactive)
10470 (setq org-display-custom-times (not org-display-custom-times))
10471 (unless org-display-custom-times
10472 (let ((p (point-min)) (bmp (buffer-modified-p)))
10473 (while (setq p (next-single-property-change p 'display))
10474 (if (and (get-text-property p 'display)
10475 (eq (get-text-property p 'face) 'org-date))
10476 (remove-text-properties
10477 p (setq p (next-single-property-change p 'display))
10478 '(display t))))
10479 (set-buffer-modified-p bmp)))
10480 (if (featurep 'xemacs)
10481 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10482 (org-restart-font-lock)
10483 (setq org-table-may-need-update t)
10484 (if org-display-custom-times
10485 (message "Time stamps are overlayed with custom format")
10486 (message "Time stamp overlays removed")))
10488 (defun org-display-custom-time (beg end)
10489 "Overlay modified time stamp format over timestamp between BEG and END."
10490 (let* ((ts (buffer-substring beg end))
10491 t1 w1 with-hm tf time str w2 (off 0))
10492 (save-match-data
10493 (setq t1 (org-parse-time-string ts t))
10494 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10495 (setq off (- (match-end 0) (match-beginning 0)))))
10496 (setq end (- end off))
10497 (setq w1 (- end beg)
10498 with-hm (and (nth 1 t1) (nth 2 t1))
10499 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10500 time (org-fix-decoded-time t1)
10501 str (org-add-props
10502 (format-time-string
10503 (substring tf 1 -1) (apply 'encode-time time))
10504 nil 'mouse-face 'highlight)
10505 w2 (length str))
10506 (if (not (= w2 w1))
10507 (add-text-properties (1+ beg) (+ 2 beg)
10508 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10509 (if (featurep 'xemacs)
10510 (progn
10511 (put-text-property beg end 'invisible t)
10512 (put-text-property beg end 'end-glyph (make-glyph str)))
10513 (put-text-property beg end 'display str))))
10515 (defun org-translate-time (string)
10516 "Translate all timestamps in STRING to custom format.
10517 But do this only if the variable `org-display-custom-times' is set."
10518 (when org-display-custom-times
10519 (save-match-data
10520 (let* ((start 0)
10521 (re org-ts-regexp-both)
10522 t1 with-hm inactive tf time str beg end)
10523 (while (setq start (string-match re string start))
10524 (setq beg (match-beginning 0)
10525 end (match-end 0)
10526 t1 (save-match-data
10527 (org-parse-time-string (substring string beg end) t))
10528 with-hm (and (nth 1 t1) (nth 2 t1))
10529 inactive (equal (substring string beg (1+ beg)) "[")
10530 tf (funcall (if with-hm 'cdr 'car)
10531 org-time-stamp-custom-formats)
10532 time (org-fix-decoded-time t1)
10533 str (format-time-string
10534 (concat
10535 (if inactive "[" "<") (substring tf 1 -1)
10536 (if inactive "]" ">"))
10537 (apply 'encode-time time))
10538 string (replace-match str t t string)
10539 start (+ start (length str)))))))
10540 string)
10542 (defun org-fix-decoded-time (time)
10543 "Set 0 instead of nil for the first 6 elements of time.
10544 Don't touch the rest."
10545 (let ((n 0))
10546 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10548 (defun org-days-to-time (timestamp-string)
10549 "Difference between TIMESTAMP-STRING and now in days."
10550 (- (time-to-days (org-time-string-to-time timestamp-string))
10551 (time-to-days (current-time))))
10553 (defun org-deadline-close (timestamp-string &optional ndays)
10554 "Is the time in TIMESTAMP-STRING close to the current date?"
10555 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10556 (and (< (org-days-to-time timestamp-string) ndays)
10557 (not (org-entry-is-done-p))))
10559 (defun org-get-wdays (ts)
10560 "Get the deadline lead time appropriate for timestring TS."
10561 (cond
10562 ((<= org-deadline-warning-days 0)
10563 ;; 0 or negative, enforce this value no matter what
10564 (- org-deadline-warning-days))
10565 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10566 ;; lead time is specified.
10567 (floor (* (string-to-number (match-string 1 ts))
10568 (cdr (assoc (match-string 2 ts)
10569 '(("d" . 1) ("w" . 7)
10570 ("m" . 30.4) ("y" . 365.25)))))))
10571 ;; go for the default.
10572 (t org-deadline-warning-days)))
10574 (defun org-calendar-select-mouse (ev)
10575 "Return to `org-read-date' with the date currently selected.
10576 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10577 (interactive "e")
10578 (mouse-set-point ev)
10579 (when (calendar-cursor-to-date)
10580 (let* ((date (calendar-cursor-to-date))
10581 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10582 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10583 (if (active-minibuffer-window) (exit-minibuffer))))
10585 (defun org-check-deadlines (ndays)
10586 "Check if there are any deadlines due or past due.
10587 A deadline is considered due if it happens within `org-deadline-warning-days'
10588 days from today's date. If the deadline appears in an entry marked DONE,
10589 it is not shown. The prefix arg NDAYS can be used to test that many
10590 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10591 (interactive "P")
10592 (let* ((org-warn-days
10593 (cond
10594 ((equal ndays '(4)) 100000)
10595 (ndays (prefix-numeric-value ndays))
10596 (t (abs org-deadline-warning-days))))
10597 (case-fold-search nil)
10598 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10599 (callback
10600 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10602 (message "%d deadlines past-due or due within %d days"
10603 (org-occur regexp nil callback)
10604 org-warn-days)))
10606 (defun org-check-before-date (date)
10607 "Check if there are deadlines or scheduled entries before DATE."
10608 (interactive (list (org-read-date)))
10609 (let ((case-fold-search nil)
10610 (regexp (concat "\\<\\(" org-deadline-string
10611 "\\|" org-scheduled-string
10612 "\\) *<\\([^>]+\\)>"))
10613 (callback
10614 (lambda () (time-less-p
10615 (org-time-string-to-time (match-string 2))
10616 (org-time-string-to-time date)))))
10617 (message "%d entries before %s"
10618 (org-occur regexp nil callback) date)))
10620 (defun org-evaluate-time-range (&optional to-buffer)
10621 "Evaluate a time range by computing the difference between start and end.
10622 Normally the result is just printed in the echo area, but with prefix arg
10623 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10624 If the time range is actually in a table, the result is inserted into the
10625 next column.
10626 For time difference computation, a year is assumed to be exactly 365
10627 days in order to avoid rounding problems."
10628 (interactive "P")
10630 (org-clock-update-time-maybe)
10631 (save-excursion
10632 (unless (org-at-date-range-p t)
10633 (goto-char (point-at-bol))
10634 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10635 (if (not (org-at-date-range-p t))
10636 (error "Not at a time-stamp range, and none found in current line")))
10637 (let* ((ts1 (match-string 1))
10638 (ts2 (match-string 2))
10639 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10640 (match-end (match-end 0))
10641 (time1 (org-time-string-to-time ts1))
10642 (time2 (org-time-string-to-time ts2))
10643 (t1 (time-to-seconds time1))
10644 (t2 (time-to-seconds time2))
10645 (diff (abs (- t2 t1)))
10646 (negative (< (- t2 t1) 0))
10647 ;; (ys (floor (* 365 24 60 60)))
10648 (ds (* 24 60 60))
10649 (hs (* 60 60))
10650 (fy "%dy %dd %02d:%02d")
10651 (fy1 "%dy %dd")
10652 (fd "%dd %02d:%02d")
10653 (fd1 "%dd")
10654 (fh "%02d:%02d")
10655 y d h m align)
10656 (if havetime
10657 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10659 d (floor (/ diff ds)) diff (mod diff ds)
10660 h (floor (/ diff hs)) diff (mod diff hs)
10661 m (floor (/ diff 60)))
10662 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10664 d (floor (+ (/ diff ds) 0.5))
10665 h 0 m 0))
10666 (if (not to-buffer)
10667 (message "%s" (org-make-tdiff-string y d h m))
10668 (if (org-at-table-p)
10669 (progn
10670 (goto-char match-end)
10671 (setq align t)
10672 (and (looking-at " *|") (goto-char (match-end 0))))
10673 (goto-char match-end))
10674 (if (looking-at
10675 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10676 (replace-match ""))
10677 (if negative (insert " -"))
10678 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10679 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10680 (insert " " (format fh h m))))
10681 (if align (org-table-align))
10682 (message "Time difference inserted")))))
10684 (defun org-make-tdiff-string (y d h m)
10685 (let ((fmt "")
10686 (l nil))
10687 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10688 l (push y l)))
10689 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10690 l (push d l)))
10691 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10692 l (push h l)))
10693 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10694 l (push m l)))
10695 (apply 'format fmt (nreverse l))))
10697 (defun org-time-string-to-time (s)
10698 (apply 'encode-time (org-parse-time-string s)))
10700 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10701 "Convert a time stamp to an absolute day number.
10702 If there is a specifyer for a cyclic time stamp, get the closest date to
10703 DAYNR.
10704 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10705 (cond
10706 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10707 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10708 daynr
10709 (+ daynr 1000)))
10710 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10711 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10712 (time-to-days (current-time))) (match-string 0 s)
10713 prefer show-all))
10714 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10716 (defun org-days-to-iso-week (days)
10717 "Return the iso week number."
10718 (require 'cal-iso)
10719 (car (calendar-iso-from-absolute days)))
10721 (defun org-small-year-to-year (year)
10722 "Convert 2-digit years into 4-digit years.
10723 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10724 The year 2000 cannot be abbreviated. Any year lager than 99
10725 is retrned unchanged."
10726 (if (< year 38)
10727 (setq year (+ 2000 year))
10728 (if (< year 100)
10729 (setq year (+ 1900 year))))
10730 year)
10732 (defun org-time-from-absolute (d)
10733 "Return the time corresponding to date D.
10734 D may be an absolute day number, or a calendar-type list (month day year)."
10735 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10736 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10738 (defun org-calendar-holiday ()
10739 "List of holidays, for Diary display in Org-mode."
10740 (require 'holidays)
10741 (let ((hl (funcall
10742 (if (fboundp 'calendar-check-holidays)
10743 'calendar-check-holidays 'check-calendar-holidays) date)))
10744 (if hl (mapconcat 'identity hl "; "))))
10746 (defun org-diary-sexp-entry (sexp entry date)
10747 "Process a SEXP diary ENTRY for DATE."
10748 (require 'diary-lib)
10749 (let ((result (if calendar-debug-sexp
10750 (let ((stack-trace-on-error t))
10751 (eval (car (read-from-string sexp))))
10752 (condition-case nil
10753 (eval (car (read-from-string sexp)))
10754 (error
10755 (beep)
10756 (message "Bad sexp at line %d in %s: %s"
10757 (org-current-line)
10758 (buffer-file-name) sexp)
10759 (sleep-for 2))))))
10760 (cond ((stringp result) result)
10761 ((and (consp result)
10762 (stringp (cdr result))) (cdr result))
10763 (result entry)
10764 (t nil))))
10766 (defun org-diary-to-ical-string (frombuf)
10767 "Get iCalendar entries from diary entries in buffer FROMBUF.
10768 This uses the icalendar.el library."
10769 (let* ((tmpdir (if (featurep 'xemacs)
10770 (temp-directory)
10771 temporary-file-directory))
10772 (tmpfile (make-temp-name
10773 (expand-file-name "orgics" tmpdir)))
10774 buf rtn b e)
10775 (save-excursion
10776 (set-buffer frombuf)
10777 (icalendar-export-region (point-min) (point-max) tmpfile)
10778 (setq buf (find-buffer-visiting tmpfile))
10779 (set-buffer buf)
10780 (goto-char (point-min))
10781 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10782 (setq b (match-beginning 0)))
10783 (goto-char (point-max))
10784 (if (re-search-backward "^END:VEVENT" nil t)
10785 (setq e (match-end 0)))
10786 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10787 (kill-buffer buf)
10788 (kill-buffer frombuf)
10789 (delete-file tmpfile)
10790 rtn))
10792 (defun org-closest-date (start current change prefer show-all)
10793 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10794 When PREFER is `past' return a date that is either CURRENT or past.
10795 When PREFER is `future', return a date that is either CURRENT or future.
10796 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10797 ;; Make the proper lists from the dates
10798 (catch 'exit
10799 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10800 dn dw sday cday n1 n2
10801 d m y y1 y2 date1 date2 nmonths nm ny m2)
10803 (setq start (org-date-to-gregorian start)
10804 current (org-date-to-gregorian
10805 (if show-all
10806 current
10807 (time-to-days (current-time))))
10808 sday (calendar-absolute-from-gregorian start)
10809 cday (calendar-absolute-from-gregorian current))
10811 (if (<= cday sday) (throw 'exit sday))
10813 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10814 (setq dn (string-to-number (match-string 1 change))
10815 dw (cdr (assoc (match-string 2 change) a1)))
10816 (error "Invalid change specifyer: %s" change))
10817 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10818 (cond
10819 ((eq dw 'day)
10820 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10821 n2 (+ n1 dn)))
10822 ((eq dw 'year)
10823 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10824 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10825 (setq date1 (list m d y1)
10826 n1 (calendar-absolute-from-gregorian date1)
10827 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10828 n2 (calendar-absolute-from-gregorian date2)))
10829 ((eq dw 'month)
10830 ;; approx number of month between the tow dates
10831 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10832 ;; How often does dn fit in there?
10833 (setq d (nth 1 start) m (car start) y (nth 2 start)
10834 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10835 m (+ m nm)
10836 ny (floor (/ m 12))
10837 y (+ y ny)
10838 m (- m (* ny 12)))
10839 (while (> m 12) (setq m (- m 12) y (1+ y)))
10840 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10841 (setq m2 (+ m dn) y2 y)
10842 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10843 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10844 (while (< n2 cday)
10845 (setq n1 n2 m m2 y y2)
10846 (setq m2 (+ m dn) y2 y)
10847 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10848 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10850 (if show-all
10851 (cond
10852 ((eq prefer 'past) n1)
10853 ((eq prefer 'future) (if (= cday n1) n1 n2))
10854 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10855 (cond
10856 ((eq prefer 'past) n1)
10857 ((eq prefer 'future) (if (= cday n1) n1 n2))
10858 (t (if (= cday n1) n1 n2)))))))
10860 (defun org-date-to-gregorian (date)
10861 "Turn any specification of DATE into a gregorian date for the calendar."
10862 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10863 ((and (listp date) (= (length date) 3)) date)
10864 ((stringp date)
10865 (setq date (org-parse-time-string date))
10866 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10867 ((listp date)
10868 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10870 (defun org-parse-time-string (s &optional nodefault)
10871 "Parse the standard Org-mode time string.
10872 This should be a lot faster than the normal `parse-time-string'.
10873 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10874 hour and minute fields will be nil if not given."
10875 (if (string-match org-ts-regexp0 s)
10876 (list 0
10877 (if (or (match-beginning 8) (not nodefault))
10878 (string-to-number (or (match-string 8 s) "0")))
10879 (if (or (match-beginning 7) (not nodefault))
10880 (string-to-number (or (match-string 7 s) "0")))
10881 (string-to-number (match-string 4 s))
10882 (string-to-number (match-string 3 s))
10883 (string-to-number (match-string 2 s))
10884 nil nil nil)
10885 (make-list 9 0)))
10887 (defun org-timestamp-up (&optional arg)
10888 "Increase the date item at the cursor by one.
10889 If the cursor is on the year, change the year. If it is on the month or
10890 the day, change that.
10891 With prefix ARG, change by that many units."
10892 (interactive "p")
10893 (org-timestamp-change (prefix-numeric-value arg)))
10895 (defun org-timestamp-down (&optional arg)
10896 "Decrease the date item at the cursor by one.
10897 If the cursor is on the year, change the year. If it is on the month or
10898 the day, change that.
10899 With prefix ARG, change by that many units."
10900 (interactive "p")
10901 (org-timestamp-change (- (prefix-numeric-value arg))))
10903 (defun org-timestamp-up-day (&optional arg)
10904 "Increase the date in the time stamp by one day.
10905 With prefix ARG, change that many days."
10906 (interactive "p")
10907 (if (and (not (org-at-timestamp-p t))
10908 (org-on-heading-p))
10909 (org-todo 'up)
10910 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10912 (defun org-timestamp-down-day (&optional arg)
10913 "Decrease the date in the time stamp by one day.
10914 With prefix ARG, change that many days."
10915 (interactive "p")
10916 (if (and (not (org-at-timestamp-p t))
10917 (org-on-heading-p))
10918 (org-todo 'down)
10919 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10921 (defun org-at-timestamp-p (&optional inactive-ok)
10922 "Determine if the cursor is in or at a timestamp."
10923 (interactive)
10924 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10925 (pos (point))
10926 (ans (or (looking-at tsr)
10927 (save-excursion
10928 (skip-chars-backward "^[<\n\r\t")
10929 (if (> (point) (point-min)) (backward-char 1))
10930 (and (looking-at tsr)
10931 (> (- (match-end 0) pos) -1))))))
10932 (and ans
10933 (boundp 'org-ts-what)
10934 (setq org-ts-what
10935 (cond
10936 ((= pos (match-beginning 0)) 'bracket)
10937 ((= pos (1- (match-end 0))) 'bracket)
10938 ((org-pos-in-match-range pos 2) 'year)
10939 ((org-pos-in-match-range pos 3) 'month)
10940 ((org-pos-in-match-range pos 7) 'hour)
10941 ((org-pos-in-match-range pos 8) 'minute)
10942 ((or (org-pos-in-match-range pos 4)
10943 (org-pos-in-match-range pos 5)) 'day)
10944 ((and (> pos (or (match-end 8) (match-end 5)))
10945 (< pos (match-end 0)))
10946 (- pos (or (match-end 8) (match-end 5))))
10947 (t 'day))))
10948 ans))
10950 (defun org-toggle-timestamp-type ()
10951 "Toggle the type (<active> or [inactive]) of a time stamp."
10952 (interactive)
10953 (when (org-at-timestamp-p t)
10954 (save-excursion
10955 (goto-char (match-beginning 0))
10956 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10957 (goto-char (1- (match-end 0)))
10958 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10959 (message "Timestamp is now %sactive"
10960 (if (equal (char-before) ?>) "in" ""))))
10962 (defun org-timestamp-change (n &optional what)
10963 "Change the date in the time stamp at point.
10964 The date will be changed by N times WHAT. WHAT can be `day', `month',
10965 `year', `minute', `second'. If WHAT is not given, the cursor position
10966 in the timestamp determines what will be changed."
10967 (let ((pos (point))
10968 with-hm inactive
10969 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10970 org-ts-what
10971 extra rem
10972 ts time time0)
10973 (if (not (org-at-timestamp-p t))
10974 (error "Not at a timestamp"))
10975 (if (and (not what) (eq org-ts-what 'bracket))
10976 (org-toggle-timestamp-type)
10977 (if (and (not what) (not (eq org-ts-what 'day))
10978 org-display-custom-times
10979 (get-text-property (point) 'display)
10980 (not (get-text-property (1- (point)) 'display)))
10981 (setq org-ts-what 'day))
10982 (setq org-ts-what (or what org-ts-what)
10983 inactive (= (char-after (match-beginning 0)) ?\[)
10984 ts (match-string 0))
10985 (replace-match "")
10986 (if (string-match
10987 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10989 (setq extra (match-string 1 ts)))
10990 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10991 (setq with-hm t))
10992 (setq time0 (org-parse-time-string ts))
10993 (when (and (eq org-ts-what 'minute)
10994 (eq current-prefix-arg nil))
10995 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10996 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10997 (setcar (cdr time0) (+ (nth 1 time0)
10998 (if (> n 0) (- rem) (- dm rem))))))
10999 (setq time
11000 (encode-time (or (car time0) 0)
11001 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11002 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11003 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11004 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11005 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11006 (nthcdr 6 time0)))
11007 (when (integerp org-ts-what)
11008 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11009 (if (eq what 'calendar)
11010 (let ((cal-date (org-get-date-from-calendar)))
11011 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11012 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11013 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11014 (setcar time0 (or (car time0) 0))
11015 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11016 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11017 (setq time (apply 'encode-time time0))))
11018 (setq org-last-changed-timestamp
11019 (org-insert-time-stamp time with-hm inactive nil nil extra))
11020 (org-clock-update-time-maybe)
11021 (goto-char pos)
11022 ;; Try to recenter the calendar window, if any
11023 (if (and org-calendar-follow-timestamp-change
11024 (get-buffer-window "*Calendar*" t)
11025 (memq org-ts-what '(day month year)))
11026 (org-recenter-calendar (time-to-days time))))))
11028 (defun org-modify-ts-extra (s pos n dm)
11029 "Change the different parts of the lead-time and repeat fields in timestamp."
11030 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11031 ng h m new rem)
11032 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11033 (cond
11034 ((or (org-pos-in-match-range pos 2)
11035 (org-pos-in-match-range pos 3))
11036 (setq m (string-to-number (match-string 3 s))
11037 h (string-to-number (match-string 2 s)))
11038 (if (org-pos-in-match-range pos 2)
11039 (setq h (+ h n))
11040 (setq n (* dm (org-no-warnings (signum n))))
11041 (when (not (= 0 (setq rem (% m dm))))
11042 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11043 (setq m (+ m n)))
11044 (if (< m 0) (setq m (+ m 60) h (1- h)))
11045 (if (> m 59) (setq m (- m 60) h (1+ h)))
11046 (setq h (min 24 (max 0 h)))
11047 (setq ng 1 new (format "-%02d:%02d" h m)))
11048 ((org-pos-in-match-range pos 6)
11049 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11050 ((org-pos-in-match-range pos 5)
11051 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11053 ((org-pos-in-match-range pos 9)
11054 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11055 ((org-pos-in-match-range pos 8)
11056 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11058 (when ng
11059 (setq s (concat
11060 (substring s 0 (match-beginning ng))
11062 (substring s (match-end ng))))))
11065 (defun org-recenter-calendar (date)
11066 "If the calendar is visible, recenter it to DATE."
11067 (let* ((win (selected-window))
11068 (cwin (get-buffer-window "*Calendar*" t))
11069 (calendar-move-hook nil))
11070 (when cwin
11071 (select-window cwin)
11072 (calendar-goto-date (if (listp date) date
11073 (calendar-gregorian-from-absolute date)))
11074 (select-window win))))
11076 (defun org-goto-calendar (&optional arg)
11077 "Go to the Emacs calendar at the current date.
11078 If there is a time stamp in the current line, go to that date.
11079 A prefix ARG can be used to force the current date."
11080 (interactive "P")
11081 (let ((tsr org-ts-regexp) diff
11082 (calendar-move-hook nil)
11083 (calendar-view-holidays-initially-flag nil)
11084 (view-calendar-holidays-initially nil)
11085 (calendar-view-diary-initially-flag nil)
11086 (view-diary-entries-initially nil))
11087 (if (or (org-at-timestamp-p)
11088 (save-excursion
11089 (beginning-of-line 1)
11090 (looking-at (concat ".*" tsr))))
11091 (let ((d1 (time-to-days (current-time)))
11092 (d2 (time-to-days
11093 (org-time-string-to-time (match-string 1)))))
11094 (setq diff (- d2 d1))))
11095 (calendar)
11096 (calendar-goto-today)
11097 (if (and diff (not arg)) (calendar-forward-day diff))))
11099 (defun org-get-date-from-calendar ()
11100 "Return a list (month day year) of date at point in calendar."
11101 (with-current-buffer "*Calendar*"
11102 (save-match-data
11103 (calendar-cursor-to-date))))
11105 (defun org-date-from-calendar ()
11106 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11107 If there is already a time stamp at the cursor position, update it."
11108 (interactive)
11109 (if (org-at-timestamp-p t)
11110 (org-timestamp-change 0 'calendar)
11111 (let ((cal-date (org-get-date-from-calendar)))
11112 (org-insert-time-stamp
11113 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11115 (defun org-minutes-to-hh:mm-string (m)
11116 "Compute H:MM from a number of minutes."
11117 (let ((h (/ m 60)))
11118 (setq m (- m (* 60 h)))
11119 (format "%d:%02d" h m)))
11121 (defun org-hh:mm-string-to-minutes (s)
11122 "Convert a string H:MM to a number of minutes."
11123 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11124 (+ (* (string-to-number (match-string 1 s)) 60)
11125 (string-to-number (match-string 2 s)))
11128 ;;;; Agenda files
11130 ;;;###autoload
11131 (defun org-iswitchb (&optional arg)
11132 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11133 With a prefix argument, restrict available to files.
11134 With two prefix arguments, restrict available buffers to agenda files.
11136 Due to some yet unresolved reason, global function
11137 `iswitchb-mode' needs to be active for this function to work."
11138 (interactive "P")
11139 (require 'iswitchb)
11140 (let ((enabled iswitchb-mode) blist)
11141 (or enabled (iswitchb-mode 1))
11142 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11143 ((equal arg '(16)) (org-buffer-list 'agenda))
11144 (t (org-buffer-list))))
11145 (unwind-protect
11146 (let ((iswitchb-make-buflist-hook
11147 (lambda ()
11148 (setq iswitchb-temp-buflist
11149 (mapcar 'buffer-name blist)))))
11150 (switch-to-buffer
11151 (iswitchb-read-buffer
11152 "Switch-to: " nil t))
11153 (or enabled (iswitchb-mode -1))))))
11155 (defun org-buffer-list (&optional predicate tmp)
11156 "Return a list of Org buffers.
11157 PREDICATE can be either 'export, 'files or 'agenda.
11159 'export restrict the list to Export buffers.
11160 'files restrict the list to buffers visiting Org files.
11161 'agenda restrict the list to buffers visiting agenda files.
11163 If TMP is non-nil, don't include temporary buffers."
11164 (let (filter blist)
11165 (setq filter
11166 (cond ((eq predicate 'files) "\.org$")
11167 ((eq predicate 'export) "\*Org .*Export")
11168 (t "\*Org \\|\.org$")))
11169 (setq blist
11170 (mapcar
11171 (lambda(b)
11172 (let ((bname (buffer-name b))
11173 (bfile (buffer-file-name b)))
11174 (if (and (string-match filter bname)
11175 (if (eq predicate 'agenda)
11176 (member bfile
11177 (mapcar (lambda(f) (file-truename f))
11178 org-agenda-files)) t)
11179 (if tmp (not (string-match "tmp" bname)) t)) b)))
11180 (buffer-list)))
11181 (delete nil blist)))
11183 (defun org-agenda-files (&optional unrestricted ext)
11184 "Get the list of agenda files.
11185 Optional UNRESTRICTED means return the full list even if a restriction
11186 is currently in place.
11187 When EXT is non-nil, try to add all files that are created by adding EXT
11188 to the file nemes. Basically, this is a way to add the archive files
11189 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11190 a string, \"_archive\" will be used."
11191 (let ((files
11192 (cond
11193 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11194 ((stringp org-agenda-files) (org-read-agenda-file-list))
11195 ((listp org-agenda-files) org-agenda-files)
11196 (t (error "Invalid value of `org-agenda-files'")))))
11197 (setq files (apply 'append
11198 (mapcar (lambda (f)
11199 (if (file-directory-p f)
11200 (directory-files
11201 f t org-agenda-file-regexp)
11202 (list f)))
11203 files)))
11204 (when org-agenda-skip-unavailable-files
11205 (setq files (delq nil
11206 (mapcar (function
11207 (lambda (file)
11208 (and (file-readable-p file) file)))
11209 files))))
11210 (when ext
11211 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11212 ext "_archive"))
11213 (setq files (apply 'append
11214 (mapcar
11215 (lambda (f)
11216 (if (file-exists-p (concat f ext))
11217 (list f (concat f ext))
11218 (list f)))
11219 files))))
11220 files))
11222 (defun org-edit-agenda-file-list ()
11223 "Edit the list of agenda files.
11224 Depending on setup, this either uses customize to edit the variable
11225 `org-agenda-files', or it visits the file that is holding the list. In the
11226 latter case, the buffer is set up in a way that saving it automatically kills
11227 the buffer and restores the previous window configuration."
11228 (interactive)
11229 (if (stringp org-agenda-files)
11230 (let ((cw (current-window-configuration)))
11231 (find-file org-agenda-files)
11232 (org-set-local 'org-window-configuration cw)
11233 (org-add-hook 'after-save-hook
11234 (lambda ()
11235 (set-window-configuration
11236 (prog1 org-window-configuration
11237 (kill-buffer (current-buffer))))
11238 (org-install-agenda-files-menu)
11239 (message "New agenda file list installed"))
11240 nil 'local)
11241 (message "%s" (substitute-command-keys
11242 "Edit list and finish with \\[save-buffer]")))
11243 (customize-variable 'org-agenda-files)))
11245 (defun org-store-new-agenda-file-list (list)
11246 "Set new value for the agenda file list and save it correcly."
11247 (if (stringp org-agenda-files)
11248 (let ((f org-agenda-files) b)
11249 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11250 (with-temp-file f
11251 (insert (mapconcat 'identity list "\n") "\n")))
11252 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11253 (setq org-agenda-files list)
11254 (customize-save-variable 'org-agenda-files org-agenda-files))))
11256 (defun org-read-agenda-file-list ()
11257 "Read the list of agenda files from a file."
11258 (when (file-directory-p org-agenda-files)
11259 (error "`org-agenda-files' cannot be a single directory"))
11260 (when (stringp org-agenda-files)
11261 (with-temp-buffer
11262 (insert-file-contents org-agenda-files)
11263 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11266 ;;;###autoload
11267 (defun org-cycle-agenda-files ()
11268 "Cycle through the files in `org-agenda-files'.
11269 If the current buffer visits an agenda file, find the next one in the list.
11270 If the current buffer does not, find the first agenda file."
11271 (interactive)
11272 (let* ((fs (org-agenda-files t))
11273 (files (append fs (list (car fs))))
11274 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11275 file)
11276 (unless files (error "No agenda files"))
11277 (catch 'exit
11278 (while (setq file (pop files))
11279 (if (equal (file-truename file) tcf)
11280 (when (car files)
11281 (find-file (car files))
11282 (throw 'exit t))))
11283 (find-file (car fs)))
11284 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11286 (defun org-agenda-file-to-front (&optional to-end)
11287 "Move/add the current file to the top of the agenda file list.
11288 If the file is not present in the list, it is added to the front. If it is
11289 present, it is moved there. With optional argument TO-END, add/move to the
11290 end of the list."
11291 (interactive "P")
11292 (let ((org-agenda-skip-unavailable-files nil)
11293 (file-alist (mapcar (lambda (x)
11294 (cons (file-truename x) x))
11295 (org-agenda-files t)))
11296 (ctf (file-truename buffer-file-name))
11297 x had)
11298 (setq x (assoc ctf file-alist) had x)
11300 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11301 (if to-end
11302 (setq file-alist (append (delq x file-alist) (list x)))
11303 (setq file-alist (cons x (delq x file-alist))))
11304 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11305 (org-install-agenda-files-menu)
11306 (message "File %s to %s of agenda file list"
11307 (if had "moved" "added") (if to-end "end" "front"))))
11309 (defun org-remove-file (&optional file)
11310 "Remove current file from the list of files in variable `org-agenda-files'.
11311 These are the files which are being checked for agenda entries.
11312 Optional argument FILE means, use this file instead of the current."
11313 (interactive)
11314 (let* ((org-agenda-skip-unavailable-files nil)
11315 (file (or file buffer-file-name))
11316 (true-file (file-truename file))
11317 (afile (abbreviate-file-name file))
11318 (files (delq nil (mapcar
11319 (lambda (x)
11320 (if (equal true-file
11321 (file-truename x))
11322 nil x))
11323 (org-agenda-files t)))))
11324 (if (not (= (length files) (length (org-agenda-files t))))
11325 (progn
11326 (org-store-new-agenda-file-list files)
11327 (org-install-agenda-files-menu)
11328 (message "Removed file: %s" afile))
11329 (message "File was not in list: %s (not removed)" afile))))
11331 (defun org-file-menu-entry (file)
11332 (vector file (list 'find-file file) t))
11334 (defun org-check-agenda-file (file)
11335 "Make sure FILE exists. If not, ask user what to do."
11336 (when (not (file-exists-p file))
11337 (message "non-existent file %s. [R]emove from list or [A]bort?"
11338 (abbreviate-file-name file))
11339 (let ((r (downcase (read-char-exclusive))))
11340 (cond
11341 ((equal r ?r)
11342 (org-remove-file file)
11343 (throw 'nextfile t))
11344 (t (error "Abort"))))))
11346 (defun org-get-agenda-file-buffer (file)
11347 "Get a buffer visiting FILE. If the buffer needs to be created, add
11348 it to the list of buffers which might be released later."
11349 (let ((buf (org-find-base-buffer-visiting file)))
11350 (if buf
11351 buf ; just return it
11352 ;; Make a new buffer and remember it
11353 (setq buf (find-file-noselect file))
11354 (if buf (push buf org-agenda-new-buffers))
11355 buf)))
11357 (defun org-release-buffers (blist)
11358 "Release all buffers in list, asking the user for confirmation when needed.
11359 When a buffer is unmodified, it is just killed. When modified, it is saved
11360 \(if the user agrees) and then killed."
11361 (let (buf file)
11362 (while (setq buf (pop blist))
11363 (setq file (buffer-file-name buf))
11364 (when (and (buffer-modified-p buf)
11365 file
11366 (y-or-n-p (format "Save file %s? " file)))
11367 (with-current-buffer buf (save-buffer)))
11368 (kill-buffer buf))))
11370 (defun org-prepare-agenda-buffers (files)
11371 "Create buffers for all agenda files, protect archived trees and comments."
11372 (interactive)
11373 (let ((pa '(:org-archived t))
11374 (pc '(:org-comment t))
11375 (pall '(:org-archived t :org-comment t))
11376 (inhibit-read-only t)
11377 (rea (concat ":" org-archive-tag ":"))
11378 bmp file re)
11379 (save-excursion
11380 (save-restriction
11381 (while (setq file (pop files))
11382 (if (bufferp file)
11383 (set-buffer file)
11384 (org-check-agenda-file file)
11385 (set-buffer (org-get-agenda-file-buffer file)))
11386 (widen)
11387 (setq bmp (buffer-modified-p))
11388 (org-refresh-category-properties)
11389 (setq org-todo-keywords-for-agenda
11390 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11391 (setq org-done-keywords-for-agenda
11392 (append org-done-keywords-for-agenda org-done-keywords))
11393 (save-excursion
11394 (remove-text-properties (point-min) (point-max) pall)
11395 (when org-agenda-skip-archived-trees
11396 (goto-char (point-min))
11397 (while (re-search-forward rea nil t)
11398 (if (org-on-heading-p t)
11399 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11400 (goto-char (point-min))
11401 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11402 (while (re-search-forward re nil t)
11403 (add-text-properties
11404 (match-beginning 0) (org-end-of-subtree t) pc)))
11405 (set-buffer-modified-p bmp))))))
11407 ;;;; Embedded LaTeX
11409 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11410 "Keymap for the minor `org-cdlatex-mode'.")
11412 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11413 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11414 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11415 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11416 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11418 (defvar org-cdlatex-texmathp-advice-is-done nil
11419 "Flag remembering if we have applied the advice to texmathp already.")
11421 (define-minor-mode org-cdlatex-mode
11422 "Toggle the minor `org-cdlatex-mode'.
11423 This mode supports entering LaTeX environment and math in LaTeX fragments
11424 in Org-mode.
11425 \\{org-cdlatex-mode-map}"
11426 nil " OCDL" nil
11427 (when org-cdlatex-mode (require 'cdlatex))
11428 (unless org-cdlatex-texmathp-advice-is-done
11429 (setq org-cdlatex-texmathp-advice-is-done t)
11430 (defadvice texmathp (around org-math-always-on activate)
11431 "Always return t in org-mode buffers.
11432 This is because we want to insert math symbols without dollars even outside
11433 the LaTeX math segments. If Orgmode thinks that point is actually inside
11434 en embedded LaTeX fragement, let texmathp do its job.
11435 \\[org-cdlatex-mode-map]"
11436 (interactive)
11437 (let (p)
11438 (cond
11439 ((not (org-mode-p)) ad-do-it)
11440 ((eq this-command 'cdlatex-math-symbol)
11441 (setq ad-return-value t
11442 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11444 (let ((p (org-inside-LaTeX-fragment-p)))
11445 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11446 (setq ad-return-value t
11447 texmathp-why '("Org-mode embedded math" . 0))
11448 (if p ad-do-it)))))))))
11450 (defun turn-on-org-cdlatex ()
11451 "Unconditionally turn on `org-cdlatex-mode'."
11452 (org-cdlatex-mode 1))
11454 (defun org-inside-LaTeX-fragment-p ()
11455 "Test if point is inside a LaTeX fragment.
11456 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11457 sequence appearing also before point.
11458 Even though the matchers for math are configurable, this function assumes
11459 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11460 delimiters are skipped when they have been removed by customization.
11461 The return value is nil, or a cons cell with the delimiter and
11462 and the position of this delimiter.
11464 This function does a reasonably good job, but can locally be fooled by
11465 for example currency specifications. For example it will assume being in
11466 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11467 fragments that are properly closed, but during editing, we have to live
11468 with the uncertainty caused by missing closing delimiters. This function
11469 looks only before point, not after."
11470 (catch 'exit
11471 (let ((pos (point))
11472 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11473 (lim (progn
11474 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11475 (point)))
11476 dd-on str (start 0) m re)
11477 (goto-char pos)
11478 (when dodollar
11479 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11480 re (nth 1 (assoc "$" org-latex-regexps)))
11481 (while (string-match re str start)
11482 (cond
11483 ((= (match-end 0) (length str))
11484 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11485 ((= (match-end 0) (- (length str) 5))
11486 (throw 'exit nil))
11487 (t (setq start (match-end 0))))))
11488 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11489 (goto-char pos)
11490 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11491 (and (match-beginning 2) (throw 'exit nil))
11492 ;; count $$
11493 (while (re-search-backward "\\$\\$" lim t)
11494 (setq dd-on (not dd-on)))
11495 (goto-char pos)
11496 (if dd-on (cons "$$" m))))))
11499 (defun org-try-cdlatex-tab ()
11500 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11501 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11502 - inside a LaTeX fragment, or
11503 - after the first word in a line, where an abbreviation expansion could
11504 insert a LaTeX environment."
11505 (when org-cdlatex-mode
11506 (cond
11507 ((save-excursion
11508 (skip-chars-backward "a-zA-Z0-9*")
11509 (skip-chars-backward " \t")
11510 (bolp))
11511 (cdlatex-tab) t)
11512 ((org-inside-LaTeX-fragment-p)
11513 (cdlatex-tab) t)
11514 (t nil))))
11516 (defun org-cdlatex-underscore-caret (&optional arg)
11517 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11518 Revert to the normal definition outside of these fragments."
11519 (interactive "P")
11520 (if (org-inside-LaTeX-fragment-p)
11521 (call-interactively 'cdlatex-sub-superscript)
11522 (let (org-cdlatex-mode)
11523 (call-interactively (key-binding (vector last-input-event))))))
11525 (defun org-cdlatex-math-modify (&optional arg)
11526 "Execute `cdlatex-math-modify' in LaTeX fragments.
11527 Revert to the normal definition outside of these fragments."
11528 (interactive "P")
11529 (if (org-inside-LaTeX-fragment-p)
11530 (call-interactively 'cdlatex-math-modify)
11531 (let (org-cdlatex-mode)
11532 (call-interactively (key-binding (vector last-input-event))))))
11534 (defvar org-latex-fragment-image-overlays nil
11535 "List of overlays carrying the images of latex fragments.")
11536 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11538 (defun org-remove-latex-fragment-image-overlays ()
11539 "Remove all overlays with LaTeX fragment images in current buffer."
11540 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11541 (setq org-latex-fragment-image-overlays nil))
11543 (defun org-preview-latex-fragment (&optional subtree)
11544 "Preview the LaTeX fragment at point, or all locally or globally.
11545 If the cursor is in a LaTeX fragment, create the image and overlay
11546 it over the source code. If there is no fragment at point, display
11547 all fragments in the current text, from one headline to the next. With
11548 prefix SUBTREE, display all fragments in the current subtree. With a
11549 double prefix `C-u C-u', or when the cursor is before the first headline,
11550 display all fragments in the buffer.
11551 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11552 (interactive "P")
11553 (org-remove-latex-fragment-image-overlays)
11554 (save-excursion
11555 (save-restriction
11556 (let (beg end at msg)
11557 (cond
11558 ((or (equal subtree '(16))
11559 (not (save-excursion
11560 (re-search-backward (concat "^" outline-regexp) nil t))))
11561 (setq beg (point-min) end (point-max)
11562 msg "Creating images for buffer...%s"))
11563 ((equal subtree '(4))
11564 (org-back-to-heading)
11565 (setq beg (point) end (org-end-of-subtree t)
11566 msg "Creating images for subtree...%s"))
11568 (if (setq at (org-inside-LaTeX-fragment-p))
11569 (goto-char (max (point-min) (- (cdr at) 2)))
11570 (org-back-to-heading))
11571 (setq beg (point) end (progn (outline-next-heading) (point))
11572 msg (if at "Creating image...%s"
11573 "Creating images for entry...%s"))))
11574 (message msg "")
11575 (narrow-to-region beg end)
11576 (goto-char beg)
11577 (org-format-latex
11578 (concat "ltxpng/" (file-name-sans-extension
11579 (file-name-nondirectory
11580 buffer-file-name)))
11581 default-directory 'overlays msg at 'forbuffer)
11582 (message msg "done. Use `C-c C-c' to remove images.")))))
11584 (defvar org-latex-regexps
11585 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11586 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11587 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11588 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11589 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11590 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11591 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11592 "Regular expressions for matching embedded LaTeX.")
11594 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11595 "Replace LaTeX fragments with links to an image, and produce images."
11596 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11597 (let* ((prefixnodir (file-name-nondirectory prefix))
11598 (absprefix (expand-file-name prefix dir))
11599 (todir (file-name-directory absprefix))
11600 (opt org-format-latex-options)
11601 (matchers (plist-get opt :matchers))
11602 (re-list org-latex-regexps)
11603 (cnt 0) txt link beg end re e checkdir
11604 m n block linkfile movefile ov)
11605 ;; Check if there are old images files with this prefix, and remove them
11606 (when (file-directory-p todir)
11607 (mapc 'delete-file
11608 (directory-files
11609 todir 'full
11610 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11611 ;; Check the different regular expressions
11612 (while (setq e (pop re-list))
11613 (setq m (car e) re (nth 1 e) n (nth 2 e)
11614 block (if (nth 3 e) "\n\n" ""))
11615 (when (member m matchers)
11616 (goto-char (point-min))
11617 (while (re-search-forward re nil t)
11618 (when (or (not at) (equal (cdr at) (match-beginning n)))
11619 (setq txt (match-string n)
11620 beg (match-beginning n) end (match-end n)
11621 cnt (1+ cnt)
11622 linkfile (format "%s_%04d.png" prefix cnt)
11623 movefile (format "%s_%04d.png" absprefix cnt)
11624 link (concat block "[[file:" linkfile "]]" block))
11625 (if msg (message msg cnt))
11626 (goto-char beg)
11627 (unless checkdir ; make sure the directory exists
11628 (setq checkdir t)
11629 (or (file-directory-p todir) (make-directory todir)))
11630 (org-create-formula-image
11631 txt movefile opt forbuffer)
11632 (if overlays
11633 (progn
11634 (setq ov (org-make-overlay beg end))
11635 (if (featurep 'xemacs)
11636 (progn
11637 (org-overlay-put ov 'invisible t)
11638 (org-overlay-put
11639 ov 'end-glyph
11640 (make-glyph (vector 'png :file movefile))))
11641 (org-overlay-put
11642 ov 'display
11643 (list 'image :type 'png :file movefile :ascent 'center)))
11644 (push ov org-latex-fragment-image-overlays)
11645 (goto-char end))
11646 (delete-region beg end)
11647 (insert link))))))))
11649 ;; This function borrows from Ganesh Swami's latex2png.el
11650 (defun org-create-formula-image (string tofile options buffer)
11651 (let* ((tmpdir (if (featurep 'xemacs)
11652 (temp-directory)
11653 temporary-file-directory))
11654 (texfilebase (make-temp-name
11655 (expand-file-name "orgtex" tmpdir)))
11656 (texfile (concat texfilebase ".tex"))
11657 (dvifile (concat texfilebase ".dvi"))
11658 (pngfile (concat texfilebase ".png"))
11659 (fnh (if (featurep 'xemacs)
11660 (font-height (get-face-font 'default))
11661 (face-attribute 'default :height nil)))
11662 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11663 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11664 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11665 "Black"))
11666 (bg (or (plist-get options (if buffer :background :html-background))
11667 "Transparent")))
11668 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11669 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11670 (with-temp-file texfile
11671 (insert org-format-latex-header
11672 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11673 (let ((dir default-directory))
11674 (condition-case nil
11675 (progn
11676 (cd tmpdir)
11677 (call-process "latex" nil nil nil texfile))
11678 (error nil))
11679 (cd dir))
11680 (if (not (file-exists-p dvifile))
11681 (progn (message "Failed to create dvi file from %s" texfile) nil)
11682 (call-process "dvipng" nil nil nil
11683 "-E" "-fg" fg "-bg" bg
11684 "-D" dpi
11685 ;;"-x" scale "-y" scale
11686 "-T" "tight"
11687 "-o" pngfile
11688 dvifile)
11689 (if (not (file-exists-p pngfile))
11690 (progn (message "Failed to create png file from %s" texfile) nil)
11691 ;; Use the requested file name and clean up
11692 (copy-file pngfile tofile 'replace)
11693 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11694 (delete-file (concat texfilebase e)))
11695 pngfile))))
11697 (defun org-dvipng-color (attr)
11698 "Return an rgb color specification for dvipng."
11699 (apply 'format "rgb %s %s %s"
11700 (mapcar 'org-normalize-color
11701 (color-values (face-attribute 'default attr nil)))))
11703 (defun org-normalize-color (value)
11704 "Return string to be used as color value for an RGB component."
11705 (format "%g" (/ value 65535.0)))
11708 ;;;; Key bindings
11710 ;; Make `C-c C-x' a prefix key
11711 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11713 ;; TAB key with modifiers
11714 (org-defkey org-mode-map "\C-i" 'org-cycle)
11715 (org-defkey org-mode-map [(tab)] 'org-cycle)
11716 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11717 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11718 (org-defkey org-mode-map "\M-\t" 'org-complete)
11719 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11720 ;; The following line is necessary under Suse GNU/Linux
11721 (unless (featurep 'xemacs)
11722 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11723 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11724 (define-key org-mode-map [backtab] 'org-shifttab)
11726 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11727 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11728 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11730 ;; Cursor keys with modifiers
11731 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11732 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11733 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11734 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11736 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11737 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11738 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11739 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11741 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11742 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11743 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11744 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11746 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11747 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11749 ;;; Extra keys for tty access.
11750 ;; We only set them when really needed because otherwise the
11751 ;; menus don't show the simple keys
11753 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11754 (not window-system))
11755 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11756 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11757 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11758 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11759 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11760 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11761 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11762 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11763 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11764 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11765 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11766 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11767 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11768 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11769 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11770 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11771 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11772 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11773 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11774 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11775 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11776 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11778 ;; All the other keys
11780 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11781 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11782 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11783 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11784 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11785 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11786 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11787 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11788 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11789 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11790 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11791 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11792 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11793 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11794 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11795 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11796 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11797 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11798 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11799 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11800 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11801 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11802 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11803 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11804 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11805 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11806 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11807 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11808 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11809 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11810 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11811 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11812 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11813 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11814 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11815 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11816 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11817 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11818 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11819 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11820 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11821 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11822 (org-defkey org-mode-map "\C-c^" 'org-sort)
11823 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11824 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11825 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11826 (org-defkey org-mode-map "\C-m" 'org-return)
11827 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11828 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11829 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11830 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11831 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11832 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11833 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11834 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11835 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11836 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11837 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11838 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11839 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11840 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11841 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11842 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11844 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11845 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11846 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11847 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11849 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11850 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11851 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11852 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11853 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11854 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11855 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11856 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11857 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11858 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11859 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11860 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11862 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11864 (when (featurep 'xemacs)
11865 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11867 (defvar org-table-auto-blank-field) ; defined in org-table.el
11868 (defun org-self-insert-command (N)
11869 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11870 If the cursor is in a table looking at whitespace, the whitespace is
11871 overwritten, and the table is not marked as requiring realignment."
11872 (interactive "p")
11873 (if (and (org-table-p)
11874 (progn
11875 ;; check if we blank the field, and if that triggers align
11876 (and (featurep 'org-table) org-table-auto-blank-field
11877 (member last-command
11878 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11879 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11880 ;; got extra space, this field does not determine column width
11881 (let (org-table-may-need-update) (org-table-blank-field))
11882 ;; no extra space, this field may determine column width
11883 (org-table-blank-field)))
11885 (eq N 1)
11886 (looking-at "[^|\n]* |"))
11887 (let (org-table-may-need-update)
11888 (goto-char (1- (match-end 0)))
11889 (delete-backward-char 1)
11890 (goto-char (match-beginning 0))
11891 (self-insert-command N))
11892 (setq org-table-may-need-update t)
11893 (self-insert-command N)
11894 (org-fix-tags-on-the-fly)))
11896 (defun org-fix-tags-on-the-fly ()
11897 (when (and (equal (char-after (point-at-bol)) ?*)
11898 (org-on-heading-p))
11899 (org-align-tags-here org-tags-column)))
11901 (defun org-delete-backward-char (N)
11902 "Like `delete-backward-char', insert whitespace at field end in tables.
11903 When deleting backwards, in tables this function will insert whitespace in
11904 front of the next \"|\" separator, to keep the table aligned. The table will
11905 still be marked for re-alignment if the field did fill the entire column,
11906 because, in this case the deletion might narrow the column."
11907 (interactive "p")
11908 (if (and (org-table-p)
11909 (eq N 1)
11910 (string-match "|" (buffer-substring (point-at-bol) (point)))
11911 (looking-at ".*?|"))
11912 (let ((pos (point))
11913 (noalign (looking-at "[^|\n\r]* |"))
11914 (c org-table-may-need-update))
11915 (backward-delete-char N)
11916 (skip-chars-forward "^|")
11917 (insert " ")
11918 (goto-char (1- pos))
11919 ;; noalign: if there were two spaces at the end, this field
11920 ;; does not determine the width of the column.
11921 (if noalign (setq org-table-may-need-update c)))
11922 (backward-delete-char N)
11923 (org-fix-tags-on-the-fly)))
11925 (defun org-delete-char (N)
11926 "Like `delete-char', but insert whitespace at field end in tables.
11927 When deleting characters, in tables this function will insert whitespace in
11928 front of the next \"|\" separator, to keep the table aligned. The table will
11929 still be marked for re-alignment if the field did fill the entire column,
11930 because, in this case the deletion might narrow the column."
11931 (interactive "p")
11932 (if (and (org-table-p)
11933 (not (bolp))
11934 (not (= (char-after) ?|))
11935 (eq N 1))
11936 (if (looking-at ".*?|")
11937 (let ((pos (point))
11938 (noalign (looking-at "[^|\n\r]* |"))
11939 (c org-table-may-need-update))
11940 (replace-match (concat
11941 (substring (match-string 0) 1 -1)
11942 " |"))
11943 (goto-char pos)
11944 ;; noalign: if there were two spaces at the end, this field
11945 ;; does not determine the width of the column.
11946 (if noalign (setq org-table-may-need-update c)))
11947 (delete-char N))
11948 (delete-char N)
11949 (org-fix-tags-on-the-fly)))
11951 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11952 (put 'org-self-insert-command 'delete-selection t)
11953 (put 'orgtbl-self-insert-command 'delete-selection t)
11954 (put 'org-delete-char 'delete-selection 'supersede)
11955 (put 'org-delete-backward-char 'delete-selection 'supersede)
11957 ;; Make `flyspell-mode' delay after some commands
11958 (put 'org-self-insert-command 'flyspell-delayed t)
11959 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11960 (put 'org-delete-char 'flyspell-delayed t)
11961 (put 'org-delete-backward-char 'flyspell-delayed t)
11963 ;; Make pabbrev-mode expand after org-mode commands
11964 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11965 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11967 ;; How to do this: Measure non-white length of current string
11968 ;; If equal to column width, we should realign.
11970 (defun org-remap (map &rest commands)
11971 "In MAP, remap the functions given in COMMANDS.
11972 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11973 (let (new old)
11974 (while commands
11975 (setq old (pop commands) new (pop commands))
11976 (if (fboundp 'command-remapping)
11977 (org-defkey map (vector 'remap old) new)
11978 (substitute-key-definition old new map global-map)))))
11980 (when (eq org-enable-table-editor 'optimized)
11981 ;; If the user wants maximum table support, we need to hijack
11982 ;; some standard editing functions
11983 (org-remap org-mode-map
11984 'self-insert-command 'org-self-insert-command
11985 'delete-char 'org-delete-char
11986 'delete-backward-char 'org-delete-backward-char)
11987 (org-defkey org-mode-map "|" 'org-force-self-insert))
11989 (defun org-shiftcursor-error ()
11990 "Throw an error because Shift-Cursor command was applied in wrong context."
11991 (error "This command is active in special context like tables, headlines or timestamps"))
11993 (defun org-shifttab (&optional arg)
11994 "Global visibility cycling or move to previous table field.
11995 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11996 on context.
11997 See the individual commands for more information."
11998 (interactive "P")
11999 (cond
12000 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12001 (arg (message "Content view to level: ")
12002 (org-content (prefix-numeric-value arg))
12003 (setq org-cycle-global-status 'overview))
12004 (t (call-interactively 'org-global-cycle))))
12006 (defun org-shiftmetaleft ()
12007 "Promote subtree or delete table column.
12008 Calls `org-promote-subtree', `org-outdent-item',
12009 or `org-table-delete-column', depending on context.
12010 See the individual commands for more information."
12011 (interactive)
12012 (cond
12013 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12014 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12015 ((org-at-item-p) (call-interactively 'org-outdent-item))
12016 (t (org-shiftcursor-error))))
12018 (defun org-shiftmetaright ()
12019 "Demote subtree or insert table column.
12020 Calls `org-demote-subtree', `org-indent-item',
12021 or `org-table-insert-column', depending on context.
12022 See the individual commands for more information."
12023 (interactive)
12024 (cond
12025 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12026 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12027 ((org-at-item-p) (call-interactively 'org-indent-item))
12028 (t (org-shiftcursor-error))))
12030 (defun org-shiftmetaup (&optional arg)
12031 "Move subtree up or kill table row.
12032 Calls `org-move-subtree-up' or `org-table-kill-row' or
12033 `org-move-item-up' depending on context. See the individual commands
12034 for more information."
12035 (interactive "P")
12036 (cond
12037 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12038 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12039 ((org-at-item-p) (call-interactively 'org-move-item-up))
12040 (t (org-shiftcursor-error))))
12041 (defun org-shiftmetadown (&optional arg)
12042 "Move subtree down or insert table row.
12043 Calls `org-move-subtree-down' or `org-table-insert-row' or
12044 `org-move-item-down', depending on context. See the individual
12045 commands for more information."
12046 (interactive "P")
12047 (cond
12048 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12049 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12050 ((org-at-item-p) (call-interactively 'org-move-item-down))
12051 (t (org-shiftcursor-error))))
12053 (defun org-metaleft (&optional arg)
12054 "Promote heading or move table column to left.
12055 Calls `org-do-promote' or `org-table-move-column', depending on context.
12056 With no specific context, calls the Emacs default `backward-word'.
12057 See the individual commands for more information."
12058 (interactive "P")
12059 (cond
12060 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12061 ((or (org-on-heading-p) (org-region-active-p))
12062 (call-interactively 'org-do-promote))
12063 ((org-at-item-p) (call-interactively 'org-outdent-item))
12064 (t (call-interactively 'backward-word))))
12066 (defun org-metaright (&optional arg)
12067 "Demote subtree or move table column to right.
12068 Calls `org-do-demote' or `org-table-move-column', depending on context.
12069 With no specific context, calls the Emacs default `forward-word'.
12070 See the individual commands for more information."
12071 (interactive "P")
12072 (cond
12073 ((org-at-table-p) (call-interactively 'org-table-move-column))
12074 ((or (org-on-heading-p) (org-region-active-p))
12075 (call-interactively 'org-do-demote))
12076 ((org-at-item-p) (call-interactively 'org-indent-item))
12077 (t (call-interactively 'forward-word))))
12079 (defun org-metaup (&optional arg)
12080 "Move subtree up or move table row up.
12081 Calls `org-move-subtree-up' or `org-table-move-row' or
12082 `org-move-item-up', depending on context. See the individual commands
12083 for more information."
12084 (interactive "P")
12085 (cond
12086 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12087 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12088 ((org-at-item-p) (call-interactively 'org-move-item-up))
12089 (t (transpose-lines 1) (beginning-of-line -1))))
12091 (defun org-metadown (&optional arg)
12092 "Move subtree down or move table row down.
12093 Calls `org-move-subtree-down' or `org-table-move-row' or
12094 `org-move-item-down', depending on context. See the individual
12095 commands for more information."
12096 (interactive "P")
12097 (cond
12098 ((org-at-table-p) (call-interactively 'org-table-move-row))
12099 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12100 ((org-at-item-p) (call-interactively 'org-move-item-down))
12101 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12103 (defun org-shiftup (&optional arg)
12104 "Increase item in timestamp or increase priority of current headline.
12105 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12106 depending on context. See the individual commands for more information."
12107 (interactive "P")
12108 (cond
12109 ((org-at-timestamp-p t)
12110 (call-interactively (if org-edit-timestamp-down-means-later
12111 'org-timestamp-down 'org-timestamp-up)))
12112 ((org-on-heading-p) (call-interactively 'org-priority-up))
12113 ((org-at-item-p) (call-interactively 'org-previous-item))
12114 ((org-clocktable-try-shift 'up arg))
12115 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12117 (defun org-shiftdown (&optional arg)
12118 "Decrease item in timestamp or decrease priority of current headline.
12119 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12120 depending on context. See the individual commands for more information."
12121 (interactive "P")
12122 (cond
12123 ((org-at-timestamp-p t)
12124 (call-interactively (if org-edit-timestamp-down-means-later
12125 'org-timestamp-up 'org-timestamp-down)))
12126 ((org-on-heading-p) (call-interactively 'org-priority-down))
12127 ((org-clocktable-try-shift 'down arg))
12128 (t (call-interactively 'org-next-item))))
12130 (defun org-shiftright (&optional arg)
12131 "Next TODO keyword or timestamp one day later, depending on context."
12132 (interactive "P")
12133 (cond
12134 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12135 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12136 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12137 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12138 ((org-clocktable-try-shift 'right arg))
12139 (t (org-shiftcursor-error))))
12141 (defun org-shiftleft (&optional arg)
12142 "Previous TODO keyword or timestamp one day earlier, depending on context."
12143 (interactive "P")
12144 (cond
12145 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12146 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12147 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12148 ((org-at-property-p)
12149 (call-interactively 'org-property-previous-allowed-value))
12150 ((org-clocktable-try-shift 'left arg))
12151 (t (org-shiftcursor-error))))
12153 (defun org-shiftcontrolright ()
12154 "Switch to next TODO set."
12155 (interactive)
12156 (cond
12157 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12158 (t (org-shiftcursor-error))))
12160 (defun org-shiftcontrolleft ()
12161 "Switch to previous TODO set."
12162 (interactive)
12163 (cond
12164 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12165 (t (org-shiftcursor-error))))
12167 (defun org-ctrl-c-ret ()
12168 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12169 (interactive)
12170 (cond
12171 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12172 (t (call-interactively 'org-insert-heading))))
12174 (defun org-copy-special ()
12175 "Copy region in table or copy current subtree.
12176 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12177 See the individual commands for more information."
12178 (interactive)
12179 (call-interactively
12180 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12182 (defun org-cut-special ()
12183 "Cut region in table or cut current subtree.
12184 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12185 See the individual commands for more information."
12186 (interactive)
12187 (call-interactively
12188 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12190 (defun org-paste-special (arg)
12191 "Paste rectangular region into table, or past subtree relative to level.
12192 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12193 See the individual commands for more information."
12194 (interactive "P")
12195 (if (org-at-table-p)
12196 (org-table-paste-rectangle)
12197 (org-paste-subtree arg)))
12199 (defun org-ctrl-c-ctrl-c (&optional arg)
12200 "Set tags in headline, or update according to changed information at point.
12202 This command does many different things, depending on context:
12204 - If the cursor is in a headline, prompt for tags and insert them
12205 into the current line, aligned to `org-tags-column'. When called
12206 with prefix arg, realign all tags in the current buffer.
12208 - If the cursor is in one of the special #+KEYWORD lines, this
12209 triggers scanning the buffer for these lines and updating the
12210 information.
12212 - If the cursor is inside a table, realign the table. This command
12213 works even if the automatic table editor has been turned off.
12215 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12216 the entire table.
12218 - If the cursor is a the beginning of a dynamic block, update it.
12220 - If the cursor is inside a table created by the table.el package,
12221 activate that table.
12223 - If the current buffer is a remember buffer, close note and file it.
12224 with a prefix argument, file it without further interaction to the default
12225 location.
12227 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12228 links in this buffer.
12230 - If the cursor is on a numbered item in a plain list, renumber the
12231 ordered list.
12233 - If the cursor is on a checkbox, toggle it."
12234 (interactive "P")
12235 (let ((org-enable-table-editor t))
12236 (cond
12237 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12238 org-occur-highlights
12239 org-latex-fragment-image-overlays)
12240 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12241 (org-remove-occur-highlights)
12242 (org-remove-latex-fragment-image-overlays)
12243 (message "Temporary highlights/overlays removed from current buffer"))
12244 ((and (local-variable-p 'org-finish-function (current-buffer))
12245 (fboundp org-finish-function))
12246 (funcall org-finish-function))
12247 ((org-at-property-p)
12248 (call-interactively 'org-property-action))
12249 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12250 ((org-on-heading-p) (call-interactively 'org-set-tags))
12251 ((org-at-table.el-p)
12252 (require 'table)
12253 (beginning-of-line 1)
12254 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12255 (call-interactively 'table-recognize-table))
12256 ((org-at-table-p)
12257 (org-table-maybe-eval-formula)
12258 (if arg
12259 (call-interactively 'org-table-recalculate)
12260 (org-table-maybe-recalculate-line))
12261 (call-interactively 'org-table-align))
12262 ((org-at-item-checkbox-p)
12263 (call-interactively 'org-toggle-checkbox))
12264 ((org-at-item-p)
12265 (call-interactively 'org-maybe-renumber-ordered-list))
12266 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12267 ;; Dynamic block
12268 (beginning-of-line 1)
12269 (org-update-dblock))
12270 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12271 (cond
12272 ((equal (match-string 1) "TBLFM")
12273 ;; Recalculate the table before this line
12274 (save-excursion
12275 (beginning-of-line 1)
12276 (skip-chars-backward " \r\n\t")
12277 (if (org-at-table-p)
12278 (org-call-with-arg 'org-table-recalculate t))))
12280 (call-interactively 'org-mode-restart))))
12281 (t (error "C-c C-c can do nothing useful at this location.")))))
12283 (defun org-mode-restart ()
12284 "Restart Org-mode, to scan again for special lines.
12285 Also updates the keyword regular expressions."
12286 (interactive)
12287 (let ((org-inhibit-startup t)) (org-mode))
12288 (message "Org-mode restarted to refresh keyword and special line setup"))
12290 (defun org-kill-note-or-show-branches ()
12291 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12292 (interactive)
12293 (if (not org-finish-function)
12294 (call-interactively 'show-branches)
12295 (let ((org-note-abort t))
12296 (funcall org-finish-function))))
12298 (defun org-return (&optional indent)
12299 "Goto next table row or insert a newline.
12300 Calls `org-table-next-row' or `newline', depending on context.
12301 See the individual commands for more information."
12302 (interactive)
12303 (cond
12304 ((bobp) (if indent (newline-and-indent) (newline)))
12305 ((and (org-at-heading-p)
12306 (looking-at
12307 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12308 (org-show-entry)
12309 (end-of-line 1)
12310 (newline))
12311 ((org-at-table-p)
12312 (org-table-justify-field-maybe)
12313 (call-interactively 'org-table-next-row))
12314 (t (if indent (newline-and-indent) (newline)))))
12316 (defun org-return-indent ()
12317 "Goto next table row or insert a newline and indent.
12318 Calls `org-table-next-row' or `newline-and-indent', depending on
12319 context. See the individual commands for more information."
12320 (interactive)
12321 (org-return t))
12323 (defun org-ctrl-c-star ()
12324 "Compute table, or change heading status of lines.
12325 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12326 depending on context. This will also turn a plain list item or a normal
12327 line into a subheading."
12328 (interactive)
12329 (cond
12330 ((org-at-table-p)
12331 (call-interactively 'org-table-recalculate))
12332 ((org-region-active-p)
12333 ;; Convert all lines in region to list items
12334 (call-interactively 'org-toggle-region-headings))
12335 ((org-on-heading-p)
12336 (org-toggle-region-headings (point-at-bol)
12337 (min (1+ (point-at-eol)) (point-max))))
12338 ((org-at-item-p)
12339 ;; Convert to heading
12340 (let ((level (save-match-data
12341 (save-excursion
12342 (condition-case nil
12343 (progn
12344 (org-back-to-heading t)
12345 (funcall outline-level))
12346 (error 0))))))
12347 (replace-match
12348 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12349 (t (org-toggle-region-headings (point-at-bol)
12350 (min (1+ (point-at-eol)) (point-max))))))
12352 (defun org-ctrl-c-minus ()
12353 "Insert separator line in table or modify bullet status of line.
12354 Also turns a plain line or a region of lines into list items.
12355 Calls `org-table-insert-hline', `org-toggle-region-items', or
12356 `org-cycle-list-bullet', depending on context."
12357 (interactive)
12358 (cond
12359 ((org-at-table-p)
12360 (call-interactively 'org-table-insert-hline))
12361 ((org-on-heading-p)
12362 ;; Convert to item
12363 (save-excursion
12364 (beginning-of-line 1)
12365 (if (looking-at "\\*+ ")
12366 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12367 ((org-region-active-p)
12368 ;; Convert all lines in region to list items
12369 (call-interactively 'org-toggle-region-items))
12370 ((org-in-item-p)
12371 (call-interactively 'org-cycle-list-bullet))
12372 (t (org-toggle-region-items (point-at-bol)
12373 (min (1+ (point-at-eol)) (point-max))))))
12375 (defun org-toggle-region-items (beg end)
12376 "Convert all lines in region to list items.
12377 If the first line is already an item, convert all list items in the region
12378 to normal lines."
12379 (interactive "r")
12380 (let (l2 l)
12381 (save-excursion
12382 (goto-char end)
12383 (setq l2 (org-current-line))
12384 (goto-char beg)
12385 (beginning-of-line 1)
12386 (setq l (1- (org-current-line)))
12387 (if (org-at-item-p)
12388 ;; We already have items, de-itemize
12389 (while (< (setq l (1+ l)) l2)
12390 (when (org-at-item-p)
12391 (goto-char (match-beginning 2))
12392 (delete-region (match-beginning 2) (match-end 2))
12393 (and (looking-at "[ \t]+") (replace-match "")))
12394 (beginning-of-line 2))
12395 (while (< (setq l (1+ l)) l2)
12396 (unless (org-at-item-p)
12397 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12398 (replace-match "\\1- \\2")))
12399 (beginning-of-line 2))))))
12401 (defun org-toggle-region-headings (beg end)
12402 "Convert all lines in region to list items.
12403 If the first line is already an item, convert all list items in the region
12404 to normal lines."
12405 (interactive "r")
12406 (let (l2 l)
12407 (save-excursion
12408 (goto-char end)
12409 (setq l2 (org-current-line))
12410 (goto-char beg)
12411 (beginning-of-line 1)
12412 (setq l (1- (org-current-line)))
12413 (if (org-on-heading-p)
12414 ;; We already have headlines, de-star them
12415 (while (< (setq l (1+ l)) l2)
12416 (when (org-on-heading-p t)
12417 (and (looking-at outline-regexp) (replace-match "")))
12418 (beginning-of-line 2))
12419 (let* ((stars (save-excursion
12420 (re-search-backward org-complex-heading-regexp nil t)
12421 (or (match-string 1) "*")))
12422 (add-stars (if org-odd-levels-only "**" "*"))
12423 (rpl (concat stars add-stars " \\2")))
12424 (while (< (setq l (1+ l)) l2)
12425 (unless (org-on-heading-p)
12426 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12427 (replace-match rpl)))
12428 (beginning-of-line 2)))))))
12430 (defun org-meta-return (&optional arg)
12431 "Insert a new heading or wrap a region in a table.
12432 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12433 See the individual commands for more information."
12434 (interactive "P")
12435 (cond
12436 ((org-at-table-p)
12437 (call-interactively 'org-table-wrap-region))
12438 (t (call-interactively 'org-insert-heading))))
12440 ;;; Menu entries
12442 ;; Define the Org-mode menus
12443 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12444 '("Tbl"
12445 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12446 ["Next Field" org-cycle (org-at-table-p)]
12447 ["Previous Field" org-shifttab (org-at-table-p)]
12448 ["Next Row" org-return (org-at-table-p)]
12449 "--"
12450 ["Blank Field" org-table-blank-field (org-at-table-p)]
12451 ["Edit Field" org-table-edit-field (org-at-table-p)]
12452 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12453 "--"
12454 ("Column"
12455 ["Move Column Left" org-metaleft (org-at-table-p)]
12456 ["Move Column Right" org-metaright (org-at-table-p)]
12457 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12458 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12459 ("Row"
12460 ["Move Row Up" org-metaup (org-at-table-p)]
12461 ["Move Row Down" org-metadown (org-at-table-p)]
12462 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12463 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12464 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12465 "--"
12466 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12467 ("Rectangle"
12468 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12469 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12470 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12471 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12472 "--"
12473 ("Calculate"
12474 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12475 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12476 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12477 "--"
12478 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12479 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12480 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12481 "--"
12482 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12483 "--"
12484 ["Sum Column/Rectangle" org-table-sum
12485 (or (org-at-table-p) (org-region-active-p))]
12486 ["Which Column?" org-table-current-column (org-at-table-p)])
12487 ["Debug Formulas"
12488 org-table-toggle-formula-debugger
12489 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12490 ["Show Col/Row Numbers"
12491 org-table-toggle-coordinate-overlays
12492 :style toggle
12493 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12494 "--"
12495 ["Create" org-table-create (and (not (org-at-table-p))
12496 org-enable-table-editor)]
12497 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12498 ["Import from File" org-table-import (not (org-at-table-p))]
12499 ["Export to File" org-table-export (org-at-table-p)]
12500 "--"
12501 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12503 (easy-menu-define org-org-menu org-mode-map "Org menu"
12504 '("Org"
12505 ("Show/Hide"
12506 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12507 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12508 ["Sparse Tree..." org-sparse-tree t]
12509 ["Reveal Context" org-reveal t]
12510 ["Show All" show-all t]
12511 "--"
12512 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12513 "--"
12514 ["New Heading" org-insert-heading t]
12515 ("Navigate Headings"
12516 ["Up" outline-up-heading t]
12517 ["Next" outline-next-visible-heading t]
12518 ["Previous" outline-previous-visible-heading t]
12519 ["Next Same Level" outline-forward-same-level t]
12520 ["Previous Same Level" outline-backward-same-level t]
12521 "--"
12522 ["Jump" org-goto t])
12523 ("Edit Structure"
12524 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12525 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12526 "--"
12527 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12528 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12529 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12530 "--"
12531 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12532 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12533 ["Demote Heading" org-metaright (not (org-at-table-p))]
12534 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12535 "--"
12536 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12537 "--"
12538 ["Convert to odd levels" org-convert-to-odd-levels t]
12539 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12540 ("Editing"
12541 ["Emphasis..." org-emphasize t])
12542 ("Archive"
12543 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12544 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12545 ; :active t :keys "C-u C-c C-x C-a"]
12546 ["Sparse trees open ARCHIVE trees"
12547 (setq org-sparse-tree-open-archived-trees
12548 (not org-sparse-tree-open-archived-trees))
12549 :style toggle :selected org-sparse-tree-open-archived-trees]
12550 ["Cycling opens ARCHIVE trees"
12551 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12552 :style toggle :selected org-cycle-open-archived-trees]
12553 ["Agenda includes ARCHIVE trees"
12554 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12555 :style toggle :selected (not org-agenda-skip-archived-trees)]
12556 "--"
12557 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12558 ; ["Check and Move Children" (org-archive-subtree '(4))
12559 ; :active t :keys "C-u C-c C-x C-s"]
12561 "--"
12562 ("TODO Lists"
12563 ["TODO/DONE/-" org-todo t]
12564 ("Select keyword"
12565 ["Next keyword" org-shiftright (org-on-heading-p)]
12566 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12567 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12568 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12569 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12570 ["Show TODO Tree" org-show-todo-tree t]
12571 ["Global TODO list" org-todo-list t]
12572 "--"
12573 ["Set Priority" org-priority t]
12574 ["Priority Up" org-shiftup t]
12575 ["Priority Down" org-shiftdown t])
12576 ("TAGS and Properties"
12577 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12578 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12579 "--"
12580 ["Set property" 'org-set-property t]
12581 ["Column view of properties" org-columns t]
12582 ["Insert Column View DBlock" org-insert-columns-dblock t])
12583 ("Dates and Scheduling"
12584 ["Timestamp" org-time-stamp t]
12585 ["Timestamp (inactive)" org-time-stamp-inactive t]
12586 ("Change Date"
12587 ["1 Day Later" org-shiftright t]
12588 ["1 Day Earlier" org-shiftleft t]
12589 ["1 ... Later" org-shiftup t]
12590 ["1 ... Earlier" org-shiftdown t])
12591 ["Compute Time Range" org-evaluate-time-range t]
12592 ["Schedule Item" org-schedule t]
12593 ["Deadline" org-deadline t]
12594 "--"
12595 ["Custom time format" org-toggle-time-stamp-overlays
12596 :style radio :selected org-display-custom-times]
12597 "--"
12598 ["Goto Calendar" org-goto-calendar t]
12599 ["Date from Calendar" org-date-from-calendar t])
12600 ("Logging work"
12601 ["Clock in" org-clock-in t]
12602 ["Clock out" org-clock-out t]
12603 ["Clock cancel" org-clock-cancel t]
12604 ["Goto running clock" org-clock-goto t]
12605 ["Display times" org-clock-display t]
12606 ["Create clock table" org-clock-report t]
12607 "--"
12608 ["Record DONE time"
12609 (progn (setq org-log-done (not org-log-done))
12610 (message "Switching to %s will %s record a timestamp"
12611 (car org-done-keywords)
12612 (if org-log-done "automatically" "not")))
12613 :style toggle :selected org-log-done])
12614 "--"
12615 ["Agenda Command..." org-agenda t]
12616 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12617 ("File List for Agenda")
12618 ("Special views current file"
12619 ["TODO Tree" org-show-todo-tree t]
12620 ["Check Deadlines" org-check-deadlines t]
12621 ["Timeline" org-timeline t]
12622 ["Tags Tree" org-tags-sparse-tree t])
12623 "--"
12624 ("Hyperlinks"
12625 ["Store Link (Global)" org-store-link t]
12626 ["Insert Link" org-insert-link t]
12627 ["Follow Link" org-open-at-point t]
12628 "--"
12629 ["Next link" org-next-link t]
12630 ["Previous link" org-previous-link t]
12631 "--"
12632 ["Descriptive Links"
12633 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12634 :style radio
12635 :selected (member '(org-link) buffer-invisibility-spec)]
12636 ["Literal Links"
12637 (progn
12638 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12639 :style radio
12640 :selected (not (member '(org-link) buffer-invisibility-spec))])
12641 "--"
12642 ["Export/Publish..." org-export t]
12643 ("LaTeX"
12644 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12645 :selected org-cdlatex-mode]
12646 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12647 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12648 ["Modify math symbol" org-cdlatex-math-modify
12649 (org-inside-LaTeX-fragment-p)]
12650 ["Export LaTeX fragments as images"
12651 (if (featurep 'org-exp)
12652 (setq org-export-with-LaTeX-fragments
12653 (not org-export-with-LaTeX-fragments))
12654 (require 'org-exp))
12655 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12656 org-export-with-LaTeX-fragments)])
12657 "--"
12658 ("Documentation"
12659 ["Show Version" org-version t]
12660 ["Info Documentation" org-info t])
12661 ("Customize"
12662 ["Browse Org Group" org-customize t]
12663 "--"
12664 ["Expand This Menu" org-create-customize-menu
12665 (fboundp 'customize-menu-create)])
12666 "--"
12667 ["Refresh setup" org-mode-restart t]
12670 (defun org-info (&optional node)
12671 "Read documentation for Org-mode in the info system.
12672 With optional NODE, go directly to that node."
12673 (interactive)
12674 (info (format "(org)%s" (or node ""))))
12676 (defun org-install-agenda-files-menu ()
12677 (let ((bl (buffer-list)))
12678 (save-excursion
12679 (while bl
12680 (set-buffer (pop bl))
12681 (if (org-mode-p) (setq bl nil)))
12682 (when (org-mode-p)
12683 (easy-menu-change
12684 '("Org") "File List for Agenda"
12685 (append
12686 (list
12687 ["Edit File List" (org-edit-agenda-file-list) t]
12688 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12689 ["Remove Current File from List" org-remove-file t]
12690 ["Cycle through agenda files" org-cycle-agenda-files t]
12691 ["Occur in all agenda files" org-occur-in-agenda-files t]
12692 "--")
12693 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12695 ;;;; Documentation
12697 (defun org-require-autoloaded-modules ()
12698 (interactive)
12699 (mapc 'require
12700 '(org-agenda org-archive org-clock org-colview
12701 org-exp org-export-latex org-publish
12702 org-remember org-table)))
12704 (defun org-customize ()
12705 "Call the customize function with org as argument."
12706 (interactive)
12707 (org-load-modules-maybe)
12708 (org-require-autoloaded-modules)
12709 (customize-browse 'org))
12711 (defun org-create-customize-menu ()
12712 "Create a full customization menu for Org-mode, insert it into the menu."
12713 (interactive)
12714 (org-load-modules-maybe)
12715 (org-require-autoloaded-modules)
12716 (if (fboundp 'customize-menu-create)
12717 (progn
12718 (easy-menu-change
12719 '("Org") "Customize"
12720 `(["Browse Org group" org-customize t]
12721 "--"
12722 ,(customize-menu-create 'org)
12723 ["Set" Custom-set t]
12724 ["Save" Custom-save t]
12725 ["Reset to Current" Custom-reset-current t]
12726 ["Reset to Saved" Custom-reset-saved t]
12727 ["Reset to Standard Settings" Custom-reset-standard t]))
12728 (message "\"Org\"-menu now contains full customization menu"))
12729 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12731 ;;;; Miscellaneous stuff
12733 ;;; Generally useful functions
12735 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12736 "Display the given MESSAGE as a warning."
12737 (if (fboundp 'display-warning)
12738 (display-warning 'org message
12739 (if (featurep 'xemacs)
12740 'warning
12741 :warning))
12742 (let ((buf (get-buffer-create "*Org warnings*")))
12743 (with-current-buffer buf
12744 (goto-char (point-max))
12745 (insert "Warning (Org): " message)
12746 (unless (bolp)
12747 (newline)))
12748 (display-buffer buf)
12749 (sit-for 0))))
12751 (defun org-plist-delete (plist property)
12752 "Delete PROPERTY from PLIST.
12753 This is in contrast to merely setting it to 0."
12754 (let (p)
12755 (while plist
12756 (if (not (eq property (car plist)))
12757 (setq p (plist-put p (car plist) (nth 1 plist))))
12758 (setq plist (cddr plist)))
12761 (defun org-force-self-insert (N)
12762 "Needed to enforce self-insert under remapping."
12763 (interactive "p")
12764 (self-insert-command N))
12766 (defun org-string-width (s)
12767 "Compute width of string, ignoring invisible characters.
12768 This ignores character with invisibility property `org-link', and also
12769 characters with property `org-cwidth', because these will become invisible
12770 upon the next fontification round."
12771 (let (b l)
12772 (when (or (eq t buffer-invisibility-spec)
12773 (assq 'org-link buffer-invisibility-spec))
12774 (while (setq b (text-property-any 0 (length s)
12775 'invisible 'org-link s))
12776 (setq s (concat (substring s 0 b)
12777 (substring s (or (next-single-property-change
12778 b 'invisible s) (length s)))))))
12779 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12780 (setq s (concat (substring s 0 b)
12781 (substring s (or (next-single-property-change
12782 b 'org-cwidth s) (length s))))))
12783 (setq l (string-width s) b -1)
12784 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12785 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12788 (defun org-base-buffer (buffer)
12789 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12790 (if (not buffer)
12791 buffer
12792 (or (buffer-base-buffer buffer)
12793 buffer)))
12795 (defun org-trim (s)
12796 "Remove whitespace at beginning and end of string."
12797 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12798 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12801 (defun org-wrap (string &optional width lines)
12802 "Wrap string to either a number of lines, or a width in characters.
12803 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12804 that costs. If there is a word longer than WIDTH, the text is actually
12805 wrapped to the length of that word.
12806 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12807 many lines, whatever width that takes.
12808 The return value is a list of lines, without newlines at the end."
12809 (let* ((words (org-split-string string "[ \t\n]+"))
12810 (maxword (apply 'max (mapcar 'org-string-width words)))
12811 w ll)
12812 (cond (width
12813 (org-do-wrap words (max maxword width)))
12814 (lines
12815 (setq w maxword)
12816 (setq ll (org-do-wrap words maxword))
12817 (if (<= (length ll) lines)
12819 (setq ll words)
12820 (while (> (length ll) lines)
12821 (setq w (1+ w))
12822 (setq ll (org-do-wrap words w)))
12823 ll))
12824 (t (error "Cannot wrap this")))))
12826 (defun org-do-wrap (words width)
12827 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12828 (let (lines line)
12829 (while words
12830 (setq line (pop words))
12831 (while (and words (< (+ (length line) (length (car words))) width))
12832 (setq line (concat line " " (pop words))))
12833 (setq lines (push line lines)))
12834 (nreverse lines)))
12836 (defun org-split-string (string &optional separators)
12837 "Splits STRING into substrings at SEPARATORS.
12838 No empty strings are returned if there are matches at the beginning
12839 and end of string."
12840 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12841 (start 0)
12842 notfirst
12843 (list nil))
12844 (while (and (string-match rexp string
12845 (if (and notfirst
12846 (= start (match-beginning 0))
12847 (< start (length string)))
12848 (1+ start) start))
12849 (< (match-beginning 0) (length string)))
12850 (setq notfirst t)
12851 (or (eq (match-beginning 0) 0)
12852 (and (eq (match-beginning 0) (match-end 0))
12853 (eq (match-beginning 0) start))
12854 (setq list
12855 (cons (substring string start (match-beginning 0))
12856 list)))
12857 (setq start (match-end 0)))
12858 (or (eq start (length string))
12859 (setq list
12860 (cons (substring string start)
12861 list)))
12862 (nreverse list)))
12864 (defun org-context ()
12865 "Return a list of contexts of the current cursor position.
12866 If several contexts apply, all are returned.
12867 Each context entry is a list with a symbol naming the context, and
12868 two positions indicating start and end of the context. Possible
12869 contexts are:
12871 :headline anywhere in a headline
12872 :headline-stars on the leading stars in a headline
12873 :todo-keyword on a TODO keyword (including DONE) in a headline
12874 :tags on the TAGS in a headline
12875 :priority on the priority cookie in a headline
12876 :item on the first line of a plain list item
12877 :item-bullet on the bullet/number of a plain list item
12878 :checkbox on the checkbox in a plain list item
12879 :table in an org-mode table
12880 :table-special on a special filed in a table
12881 :table-table in a table.el table
12882 :link on a hyperlink
12883 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12884 :target on a <<target>>
12885 :radio-target on a <<<radio-target>>>
12886 :latex-fragment on a LaTeX fragment
12887 :latex-preview on a LaTeX fragment with overlayed preview image
12889 This function expects the position to be visible because it uses font-lock
12890 faces as a help to recognize the following contexts: :table-special, :link,
12891 and :keyword."
12892 (let* ((f (get-text-property (point) 'face))
12893 (faces (if (listp f) f (list f)))
12894 (p (point)) clist o)
12895 ;; First the large context
12896 (cond
12897 ((org-on-heading-p t)
12898 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12899 (when (progn
12900 (beginning-of-line 1)
12901 (looking-at org-todo-line-tags-regexp))
12902 (push (org-point-in-group p 1 :headline-stars) clist)
12903 (push (org-point-in-group p 2 :todo-keyword) clist)
12904 (push (org-point-in-group p 4 :tags) clist))
12905 (goto-char p)
12906 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12907 (if (looking-at "\\[#[A-Z0-9]\\]")
12908 (push (org-point-in-group p 0 :priority) clist)))
12910 ((org-at-item-p)
12911 (push (org-point-in-group p 2 :item-bullet) clist)
12912 (push (list :item (point-at-bol)
12913 (save-excursion (org-end-of-item) (point)))
12914 clist)
12915 (and (org-at-item-checkbox-p)
12916 (push (org-point-in-group p 0 :checkbox) clist)))
12918 ((org-at-table-p)
12919 (push (list :table (org-table-begin) (org-table-end)) clist)
12920 (if (memq 'org-formula faces)
12921 (push (list :table-special
12922 (previous-single-property-change p 'face)
12923 (next-single-property-change p 'face)) clist)))
12924 ((org-at-table-p 'any)
12925 (push (list :table-table) clist)))
12926 (goto-char p)
12928 ;; Now the small context
12929 (cond
12930 ((org-at-timestamp-p)
12931 (push (org-point-in-group p 0 :timestamp) clist))
12932 ((memq 'org-link faces)
12933 (push (list :link
12934 (previous-single-property-change p 'face)
12935 (next-single-property-change p 'face)) clist))
12936 ((memq 'org-special-keyword faces)
12937 (push (list :keyword
12938 (previous-single-property-change p 'face)
12939 (next-single-property-change p 'face)) clist))
12940 ((org-on-target-p)
12941 (push (org-point-in-group p 0 :target) clist)
12942 (goto-char (1- (match-beginning 0)))
12943 (if (looking-at org-radio-target-regexp)
12944 (push (org-point-in-group p 0 :radio-target) clist))
12945 (goto-char p))
12946 ((setq o (car (delq nil
12947 (mapcar
12948 (lambda (x)
12949 (if (memq x org-latex-fragment-image-overlays) x))
12950 (org-overlays-at (point))))))
12951 (push (list :latex-fragment
12952 (org-overlay-start o) (org-overlay-end o)) clist)
12953 (push (list :latex-preview
12954 (org-overlay-start o) (org-overlay-end o)) clist))
12955 ((org-inside-LaTeX-fragment-p)
12956 ;; FIXME: positions wrong.
12957 (push (list :latex-fragment (point) (point)) clist)))
12959 (setq clist (nreverse (delq nil clist)))
12960 clist))
12962 ;; FIXME: Compare with at-regexp-p Do we need both?
12963 (defun org-in-regexp (re &optional nlines visually)
12964 "Check if point is inside a match of regexp.
12965 Normally only the current line is checked, but you can include NLINES extra
12966 lines both before and after point into the search.
12967 If VISUALLY is set, require that the cursor is not after the match but
12968 really on, so that the block visually is on the match."
12969 (catch 'exit
12970 (let ((pos (point))
12971 (eol (point-at-eol (+ 1 (or nlines 0))))
12972 (inc (if visually 1 0)))
12973 (save-excursion
12974 (beginning-of-line (- 1 (or nlines 0)))
12975 (while (re-search-forward re eol t)
12976 (if (and (<= (match-beginning 0) pos)
12977 (>= (+ inc (match-end 0)) pos))
12978 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12980 (defun org-at-regexp-p (regexp)
12981 "Is point inside a match of REGEXP in the current line?"
12982 (catch 'exit
12983 (save-excursion
12984 (let ((pos (point)) (end (point-at-eol)))
12985 (beginning-of-line 1)
12986 (while (re-search-forward regexp end t)
12987 (if (and (<= (match-beginning 0) pos)
12988 (>= (match-end 0) pos))
12989 (throw 'exit t)))
12990 nil))))
12992 (defun org-occur-in-agenda-files (regexp &optional nlines)
12993 "Call `multi-occur' with buffers for all agenda files."
12994 (interactive "sOrg-files matching: \np")
12995 (let* ((files (org-agenda-files))
12996 (tnames (mapcar 'file-truename files))
12997 (extra org-agenda-text-search-extra-files)
12999 (when (eq (car extra) 'agenda-archives)
13000 (setq extra (cdr extra))
13001 (setq files (org-add-archive-files files)))
13002 (while (setq f (pop extra))
13003 (unless (member (file-truename f) tnames)
13004 (add-to-list 'files f 'append)
13005 (add-to-list 'tnames (file-truename f) 'append)))
13006 (multi-occur
13007 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13008 regexp)))
13010 (if (boundp 'occur-mode-find-occurrence-hook)
13011 ;; Emacs 23
13012 (add-hook 'occur-mode-find-occurrence-hook
13013 (lambda ()
13014 (when (org-mode-p)
13015 (org-reveal))))
13016 ;; Emacs 22
13017 (defadvice occur-mode-goto-occurrence
13018 (after org-occur-reveal activate)
13019 (and (org-mode-p) (org-reveal)))
13020 (defadvice occur-mode-goto-occurrence-other-window
13021 (after org-occur-reveal activate)
13022 (and (org-mode-p) (org-reveal)))
13023 (defadvice occur-mode-display-occurrence
13024 (after org-occur-reveal activate)
13025 (when (org-mode-p)
13026 (let ((pos (occur-mode-find-occurrence)))
13027 (with-current-buffer (marker-buffer pos)
13028 (save-excursion
13029 (goto-char pos)
13030 (org-reveal)))))))
13032 (defun org-uniquify (list)
13033 "Remove duplicate elements from LIST."
13034 (let (res)
13035 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13036 res))
13038 (defun org-delete-all (elts list)
13039 "Remove all elements in ELTS from LIST."
13040 (while elts
13041 (setq list (delete (pop elts) list)))
13042 list)
13044 (defun org-back-over-empty-lines ()
13045 "Move backwards over witespace, to the beginning of the first empty line.
13046 Returns the number of empty lines passed."
13047 (let ((pos (point)))
13048 (skip-chars-backward " \t\n\r")
13049 (beginning-of-line 2)
13050 (goto-char (min (point) pos))
13051 (count-lines (point) pos)))
13053 (defun org-skip-whitespace ()
13054 (skip-chars-forward " \t\n\r"))
13056 (defun org-point-in-group (point group &optional context)
13057 "Check if POINT is in match-group GROUP.
13058 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13059 match. If the match group does ot exist or point is not inside it,
13060 return nil."
13061 (and (match-beginning group)
13062 (>= point (match-beginning group))
13063 (<= point (match-end group))
13064 (if context
13065 (list context (match-beginning group) (match-end group))
13066 t)))
13068 (defun org-switch-to-buffer-other-window (&rest args)
13069 "Switch to buffer in a second window on the current frame.
13070 In particular, do not allow pop-up frames."
13071 (let (pop-up-frames special-display-buffer-names special-display-regexps
13072 special-display-function)
13073 (apply 'switch-to-buffer-other-window args)))
13075 (defun org-combine-plists (&rest plists)
13076 "Create a single property list from all plists in PLISTS.
13077 The process starts by copying the first list, and then setting properties
13078 from the other lists. Settings in the last list are the most significant
13079 ones and overrule settings in the other lists."
13080 (let ((rtn (copy-sequence (pop plists)))
13081 p v ls)
13082 (while plists
13083 (setq ls (pop plists))
13084 (while ls
13085 (setq p (pop ls) v (pop ls))
13086 (setq rtn (plist-put rtn p v))))
13087 rtn))
13089 (defun org-move-line-down (arg)
13090 "Move the current line down. With prefix argument, move it past ARG lines."
13091 (interactive "p")
13092 (let ((col (current-column))
13093 beg end pos)
13094 (beginning-of-line 1) (setq beg (point))
13095 (beginning-of-line 2) (setq end (point))
13096 (beginning-of-line (+ 1 arg))
13097 (setq pos (move-marker (make-marker) (point)))
13098 (insert (delete-and-extract-region beg end))
13099 (goto-char pos)
13100 (org-move-to-column col)))
13102 (defun org-move-line-up (arg)
13103 "Move the current line up. With prefix argument, move it past ARG lines."
13104 (interactive "p")
13105 (let ((col (current-column))
13106 beg end pos)
13107 (beginning-of-line 1) (setq beg (point))
13108 (beginning-of-line 2) (setq end (point))
13109 (beginning-of-line (- arg))
13110 (setq pos (move-marker (make-marker) (point)))
13111 (insert (delete-and-extract-region beg end))
13112 (goto-char pos)
13113 (org-move-to-column col)))
13115 (defun org-replace-escapes (string table)
13116 "Replace %-escapes in STRING with values in TABLE.
13117 TABLE is an association list with keys like \"%a\" and string values.
13118 The sequences in STRING may contain normal field width and padding information,
13119 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13120 so values can contain further %-escapes if they are define later in TABLE."
13121 (let ((case-fold-search nil)
13122 e re rpl)
13123 (while (setq e (pop table))
13124 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13125 (while (string-match re string)
13126 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13127 (cdr e)))
13128 (setq string (replace-match rpl t t string))))
13129 string))
13132 (defun org-sublist (list start end)
13133 "Return a section of LIST, from START to END.
13134 Counting starts at 1."
13135 (let (rtn (c start))
13136 (setq list (nthcdr (1- start) list))
13137 (while (and list (<= c end))
13138 (push (pop list) rtn)
13139 (setq c (1+ c)))
13140 (nreverse rtn)))
13142 (defun org-find-base-buffer-visiting (file)
13143 "Like `find-buffer-visiting' but alway return the base buffer and
13144 not an indirect buffer."
13145 (let ((buf (find-buffer-visiting file)))
13146 (if buf
13147 (or (buffer-base-buffer buf) buf)
13148 nil)))
13150 (defun org-image-file-name-regexp ()
13151 "Return regexp matching the file names of images."
13152 (if (fboundp 'image-file-name-regexp)
13153 (image-file-name-regexp)
13154 (let ((image-file-name-extensions
13155 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13156 "xbm" "xpm" "pbm" "pgm" "ppm")))
13157 (concat "\\."
13158 (regexp-opt (nconc (mapcar 'upcase
13159 image-file-name-extensions)
13160 image-file-name-extensions)
13162 "\\'"))))
13164 (defun org-file-image-p (file)
13165 "Return non-nil if FILE is an image."
13166 (save-match-data
13167 (string-match (org-image-file-name-regexp) file)))
13169 ;;; Paragraph filling stuff.
13170 ;; We want this to be just right, so use the full arsenal.
13172 (defun org-indent-line-function ()
13173 "Indent line like previous, but further if previous was headline or item."
13174 (interactive)
13175 (let* ((pos (point))
13176 (itemp (org-at-item-p))
13177 column bpos bcol tpos tcol bullet btype bullet-type)
13178 ;; Find the previous relevant line
13179 (beginning-of-line 1)
13180 (cond
13181 ((looking-at "#") (setq column 0))
13182 ((looking-at "\\*+ ") (setq column 0))
13184 (beginning-of-line 0)
13185 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13186 (beginning-of-line 0))
13187 (cond
13188 ((looking-at "\\*+[ \t]+")
13189 (goto-char (match-end 0))
13190 (setq column (current-column)))
13191 ((org-in-item-p)
13192 (org-beginning-of-item)
13193 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13194 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13195 (setq bpos (match-beginning 1) tpos (match-end 0)
13196 bcol (progn (goto-char bpos) (current-column))
13197 tcol (progn (goto-char tpos) (current-column))
13198 bullet (match-string 1)
13199 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13200 (if (not itemp)
13201 (setq column tcol)
13202 (goto-char pos)
13203 (beginning-of-line 1)
13204 (if (looking-at "\\S-")
13205 (progn
13206 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13207 (setq bullet (match-string 1)
13208 btype (if (string-match "[0-9]" bullet) "n" bullet))
13209 (setq column (if (equal btype bullet-type) bcol tcol)))
13210 (setq column (org-get-indentation)))))
13211 (t (setq column (org-get-indentation))))))
13212 (goto-char pos)
13213 (if (<= (current-column) (current-indentation))
13214 (org-indent-line-to column)
13215 (save-excursion (org-indent-line-to column)))
13216 (setq column (current-column))
13217 (beginning-of-line 1)
13218 (if (looking-at
13219 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13220 (replace-match (concat "\\1" (format org-property-format
13221 (match-string 2) (match-string 3)))
13222 t nil))
13223 (org-move-to-column column)))
13225 (defun org-set-autofill-regexps ()
13226 (interactive)
13227 ;; In the paragraph separator we include headlines, because filling
13228 ;; text in a line directly attached to a headline would otherwise
13229 ;; fill the headline as well.
13230 (org-set-local 'comment-start-skip "^#+[ \t]*")
13231 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13232 ;; The paragraph starter includes hand-formatted lists.
13233 (org-set-local 'paragraph-start
13234 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13235 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13236 ;; But only if the user has not turned off tables or fixed-width regions
13237 (org-set-local
13238 'auto-fill-inhibit-regexp
13239 (concat "\\*+ \\|#\\+"
13240 "\\|[ \t]*" org-keyword-time-regexp
13241 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13242 (concat
13243 "\\|[ \t]*["
13244 (if org-enable-table-editor "|" "")
13245 (if org-enable-fixed-width-editor ":" "")
13246 "]"))))
13247 ;; We use our own fill-paragraph function, to make sure that tables
13248 ;; and fixed-width regions are not wrapped. That function will pass
13249 ;; through to `fill-paragraph' when appropriate.
13250 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13251 ; Adaptive filling: To get full control, first make sure that
13252 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13253 (org-set-local 'adaptive-fill-regexp "\000")
13254 (org-set-local 'adaptive-fill-function
13255 'org-adaptive-fill-function)
13256 (org-set-local
13257 'align-mode-rules-list
13258 '((org-in-buffer-settings
13259 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13260 (modes . '(org-mode))))))
13262 (defun org-fill-paragraph (&optional justify)
13263 "Re-align a table, pass through to fill-paragraph if no table."
13264 (let ((table-p (org-at-table-p))
13265 (table.el-p (org-at-table.el-p)))
13266 (cond ((and (equal (char-after (point-at-bol)) ?*)
13267 (save-excursion (goto-char (point-at-bol))
13268 (looking-at outline-regexp)))
13269 t) ; skip headlines
13270 (table.el-p t) ; skip table.el tables
13271 (table-p (org-table-align) t) ; align org-mode tables
13272 (t nil)))) ; call paragraph-fill
13274 ;; For reference, this is the default value of adaptive-fill-regexp
13275 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13277 (defun org-adaptive-fill-function ()
13278 "Return a fill prefix for org-mode files.
13279 In particular, this makes sure hanging paragraphs for hand-formatted lists
13280 work correctly."
13281 (cond ((looking-at "#[ \t]+")
13282 (match-string 0))
13283 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13284 (save-excursion
13285 (goto-char (match-end 0))
13286 (make-string (current-column) ?\ )))
13287 (t nil)))
13289 ;;; Other stuff.
13291 (defun org-toggle-fixed-width-section (arg)
13292 "Toggle the fixed-width export.
13293 If there is no active region, the QUOTE keyword at the current headline is
13294 inserted or removed. When present, it causes the text between this headline
13295 and the next to be exported as fixed-width text, and unmodified.
13296 If there is an active region, this command adds or removes a colon as the
13297 first character of this line. If the first character of a line is a colon,
13298 this line is also exported in fixed-width font."
13299 (interactive "P")
13300 (let* ((cc 0)
13301 (regionp (org-region-active-p))
13302 (beg (if regionp (region-beginning) (point)))
13303 (end (if regionp (region-end)))
13304 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13305 (case-fold-search nil)
13306 (re "[ \t]*\\(:\\)")
13307 off)
13308 (if regionp
13309 (save-excursion
13310 (goto-char beg)
13311 (setq cc (current-column))
13312 (beginning-of-line 1)
13313 (setq off (looking-at re))
13314 (while (> nlines 0)
13315 (setq nlines (1- nlines))
13316 (beginning-of-line 1)
13317 (cond
13318 (arg
13319 (org-move-to-column cc t)
13320 (insert ":\n")
13321 (forward-line -1))
13322 ((and off (looking-at re))
13323 (replace-match "" t t nil 1))
13324 ((not off) (org-move-to-column cc t) (insert ":")))
13325 (forward-line 1)))
13326 (save-excursion
13327 (org-back-to-heading)
13328 (if (looking-at (concat outline-regexp
13329 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13330 (replace-match "" t t nil 1)
13331 (if (looking-at outline-regexp)
13332 (progn
13333 (goto-char (match-end 0))
13334 (insert org-quote-string " "))))))))
13336 ;;;; Functions extending outline functionality
13338 (defun org-beginning-of-line (&optional arg)
13339 "Go to the beginning of the current line. If that is invisible, continue
13340 to a visible line beginning. This makes the function of C-a more intuitive.
13341 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13342 first attempt, and only move to after the tags when the cursor is already
13343 beyond the end of the headline."
13344 (interactive "P")
13345 (let ((pos (point)))
13346 (beginning-of-line 1)
13347 (if (bobp)
13349 (backward-char 1)
13350 (if (org-invisible-p)
13351 (while (and (not (bobp)) (org-invisible-p))
13352 (backward-char 1)
13353 (beginning-of-line 1))
13354 (forward-char 1)))
13355 (when org-special-ctrl-a/e
13356 (cond
13357 ((and (looking-at org-todo-line-regexp)
13358 (= (char-after (match-end 1)) ?\ ))
13359 (goto-char
13360 (if (eq org-special-ctrl-a/e t)
13361 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13362 ((= pos (point)) (match-beginning 3))
13363 (t (point)))
13364 (cond ((> pos (point)) (point))
13365 ((not (eq last-command this-command)) (point))
13366 (t (match-beginning 3))))))
13367 ((org-at-item-p)
13368 (goto-char
13369 (if (eq org-special-ctrl-a/e t)
13370 (cond ((> pos (match-end 4)) (match-end 4))
13371 ((= pos (point)) (match-end 4))
13372 (t (point)))
13373 (cond ((> pos (point)) (point))
13374 ((not (eq last-command this-command)) (point))
13375 (t (match-end 4))))))))))
13377 (defun org-end-of-line (&optional arg)
13378 "Go to the end of the line.
13379 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13380 first attempt, and only move to after the tags when the cursor is already
13381 beyond the end of the headline."
13382 (interactive "P")
13383 (if (or (not org-special-ctrl-a/e)
13384 (not (org-on-heading-p)))
13385 (end-of-line arg)
13386 (let ((pos (point)))
13387 (beginning-of-line 1)
13388 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13389 (if (eq org-special-ctrl-a/e t)
13390 (if (or (< pos (match-beginning 1))
13391 (= pos (match-end 0)))
13392 (goto-char (match-beginning 1))
13393 (goto-char (match-end 0)))
13394 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13395 (goto-char (match-end 0))
13396 (goto-char (match-beginning 1))))
13397 (end-of-line arg)))))
13399 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13400 (define-key org-mode-map "\C-e" 'org-end-of-line)
13402 (defun org-kill-line (&optional arg)
13403 "Kill line, to tags or end of line."
13404 (interactive "P")
13405 (cond
13406 ((or (not org-special-ctrl-k)
13407 (bolp)
13408 (not (org-on-heading-p)))
13409 (call-interactively 'kill-line))
13410 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13411 (kill-region (point) (match-beginning 1))
13412 (org-set-tags nil t))
13413 (t (kill-region (point) (point-at-eol)))))
13415 (define-key org-mode-map "\C-k" 'org-kill-line)
13417 (defun org-invisible-p ()
13418 "Check if point is at a character currently not visible."
13419 ;; Early versions of noutline don't have `outline-invisible-p'.
13420 (if (fboundp 'outline-invisible-p)
13421 (outline-invisible-p)
13422 (get-char-property (point) 'invisible)))
13424 (defun org-invisible-p2 ()
13425 "Check if point is at a character currently not visible."
13426 (save-excursion
13427 (if (and (eolp) (not (bobp))) (backward-char 1))
13428 ;; Early versions of noutline don't have `outline-invisible-p'.
13429 (if (fboundp 'outline-invisible-p)
13430 (outline-invisible-p)
13431 (get-char-property (point) 'invisible))))
13433 (defalias 'org-back-to-heading 'outline-back-to-heading)
13434 (defalias 'org-on-heading-p 'outline-on-heading-p)
13435 (defalias 'org-at-heading-p 'outline-on-heading-p)
13436 (defun org-at-heading-or-item-p ()
13437 (or (org-on-heading-p) (org-at-item-p)))
13439 (defun org-on-target-p ()
13440 (or (org-in-regexp org-radio-target-regexp)
13441 (org-in-regexp org-target-regexp)))
13443 (defun org-up-heading-all (arg)
13444 "Move to the heading line of which the present line is a subheading.
13445 This function considers both visible and invisible heading lines.
13446 With argument, move up ARG levels."
13447 (if (fboundp 'outline-up-heading-all)
13448 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13449 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13451 (defun org-up-heading-safe ()
13452 "Move to the heading line of which the present line is a subheading.
13453 This version will not throw an error. It will return the level of the
13454 headline found, or nil if no higher level is found."
13455 (let ((pos (point)) start-level level
13456 (re (concat "^" outline-regexp)))
13457 (catch 'exit
13458 (outline-back-to-heading t)
13459 (setq start-level (funcall outline-level))
13460 (if (equal start-level 1) (throw 'exit nil))
13461 (while (re-search-backward re nil t)
13462 (setq level (funcall outline-level))
13463 (if (< level start-level) (throw 'exit level)))
13464 nil)))
13466 (defun org-first-sibling-p ()
13467 "Is this heading the first child of its parents?"
13468 (interactive)
13469 (let ((re (concat "^" outline-regexp))
13470 level l)
13471 (unless (org-at-heading-p t)
13472 (error "Not at a heading"))
13473 (setq level (funcall outline-level))
13474 (save-excursion
13475 (if (not (re-search-backward re nil t))
13477 (setq l (funcall outline-level))
13478 (< l level)))))
13480 (defun org-goto-sibling (&optional previous)
13481 "Goto the next sibling, even if it is invisible.
13482 When PREVIOUS is set, go to the previous sibling instead. Returns t
13483 when a sibling was found. When none is found, return nil and don't
13484 move point."
13485 (let ((fun (if previous 're-search-backward 're-search-forward))
13486 (pos (point))
13487 (re (concat "^" outline-regexp))
13488 level l)
13489 (when (condition-case nil (org-back-to-heading t) (error nil))
13490 (setq level (funcall outline-level))
13491 (catch 'exit
13492 (or previous (forward-char 1))
13493 (while (funcall fun re nil t)
13494 (setq l (funcall outline-level))
13495 (when (< l level) (goto-char pos) (throw 'exit nil))
13496 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13497 (goto-char pos)
13498 nil))))
13500 (defun org-show-siblings ()
13501 "Show all siblings of the current headline."
13502 (save-excursion
13503 (while (org-goto-sibling) (org-flag-heading nil)))
13504 (save-excursion
13505 (while (org-goto-sibling 'previous)
13506 (org-flag-heading nil))))
13508 (defun org-show-hidden-entry ()
13509 "Show an entry where even the heading is hidden."
13510 (save-excursion
13511 (org-show-entry)))
13513 (defun org-flag-heading (flag &optional entry)
13514 "Flag the current heading. FLAG non-nil means make invisible.
13515 When ENTRY is non-nil, show the entire entry."
13516 (save-excursion
13517 (org-back-to-heading t)
13518 ;; Check if we should show the entire entry
13519 (if entry
13520 (progn
13521 (org-show-entry)
13522 (save-excursion
13523 (and (outline-next-heading)
13524 (org-flag-heading nil))))
13525 (outline-flag-region (max (point-min) (1- (point)))
13526 (save-excursion (outline-end-of-heading) (point))
13527 flag))))
13529 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13530 ;; This is an exact copy of the original function, but it uses
13531 ;; `org-back-to-heading', to make it work also in invisible
13532 ;; trees. And is uses an invisible-OK argument.
13533 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13534 (org-back-to-heading invisible-OK)
13535 (let ((first t)
13536 (level (funcall outline-level)))
13537 (while (and (not (eobp))
13538 (or first (> (funcall outline-level) level)))
13539 (setq first nil)
13540 (outline-next-heading))
13541 (unless to-heading
13542 (if (memq (preceding-char) '(?\n ?\^M))
13543 (progn
13544 ;; Go to end of line before heading
13545 (forward-char -1)
13546 (if (memq (preceding-char) '(?\n ?\^M))
13547 ;; leave blank line before heading
13548 (forward-char -1))))))
13549 (point))
13551 (defun org-show-subtree ()
13552 "Show everything after this heading at deeper levels."
13553 (outline-flag-region
13554 (point)
13555 (save-excursion
13556 (outline-end-of-subtree) (outline-next-heading) (point))
13557 nil))
13559 (defun org-show-entry ()
13560 "Show the body directly following this heading.
13561 Show the heading too, if it is currently invisible."
13562 (interactive)
13563 (save-excursion
13564 (condition-case nil
13565 (progn
13566 (org-back-to-heading t)
13567 (outline-flag-region
13568 (max (point-min) (1- (point)))
13569 (save-excursion
13570 (re-search-forward
13571 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13572 (or (match-beginning 1) (point-max)))
13573 nil))
13574 (error nil))))
13576 (defun org-make-options-regexp (kwds)
13577 "Make a regular expression for keyword lines."
13578 (concat
13580 "#?[ \t]*\\+\\("
13581 (mapconcat 'regexp-quote kwds "\\|")
13582 "\\):[ \t]*"
13583 "\\(.+\\)"))
13585 ;; Make isearch reveal the necessary context
13586 (defun org-isearch-end ()
13587 "Reveal context after isearch exits."
13588 (when isearch-success ; only if search was successful
13589 (if (featurep 'xemacs)
13590 ;; Under XEmacs, the hook is run in the correct place,
13591 ;; we directly show the context.
13592 (org-show-context 'isearch)
13593 ;; In Emacs the hook runs *before* restoring the overlays.
13594 ;; So we have to use a one-time post-command-hook to do this.
13595 ;; (Emacs 22 has a special variable, see function `org-mode')
13596 (unless (and (boundp 'isearch-mode-end-hook-quit)
13597 isearch-mode-end-hook-quit)
13598 ;; Only when the isearch was not quitted.
13599 (org-add-hook 'post-command-hook 'org-isearch-post-command
13600 'append 'local)))))
13602 (defun org-isearch-post-command ()
13603 "Remove self from hook, and show context."
13604 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13605 (org-show-context 'isearch))
13608 ;;;; Integration with and fixes for other packages
13610 ;;; Imenu support
13612 (defvar org-imenu-markers nil
13613 "All markers currently used by Imenu.")
13614 (make-variable-buffer-local 'org-imenu-markers)
13616 (defun org-imenu-new-marker (&optional pos)
13617 "Return a new marker for use by Imenu, and remember the marker."
13618 (let ((m (make-marker)))
13619 (move-marker m (or pos (point)))
13620 (push m org-imenu-markers)
13623 (defun org-imenu-get-tree ()
13624 "Produce the index for Imenu."
13625 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13626 (setq org-imenu-markers nil)
13627 (let* ((n org-imenu-depth)
13628 (re (concat "^" outline-regexp))
13629 (subs (make-vector (1+ n) nil))
13630 (last-level 0)
13631 m tree level head)
13632 (save-excursion
13633 (save-restriction
13634 (widen)
13635 (goto-char (point-max))
13636 (while (re-search-backward re nil t)
13637 (setq level (org-reduced-level (funcall outline-level)))
13638 (when (<= level n)
13639 (looking-at org-complex-heading-regexp)
13640 (setq head (org-match-string-no-properties 4)
13641 m (org-imenu-new-marker))
13642 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13643 (if (>= level last-level)
13644 (push (cons head m) (aref subs level))
13645 (push (cons head (aref subs (1+ level))) (aref subs level))
13646 (loop for i from (1+ level) to n do (aset subs i nil)))
13647 (setq last-level level)))))
13648 (aref subs 1)))
13650 (eval-after-load "imenu"
13651 '(progn
13652 (add-hook 'imenu-after-jump-hook
13653 (lambda () (org-show-context 'org-goto)))))
13655 ;; Speedbar support
13657 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13658 "Overlay marking the agenda restriction line in speedbar.")
13659 (org-overlay-put org-speedbar-restriction-lock-overlay
13660 'face 'org-agenda-restriction-lock)
13661 (org-overlay-put org-speedbar-restriction-lock-overlay
13662 'help-echo "Agendas are currently limited to this item.")
13663 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13665 (defun org-speedbar-set-agenda-restriction ()
13666 "Restrict future agenda commands to the location at point in speedbar.
13667 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13668 (interactive)
13669 (require 'org-agenda)
13670 (let (p m tp np dir txt w)
13671 (cond
13672 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13673 'org-imenu t))
13674 (setq m (get-text-property p 'org-imenu-marker))
13675 (save-excursion
13676 (save-restriction
13677 (set-buffer (marker-buffer m))
13678 (goto-char m)
13679 (org-agenda-set-restriction-lock 'subtree))))
13680 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13681 'speedbar-function 'speedbar-find-file))
13682 (setq tp (previous-single-property-change
13683 (1+ p) 'speedbar-function)
13684 np (next-single-property-change
13685 tp 'speedbar-function)
13686 dir (speedbar-line-directory)
13687 txt (buffer-substring-no-properties (or tp (point-min))
13688 (or np (point-max))))
13689 (save-excursion
13690 (save-restriction
13691 (set-buffer (find-file-noselect
13692 (let ((default-directory dir))
13693 (expand-file-name txt))))
13694 (unless (org-mode-p)
13695 (error "Cannot restrict to non-Org-mode file"))
13696 (org-agenda-set-restriction-lock 'file))))
13697 (t (error "Don't know how to restrict Org-mode's agenda")))
13698 (org-move-overlay org-speedbar-restriction-lock-overlay
13699 (point-at-bol) (point-at-eol))
13700 (setq current-prefix-arg nil)
13701 (org-agenda-maybe-redo)))
13703 (eval-after-load "speedbar"
13704 '(progn
13705 (speedbar-add-supported-extension ".org")
13706 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13707 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13708 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13709 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13710 (add-hook 'speedbar-visiting-tag-hook
13711 (lambda () (org-show-context 'org-goto)))))
13714 ;;; Fixes and Hacks for problems with other packages
13716 ;; Make flyspell not check words in links, to not mess up our keymap
13717 (defun org-mode-flyspell-verify ()
13718 "Don't let flyspell put overlays at active buttons."
13719 (not (get-text-property (point) 'keymap)))
13721 ;; Make `bookmark-jump' show the jump location if it was hidden.
13722 (eval-after-load "bookmark"
13723 '(if (boundp 'bookmark-after-jump-hook)
13724 ;; We can use the hook
13725 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13726 ;; Hook not available, use advice
13727 (defadvice bookmark-jump (after org-make-visible activate)
13728 "Make the position visible."
13729 (org-bookmark-jump-unhide))))
13731 (defun org-bookmark-jump-unhide ()
13732 "Unhide the current position, to show the bookmark location."
13733 (and (org-mode-p)
13734 (or (org-invisible-p)
13735 (save-excursion (goto-char (max (point-min) (1- (point))))
13736 (org-invisible-p)))
13737 (org-show-context 'bookmark-jump)))
13739 ;; Make session.el ignore our circular variable
13740 (eval-after-load "session"
13741 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13743 ;;;; Experimental code
13745 (defun org-closed-in-range ()
13746 "Sparse tree of items closed in a certain time range.
13747 Still experimental, may disappear in the future."
13748 (interactive)
13749 ;; Get the time interval from the user.
13750 (let* ((time1 (time-to-seconds
13751 (org-read-date nil 'to-time nil "Starting date: ")))
13752 (time2 (time-to-seconds
13753 (org-read-date nil 'to-time nil "End date:")))
13754 ;; callback function
13755 (callback (lambda ()
13756 (let ((time
13757 (time-to-seconds
13758 (apply 'encode-time
13759 (org-parse-time-string
13760 (match-string 1))))))
13761 ;; check if time in interval
13762 (and (>= time time1) (<= time time2))))))
13763 ;; make tree, check each match with the callback
13764 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13767 ;;;; Finish up
13769 (provide 'org)
13771 (run-hooks 'org-load-hook)
13773 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13775 ;;; org.el ends here